问:
Google Distance Matrix Api React Js Cant Set Distance To The State
I have it working it will log the response to the console but then I can't set the distance to the state I will put all the code below.

```<code>getDist(dest){
var self = this;
var origin = this.state.location,
    destination = this.state.dest,
    service = new window.google.maps.DistanceMatrixService();

    service.getDistanceMatrix(
    {
        origins: [origin],
        destinations: [destination],
        travelMode: window.google.maps.TravelMode.DRIVING,
        avoidHighways: false,
        avoidTolls: false,
        unitSystem: window.google.maps.UnitSystem.IMPERIAL
      },
      this.callback
    );
}

callback(response, status) {
    const self = this;
    if(status === "OK") {
        console.log(response);
        var dest = response.destinationAddresses[0];
        var dist = response.rows[0].elements[0].distance.text;
        return response;
    } else {
        alert("Error: " + status);
    }
  }
</code>```

ive tried to set the state in the callback function and it says that setState({}) is not a function. ive tried to set the state by doing this this.setState({ distFromLoc: self.callback }) but that just sets the call back function code to the state which is not what I want I have reached the end of my knowledge and the other web developer I work with makes no sense with our logic.

I just need to be able to set state for 2 seconds as im looping through a list of about 36 jobs and after every search it is going to check whether that job is close enough to the person searching or not.

Thanks in advance -Andy

Edit 1: I have edited my code it doesnt error any more but it still wont let me return the data would you be able to maybe show me what im doing wrong?

going to add the class that calls it, because it is saying that i cant use .then on a function to turn the function into a promise function.

```<code>updateSearchResults(data) {
this.setState({
  searching: true,
});
var self = this;
var output = [];
console.log('Here we will search the db using user data for suitable jobs');
console.log('do some math to work out how many pagination we need for the amount of returned jobs and update the state accordingly');
data.forEach(item => {
  console.log('before');
  this.getDist(item.postcode).then(function (res){
    console.log('after');
    console.log(this.state.distFromLoc);
    if (this.state.location === '') {
      if (item.option === 'Part Time' && this.state.partTime && !this.state.weekend){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('1');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('2');
          output.push(item);
        }
      } else if (item.option === 'Weekends' && this.state.weekend && !this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('3');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('4');
          output.push(item);
        }
      } else if (item.option === 'both' && this.state.weekend && this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('5');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('6');
          output.push(item);
        }
      } else if (!this.state.weekend && !this.state.partTime) {
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('7');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('8');
          output.push(item);
        }
      }
    } else if (this.state.distFromLoc <= this.state.distance) {
      console.log(this.state.distFromLoc);
      console.log(this.state.distance);
      if (item.option === 'Part Time' && this.state.partTime && !this.state.weekend){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('9');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('10');
          output.push(item);
        }
      } else if (item.option === 'Weekends' && this.state.weekend && !this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('11');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('12');
          output.push(item);
        }
      } else if (item.option === 'both' && this.state.weekend && this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('13');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('14');
          output.push(item);
        }
      } else if (!this.state.weekend && !this.state.partTime) {
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('15');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('16');
          output.push(item);
        }
      }
    }
  })
  .catch(function (err){
    console.log(err);
  });
});
window.setTimeout(function() {
self.setState({
  dataToShow: output,
  searching: false,
  current: 1,
});
const dataLength = self.state.dataToShow.length
self.setState({
  amountOfJobs: dataLength
})}, 10000)
}

getDist(dest){
var self = this;
const wrappedCallback = (...args) => this.callback(...args);
var origin = this.state.location,
    destination = dest,
    service = new window.google.maps.DistanceMatrixService();

    service.getDistanceMatrix(
    {
        origins: [origin],
        destinations: [destination],
        travelMode: window.google.maps.TravelMode.DRIVING,
        avoidHighways: false,
        avoidTolls: false,
        unitSystem: window.google.maps.UnitSystem.IMPERIAL
      }, wrappedCallback
    );
}

callback(response, status) {
    const self = this;
    if(status === "OK") {
        console.log(response);
        var dest = response.destinationAddresses[0];
        if (response.rows[0].elements[0].status === "ZERO_RESULTS"){

        } else if (response.rows[0].elements[0].status === "OK"){
          var dist = response.rows[0].elements[0].distance.text;
          this.setState({
            distFromLoc: dist
          })
        }
    } else {
        alert("Error: " + status);
    }
  }
</code>```

i know im doing something wrong i just cant work out what it is exactly.

current error im getting is this TypeError: Cannot read property 'then' of undefined why cant i put a promise on the function.

答:
This is a binding problem and one of the main reasons to avoid using classes in javascript. Here's where your problem is:

```<code>service.getDistanceMatrix({
    origins: [origin],
    destinations: [destination],
    travelMode: window.google.maps.TravelMode.DRIVING,
    avoidHighways: false,
    avoidTolls: false,
    unitSystem: window.google.maps.UnitSystem.IMPERIAL
  },
  this.callback
);
</code>```

When you provide the callback as this.callback, you're passing in a function. When that function gets called, however, it no longer has the context it needs to know what this actually is, because the calling code is now in Google's API. There's 3 solutions to this problem.

1) Bind the function so that it knows what this is

```<code> //boundCallback will now always have the correct value for "this"
const boundCallback = this.callback.bind( this );
</code>```

2) Wrap it in a fat arrow function (ES6 only)

```<code>//fat arrow always takes the value of "this" from surrounding scope
const wrappedCallback = (...args) => this.callback(...args);
</code>```

3) Use React.createClass() for your component
This is my preferred solution - if you create your component with React.createClass() instead of using class Comp extends React.Component, all the functions are automatically bound for you, so you never need to mess about - this.callback is always correct.

Body:
I have it working it will log the response to the console but then I can't set the distance to the state I will put all the code below.

getDist(dest){
var self = this;
var origin = this.state.location,
    destination = this.state.dest,
    service = new window.google.maps.DistanceMatrixService();

    service.getDistanceMatrix(
    {
        origins: [origin],
        destinations: [destination],
        travelMode: window.google.maps.TravelMode.DRIVING,
        avoidHighways: false,
        avoidTolls: false,
        unitSystem: window.google.maps.UnitSystem.IMPERIAL
      },
      this.callback
    );
}

callback(response, status) {
    const self = this;
    if(status === "OK") {
        console.log(response);
        var dest = response.destinationAddresses[0];
        var dist = response.rows[0].elements[0].distance.text;
        return response;
    } else {
        alert("Error: " + status);
    }
  }

ive tried to set the state in the callback function and it says that setState({}) is not a function. ive tried to set the state by doing this this.setState({ distFromLoc: self.callback }) but that just sets the call back function code to the state which is not what I want I have reached the end of my knowledge and the other web developer I work with makes no sense with our logic.

I just need to be able to set state for 2 seconds as im looping through a list of about 36 jobs and after every search it is going to check whether that job is close enough to the person searching or not.

Thanks in advance -Andy

Edit 1: I have edited my code it doesnt error any more but it still wont let me return the data would you be able to maybe show me what im doing wrong?

going to add the class that calls it, because it is saying that i cant use .then on a function to turn the function into a promise function.

updateSearchResults(data) {
this.setState({
  searching: true,
});
var self = this;
var output = [];
console.log('Here we will search the db using user data for suitable jobs');
console.log('do some math to work out how many pagination we need for the amount of returned jobs and update the state accordingly');
data.forEach(item => {
  console.log('before');
  this.getDist(item.postcode).then(function (res){
    console.log('after');
    console.log(this.state.distFromLoc);
    if (this.state.location === '') {
      if (item.option === 'Part Time' && this.state.partTime && !this.state.weekend){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('1');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('2');
          output.push(item);
        }
      } else if (item.option === 'Weekends' && this.state.weekend && !this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('3');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('4');
          output.push(item);
        }
      } else if (item.option === 'both' && this.state.weekend && this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('5');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('6');
          output.push(item);
        }
      } else if (!this.state.weekend && !this.state.partTime) {
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('7');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('8');
          output.push(item);
        }
      }
    } else if (this.state.distFromLoc <= this.state.distance) {
      console.log(this.state.distFromLoc);
      console.log(this.state.distance);
      if (item.option === 'Part Time' && this.state.partTime && !this.state.weekend){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('9');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('10');
          output.push(item);
        }
      } else if (item.option === 'Weekends' && this.state.weekend && !this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('11');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('12');
          output.push(item);
        }
      } else if (item.option === 'both' && this.state.weekend && this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('13');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('14');
          output.push(item);
        }
      } else if (!this.state.weekend && !this.state.partTime) {
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('15');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('16');
          output.push(item);
        }
      }
    }
  })
  .catch(function (err){
    console.log(err);
  });
});
window.setTimeout(function() {
self.setState({
  dataToShow: output,
  searching: false,
  current: 1,
});
const dataLength = self.state.dataToShow.length
self.setState({
  amountOfJobs: dataLength
})}, 10000)
}

getDist(dest){
var self = this;
const wrappedCallback = (...args) => this.callback(...args);
var origin = this.state.location,
    destination = dest,
    service = new window.google.maps.DistanceMatrixService();

    service.getDistanceMatrix(
    {
        origins: [origin],
        destinations: [destination],
        travelMode: window.google.maps.TravelMode.DRIVING,
        avoidHighways: false,
        avoidTolls: false,
        unitSystem: window.google.maps.UnitSystem.IMPERIAL
      }, wrappedCallback
    );
}

callback(response, status) {
    const self = this;
    if(status === "OK") {
        console.log(response);
        var dest = response.destinationAddresses[0];
        if (response.rows[0].elements[0].status === "ZERO_RESULTS"){

        } else if (response.rows[0].elements[0].status === "OK"){
          var dist = response.rows[0].elements[0].distance.text;
          this.setState({
            distFromLoc: dist
          })
        }
    } else {
        alert("Error: " + status);
    }
  }

i know im doing something wrong i just cant work out what it is exactly.

current error im getting is this TypeError: Cannot read property 'then' of undefined why cant i put a promise on the function.

Body:
This is a binding problem and one of the main reasons to avoid using classes in javascript. Here's where your problem is:

service.getDistanceMatrix({
    origins: [origin],
    destinations: [destination],
    travelMode: window.google.maps.TravelMode.DRIVING,
    avoidHighways: false,
    avoidTolls: false,
    unitSystem: window.google.maps.UnitSystem.IMPERIAL
  },
  this.callback
);

When you provide the callback as this.callback, you're passing in a function. When that function gets called, however, it no longer has the context it needs to know what this actually is, because the calling code is now in Google's API. There's 3 solutions to this problem.

1) Bind the function so that it knows what this is

 //boundCallback will now always have the correct value for "this"
const boundCallback = this.callback.bind( this );

2) Wrap it in a fat arrow function (ES6 only)

//fat arrow always takes the value of "this" from surrounding scope
const wrappedCallback = (...args) => this.callback(...args);

3) Use React.createClass() for your component
This is my preferred solution - if you create your component with React.createClass() instead of using class Comp extends React.Component, all the functions are automatically bound for you, so you never need to mess about - this.callback is always correct.


来源: stackexchange

问:
Keeping a WKWebView and it's UIViewController in the background running and accessible from multiple ViewControllers

Background: In order to make web requests to an API endpoint, I need to scrape a website and retrieve a token every 25-30 seconds. I'm doing this with a WKWebView and injecting some custom JavaScript using WKUserScript to retrieve AJAX response headers containing the token. Please focus on the question specifically and not on this background information - I'm attempting this entirely for my own educational purposes.

Goal

I will have different 'model' classes, or even just other UIViewControllers, that may need to call the shared UIViewController to retrieve this token to make an authenticated request.

Maybe I might abstract this into one "Sdk" class. Regardless, this 'model' SDK class could be instantiated and used by any other ViewController.

More info

I would like to be able to call the UIViewController of the WKWebView and retrieve some data. Unless I re-create it every 25 seconds, I need to run it in the background or share it. I would like to be able to run a UIViewController 'in the background' and receive some information from it once WKWebView has done it's thing.

I know there are multiple ways of communicating with another ViewController including delegation and segueing. However, I'm not sure that these help me keep the view containing the WKWebView existing in the background so I can call it's ViewController and have it re-perform the scrape. Delegation may work for normal code, but what about one that must have the view existing? Would I have to re-create this WKWebView dynamically each time a different model, or view controller, were to try and get this token?

One post suggests utilising ContainerViewControllers. From this, I gather that in the 'master' ViewController (the one containing the other ones), I could place the hidden WKWebView to do it's thing and communicate to the child view controllers that way via delegation.

Another post suggests using AppDelegate and making it a shared service. I'm completely against using a Singleton as it is widely considered an anti-pattern. There must be another way, even if a little more complex, that helps me do what I want without resorting to this 'cheat'.

This post talks about communicating between multiple ViewControllers, but I can't figure out how this would be useful when something needs to stay running and executing things.

How about any other ways to do this? Run something in a background thread with a strong pointer so it doesn't get discarded? I'm using Xcode 9.2, Swift 4, and iOS 11. As I'm very new to iOS programming, any small code examples on this would be appreciated.

答:
Here is a way if you don't wish to use a singleton.

1- In the DidFinishlaunchingWithOptions, Make a timer that runs in the background and call a method inside the app delegate Called FetchNewToken.

2- In FetchNewToken, make the call needed and retrieve the new token (you can use alamofire or any 3rd library to make the call easier for you).

Up on successfully retrieving the token, save it in NSUserDefaults under the name upToDateToken

You can access this token anywhere from the application using NSUserDefaults and it will always be up to date.

ContentLicense: CC BY-SA 3.0


问:
How do I print out the results of my delete script in Powershell
I'm trying to find a way to get my script to print out a log file of what files are actually being deleted. Does anyone know how I could go about doing this? Here is my screen I would like to add that onto.</p>

```<code>Where-Object { -not $_.PSIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-1) } |
    Remove-Item -Force
</code>```

答:
You would need a loop:</p>

```<code>Get-ChildItem -Path $Targets |
    Where-Object { -not $_.PSIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-1) } |
    ForEach-Object {
        $_ | Remove-Item -Force
        $_.FullName | Out-File -FilePath $LogFile -Append
    }
</code>```

Body:
I'm trying to find a way to get my script to print out a log file of what files are actually being deleted. Does anyone know how I could go about doing this? Here is my screen I would like to add that onto.

Where-Object { -not $_.PSIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-1) } |
    Remove-Item -Force

Body:
You would need a loop:

Get-ChildItem -Path $Targets |
    Where-Object { -not $_.PSIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-1) } |
    ForEach-Object {
        $_ | Remove-Item -Force
        $_.FullName | Out-File -FilePath $LogFile -Append
    }


问:
Breakpoints not being hit when debugging Serverless in vscode
None of my breakpoints are active when debugging my serverless based application in VSCode.

launch.json

```<code>{
  "configurations": [
    {
      "console": "integratedTerminal",
      "cwd": "${workspaceRoot}",
      "name": "Debug",
     "port": 5858,
      "request": "launch",
      "runtimeArgs": [
        "run-script",
        "vscode:debug"
      ],
      "runtimeExecutable": "npm",
      "type": "node"
    }
  ],
  "version": "0.2.0"
}
</code>```

My package.json

```<code>...
"scripts": {
  ...
  "vscode:debug": "export SLS_DEBUG=* && node --inspect=5858 --debug-brk --nolazy ./node_modules/.bin/serverless invoke local -s local -f customerAlexa -p ./test/requests/FindAgent-First-GoodZip.json"
},
....
</code>```

When I choose Start Debugging from the menu, all the red breakpoints go grey and the program just executes without stopping on the breakpoints.

I am running Node 6.11.2, Serverless 1.23.0 on a Mac.  Thanks all.

答:
Here is my launch.json which allows me to use breakpoints.

```<code>{
  "type": "node",
  "request": "launch",
  "name": "Launch Program",
  "program": "${workspaceRoot}/node_modules/.bin/serverless",
  "args": [
    "offline",
    "start",
    "--skipCacheInvalidation"
  ],
  "env": {
    "NODE_ENV": "development"
  }
}
</code>```

I am using the serverless-offline to run locally.  I also am using webpack and babel.  The  skipCacheInvalidation is for that.

I hope this points you in the right direction.

Body:
None of my breakpoints are active when debugging my serverless based application in VSCode.

launch.json

{
  "configurations": [
    {
      "console": "integratedTerminal",
      "cwd": "${workspaceRoot}",
      "name": "Debug",
     "port": 5858,
      "request": "launch",
      "runtimeArgs": [
        "run-script",
        "vscode:debug"
      ],
      "runtimeExecutable": "npm",
      "type": "node"
    }
  ],
  "version": "0.2.0"
}

My package.json

...
"scripts": {
  ...
  "vscode:debug": "export SLS_DEBUG=* && node --inspect=5858 --debug-brk --nolazy ./node_modules/.bin/serverless invoke local -s local -f customerAlexa -p ./test/requests/FindAgent-First-GoodZip.json"
},
....

When I choose Start Debugging from the menu, all the red breakpoints go grey and the program just executes without stopping on the breakpoints.

I am running Node 6.11.2, Serverless 1.23.0 on a Mac.  Thanks all.

Body:
Here is my launch.json which allows me to use breakpoints.

{
  "type": "node",
  "request": "launch",
  "name": "Launch Program",
  "program": "${workspaceRoot}/node_modules/.bin/serverless",
  "args": [
    "offline",
    "start",
    "--skipCacheInvalidation"
  ],
  "env": {
    "NODE_ENV": "development"
  }
}

I am using the serverless-offline to run locally.  I also am using webpack and babel.  The  skipCacheInvalidation is for that.

I hope this points you in the right direction.


问:
python requests can't find a folder with a certificate when converted to .exe
I have a program that pools ad stats from different marketing systems. Everything works fine untill i convert it to the .exe format and run it.

```<code>Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 1549, in __call__
    return self.func(*args)
  File "C:\Users\user\Desktop\alg\TSK_7. Marketing\report_gui.py", line 24, in <lambda>
    ok = tk.Button(root, text="DO NOT PRESS", bg="red", command=lambda: self.run())
  File "C:\Users\user\Desktop\alg\TSK_7. Marketing\report_gui.py", line 43, in run
    report.merge_all()
  File "C:\Users\user\Desktop\alg\TSK_7. Marketing\process_data.py", line 400, in merge_all
    fb_df     = self.fetch_fb()
  File "C:\Users\user\Desktop\alg\TSK_7. Marketing\process_data.py", line 156, in fetch_fb
    fb_campaigns = from_fb.run_fb(self.start_date, self.end_date)  # in JSON format
  File "C:\Users\user\Desktop\alg\TSK_7. Marketing\from_fb.py", line 110, in run_fb
    return s.get_stats()
  File "C:\Users\user\Desktop\alg\TSK_7. Marketing\from_fb.py", line 84, in get_stats
    params=params,
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\facebookads\adobjects\adaccount.py", line 1551, in get_insights
    return request.execute()
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\facebookads\api.py", line 653, in execute
    cursor.load_next_page()
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\facebookads\api.py", line 797, in load_next_page
    params=self.params,
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\facebookads\api.py", line 305, in call
    timeout=self._session.timeout
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\requests\sessions.py", line 508, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\requests\sessions.py", line 618, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\requests\adapters.py", line 407, in send
    self.cert_verify(conn, request.url, verify, cert)
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\requests\adapters.py", line 226, in cert_verify
    "invalid path: {0}".format(cert_loc))
OSError: Could not find a suitable TLS CA certificate bundle, invalid path: C:\Users\user\AppData\Local\Temp\_MEI253762\facebookads\fb_ca_chain_bundle.crt
</code>```

I tried to fix that by using this code but MEI folder keeps changing its digits everytime i run this code so it's no use.

```<code>dst = r'C:\Users\user\AppData\Local\Temp\_MEI120642\facebookads'
file = 'fb_ca_chain_bundle.crt'

try:
    os.makedirs(dst);  ## it creates the destination folder
except:
    pass

shutil.move(file, dst)
</code>```

So i went to this file

C:\Users\user\AppData\Local\Programs\Python\Python35\Lib\site-packages\requests\adapters.py

and tried to comment if statements that raise this error out but got an SSL error. I couldn't find a piece of code responsible for generating those MEI digits.

```<code>def cert_verify(self, conn, url, verify, cert):
    """Verify a SSL certificate. This method should not be called from user
    code, and is only exposed for use when subclassing the
    :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.

    :param conn: The urllib3 connection object associated with the cert.
    :param url: The requested URL.
    :param verify: Either a boolean, in which case it controls whether we verify
        the server's TLS certificate, or a string, in which case it must be a path
        to a CA bundle to use
    :param cert: The SSL certificate to verify.
    """
    if url.lower().startswith('https') and verify:

        cert_loc = None

        # Allow self-specified cert location.
        if verify is not True:
            cert_loc = verify

        if not cert_loc:
            cert_loc = DEFAULT_CA_BUNDLE_PATH

        if not cert_loc or not os.path.exists(cert_loc):
            raise IOError("Could not find a suitable TLS CA certificate bundle, "
                          "invalid path: {0}".format(cert_loc))

        conn.cert_reqs = 'CERT_REQUIRED'

        if not os.path.isdir(cert_loc):
            conn.ca_certs = cert_loc
        else:
            conn.ca_cert_dir = cert_loc
    else:
        conn.cert_reqs = 'CERT_NONE'
        conn.ca_certs = None
        conn.ca_cert_dir = None

    if cert:
        if not isinstance(cert, basestring):
            conn.cert_file = cert[0]
            conn.key_file = cert[1]
        else:
            conn.cert_file = cert
            conn.key_file = None
        if conn.cert_file and not os.path.exists(conn.cert_file):
            raise IOError("Could not find the TLS certificate file, "
                          "invalid path: {0}".format(conn.cert_file))
        if conn.key_file and not os.path.exists(conn.key_file):
            raise IOError("Could not find the TLS key file, "
                          "invalid path: {0}".format(conn.key_file))
</code>```

答:
I ran into this problem as well. It looks like it comes from the certificate bundle cacert.pem not being included in the requests package directory when the program is compiled. The requests module uses the function certifi.core.where to determine the location of cacert.pem.  Overriding this function and overriding the variables set by this function seems to fix the problem.

I added this code to the beginning of my program:

```<code>import sys, os

def override_where():
    """ overrides certifi.core.where to return actual location of cacert.pem"""
    # change this to match the location of cacert.pem
    return os.path.abspath("cacert.pem")

# is the program compiled?
if hasattr(sys, "frozen"):
    import certifi.core

    os.environ["REQUESTS_CA_BUNDLE"] = override_where()
    certifi.core.where = override_where

    # delay importing until after where() has been replaced
    import requests.utils
    import requests.adapters
    # replace these variables in case these modules were
    # imported before we replaced certifi.core.where
    requests.utils.DEFAULT_CA_BUNDLE_PATH = override_where()
    requests.adapters.DEFAULT_CA_BUNDLE_PATH = override_where()
</code>```

Body:
I have a program that pools ad stats from different marketing systems. Everything works fine untill i convert it to the .exe format and run it.

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 1549, in __call__
    return self.func(*args)
  File "C:\Users\user\Desktop\alg\TSK_7. Marketing\report_gui.py", line 24, in <lambda>
    ok = tk.Button(root, text="DO NOT PRESS", bg="red", command=lambda: self.run())
  File "C:\Users\user\Desktop\alg\TSK_7. Marketing\report_gui.py", line 43, in run
    report.merge_all()
  File "C:\Users\user\Desktop\alg\TSK_7. Marketing\process_data.py", line 400, in merge_all
    fb_df     = self.fetch_fb()
  File "C:\Users\user\Desktop\alg\TSK_7. Marketing\process_data.py", line 156, in fetch_fb
    fb_campaigns = from_fb.run_fb(self.start_date, self.end_date)  # in JSON format
  File "C:\Users\user\Desktop\alg\TSK_7. Marketing\from_fb.py", line 110, in run_fb
    return s.get_stats()
  File "C:\Users\user\Desktop\alg\TSK_7. Marketing\from_fb.py", line 84, in get_stats
    params=params,
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\facebookads\adobjects\adaccount.py", line 1551, in get_insights
    return request.execute()
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\facebookads\api.py", line 653, in execute
    cursor.load_next_page()
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\facebookads\api.py", line 797, in load_next_page
    params=self.params,
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\facebookads\api.py", line 305, in call
    timeout=self._session.timeout
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\requests\sessions.py", line 508, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\requests\sessions.py", line 618, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\requests\adapters.py", line 407, in send
    self.cert_verify(conn, request.url, verify, cert)
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\requests\adapters.py", line 226, in cert_verify
    "invalid path: {0}".format(cert_loc))
OSError: Could not find a suitable TLS CA certificate bundle, invalid path: C:\Users\user\AppData\Local\Temp\_MEI253762\facebookads\fb_ca_chain_bundle.crt

I tried to fix that by using this code but MEI folder keeps changing its digits everytime i run this code so it's no use.

dst = r'C:\Users\user\AppData\Local\Temp\_MEI120642\facebookads'
file = 'fb_ca_chain_bundle.crt'

try:
    os.makedirs(dst);  ## it creates the destination folder
except:
    pass

shutil.move(file, dst)

So i went to this file

C:\Users\user\AppData\Local\Programs\Python\Python35\Lib\site-packages\requests\adapters.py

and tried to comment if statements that raise this error out but got an SSL error. I couldn't find a piece of code responsible for generating those MEI digits.

def cert_verify(self, conn, url, verify, cert):
    """Verify a SSL certificate. This method should not be called from user
    code, and is only exposed for use when subclassing the
    :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.

    :param conn: The urllib3 connection object associated with the cert.
    :param url: The requested URL.
    :param verify: Either a boolean, in which case it controls whether we verify
        the server's TLS certificate, or a string, in which case it must be a path
        to a CA bundle to use
    :param cert: The SSL certificate to verify.
    """
    if url.lower().startswith('https') and verify:

        cert_loc = None

        # Allow self-specified cert location.
        if verify is not True:
            cert_loc = verify

        if not cert_loc:
            cert_loc = DEFAULT_CA_BUNDLE_PATH

        if not cert_loc or not os.path.exists(cert_loc):
            raise IOError("Could not find a suitable TLS CA certificate bundle, "
                          "invalid path: {0}".format(cert_loc))

        conn.cert_reqs = 'CERT_REQUIRED'

        if not os.path.isdir(cert_loc):
            conn.ca_certs = cert_loc
        else:
            conn.ca_cert_dir = cert_loc
    else:
        conn.cert_reqs = 'CERT_NONE'
        conn.ca_certs = None
        conn.ca_cert_dir = None

    if cert:
        if not isinstance(cert, basestring):
            conn.cert_file = cert[0]
            conn.key_file = cert[1]
        else:
            conn.cert_file = cert
            conn.key_file = None
        if conn.cert_file and not os.path.exists(conn.cert_file):
            raise IOError("Could not find the TLS certificate file, "
                          "invalid path: {0}".format(conn.cert_file))
        if conn.key_file and not os.path.exists(conn.key_file):
            raise IOError("Could not find the TLS key file, "
                          "invalid path: {0}".format(conn.key_file))

Body:
I ran into this problem as well. It looks like it comes from the certificate bundle cacert.pem not being included in the requests package directory when the program is compiled. The requests module uses the function certifi.core.where to determine the location of cacert.pem.  Overriding this function and overriding the variables set by this function seems to fix the problem.

I added this code to the beginning of my program:

import sys, os

def override_where():
    """ overrides certifi.core.where to return actual location of cacert.pem"""
    # change this to match the location of cacert.pem
    return os.path.abspath("cacert.pem")

# is the program compiled?
if hasattr(sys, "frozen"):
    import certifi.core

    os.environ["REQUESTS_CA_BUNDLE"] = override_where()
    certifi.core.where = override_where

    # delay importing until after where() has been replaced
    import requests.utils
    import requests.adapters
    # replace these variables in case these modules were
    # imported before we replaced certifi.core.where
    requests.utils.DEFAULT_CA_BUNDLE_PATH = override_where()
    requests.adapters.DEFAULT_CA_BUNDLE_PATH = override_where()


问:
Need to make the row in normal mode after updating
I have a gridview with "Edit Update Cancel" command field. When I click Edit, all the columns in the particular row becomes editable and when I click update, the Table is updated based on the new values.
Then the Gridview is binded with the updated datatable. But the "Update Cancel" button still
remains.

Once the row , has been updated, the "Update Cancel" button has to be changed to "Edit"  So how is that made possible.

Thanks in Advance

This is the code for updating and displaying the updated data

```<code> protected void StaticNoticeGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {

            try
            {
                //Gets the updated value from GridView
                string id = StaticNoticeGridView.Rows[e.RowIndex].Cells[0].Text;
                string updatedItem = e.NewValues[0].ToString();
                string updatedURL = e.NewValues[1].ToString();

                //Updated the Database
                StaticNoticeController staticNoticeController = new StaticNoticeController();
                int rocordsAffected = staticNoticeController.UpdateStaticNoticeData(updatedItem, updatedURL, id);

                //Gets the updated datatable and binds the Gridview again
                if (rocordsAffected == 1)
                {
                    this.StaticNoticeGridView.DataSource = null;
                    this.StaticNoticeGridView.DataSource = staticNoticeController.GetStaticNoticeData();
                    this.StaticNoticeGridView.DataBind();
                }
            }
            catch(SystemException ex)
            {
                //ToDo: Log the Exception
            }
        }
</code>```

答: set GridView1.EditIndex = -1;before this.StaticNoticeGridView.DataBind();in the method StaticNoticeGridView_RowUpdating

ContentLicense: CC BY-SA 2.5

Body:
I have a gridview with "Edit Update Cancel" command field. When I click Edit, all the columns in the particular row becomes editable and when I click update, the Table is updated based on the new values.
Then the Gridview is binded with the updated datatable. But the "Update Cancel" button still
remains.

Once the row , has been updated, the "Update Cancel" button has to be changed to "Edit"  So how is that made possible.

Thanks in Advance

This is the code for updating and displaying the updated data

 protected void StaticNoticeGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {

            try
            {
                //Gets the updated value from GridView
                string id = StaticNoticeGridView.Rows[e.RowIndex].Cells[0].Text;
                string updatedItem = e.NewValues[0].ToString();
                string updatedURL = e.NewValues[1].ToString();

                //Updated the Database
                StaticNoticeController staticNoticeController = new StaticNoticeController();
                int rocordsAffected = staticNoticeController.UpdateStaticNoticeData(updatedItem, updatedURL, id);

                //Gets the updated datatable and binds the Gridview again
                if (rocordsAffected == 1)
                {
                    this.StaticNoticeGridView.DataSource = null;
                    this.StaticNoticeGridView.DataSource = staticNoticeController.GetStaticNoticeData();
                    this.StaticNoticeGridView.DataBind();
                }
            }
            catch(SystemException ex)
            {
                //ToDo: Log the Exception
            }
        }


问:
How can I target the src attribute of the img element using jQuery?
You can target an id with jQuery using $("#yourId"), but how can I target the src attribute of the img element since it's not an id. I want to link the api's images link directly.

I have a

var ico = data.weather[0].icon

I want ico in src"" using jquery.

答:
You can target elements with attributes.

```<code>$('img[src="imageurl"]')
</code>```

If you only want to track images with part of an URL use this:

```<code>$('img[src*="partOfTheImageUrl"]')
</code>```

This checks if the src attribute contains your string.

EDIT

Since you changed your question, I will change my answer too.

To set the src of an image use this:

```<code>$('img').attr('src', ico);
</code>```

You may want to use another selector instead of img. As example an ID like you already described in your question.

Body:
You can target elements with attributes.

$('img[src="imageurl"]')

If you only want to track images with part of an URL use this:

$('img[src*="partOfTheImageUrl"]')

This checks if the src attribute contains your string.

EDIT

Since you changed your question, I will change my answer too.

To set the src of an image use this:

$('img').attr('src', ico);

You may want to use another selector instead of img. As example an ID like you already described in your question.

ContentLicense: CC BY-SA 4.0


问:
How to specify class for instance variable in smalltalk
Probably I haven't understood the concepts of smalltalk enough, but here is my problem:

I am creating a class, let's call it Main-class, that has an instance variable bar, that I want to be of a certain class - Other-class, and use this Other-class' methods on that in the Main-class methods kind of like this:

```<code>    Object subclass: #Other-class
        instanceVariableNames: 'foo'
        classVariableNames: ''
        poolDictionaries: ''
        category: 'Custom-class'

setFoo: newFoo

    foo := newFoo.
</code>```

And the Main-class :

```<code>  Object subclass: #Main-class
        instanceVariableNames: 'bar'
        classVariableNames: ''
        poolDictionaries: ''
        category: 'Custom-class'

newBar: val

    bar := Bar new.
    bar setFoo: val.
</code>```

Obviously, I get an error that there is no setFoo method.
But how do I specify that I want bar to be variable of a specific class and then use that class' methods on it?

答:
Concerning the question's title: you don't. Smalltalk is a dynamically typed language, which means that the value of a variable can have different types at different points in time -- types are not declared for variables. But for humans, you can note the actual types of the variables in the class comment (see the ? button next to the instance-side and class-side buttons in the system browser).

Concerning your problem: You have to make sure that the object that is assigned to the instance variable bar is of a suitable type. In this case it must understand the message setFoo:. In your second code snippet, this means either:

that instead of Bar you should use another class that can respond to setFoo:, such as Other-class (which is an odd name by the way because of the hyphen, you cannot easily reference that in your methods, use CamelCase instead), to fill the variable, or

that setFoo: must be implemented for the class Bar.

Body:
Probably I haven't understood the concepts of smalltalk enough, but here is my problem:

I am creating a class, let's call it Main-class, that has an instance variable bar, that I want to be of a certain class - Other-class, and use this Other-class' methods on that in the Main-class methods kind of like this:

    Object subclass: #Other-class
        instanceVariableNames: 'foo'
        classVariableNames: ''
        poolDictionaries: ''
        category: 'Custom-class'

setFoo: newFoo

    foo := newFoo.

And the Main-class :

  Object subclass: #Main-class
        instanceVariableNames: 'bar'
        classVariableNames: ''
        poolDictionaries: ''
        category: 'Custom-class'

newBar: val

    bar := Bar new.
    bar setFoo: val.

Obviously, I get an error that there is no setFoo method.
But how do I specify that I want bar to be variable of a specific class and then use that class' methods on it?


问:
Compare/View 2 rows of images via scroll or slider
My goal is to have an interface where two rows/columns of images are compared.

I'd like to slide/scroll through each row so that the user can eventually identify 2 images that match.

I've seen code for a few sliders and scroll apps, but not any where each row can slide independent of the other. Any advice or links to resources online would be greatly appreciated.

答: Try jquery-ui there are a number of tools on there for things like sliders, and each element can be put on there separately.  I'd be amazed if you can do the same with images, although mostly I've seen it done using vertical sliders and it sounds like you want horizontal ones.  </p>


问:
What is the best way to validate if a value with decimals is in a defined range
I have a file with thresholds defined and these threshold are use to help to take decision.

The values looks like this:

```<code>"thresholds":[
    { "min": 0.0, "max": 0.25, "text": "VERY UNLIKELY" },
    { "min": 0.26, "max": 0.50, "text": "UNLIKELY" }
    { "min": 0.51, "max": 0.75, "text": "LIKELY" }
    { "min": 0.76, "max": 1.0, "text": "VERY LIKELY" }
]
</code>```

The condition:

```<code>for (Threshold threshold : thresholds) {
    if ((threshold.getMin() <= predictionValue) &&
        (predictionValue <= threshold.getMax())) {
            return threshold.getText();
    }
}
</code>```

If the value to check is something like 0.2500000001, it fall somewhere between 0.25 and 0.26. So I ask, what is the optimal way to determine if a value is in a certain range without having empty gap?

Should I add a parameter for precision and apply this precision on the min & max values? I don't want to have to configure the file with values like 0.259999999.

答:
You end up with this grey zone because you want to declare a boundary with 2 values. This does not work. I will give you an idea of how it works:

What you should do:

```<code>"thresholds":[
    { "max": 0.25, "text": "VERY UNLIKELY" },
    { "max": 0.50, "text": "UNLIKELY" }
    { "max": 0.75, "text": "LIKELY" }
    { "max": 1.0, "text": "VERY LIKELY" }
]
</code>```

And the condition:

```<code>for (Threshold threshold : thresholds) {
    if (predictionValue < threshold.getMax()) {
            return threshold.getText();
    }
}
</code>```

As you can see, one value suffices to define a boundary.

Body:
I have a file with thresholds defined and these threshold are use to help to take decision.

The values looks like this:

"thresholds":[
    { "min": 0.0, "max": 0.25, "text": "VERY UNLIKELY" },
    { "min": 0.26, "max": 0.50, "text": "UNLIKELY" }
    { "min": 0.51, "max": 0.75, "text": "LIKELY" }
    { "min": 0.76, "max": 1.0, "text": "VERY LIKELY" }
]

The condition:

for (Threshold threshold : thresholds) {
    if ((threshold.getMin() <= predictionValue) &&
        (predictionValue <= threshold.getMax())) {
            return threshold.getText();
    }
}

If the value to check is something like 0.2500000001, it fall somewhere between 0.25 and 0.26. So I ask, what is the optimal way to determine if a value is in a certain range without having empty gap?

Should I add a parameter for precision and apply this precision on the min & max values? I don't want to have to configure the file with values like 0.259999999.

Body:
You end up with this grey zone because you want to declare a boundary with 2 values. This does not work. I will give you an idea of how it works:

What you should do:

"thresholds":[
    { "max": 0.25, "text": "VERY UNLIKELY" },
    { "max": 0.50, "text": "UNLIKELY" }
    { "max": 0.75, "text": "LIKELY" }
    { "max": 1.0, "text": "VERY LIKELY" }
]

And the condition:

for (Threshold threshold : thresholds) {
    if (predictionValue < threshold.getMax()) {
            return threshold.getText();
    }
}

As you can see, one value suffices to define a boundary.


问:
MS Access - Browser to Attach/Move Files not working right
I found a form that will let you browse for files and attach them to the record, but it actually copies the attachment and puts them into a folder and the file path is saved in the database. This works great...but, I split the database and multiple people will copy the front end to their desktop and work from there. Right now, this code is set up where it will create a new folder or use a folder if already created where the front end is, so in this case it would actually create a folder on the users desktop and this is not what I want. I would like all the attachments to be moved to the server in a central folder and for the database to read files from that folder. Here is the code:

```<code>Private Sub cmd_LocateFile_Click()
On Error GoTo Error_Handler
Dim sFile As String
Dim sFolder As String
Dim ID As Long
Dim sTarget As String

sFile = FSBrowse("", msoFileDialogFilePicker, "All Files (*.*),*.*")
If sFile <> "" Then
    sFolder = Application.CodeProject.path & "\" & sAttachmentFolderName & "\"
    If FolderExist(sFolder) = False Then MkDir (sFolder)
    ID = RequestID_FK  ' Set current record id.
sTarget = sFolder & CStr(ID) & "-" & GetFileName(sFile)
If CopyFile(sFile, sFolder & GetFileName(sTarget)) = True Then
        Me!FullFileName.Value = sTarget
    Else
    End If
End If
Error_Handler_Exit:
On Error Resume Next
Exit Sub
Error_Handler:
MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
       "Error Number: " & Err.Number & vbCrLf & _
       "Error Source: " & sModName & "\cmd_LocateFile_Click" & vbCrLf & _
       "Error Description: " & Err.Description & _
       Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
       , vbOKOnly + vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit
End Sub
</code>```

Here is the rest of the coding

```<code>'Delete the current attachment/record and the attachment file itself
Private Sub cmd_RecDel_Click()
On Error GoTo Error_Handler
Dim sFile                 As String

sFile = Me.FullFileName
'Delete the database record
DoCmd.DoMenuItem acFormBar, acEditMenu, 8, , acMenuVer70
DoCmd.DoMenuItem acFormBar, acEditMenu, 6, , acMenuVer70
'If we're here the record was deleted, so let delete the actual file from the server
Kill sFile

Error_Handler_Exit:
On Error Resume Next
Exit Sub

Error_Handler:
If Err.Number <> 2501 Then
    MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: " & sModName & "\cmd_RecDel_Click" & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has Occured!"
End If
Resume Error_Handler_Exit
End Sub

'Open the attachment
Private Sub cmd_ViewFile_Click()
On Error GoTo Error_Handler

Call ExecuteFile(Me.FullFileName, "Open")

Error_Handler_Exit:
On Error Resume Next
Exit Sub
Error_Handler:
MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
       "Error Number: " & Err.Number & vbCrLf & _
       "Error Source: " & sModName & "\cmd_ViewFile_Click" & vbCrLf & _
       "Error Description: " & Err.Description & _
       Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
       , vbOKOnly + vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit
End Sub
</code>```

答:
That is not a valid string in the comment. Constant strings must be enclosed in double quotes "mystring"

Assuming it's a UNC path, this should work:

```<code>sFolder = "\\aiowima23fp1\Ecological Sciences and Engineering\Cultural Resources\New - Cultural Resources Request Database\" & sAttachmentFolderName & "\"
</code>```

Body:
I found a form that will let you browse for files and attach them to the record, but it actually copies the attachment and puts them into a folder and the file path is saved in the database. This works great...but, I split the database and multiple people will copy the front end to their desktop and work from there. Right now, this code is set up where it will create a new folder or use a folder if already created where the front end is, so in this case it would actually create a folder on the users desktop and this is not what I want. I would like all the attachments to be moved to the server in a central folder and for the database to read files from that folder. Here is the code:

Private Sub cmd_LocateFile_Click()
On Error GoTo Error_Handler
Dim sFile As String
Dim sFolder As String
Dim ID As Long
Dim sTarget As String

sFile = FSBrowse("", msoFileDialogFilePicker, "All Files (*.*),*.*")
If sFile <> "" Then
    sFolder = Application.CodeProject.path & "\" & sAttachmentFolderName & "\"
    If FolderExist(sFolder) = False Then MkDir (sFolder)
    ID = RequestID_FK  ' Set current record id.
sTarget = sFolder & CStr(ID) & "-" & GetFileName(sFile)
If CopyFile(sFile, sFolder & GetFileName(sTarget)) = True Then
        Me!FullFileName.Value = sTarget
    Else
    End If
End If
Error_Handler_Exit:
On Error Resume Next
Exit Sub
Error_Handler:
MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
       "Error Number: " & Err.Number & vbCrLf & _
       "Error Source: " & sModName & "\cmd_LocateFile_Click" & vbCrLf & _
       "Error Description: " & Err.Description & _
       Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
       , vbOKOnly + vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit
End Sub

Here is the rest of the coding

'Delete the current attachment/record and the attachment file itself
Private Sub cmd_RecDel_Click()
On Error GoTo Error_Handler
Dim sFile                 As String

sFile = Me.FullFileName
'Delete the database record
DoCmd.DoMenuItem acFormBar, acEditMenu, 8, , acMenuVer70
DoCmd.DoMenuItem acFormBar, acEditMenu, 6, , acMenuVer70
'If we're here the record was deleted, so let delete the actual file from the server
Kill sFile

Error_Handler_Exit:
On Error Resume Next
Exit Sub

Error_Handler:
If Err.Number <> 2501 Then
    MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: " & sModName & "\cmd_RecDel_Click" & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has Occured!"
End If
Resume Error_Handler_Exit
End Sub

'Open the attachment
Private Sub cmd_ViewFile_Click()
On Error GoTo Error_Handler

Call ExecuteFile(Me.FullFileName, "Open")

Error_Handler_Exit:
On Error Resume Next
Exit Sub
Error_Handler:
MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
       "Error Number: " & Err.Number & vbCrLf & _
       "Error Source: " & sModName & "\cmd_ViewFile_Click" & vbCrLf & _
       "Error Description: " & Err.Description & _
       Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
       , vbOKOnly + vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit
End Sub

Body:
That is not a valid string in the comment. Constant strings must be enclosed in double quotes "mystring"

Assuming it's a UNC path, this should work:

sFolder = "\\aiowima23fp1\Ecological Sciences and Engineering\Cultural Resources\New - Cultural Resources Request Database\" & sAttachmentFolderName & "\"


问:
How to retrieve the system timezone in TZ format .net c#
I'm trying to work out how to retrieve the current system timezone in a (TZ) format on windows, ie. America/New_York, I need to supply this to an API this application communicates with.

I'm currently using

```<code>TimeZone.CurrentTimeZone
</code>```

Which gives me this output

```<code>GMT Standard Time
</code>```

What I hope to get is something like

```<code>Europe/London
</code>```

Am I missing something simple or is this not available and thus does that mean I need to do the conversion myself?

答:
I recommend to use NodaTime for that.

You can get the timezone of your system like that :

```<code>DateTimeZone tz = DateTimeZoneProviders.Tzdb.GetSystemDefault();
</code>```

It will get the IANA Timezone as you need if you use tz.ToString()

(and apart from that, it is a very nice open source library that handles timezone, datetimes, instants and calendars in a IMHO much more structured and reliable way than the builtin .NET DateTime classes).

NodaTime is maintained and well supported by some high rep users here in SO ;) .

For information, the output that you are getting and you don't want, the one used by .NET, is called BCL Timezone, but you want the IANA Timezone (or TZDB) (which is more accurate)

Body:
I'm trying to work out how to retrieve the current system timezone in a (TZ) format on windows, ie. America/New_York, I need to supply this to an API this application communicates with.

I'm currently using

TimeZone.CurrentTimeZone

Which gives me this output

GMT Standard Time

What I hope to get is something like

Europe/London

Am I missing something simple or is this not available and thus does that mean I need to do the conversion myself?

Body:
I recommend to use NodaTime for that.

You can get the timezone of your system like that :

DateTimeZone tz = DateTimeZoneProviders.Tzdb.GetSystemDefault();

It will get the IANA Timezone as you need if you use tz.ToString()

(and apart from that, it is a very nice open source library that handles timezone, datetimes, instants and calendars in a IMHO much more structured and reliable way than the builtin .NET DateTime classes).

NodaTime is maintained and well supported by some high rep users here in SO ;) .

For information, the output that you are getting and you don't want, the one used by .NET, is called BCL Timezone, but you want the IANA Timezone (or TZDB) (which is more accurate)


问:
Generate a Key, Value JSON object from a Ruby Object Array
I have a Ruby array of students. Student class has attributes id, name and age.

```<code>students = [
             {id:"id1",name:"name1",age:"age1"},
             {id:"id2",name:"name2",age:"age2"},
             {id:"id3",name:"name3",age:"age3"}
           ]
</code>```

I want to create a JSON key value object from this array as follows.

```<code>json_object = {id1:name1, id2:name2, id3:name3}
</code>```

答:
Your data is all identical, but if you wanted to generate a hash that took the value of students[n][:id] as keys and students[n][:name] as values you could do this:

```<code>student_ids_to_names = students.each_with_object({}) do |student, memo|
  memo[student[:id]] = student[:name]
end
</code>```

For your data, you'd end up with only one entry as the students are identical: { "id1" => "name1" }. If the data were different each key would be unique on :id.

Once you have a hash, you can call json_object = students_ids_to_names.to_json to get a JSON string.

Body:
I have a Ruby array of students. Student class has attributes id, name and age.

students = [
             {id:"id1",name:"name1",age:"age1"},
             {id:"id2",name:"name2",age:"age2"},
             {id:"id3",name:"name3",age:"age3"}
           ]

I want to create a JSON key value object from this array as follows.

json_object = {id1:name1, id2:name2, id3:name3}

Body:
Your data is all identical, but if you wanted to generate a hash that took the value of students[n][:id] as keys and students[n][:name] as values you could do this:

student_ids_to_names = students.each_with_object({}) do |student, memo|
  memo[student[:id]] = student[:name]
end

For your data, you'd end up with only one entry as the students are identical: { "id1" => "name1" }. If the data were different each key would be unique on :id.

Once you have a hash, you can call json_object = students_ids_to_names.to_json to get a JSON string.


问:
How to use npm with source control and multiple developers
I have an Angular-Application, which I would like to bundle within a jar-File (containing the Back-End), using an Ant-script.

This Ant-script should install/update the dependencies (using npm) and then build the application using Angular CLI.

It will be used by multiple developers on multiple environments and not all of the developers have to deal with Front-End, so the requirements should be as low as possible.

Idealy only NodeJS needs to be installed on all the PCs.

Therefore the Ant-script has to make sure, that all the dependencies are installed and up to date, before building the web-page.

Now I can think of multiple ways for doing this, however I am not sure which one is the best and the most stable way:

Delete node_modules folder and reinstall all modules using npm install.

This is probably save, but slow, as an Angular-Applications have tons of dependencies to download.

Use npm install, without deleting the node_modules first.

This will be faster but some libraries (for example Angular CLI) suggest to do a clean install when updating.

Use npm update. This way the dependencies would not only be installed, but also updated to match the latest possible version (^ or ~ will affect update).

At the moment I use npm install, if node_modules-folder does not exist and npm update otherwise.

The main problem is, that npm update might change the package.lock.json, which is versioned (as sugested by npm documentation) and it led to merge conflicts.

So basicly I am looking for a way to install all the needed dependencies (only NodeJS is a requirement for all developers) inside the build-script, without touching versioned files.

答: Option #1 is the way to go. You should only have your package.json file with all the dependencies that your project has. No need and really it's just way to have to include node_modules.</p>


问:
Error:Module 'app': platform 'Google Inc.:Google APIs:23' not found
Gradle file:

```<code>android {
    compileSdkVersion 'Google Inc.:Google APIs:23'
    buildToolsVersion '27.0.1'
</code>```

It works perfectly in other Windows machine, but in this computer it gives this error: Error:Module 'app': platform 'Google Inc.:Google APIs:23' not found.

I need to compile with Google APIs:23 instead of SDK 23 because I'm using some things that are in Google APIs add-on.

I checked that some solutions here in Stack Overflow tell that you can avoid this problem changing my Gradle file to compileSdkVersion 23, but it is not a good solution because if you do that you are not compiling using Google APIs add-ons.

Both AndroidStudios and AndroidSDKs are fully updated in both machines, so I can't understand why I'm getting this error only in one of them.

答:
Finally I got it working.

Rename your line from compileSdkVersion 'Google Inc.:Google APIs:23' to compileSdkVersion 23

Build project, it should work (but supossedly without google apis add-ons)

Rename again your line from compileSdkVersion 23 to 'Google Inc.:Google APIs:23'.

Build project.

If it does not work, try downloading Google APIs:23 add-on from command line tool sdkmanager and repeat the process.

Body:
Gradle file:

android {
    compileSdkVersion 'Google Inc.:Google APIs:23'
    buildToolsVersion '27.0.1'

It works perfectly in other Windows machine, but in this computer it gives this error: Error:Module 'app': platform 'Google Inc.:Google APIs:23' not found.

I need to compile with Google APIs:23 instead of SDK 23 because I'm using some things that are in Google APIs add-on.

I checked that some solutions here in Stack Overflow tell that you can avoid this problem changing my Gradle file to compileSdkVersion 23, but it is not a good solution because if you do that you are not compiling using Google APIs add-ons.

Both AndroidStudios and AndroidSDKs are fully updated in both machines, so I can't understand why I'm getting this error only in one of them.


答:
Give this a go:

```<code>students = [
             {id:"id1",name:"name1",age:"age1"},
             {id:"id2",name:"name2",age:"age2"},
             {id:"id3",name:"name3",age:"age3"}
           ]

json_object = students.each_with_object({}) do |hsh, returning|
  returning[hsh[:id]] = hsh[:name]
end.to_json
</code>```

In console:

```<code>puts json_object
 => {"id1":"name1","id2":"name2","id3":"name3"}
</code>```

Title: Generate a Key, Value JSON object from a Ruby Object Array

Body:
Give this a go:

students = [
             {id:"id1",name:"name1",age:"age1"},
             {id:"id2",name:"name2",age:"age2"},
             {id:"id3",name:"name3",age:"age3"}
           ]

json_object = students.each_with_object({}) do |hsh, returning|
  returning[hsh[:id]] = hsh[:name]
end.to_json

In console:

puts json_object
 => {"id1":"name1","id2":"name2","id3":"name3"}


问:
flexible css button no images
need your brains!!

i am hoping to make a button with no images, as with CSS3, that will scale based on the verbiage in the button. I have tried a few things but I am unable to get anything to work.

For Example:
the button has a minimum width of say 95px

and that's great for HOME or ABOUT US
but if i have copy that is like
Dallas City Council Team

It would be great if the button would get wider.

Can anyone help me with this? pretty please? I've driven myself insane!!!

Thank you so much in advance!!!

答:
this is how i wound up resolving my issue. it's not as pretty as i'd like but it's going to work. i was having trouble setting the minimum width, so i just changed it all to have a fixed width of 200 because that's all the space i have available. that being said, if you remove the DISPLAY: INLINE-BLOCK; it will go back to scaling based on the menu button copy (even if you leave the width:200px; in there)

i also had to create 'left menu anchor' classes because all of our links were blue and didn't show up very well but that was just a quick copy, rename and color change.

thank you guys for all of your help! i truly appreciate it. hope this helps some peeps in the future.

.left_menu_btn_css {
  background: #39a7f0;
  background-image: -webkit-linear-gradient(top, #39a7f0, #2979ab);
  background-image: -moz-linear-gradient(top, #39a7f0, #2979ab);
  background-image: -ms-linear-gradient(top, #39a7f0, #2979ab);
  background-image: -o-linear-gradient(top, #39a7f0, #2979ab);
  background-image: linear-gradient(to bottom, #39a7f0, #2979ab);
  -webkit-border-radius: 5;
  -moz-border-radius: 5;
  border-radius: 3px;
  font-family: Arial;
  color: #ffffff;
  font-size: 12px;
  padding: 5px 5px 5px 5px;
  text-decoration: none;
  width: 200px;
  display: inline-block;
}

.left_menu_btn_css:hover {
  background: #3cb0fd;
  background-image: -webkit-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -moz-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -ms-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -o-linear-gradient(top, #3cb0fd, #3498db);
  background-image: linear-gradient(to bottom, #3cb0fd, #3498db);
  text-decoration: none;
}```

Title: flexible css button no images


问:
Google Cloud VPS network traffic
I have a Google Cloud Compute Engine Windows VPS. I wanted to know that if i try to upload files on Google Drive from VPS will it charge me network fees.

as per the chart below I thought it will not because google cloud VPS and Google Drive is from Google and utilizing other google services from VPS is free. Please tell me if i am wrong? just wanted to confirm

答:
Yes, you are right.

Network Egress traffic to Google products (such as YouTube, Maps, Drive), whether from a VM in GCP with a public (external) IP addresses or private (internal) IP addresses has no charge

General network pricing.

I know it used to be a promotional price but now it's in the General network pricing list as 'No charge'.

Title: Google Cloud VPS network traffic


问:
How to ask for NSPhotoLibraryAddUsageDescription manually?
In IOS there is a permission NSPhotoLibraryAddUsageDescription
and I would like to ask for it when my app is started for the first time.

So I want just to check if it is permitted and ask for it.

What I can do to force this permission check?

答:
I would strongly discourage you from asking this when your app is started for the first time. It is much better to wait until the app needs to use that functionality when you have an opportunity to explain to your users why the app is asking for that permission.

Your app can only ever ask for this permission once, and without the proper context of why it is asking, users are much more inclined to decline the permission. You will get a much higher percentage of users granting permission if they better understand the benefit they will receive by granting it.


问:
Cannot complete the function with CDOEX and Exchange 2000
I am trying to create an appointment using CDOEX in Exchange 2000. The code snippet is from msdn and is VB6.

When I reach this line: ".DataSource.SaveToContainer iMbx.Calendar, Conn" I am getting error "cannot complete the function (800703eb)"

Any help will be appreciated!

```<code>Function CreateAppointment(StartTime As Date, _
                            EndTime As Date, _
                            Subject As String, _
                            Location As String, _
                            TextBody As String, _
                            iMbx As IMailbox) As Appointment

' Reference to Microsoft ActiveX Data Objects 2.5 Library
' Reference to Microsoft CDO for Exchange 2000 Library

    Dim iAppt       As New Appointment
    Dim Conn        As New ADODB.Connection
    Conn.Provider = "ExOLEDB.DataSource"

    'Set the appointment properties
    With iAppt
        .StartTime = StartTime
        .EndTime = EndTime
        .Subject = Subject
        .Location = Location
        .TextBody = TextBody
        'Save the appointment
        Conn.Open iMbx.BaseFolder
        .DataSource.SaveToContainer iMbx.Calendar, Conn
    End With

    Set CreateAppointment = iAppt
End Function
</code>```

答:
I have found the problem and solution, so here it is in case somebody needs it: link
Also, I have found examples that saved my life: link</p>

Body:
I am trying to create an appointment using CDOEX in Exchange 2000. The code snippet is from msdn and is VB6.

When I reach this line: ".DataSource.SaveToContainer iMbx.Calendar, Conn" I am getting error "cannot complete the function (800703eb)"

Any help will be appreciated!

Function CreateAppointment(StartTime As Date, _
                            EndTime As Date, _
                            Subject As String, _
                            Location As String, _
                            TextBody As String, _
                            iMbx As IMailbox) As Appointment

' Reference to Microsoft ActiveX Data Objects 2.5 Library
' Reference to Microsoft CDO for Exchange 2000 Library

    Dim iAppt       As New Appointment
    Dim Conn        As New ADODB.Connection
    Conn.Provider = "ExOLEDB.DataSource"

    'Set the appointment properties
    With iAppt
        .StartTime = StartTime
        .EndTime = EndTime
        .Subject = Subject
        .Location = Location
        .TextBody = TextBody
        'Save the appointment
        Conn.Open iMbx.BaseFolder
        .DataSource.SaveToContainer iMbx.Calendar, Conn
    End With

    Set CreateAppointment = iAppt
End Function


问:
C# Entity Framework, Simplify Select Child Property That Using Same Condition
I have 2 ef model, let's say  Task() and Progress()

```<code>public class Task()
{
    public int Id { get; set; }
    public string Title { get; set; }
}
</code>```

and then

```<code>public class Progress()
{
    public int Id { get; set; }
    public int Id_Task { get; set; }
    public string Status { get; set; }
    public DateTime Update { get; set; }
}
</code>```

I want to get data for each task and it's last progress, So i make a ViewModel

```<code>public class ViewTask()
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Last_Status { get; set; }
    public DateTime Last_Update { get; set; }
}
</code>```

Right now, this is what i did:

```<code>var data = _context.Task
    .Select(x => new ViewTask
    {
        Id = x.Id,
        Title = x.Title,
        Last_Status = x.Progress.OrderByDescending(y => y.Update)
            .Select(y => y.Status).FirstOrDefault(),
        Last_Update = x.Progress.OrderByDescending(y => y.Update)
            .Select(y => y.Update).FirstOrDefault()
    }).ToList();
</code>```

Is there any better ways so I don't need to repeat x.Progress... part? The only code i can think of is something like this:

```<code>var data = _context.Task
    .Select(x => new
    {
        Id = x.Id,
        Title = x.Title,
        Progress = x.Progress.OrderByDescending(y => y.Update).FirstOrDefault()
    })
    .Select(x => new ViewTask
    {
        Id = x.Id,
        Title = x.Title,
        Last_Status = x.Progress.Status
        Last_Update = x.Progress.Update
    }).ToList();
</code>```

I appriciete any kind of suggestion. Thanks :)

答:
You can use MaxBy and MinBy methods from moreLINQ library.

```<code>var data = _context.Task
.Select(x => new ViewTask
{
    Id = x.Id,
    Title = x.Title,
    Last_Status = x.Progress.MaxBy(y => y.Update).Status,
    Last_Update = x.Progress.MaxBy(y => y.Update).Update
 }).ToList();
</code>```

Hope it helps!!

Body:
I have 2 ef model, let's say  Task() and Progress()

public class Task()
{
    public int Id { get; set; }
    public string Title { get; set; }
}

and then

public class Progress()
{
    public int Id { get; set; }
    public int Id_Task { get; set; }
    public string Status { get; set; }
    public DateTime Update { get; set; }
}

I want to get data for each task and it's last progress, So i make a ViewModel

public class ViewTask()
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Last_Status { get; set; }
    public DateTime Last_Update { get; set; }
}

Right now, this is what i did:

var data = _context.Task
    .Select(x => new ViewTask
    {
        Id = x.Id,
        Title = x.Title,
        Last_Status = x.Progress.OrderByDescending(y => y.Update)
            .Select(y => y.Status).FirstOrDefault(),
        Last_Update = x.Progress.OrderByDescending(y => y.Update)
            .Select(y => y.Update).FirstOrDefault()
    }).ToList();

Is there any better ways so I don't need to repeat x.Progress... part? The only code i can think of is something like this:

var data = _context.Task
    .Select(x => new
    {
        Id = x.Id,
        Title = x.Title,
        Progress = x.Progress.OrderByDescending(y => y.Update).FirstOrDefault()
    })
    .Select(x => new ViewTask
    {
        Id = x.Id,
        Title = x.Title,
        Last_Status = x.Progress.Status
        Last_Update = x.Progress.Update
    }).ToList();

I appriciete any kind of suggestion. Thanks :)

Body:
You can use MaxBy and MinBy methods from moreLINQ library.

var data = _context.Task
.Select(x => new ViewTask
{
    Id = x.Id,
    Title = x.Title,
    Last_Status = x.Progress.MaxBy(y => y.Update).Status,
    Last_Update = x.Progress.MaxBy(y => y.Update).Update
 }).ToList();

Hope it helps!!


问:
Golang read line and then read word from same bufio.Scanner
I'm trying to read a line and words from stdin using the same bufio.Scanner instance.

I've tried using two bufio.Scanner first but it the second scanner can't read anything.

```<code>package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

func main() {
    r := strings.NewReader("first line\n2nd line")
    scanner := bufio.NewScanner(r)
    scanner2 := bufio.NewScanner(r)

    fmt.Println("scanning line")
    if scanner.Scan() {
        fmt.Println("Scanned line: ", scanner.Text())
    }

    if err := scanner.Err(); err != nil {
        fmt.Fprintln(os.Stderr, "reading standard input:", err)
    }

    scanner2.Split(bufio.ScanWords)
    fmt.Println("scanning word")
    if scanner2.Scan() {
        // i'm expecting that this would read "2nd"
        fmt.Println("Scanned word: ", scanner2.Text())
    }

    if err := scanner2.Err(); err != nil {
        fmt.Fprintln(os.Stderr, "reading standard input:", err)
    }
}
</code>```

Then I tried setting the scanner.Split , but it doesn't allow calling the scanner.Split after calling scanner.Scan.

Is there a way that I can read a line and then words from the same bufio.Scanner?

答:
First. You can't read same line from reader multiple times. You read it once reader going to be empty, that is why the second scanner can't read anything. In your example you are using strings.Reader no os.Stdin. You can use something like io.TeeReader to duplicate to read the reader more times but this isn't your case.

Second. You cant call scanner.Split after scanner.Scan was called, you need to create a new scanner with os.Stdin as input.

For example:

```<code>// this gonna read from stdin complete lines
scanner := bufio.NewScanner(os.Stdin)

// scanning lines until Q is typed
for scanner.Scan() {
    t := scanner.Text()

    if t == "Q" {
        break
    }
    fmt.Println(scanner.Text())
}

// new scanner to read but this time words
scanner = bufio.NewScanner(os.Stdin)
scanner.Split(bufio.ScanWords)

for scanner.Scan() {
    fmt.Println(scanner.Text()) // Println will add back the final '\n'
}
</code>```

Body:
I'm trying to read a line and words from stdin using the same bufio.Scanner instance.

I've tried using two bufio.Scanner first but it the second scanner can't read anything.

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

func main() {
    r := strings.NewReader("first line\n2nd line")
    scanner := bufio.NewScanner(r)
    scanner2 := bufio.NewScanner(r)

    fmt.Println("scanning line")
    if scanner.Scan() {
        fmt.Println("Scanned line: ", scanner.Text())
    }

    if err := scanner.Err(); err != nil {
        fmt.Fprintln(os.Stderr, "reading standard input:", err)
    }

    scanner2.Split(bufio.ScanWords)
    fmt.Println("scanning word")
    if scanner2.Scan() {
        // i'm expecting that this would read "2nd"
        fmt.Println("Scanned word: ", scanner2.Text())
    }

    if err := scanner2.Err(); err != nil {
        fmt.Fprintln(os.Stderr, "reading standard input:", err)
    }
}

Then I tried setting the scanner.Split , but it doesn't allow calling the scanner.Split after calling scanner.Scan.

Is there a way that I can read a line and then words from the same bufio.Scanner?

Body:
First. You can't read same line from reader multiple times. You read it once reader going to be empty, that is why the second scanner can't read anything. In your example you are using strings.Reader no os.Stdin. You can use something like io.TeeReader to duplicate to read the reader more times but this isn't your case.

Second. You cant call scanner.Split after scanner.Scan was called, you need to create a new scanner with os.Stdin as input.

For example:

// this gonna read from stdin complete lines
scanner := bufio.NewScanner(os.Stdin)

// scanning lines until Q is typed
for scanner.Scan() {
    t := scanner.Text()

    if t == "Q" {
        break
    }
    fmt.Println(scanner.Text())
}

// new scanner to read but this time words
scanner = bufio.NewScanner(os.Stdin)
scanner.Split(bufio.ScanWords)

for scanner.Scan() {
    fmt.Println(scanner.Text()) // Println will add back the final '\n'
}


问:
Is there a way to infuse the input variable in regex?
EDIT: So apparently, this is a string interpolation in regex. Thanks for clarifying.

I have a input function that is named omj.

```<code>omj
</code>```

When I run it, it gives me

```<code>"obik"
</code>```

I then use that output in this regex function

```<code>re.findall("\w*obik\w*",dataframe)
</code>```

I received EXACTLY what I wanted, which is the answer

```<code>"Yaobikuni"
</code>```

Notice that "obik" is in the word, and there is only one match for it. Is there a way to put the input omj in the regex function to get Yaobikuni straightforwardly, or is this the only way it would work?

EDIT: I don't understand why people are downvoting, but I thought I made it clear that omj can be considered as an input string that gives the answer obik.

```<code>omj = """obik"""
</code>```

EDIT2: Thank you for the help @Nick Chapman . I tried this on the first time and I thought it might not have been possible to infuse the input omj on an regex function:

```<code>re.findall("\w*"omj"\w*",dataframe)
</code>```

答:
Can't you just do</p>

```<code>re.findall("\w*" + omj + "\w*",dataframe)
</code>```

Body:
EDIT: So apparently, this is a string interpolation in regex. Thanks for clarifying.

I have a input function that is named omj.

omj

When I run it, it gives me

"obik"

I then use that output in this regex function

re.findall("\w*obik\w*",dataframe)

I received EXACTLY what I wanted, which is the answer

"Yaobikuni"

Notice that "obik" is in the word, and there is only one match for it. Is there a way to put the input omj in the regex function to get Yaobikuni straightforwardly, or is this the only way it would work?

EDIT: I don't understand why people are downvoting, but I thought I made it clear that omj can be considered as an input string that gives the answer obik.

omj = """obik"""

EDIT2: Thank you for the help @Nick Chapman . I tried this on the first time and I thought it might not have been possible to infuse the input omj on an regex function:

re.findall("\w*"omj"\w*",dataframe)

Body:
Can't you just do

re.findall("\w*" + omj + "\w*",dataframe)


问:
Return to the caller state?
I am using C#'s stateless state-machine, but I've had this issue in the past with other state-machine implementation. The question is mostly theoretical, though I can add some dummy code if asked for.

I have a situation which I am quite unsure how to solve. Lets say you have 2 states (walk and run), and they both can transition to a 3rd state (jump). Once the 3rd state is done, I wish to go back to the caller state. In a way, I'd have to be able to influence the callee trigger, but this is only passed on to OnEntry and the likes, not the state itself.

Using EntryFrom doesn't seem to work, because there is no way to influence the "jump" state itself, only the OnEntry function.
Using PermitDynamic doesn't seem to work either, because once in the "jump" state, I have no idea where I came from.

I could have 2 jump states (jumpfromrun, jumpfromwalk) with a single OnEntry function, to minimize some duplicate code. This is what I currently use.

I could save the previous state in an external variable and pass that to my state update. I do not wish to do this (at all).

Is there a known technique or way to deal with this sort of problem? Having a shared state, that should transition back to the caller?
Thank you!

答:
From reading the docs, it seems like this is a pretty good usecase for substates.

You can have a jump state:

```<code>stateMachine.Configure(State.Jumping)
    .OnEntry(() => StartJump())
    .OnExit(() => EndJump());
</code>```

and two jump sub-states. One for walking, one for running:

```<code>stateMachine.Configure(State.WalkJumping)
    .SubstateOf(State.Jumping)
    .Permit(Trigger.DoneJumping, State.Walking);

stateMachine.Configure(State.RunJumping)
    .SubstateOf(State.Jumping)
    .Permit(Trigger.DoneJumping, State.Running);
</code>```

Then you make walk and run route to WalkJumping and RunJumping, respectively.

```<code>stateMachine.Configure(State.Walking)
    .OnEntry(() => StartWalking())
    .OnExit(() => EndWalking());
    .Permit(Trigger.Jump, State.WalkJumping);

stateMachine.Configure(State.Running)
    .OnEntry(() => StartRunning())
    .OnExit(() => EndRunning());
    .Permit(Trigger.Jump, State.RunJumping);
</code>```

Using substrates like this, as opposed to just regular states, has the added benefit that the State.Jumping can define the same OnEntry and OnExit that will be inherited by both WalkJumping and EndJumping.

Additionally, it gives you an easier way to check if you're in the middle of a jump. Instead of:

```<code>var state = stateMachine.state;
var isJumping = state == State.WalkJumping || state == RunJumping;
</code>```

You can simply do:

```<code>var isJumping = stateMachine.IsInState(State.Jumping);
</code>```

Which will properly consider all substates, which are currently WalkJumping and RunJumping. But if you add a new jump substate in the future, e.g. DoubleJumping, then the isJumping predicate will automatically cover that case too, without needing to remember to fix it.

Title: Return to the caller state?

Body:
From reading the docs, it seems like this is a pretty good usecase for substates.

You can have a jump state:

stateMachine.Configure(State.Jumping)
    .OnEntry(() => StartJump())
    .OnExit(() => EndJump());

and two jump sub-states. One for walking, one for running:

stateMachine.Configure(State.WalkJumping)
    .SubstateOf(State.Jumping)
    .Permit(Trigger.DoneJumping, State.Walking);

stateMachine.Configure(State.RunJumping)
    .SubstateOf(State.Jumping)
    .Permit(Trigger.DoneJumping, State.Running);

Then you make walk and run route to WalkJumping and RunJumping, respectively.

stateMachine.Configure(State.Walking)
    .OnEntry(() => StartWalking())
    .OnExit(() => EndWalking());
    .Permit(Trigger.Jump, State.WalkJumping);

stateMachine.Configure(State.Running)
    .OnEntry(() => StartRunning())
    .OnExit(() => EndRunning());
    .Permit(Trigger.Jump, State.RunJumping);

Using substrates like this, as opposed to just regular states, has the added benefit that the State.Jumping can define the same OnEntry and OnExit that will be inherited by both WalkJumping and EndJumping.

Additionally, it gives you an easier way to check if you're in the middle of a jump. Instead of:

var state = stateMachine.state;
var isJumping = state == State.WalkJumping || state == RunJumping;

You can simply do:

var isJumping = stateMachine.IsInState(State.Jumping);

Which will properly consider all substates, which are currently WalkJumping and RunJumping. But if you add a new jump substate in the future, e.g. DoubleJumping, then the isJumping predicate will automatically cover that case too, without needing to remember to fix it.


问:
Retrofit2: ClassCastException: java.util.ArrayList cannot be cast to retrofit2.Call
please help with Retrofit2. I'm very new in Retrofit.
I create simple server application.
The application manage list of Journals: add Journal in the in-memory list and return Journal by id.
There is an Journal.java:

```<code>public class Journal {
private AtomicInteger getNewId = new AtomicInteger(0);
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("name")
@Expose
private String name;

public Journal(String name) {
    this.id = getNewId.incrementAndGet();
    this.name = name;}

public Integer getId() {return id;}
public String getName() {return name;}
}
</code>```

There is an controller interface:

```<code>public interface JournalController {

@GET("journal")
Call<List<Journal>> getJournalList();

@GET("journal/{id}")
Call<Journal> getJournal(@Path("id") Integer id);

@POST("journal")
Call<Journal>  addJournal(@Body Journal journal);
}
</code>```

This is interface implementation:

```<code>@Controller
public class JournalControllerImpl implements JournalController {
// An in-memory list that the controller uses to store the Journals
private List<Journal> journals = new ArrayList<>();

@RequestMapping(value= "journal", method=RequestMethod.GET)
public @ResponseBody Call<List<Journal>> getJournalList() {
    return (Call<List<Journal>>) journals;}

@RequestMapping(value= "journal/{id}", method= RequestMethod.GET)
public @ResponseBody Call<Journal> getJournal(@Path("id") Integer id) {
    Journal journal = journals.get(id);
    return (Call<Journal>) journal;}

@RequestMapping(value= "journal", method= RequestMethod.POST)
public @ResponseBody Call<Journal> addJournal(@Body Journal journal) {
    journals.add(journal);
    return (Call<Journal> ) journal; }
}
</code>```

The application started succesesully. Console output during application's startup:

Mapped "{[/journal],methods=[GET]}" onto public retrofit2.Call> main.JournalControllerImpl.getJournalList()

Mapped "{[/journal],methods=[POST]}" onto public retrofit2.Call main.JournalControllerImpl.addJournal(main.Journal)

Mapped "{[/journal{/id}],methods=[GET]}" onto public retrofit2.Call main.JournalControllerImpl.getJournal(java.lang.Integer)

Than I try to run URL http://localhost:8080/journal on browser (or GET HttpRequest http://localhost:8080/journal).
There is an error in application output:

"... java.lang.ClassCastException: java.util.ArrayList cannot be cast to retrofit2.Call..."

Could you guess what is wrong?
Is it really problems with conversion java.util.ArrayList to Call ? (I've tryed to CopyOnWriteArrayList but this doesn't help.

Thank you in advance.

答:
The way to use the service interface (service) is to the service with a callback (onResponse, onFailure)implement the detail the logic need as highlighted below.

//Pass in a constructor upon creating
   JournalController journalService;
    //Return journal list

```<code>Call<List<Journal>> call = journalService.getJournalList();
call.enqueue(new Callback<>() {
    @Override
    public void onResponse(Call<List<Journal>> call, Response<List<Journal>>
       response) {
       int statusCode = response.code();
       List<Journal> journal = response.body();

   }

   @Override
   public void onFailure(Call<Journal> call, Throwable t) {
      // Log error here since request failed
  }
});

//Return a journal

Call<Journal> call = journalService.getJournal(userId);
call.enqueue(new Callback<Journal>() {
    @Override
    public void onResponse(Call<Journal> call, Response<Journal> response) {
       int statusCode = response.code();
       Journal journal = response.body();
   }

   @Override
   public void onFailure(Call<Journal> call, Throwable t) {
      // Log error here since request failed
  }
});

//Add journal

Call<Journal> call = journalService.addJournal(new Journal("username");
call.enqueue(new Callback<Journal>() {
    @Override
    public void onResponse(Call<Journal> call, Response<Journal> response) {
       int statusCode = response.code();
       Journal journal = response.body();
   }

   @Override
   public void onFailure(Call<Journal> call, Throwable t) {
      // Log error here since request failed
  }
});
</code>```

Body:
please help with Retrofit2. I'm very new in Retrofit.
I create simple server application.
The application manage list of Journals: add Journal in the in-memory list and return Journal by id.
There is an Journal.java:

public class Journal {
private AtomicInteger getNewId = new AtomicInteger(0);
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("name")
@Expose
private String name;

public Journal(String name) {
    this.id = getNewId.incrementAndGet();
    this.name = name;}

public Integer getId() {return id;}
public String getName() {return name;}
}

There is an controller interface:

public interface JournalController {

@GET("journal")
Call<List<Journal>> getJournalList();

@GET("journal/{id}")
Call<Journal> getJournal(@Path("id") Integer id);

@POST("journal")
Call<Journal>  addJournal(@Body Journal journal);
}

This is interface implementation:

@Controller
public class JournalControllerImpl implements JournalController {
// An in-memory list that the controller uses to store the Journals
private List<Journal> journals = new ArrayList<>();

@RequestMapping(value= "journal", method=RequestMethod.GET)
public @ResponseBody Call<List<Journal>> getJournalList() {
    return (Call<List<Journal>>) journals;}

@RequestMapping(value= "journal/{id}", method= RequestMethod.GET)
public @ResponseBody Call<Journal> getJournal(@Path("id") Integer id) {
    Journal journal = journals.get(id);
    return (Call<Journal>) journal;}

@RequestMapping(value= "journal", method= RequestMethod.POST)
public @ResponseBody Call<Journal> addJournal(@Body Journal journal) {
    journals.add(journal);
    return (Call<Journal> ) journal; }
}

The application started succesesully. Console output during application's startup:

Mapped "{[/journal],methods=[GET]}" onto public retrofit2.Call> main.JournalControllerImpl.getJournalList()

Mapped "{[/journal],methods=[POST]}" onto public retrofit2.Call main.JournalControllerImpl.addJournal(main.Journal)

Mapped "{[/journal{/id}],methods=[GET]}" onto public retrofit2.Call main.JournalControllerImpl.getJournal(java.lang.Integer)

Than I try to run URL http://localhost:8080/journal on browser (or GET HttpRequest http://localhost:8080/journal).
There is an error in application output:

"... java.lang.ClassCastException: java.util.ArrayList cannot be cast to retrofit2.Call..."

Could you guess what is wrong?
Is it really problems with conversion java.util.ArrayList to Call ? (I've tryed to CopyOnWriteArrayList but this doesn't help.

Thank you in advance.

Body:
The way to use the service interface (service) is to the service with a callback (onResponse, onFailure)implement the detail the logic need as highlighted below.

//Pass in a constructor upon creating
   JournalController journalService;
    //Return journal list

Call<List<Journal>> call = journalService.getJournalList();
call.enqueue(new Callback<>() {
    @Override
    public void onResponse(Call<List<Journal>> call, Response<List<Journal>>
       response) {
       int statusCode = response.code();
       List<Journal> journal = response.body();

   }

   @Override
   public void onFailure(Call<Journal> call, Throwable t) {
      // Log error here since request failed
  }
});

//Return a journal

Call<Journal> call = journalService.getJournal(userId);
call.enqueue(new Callback<Journal>() {
    @Override
    public void onResponse(Call<Journal> call, Response<Journal> response) {
       int statusCode = response.code();
       Journal journal = response.body();
   }

   @Override
   public void onFailure(Call<Journal> call, Throwable t) {
      // Log error here since request failed
  }
});

//Add journal

Call<Journal> call = journalService.addJournal(new Journal("username");
call.enqueue(new Callback<Journal>() {
    @Override
    public void onResponse(Call<Journal> call, Response<Journal> response) {
       int statusCode = response.code();
       Journal journal = response.body();
   }

   @Override
   public void onFailure(Call<Journal> call, Throwable t) {
      // Log error here since request failed
  }
});


问:
How to add a redirection button to jqGrid with a rowID parameter
I'm using jqGrid to display a database table on screen, and I need to add at the end of every row a button that redirects me to another page (let's call it page2.php) AND that passes the value of the row ID through to that page.

I've added a column in colModel with a formatter but I can't seem to find the right function to add a functionnal button (the redirection works fine but I have trouble with the ID passing) :

```<code>{name:'refresh', index:'refresh', width:70, align:'center', formatter:refreshButton}
</code>```

And the corresponding function :

```<code>function refreshButton(cellvalue, options, rowobject){
    return '<button type="button" onclick="window.location=\'page2.php\'">Go</button>';
}
</code>```

i found somewhere that adding ?id="+rowid+"&oper=edit after page2.php would work to pass the rowID but then the redirection won't work anymore...

I'd gladly use some help with that, thanks in advance

答:
This code works for me any time I click on the button</p>

```<code>function refreshButton(cellvalue, options, rowobject) {
    return '<button type="button" onclick="location.href=\'page2.php?oper=edit&id='+options.rowId+'\'">Go</button>';
}
</code>```

Body:
I'm using jqGrid to display a database table on screen, and I need to add at the end of every row a button that redirects me to another page (let's call it page2.php) AND that passes the value of the row ID through to that page.

I've added a column in colModel with a formatter but I can't seem to find the right function to add a functionnal button (the redirection works fine but I have trouble with the ID passing) :

{name:'refresh', index:'refresh', width:70, align:'center', formatter:refreshButton}

And the corresponding function :

function refreshButton(cellvalue, options, rowobject){
    return '<button type="button" onclick="window.location=\'page2.php\'">Go</button>';
}

i found somewhere that adding ?id="+rowid+"&oper=edit after page2.php would work to pass the rowID but then the redirection won't work anymore...

I'd gladly use some help with that, thanks in advance

Body:
This code works for me any time I click on the button

function refreshButton(cellvalue, options, rowobject) {
    return '<button type="button" onclick="location.href=\'page2.php?oper=edit&id='+options.rowId+'\'">Go</button>';
}