问:
Does R not know that time is circular? How to find closest time of the day to a given time
23:59:59 o'clock is closer to midnight than 03:00:00 o'clock to midnight, for example. Unfortunately, R tells the opposite (at least the package I use). Here is what I mean:

In fact I do not only care about midnight but I need to find the closest time of the day in a vector to a given time and I do not care about the date. There is a similiar question with a great answer but the code doesn't work as expected because in the link time is a timeline not a circle. See here:

```<code>library("chron")
x <- times(c("00:00:02", "23:59:59"))
v <- times("00:00:00")
indx <- which(abs(x-v) == min(abs(x - v)))
x[indx]
00:00:02 # which is further from 00:00:00 than 23:59:59
</code>```

According to the code all times between 00:00:00 and 23:59:59 are closer to midnigth than 23:59:59. For example, this leads to the confusing result that 16:23:11 is closer to midnight than 23:59:59. So R seems to start at 00:00:00 and end at 23:59:59 and thus "does not see" that 23:59:59 is pretty close to 00:00:00. I understand that this makes sense if we take into account dates: For example, 2001-01-01 00:00:02 is closer to 2001-01-01 00:00:00 than is 2001-01-01 23:59:59 to 2001-01-01 00:00:00. But how to find the closest time of the day where one considers the time as a circle?

答:
Edit for a more general solution:

If you are just looking for a nice general solution for this problem:

Since this solution above is only applicable for a very specific situation I tried to create a more general solution. I created a function that wil find to time in a vector closest to a given time.

```<code>library('chron')

#' This function returns the time in 'timeVector' that is
#' closest to 'time'
closest.time <- function(timeVector, time) {
  times()
  x <- times(timeVector)
  v <- times(time)

  clockwise_distance = abs(x - v)
  anticlockwise_distance = times("23:59:59") - clockwise_distance + times("00:00:01")
  clockwise_and_anticlockwise <-  matrix(c(anticlockwise_distance,  clockwise_distance), ncol = 2)
  shortest_distance_of_the_two <- apply(clockwise_and_anticlockwise, 1, min)

  indx <- which(shortest_distance_of_the_two == min(shortest_distance_of_the_two))

  x[indx]
}
</code>```

This solution is based on the idea that there are two ways to go round the circle. The first is just the normal clockwise distance. The second is the anticlockwise distance. Since the whole circle is 24 hours, the anticlockwise distance is '24_hours - clockwise_distance'.

Then for each value in timesVector there should be checked if the clockwise or anticlockwise distance is the shortest.

Lastly, there should be checked which time in timeVector is closest to time

Old answer

Since chron does not have a nice function to do this and I can't come up with a solution that uses the times data type, I am going to abandon times and use POSIXct instead.

POSIXct also has a date attribute that you said you don't want to use. This is why the date in our POSIXct is just a dummy value that we don't really look at, except for changing it in ways to solve our problem.

```<code>x <- c("00:00:02", "23:59:59")
x <- as.POSIXct(x, format = "%H:%M:%OS")
v <- as.POSIXct("00:00:00", format = "%H:%M:%OS")

# I subtract 24 hours to center all times around the same midnight.
mid.day <- as.POSIXct("12:00:00", format = "%H:%M:%OS")
x[x > mid.day] <- x[x > mid.day] - 24*60*60

# I used your same approach to check the time closest to midnight.
# you might want to change this to something that uses difftime(). Ask me if you  need help with this.
indx <- which(abs(x-v) == min(abs(x - v)))

# shows us the POSIXct object the way we want to see it (only time)
format(x[indx], format="%H:%M:%S")
</code>```

Note that you might want to use difftime(x,y) now to get the difference in time

```<code> indx <- which(abs(difftime(x, v)) == min(abs(difftime(x, v))))
</code>```

Body:
23:59:59 o'clock is closer to midnight than 03:00:00 o'clock to midnight, for example. Unfortunately, R tells the opposite (at least the package I use). Here is what I mean:

In fact I do not only care about midnight but I need to find the closest time of the day in a vector to a given time and I do not care about the date. There is a similiar question with a great answer but the code doesn't work as expected because in the link time is a timeline not a circle. See here:

library("chron")
x <- times(c("00:00:02", "23:59:59"))
v <- times("00:00:00")
indx <- which(abs(x-v) == min(abs(x - v)))
x[indx]
00:00:02 # which is further from 00:00:00 than 23:59:59

According to the code all times between 00:00:00 and 23:59:59 are closer to midnigth than 23:59:59. For example, this leads to the confusing result that 16:23:11 is closer to midnight than 23:59:59. So R seems to start at 00:00:00 and end at 23:59:59 and thus "does not see" that 23:59:59 is pretty close to 00:00:00. I understand that this makes sense if we take into account dates: For example, 2001-01-01 00:00:02 is closer to 2001-01-01 00:00:00 than is 2001-01-01 23:59:59 to 2001-01-01 00:00:00. But how to find the closest time of the day where one considers the time as a circle?

Body:
Edit for a more general solution:

If you are just looking for a nice general solution for this problem:

Since this solution above is only applicable for a very specific situation I tried to create a more general solution. I created a function that wil find to time in a vector closest to a given time.

library('chron')

#' This function returns the time in 'timeVector' that is
#' closest to 'time'
closest.time <- function(timeVector, time) {
  times()
  x <- times(timeVector)
  v <- times(time)

  clockwise_distance = abs(x - v)
  anticlockwise_distance = times("23:59:59") - clockwise_distance + times("00:00:01")
  clockwise_and_anticlockwise <-  matrix(c(anticlockwise_distance,  clockwise_distance), ncol = 2)
  shortest_distance_of_the_two <- apply(clockwise_and_anticlockwise, 1, min)

  indx <- which(shortest_distance_of_the_two == min(shortest_distance_of_the_two))

  x[indx]
}

This solution is based on the idea that there are two ways to go round the circle. The first is just the normal clockwise distance. The second is the anticlockwise distance. Since the whole circle is 24 hours, the anticlockwise distance is '24_hours - clockwise_distance'.

Then for each value in timesVector there should be checked if the clockwise or anticlockwise distance is the shortest.

Lastly, there should be checked which time in timeVector is closest to time

Old answer

Since chron does not have a nice function to do this and I can't come up with a solution that uses the times data type, I am going to abandon times and use POSIXct instead.

POSIXct also has a date attribute that you said you don't want to use. This is why the date in our POSIXct is just a dummy value that we don't really look at, except for changing it in ways to solve our problem.

x <- c("00:00:02", "23:59:59")
x <- as.POSIXct(x, format = "%H:%M:%OS")
v <- as.POSIXct("00:00:00", format = "%H:%M:%OS")

# I subtract 24 hours to center all times around the same midnight.
mid.day <- as.POSIXct("12:00:00", format = "%H:%M:%OS")
x[x > mid.day] <- x[x > mid.day] - 24*60*60

# I used your same approach to check the time closest to midnight.
# you might want to change this to something that uses difftime(). Ask me if you  need help with this.
indx <- which(abs(x-v) == min(abs(x - v)))

# shows us the POSIXct object the way we want to see it (only time)
format(x[indx], format="%H:%M:%S")

Note that you might want to use difftime(x,y) now to get the difference in time

 indx <- which(abs(difftime(x, v)) == min(abs(difftime(x, v))))


来源: stackexchange

问:
Service Error : Expected 0 arguments, but got 1.ts(2554)
while creating the new service using ng g s serviceName i am getting the error Expected 0 arguments, but got 1.

this is my package.json

```<code>{
  "name": "rapid",
  "version": "1.1.9",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^5.2.0",
    "@angular/common": "^5.2.0",
    "@angular/compiler": "^5.2.0",
    "@angular/core": "^5.2.11",
    "@angular/forms": "^5.2.0",
    "@angular/http": "^5.2.0",
    "@angular/platform-browser": "^5.2.0",
    "@angular/platform-browser-dynamic": "^5.2.0",
    "@angular/router": "^5.2.0",
    "@asymmetrik/ngx-leaflet": "^4.0.0",
    "@dvsl/zoomcharts": "^1.18.4",
    "@ng-bootstrap/ng-bootstrap": "^4.0.3",
    "@types/c3": "^0.6.0",
    "@types/mixpanel": "^2.14.1",
    "angular-2-dropdown-multiselect": "^1.8.1",
    "angular-confirmation-popover": "^4.2.0",
    "angular-datatables": "^6.0.0",
    "angular2-tag-input": "^1.2.3",
    "angular2-toaster": "^6.1.0",
    "aws-sdk": "^2.271.1",
    "bootstrap": "^3.3.7",
    "bootstrap-daterangepicker": "^3.0.3",
    "c3": "^0.6.6",
    "core-js": "^2.4.1",
    "crypto-js": "^3.1.9-1",
    "datatables.net": "^1.10.18",
    "datatables.net-dt": "^1.10.18",
    "file-saver": "^2.0.0",
    "jquery": "^3.3.1",
    "leaflet": "^1.3.4",
    "mixpanel-browser": "^2.28.0",
    "moment": "^2.22.2",
    "ng-multiselect-dropdown": "^0.1.9",
    "ng-recaptcha": "^4.2.1",
    "ng2-table": "^1.3.2",
    "ng2-tooltip-directive": "^2.1.6",
    "ngx-bootstrap": "^3.1.2",
    "ngx-cookie-service": "^1.0.10",
    "ngx-popover": "0.0.16",
    "ngx-tooltip": "0.0.9",
    "ngx-webstorage": "^2.0.1",
    "popper.js": "^1.14.3",
    "rxjs": "^5.5.6",
    "tslib": "^1.9.0",
    "xlsx": "^0.14.1",
    "zone.js": "^0.8.19"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.12.4",
    "@angular/cli": "^7.2.1",
    "@angular/compiler-cli": "^5.2.0",
    "@angular/language-service": "^5.2.0",
    "@types/datatables.net": "^1.10.11",
    "@types/jasmine": "~2.8.3",
    "@types/jasminewd2": "~2.0.2",
    "@types/jquery": "^3.3.4",
    "@types/node": "~6.0.60",
    "codelyzer": "^4.0.1",
    "jasmine-core": "~2.8.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^3.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "^5.4.0",
    "ts-node": "~4.1.0",
    "tslint": "~5.9.1",
    "typescript": "~2.5.3"
  }
}
</code>```

by taking out the providedIn parameter from @Injectable the service works as the same or i need to modify my code to solve this error i created service by ng g s serviceName to generate the service.ts file

答:
This is the new feature in Angular 6,

I think you need to update your angular-cli globally.

Please use below commands.

npm install -g @angular/cli

npm install @angular/cli

Update package.json

ng update @angular/cli

Update @Angular/Core

ng update @angular/core

ContentLicense: CC BY-SA 4.0

Body:
while creating the new service using ng g s serviceName i am getting the error Expected 0 arguments, but got 1.

this is my package.json

{
  "name": "rapid",
  "version": "1.1.9",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^5.2.0",
    "@angular/common": "^5.2.0",
    "@angular/compiler": "^5.2.0",
    "@angular/core": "^5.2.11",
    "@angular/forms": "^5.2.0",
    "@angular/http": "^5.2.0",
    "@angular/platform-browser": "^5.2.0",
    "@angular/platform-browser-dynamic": "^5.2.0",
    "@angular/router": "^5.2.0",
    "@asymmetrik/ngx-leaflet": "^4.0.0",
    "@dvsl/zoomcharts": "^1.18.4",
    "@ng-bootstrap/ng-bootstrap": "^4.0.3",
    "@types/c3": "^0.6.0",
    "@types/mixpanel": "^2.14.1",
    "angular-2-dropdown-multiselect": "^1.8.1",
    "angular-confirmation-popover": "^4.2.0",
    "angular-datatables": "^6.0.0",
    "angular2-tag-input": "^1.2.3",
    "angular2-toaster": "^6.1.0",
    "aws-sdk": "^2.271.1",
    "bootstrap": "^3.3.7",
    "bootstrap-daterangepicker": "^3.0.3",
    "c3": "^0.6.6",
    "core-js": "^2.4.1",
    "crypto-js": "^3.1.9-1",
    "datatables.net": "^1.10.18",
    "datatables.net-dt": "^1.10.18",
    "file-saver": "^2.0.0",
    "jquery": "^3.3.1",
    "leaflet": "^1.3.4",
    "mixpanel-browser": "^2.28.0",
    "moment": "^2.22.2",
    "ng-multiselect-dropdown": "^0.1.9",
    "ng-recaptcha": "^4.2.1",
    "ng2-table": "^1.3.2",
    "ng2-tooltip-directive": "^2.1.6",
    "ngx-bootstrap": "^3.1.2",
    "ngx-cookie-service": "^1.0.10",
    "ngx-popover": "0.0.16",
    "ngx-tooltip": "0.0.9",
    "ngx-webstorage": "^2.0.1",
    "popper.js": "^1.14.3",
    "rxjs": "^5.5.6",
    "tslib": "^1.9.0",
    "xlsx": "^0.14.1",
    "zone.js": "^0.8.19"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.12.4",
    "@angular/cli": "^7.2.1",
    "@angular/compiler-cli": "^5.2.0",
    "@angular/language-service": "^5.2.0",
    "@types/datatables.net": "^1.10.11",
    "@types/jasmine": "~2.8.3",
    "@types/jasminewd2": "~2.0.2",
    "@types/jquery": "^3.3.4",
    "@types/node": "~6.0.60",
    "codelyzer": "^4.0.1",
    "jasmine-core": "~2.8.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^3.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "^5.4.0",
    "ts-node": "~4.1.0",
    "tslint": "~5.9.1",
    "typescript": "~2.5.3"
  }
}

by taking out the providedIn parameter from @Injectable the service works as the same or i need to modify my code to solve this error i created service by ng g s serviceName to generate the service.ts file


问:
Can a user click a login hyperlink?
I can log a user out of my MVC Core application as follows:

```<code>public IActionResult Logout()
{
    return SignOut("Cookies", "oidc");
}
</code>```

Identity server is called and the user is logged out as expected.  Is it possible to log a user in by specifying a link? I realise the user will be automatically forwarded if they access a secure area of the website.  However, is it possible for the user to say themselves that they wish to login (the return url would be the homepage i.e. home/Index).

I have spent the last hour researching this.  I have found lots of examples explaining how to logout explicitly, however I have not found an example, which shows how to login explicitly.

答:
The question is really unclear, but I will try:

At your Account controller (which is the secure area, right?) create a secured "Login" action.

[Authorized] //actually you don't need this attribute here when have it on controller level
//All this action does is authenticating the user and redirecting to home/Index
public ActionResult AutoLogin()
{
  return RedirectToAction("Index", "Home");
}
```

<p>Then in your layout add:</p>

```@Html.ActionLink(
       "Login", "AutoLogin", "Account", routeValues: new{}, htmlAttributes: new {id = "loginLink"})
```

Title: Can a user click a login hyperlink?

Body:
I can log a user out of my MVC Core application as follows:

public IActionResult Logout()
{
    return SignOut("Cookies", "oidc");
}

Identity server is called and the user is logged out as expected.  Is it possible to log a user in by specifying a link? I realise the user will be automatically forwarded if they access a secure area of the website.  However, is it possible for the user to say themselves that they wish to login (the return url would be the homepage i.e. home/Index).

I have spent the last hour researching this.  I have found lots of examples explaining how to logout explicitly, however I have not found an example, which shows how to login explicitly.

Body:
The question is really unclear, but I will try:

At your Account controller (which is the secure area, right?) create a secured "Login" action.

[Authorized] //actually you don't need this attribute here when have it on controller level
//All this action does is authenticating the user and redirecting to home/Index
public ActionResult AutoLogin()
{
  return RedirectToAction("Index", "Home");
}

Then in your layout add:

@Html.ActionLink(
       "Login", "AutoLogin", "Account", routeValues: new{}, htmlAttributes: new {id = "loginLink"})


问:
Is there an approach which can delay certain seconds between every function call which need to update ui components?
I am writing a maze game, and one of its features is "Show solution". The solution may contain many steps, I am using a for loop to iterate every step, in order to show it clear to a player, I wish it can pause one second around after every step. I know the delay operation cannot be put in UI thread, so I have tried several async delay approach. Unfortunately, because of its async nature, if the solution has more than one step, the UI cannot update till the last step finish. That's not I want certainly.

I have tried handler.postDelayed approach, new Timer().schedule approach.

    public void showSolutionClick(View view) {
        int stage = currentGame.currentStage;
        int[][] solution = GameMap.solutionList[stage];
        drawStage(stage);
        for(int[] step: solution) {
            ImageView v = (ImageView)findViewById(viewIdList[step[0]][step[1]]);
            setTimeout(() -> {v.callOnClick();}, 1);
        }
    }

    private void setTimeout(Runnable r, int seconds) {
        Handler handler = new Handler();
        handler.postDelayed(r, seconds * 1000);
    }
```

<p>Maybe a synchronous delay approach is what I need, and it must not block the ui update.</p>

<p>update: CountDownTimer is suitable for this situation. In fact, I have seen a CountDownTime answer at other questions, I should have tried that approach first before I ask. Thank you all who have given a response.  Here's my final code:</p>

<pre class="lang-java prettyprint-override"><code>    public void showSolutionClick(View view) {
        int stage = currentGame.currentStage;
        int[][] solution = GameMap.solutionList[stage];
        drawStage(stage);
        int stepTotal = solution.length;
        int stepPause = 1000;
        int timeTotal = (stepTotal + 1) * stepPause;

        new CountDownTimer(timeTotal, stepPause) {
            int stepIndex = 0;
            public void onTick(long timeRemain) {
                int[] pos = solution[stepIndex];
                ImageView v = (ImageView)findViewById(viewIdList[pos[0]][pos[1]]);
                v.callOnClick();
                stepIndex += 1;
                Log.d("time remain:", "" + timeRemain / 1000);
            }

            public void onFinish() {
                Log.d("final step", ":" + (stepIndex - 1));
            }
        }.start();
    }
</code>```

答:
You can use a countdown timer.    </p>

```<code> new CountDownTimer(30000, 1000){
                    public void onTick(long millisUntilFinished){
                        doUpdateOnEveryTick()
                    }
                    public  void onFinish(){
                       doActionOnFinish()
                    }
                }.start();
</code>```

Body:
I am writing a maze game, and one of its features is "Show solution". The solution may contain many steps, I am using a for loop to iterate every step, in order to show it clear to a player, I wish it can pause one second around after every step. I know the delay operation cannot be put in UI thread, so I have tried several async delay approach. Unfortunately, because of its async nature, if the solution has more than one step, the UI cannot update till the last step finish. That's not I want certainly.

I have tried handler.postDelayed approach, new Timer().schedule approach.

    public void showSolutionClick(View view) {
        int stage = currentGame.currentStage;
        int[][] solution = GameMap.solutionList[stage];
        drawStage(stage);
        for(int[] step: solution) {
            ImageView v = (ImageView)findViewById(viewIdList[step[0]][step[1]]);
            setTimeout(() -> {v.callOnClick();}, 1);
        }
    }

    private void setTimeout(Runnable r, int seconds) {
        Handler handler = new Handler();
        handler.postDelayed(r, seconds * 1000);
    }

Maybe a synchronous delay approach is what I need, and it must not block the ui update.

update: CountDownTimer is suitable for this situation. In fact, I have seen a CountDownTime answer at other questions, I should have tried that approach first before I ask. Thank you all who have given a response.  Here's my final code:

    public void showSolutionClick(View view) {
        int stage = currentGame.currentStage;
        int[][] solution = GameMap.solutionList[stage];
        drawStage(stage);
        int stepTotal = solution.length;
        int stepPause = 1000;
        int timeTotal = (stepTotal + 1) * stepPause;

        new CountDownTimer(timeTotal, stepPause) {
            int stepIndex = 0;
            public void onTick(long timeRemain) {
                int[] pos = solution[stepIndex];
                ImageView v = (ImageView)findViewById(viewIdList[pos[0]][pos[1]]);
                v.callOnClick();
                stepIndex += 1;
                Log.d("time remain:", "" + timeRemain / 1000);
            }

            public void onFinish() {
                Log.d("final step", ":" + (stepIndex - 1));
            }
        }.start();
    }

Body:
You can use a countdown timer.

 new CountDownTimer(30000, 1000){
                    public void onTick(long millisUntilFinished){
                        doUpdateOnEveryTick()
                    }
                    public  void onFinish(){
                       doActionOnFinish()
                    }
                }.start();


问:
How can I separate variable and set the key to true for swift?
I want to separate the string in var into different vars and set key to true. For example

var x = [English , Chinese , Maths] => "English":true "Chinese":true
  "Maths":true

and push to firebase in order to get a data structure like:

name:anon subject:{"English":true
           "Chinese":true
           "Maths":true}

What should I do ?

答:
You can use reduce(into:_:) method to enumerate the array and create a dictionary</p>

```<code> let x = ["English" , "Chinese" , "Maths"]
 let result = x.reduce(into:[String:Bool](), { $0[$1] = true })
 print(result)//["Chinese": true, "Maths": true, "English": true]
 let valueToSend = ["name":"anon", "subject": result]
</code>```

Body:
You can use reduce(into:_:) method to enumerate the array and create a dictionary

 let x = ["English" , "Chinese" , "Maths"]
 let result = x.reduce(into:[String:Bool](), { $0[$1] = true })
 print(result)//["Chinese": true, "Maths": true, "English": true]
 let valueToSend = ["name":"anon", "subject": result]


问:
jquery stop event bubbling with live
I have this code

```<code> var input = $("form input[name='name'].dhxlist_txt_textarea");

 $(input).live('click', function () {

       ShowLookupGrid();
 });
</code>```

Then I've putted a second live binding before the first get executed

```<code>  $('#Id').live('click', function () {

       return false;
 });
</code>```

But the return false statement isn't stoping bubbling up the event to the second binding.

答:
here written clearly

Since the .live() method handles
  events once they have propagated to
  the top of the document, it is not
  possible to stop propagation of live
  events.

work around for .live() event propagation issues.
nodes created dynamically will not receive the event until after their parent has received it.
this will cause funkyness and stopPropagation and preventDefault will not solve this issue.
To Fix: add the lines

```<code>if(event.target != this){
return true;
}
</code>```

to the top of the parent nodes event handler. this will stop the parent event from firing when the event is actually addressed to a child node, and (unlike return false) will propagate the event to the intended node.

ContentLicense: CC BY-SA 3.0

Title: jquery stop event bubbling with live

Body:
I have this code

 var input = $("form input[name='name'].dhxlist_txt_textarea");

 $(input).live('click', function () {

       ShowLookupGrid();
 });

Then I've putted a second live binding before the first get executed

  $('#Id').live('click', function () {

       return false;
 });

But the return false statement isn't stoping bubbling up the event to the second binding.

Body:
here written clearly

Since the .live() method handles
  events once they have propagated to
  the top of the document, it is not
  possible to stop propagation of live
  events.

work around for .live() event propagation issues.
nodes created dynamically will not receive the event until after their parent has received it.
this will cause funkyness and stopPropagation and preventDefault will not solve this issue.
To Fix: add the lines

if(event.target != this){
return true;
}

to the top of the parent nodes event handler. this will stop the parent event from firing when the event is actually addressed to a child node, and (unlike return false) will propagate the event to the intended node.


问:
Google Play Release to Production for Closed track
I want to submit my Android app to Google Play, but I want to use the Closed track before I release the app into production. So I configured the email list for testers, hit the Review and Rollout buttons (everything in Closed track section), then a new button appeared "Release to Production". Does this mean Production for everybody, or just for my testers? And how are they going to access the app?

This is my first time submitting an app, and I am a little confused.

Thank you

答:
Clicking the "Release to production" from a Closed Track release doesn't make the app available to everybody. The app will be only available to the list of your testers.

I know this wording from Google is a little confusing. Before it go to Production (Public Access), it moves from alpha -> Beta -> Production and you can track these releases.


问:
How to calculate mean of columns from array lists in python using numpy?
I am trying to calculate the mean average of columns from a list of arrays.

```<code>f1_score = [array([0.807892  , 0.91698113, 0.73846154]),
            array([0.80041797, 0.9056244 , 0.72017837]),
            array([0.80541103, 0.91493384, 0.70282486])]
</code>```

I also tried as mentioned below, but I couldn't get the mean value for columns.

```<code>output = []
for i in range(len(f1_score)):
   output.append(np.mean(f1_score[i], axis = 0))
</code>```

I get the mean values for rows:

```<code>[0.8211115582302323, 0.8087402497928408, 0.8077232421210242]
</code>```

But I need the mean values for columns:

```<code>array([0.8045736667, 0.9125131233, 0.7204882567])
</code>```

Thanks in advance for your answer.

答:
If you dont mind using numpy you can do the following

```<code>import numpy as np
arr = np.random.randint(0,10,size=(2,2)) #sample data
arr
#array([[0, 2],
#       [6, 1]])
arr.mean(axis=0) #mean along the columns
# array([3. , 1.5])
arr.mean(axis=1) #mean along the rows
# array([1. , 3.5])
</code>```

Alternatively, you can find the means by doing the following

```<code>arr = [[0,2], [6,1]]
col_means = [sum(i)/len(i) for i in zip(*arr)] #column wise means
# [3.0, 1.5]
row_means = [sum(i)/len(i) for i in arr] #row wise means
# [1.0, 3.5]
</code>```

Body:
I am trying to calculate the mean average of columns from a list of arrays.

f1_score = [array([0.807892  , 0.91698113, 0.73846154]),
            array([0.80041797, 0.9056244 , 0.72017837]),
            array([0.80541103, 0.91493384, 0.70282486])]

I also tried as mentioned below, but I couldn't get the mean value for columns.

output = []
for i in range(len(f1_score)):
   output.append(np.mean(f1_score[i], axis = 0))

I get the mean values for rows:

[0.8211115582302323, 0.8087402497928408, 0.8077232421210242]

But I need the mean values for columns:

array([0.8045736667, 0.9125131233, 0.7204882567])

Thanks in advance for your answer.

Body:
If you dont mind using numpy you can do the following

import numpy as np
arr = np.random.randint(0,10,size=(2,2)) #sample data
arr
#array([[0, 2],
#       [6, 1]])
arr.mean(axis=0) #mean along the columns
# array([3. , 1.5])
arr.mean(axis=1) #mean along the rows
# array([1. , 3.5])

Alternatively, you can find the means by doing the following

arr = [[0,2], [6,1]]
col_means = [sum(i)/len(i) for i in zip(*arr)] #column wise means
# [3.0, 1.5]
row_means = [sum(i)/len(i) for i in arr] #row wise means
# [1.0, 3.5]


问:
How can I locate tooltip tooltip values inside the table using selenium
from this side https://en.wikipedia.org/wiki/China

I need the values of tables at the right side.
How can I get this?

I stored the header values and trying to match the table header and retrieve the column values but showing error.

```<code>List<String> search=new ArrayList<String>();
                 search.add("President");
                 search.add("Capital");
                 search.add("Dialing code");
                 search.add("Currency");
                 search.add("Population");
                 search.add("Official script");
                        for(int ii=0;ii<search.size();ii++) {
                            System.out.print("VALUE in search list ; "+search.get(ii));
                             for(int i=1;i<43;i++) {

                              String ss=driver.findElement(By.xpath("//*[@id=\"mw-content-text\"]/div/table[1]/tbody/tr["+i+"]/th[1]")).getText();
                             System.out.println(" VALUE in ss ; "+ss+" tr["+i+"]");
                            if(ss.toLowerCase().contains(search.get(ii).toLowerCase())) {
                            System.out.println("value matched");
                            //WebElement web= driver.findElement(By.xpath("//*[@id=\"mw-content-text\"]/div/table[1]/tbody/tr["+i+"]/td/a"));
                            //String title=web.getAttribute("title");
                            //System.out.println(title);
                            break;
                        }
                 }

            }
</code>```

i need to get the href tooltip values of each column like President=Xi jinping,Capital=Beijing,official script=simplified chinese etc.But showing error .Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="mw-content-text"]/div/table[1]/tbody/tr[2]/th[1]"}

答:
If you see the xpath what you are using and the HTML code for the same page what you have given, the first row(tr) of the table is having table header (th) and from the second row onwards, we have table data (td), but not th. That is the reason, you are getting text for 1st index and getting NoSuchElementException from the 2nd index onwards. You can change your xpath in such way to handle where ever table header is there and where table data is there. That will help you to fetch the data.

This xpath (//[@id="mw-content-text"]/div/table[1]/tbody/tr) gives 55 matching elements. If you apply //[@id="mw-content-text"]/div/table[1]/tbody/tr[1], it will match with first element and this element have 'th'. i.e. (//[@id="mw-content-text"]/div/table[1]/tbody/tr[1]/th[1]) will work. But for the 2nd index (//[@id="mw-content-text"]/div/table[1]/tbody/tr[2]), we have td instead of th. There is a problem.

You can change your xptah based on above explanation (I have reviewed HTML for the same and observed some are having th and some are with td. In those cases, fetching all elements data with same xpath is not at all possible. The only possible way is to write the xpath individually or segregate all th's and td's and run the loop with if condition).

Title: How can I locate tooltip <a href>tooltip</a> values inside the table using selenium

Body:
from this side https://en.wikipedia.org/wiki/China

I need the values of tables at the right side.
How can I get this?

I stored the header values and trying to match the table header and retrieve the column values but showing error.

List<String> search=new ArrayList<String>();
                 search.add("President");
                 search.add("Capital");
                 search.add("Dialing code");
                 search.add("Currency");
                 search.add("Population");
                 search.add("Official script");
                        for(int ii=0;ii<search.size();ii++) {
                            System.out.print("VALUE in search list ; "+search.get(ii));
                             for(int i=1;i<43;i++) {

                              String ss=driver.findElement(By.xpath("//*[@id=\"mw-content-text\"]/div/table[1]/tbody/tr["+i+"]/th[1]")).getText();
                             System.out.println(" VALUE in ss ; "+ss+" tr["+i+"]");
                            if(ss.toLowerCase().contains(search.get(ii).toLowerCase())) {
                            System.out.println("value matched");
                            //WebElement web= driver.findElement(By.xpath("//*[@id=\"mw-content-text\"]/div/table[1]/tbody/tr["+i+"]/td/a"));
                            //String title=web.getAttribute("title");
                            //System.out.println(title);
                            break;
                        }
                 }

            }

i need to get the href tooltip values of each column like President=Xi jinping,Capital=Beijing,official script=simplified chinese etc.But showing error .Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="mw-content-text"]/div/table[1]/tbody/tr[2]/th[1]"}


问:
Python split by multiple separators, including space?
Input:

```<code>Some Text here: Java, PHP, JS, HTML 5, CSS, Web, C#, SQL, databases, AJAX, etc.
</code>```

Code:

```<code>import re

input_words = list(re.split('\s+', input()))
print(input_words)
</code>```

Works perfect and returns me:

```<code>['Some', 'Text', 'here:', 'Java,', 'PHP,', 'JS,', 'HTML', '5,', 'CSS,', 'Web,', 'C#,', 'SQL,', 'databases,', 'AJAX,', 'etc.']
</code>```

But when add some other separators, like this:

```<code>import re

input_words = list(re.split('\s+ , ; : . ! ( ) " \' \ / [ ] ', input()))
print(input_words)
</code>```

It doesn't split by spaces anymore, where am I wrong?

Expected outpus would be:

```<code>['Some', 'Text', 'here', 'Java', 'PHP', 'JS', 'HTML', '5', 'CSS', 'Web', 'C#', 'SQL', 'databases', 'AJAX', 'etc']
</code>```

答:
Word tokenization using nltk module

```<code>#!/usr/bin/python3
import nltk

sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
words = nltk.tokenize.word_tokenize(sentence)
print(words)
</code>```

output:

['At', 'eight', "o'clock", 'on', 'Thursday', 'morning', '...',
  'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']

Body:
Input:

Some Text here: Java, PHP, JS, HTML 5, CSS, Web, C#, SQL, databases, AJAX, etc.

Code:

import re

input_words = list(re.split('\s+', input()))
print(input_words)

Works perfect and returns me:

['Some', 'Text', 'here:', 'Java,', 'PHP,', 'JS,', 'HTML', '5,', 'CSS,', 'Web,', 'C#,', 'SQL,', 'databases,', 'AJAX,', 'etc.']

But when add some other separators, like this:

import re

input_words = list(re.split('\s+ , ; : . ! ( ) " \' \ / [ ] ', input()))
print(input_words)

It doesn't split by spaces anymore, where am I wrong?

Expected outpus would be:

['Some', 'Text', 'here', 'Java', 'PHP', 'JS', 'HTML', '5', 'CSS', 'Web', 'C#', 'SQL', 'databases', 'AJAX', 'etc']

Body:
Word tokenization using nltk module

#!/usr/bin/python3
import nltk

sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
words = nltk.tokenize.word_tokenize(sentence)
print(words)

output:

['At', 'eight', "o'clock", 'on', 'Thursday', 'morning', '...',
  'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']


问:
Inserting in Excel sheet from another Excel sheet
I am trying to read one excel sheet and then creating another excel sheet through OleDb

In this another excel sheet, I made some colums like Name char(10), Age Number

now when I reading that excel sheet and trying to insert the values in this another excel sheet then values are inserting but also contains one extra char i.e single quote(') as the first char.

Why all the values are instered with single quote pre to actual value? How to get rid of it? I am using c#.net for this.

@Edit

```<code>    OleDbCommand cmd = new OleDbCommand();
                   cmd.CommandType = System.Data.CommandType.Text;
                   cmd.Connection = con;
                   cmd.CommandText = "CREATE TABLE Data1 (Name char(10), Age char(10)) ";

                   cmd.ExecuteNonQuery();

foreach (DataRow row in someDataTable.Rows)
 {

       cmd.CommandText = "INSERT INTO Data1 values ('" + row["Name"] +
                       "','" + row["Age"] +  "')";

       cmd.ExecuteNonQuery();
}
</code>```

I have exactlly the same data in someDataTable as in excel which I need to copy.

答: I've experienced the same problem, inserted fields would get a leading single quote. I've found out that this was only the case when using the JET 4.0 library, the moment I switched to the ACE 12.0 library, the problem was solved.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am trying to read one excel sheet and then creating another excel sheet through OleDb

In this another excel sheet, I made some colums like Name char(10), Age Number

now when I reading that excel sheet and trying to insert the values in this another excel sheet then values are inserting but also contains one extra char i.e single quote(') as the first char.

Why all the values are instered with single quote pre to actual value? How to get rid of it? I am using c#.net for this.

@Edit

    OleDbCommand cmd = new OleDbCommand();
                   cmd.CommandType = System.Data.CommandType.Text;
                   cmd.Connection = con;
                   cmd.CommandText = "CREATE TABLE Data1 (Name char(10), Age char(10)) ";

                   cmd.ExecuteNonQuery();

foreach (DataRow row in someDataTable.Rows)
 {

       cmd.CommandText = "INSERT INTO Data1 values ('" + row["Name"] +
                       "','" + row["Age"] +  "')";

       cmd.ExecuteNonQuery();
}

I have exactlly the same data in someDataTable as in excel which I need to copy.


问:
compare values of two dataframes based on certain filter conditions and then get count
I am new to spark. I am writing a pyspark code where I have two dataframes such that :

DATAFRAME-1:

```<code>NAME BATCH MARKS
A     1     44
B     15    50
C     45    99
D     2     18
</code>```

DATAFRAME-2:

```<code>NAME  MARKS
A       36
B       100
C       23
D       67
</code>```

I want my output as a comparison between these two dataframes such that I can store the counts as my variables.

for instance,

improvedStudents = 1 (since D belongs to batch 1-15 and has improved his score)

badPerformance = 2 (A,B have performed bad since they belong between batch 1-15 and their marks are lesser than before)

neutralPerformance = 1 (C because even if his marks went down, he belongs to batch 45 that we dont want to consider)

This is just an example out of a complex problem I'm trying to solve.

Thanks

答:
If the data is as in your example why don't you just join them and create new columns for every metric that you have:</p>

```<code>val df = df1.withColumnRenamed("MARKS", "PRE_MARKS")
.join(df2.withColumnRenamed("MARKS", "POST_MARKS"), Seq("NAME"))
.withColumn("Evaluation",
    when(col("BATCH") > 15, lit("neutral"))
    .when(col("PRE_MARKS") gt col("POST_MARKS"), lit("bad"))
    .when(col("POST_MARKS") gt col("PRE_MARKS"), lit("improved"))
    .otherwise(lit("neutral"))
    .groupBy("Evaluation")
    .count
</code>```

Body:
I am new to spark. I am writing a pyspark code where I have two dataframes such that :

DATAFRAME-1:

NAME BATCH MARKS
A     1     44
B     15    50
C     45    99
D     2     18

DATAFRAME-2:

NAME  MARKS
A       36
B       100
C       23
D       67

I want my output as a comparison between these two dataframes such that I can store the counts as my variables.

for instance,

improvedStudents = 1 (since D belongs to batch 1-15 and has improved his score)

badPerformance = 2 (A,B have performed bad since they belong between batch 1-15 and their marks are lesser than before)

neutralPerformance = 1 (C because even if his marks went down, he belongs to batch 45 that we dont want to consider)

This is just an example out of a complex problem I'm trying to solve.

Thanks

Body:
If the data is as in your example why don't you just join them and create new columns for every metric that you have:

val df = df1.withColumnRenamed("MARKS", "PRE_MARKS")
.join(df2.withColumnRenamed("MARKS", "POST_MARKS"), Seq("NAME"))
.withColumn("Evaluation",
    when(col("BATCH") > 15, lit("neutral"))
    .when(col("PRE_MARKS") gt col("POST_MARKS"), lit("bad"))
    .when(col("POST_MARKS") gt col("PRE_MARKS"), lit("improved"))
    .otherwise(lit("neutral"))
    .groupBy("Evaluation")
    .count


问:
How to get value
I have a problem and a code like this.

```<code>{"resultcode":"0","message":"Success","description":[{"STORECODE":"F3YQ","STORENAME":"BUNGUR BESAR 30B","ADDRESS":"JL.BUNGUR BESAR NO.30BGUNUNG SAHARI SELATAN","PHONE":"021","POSTALCODE":"10610","OPHOURS":"EVERYDAY (07.00-22.00)","LATITUDE":"-6.1605556","LONGITUDE":"106.8391667","DCCODE":"G137","DCNAME":"JKT2"}]}
</code>```

I was difficult to get the value.
I need a value like this :

Success
F3YQ
10610
JKT2

答:
You need to use json_decode() to covert json to array then you can do what you want Please check below code

```<code>$str_json = '{"resultcode":"0","message":"Success","description":[{"STORECODE":"F3YQ","STORENAME":"BUNGUR BESAR 30B","ADDRESS":"JL.BUNGUR BESAR NO.30BGUNUNG SAHARI SELATAN","PHONE":"021","POSTALCODE":"10610","OPHOURS":"EVERYDAY (07.00-22.00)","LATITUDE":"-6.1605556","LONGITUDE":"106.8391667","DCCODE":"G137","DCNAME":"JKT2"}]}';
echo'```';print_r(json_decode($str_json,true));
$str_array = json_decode($str_json,true);
echo $str_array['message'].' '.$str_array['description'][0]['STORECODE'].' '.$str_array['description'][0]['POSTALCODE'].' '.$str_array['description'][0]['DCNAME'];die;
```

<p>OUTPUT:</p>

```Array
(
    [resultcode] => 0
    [message] => Success
    [description] => Array
        (
            [0] => Array
                (
                    [STORECODE] => F3YQ
                    [STORENAME] => BUNGUR BESAR 30B
                    [ADDRESS] => JL.BUNGUR BESAR NO.30BGUNUNG SAHARI SELATAN
                    [PHONE] => 021
                    [POSTALCODE] => 10610
                    [OPHOURS] => EVERYDAY (07.00-22.00)
                    [LATITUDE] => -6.1605556
                    [LONGITUDE] => 106.8391667
                    [DCCODE] => G137
                    [DCNAME] => JKT2
                )

        )

)
Success F3YQ 10610 JKT2
```

Title: How to get value

Body:
I have a problem and a code like this.

{"resultcode":"0","message":"Success","description":[{"STORECODE":"F3YQ","STORENAME":"BUNGUR BESAR 30B","ADDRESS":"JL.BUNGUR BESAR NO.30BGUNUNG SAHARI SELATAN","PHONE":"021","POSTALCODE":"10610","OPHOURS":"EVERYDAY (07.00-22.00)","LATITUDE":"-6.1605556","LONGITUDE":"106.8391667","DCCODE":"G137","DCNAME":"JKT2"}]}

I was difficult to get the value.
I need a value like this :

Success
F3YQ
10610
JKT2

Body:
You need to use json_decode() to covert json to array then you can do what you want Please check below code

$str_json = '{"resultcode":"0","message":"Success","description":[{"STORECODE":"F3YQ","STORENAME":"BUNGUR BESAR 30B","ADDRESS":"JL.BUNGUR BESAR NO.30BGUNUNG SAHARI SELATAN","PHONE":"021","POSTALCODE":"10610","OPHOURS":"EVERYDAY (07.00-22.00)","LATITUDE":"-6.1605556","LONGITUDE":"106.8391667","DCCODE":"G137","DCNAME":"JKT2"}]}';
echo'<pre>';print_r(json_decode($str_json,true));
$str_array = json_decode($str_json,true);
echo $str_array['message'].' '.$str_array['description'][0]['STORECODE'].' '.$str_array['description'][0]['POSTALCODE'].' '.$str_array['description'][0]['DCNAME'];die;

OUTPUT:

Array
(
    [resultcode] => 0
    [message] => Success
    [description] => Array
        (
            [0] => Array
                (
                    [STORECODE] => F3YQ
                    [STORENAME] => BUNGUR BESAR 30B
                    [ADDRESS] => JL.BUNGUR BESAR NO.30BGUNUNG SAHARI SELATAN
                    [PHONE] => 021
                    [POSTALCODE] => 10610
                    [OPHOURS] => EVERYDAY (07.00-22.00)
                    [LATITUDE] => -6.1605556
                    [LONGITUDE] => 106.8391667
                    [DCCODE] => G137
                    [DCNAME] => JKT2
                )

        )

)
Success F3YQ 10610 JKT2


问:
Conditionally concatenate string values of a tuple in a list in python based on the elements
Here is the list which includes tags to the word type

```<code>t = [('The','OTHER'),('name','OTHER'),('is','OTHER'),('Wall','ORGANIZATION'),('Mart','ORGANIZATION'),('and','OTHER'),('Thomas','ORGANIZATION'),('Cook','ORGANIZATION')]
</code>```

The expectation is to conditionally check if the subsequent tuple is tagged as organization if so concatenate them with a space and continue with the same over the entire list.

Expected output:

```<code>Wall Mart, Thomas Cook

for x in t:
    if(x[1] == 'ORGANIZATION'):
         org_list = org_list + ' | ' + x[0]
</code>```

I was just able to extract the names but not really getting a way where I could concatenate the words tagged as organization.

Refereed to other Question asked: [Link]Concatenate elements of a tuple in a list in python

Expected output: Wall Mart, Thomas Cook

答:
Given that there will always be an 'OTHER' between two subsequent 'ORGANIZATION', one approach is using itertools.groupby to group subsequent tuples by their second element, and str.join their first items if the grouping key is 'ORGANIZATION':

```<code>t = [('The','OTHER'),('name','OTHER'),('is','OTHER'),('Wall','ORGANIZATION'),
     ('Mart','ORGANIZATION'),('and','OTHER'),('Thomas','ORGANIZATION'),
     ('Cook','ORGANIZATION')]

from itertools import groupby
from operator import itemgetter as g

[' '.join(i[0] for i in [*v]) for k,v in groupby(t, key=g(1)) if k=='ORGANIZATION']
# ['Wall Mart', 'Thomas Cook']
</code>```

If you prefer a for loop solution without any imports, you can do: -- This will work only for two subsequent tags:

```<code>f = False
out = []
for i in t:
    if i[1] == 'ORGANIZATION':
        if not f:
            out.append(i[0])
            f = True
        else:
            out[-1] += f' {i[0]}'
            f = False

print(out)
# ['Wall Mart', 'Thomas Cook']
</code>```

Body:
Here is the list which includes tags to the word type

t = [('The','OTHER'),('name','OTHER'),('is','OTHER'),('Wall','ORGANIZATION'),('Mart','ORGANIZATION'),('and','OTHER'),('Thomas','ORGANIZATION'),('Cook','ORGANIZATION')]

The expectation is to conditionally check if the subsequent tuple is tagged as organization if so concatenate them with a space and continue with the same over the entire list.

Expected output:

Wall Mart, Thomas Cook

for x in t:
    if(x[1] == 'ORGANIZATION'):
         org_list = org_list + ' | ' + x[0]

I was just able to extract the names but not really getting a way where I could concatenate the words tagged as organization.

Refereed to other Question asked: [Link]Concatenate elements of a tuple in a list in python

Expected output: Wall Mart, Thomas Cook

Body:
Given that there will always be an 'OTHER' between two subsequent 'ORGANIZATION', one approach is using itertools.groupby to group subsequent tuples by their second element, and str.join their first items if the grouping key is 'ORGANIZATION':

t = [('The','OTHER'),('name','OTHER'),('is','OTHER'),('Wall','ORGANIZATION'),
     ('Mart','ORGANIZATION'),('and','OTHER'),('Thomas','ORGANIZATION'),
     ('Cook','ORGANIZATION')]

from itertools import groupby
from operator import itemgetter as g

[' '.join(i[0] for i in [*v]) for k,v in groupby(t, key=g(1)) if k=='ORGANIZATION']
# ['Wall Mart', 'Thomas Cook']

If you prefer a for loop solution without any imports, you can do: -- This will work only for two subsequent tags:

f = False
out = []
for i in t:
    if i[1] == 'ORGANIZATION':
        if not f:
            out.append(i[0])
            f = True
        else:
            out[-1] += f' {i[0]}'
            f = False

print(out)
# ['Wall Mart', 'Thomas Cook']


问:
How to get value by dynamic field Name using sql select query
I am passing dynamic column name base that column name  to get the value and below i my table

```<code>Table_CandidateInfo

Id     Name        Age    City

1      Mazhar      30     Gulbarga

20     Khan        29     Bidar
</code>```

Example1

```<code>Declare @ColumnName varchar(100), @Id int

set @ColumnName='Age'
set @Id=20

select * from Table_CandidateInfo where ID=@Id and
</code>```

I am not able to pass ColumnName with and query because column name is dynamic pass by code. My output should be

```<code>29
</code>```

Example2: If my @ColumnName='City'  and @Id=20 then output should be like below

```<code>Bidar
</code>```

答:
Alas, you cannot pass identifiers as parameters.  You need to use dynamic SQL:</p>

```<code>declare @columnName varchar(100);
declare @Id int;

set @ColumnName = 'Age' ;
set @Id = 20;

declare @sql nvarchar(max);

set @sql = '
select *
from Table_CandidateInfo
where [columnName] = @Id';

select @sql = replace(@sql, '[columnName]', quotename(@columnName));

exec sp_executesql @sql,
                   N'@id int',
                   @id=@id;
</code>```

Body:
I am passing dynamic column name base that column name  to get the value and below i my table

Table_CandidateInfo

Id     Name        Age    City

1      Mazhar      30     Gulbarga

20     Khan        29     Bidar

Example1

Declare @ColumnName varchar(100), @Id int

set @ColumnName='Age'
set @Id=20

select * from Table_CandidateInfo where ID=@Id and

I am not able to pass ColumnName with and query because column name is dynamic pass by code. My output should be

29

Example2: If my @ColumnName='City'  and @Id=20 then output should be like below

Bidar

Body:
Alas, you cannot pass identifiers as parameters.  You need to use dynamic SQL:

declare @columnName varchar(100);
declare @Id int;

set @ColumnName = 'Age' ;
set @Id = 20;

declare @sql nvarchar(max);

set @sql = '
select *
from Table_CandidateInfo
where [columnName] = @Id';

select @sql = replace(@sql, '[columnName]', quotename(@columnName));

exec sp_executesql @sql,
                   N'@id int',
                   @id=@id;


问:
VirtualBox kept asking me to reinstall Red Hat
I am using Windows 10 and try to install Red Hat in virtualbox. After its installation it asked me to reboot. But after reboot I will come the install UI again. May I ask has anyone met similar problem?

I have ensured that I have disabled the Hyper-V function. And I installed Ubuntu propertly in VirtualBox two days ago.

Versions:

Virtual box: 6.0.8-130520

Red Hat ISO: rhel-8.0-x86_64-dvd

答:
Unbelievable, I have to mannually remove the installingt ISO in virtualbox via:

Settings-> Storage and remove the installing ISO there.


问:
is symfony system wide?
i have a directory with some .php files in it...do i need to install symfony in that directory so that i can run symfony commands from that directory?? i tried: pear channel-discover pear.symfony-project.com

and got:
Channel "pear.symfony-project.com" is already initialized

the i tried: pear install symfony/symfony

and got:
WARNING: configuration download directory "/build/buildd/php5-5.3.2/pear-build-download" is not writeable.  Change download_dir config variable to a writeable dir to avoid this warning
Cannot install, php_dir for channel "pear.symfony-project.com" is not writeable by the current user

how do i fix this please? must i run it as sudo??
thanks

答:
If I remember well, Symfony is "system-wide" if installed through PEAR (like you are trying to do).

Now it is recommended by the manual to do a "standalone" install through SVN. See http://www.symfony-project.org/gentle-introduction/1_4/en/03-Running-Symfony

As well, the sandbox will bring a "standalone" installation of Symfony (you will have to be in the project root directory to be able to run the symfony commands)

EDIT

Example of quick install using SVN:

```<code>mkdir /path/to/symfony
cd /path/to/symfony
svn checkout http://svn.symfony-project.com/tags/RELEASE_1_4_0 .
</code>```

but it should be better to follow the manual and configure the external SVN sources.

Title: is symfony system wide?

Body:
If I remember well, Symfony is "system-wide" if installed through PEAR (like you are trying to do).

Now it is recommended by the manual to do a "standalone" install through SVN. See http://www.symfony-project.org/gentle-introduction/1_4/en/03-Running-Symfony

As well, the sandbox will bring a "standalone" installation of Symfony (you will have to be in the project root directory to be able to run the symfony commands)

EDIT

Example of quick install using SVN:

mkdir /path/to/symfony
cd /path/to/symfony
svn checkout http://svn.symfony-project.com/tags/RELEASE_1_4_0 .

but it should be better to follow the manual and configure the external SVN sources.


问:
How do I interrogate the current app's URL scheme programmatically?
My iOS app has 50+ targets, each with their own custom URL scheme.  I need to detect if a request from a webview matches the scheme of the currently running app.  In order to do this, I need to be able to interrogate the current app's URL scheme(s) from code.

Similar questions deal with attempting to interrogate other apps to discover their URL schemes, which seems like it is not possible.  I need to find the scheme out for my own app, from within my app.

I would like to avoid having to set another plist value to the URL scheme and including that with the target.

Is there any way to get the URL scheme of the current app?

答:
Extension for Bundle swift 4 syntax</p>

```<code>extension Bundle {

    static let externalURLSchemes: [String] = {
        guard let urlTypes = main.infoDictionary?["CFBundleURLTypes"] as? [[String: Any]] else {
            return []
        }

        var result: [String] = []
        for urlTypeDictionary in urlTypes {
            guard let urlSchemes = urlTypeDictionary["CFBundleURLSchemes"] as? [String] else { continue }
            guard let externalURLScheme = urlSchemes.first else { continue }
            result.append(externalURLScheme)
        }

        return result
    }()

}
</code>```

Body:
Extension for Bundle swift 4 syntax

extension Bundle {

    static let externalURLSchemes: [String] = {
        guard let urlTypes = main.infoDictionary?["CFBundleURLTypes"] as? [[String: Any]] else {
            return []
        }

        var result: [String] = []
        for urlTypeDictionary in urlTypes {
            guard let urlSchemes = urlTypeDictionary["CFBundleURLSchemes"] as? [String] else { continue }
            guard let externalURLScheme = urlSchemes.first else { continue }
            result.append(externalURLScheme)
        }

        return result
    }()

}


问:
How to close/hide the Android soft keyboard programmatically?
I have an EditText and a Button in my layout.

After writing in the edit field and clicking on the Button, I want to hide the virtual keyboard when touching outside the keyboard. I assume that this is a simple piece of code, but where can I find an example of it?

答:
This code snippet can helped:

```<code>    final InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
    if (inputMethodManager != null && inputMethodManager.isActive()) {
        if (getCurrentFocus() != null) {
            inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }
</code>```

It can be called in different methods according to need (ex. onPause, onResume, onRestart ...)

Body:
This code snippet can helped:

    final InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
    if (inputMethodManager != null && inputMethodManager.isActive()) {
        if (getCurrentFocus() != null) {
            inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }

It can be called in different methods according to need (ex. onPause, onResume, onRestart ...)


问:
SQL Server connection works on an test app but not on the actual app
I made a simple test app to test a SQL Server connection. First I tested a local database and then the actual remote database. Both connections worked fine.

But when I paste this very same code to my actual application then only the local database connection works. Trying to connect to the remote database throws SqlException #2

I can't see why the code works on one app but not on another. Any ideas?

```<code>Imports System.Data.SqlClient

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim connStr As String = "Server=AAG-SQL02;Database=ProhaDB;Trusted_Connection=True"
        ''Dim connStr As String = "Server=localhost\SQLEXPRESS01;Database=ProhaDB;Trusted_Connection=True"

        Try
            Dim dbConn = New SqlConnection(connStr)
            dbConn.Open()
            dbConn.Close()
            MsgBox("Connection OK")
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub
End Class
</code>```

Exception thrown:

'System.Data.SqlClient.SqlException' in Microsoft.VisualBasic.dll

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

答:
Please allow the user the specific database which you're defined into the database and with same user need to access the db other network error will throw you the same exception always.

Ping the server ip in your cmd and check the server responds to you or not.

open the cmd
just write ping AAG-SQL02

Body:
I made a simple test app to test a SQL Server connection. First I tested a local database and then the actual remote database. Both connections worked fine.

But when I paste this very same code to my actual application then only the local database connection works. Trying to connect to the remote database throws SqlException #2

I can't see why the code works on one app but not on another. Any ideas?

Imports System.Data.SqlClient

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim connStr As String = "Server=AAG-SQL02;Database=ProhaDB;Trusted_Connection=True"
        ''Dim connStr As String = "Server=localhost\SQLEXPRESS01;Database=ProhaDB;Trusted_Connection=True"

        Try
            Dim dbConn = New SqlConnection(connStr)
            dbConn.Open()
            dbConn.Close()
            MsgBox("Connection OK")
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub
End Class

Exception thrown:

'System.Data.SqlClient.SqlException' in Microsoft.VisualBasic.dll

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)


答:
Demo Link

You can get data using json_decode php function

```<code>$nvjsonresponse = '{"resultcode":"0","message":"Success","description":[{"STORECODE":"F3YQ","STORENAME":"BUNGUR BESAR 30B","ADDRESS":"JL.BUNGUR BESAR NO.30BGUNUNG SAHARI SELATAN","PHONE":"021","POSTALCODE":"10610","OPHOURS":"EVERYDAY (07.00-22.00)","LATITUDE":"-6.1605556","LONGITUDE":"106.8391667","DCCODE":"G137","DCNAME":"JKT2"}]};'
$nvarrayval = json_decode($nvjsonresponse,true);
print_r($nvarrayval);
</code>```

Title: How to get value

Body:
Demo Link

You can get data using json_decode php function

$nvjsonresponse = '{"resultcode":"0","message":"Success","description":[{"STORECODE":"F3YQ","STORENAME":"BUNGUR BESAR 30B","ADDRESS":"JL.BUNGUR BESAR NO.30BGUNUNG SAHARI SELATAN","PHONE":"021","POSTALCODE":"10610","OPHOURS":"EVERYDAY (07.00-22.00)","LATITUDE":"-6.1605556","LONGITUDE":"106.8391667","DCCODE":"G137","DCNAME":"JKT2"}]};'
$nvarrayval = json_decode($nvjsonresponse,true);
print_r($nvarrayval);


问:
Can't install any packages with Node.js
I'm an absolute novice in Ionic, Cordova and Node.js.

I have the following problem with Node.js:

I got a project from a colleague created with ionic and cordova. The app itself is also running, for a special customer, we have adapted the design. My thought was that it was done quickly. I changed my branch in GIT to the corresponding project and wanted to do it. Unfortunately, I get countless error messages and warnings that I did not have in the previous project.

I uninstalled Node.js and reinstalled it completely, unfortunately nothing has changed. I can not uninstall or install any of the packages. I always get this eternally long error message and I do not know exactly what the problem is. Uninstalling Ionic and cordova does not work either, same error message. Below is a listing of my version of Node.js, Ionic and cordova and the beginning and end of the error message.

```<code>Console:gitproject user$ git branch
* development
  master
Console:gitproject user$ ionic cordova build
? What platform would you like to build (android, ios): ios
> ionic-app-scripts build --target cordova --platform ios
[08:44:43]  ionic-app-scripts 3.2.3
[08:44:43]  build dev started ...
[08:44:43]  clean started ...
[08:44:43]  clean finished in 24 ms
[08:44:43]  copy started ...
[08:44:43]  deeplinks started ...
[08:44:44]  deeplinks finished in 593 ms
[08:44:44]  transpile started ...
[08:44:56]  typescript: src/app/app.component.ts, line: 34
            Cannot find name 'Globalization'.

      L33:            private translate: TranslateService,
      L34:            private globalization: Globalization) {
      L35:  platform.ready().then(() => {

[08:44:56]  ionic-app-script task: "build"
[08:44:56]  Error: Failed to transpile program
Error: Failed to transpile program
    at new BuildError (/path/to/project/gitproject/node_modules/@ionic/app-scripts/dist/util/errors.js:16:28)
    at /path/to/project/gitproject/node_modules/@ionic/app-scripts/dist/transpile.js:159:20
    at new Promise (<anonymous>)
    at transpileWorker (/path/to/project/gitproject/node_modules/@ionic/app-scripts/dist/transpile.js:107:12)
    at Object.transpile (/path/to/project/gitproject/node_modules/@ionic/app-scripts/dist/transpile.js:64:12)
    at /path/to/project/gitproject/node_modules/@ionic/app-scripts/dist/build.js:109:82
[ERROR] An error occurred while running subprocess ionic-app-scripts.

        ionic-app-scripts build --target cordova --platform ios exited with exit code 1.

        Re-running this command with the --verbose flag may provide more information.
Console:gitproject user$ ionic cordova plugin add cordova-plugin-globalization
> cordova plugin add cordova-plugin-globalization --save
Installing "cordova-plugin-globalization" for ios
Unable to load PlatformApi from platform. Error: Cannot find module 'unorm'
Require stack:
- /path/to/project/gitproject/platforms/ios/cordova/Api.js
- /usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/cordova/util.js
- /usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/platforms/platforms.js
- /usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/plugman/install.js
- /usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/plugman/plugman.js
- /usr/local/lib/node_modules/cordova/node_modules/cordova-lib/cordova-lib.js
- /usr/local/lib/node_modules/cordova/src/help.js
- /usr/local/lib/node_modules/cordova/src/cli.js
- /usr/local/lib/node_modules/cordova/bin/cordova
Failed to install 'cordova-plugin-globalization': Error [ERR_UNHANDLED_ERROR]: Unhandled error. ('The platform "ios" does not appear to be a valid ' +
  'cordova platform. It is missing API.js. ios not ' +
  'supported.')
    at CordovaEventEmitter.emit (events.js:185:17)
    at CordovaEventEmitter.emit (/usr/local/lib/node_modules/cordova/node_modules/cordova-common/src/events.js:69:22)
    at Object.getPlatformApiFunction (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/cordova/util.js:384:20)
    at Object.getPlatformApi (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/platforms/platforms.js:55:32)
    at handleInstall (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/plugman/install.js:580:29)
    at /usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/plugman/install.js:349:28
    at processTicksAndRejections (internal/process/task_queues.js:89:5)
Unhandled error. ('The platform "ios" does not appear to be a valid ' +
  'cordova platform. It is missing API.js. ios not ' +
  'supported.')
Console:gitproject user$ npm install @ionic-native/globalization

> fsevents@1.2.4 install /path/to/project/gitproject/node_modules/fsevents
> node install

node-pre-gyp WARN Tried to download(404): https://fsevents-binaries.s3-us-west-2.amazonaws.com/v1.2.4/fse-v1.2.4-node-v72-darwin-x64.tar.gz
node-pre-gyp WARN Pre-built binaries not found for fsevents@1.2.4 and node@12.2.0 (node-v72 ABI, unknown) (falling back to source compile with node-gyp)

...
...
...
...

10 warnings and 8 errors generated.
make: *** [Release/obj.target/binding/src/binding.o] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/path/to/project/gitproject/node_modules/node-gyp/lib/build.js:262:23)
gyp ERR! stack     at ChildProcess.emit (events.js:200:13)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:272:12)
gyp ERR! System Darwin 18.6.0
gyp ERR! command "/usr/local/bin/node" "/path/to/project/gitproject/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
gyp ERR! cwd /path/to/project/gitproject/node_modules/node-sass
gyp ERR! node -v v12.3.1
gyp ERR! node-gyp -v v3.7.0
gyp ERR! not ok
Build failed with error code: 1
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/fsevents):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 install: `node install`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! node-sass@4.9.0 postinstall: `node scripts/build.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-sass@4.9.0 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /path/to/user/folder/.npm/_logs/2019-05-27T08_04_02_672Z-debug.log
</code>```

Here is the edition from the above mentioned error log

```<code>2653 warn optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/fsevents):
2654 warn optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 install: `node install`
2654 warn optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1
2655 verbose optional SKIPPING OPTIONAL DEPENDENCY:
2655 verbose optional Failed at the fsevents@1.2.4 install script.
2655 verbose optional SKIPPING OPTIONAL DEPENDENCY: This is probably not a problem with npm. There is likely additional logging output above.
2656 verbose stack Error: node-sass@4.9.0 postinstall: `node scripts/build.js`
2656 verbose stack Exit status 1
2656 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:301:16)
2656 verbose stack     at EventEmitter.emit (events.js:200:13)
2656 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
2656 verbose stack     at ChildProcess.emit (events.js:200:13)
2656 verbose stack     at maybeClose (internal/child_process.js:1021:16)
2656 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5)
2657 verbose pkgid node-sass@4.9.0
2658 verbose cwd /Users/premox/Documents/projects/gitproject
2659 verbose Darwin 18.6.0
2660 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "uninstall" "sass"
2661 verbose node v12.3.1
2662 verbose npm  v6.9.0
2663 error code ELIFECYCLE
2664 error errno 1
2665 error node-sass@4.9.0 postinstall: `node scripts/build.js`
2665 error Exit status 1
2666 error Failed at the node-sass@4.9.0 postinstall script.
2666 error This is probably not a problem with npm. There is likely additional logging output above.
2667 verbose exit [ 1, true ]

Console:gitproject user$ node -v
v12.3.1
Console:gitproject user$ npm -v
6.9.0
</code>```

Can someone explain this error message to me?

答:
There are a couple of things you can do in order to setup the project correctly.

Check if node, ionic and cordova are properly installed.

Completely delete the node modules folder and then run the following command:-

npm install

This would install all the dependencies in the project.

If above doesnot work then you can try, same step mentioned by Ashok to resolve:-

npm install @ionic/app-scripts@latest --save-dev

Please let me know if you have any questions.

Title: Can't install any packages with Node.js

Body:
I'm an absolute novice in Ionic, Cordova and Node.js.

I have the following problem with Node.js:

I got a project from a colleague created with ionic and cordova. The app itself is also running, for a special customer, we have adapted the design. My thought was that it was done quickly. I changed my branch in GIT to the corresponding project and wanted to do it. Unfortunately, I get countless error messages and warnings that I did not have in the previous project.

I uninstalled Node.js and reinstalled it completely, unfortunately nothing has changed. I can not uninstall or install any of the packages. I always get this eternally long error message and I do not know exactly what the problem is. Uninstalling Ionic and cordova does not work either, same error message. Below is a listing of my version of Node.js, Ionic and cordova and the beginning and end of the error message.

Console:gitproject user$ git branch
* development
  master
Console:gitproject user$ ionic cordova build
? What platform would you like to build (android, ios): ios
> ionic-app-scripts build --target cordova --platform ios
[08:44:43]  ionic-app-scripts 3.2.3
[08:44:43]  build dev started ...
[08:44:43]  clean started ...
[08:44:43]  clean finished in 24 ms
[08:44:43]  copy started ...
[08:44:43]  deeplinks started ...
[08:44:44]  deeplinks finished in 593 ms
[08:44:44]  transpile started ...
[08:44:56]  typescript: src/app/app.component.ts, line: 34
            Cannot find name 'Globalization'.

      L33:            private translate: TranslateService,
      L34:            private globalization: Globalization) {
      L35:  platform.ready().then(() => {

[08:44:56]  ionic-app-script task: "build"
[08:44:56]  Error: Failed to transpile program
Error: Failed to transpile program
    at new BuildError (/path/to/project/gitproject/node_modules/@ionic/app-scripts/dist/util/errors.js:16:28)
    at /path/to/project/gitproject/node_modules/@ionic/app-scripts/dist/transpile.js:159:20
    at new Promise (<anonymous>)
    at transpileWorker (/path/to/project/gitproject/node_modules/@ionic/app-scripts/dist/transpile.js:107:12)
    at Object.transpile (/path/to/project/gitproject/node_modules/@ionic/app-scripts/dist/transpile.js:64:12)
    at /path/to/project/gitproject/node_modules/@ionic/app-scripts/dist/build.js:109:82
[ERROR] An error occurred while running subprocess ionic-app-scripts.

        ionic-app-scripts build --target cordova --platform ios exited with exit code 1.

        Re-running this command with the --verbose flag may provide more information.
Console:gitproject user$ ionic cordova plugin add cordova-plugin-globalization
> cordova plugin add cordova-plugin-globalization --save
Installing "cordova-plugin-globalization" for ios
Unable to load PlatformApi from platform. Error: Cannot find module 'unorm'
Require stack:
- /path/to/project/gitproject/platforms/ios/cordova/Api.js
- /usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/cordova/util.js
- /usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/platforms/platforms.js
- /usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/plugman/install.js
- /usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/plugman/plugman.js
- /usr/local/lib/node_modules/cordova/node_modules/cordova-lib/cordova-lib.js
- /usr/local/lib/node_modules/cordova/src/help.js
- /usr/local/lib/node_modules/cordova/src/cli.js
- /usr/local/lib/node_modules/cordova/bin/cordova
Failed to install 'cordova-plugin-globalization': Error [ERR_UNHANDLED_ERROR]: Unhandled error. ('The platform "ios" does not appear to be a valid ' +
  'cordova platform. It is missing API.js. ios not ' +
  'supported.')
    at CordovaEventEmitter.emit (events.js:185:17)
    at CordovaEventEmitter.emit (/usr/local/lib/node_modules/cordova/node_modules/cordova-common/src/events.js:69:22)
    at Object.getPlatformApiFunction (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/cordova/util.js:384:20)
    at Object.getPlatformApi (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/platforms/platforms.js:55:32)
    at handleInstall (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/plugman/install.js:580:29)
    at /usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/plugman/install.js:349:28
    at processTicksAndRejections (internal/process/task_queues.js:89:5)
Unhandled error. ('The platform "ios" does not appear to be a valid ' +
  'cordova platform. It is missing API.js. ios not ' +
  'supported.')
Console:gitproject user$ npm install @ionic-native/globalization

> fsevents@1.2.4 install /path/to/project/gitproject/node_modules/fsevents
> node install

node-pre-gyp WARN Tried to download(404): https://fsevents-binaries.s3-us-west-2.amazonaws.com/v1.2.4/fse-v1.2.4-node-v72-darwin-x64.tar.gz
node-pre-gyp WARN Pre-built binaries not found for fsevents@1.2.4 and node@12.2.0 (node-v72 ABI, unknown) (falling back to source compile with node-gyp)

...
...
...
...

10 warnings and 8 errors generated.
make: *** [Release/obj.target/binding/src/binding.o] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/path/to/project/gitproject/node_modules/node-gyp/lib/build.js:262:23)
gyp ERR! stack     at ChildProcess.emit (events.js:200:13)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:272:12)
gyp ERR! System Darwin 18.6.0
gyp ERR! command "/usr/local/bin/node" "/path/to/project/gitproject/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
gyp ERR! cwd /path/to/project/gitproject/node_modules/node-sass
gyp ERR! node -v v12.3.1
gyp ERR! node-gyp -v v3.7.0
gyp ERR! not ok
Build failed with error code: 1
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/fsevents):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 install: `node install`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! node-sass@4.9.0 postinstall: `node scripts/build.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-sass@4.9.0 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /path/to/user/folder/.npm/_logs/2019-05-27T08_04_02_672Z-debug.log

Here is the edition from the above mentioned error log

2653 warn optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/fsevents):
2654 warn optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 install: `node install`
2654 warn optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1
2655 verbose optional SKIPPING OPTIONAL DEPENDENCY:
2655 verbose optional Failed at the fsevents@1.2.4 install script.
2655 verbose optional SKIPPING OPTIONAL DEPENDENCY: This is probably not a problem with npm. There is likely additional logging output above.
2656 verbose stack Error: node-sass@4.9.0 postinstall: `node scripts/build.js`
2656 verbose stack Exit status 1
2656 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:301:16)
2656 verbose stack     at EventEmitter.emit (events.js:200:13)
2656 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
2656 verbose stack     at ChildProcess.emit (events.js:200:13)
2656 verbose stack     at maybeClose (internal/child_process.js:1021:16)
2656 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5)
2657 verbose pkgid node-sass@4.9.0
2658 verbose cwd /Users/premox/Documents/projects/gitproject
2659 verbose Darwin 18.6.0
2660 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "uninstall" "sass"
2661 verbose node v12.3.1
2662 verbose npm  v6.9.0
2663 error code ELIFECYCLE
2664 error errno 1
2665 error node-sass@4.9.0 postinstall: `node scripts/build.js`
2665 error Exit status 1
2666 error Failed at the node-sass@4.9.0 postinstall script.
2666 error This is probably not a problem with npm. There is likely additional logging output above.
2667 verbose exit [ 1, true ]

Console:gitproject user$ node -v
v12.3.1
Console:gitproject user$ npm -v
6.9.0

Can someone explain this error message to me?


问:
Foreign key problems in sqlite3
I get an error "unknown column "CustID" in foreign key definition"
and "no such table: serviceticket"

Can anyone help me?

```<code>drop table if exists customer;
drop table if exists serviceticket;

PRAGMA foreign_keys = ON;

create table customer (CustID char(6) not null primary key UNIQUE,
    CustNAME TEXT,
    STREET TEXT,
    CITY TEXT,
    ZIP INT(5),
    EMAIL VARCHAR,
    PHONENUMBER INT(10)
    );

create table serviceticket (TicketID char(4) not null primary key,
    TicketNO char(5),
    WatchID char(6),
    DateRecieved char(6),
    ExpectedDelivery char(6),
    COMMENTS text,
    DateReturned char(6),
    FOREIGN KEY (CustID) REFERENCES customer (CustID)
    );

insert into customer (CustID, CustNAME, STREET, CITY, ZIP, PHONENUMBER, EMAIL)
    values (170362, 'James', 'Vvegen', New York, 12345, 8170710520, 'brt92@outlook.com');

insert into serviceticket (TicketID, WatchID, CustID, DateRecieved, DateReturned, ExpectedDelivery, COMMENTS, DateReturned)
    values (6745, 87463, 098636, 124319, 362836, 683743, 'Nothing to say', 583728);
</code>```

答:
The code below will work.

This has three changes instead of using FOREIGN KEY (CustID) REFERENCES customer (CustID), which requires the column CustID in the serviceticket table to have been defined; CustID REFERENCES customer (CustID), this defines the CustID column and sets the Foreign Key constraint.

The second change replaces 098636 which will result in a Foreign Key constraint conflict, with 170362 which is a value that exists in the CustID column of the Customer table.

e.g. :-

This works (after the table has been correctly defined) :-

```<code>    insert into serviceticket (TicketID, WatchID, CustID, DateRecieved, DateReturned, ExpectedDelivery, COMMENTS, DateReturned)
    values (6745, 87463, '170362', 124319, 362836, 683743, 'Nothing to say', 583728)
> Affected rows: 1
> Time: 0.082s
</code>```

This will (as per the message) fail

```<code>insert into serviceticket (TicketID, WatchID, CustID, DateRecieved, DateReturned, ExpectedDelivery, COMMENTS, DateReturned)
values (6745, 87463, 098636, 124319, 362836, 683743, 'Nothing to say', 583728)
> FOREIGN KEY constraint failed
> Time: 0s
</code>```

The third change is swapping the order in which the tables are dropped.

The working code

```<code>drop table if exists serviceticket; -- <<<<<<<<<< if not coding ON DELETE CASCADE the children have to be deleted first (so moved before dropping customer table)
drop table if exists customer;

PRAGMA foreign_keys = ON;

create table customer (CustID char(6) not null primary key UNIQUE,
    CustNAME TEXT,
    STREET TEXT,
    CITY TEXT,
    ZIP INT(5),
    EMAIL VARCHAR,
    PHONENUMBER INT(10)
    );

create table serviceticket (TicketID char(4) not null primary key,
    TicketNO char(5),
    WatchID char(6),
    DateRecieved char(6),
    ExpectedDelivery char(6),
    COMMENTS text,
    DateReturned char(6),
    CustID REFERENCES customer (CustID) -- <<<<<<<<<< defines the column and foreign key
    );

insert into customer (CustID, CustNAME, STREET, CITY, ZIP, PHONENUMBER, EMAIL)
    values (170362, 'James', 'Vvegen', 'New York', 12345, 8170710520, 'brt92@outlook.com');

insert into serviceticket (TicketID, WatchID, CustID, DateRecieved, DateReturned, ExpectedDelivery, COMMENTS, DateReturned)
    values (6745, 87463,
        '170362', -- <<<<<<<<<< MUST match a value in CustID column of the customer table (changed to work)
        124319, 362836, 683743, 'Nothing to say', 583728);
</code>```

Additional

you may wish to consider using (or variants thereof):-

```<code>CustID REFERENCES customer (CustID) ON DELETE CASCADE ON UPDATE CASCADE
</code>```

4.3. ON DELETE and ON UPDATE Actions

Title: Foreign key problems in sqlite3

Body:
I get an error "unknown column "CustID" in foreign key definition"
and "no such table: serviceticket"

Can anyone help me?

drop table if exists customer;
drop table if exists serviceticket;

PRAGMA foreign_keys = ON;

create table customer (CustID char(6) not null primary key UNIQUE,
    CustNAME TEXT,
    STREET TEXT,
    CITY TEXT,
    ZIP INT(5),
    EMAIL VARCHAR,
    PHONENUMBER INT(10)
    );

create table serviceticket (TicketID char(4) not null primary key,
    TicketNO char(5),
    WatchID char(6),
    DateRecieved char(6),
    ExpectedDelivery char(6),
    COMMENTS text,
    DateReturned char(6),
    FOREIGN KEY (CustID) REFERENCES customer (CustID)
    );

insert into customer (CustID, CustNAME, STREET, CITY, ZIP, PHONENUMBER, EMAIL)
    values (170362, 'James', 'Vvegen', New York, 12345, 8170710520, 'brt92@outlook.com');

insert into serviceticket (TicketID, WatchID, CustID, DateRecieved, DateReturned, ExpectedDelivery, COMMENTS, DateReturned)
    values (6745, 87463, 098636, 124319, 362836, 683743, 'Nothing to say', 583728);

Body:
The code below will work.

This has three changes instead of using FOREIGN KEY (CustID) REFERENCES customer (CustID), which requires the column CustID in the serviceticket table to have been defined; CustID REFERENCES customer (CustID), this defines the CustID column and sets the Foreign Key constraint.

The second change replaces 098636 which will result in a Foreign Key constraint conflict, with 170362 which is a value that exists in the CustID column of the Customer table.

e.g. :-

This works (after the table has been correctly defined) :-

    insert into serviceticket (TicketID, WatchID, CustID, DateRecieved, DateReturned, ExpectedDelivery, COMMENTS, DateReturned)
    values (6745, 87463, '170362', 124319, 362836, 683743, 'Nothing to say', 583728)
> Affected rows: 1
> Time: 0.082s

This will (as per the message) fail

insert into serviceticket (TicketID, WatchID, CustID, DateRecieved, DateReturned, ExpectedDelivery, COMMENTS, DateReturned)
values (6745, 87463, 098636, 124319, 362836, 683743, 'Nothing to say', 583728)
> FOREIGN KEY constraint failed
> Time: 0s

The third change is swapping the order in which the tables are dropped.

The working code

drop table if exists serviceticket; -- <<<<<<<<<< if not coding ON DELETE CASCADE the children have to be deleted first (so moved before dropping customer table)
drop table if exists customer;

PRAGMA foreign_keys = ON;

create table customer (CustID char(6) not null primary key UNIQUE,
    CustNAME TEXT,
    STREET TEXT,
    CITY TEXT,
    ZIP INT(5),
    EMAIL VARCHAR,
    PHONENUMBER INT(10)
    );

create table serviceticket (TicketID char(4) not null primary key,
    TicketNO char(5),
    WatchID char(6),
    DateRecieved char(6),
    ExpectedDelivery char(6),
    COMMENTS text,
    DateReturned char(6),
    CustID REFERENCES customer (CustID) -- <<<<<<<<<< defines the column and foreign key
    );

insert into customer (CustID, CustNAME, STREET, CITY, ZIP, PHONENUMBER, EMAIL)
    values (170362, 'James', 'Vvegen', 'New York', 12345, 8170710520, 'brt92@outlook.com');

insert into serviceticket (TicketID, WatchID, CustID, DateRecieved, DateReturned, ExpectedDelivery, COMMENTS, DateReturned)
    values (6745, 87463,
        '170362', -- <<<<<<<<<< MUST match a value in CustID column of the customer table (changed to work)
        124319, 362836, 683743, 'Nothing to say', 583728);

Additional

you may wish to consider using (or variants thereof):-

CustID REFERENCES customer (CustID) ON DELETE CASCADE ON UPDATE CASCADE

4.3. ON DELETE and ON UPDATE Actions


问:
Auto add a product for cart item from specific product categories in WooCommerce
I have a code to add a product (a deposit) automatically to a customers cart, no matter what product he has chosen - with the code below inside the functions.php. This works fine.

But now, how to extend the code that this product will only be automatically added to the cart when the customer has chosen a product from a specific product category? E.g. the deposit shouldn't be added to the cart when a customer buys a gift card.

Thanks a lot!

```<code>/**
 * Automatically adds product to cart on visit
 */
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
    if ( ! is_admin() ) {
        $product_id = 1267; //product added automatically
        $found = false;
        //check if product already in cart
        if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
            foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
                $_product = $values['data'];
                if ( $_product->get_id() == $product_id )
                    $found = true;
            }
            // if product not found, add it
            if ( ! $found )
                WC()->cart->add_to_cart( $product_id );
        } else {

        }
    }
}
</code>```

答:
You will have to use the Wordpress conditional function hast_term() in a completely different way.

The following code will auto add to cart a pre-defined product, if a product from a product category is already in cart:

```<code>add_action( 'woocommerce_before_calculate_totals', 'auto_add_item_based_on_product_category', 10, 1 );
function auto_add_item_based_on_product_category( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    $required_categories = array('t-shirts'); // Required product category(ies)
    $added_product_id = 1267; // Specific product to be added automatically
    $matched_category = false;

    // Loop through cart items
    foreach ( $cart->get_cart() as $item_key => $item ) {
        // Check for product category
        if( has_term( $required_categories, 'product_cat', $item['product_id'] ) ) {
            $matched_category = true;
        }
        // Check if specific product is already auto added
        if( $item['data']->get_id() == $added_product_id ) {
            $saved_item_key = $item_key; // keep cart item key
        }
    }

    // If specific product is already auto added but without items from product category
    if ( isset($saved_item_key) && ! $matched_category ) {
        $cart->remove_cart_item( $saved_item_key ); // Remove specific product
    }
    // If there is an item from defined product category and specific product is not in cart
    elseif ( ! isset($saved_item_key) && $matched_category ) {
        $cart->add_to_cart( $added_product_id ); // Add specific product
    }
}
</code>```

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Body:
I have a code to add a product (a deposit) automatically to a customers cart, no matter what product he has chosen - with the code below inside the functions.php. This works fine.

But now, how to extend the code that this product will only be automatically added to the cart when the customer has chosen a product from a specific product category? E.g. the deposit shouldn't be added to the cart when a customer buys a gift card.

Thanks a lot!

/**
 * Automatically adds product to cart on visit
 */
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
    if ( ! is_admin() ) {
        $product_id = 1267; //product added automatically
        $found = false;
        //check if product already in cart
        if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
            foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
                $_product = $values['data'];
                if ( $_product->get_id() == $product_id )
                    $found = true;
            }
            // if product not found, add it
            if ( ! $found )
                WC()->cart->add_to_cart( $product_id );
        } else {

        }
    }
}

Body:
You will have to use the Wordpress conditional function hast_term() in a completely different way.

The following code will auto add to cart a pre-defined product, if a product from a product category is already in cart:

add_action( 'woocommerce_before_calculate_totals', 'auto_add_item_based_on_product_category', 10, 1 );
function auto_add_item_based_on_product_category( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    $required_categories = array('t-shirts'); // Required product category(ies)
    $added_product_id = 1267; // Specific product to be added automatically
    $matched_category = false;

    // Loop through cart items
    foreach ( $cart->get_cart() as $item_key => $item ) {
        // Check for product category
        if( has_term( $required_categories, 'product_cat', $item['product_id'] ) ) {
            $matched_category = true;
        }
        // Check if specific product is already auto added
        if( $item['data']->get_id() == $added_product_id ) {
            $saved_item_key = $item_key; // keep cart item key
        }
    }

    // If specific product is already auto added but without items from product category
    if ( isset($saved_item_key) && ! $matched_category ) {
        $cart->remove_cart_item( $saved_item_key ); // Remove specific product
    }
    // If there is an item from defined product category and specific product is not in cart
    elseif ( ! isset($saved_item_key) && $matched_category ) {
        $cart->add_to_cart( $added_product_id ); // Add specific product
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.


问:
Running RabbitMQ+Celery in the same server as production environment
I'm running a Django app in an EC2 instance, which uses RabbitMQ + Celery for task queuing. Are there any drawbacks to running my RabbitMQ node from the same EC2 instance as my production app?</p>

答:
The answer to this questions really depends on the context of your application.

When you're faced with scenarios you should always consider a few things.

Seperation of concerns
Here, we want to make sure that if one of the systems are not responsible for the running of other systems. This includes things like

If the ec2 instance running all the stuff goes down, will the remaining tasks in queue continue running

if my RAM is full, will all systems remain functioning

Can I scale just one segment of my app without having to redesign infrastructure.

By having rabbit and django (with some kind of service, wsgi, gunicorn, waitress etc) all on one box, you loose a lot of resource contingency.

Although RAM and CPU may be abundant, there is a limit to IO, disk writes, network writes etc. This means that if for some reason you have a heavy write function, all other systems may suffer as a result. If you have a heavy write to RAM funciton, the same applies.

So really the downfalls from keeping things in one system that I can see from your question and my own experience are as follows.

Multiple points of failure. If your one instance of rabbit fails, your queues and tasks stop working.

If your app starts generating big traffic, other systems start to contend for recourses.

If any component goes down, that could mean other downtime of other services.

System downtime means complete downtime of all components.

Lots of headaches when your application demands more resources with minimal downtime.

Lots of web traffic will slow down task running

Lots of task running will slow down web requests

Lots of IO will slow down all the things

The rule of thumb that I usually follow is keep single points of failures far from each other - that way you only need to manage those components. A good use case for this would be to use an EC2 instance for your app, another for your workers and another for your rabbit. That way you can apply smaller/bigger instances for just those components if you need to. You can even create AMIs and create autoscaling groups - if it is your use case.

Here are some articles for reference

Seperation of concern

Modern design architectures

Single points of failure


问:
How to properly login to use private images from GCR in Gitlab-ci?
I'm trying to login into CGR and use some private docker images in Gitlab-ci runner.

I have made a new project in Google Cloud and activated the Google Cloud Registry API. I also made a new Service Account (IAM) in which I gave ownership permission to the previous Cloud Registry instance. Then I produced a json key. I tested the key with the following gitlab-ci configuration and in the local machine:

```<code>image: docker:latest
services:
  - docker:dind
auth:
  stage: auth
  script:
    - docker login -u _json_key --password-stdin https://gcr.io < ./keyfile.json
</code>```

It seems to be authenticated and authorised to push/pull images.

What I need to do is to have the following, I need to go to my private repository and use those images in the gitlab-ci runner. Something like this:

```<code>before_script:
    - docker login -u _json_key --password-stdin https://gcr.io < ./keyfile.json

build:
  stage: build
  image: gcr.io/image-repo/image
  script:
    - gradle clean build

deploy:
  stage: deploy
  image: gcr.io/image-repo/image
  script:
    - gradle publish
  only:
    - master
</code>```

However, I keep on getting this error:

Running with gitlab-runner 11.10.1 (1f513601)   on docker-auto-scale
  0277ea0f Using Docker executor with image gcr.io/image-repo/image ...
  Pulling docker image gcr.io/image-repo/image ... ERROR: Preparation
  failed: Error response from daemon: unauthorized: You don't have the
  needed permissions to perform this operation, and you may have invalid
  credentials. To authenticate your request, follow the steps in:
  https://cloud.google.com/container-registry/docs/advanced-authentication
  (executor_docker.go:168:0s) Will be retried in 3s ...

答:
I achieved a practical solution:

One needs to use the wind service to have a reseted docker configuration and then login, for instance in their local machine using:

```<code>docker login -u _json_key --password-stdin https://gcr.io < ./keyfile.json
</code>```

Then, just just copy the configuration present in ~/.docker/config.json
to the variable DOCKER_AUTH_CONFIG in Gitlab CI and you're set to go.

Body:
I'm trying to login into CGR and use some private docker images in Gitlab-ci runner.

I have made a new project in Google Cloud and activated the Google Cloud Registry API. I also made a new Service Account (IAM) in which I gave ownership permission to the previous Cloud Registry instance. Then I produced a json key. I tested the key with the following gitlab-ci configuration and in the local machine:

image: docker:latest
services:
  - docker:dind
auth:
  stage: auth
  script:
    - docker login -u _json_key --password-stdin https://gcr.io < ./keyfile.json

It seems to be authenticated and authorised to push/pull images.

What I need to do is to have the following, I need to go to my private repository and use those images in the gitlab-ci runner. Something like this:

before_script:
    - docker login -u _json_key --password-stdin https://gcr.io < ./keyfile.json

build:
  stage: build
  image: gcr.io/image-repo/image
  script:
    - gradle clean build

deploy:
  stage: deploy
  image: gcr.io/image-repo/image
  script:
    - gradle publish
  only:
    - master

However, I keep on getting this error:

Running with gitlab-runner 11.10.1 (1f513601)   on docker-auto-scale
  0277ea0f Using Docker executor with image gcr.io/image-repo/image ...
  Pulling docker image gcr.io/image-repo/image ... ERROR: Preparation
  failed: Error response from daemon: unauthorized: You don't have the
  needed permissions to perform this operation, and you may have invalid
  credentials. To authenticate your request, follow the steps in:
  https://cloud.google.com/container-registry/docs/advanced-authentication
  (executor_docker.go:168:0s) Will be retried in 3s ...

Body:
I achieved a practical solution:

One needs to use the wind service to have a reseted docker configuration and then login, for instance in their local machine using:

docker login -u _json_key --password-stdin https://gcr.io < ./keyfile.json

Then, just just copy the configuration present in ~/.docker/config.json
to the variable DOCKER_AUTH_CONFIG in Gitlab CI and you're set to go.