问:
Issues in getting a value of a key from an object using md-select AngularJs 1.X.X
I'm having an issue in getting a Value of a Key from an Object which is selected using md-select in a AngularJs application (Version 1.X.X).

I having a two drop downs "Department" and "Designation". Initially I loaded the Department and based on Department selection, the Designation will auto populate. Kindly have a look into the JSON object

```<code>{
   "Status":true,
   "Message":"",
   "Result":[
      {
         "DepartmentId":1,
         "Name":"Bala",
         "Designation":[
            {
               "DesignationId":1,
               "DepartmentId":1,
               "Name":"Software Engg"
            },
            {
               "DesignationId":3,
               "DepartmentId":1,
               "Name":"Sr. Human Resouce"
            },
            {
               "DesignationId":2,
               "DepartmentId":1,
               "Name":"Sr. Software Engg"
            }
         ]
      },
      {
         "DepartmentId":2,
         "Name":"Dev",
         "Designation":[

         ]
      },
      {
         "DepartmentId":3,
         "Name":"HR Team",
         "Designation":[

         ]
      },
      {
         "DepartmentId":4,
         "Name":"Sales",
         "Designation":[
            {
               "DesignationId":4,
               "DepartmentId":4,
               "Name":"Sr. Sales Manager"
            }
         ]
      }
   ]
}
</code>```

Kindly have a look the code

<!DOCTYPE html>

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.1/angular-material.min.css">

Department:

  <md-select ng-model="select.Department" tabindex="9" ng-change="onChange(select.Department)">
    <md-option ng-repeat="key in loadUpData.Department" value="{{key}}">{{key.Name}}</md-option>
  </md-select>

Department ID:

  <md-input-container class="md-block">
    <input type="text" ng-model="select.Department.DepartmentId" maxlength="300" tabindex="32" />
  </md-input-container>

Designation:

  <md-select ng-model="select.Designation" tabindex="9">
    <md-option ng-repeat="key in designationData" value="{{key}}">{{key.Name}}</md-option>
  </md-select>

Designation ID:

  <md-input-container class="md-block">
    <input type="text" ng-model="select.Designation.DesignationId" maxlength="300" tabindex="32" />
  </md-input-container>

```

I'm trying to display the DepartmentId and DesignationId of a Selected Item, but I can't able to get the Id's. Kindly assist me.

答:
Two main things needed fixing:

You define $scope.Select = ... in your controller but try to reference it with ng-model="select.Department" in the view. JavaScript/Angular is case-sensitive so Select !== select - make sure to reference variables with the same case.

On the <md-option> elements use ng-value="key" instead of value="{{key}}" when you want to bind an object value to the control. With this fixed you don't need JSON.parse(...) in the onChange handler.

With these two changes here is the updated code:

    <!DOCTYPE html>

    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.1/angular-material.min.css">

Department:

      <md-select ng-model="select.Department" tabindex="9" ng-change="onChange(select.Department)">
        <md-option ng-repeat="key in loadUpData.Department" ng-value="key">{{key.Name}}</md-option>
      </md-select>

Department ID:

      <md-input-container class="md-block">
        <input type="text" ng-model="select.Department.DepartmentId" maxlength="300" tabindex="32" />
      </md-input-container>

Designation:

      <md-select ng-model="select.Designation" tabindex="9">
        <md-option ng-repeat="key in designationData" ng-value="key">{{key.Name}}</md-option>
      </md-select>

Designation ID:

      <md-input-container class="md-block">
        <input type="text" ng-model="select.Designation.DesignationId" maxlength="300" tabindex="32" />
      </md-input-container>

    ```

Body:
I'm having an issue in getting a Value of a Key from an Object which is selected using md-select in a AngularJs application (Version 1.X.X).

I having a two drop downs "Department" and "Designation". Initially I loaded the Department and based on Department selection, the Designation will auto populate. Kindly have a look into the JSON object

{
   "Status":true,
   "Message":"",
   "Result":[
      {
         "DepartmentId":1,
         "Name":"Bala",
         "Designation":[
            {
               "DesignationId":1,
               "DepartmentId":1,
               "Name":"Software Engg"
            },
            {
               "DesignationId":3,
               "DepartmentId":1,
               "Name":"Sr. Human Resouce"
            },
            {
               "DesignationId":2,
               "DepartmentId":1,
               "Name":"Sr. Software Engg"
            }
         ]
      },
      {
         "DepartmentId":2,
         "Name":"Dev",
         "Designation":[

         ]
      },
      {
         "DepartmentId":3,
         "Name":"HR Team",
         "Designation":[

         ]
      },
      {
         "DepartmentId":4,
         "Name":"Sales",
         "Designation":[
            {
               "DesignationId":4,
               "DepartmentId":4,
               "Name":"Sr. Sales Manager"
            }
         ]
      }
   ]
}

Kindly have a look the code

<!DOCTYPE html>

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.1/angular-material.min.css">

Department:

  <md-select ng-model="select.Department" tabindex="9" ng-change="onChange(select.Department)">
    <md-option ng-repeat="key in loadUpData.Department" value="{{key}}">{{key.Name}}</md-option>
  </md-select>

Department ID:

  <md-input-container class="md-block">
    <input type="text" ng-model="select.Department.DepartmentId" maxlength="300" tabindex="32" />
  </md-input-container>

Designation:

  <md-select ng-model="select.Designation" tabindex="9">
    <md-option ng-repeat="key in designationData" value="{{key}}">{{key.Name}}</md-option>
  </md-select>

Designation ID:

  <md-input-container class="md-block">
    <input type="text" ng-model="select.Designation.DesignationId" maxlength="300" tabindex="32" />
  </md-input-container>

I'm trying to display the DepartmentId and DesignationId of a Selected Item, but I can't able to get the Id's. Kindly assist me.

Body:
Two main things needed fixing:

You define $scope.Select = ... in your controller but try to reference it with ng-model="select.Department" in the view. JavaScript/Angular is case-sensitive so Select !== select - make sure to reference variables with the same case.

On the <md-option> elements use ng-value="key" instead of value="{{key}}" when you want to bind an object value to the control. With this fixed you don't need JSON.parse(...) in the onChange handler.

With these two changes here is the updated code:

    <!DOCTYPE html>
    <html>
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.1/angular-material.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-animate.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-aria.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-messages.min.js"></script>

    <!-- Angular Material Library -->
    <script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.1/angular-material.min.js"></script>
    <body ng-app="myApp">

    <div ng-controller="myCtrl">
      <p>Department:</p>
      <md-select ng-model="select.Department" tabindex="9" ng-change="onChange(select.Department)">
        <md-option ng-repeat="key in loadUpData.Department" ng-value="key">{{key.Name}}</md-option>
      </md-select>
      <p>Department ID:</p>
      <md-input-container class="md-block">
        <input type="text" ng-model="select.Department.DepartmentId" maxlength="300" tabindex="32" />
      </md-input-container>
      <br/>
      <p>Designation:</p>
      <md-select ng-model="select.Designation" tabindex="9">
        <md-option ng-repeat="key in designationData" ng-value="key">{{key.Name}}</md-option>
      </md-select>
      <p>Designation ID:</p>
      <md-input-container class="md-block">
        <input type="text" ng-model="select.Designation.DesignationId" maxlength="300" tabindex="32" />
      </md-input-container>
    </div>

    <script>
    var app = angular.module('myApp', ['ngMaterial']);

    app.controller('myCtrl', function($scope) {
      $scope.loadUpData = {
        Department: angular.fromJson("{" +
          "   \"Status\":true," +
          "   \"Message\":\"\"," +
          "   \"Result\":[" +
          "      {" +
          "         \"DepartmentId\":1," +
          "         \"Name\":\"Bala\"," +
          "         \"Designation\":[" +
          "            {" +
          "               \"DesignationId\":1," +
          "               \"DepartmentId\":1," +
          "               \"Name\":\"Software Engg\"" +
          "            }," +
          "            {" +
          "               \"DesignationId\":3," +
          "               \"DepartmentId\":1," +
          "               \"Name\":\"Sr. Human Resouce\"" +
          "            }," +
          "            {" +
          "               \"DesignationId\":2," +
          "               \"DepartmentId\":1," +
          "               \"Name\":\"Sr. Software Engg\"" +
          "            }" +
          "         ]" +
          "      }," +
          "      {" +
          "         \"DepartmentId\":2," +
          "         \"Name\":\"Dev\"," +
          "         \"Designation\":[" +
          "         ]" +
          "      }," +
          "      {" +
          "         \"DepartmentId\":3," +
          "         \"Name\":\"HR Team\"," +
          "         \"Designation\":[" +
          "         ]" +
          "      }," +
          "      {" +
          "         \"DepartmentId\":4," +
          "         \"Name\":\"Sales\"," +
          "         \"Designation\":[" +
          "            {" +
          "               \"DesignationId\":4," +
          "               \"DepartmentId\":4," +
          "               \"Name\":\"Sr. Sales Manager\"" +
          "            }" +
          "         ]" +
          "      }" +
          "   ]" +
          "}").Result
      };

      $scope.select = {
        Department: {},
        Designation: {}
      };

      $scope.onChange = function(selected) {
          var Designation = selected.Designation;
          console.log(Designation);
          $scope.designationData = Designation;
      };

    });
    </script>
    </body>
    </html>


来源: stackexchange

问:
How do you route the path to ManagedService in Atmosphere on Play Framework
I am using the atmosphere-play plugin in Play Framework, together with the basic atmosphere-runtime. See https://github.com/Atmosphere/atmosphere-play

I'm trying to set up a class with the ManagedService annotation, as in the tutorial, but can't figure out how to map the path through the Play router file and haven't been able to find anyone else having done this. The documentation skips this step completely and I just get a 404 error when trying to connect to the server through the atmosphere client script.

Example code:

```<code>@ManagedService(path = "/poll")
public class PostPoller {
  ...
}
</code>```

Client:

```<code>var socket = $.atmosphere;
var subSocket;
var transport = 'websocket';

// We are now ready to cut the request
var request = { url: '/poll',
    contentType : "application/json",
    trackMessageLength : true,
    shared : true,
    transport : transport ,
    fallbackTransport: 'long-polling'};
</code>```

How do I set up the route to the ManagedService in the Play router?

答:
In case anyone else is looking for this, I was able to get it working in Atmosphere-Play 2.3.0 by adding the following to the main Application Controller:

```<code>import static org.atmosphere.play.AtmosphereCoordinator.instance;

public class Application extends Controller {

    @Inject
    public Application(ApplicationLifecycle lifecycle) {

        // replace PostPoller with the ManagedService class you are using
        instance.discover(PostPoller.class).ready();

        lifecycle.addStopHook(() -> {
            instance().shutdown();
            return CompletableFuture.completedFuture(null);
        });

        ...
    }

    ...
}
</code>```

Found the answer at https://github.com/Atmosphere/atmosphere-play/issues/39.

ContentLicense: CC BY-SA 3.0

Body:
I am using the atmosphere-play plugin in Play Framework, together with the basic atmosphere-runtime. See https://github.com/Atmosphere/atmosphere-play

I'm trying to set up a class with the ManagedService annotation, as in the tutorial, but can't figure out how to map the path through the Play router file and haven't been able to find anyone else having done this. The documentation skips this step completely and I just get a 404 error when trying to connect to the server through the atmosphere client script.

Example code:

@ManagedService(path = "/poll")
public class PostPoller {
  ...
}

Client:

var socket = $.atmosphere;
var subSocket;
var transport = 'websocket';

// We are now ready to cut the request
var request = { url: '/poll',
    contentType : "application/json",
    trackMessageLength : true,
    shared : true,
    transport : transport ,
    fallbackTransport: 'long-polling'};

How do I set up the route to the ManagedService in the Play router?

Body:
In case anyone else is looking for this, I was able to get it working in Atmosphere-Play 2.3.0 by adding the following to the main Application Controller:

import static org.atmosphere.play.AtmosphereCoordinator.instance;

public class Application extends Controller {

    @Inject
    public Application(ApplicationLifecycle lifecycle) {

        // replace PostPoller with the ManagedService class you are using
        instance.discover(PostPoller.class).ready();

        lifecycle.addStopHook(() -> {
            instance().shutdown();
            return CompletableFuture.completedFuture(null);
        });

        ...
    }

    ...
}

Found the answer at https://github.com/Atmosphere/atmosphere-play/issues/39.


问:
c++ - 3 bears in a vector of a struct, how can I change this code so the specific bear at the exit is removed?
```<code>    void updateGameData(const char g[][SIZEX], vector<Item>& bears, vector<Item>& bombs, Item& detonator, Item& exit, const int key, string& message, int& bearsSaved, bool& bombsActive, int& moves)
{ //move bear in required direction
    bool isArrowKey(const int k);
    void setKeyDirection(int k, int& dx, int& dy, int& moves);
    void gameLost(string& message);
    assert(isArrowKey(key));

    //reset message to blank
    message = "                                         ";      //reset message to blank

    //calculate direction of movement for given key
    int dx(0), dy(0);
    setKeyDirection(key, dx, dy, moves);
    //save number of bears saved ready to output later for the user

    //check new target position in grid and update game data (incl. bear coordinates) if move is possible
    for (unsigned int bearNo = 0; bearNo < bears.size(); ++bearNo)
    {
        switch (g[bears.at(bearNo).y + dy][bears.at(bearNo).x + dx])
        {           //...depending on what's on the target position in grid...
            case TUNNEL:        //can move
            {
                bears.at(bearNo).y += dy;   //go in that Y direction
                bears.at(bearNo).x += dx;   //go in that X direction
            }
                break;
            case WALL:          //hit a wall and stay there
            {
                cout << '\a';   //beep the alarm
                message = "CANNOT GO THERE!";
            }
                break;
            case BOMB:
            {
                bears.at(bearNo).y += dy;   //go in that Y direction
                bears.at(bearNo).x += dx;
                    //sets the bomb to active, how to pass this through to cheat??
                if (bombsActive)
                {
                    cout << "\a";
                    message = "BOOM!";
                    bears.clear();  // Remove all bears from the vector/end the game
                    if (bears.size() == 0)
                        gameLost(message);
                }
            }
                break;
                // The pop_back function only removes the last item in a (non-empty) vector, causing the size of the vector to decrease automatically.
                // To remove an item knowing its position on the vector the above has been used (bears.begin() + 0 removes the first element)
            case DETONATOR:
            {
                bears.at(bearNo).y += dy;   //go in that Y direction
                bears.at(bearNo).x += dx;   //go in that X direction, means the bear can walk over the detonator and that it reappears afterwards
                cout << "\a";
                message = "BOMBS DISABLED!";
                bombs.clear();
            }
                break;
            case EXIT:
            {
                // Case for the exit symbol on the grid, if a bear walks into it that bear 'escapes' by being removed from the vector, and then the amount of
                // bears saved by the user is increased and incorporated into their high score
                cout << "\a";
                message = "BEAR IS FREE!";
                bears.erase(bears.begin() + ((bears.at(bearNo).y) || (bears.at(bearNo).x))); //I'm assuming it's because of the bears.begin line, but I don't know how to otherwise change it to delete the bear at the y || x coordinate
                bearsSaved++;
            }
                break;
        }
    }
}
</code>```

The case for exit is where I'm having the issue - as soon as a bear reaches the same coordinate at the exit, any bear in particular seems to disappear and another bear, that may be at the other side of the map, is placed at the side of the exit.

```<code>bears.erase(bears.begin() + ((bears.at(bearNo).y) || (bears.at(bearNo).x)));
//I'm assuming it's because of the bears.begin line, but I don't know
//how to otherwise change it to delete the bear at the y || x coordinate
</code>```

For reference I've included some images that better illustrate what I'm talking about. There's other code where the bears are drawn and the grid (the name of my array) are initialised as well, but I don't think they're relevant.

The before image (the @ symbols are the bears, the X is the exit)

The after image, the bear near the T has disappeared, instead of the one in the exit

答:
You are using an iterator type to delete. For proof, see http://en.cppreference.com/w/cpp/container/vector/erase

bears.begin() is an iterator referring to the first bear.

bears.begin() + 1 is an iterator referring to the second bear.

bears.begin() + 2 an iterator referring to is the third ...

Your code is

```<code>bears.erase(bears.begin() + ((bears.at(bearNo).y) || (bears.at(bearNo).x)));
</code>```

so you are deleting either the first or second bear, depending on the result of this expression (something1 || something2). Logical or can only be true or false, which will then be 0 or 1 when you convert it to an int to increment the iterator returned by bears.begin()

Besides the number being wrong, it doesn't make sense. You want to delete a bear from the vector of bears.  Therefore where the bear is on the game board is completely irrelevant.  If you use x or y, it's probably wrong.

If you want to delete the bear at bearNo, you could use

```<code>bears.erase( bears.begin() + bearNo )
</code>```

But that will cause the for loop to be wrong. The next bear moves to bearNo, but you never look at it. The easiest fix is to start at the back and iterate forward. That way, when you change the vector, you don't change anything in the part you have not yet evaluated.  (This will change some of the tricks players can exploit if they know which bear is which -- if you want no change to the code you will have to handle incrementing bearNo inside the for loop based on whether or not you deleted a bear.)

```<code>#include <iostream>
#include <vector>
struct bear_type { int x, y; };
static const int XSIZE = 10;
static const int YSIZE = 10;

int main(){
    char gameboard[XSIZE][YSIZE];
    memset(gameboard, '\0', sizeof(gameboard));
    gameboard[3][3] = 'D';

    std::vector<bear_type> bears = {{ 5, 7 }, { 3, 3 }, { 0, 0 }};

    for (int bearnum = bears.size()-1; bearnum >= 0; --bearnum){
        const bear_type &bear = bears[bearnum];
        char gamepiece = gameboard[bear.x][bear.y];
        if ('D' == gamepiece){
            bears.erase(bears.begin() + bearnum);
        }
    }
}
</code>```

If you used iterator based iteration, there are some other ways to do it, like std::remove_if, but I didn't want to mess with your code too much.

Body:
    void updateGameData(const char g[][SIZEX], vector<Item>& bears, vector<Item>& bombs, Item& detonator, Item& exit, const int key, string& message, int& bearsSaved, bool& bombsActive, int& moves)
{ //move bear in required direction
    bool isArrowKey(const int k);
    void setKeyDirection(int k, int& dx, int& dy, int& moves);
    void gameLost(string& message);
    assert(isArrowKey(key));

    //reset message to blank
    message = "                                         ";      //reset message to blank

    //calculate direction of movement for given key
    int dx(0), dy(0);
    setKeyDirection(key, dx, dy, moves);
    //save number of bears saved ready to output later for the user

    //check new target position in grid and update game data (incl. bear coordinates) if move is possible
    for (unsigned int bearNo = 0; bearNo < bears.size(); ++bearNo)
    {
        switch (g[bears.at(bearNo).y + dy][bears.at(bearNo).x + dx])
        {           //...depending on what's on the target position in grid...
            case TUNNEL:        //can move
            {
                bears.at(bearNo).y += dy;   //go in that Y direction
                bears.at(bearNo).x += dx;   //go in that X direction
            }
                break;
            case WALL:          //hit a wall and stay there
            {
                cout << '\a';   //beep the alarm
                message = "CANNOT GO THERE!";
            }
                break;
            case BOMB:
            {
                bears.at(bearNo).y += dy;   //go in that Y direction
                bears.at(bearNo).x += dx;
                    //sets the bomb to active, how to pass this through to cheat??
                if (bombsActive)
                {
                    cout << "\a";
                    message = "BOOM!";
                    bears.clear();  // Remove all bears from the vector/end the game
                    if (bears.size() == 0)
                        gameLost(message);
                }
            }
                break;
                // The pop_back function only removes the last item in a (non-empty) vector, causing the size of the vector to decrease automatically.
                // To remove an item knowing its position on the vector the above has been used (bears.begin() + 0 removes the first element)
            case DETONATOR:
            {
                bears.at(bearNo).y += dy;   //go in that Y direction
                bears.at(bearNo).x += dx;   //go in that X direction, means the bear can walk over the detonator and that it reappears afterwards
                cout << "\a";
                message = "BOMBS DISABLED!";
                bombs.clear();
            }
                break;
            case EXIT:
            {
                // Case for the exit symbol on the grid, if a bear walks into it that bear 'escapes' by being removed from the vector, and then the amount of
                // bears saved by the user is increased and incorporated into their high score
                cout << "\a";
                message = "BEAR IS FREE!";
                bears.erase(bears.begin() + ((bears.at(bearNo).y) || (bears.at(bearNo).x))); //I'm assuming it's because of the bears.begin line, but I don't know how to otherwise change it to delete the bear at the y || x coordinate
                bearsSaved++;
            }
                break;
        }
    }
}

The case for exit is where I'm having the issue - as soon as a bear reaches the same coordinate at the exit, any bear in particular seems to disappear and another bear, that may be at the other side of the map, is placed at the side of the exit.

bears.erase(bears.begin() + ((bears.at(bearNo).y) || (bears.at(bearNo).x)));
//I'm assuming it's because of the bears.begin line, but I don't know
//how to otherwise change it to delete the bear at the y || x coordinate

For reference I've included some images that better illustrate what I'm talking about. There's other code where the bears are drawn and the grid (the name of my array) are initialised as well, but I don't think they're relevant.

The before image (the @ symbols are the bears, the X is the exit)

The after image, the bear near the T has disappeared, instead of the one in the exit

Body:
You are using an iterator type to delete. For proof, see http://en.cppreference.com/w/cpp/container/vector/erase

bears.begin() is an iterator referring to the first bear.

bears.begin() + 1 is an iterator referring to the second bear.

bears.begin() + 2 an iterator referring to is the third ...

Your code is

bears.erase(bears.begin() + ((bears.at(bearNo).y) || (bears.at(bearNo).x)));

so you are deleting either the first or second bear, depending on the result of this expression (something1 || something2). Logical or can only be true or false, which will then be 0 or 1 when you convert it to an int to increment the iterator returned by bears.begin()

Besides the number being wrong, it doesn't make sense. You want to delete a bear from the vector of bears.  Therefore where the bear is on the game board is completely irrelevant.  If you use x or y, it's probably wrong.

If you want to delete the bear at bearNo, you could use

bears.erase( bears.begin() + bearNo )

But that will cause the for loop to be wrong. The next bear moves to bearNo, but you never look at it. The easiest fix is to start at the back and iterate forward. That way, when you change the vector, you don't change anything in the part you have not yet evaluated.  (This will change some of the tricks players can exploit if they know which bear is which -- if you want no change to the code you will have to handle incrementing bearNo inside the for loop based on whether or not you deleted a bear.)

#include <iostream>
#include <vector>
struct bear_type { int x, y; };
static const int XSIZE = 10;
static const int YSIZE = 10;

int main(){
    char gameboard[XSIZE][YSIZE];
    memset(gameboard, '\0', sizeof(gameboard));
    gameboard[3][3] = 'D';

    std::vector<bear_type> bears = {{ 5, 7 }, { 3, 3 }, { 0, 0 }};

    for (int bearnum = bears.size()-1; bearnum >= 0; --bearnum){
        const bear_type &bear = bears[bearnum];
        char gamepiece = gameboard[bear.x][bear.y];
        if ('D' == gamepiece){
            bears.erase(bears.begin() + bearnum);
        }
    }
}

If you used iterator based iteration, there are some other ways to do it, like std::remove_if, but I didn't want to mess with your code too much.


问:
can't get web response with https
I use this code to get web content but get exception at WebResponse myResponse = myRequest.GetResponse();

```<code>HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("https://www.ecfr.gov");
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate (Object obj, X509Certificate X509certificate, X509Chain chain, System.Net.Security.SslPolicyErrors errors)
{
    return true;
};
myRequest.Method = "GET";
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new System.IO.StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
sr.Close();
myResponse.Close();
</code>```

I know it needs SSL/TLS Certificate, but I want to know why I still get an error?

https://www.ecfr.gov

答:
Try this</p>

```<code>    static void Main(string[] args)
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
        var client = new HttpClient();
        var result = client.GetAsync("https://www.ecfr.gov").Result;
        var str = result.Content.ReadAsStringAsync().Result;
    }
</code>```

Title: can't get web response with https

Body:
I use this code to get web content but get exception at WebResponse myResponse = myRequest.GetResponse();

HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("https://www.ecfr.gov");
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate (Object obj, X509Certificate X509certificate, X509Chain chain, System.Net.Security.SslPolicyErrors errors)
{
    return true;
};
myRequest.Method = "GET";
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new System.IO.StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
sr.Close();
myResponse.Close();

I know it needs SSL/TLS Certificate, but I want to know why I still get an error?

https://www.ecfr.gov

Body:
Try this

    static void Main(string[] args)
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
        var client = new HttpClient();
        var result = client.GetAsync("https://www.ecfr.gov").Result;
        var str = result.Content.ReadAsStringAsync().Result;
    }


问:
Unzip a file with php
I want to unzip a file and this works fine

```<code>system('unzip File.zip');
</code>```

But I need to pass in the file name through the URL and can not get it to work, this is what I have.

```<code>$master = $_GET["master"];
system('unzip $master.zip');
</code>```

What am I missing? I know it has to be something small and stupid I am overlooking.

Thank you,

答:
Use below PHP code, with file name in the URL param "name"</p>

```<code><?php

$fileName = $_GET['name'];

if (isset($fileName)) {

    $zip = new ZipArchive;
    $res = $zip->open($fileName);
    if ($res === TRUE) {
      $zip->extractTo('./');
      $zip->close();
      echo 'Extracted file "'.$fileName.'"';
    } else {
      echo 'Cannot find the file name "'.$fileName.'" (the file name should include extension (.zip, ...))';
    }
}
else {
    echo 'Please set file name in the "name" param';
}

?>
</code>```

Title: Unzip a file with php

Body:
I want to unzip a file and this works fine

system('unzip File.zip');

But I need to pass in the file name through the URL and can not get it to work, this is what I have.

$master = $_GET["master"];
system('unzip $master.zip');

What am I missing? I know it has to be something small and stupid I am overlooking.

Thank you,

Body:
Use below PHP code, with file name in the URL param "name"

<?php

$fileName = $_GET['name'];

if (isset($fileName)) {

    $zip = new ZipArchive;
    $res = $zip->open($fileName);
    if ($res === TRUE) {
      $zip->extractTo('./');
      $zip->close();
      echo 'Extracted file "'.$fileName.'"';
    } else {
      echo 'Cannot find the file name "'.$fileName.'" (the file name should include extension (.zip, ...))';
    }
}
else {
    echo 'Please set file name in the "name" param';
}

?>


问:
Why is this simplest C++0x code not valid?
I encountered a weird problem just now.

The source code is simple and self-evident as follows:

```<code>#include <vector>
#include <iostream>
#include <functional>

using namespace std;
using namespace std::tr1;

template<class T_>
void show_size(T_ coll)
{
    cout << coll.size();
}

int main()
{
    vector<int> coll;
    coll.push_back(1);

    show_size(ref(coll));

    return 0;
}
</code>```

The VC++ 2010 reports:

error C2039: 'size' : is not a member of 'std::tr1::reference_wrapper<_Ty>'

As we know, reference_wrapper can automatically convert itself to its underlying type, here is vector<int>. Why is such simple code not valid?

答:
No it can't that's the whole point of the reference wrapper, because it doesn't decay from the reference, unless explicitly requested using .get()

Edit: don't mix up the boosts reference wrapper with the standard one, the boost one actually has implicit conversion (but the target functionality is a little bit different)

ContentLicense: CC BY-SA 2.5

Body:
I encountered a weird problem just now.

The source code is simple and self-evident as follows:

#include <vector>
#include <iostream>
#include <functional>

using namespace std;
using namespace std::tr1;

template<class T_>
void show_size(T_ coll)
{
    cout << coll.size();
}

int main()
{
    vector<int> coll;
    coll.push_back(1);

    show_size(ref(coll));

    return 0;
}

The VC++ 2010 reports:

error C2039: 'size' : is not a member of 'std::tr1::reference_wrapper<_Ty>'

As we know, reference_wrapper can automatically convert itself to its underlying type, here is vector<int>. Why is such simple code not valid?


问:
How to write a spinning odometer in QT?
Hi I would like to create a spinning odometer in QT.
The result should be like this one:
https://www.shutterstock.com/video/clip-4962995-stock-footage-the-counter-displays-one-million-in-frame.html?src=search/dzZbICGUPQ7RgK0rooSE7A:1:0/gg

Something like the picker in IOS.
Any suggestions?

答:
There are mainly two ways of designing a UI with Qt:

the "older" method is based on Qt Widgets

the current suggested method is via QML/Quick

Have a look at the QML Threading example, in particular at the Spinner component. Looks much like what you need to achieve.

Title: How to write a spinning odometer in QT?


问:
Java - adding value from TextField to object constructor of another class
I am trying to do my first GUI apllication, but not all-in-one-class, but with dividing on different classes. Thats example of one of scenes:

and below, lines of code

```<code>Button backToMainSceneButton = new Button("Return");
backToMainSceneButton.setOnAction(event -> primaryStage.setScene(scene));

Label dodajZwierzeLabel = new Label("Choose type of animal:");
ChoiceBox animalChoiceBox = new ChoiceBox();
animalChoiceBox.getItems().addAll("Dog", "Cat", "Hamster", "Degu");
HBox nameHbox = new HBox(10);
HBox massHbox = new HBox(10);
HBox healthHbox = new HBox(10);

Label nameLabel = new Label("Name: ");
TextField nameTextField = new TextField();
nameHbox.getChildren().addAll(nameLabel, nameTextField);
</code>```

I would like to put name of animal, its mass, and after click on "Add" button below it would create new object 'Animal' with name and mass from textfield. It's simple in one class, but i want to try make more 'proffesional' java app.

I have another class "DatebaseOfAnimals" with arraylist of animals. So how can I implement something like:
 "put name and mass to textfield" -> "click 'add' button"  -> "new object Animal is creating and added to arraylist in another class, with adding name and mass to constructor"  ?

答:
Always aim to post a mcve : </p>

```<code>import java.util.ArrayList;
import java.util.List;

public class Main {

    //i assume that this initialization of DatabaseOfAnimals is
    //done in the GUI class constructor. (remove static modifier)
    static DatabaseOfAnimals db = new DatabaseOfAnimals();

    public static void main(String[] args) {

        addAnimal("Sancho", 8);//this should be executed by Add button
    }

    //remove static modifier
    static void addAnimal(String name, float mass) {

        db.addAnimal(new Animal(name, mass));
    }
}

class Animal{
    Animal(String name, float mass){/*do something*/}
}

class DatabaseOfAnimals{

    List<Animal> list;

    public DatabaseOfAnimals() {
        list = new ArrayList<>();
    }

    void addAnimal(Animal animal) {
        list.add(animal);
    }
}
</code>```

Body:
I am trying to do my first GUI apllication, but not all-in-one-class, but with dividing on different classes. Thats example of one of scenes:

and below, lines of code

Button backToMainSceneButton = new Button("Return");
backToMainSceneButton.setOnAction(event -> primaryStage.setScene(scene));

Label dodajZwierzeLabel = new Label("Choose type of animal:");
ChoiceBox animalChoiceBox = new ChoiceBox();
animalChoiceBox.getItems().addAll("Dog", "Cat", "Hamster", "Degu");
HBox nameHbox = new HBox(10);
HBox massHbox = new HBox(10);
HBox healthHbox = new HBox(10);

Label nameLabel = new Label("Name: ");
TextField nameTextField = new TextField();
nameHbox.getChildren().addAll(nameLabel, nameTextField);

I would like to put name of animal, its mass, and after click on "Add" button below it would create new object 'Animal' with name and mass from textfield. It's simple in one class, but i want to try make more 'proffesional' java app.

I have another class "DatebaseOfAnimals" with arraylist of animals. So how can I implement something like:
 "put name and mass to textfield" -> "click 'add' button"  -> "new object Animal is creating and added to arraylist in another class, with adding name and mass to constructor"  ?

Body:
Always aim to post a mcve :

import java.util.ArrayList;
import java.util.List;

public class Main {

    //i assume that this initialization of DatabaseOfAnimals is
    //done in the GUI class constructor. (remove static modifier)
    static DatabaseOfAnimals db = new DatabaseOfAnimals();

    public static void main(String[] args) {

        addAnimal("Sancho", 8);//this should be executed by Add button
    }

    //remove static modifier
    static void addAnimal(String name, float mass) {

        db.addAnimal(new Animal(name, mass));
    }
}

class Animal{
    Animal(String name, float mass){/*do something*/}
}

class DatabaseOfAnimals{

    List<Animal> list;

    public DatabaseOfAnimals() {
        list = new ArrayList<>();
    }

    void addAnimal(Animal animal) {
        list.add(animal);
    }
}


问:
ASP.NET MVC Validation errors not displaying
I am using tuples to load multiple models into a view.

The view is as

```<code> @using (Ajax.BeginForm(null, null, ajaxOptions, new { @class = "contact-form" }))

        {
           @Html.AntiForgeryToken()
           <div class="form-group form-group--xs">
              @Html.TextBoxFor(m => m.Item2.Email, new { @class = "form-control input-sm", placeholder = "Your email address..." })
              @Html.ValidationMessageFor(m => m.Item2.Email)
           </div>
           <div class="form-group form-group--xs">
              @Html.TextAreaFor(m => m.Item2.Message, new { @class = "form-control input-sm", placeholder = "Your message...", rows = "4" })
              @Html.ValidationMessageFor(m => m.Item2.Message)
           </div>

           <input type="submit" class="btn btn-primary-inverse btn-sm btn-block" value="Send Your Message" />
        }
</code>```

The controller is

```<code>        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<PartialViewResult> Submit([Bind(Prefix = "Item2")] ContactForm model)
        {
            bool isMessageSent = true;

            if (ModelState.IsValid)
            {
                try
                {
                    await Services.EmailService.SendContactForm(model);
                }
                catch (Exception ex)
                {
                    isMessageSent = false;
                }
            }
            else
            {
                isMessageSent = false;
            }
            return PartialView("_SubmitMessage", isMessageSent);
        }
</code>```

and the contact form is

```<code> public class ContactForm
    {
        [Required(ErrorMessage = "You must provide your email."), EmailAddress]
        public string Email { get; set; }

        [Required(ErrorMessage = "You must include a message.")]
        public string Message { get; set; }
    }
</code>```

Finally the partial view is

```<code>@model bool

@if (Model)
{
    <div style="color:#c2ff1f">Your message has been sent.</div>
}
else
{
    <div style="color:#f34141">An error occured while sending your message</div>
}
</code>```

Update: The rendered html for the email textbox is

```<code><input class="form-control input-sm"
data-val="true"
data-val-email="The Email field is not a valid e-mail address."
data-val-required="You must provide your email."
id="Item2_Email"
name="Item2.Email"
placeholder="Your email address..."
type="text"
value="">
</code>```

If i do not enter any text in the email field or the message field, the message is not sent :) but i have no validation errors in the view :(
What am i doing wrong here?

答:
I guess i need a break. I was missing</p>

```<code>@Scripts.Render("~/bundles/jqueryval")
</code>```

Body:
I am using tuples to load multiple models into a view.

The view is as

 @using (Ajax.BeginForm(null, null, ajaxOptions, new { @class = "contact-form" }))

        {
           @Html.AntiForgeryToken()

              @Html.TextBoxFor(m => m.Item2.Email, new { @class = "form-control input-sm", placeholder = "Your email address..." })
              @Html.ValidationMessageFor(m => m.Item2.Email)

              @Html.TextAreaFor(m => m.Item2.Message, new { @class = "form-control input-sm", placeholder = "Your message...", rows = "4" })
              @Html.ValidationMessageFor(m => m.Item2.Message)

           <input type="submit" class="btn btn-primary-inverse btn-sm btn-block" value="Send Your Message" />
        }

The controller is

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<PartialViewResult> Submit([Bind(Prefix = "Item2")] ContactForm model)
        {
            bool isMessageSent = true;

            if (ModelState.IsValid)
            {
                try
                {
                    await Services.EmailService.SendContactForm(model);
                }
                catch (Exception ex)
                {
                    isMessageSent = false;
                }
            }
            else
            {
                isMessageSent = false;
            }
            return PartialView("_SubmitMessage", isMessageSent);
        }

and the contact form is

 public class ContactForm
    {
        [Required(ErrorMessage = "You must provide your email."), EmailAddress]
        public string Email { get; set; }

        [Required(ErrorMessage = "You must include a message.")]
        public string Message { get; set; }
    }

Finally the partial view is

@model bool

@if (Model)
{

Your message has been sent.

}
else
{

An error occured while sending your message

}

Update: The rendered html for the email textbox is

<input class="form-control input-sm"
data-val="true"
data-val-email="The Email field is not a valid e-mail address."
data-val-required="You must provide your email."
id="Item2_Email"
name="Item2.Email"
placeholder="Your email address..."
type="text"
value="">

If i do not enter any text in the email field or the message field, the message is not sent :) but i have no validation errors in the view :(
What am i doing wrong here?

Body:
I guess i need a break. I was missing

@Scripts.Render("~/bundles/jqueryval")


问:
How to display multiple DropDownLists and get values in ASP.Net MVC
I'm looking for a simple way of creating dropdownlists through loop, and then store the values in the model.

View Model:

```<code>public class PreferencesShoppingCartViewModel
            {
                public List<CartItemPreference> CartItemPreferences{get;set;}

                public class CartItemPreference{
                      public string Selected{get;set;}
                      public CartItem CartItem {get;set;}
                }
            }

@model MVC_COMP1562.ViewModels.PreferencesShoppingCartViewModel
</code>```

View:

```<code>@model MVC_COMP1562.ViewModels.PreferencesShoppingCartViewModel

@foreach (var cartItem in Model.CartItemPreferences)
{
    @Html.DropDownListFor(m => cartItem.Selected, Model.PreferenceOptions)

}
</code>```

The ID for each dropdown is the same.

So I'm creating the the div btn-group for each item in cartItemPreferences but now how could I assign value selected to the proper CartItemPreference in Model?

答:
You need to use for loop instead of foreach, so that each dropdownlist has unique id.

```<code><form action="/" method="post">
   <select id="CartItemPreferences_0__Selected" name="CartItemPreferences[0].Selected">
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
   </select>
   <select id="CartItemPreferences_1__Selected" name="CartItemPreferences[1].Selected">
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
   </select>
   <input type="submit" value="Submit"/>
</form>
</code>```

Model

```<code>public class PreferencesShoppingCartViewModel
{
    public List<CartItemPreference> CartItemPreferences { get; set; }

    public List<SelectListItem> PreferenceOptions { get; set; }

    public PreferencesShoppingCartViewModel()
    {
        CartItemPreferences = new List<CartItemPreference>();
        PreferenceOptions = new List<SelectListItem>();
    }
}

public class CartItemPreference
{
    public string Selected { get; set; }
    public CartItem CartItem { get; set; }
}

public class CartItem
{
    public string Sample { get; set; }
}
</code>```

View

```<code>@model DemoMvc5.Models.PreferencesShoppingCartViewModel
@{
    ViewBag.Title = "Home Page";
}

@using (Html.BeginForm("Index", "Home"))
{
    for (int i = 0, length = Model.CartItemPreferences.Count; i < length; i++)
    {
        @Html.DropDownListFor(m => Model.CartItemPreferences[i].Selected, Model.PreferenceOptions)
    }
    <input type="submit" value="Submit"/>
}
</code>```

Controller

```<code>public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new PreferencesShoppingCartViewModel
        {
            CartItemPreferences = new List<CartItemPreference>
            {
                new CartItemPreference { CartItem = new CartItem { Sample = "Sample 1"}},
                new CartItemPreference { CartItem = new CartItem { Sample = "Sample 2"}}
            },
            PreferenceOptions = new List<SelectListItem>
            {
                new SelectListItem {Text = "Option 1", Value = "1"},
                new SelectListItem {Text = "Option 2", Value = "2"},
                new SelectListItem {Text = "Option 3", Value = "3"}
            }
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(PreferencesShoppingCartViewModel model)
    {
        // Do something

        return View(model);
    }
}
</code>```

Screen Shots

Body:
I'm looking for a simple way of creating dropdownlists through loop, and then store the values in the model.

View Model:

public class PreferencesShoppingCartViewModel
            {
                public List<CartItemPreference> CartItemPreferences{get;set;}

                public class CartItemPreference{
                      public string Selected{get;set;}
                      public CartItem CartItem {get;set;}
                }
            }

@model MVC_COMP1562.ViewModels.PreferencesShoppingCartViewModel

View:

@model MVC_COMP1562.ViewModels.PreferencesShoppingCartViewModel

@foreach (var cartItem in Model.CartItemPreferences)
{
    @Html.DropDownListFor(m => cartItem.Selected, Model.PreferenceOptions)

}

The ID for each dropdown is the same.

So I'm creating the the div btn-group for each item in cartItemPreferences but now how could I assign value selected to the proper CartItemPreference in Model?

Body:
You need to use for loop instead of foreach, so that each dropdownlist has unique id.

<form action="/" method="post">
   <select id="CartItemPreferences_0__Selected" name="CartItemPreferences[0].Selected">
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
   </select>
   <select id="CartItemPreferences_1__Selected" name="CartItemPreferences[1].Selected">
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
   </select>
   <input type="submit" value="Submit"/>
</form>

Model

public class PreferencesShoppingCartViewModel
{
    public List<CartItemPreference> CartItemPreferences { get; set; }

    public List<SelectListItem> PreferenceOptions { get; set; }

    public PreferencesShoppingCartViewModel()
    {
        CartItemPreferences = new List<CartItemPreference>();
        PreferenceOptions = new List<SelectListItem>();
    }
}

public class CartItemPreference
{
    public string Selected { get; set; }
    public CartItem CartItem { get; set; }
}

public class CartItem
{
    public string Sample { get; set; }
}

View

@model DemoMvc5.Models.PreferencesShoppingCartViewModel
@{
    ViewBag.Title = "Home Page";
}

@using (Html.BeginForm("Index", "Home"))
{
    for (int i = 0, length = Model.CartItemPreferences.Count; i < length; i++)
    {
        @Html.DropDownListFor(m => Model.CartItemPreferences[i].Selected, Model.PreferenceOptions)
    }
    <input type="submit" value="Submit"/>
}

Controller

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new PreferencesShoppingCartViewModel
        {
            CartItemPreferences = new List<CartItemPreference>
            {
                new CartItemPreference { CartItem = new CartItem { Sample = "Sample 1"}},
                new CartItemPreference { CartItem = new CartItem { Sample = "Sample 2"}}
            },
            PreferenceOptions = new List<SelectListItem>
            {
                new SelectListItem {Text = "Option 1", Value = "1"},
                new SelectListItem {Text = "Option 2", Value = "2"},
                new SelectListItem {Text = "Option 3", Value = "3"}
            }
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(PreferencesShoppingCartViewModel model)
    {
        // Do something

        return View(model);
    }
}

Screen Shots


问:
UICollectionView custom button actions in Swift 3
I have used UICollectionView and I am populating it with results from API. There is a ID, Image, Name, Description and Liked true or false coming in API.
I have implemented all these things and now all the results loads inside this collection view.

```<code>    extension VCResCourses : UICollectionViewDelegate {

}

extension VCResCourses: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        let length = (UIScreen.main.bounds.width - 16)
        return CGSize(width: length, height: 135);
    }
}

extension VCResCourses : UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSources.numbeOfRowsInEachGroup(section)
    }

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let currentCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier,for:indexPath) as! CVCResCourse

    let doCourses: [DOCourses] = dataSources.total()
    let doCourse = doCourses[indexPath.row]

    let courseId = doCourse.Id!
    var courseName = doCourse.Name!
    let courseAddress = doCourse.Address!
    let courseImage = doCourse.Image!
    let courseWish = doCourse.Wish!

    courseName = courseName.replacingOccurrences(of: "\t", with: "", options: .literal, range: nil)

    currentCell.imageView.kf.setImage(with: URL(string: courseImage))
    currentCell.textPrimary.text = courseName.capitalized
    currentCell.textSecondary.text = courseAddress.capitalized
    currentCell.buttonOpen.addTarget(...)
    currentCell.buttonFav.addTarget(...)

    return currentCell
    }
}
</code>```

What I am trying now is there are two button on each CELL one opens details of the record and other set favourite to true or false.

Now I need to get id of the current record and toggle its favourite state to true or false or open the detail page using the id. I am not able to add action for buttons and perform the favourite or open detail action using ID.

In android I have done this by adding clickListener inside CustomBaseAdapter which perform actions for each row or record of the data. I need to do the same in iOS as well but no luck yet

I am new to iOS development please help

答:
you need to set tag for each button for e,g

```<code>currentCell.buttonOpen.tag = indexPath.row
currentCell.buttonFav.tag = indexPath.row
currentCell.buttonOpen.addTarget(self, action: #selector(self.buttonClicked), for: .touchUpInside)
</code>```

and you can get id via button.tag, for e.g

```<code>func buttonClicked(_ sender: UIButton) {
  let doCourses: [DOCourses] = dataSources.total()
  let doCourse = doCourses[sender.tag]
 let courseId = doCourse.Id!
  print (courseId)
}
</code>```

Body:
I have used UICollectionView and I am populating it with results from API. There is a ID, Image, Name, Description and Liked true or false coming in API.
I have implemented all these things and now all the results loads inside this collection view.

    extension VCResCourses : UICollectionViewDelegate {

}

extension VCResCourses: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        let length = (UIScreen.main.bounds.width - 16)
        return CGSize(width: length, height: 135);
    }
}

extension VCResCourses : UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSources.numbeOfRowsInEachGroup(section)
    }

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let currentCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier,for:indexPath) as! CVCResCourse

    let doCourses: [DOCourses] = dataSources.total()
    let doCourse = doCourses[indexPath.row]

    let courseId = doCourse.Id!
    var courseName = doCourse.Name!
    let courseAddress = doCourse.Address!
    let courseImage = doCourse.Image!
    let courseWish = doCourse.Wish!

    courseName = courseName.replacingOccurrences(of: "\t", with: "", options: .literal, range: nil)

    currentCell.imageView.kf.setImage(with: URL(string: courseImage))
    currentCell.textPrimary.text = courseName.capitalized
    currentCell.textSecondary.text = courseAddress.capitalized
    currentCell.buttonOpen.addTarget(...)
    currentCell.buttonFav.addTarget(...)

    return currentCell
    }
}

What I am trying now is there are two button on each CELL one opens details of the record and other set favourite to true or false.

Now I need to get id of the current record and toggle its favourite state to true or false or open the detail page using the id. I am not able to add action for buttons and perform the favourite or open detail action using ID.

In android I have done this by adding clickListener inside CustomBaseAdapter which perform actions for each row or record of the data. I need to do the same in iOS as well but no luck yet

I am new to iOS development please help

Body:
you need to set tag for each button for e,g

currentCell.buttonOpen.tag = indexPath.row
currentCell.buttonFav.tag = indexPath.row
currentCell.buttonOpen.addTarget(self, action: #selector(self.buttonClicked), for: .touchUpInside)

and you can get id via button.tag, for e.g

func buttonClicked(_ sender: UIButton) {
  let doCourses: [DOCourses] = dataSources.total()
  let doCourse = doCourses[sender.tag]
 let courseId = doCourse.Id!
  print (courseId)
}


问:
How to auto complete mysql database with php?
how do I automatically fill the mysql database query with php code?

database as follows:

```<code>CREATE TABLE IF NOT EXISTS `scrore_table` (
  `scores_id` int(11) NOT NULL auto_increment,
  `scores_title` varchar(32) collate utf8_bin NOT NULL default '',
  `scores` varchar(15) collate utf8_bin NOT NULL default '',
  `decimal_place` char(1) collate utf8_bin NOT NULL,
  `value` float(15,8) NOT NULL,
  PRIMARY KEY  (`currency_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1; ;

INSERT INTO `scrore_table` (`scrore_id`, `scrore_title`, `scores`, `decimal_place`, `value`) VALUES
(1, '', 'GameA0', '',),
(2, '', 'GameA1', '',),
(3, '', 'GameA2', '',),
..............................etc
(15, '', 'GameA15', '',);
</code>```

become the benchmark (key word) are: scores, so

```<code>IF found

scores = GameA0

then insert

scores_title = Game For Player A0
decimal_place = 2
value = 1.58030000

IF found

scores = GameA1

then insert

scores_title = Game For Player A1
decimal_place = 2
value = 158.030000

IF found

scores = GameA15

then insert

scores_title = Game For Player A15
decimal_place = 2
value = 0.31303000
</code>```

etc...

Any suggestions and pointer to help me I appreciate and many thanks

答:
Some tutorials You can download from http://dev.mysql.com/doc/

This example:

```<code>if($scores == 'GameA0')
{
$scores_title = 'Game For Player A0';
$value = 1.58030000;
}
elseif($scores == 'Game15')
{
$scores_title = 'Gone ...';
$value = 0.31303000;
}
</code>```

and the table:

```<code>mysql_query("UPDATE score_table SET score_title=".$score_title.", value=".$value." where scores=".$scores."";
</code>```

Body:
how do I automatically fill the mysql database query with php code?

database as follows:

CREATE TABLE IF NOT EXISTS `scrore_table` (
  `scores_id` int(11) NOT NULL auto_increment,
  `scores_title` varchar(32) collate utf8_bin NOT NULL default '',
  `scores` varchar(15) collate utf8_bin NOT NULL default '',
  `decimal_place` char(1) collate utf8_bin NOT NULL,
  `value` float(15,8) NOT NULL,
  PRIMARY KEY  (`currency_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1; ;

INSERT INTO `scrore_table` (`scrore_id`, `scrore_title`, `scores`, `decimal_place`, `value`) VALUES
(1, '', 'GameA0', '',),
(2, '', 'GameA1', '',),
(3, '', 'GameA2', '',),
..............................etc
(15, '', 'GameA15', '',);

become the benchmark (key word) are: scores, so

IF found

scores = GameA0

then insert

scores_title = Game For Player A0
decimal_place = 2
value = 1.58030000

IF found

scores = GameA1

then insert

scores_title = Game For Player A1
decimal_place = 2
value = 158.030000

IF found

scores = GameA15

then insert

scores_title = Game For Player A15
decimal_place = 2
value = 0.31303000

etc...

Any suggestions and pointer to help me I appreciate and many thanks

Body:
Some tutorials You can download from http://dev.mysql.com/doc/

This example:

if($scores == 'GameA0')
{
$scores_title = 'Game For Player A0';
$value = 1.58030000;
}
elseif($scores == 'Game15')
{
$scores_title = 'Gone ...';
$value = 0.31303000;
}

and the table:

mysql_query("UPDATE score_table SET score_title=".$score_title.", value=".$value." where scores=".$scores."";


问:
How to positioning divs float left but also to top

How to make Divs inside div float left with no spaces; As you can see on the image have spaces, i am using these codes;

```<code>main {position:relative;left:339.5px;top:40px;width:1018px;height:1000px;-webkit-box-shadow:inset 0px 0px 40px;}

main div {float:left;margin:1px;-webkit-box-shadow:inset 0px 0px 20px;}
#div_size1 {width:336px;height:200px;}
#div_size2 {width:336px;height:300px;}
#div_size3 {width:336px;height:100px;}

<main>
<div id="div_size1">
</div>
<div id="div_size2">
</div>
<div id="div_size3">
</div>
<div id="div_size3">
</div>
<div id="div_size3">
</div>
<div id="div_size2">
</div>
<div id="div_size2">
</div>
<div id="div_size1">
</div>
<div id="div_size2">
</div>
<div id="div_size3">
</div>
<div id="div_size3">
</div>
</main>
</code>```

答:
If you change the position to absolute you can change its distance from the top and sides:

```<code>main div {
  margin:1px;
  -webkit-box-shadow:inset 0px 0px 20px;

  position:absolute;
  left: 0px;
  top: 0px;
}
</code>```

Hope this helps

Body:
How to make Divs inside div float left with no spaces; As you can see on the image have spaces, i am using these codes;

main {position:relative;left:339.5px;top:40px;width:1018px;height:1000px;-webkit-box-shadow:inset 0px 0px 40px;}

main div {float:left;margin:1px;-webkit-box-shadow:inset 0px 0px 20px;}
#div_size1 {width:336px;height:200px;}
#div_size2 {width:336px;height:300px;}
#div_size3 {width:336px;height:100px;}

Body:
If you change the position to absolute you can change its distance from the top and sides:

main div {
  margin:1px;
  -webkit-box-shadow:inset 0px 0px 20px;

  position:absolute;
  left: 0px;
  top: 0px;
}

Hope this helps


问:
BitmapDescriptorFactory.fromPath images not showing on map
I am trying to put my markers on google map. But although I debug(everythings looking fine), my markers not showing on map. Can you help me what is the problem?

```<code>                                             String imageInSD = Config.APP_IMAGES_URL + sh.cover_image_file;[enter image description here][1]

                                                                customMarker = googleMap.addMarker(new MarkerOptions()
                                                                        .position(markerLatLng)
                                                                        .title(sh.name)
                                                                        .snippet(sh.description.substring(0, Math.min(sh.description.length(), 80)) + "...")
                                                                        .icon(BitmapDescriptorFactory.fromPath(imageInSD)) // in debug looking www.asd.com/abc.jpg(right paths)
                                                                        .anchor(0.5f, 1));
</code>```

I tried also this

.icon(BitmapDescriptorFactory.FromFile(imageInSD))

but not working? Where is problem
Looking right path in debug. Added screenshot. But in application map is null

答:
Here is an example of a class that can be used to download from a website and convert to something that gmaps APIs can display.  I lifted this from a project I am working on and pulled out the not applicable stuff - did not try to compile it, but it should be close.

```<code>class DownloadWebpageAsynch  extends AsyncTask<String, Void, Integer>
{
    private String fileName;
    private final String TAG = "DownloadWebpageAsynch";

    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(Integer result)
    {
        // Perforrm any work here on the UI thread
    // in your case, create the bitmap for the google map

    BitmapDescriptor bd = BitmapDescriptorFactory.fromPath(fileName);

    // use bd in google map calls as the bitmap to add to the map
    }

    protected void DownloadComplete(BufferedInputStream inStream)
    {
    // Perform work here upon download complete on the background thread
        // inStream is what was returned by the web server

    // Safe file to temp storage
    try
    {
        File tempFile = File.createTempFile("1", ".jpg");
        tempFile.deleteOnExit();
        fileName = tempFile.toString();
        FileOutputStream fos = new FileOutputStream(tempFile);
        byte[] readyBytes = new byte[1000];
        int numRead = inStream.read(readyBytes, 0, 999);
        while(numRead != -1)
        {
        fos.write(readyBytes, 0, numRead);
        numRead = inStream.read(readyBytes, 0, 999);
        }
        fos.close();
    } catch (IOException e)
    {
        e.printStackTrace();
    }
    }

    @Override
    protected Integer doInBackground(String... urls)
    {
        // params comes from the execute() call: params[0] is the url.
        try
        {
        downloadUrl(urls[0]);
        }
        catch (IOException e)
        {
            Log.d(TAG, "Failed with exception " + e.toString());
        }
        return 0;
    }

    // Given a URL, establishes an HttpUrlConnection and retrieves
    // the web page content as a InputStream, which it returns as
    // a string.
    private void downloadUrl(String myurl) throws IOException
    {
        BufferedInputStream is = null;
        downloadFailed = false;

        try
        {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000); // 10 second timeout
            conn.setConnectTimeout(10000); // 10 second timeout
            conn.setDoInput(true);
            // Starts the query
            conn.connect();
            responseCode = conn.getResponseCode();
            if(responseCode != 200)
            {
                Log.d(TAG, "Download Failed");
            }
            else
            {
          DownloadComplete(new BufferedInputStream(conn.getInputStream());
            }
            conn.disconnect();
        }
        catch (SocketTimeoutException e)
        {
      Log.d(TAG, "Failed with exception " + e.toString());
        }
        finally
        {
            if (is != null)
            {
                is.close();
            }
        }
    }// private String downloadUrl(String myurl) throws IOException
</code>```

Hope this helps.

Body:
I am trying to put my markers on google map. But although I debug(everythings looking fine), my markers not showing on map. Can you help me what is the problem?

                                             String imageInSD = Config.APP_IMAGES_URL + sh.cover_image_file;[enter image description here][1]

                                                                customMarker = googleMap.addMarker(new MarkerOptions()
                                                                        .position(markerLatLng)
                                                                        .title(sh.name)
                                                                        .snippet(sh.description.substring(0, Math.min(sh.description.length(), 80)) + "...")
                                                                        .icon(BitmapDescriptorFactory.fromPath(imageInSD)) // in debug looking www.asd.com/abc.jpg(right paths)
                                                                        .anchor(0.5f, 1));

I tried also this

.icon(BitmapDescriptorFactory.FromFile(imageInSD))

but not working? Where is problem
Looking right path in debug. Added screenshot. But in application map is null

Body:
Here is an example of a class that can be used to download from a website and convert to something that gmaps APIs can display.  I lifted this from a project I am working on and pulled out the not applicable stuff - did not try to compile it, but it should be close.

class DownloadWebpageAsynch  extends AsyncTask<String, Void, Integer>
{
    private String fileName;
    private final String TAG = "DownloadWebpageAsynch";

    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(Integer result)
    {
        // Perforrm any work here on the UI thread
    // in your case, create the bitmap for the google map

    BitmapDescriptor bd = BitmapDescriptorFactory.fromPath(fileName);

    // use bd in google map calls as the bitmap to add to the map
    }

    protected void DownloadComplete(BufferedInputStream inStream)
    {
    // Perform work here upon download complete on the background thread
        // inStream is what was returned by the web server

    // Safe file to temp storage
    try
    {
        File tempFile = File.createTempFile("1", ".jpg");
        tempFile.deleteOnExit();
        fileName = tempFile.toString();
        FileOutputStream fos = new FileOutputStream(tempFile);
        byte[] readyBytes = new byte[1000];
        int numRead = inStream.read(readyBytes, 0, 999);
        while(numRead != -1)
        {
        fos.write(readyBytes, 0, numRead);
        numRead = inStream.read(readyBytes, 0, 999);
        }
        fos.close();
    } catch (IOException e)
    {
        e.printStackTrace();
    }
    }

    @Override
    protected Integer doInBackground(String... urls)
    {
        // params comes from the execute() call: params[0] is the url.
        try
        {
        downloadUrl(urls[0]);
        }
        catch (IOException e)
        {
            Log.d(TAG, "Failed with exception " + e.toString());
        }
        return 0;
    }

    // Given a URL, establishes an HttpUrlConnection and retrieves
    // the web page content as a InputStream, which it returns as
    // a string.
    private void downloadUrl(String myurl) throws IOException
    {
        BufferedInputStream is = null;
        downloadFailed = false;

        try
        {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000); // 10 second timeout
            conn.setConnectTimeout(10000); // 10 second timeout
            conn.setDoInput(true);
            // Starts the query
            conn.connect();
            responseCode = conn.getResponseCode();
            if(responseCode != 200)
            {
                Log.d(TAG, "Download Failed");
            }
            else
            {
          DownloadComplete(new BufferedInputStream(conn.getInputStream());
            }
            conn.disconnect();
        }
        catch (SocketTimeoutException e)
        {
      Log.d(TAG, "Failed with exception " + e.toString());
        }
        finally
        {
            if (is != null)
            {
                is.close();
            }
        }
    }// private String downloadUrl(String myurl) throws IOException

Hope this helps.


问:
word_tokenize in nltk not taking a list of string as argument
```<code>from nltk.tokenize import word_tokenize

music_comments = [['So cant you just run the bot outside of the US? ', ''], ["Just because it's illegal doesn't mean it will stop. I hope it actually gets enforced. ", ''], ['Can they do something about all the fucking bots on Tinder next?   \n\nEdit: Holy crap my inbox just blew up ', '']]

print(word_tokenize(music_comments[1]))
</code>```

I found this other question which says to pass a list of strings to word_tokenize, but in my case after running the above I get the following output:

```<code>Traceback (most recent call last):
  File "testing.py", line 5, in <module>
    print(word_tokenize(music_comments[1]))
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\__init__.py", line 109, in word_tokenize
    return [token for sent in sent_tokenize(text, language)
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\__init__.py", line 94, in sent_tokenize
    return tokenizer.tokenize(text)
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1237, in tokenize
    return list(self.sentences_from_text(text, realign_boundaries))
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1285, in sentences_from_text
    return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)]
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1276, in span_tokenize
    return [(sl.start, sl.stop) for sl in slices]
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1276, in <listcomp>
    return [(sl.start, sl.stop) for sl in slices]
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1316, in _realign_boundaries
    for sl1, sl2 in _pair_iter(slices):
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 310, in _pair_iter
    prev = next(it)
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1289, in _slices_from_text
    for match in self._lang_vars.period_context_re().finditer(text):
TypeError: expected string or bytes-like object
</code>```

What is the problem? What am I missing?

答:
```<code>def word_tokenize(self, s):
    """Tokenize a string to split off punctuation other than periods"""
    return self._word_tokenizer_re().findall(s)
</code>```

this is part of the 'Source code for nltk.tokenize.punkt'.

The input of function word_tokenize() should be a string,not a list.

Body:
from nltk.tokenize import word_tokenize

music_comments = [['So cant you just run the bot outside of the US? ', ''], ["Just because it's illegal doesn't mean it will stop. I hope it actually gets enforced. ", ''], ['Can they do something about all the fucking bots on Tinder next?   \n\nEdit: Holy crap my inbox just blew up ', '']]

print(word_tokenize(music_comments[1]))

I found this other question which says to pass a list of strings to word_tokenize, but in my case after running the above I get the following output:

Traceback (most recent call last):
  File "testing.py", line 5, in <module>
    print(word_tokenize(music_comments[1]))
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\__init__.py", line 109, in word_tokenize
    return [token for sent in sent_tokenize(text, language)
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\__init__.py", line 94, in sent_tokenize
    return tokenizer.tokenize(text)
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1237, in tokenize
    return list(self.sentences_from_text(text, realign_boundaries))
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1285, in sentences_from_text
    return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)]
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1276, in span_tokenize
    return [(sl.start, sl.stop) for sl in slices]
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1276, in <listcomp>
    return [(sl.start, sl.stop) for sl in slices]
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1316, in _realign_boundaries
    for sl1, sl2 in _pair_iter(slices):
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 310, in _pair_iter
    prev = next(it)
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1289, in _slices_from_text
    for match in self._lang_vars.period_context_re().finditer(text):
TypeError: expected string or bytes-like object

What is the problem? What am I missing?

Body:
def word_tokenize(self, s):
    """Tokenize a string to split off punctuation other than periods"""
    return self._word_tokenizer_re().findall(s)

this is part of the 'Source code for nltk.tokenize.punkt'.

The input of function word_tokenize() should be a string,not a list.


问:
Are there environment variables which are reliable always set?
Are there environment variables which are reliable always set?</p>

答:
In Bash, the following variables are read-only and should always be available in the shell:

```<code>BASH_VERSINFO
EUID
SHELLOPTS
SHLVL
UID
</code>```

They will even be set in Bash scripts that are run by:

```<code>env - scriptname
</code>```

since Bash sets them when it starts the script, not from the parent environment.

This variable is read-only, but it's not set by default. You can set it by performing a regex match.

```<code>BASH_REMATCH
</code>```

If you want it to equal "foo", just do:

```<code>[[ foo =~ .* ]]
</code>```

Body:
In Bash, the following variables are read-only and should always be available in the shell:

BASH_VERSINFO
EUID
SHELLOPTS
SHLVL
UID

They will even be set in Bash scripts that are run by:

env - scriptname

since Bash sets them when it starts the script, not from the parent environment.

This variable is read-only, but it's not set by default. You can set it by performing a regex match.

BASH_REMATCH

If you want it to equal "foo", just do:

[[ foo =~ .* ]]


问:
How to format MySQL timestamp using jquery
I read timestamp from MySQL db (is type timestamp).

Like this: 2017-04-01 15:34:31

I want to format this date using jquery and set up to some span element.

I am new in jquery and I don't know how to do it.

Thank you.

答:
Try the DATE_FORMAT(date,format) function in MySQL. Something like:

```<code>DATE_FORMAT(NOW(),'%m-%d-%Y')
</code>```

would give you 04-01-2017. Then wrap that in a .

If you are using PHP then

```<code>strftime('%m-%d-%Y',$timestamp);
</code>```

is an alternative. there are plenty of examples in Stack Overflow; Google will get you there.

Body:
Try the DATE_FORMAT(date,format) function in MySQL. Something like:

DATE_FORMAT(NOW(),'%m-%d-%Y')

would give you 04-01-2017. Then wrap that in a <span>.

If you are using PHP then

strftime('%m-%d-%Y',$timestamp);

is an alternative. there are plenty of examples in Stack Overflow; Google will get you there.


问:
use string format() to format a number
I need to format a series of float to show comma delimitation every 3 digits:

```<code>1234567.89123
</code>```

should become

```<code>1,234,567.89123
</code>```

without using:

```<code>locale.setlocale(locale.LC_ALL, 'en_US.utf8')
</code>```

I could convert the float to string and insert commas every three digits starting from left of the decimal dot...
Is there a nicer way?

答:
Refer to this for more information on how to format

```<code>s = pd.Series([12345678.9876] * 3)

s.apply('{:,}'.format)

0    12,345,678.9876
1    12,345,678.9876
2    12,345,678.9876
dtype: object
</code>```

pandas also allows you to set options temporarily with pd.option_context

```<code>with pd.option_context('display.float_format', '{:,}'.format):
    print(s)

0   12,345,678.9876
1   12,345,678.9876
2   12,345,678.9876
dtype: float64
</code>```

Title: use string format() to format a number

Body:
I need to format a series of float to show comma delimitation every 3 digits:

1234567.89123

should become

1,234,567.89123

without using:

locale.setlocale(locale.LC_ALL, 'en_US.utf8')

I could convert the float to string and insert commas every three digits starting from left of the decimal dot...
Is there a nicer way?

Body:
Refer to this for more information on how to format

s = pd.Series([12345678.9876] * 3)

s.apply('{:,}'.format)

0    12,345,678.9876
1    12,345,678.9876
2    12,345,678.9876
dtype: object

pandas also allows you to set options temporarily with pd.option_context

with pd.option_context('display.float_format', '{:,}'.format):
    print(s)

0   12,345,678.9876
1   12,345,678.9876
2   12,345,678.9876
dtype: float64


问:
locationManager Delegate not working
I have included NSLocationWhenInUsageDescription and NSLocationAlwaysUsageDescription in my info.plst file and my code is like this.

```<code>import UIKit
import MapKit

class LocationSelectorViewController: UIViewController,
UISearchBarDelegate, MKMapViewDelegate {

@IBOutlet weak var locationSearchBar: UISearchBar!
@IBOutlet weak var mapView: MKMapView!
var selectedLoc: String?
let locationManager = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()
    locationManager.requestAlwaysAuthorization()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    locationManager.startUpdatingLocation()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func locationManager(manager: CLLocationManager, didupdateLocations locations: [CLLocation]) {

}

func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {

}

func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {

}
}
</code>```

I think I have nothing wrong but it is keep showing this error

Cannot Assign value of type "LocationSelectorViewController" to type "CLLocationManagerDelegate?"

Can you tell me where is the Problem?

答:
Cannot Assign value of type "LocationSelectorViewController" to type "CLLocationManagerDelegate?"

Ans :
Your LocationSelectorViewController class must adopt and conform toCLLocationManagerDelegate protocol.

Add the CLLocationManagerDelegate in your class as shown below.

```<code>class LocationSelectorViewController: UIViewController,
UISearchBarDelegate, MKMapViewDelegate, CLLocationManagerDelegate {
</code>```

instead of

```<code> class LocationSelectorViewController: UIViewController,
UISearchBarDelegate, MKMapViewDelegate {
</code>```

Title: locationManager Delegate not working

Body:
I have included NSLocationWhenInUsageDescription and NSLocationAlwaysUsageDescription in my info.plst file and my code is like this.

import UIKit
import MapKit

class LocationSelectorViewController: UIViewController,
UISearchBarDelegate, MKMapViewDelegate {

@IBOutlet weak var locationSearchBar: UISearchBar!
@IBOutlet weak var mapView: MKMapView!
var selectedLoc: String?
let locationManager = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()
    locationManager.requestAlwaysAuthorization()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    locationManager.startUpdatingLocation()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func locationManager(manager: CLLocationManager, didupdateLocations locations: [CLLocation]) {

}

func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {

}

func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {

}
}

I think I have nothing wrong but it is keep showing this error

Cannot Assign value of type "LocationSelectorViewController" to type "CLLocationManagerDelegate?"

Can you tell me where is the Problem?

Body:
Cannot Assign value of type "LocationSelectorViewController" to type "CLLocationManagerDelegate?"

Ans :
Your LocationSelectorViewController class must adopt and conform toCLLocationManagerDelegate protocol.

Add the CLLocationManagerDelegate in your class as shown below.

class LocationSelectorViewController: UIViewController,
UISearchBarDelegate, MKMapViewDelegate, CLLocationManagerDelegate {

instead of

 class LocationSelectorViewController: UIViewController,
UISearchBarDelegate, MKMapViewDelegate {


问:
How to send multiple string by stdin in python
I send the string Router_Status[Router]='ON' by the parent code to new process

```<code>proc[Router] = subprocess.Popen([sys.executable, os.getcwd() + '/'
                                + Router + '.py', Router,
                                json.dumps(graph),
                                json.dumps(As_numbers_dict)],
                                shell=False, stderr=True,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE)

proc[Router].stdin.write(bytes(Router_Status[Router],
                               encoding='utf-8') + b'\n')
</code>```

and the child process is

```<code>Router_Status[Router]=sys.stdin.readline().strip()
path = os.path.expanduser('~' + '/BGP_Routers/' + Router)
with open(path + '/Router_Status.txt', 'w') as f:
        f.write(Router_Status[Router])
</code>```

but it does not work!
And then  I pass the second string Router_Status[Router]='OFF' to the process by
    proc[Router].stdin.write(bytes(Router_Status[Router], encoding='utf-8')

```<code>proc[Router].stdin.flush()
</code>```

and it still does not do anything!

答:
Ok, so I am not completely familiar with the arguments you are passing to your subprocess.Popen() so I am unable to check whether those are correct. I do however know a thing or two about the subprocess module and there are some things to consider looking at your code:

Using shell=False does not need to be defined explicitly as it is the standard setting (although, if you want to make it explicit for a reason, that is allright of course).

The argument stderr=False is incorrect. It must be either None or something like a subprocess.PIPE.

Then, since you are using Python3.x the docs state that:

Warning - Use communicate() rather than .stdin.write, .stdout.read or
  .stderr.read to avoid deadlocks due to any of the other OS pipe
  buffers filling up and blocking the child process.

So you'd be better of using proc[Router].communicate(input="your standard input, meaning your stdin")

It also states:

Popen.stdin - If the stdin argument was PIPE, this attribute is a
  writeable stream object as returned by open(). If the encoding or
  errors arguments were specified or the universal_newlines argument was
  True, the stream is a text stream, otherwise it is a byte stream. If
  the stdin argument was not PIPE, this attribute is None.

In your case the means stdin should indeed by a byte stream.

Overal, I am guessing you should do something like:

```<code>proc[Router] = subprocess.Popen([sys.executable, os.getcwd() + '/'
                                + Router + '.py', Router,
                                json.dumps(graph),
                                json.dumps(As_numbers_dict)],
                                stderr=subprocess.PIPE,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE)

proc[Router].stdin.communicate(str(Router_Status[Router]).encode())
</code>```

I am still wondering however, why did you include:

```<code>path = os.path.expanduser('~' + '/BGP_Routers/' + Router)
with open(path + '/Router_Status.txt', 'w') as f:
        f.write(Router_Status[Router])
</code>```

Since it is basically unrelated to the subprocess.Popen() statement. All it does is write the user input into a textfile, which will only capture the latest input btw. If you'd like to save all user input change 'w' to 'a' (this will put the file in append-mode instead of write-mode).

Body:
I send the string Router_Status[Router]='ON' by the parent code to new process

proc[Router] = subprocess.Popen([sys.executable, os.getcwd() + '/'
                                + Router + '.py', Router,
                                json.dumps(graph),
                                json.dumps(As_numbers_dict)],
                                shell=False, stderr=True,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE)

proc[Router].stdin.write(bytes(Router_Status[Router],
                               encoding='utf-8') + b'\n')

and the child process is

Router_Status[Router]=sys.stdin.readline().strip()
path = os.path.expanduser('~' + '/BGP_Routers/' + Router)
with open(path + '/Router_Status.txt', 'w') as f:
        f.write(Router_Status[Router])

but it does not work!
And then  I pass the second string Router_Status[Router]='OFF' to the process by
    proc[Router].stdin.write(bytes(Router_Status[Router], encoding='utf-8')

proc[Router].stdin.flush()

and it still does not do anything!

Body:
Ok, so I am not completely familiar with the arguments you are passing to your subprocess.Popen() so I am unable to check whether those are correct. I do however know a thing or two about the subprocess module and there are some things to consider looking at your code:

Using shell=False does not need to be defined explicitly as it is the standard setting (although, if you want to make it explicit for a reason, that is allright of course).

The argument stderr=False is incorrect. It must be either None or something like a subprocess.PIPE.

Then, since you are using Python3.x the docs state that:

Warning - Use communicate() rather than .stdin.write, .stdout.read or
  .stderr.read to avoid deadlocks due to any of the other OS pipe
  buffers filling up and blocking the child process.

So you'd be better of using proc[Router].communicate(input="your standard input, meaning your stdin")

It also states:

Popen.stdin - If the stdin argument was PIPE, this attribute is a
  writeable stream object as returned by open(). If the encoding or
  errors arguments were specified or the universal_newlines argument was
  True, the stream is a text stream, otherwise it is a byte stream. If
  the stdin argument was not PIPE, this attribute is None.

In your case the means stdin should indeed by a byte stream.

Overal, I am guessing you should do something like:

proc[Router] = subprocess.Popen([sys.executable, os.getcwd() + '/'
                                + Router + '.py', Router,
                                json.dumps(graph),
                                json.dumps(As_numbers_dict)],
                                stderr=subprocess.PIPE,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE)

proc[Router].stdin.communicate(str(Router_Status[Router]).encode())

I am still wondering however, why did you include:

path = os.path.expanduser('~' + '/BGP_Routers/' + Router)
with open(path + '/Router_Status.txt', 'w') as f:
        f.write(Router_Status[Router])

Since it is basically unrelated to the subprocess.Popen() statement. All it does is write the user input into a textfile, which will only capture the latest input btw. If you'd like to save all user input change 'w' to 'a' (this will put the file in append-mode instead of write-mode).


问:
.Net C# regex for parsing method/property chain calls
I’m trying to parse string like:

.A.B[C].D(E).F("(G) / {H})", "1" == "1").I.J[K]

where A,B,I,J are property names, D,F method names, E, "(G) / {H})", "1" == "1" method parameters and C and K index values. . The parameters can contain any characters and the string may contain any number of properties and/or methods.

I’m looking for a regex that would do that job. So far I came up with

(?<=\.)(?< PropertyOrMethodName>\w+)((\\[(?< Index>\w+)\\])|((?< Open>\\()(?< Parameters>.+)(?<-Open>\\))(?(Open)(?!))))?

but it’s not good e.g. for the above sample captures D(E).F("(G) / {H})", "1" == "1") together.

答:
I don't think you will get good results at all with a regex, unless you have a severely limited sample of c# you wish to parse - and if that's the case, you'd be better off giving a sample of the possible lines in your question.

For example:

```<code>  public void SomeMethod(int x)
  {
     foo.bar.baz(x, y => qux(y))[(x - 1)] = e.value;
  }
</code>```

Even if you come up with a regex that can successfully parse this and other complex cases (good luck) - is foo a namespace, bar a class, and baz a static method?  or is foo a field on the current type, bar a property on that, and baz an instance method?   Without a parser, you really don't get any insight at all to what each element means.

I would suggest looking at a parser - try starting with this SO question: Parser for C#

Body:
I don't think you will get good results at all with a regex, unless you have a severely limited sample of c# you wish to parse - and if that's the case, you'd be better off giving a sample of the possible lines in your question.

For example:

  public void SomeMethod(int x)
  {
     foo.bar.baz(x, y => qux(y))[(x - 1)] = e.value;
  }

Even if you come up with a regex that can successfully parse this and other complex cases (good luck) - is foo a namespace, bar a class, and baz a static method?  or is foo a field on the current type, bar a property on that, and baz an instance method?   Without a parser, you really don't get any insight at all to what each element means.

I would suggest looking at a parser - try starting with this SO question: Parser for C#


问:
transitionViewForCurrentTransition is not set, presentation controller was dismissed during the presentation
TransitionViewForCurrentTransition is not set, presentation controller was dismissed during the presentation? (<_UIFullscreenPresentationController:
how to solve it, no exception is printing but above error show on calling

```<code>-(IBAction)presume:(id)sender
{
        [self returnToRootViewController];

}

 - (UIViewController*)topmostViewController
    {
        UIViewController* vc = [[[UIApplication sharedApplication] keyWindow] rootViewController];
        while(vc.presentedViewController) {
            vc = vc.presentedViewController;
        }
        return vc;
    }

    - (void)returnToRootViewController
    {
        UIViewController* vc = [self topmostViewController];
        while (vc) {
            if(vc.presentingViewController) {
                if ([vc isKindOfClass:[CarDetailVC class]])
                {

                    @try {

                        [vc dismissViewControllerAnimated:NO completion:^{}];

                    } @catch (NSException *exception) {

                        NSLog(@"exception=%@",exception);
                    } @finally {

                    }

                 }

            }
            vc = vc.presentingViewController;
        }

    }
</code>```

答:
Let's start with a more direct path to the target vc (the instance of CarDetailVC).

```<code>- (UIViewController*)vcWithClass:(Class)klass {
    UIViewController* vc = [[[UIApplication sharedApplication] keyWindow] rootViewController];
    while(![vc.presentedViewController isKindOfClass:klass]) {
        vc = vc.presentedViewController;
    }
    return vc;
}
</code>```

Now, get to it and dismiss the vc it presented.

```<code>- (void)returnToCarVC {
    CarDetailVC *carVC =(CarDetailVC*) [self vcWithClass:[CarDetailVC self]];
    UIViewController *presented = carVC.presentedViewController;
    [presented dismissViewControllerAnimated:NO completion:^{}];
}
</code>```

Body:
TransitionViewForCurrentTransition is not set, presentation controller was dismissed during the presentation? (<_UIFullscreenPresentationController:
how to solve it, no exception is printing but above error show on calling

-(IBAction)presume:(id)sender
{
        [self returnToRootViewController];

}

 - (UIViewController*)topmostViewController
    {
        UIViewController* vc = [[[UIApplication sharedApplication] keyWindow] rootViewController];
        while(vc.presentedViewController) {
            vc = vc.presentedViewController;
        }
        return vc;
    }

    - (void)returnToRootViewController
    {
        UIViewController* vc = [self topmostViewController];
        while (vc) {
            if(vc.presentingViewController) {
                if ([vc isKindOfClass:[CarDetailVC class]])
                {

                    @try {

                        [vc dismissViewControllerAnimated:NO completion:^{}];

                    } @catch (NSException *exception) {

                        NSLog(@"exception=%@",exception);
                    } @finally {

                    }

                 }

            }
            vc = vc.presentingViewController;
        }

    }

Body:
Let's start with a more direct path to the target vc (the instance of CarDetailVC).

- (UIViewController*)vcWithClass:(Class)klass {
    UIViewController* vc = [[[UIApplication sharedApplication] keyWindow] rootViewController];
    while(![vc.presentedViewController isKindOfClass:klass]) {
        vc = vc.presentedViewController;
    }
    return vc;
}

Now, get to it and dismiss the vc it presented.

- (void)returnToCarVC {
    CarDetailVC *carVC =(CarDetailVC*) [self vcWithClass:[CarDetailVC self]];
    UIViewController *presented = carVC.presentedViewController;
    [presented dismissViewControllerAnimated:NO completion:^{}];
}


问:
Models load() usage
Can someone enligthen me ,what is the real usage of load method if setting post params can  be directly set to models attributes? Thanks

$model->load(Yii::$app->request->post());

vs

$model->attributes = Yii::$app->request->post();

答: load() will only assign attributes that have got validation rules assigned to them in current scenario so you are able to verify them.

Title: Models load() usage


答:
If you would are receving the timestamp on the client side you can Convert a Unix timestamp to time in JavaScript

// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);

// Hours part from the timestamp
var hours = date.getHours();

// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();

// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();

// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
```

<p>To add the formatted text to a <code>span</code> you could use javascript or jQuery</p>

<pre class="lang-js prettyprint-override"><code>// Javascript
document.querySelector("span").text(formattedTime);

// jQuery
$("span").text(formattedTime);
</code>```

For more information regarding the Date object, please refer to MDN or the ECMAScript 5 specification.

Additionally:

If you must use jQuery instead of Javascript, consider a plugin
https://github.com/phstc/jquery-dateFormat

There is Javascript library https://momentjs.com/ for time

There is a great JS talk about time https://www.youtube.com/watch?v=2BdFg5JT9lg

Title: How to format MySQL timestamp using jquery

Body:
I read timestamp from MySQL db (is type timestamp).

Like this: 2017-04-01 15:34:31

I want to format this date using jquery and set up to some span element.

I am new in jquery and I don't know how to do it.

Thank you.

Body:
If you would are receving the timestamp on the client side you can Convert a Unix timestamp to time in JavaScript

// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);

// Hours part from the timestamp
var hours = date.getHours();

// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();

// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();

// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);

To add the formatted text to a span you could use javascript or jQuery

// Javascript
document.querySelector("span").text(formattedTime);

// jQuery
$("span").text(formattedTime);

For more information regarding the Date object, please refer to MDN or the ECMAScript 5 specification.

Additionally:

If you must use jQuery instead of Javascript, consider a plugin
https://github.com/phstc/jquery-dateFormat

There is Javascript library https://momentjs.com/ for time

There is a great JS talk about time https://www.youtube.com/watch?v=2BdFg5JT9lg