问:
print x over y in matplotlib python
I am trying to print x over y, but the x/y is not the ideal display. Is there a way to make it look like this one below? (put the horizontal dash/hypen between x and y). Thanks.

```<code>x
_
y
</code>```

答:
You can use the mathtext syntax like this:</p>

```<code>plot.text(1, 1, r'$\frac{x}{y}$')
</code>```

Title: print x over y in matplotlib python

Body:
I am trying to print x over y, but the x/y is not the ideal display. Is there a way to make it look like this one below? (put the horizontal dash/hypen between x and y). Thanks.

x
_
y

Body:
You can use the mathtext syntax like this:

plot.text(1, 1, r'$\frac{x}{y}$')


来源: stackexchange

问:
How can i create an autocomplete with Jquery?
I'm creating a Django site, on a certain template i added an Ajax form and i would like to add an autocomplete feature, in order to make navigation easier.

My main problem is that the data i should search is a JSON array of objects, while most of the solutions i found work with normal arrays.

Here is what i have now:

```<code><script>
    $(document).ready(function(){
        // Defining the local dataset
        $.getJSON('http://127.0.0.1:8000/myapi/', function(data) {
          console.log(data)
          //Autocomplete
        });
    });
</script>

<input type="text" id='firstfield' name='input_val'>
</code>```

This is what the data looks like, it's around 700 records; here are the first three:

```<code>"results": [
        {
            "item": "First",
            "id": "1847",
        },
        {
            "item": "Second",
            "id": "4442",
        },
        {
            "item": "Third",
            "id": "3847",
        }]
</code>```

I need this to be as fast as possible. Is there a JQuery/Ajax native solution for this? Or is there a specific library to do this? Any advice or solution is appreciated, thanks in advance!

答:
Try this one:</p>

```<code>  <!doctype html>
        <html lang="en">
        <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <title>jQuery UI Autocomplete - Default functionality</title>
          <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
          <link rel="stylesheet" href="/resources/demos/style.css">
          <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
          <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
          <script>
             $(document).ready(function(){
            // Defining the local dataset
            $.getJSON('http://127.0.0.1:8000/myapi/', function(data) {
              console.log(data)
            $( "#tags" ).autocomplete({
              source: data
            });
            });
        });
          </script>
        </head>
        <body>

        <div class="ui-widget">
          <label for="tags">Tags: </label>
          <input id="tags">
        </div>

        </body>
        </html>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm creating a Django site, on a certain template i added an Ajax form and i would like to add an autocomplete feature, in order to make navigation easier.

My main problem is that the data i should search is a JSON array of objects, while most of the solutions i found work with normal arrays.

Here is what i have now:

<input type="text" id='firstfield' name='input_val'>

This is what the data looks like, it's around 700 records; here are the first three:

"results": [
        {
            "item": "First",
            "id": "1847",
        },
        {
            "item": "Second",
            "id": "4442",
        },
        {
            "item": "Third",
            "id": "3847",
        }]

I need this to be as fast as possible. Is there a JQuery/Ajax native solution for this? Or is there a specific library to do this? Any advice or solution is appreciated, thanks in advance!

Body:
Try this one:

  <!doctype html>
        <html lang="en">
        <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <title>jQuery UI Autocomplete - Default functionality</title>
          <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
          <link rel="stylesheet" href="/resources/demos/style.css">
          <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
          <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
          <script>
             $(document).ready(function(){
            // Defining the local dataset
            $.getJSON('http://127.0.0.1:8000/myapi/', function(data) {
              console.log(data)
            $( "#tags" ).autocomplete({
              source: data
            });
            });
        });
          </script>
        </head>
        <body>

        <div class="ui-widget">
          <label for="tags">Tags: </label>
          <input id="tags">
        </div>

        </body>
        </html>


问:
Arrays , replacing the first to another array with columnsto rows
I was learning arrays for like 3 to 4 days , and I get stuck on this task.
What actually i need to do is replacing the values from first to second array but the column needs to be one half and that half to replace in rows.
 For example:
 We insert
 for n = 3;
then the first array column is n*2
Like this

```<code>1,2,3,4,5,6
7,8,9,10,11,12
13,14,15,16,17,18

</code>```

And the exit need to be

```<code>1,2,3
7,8,9
13,14,15
4,5,6
10,11,12
16,17,18
</code>```

And the code that i write

```<code>#include <stdio.h>
int main ()
{
    int n,m;
    scanf("%d",&n);
    int a=n*2,b=n;
    m=n*2;
    int firstarray[n][m],secondarray[a][b];
    int i,j,k,l;
    for(i=0;i<n;i++)
        for(j=0;j<m;j++)
        scanf("%d",&firstarray[n][m]);

        for(i=0;i<n;i++)
            for(j=0;j<m/2;j++)
            secondarray[i][j]=firstarray[i][j];

        for(i=0;i<n;i++){
            for(j=m/2;j<m;j++)
            {
                for(k=n;k<a;k++)
                    for(l=0;l<b;l++)
                    secondarray[k][l]=firstarray[i][j];
            }
        }

        for(i=0;i<a;i++)
        {
             for(j=0;j<b;j++){
                 printf("%d",secondarray[i][j]);
              }
             printf("\n");
         }
}
</code>```

答:
In this section, the scanf statement is attempting to access an array element that is out of bounds :

```<code>for(i=0;i<n;i++)
        for(j=0;j<m;j++)
        scanf("%d",&firstarray[n][m]);//use i,j indexes, not n,m initializers
</code>```

I think this is probably just a typo, but using n & m this way exceeds the bounds of the array by 1 in each dimension.

Change to:

```<code>for(i=0;i<n;i++)
        for(j=0;j<m;j++)
        scanf("%d",&firstarray[i][j]);
                               ^  ^
</code>```

Note that there are other problems downstream in your logic to do what you are showing.  It is not a simple  transpose where given your example input, the result would be:

```<code>1, 7, 13
2, 8, 14
3, 9, 15
4, 10, 16
5, 11, 17
6, 12, 18
</code>```

Keeping in mind the shape of your original array is stored in memory as a contiguous series of int locations:

```<code>|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|
</code>```

So to do what you show the first loop series will need to assign values to the [6][3] array by a combination of picking the 1st three in memory, skip the next 3, and so on:

```<code>|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|
 ^ ^ ^       ^ ^ ^          ^  ^  ^
</code>```

Then to pick up the rest, start by skipping 3, assigning 3, skipping..., and so on.

```<code>|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|
       ^ ^ ^       ^  ^  ^           ^  ^  ^
</code>```

This then requires playing with the indexing to get this transformation, so given your arrays are created as:

```<code>m=n*2;
int firstarray[n][m],secondarray[m][n];
</code>```

And the inputs are given as shown in your post, populating secondarray is done in 2-stages:

```<code>    //get first 3 of 6 columns
    for(i=0;i<n;i++)
    {
        for(j=0;j<m/2;j++)
        {
            secondarray[i][j]=firstarray[i][j];
        }
    }

    //get second 3 of 6 columns
    for(i=0;i<n;i++)
    {
        for(j=3;j<m;j++)
        {
            secondarray[i+3][j-3]=firstarray[i][j];
        }
    }
</code>```

Body:
I was learning arrays for like 3 to 4 days , and I get stuck on this task.
What actually i need to do is replacing the values from first to second array but the column needs to be one half and that half to replace in rows.
 For example:
 We insert
 for n = 3;
then the first array column is n*2
Like this

1,2,3,4,5,6
7,8,9,10,11,12
13,14,15,16,17,18

And the exit need to be

1,2,3
7,8,9
13,14,15
4,5,6
10,11,12
16,17,18

And the code that i write

#include <stdio.h>
int main ()
{
    int n,m;
    scanf("%d",&n);
    int a=n*2,b=n;
    m=n*2;
    int firstarray[n][m],secondarray[a][b];
    int i,j,k,l;
    for(i=0;i<n;i++)
        for(j=0;j<m;j++)
        scanf("%d",&firstarray[n][m]);

        for(i=0;i<n;i++)
            for(j=0;j<m/2;j++)
            secondarray[i][j]=firstarray[i][j];

        for(i=0;i<n;i++){
            for(j=m/2;j<m;j++)
            {
                for(k=n;k<a;k++)
                    for(l=0;l<b;l++)
                    secondarray[k][l]=firstarray[i][j];
            }
        }

        for(i=0;i<a;i++)
        {
             for(j=0;j<b;j++){
                 printf("%d",secondarray[i][j]);
              }
             printf("\n");
         }
}

Body:
In this section, the scanf statement is attempting to access an array element that is out of bounds :

for(i=0;i<n;i++)
        for(j=0;j<m;j++)
        scanf("%d",&firstarray[n][m]);//use i,j indexes, not n,m initializers

I think this is probably just a typo, but using n & m this way exceeds the bounds of the array by 1 in each dimension.

Change to:

for(i=0;i<n;i++)
        for(j=0;j<m;j++)
        scanf("%d",&firstarray[i][j]);
                               ^  ^

Note that there are other problems downstream in your logic to do what you are showing.  It is not a simple  transpose where given your example input, the result would be:

1, 7, 13
2, 8, 14
3, 9, 15
4, 10, 16
5, 11, 17
6, 12, 18

Keeping in mind the shape of your original array is stored in memory as a contiguous series of int locations:

|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|

So to do what you show the first loop series will need to assign values to the [6][3] array by a combination of picking the 1st three in memory, skip the next 3, and so on:

|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|
 ^ ^ ^       ^ ^ ^          ^  ^  ^

Then to pick up the rest, start by skipping 3, assigning 3, skipping..., and so on.

|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|
       ^ ^ ^       ^  ^  ^           ^  ^  ^

This then requires playing with the indexing to get this transformation, so given your arrays are created as:

m=n*2;
int firstarray[n][m],secondarray[m][n];

And the inputs are given as shown in your post, populating secondarray is done in 2-stages:

    //get first 3 of 6 columns
    for(i=0;i<n;i++)
    {
        for(j=0;j<m/2;j++)
        {
            secondarray[i][j]=firstarray[i][j];
        }
    }

    //get second 3 of 6 columns
    for(i=0;i<n;i++)
    {
        for(j=3;j<m;j++)
        {
            secondarray[i+3][j-3]=firstarray[i][j];
        }
    }


问:
Async variable stored in $rootScope not available in other controllers
I am using Angular 1.x for my stack and when I make an API call and store the response in the $rootScope, it is not accessible in other controllers' view.

My controller:

```<code>angularApp.controller('mainController', ['$scope', '$rootScope', '$http', function($scope, $rootScope, $http){

  var checkIfAuthenticated = function(){
    return $http.get('/api/isAuthenticated');
  };

  checkIfAuthenticated()
  .then(function(res) {
    if(res.status===200){
        console.log("Success");
        $rootScope.userLoggedIn = true;
    }
  })
}]);
</code>```

Now, in another controller's view I use it like this:

```<code><div ng-if="userLoggedIn" class="py-1 pl-1 pr-1">
  <span><b>Message Board</b></span>
  <div class="form-control" readonly id="lockTextbox">Show something</div>
</div>
</code>```

The problem is, the API call /api/isAuthenticated does provide the right response (status 200) but the ng-view gets it wrong.

I am sure this is to do with $rootScope.userLoggedIn being a response from an async call (as I get Success in my console) but how do I solve it?

Thanks in advance!

EDIT

After I posted the question, I noticed that in the mainController's view, the ng-if logic doesn't work either. What is very strange is that when I open up the browser's debug console, it starts working! I think this is just an async issue but I don't know how to solve it. How do I tell the view that the variable is on it's way?

答:
OK, to solve the timing issue, I'll rework the answer completely. This should be a - quick and dirty but - working example:

index.html

```<code><html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <script src="script.js"></script>
  </head>

  <body ng-app="plunker" ng-cloak>
    <div ng-controller="MainCtrl as $ctrl">
      <h1>Hello {{$ctrl.name}}</h1>
      <p>Start editing and see your changes reflected here!</p>
      <div ng-if="$ctrl.name === 'Angular.js'"><b>Message Board</b</div>
    </div>
  </body>
</html>
</code>```

script.js

```<code>import angular from 'angular';

angular.module('plunker', []).controller('MainCtrl', function($scope, $http) {
  const self = this;
  self.name = 'Plunker';
  console.log('hello');

  function checkIfAuthenticated(){
    console.log('get');
   return $http.get('https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js');
  };

  checkIfAuthenticated().then(function(res) {
    if(res.status===200){
        console.log('Success');
        self.name = 'Angular.js'; // insert any logic here
    } else {
      console.log('Failed');
    }
  })
});
</code>```

Console

```<code>hello
get
Success
</code>```

Does it work for you?

Body:
I am using Angular 1.x for my stack and when I make an API call and store the response in the $rootScope, it is not accessible in other controllers' view.

My controller:

angularApp.controller('mainController', ['$scope', '$rootScope', '$http', function($scope, $rootScope, $http){

  var checkIfAuthenticated = function(){
    return $http.get('/api/isAuthenticated');
  };

  checkIfAuthenticated()
  .then(function(res) {
    if(res.status===200){
        console.log("Success");
        $rootScope.userLoggedIn = true;
    }
  })
}]);

Now, in another controller's view I use it like this:

  Message Board

Show something

The problem is, the API call /api/isAuthenticated does provide the right response (status 200) but the ng-view gets it wrong.

I am sure this is to do with $rootScope.userLoggedIn being a response from an async call (as I get Success in my console) but how do I solve it?

Thanks in advance!

EDIT

After I posted the question, I noticed that in the mainController's view, the ng-if logic doesn't work either. What is very strange is that when I open up the browser's debug console, it starts working! I think this is just an async issue but I don't know how to solve it. How do I tell the view that the variable is on it's way?

Body:
OK, to solve the timing issue, I'll rework the answer completely. This should be a - quick and dirty but - working example:

index.html

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <script src="script.js"></script>
  </head>

  <body ng-app="plunker" ng-cloak>
    <div ng-controller="MainCtrl as $ctrl">
      <h1>Hello {{$ctrl.name}}</h1>
      <p>Start editing and see your changes reflected here!</p>
      <div ng-if="$ctrl.name === 'Angular.js'"><b>Message Board</b</div>
    </div>
  </body>
</html>

script.js

import angular from 'angular';

angular.module('plunker', []).controller('MainCtrl', function($scope, $http) {
  const self = this;
  self.name = 'Plunker';
  console.log('hello');

  function checkIfAuthenticated(){
    console.log('get');
   return $http.get('https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js');
  };

  checkIfAuthenticated().then(function(res) {
    if(res.status===200){
        console.log('Success');
        self.name = 'Angular.js'; // insert any logic here
    } else {
      console.log('Failed');
    }
  })
});

Console

hello
get
Success

Does it work for you?


问:
how to show error message in basic authentication?
Using PHP, I have implemented Basic Authentication as follows:

```<code>if ((isset($_SERVER['PHP_AUTH_USER']) && $_SERVER['PHP_AUTH_USER']=='') || (isset($_SERVER['PHP_AUTH_PW']) && $_SERVER['PHP_AUTH_PW']=='')) {
    header('WWW-Authenticate: Basic realm="Authentification"');
    $UsrId = $objLDAP->authenticateUser();
    die();
} elseif (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
    $UsrId = $objLDAP->authenticateUser($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
}else{
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo '<script>window.location.reload();</script>';
    //$UsrId = $objLDAP->authenticateUser();
    //$smarty->display($templates['budWithoutAnyAccess']);
    die();
}
if ($pUser){
 //coding
}else{
    header('HTTP/1.1 401 Authorization Required');
    header('WWW-Authenticate: Basic realm="Access denied"');
    $UsrId = $objLDAP->authenticateUser();
}
</code>```

It opens up the login popup.

If user provides the wrong credentials, I can show error message on page but on page re-fresh it should open the Authentication login pop-up as well.

On cancel also, I want to show message and on refresh, it should open the Authentication login pop-up.

How can I do that?

Thank you,
Trupti

答:
Please check this! </p>

```<code> if (!isset($_SERVER['PHP_AUTH_USER']))
    {
        header('WWW-Authenticate: Basic realm="Sally Port"');
        header('HTTP/1.0 401 Unauthorized');
        echo 'Click <a href="login.php">here</a> to reload';
        exit;
    }

    if(checkLDAPUser($ldapServername))
    {
        // If ldap authentican is successful then redirect the user to gateway.php
        header("location:gateway.php");
    }
    else
    {
        //Clear global variables.
        unset($_SERVER['PHP_AUTH_USER']);
        unset($_SERVER['PHP_AUTH_PW']);

    //  If the password is incorrect, show popup until the password is correct.
        while(checkLDAPUser($ldapServername)!=1)
        {
            unset($_SERVER['PHP_AUTH_USER']);
            unset($_SERVER['PHP_AUTH_PW']);
            header('WWW-Authenticate: Basic realm="Sally Port"');
            header('HTTP/1.0 401 Unauthorized');
            echo 'Click <a href="login.php">here</a> to reload';
            exit;
        }
    }
function checkLDAPUser($ldapServername)
{
    $username=$_SERVER['PHP_AUTH_USER'];
    $password=$_SERVER['PHP_AUTH_PW'];

    //$adServer = "ldap.".$ldapServername.".com";
    $adServer = "ldap://bchq-dc-v1.blackcreek.local";
    $ldap = ldap_connect($adServer);
if($ldap)
{WriteLog("LDAP connected");

}
else
{WriteLog("LDAP Failed");

}
    $ldaprdn = "cn=read-only-admin,dc=example,dc=com";
    ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
    $bind = @ldap_bind($ldap, $ldaprdn, $password);
    //Set up session if connect is successful.
    if($bind)
    {
        return 1;
    }
    else
    {console.log("LDAP Username and Passwords are incorrect");

        return 0;
    }
}
</code>```

Body:
Using PHP, I have implemented Basic Authentication as follows:

if ((isset($_SERVER['PHP_AUTH_USER']) && $_SERVER['PHP_AUTH_USER']=='') || (isset($_SERVER['PHP_AUTH_PW']) && $_SERVER['PHP_AUTH_PW']=='')) {
    header('WWW-Authenticate: Basic realm="Authentification"');
    $UsrId = $objLDAP->authenticateUser();
    die();
} elseif (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
    $UsrId = $objLDAP->authenticateUser($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
}else{
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo '';
    //$UsrId = $objLDAP->authenticateUser();
    //$smarty->display($templates['budWithoutAnyAccess']);
    die();
}
if ($pUser){
 //coding
}else{
    header('HTTP/1.1 401 Authorization Required');
    header('WWW-Authenticate: Basic realm="Access denied"');
    $UsrId = $objLDAP->authenticateUser();
}

It opens up the login popup.

If user provides the wrong credentials, I can show error message on page but on page re-fresh it should open the Authentication login pop-up as well.

On cancel also, I want to show message and on refresh, it should open the Authentication login pop-up.

How can I do that?

Thank you,
Trupti

Body:
Please check this!

 if (!isset($_SERVER['PHP_AUTH_USER']))
    {
        header('WWW-Authenticate: Basic realm="Sally Port"');
        header('HTTP/1.0 401 Unauthorized');
        echo 'Click <a href="login.php">here</a> to reload';
        exit;
    }

    if(checkLDAPUser($ldapServername))
    {
        // If ldap authentican is successful then redirect the user to gateway.php
        header("location:gateway.php");
    }
    else
    {
        //Clear global variables.
        unset($_SERVER['PHP_AUTH_USER']);
        unset($_SERVER['PHP_AUTH_PW']);

    //  If the password is incorrect, show popup until the password is correct.
        while(checkLDAPUser($ldapServername)!=1)
        {
            unset($_SERVER['PHP_AUTH_USER']);
            unset($_SERVER['PHP_AUTH_PW']);
            header('WWW-Authenticate: Basic realm="Sally Port"');
            header('HTTP/1.0 401 Unauthorized');
            echo 'Click <a href="login.php">here</a> to reload';
            exit;
        }
    }
function checkLDAPUser($ldapServername)
{
    $username=$_SERVER['PHP_AUTH_USER'];
    $password=$_SERVER['PHP_AUTH_PW'];

    //$adServer = "ldap.".$ldapServername.".com";
    $adServer = "ldap://bchq-dc-v1.blackcreek.local";
    $ldap = ldap_connect($adServer);
if($ldap)
{WriteLog("LDAP connected");

}
else
{WriteLog("LDAP Failed");

}
    $ldaprdn = "cn=read-only-admin,dc=example,dc=com";
    ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
    $bind = @ldap_bind($ldap, $ldaprdn, $password);
    //Set up session if connect is successful.
    if($bind)
    {
        return 1;
    }
    else
    {console.log("LDAP Username and Passwords are incorrect");

        return 0;
    }
}


问:
java Play add jar to lib
I'm trying to add org.json.simple.

I have created my lib folder in root and added the jar file and restarted my project with sbt run.

I still get package org.json.simple does not exist.

I tried to add to the build.sbt (this did not work):

```<code>libraryDependencies += "org.json.simple.JSONArray% "JSONArray" % "3.1.1"
libraryDependencies += "org.json.simple.JSONObject% "JSONObject" % "3.1.1"
</code>```

IDE: VS Code

System: MAC

答:
You need to add dependencies to libaries in libraryDependencies. Right now, you are trying to specify classes, which will not work.

Instead, you need to use

```<code>libraryDependencies += "com.github.cliftonlabs" % "json-simple" % "3.1.1"
</code>```

Note that above dependency is probably not the one you need, as it uses a different package and class names, I picked it as it has the same version as you specify. Maybe you need to use "com.googlecode.json-simple" % "json-simple" % "1.1.1" instead.

Title: java Play add jar to lib

Body:
I'm trying to add org.json.simple.

I have created my lib folder in root and added the jar file and restarted my project with sbt run.

I still get package org.json.simple does not exist.

I tried to add to the build.sbt (this did not work):

libraryDependencies += "org.json.simple.JSONArray% "JSONArray" % "3.1.1"
libraryDependencies += "org.json.simple.JSONObject% "JSONObject" % "3.1.1"

IDE: VS Code

System: MAC

Body:
You need to add dependencies to libaries in libraryDependencies. Right now, you are trying to specify classes, which will not work.

Instead, you need to use

libraryDependencies += "com.github.cliftonlabs" % "json-simple" % "3.1.1"

Note that above dependency is probably not the one you need, as it uses a different package and class names, I picked it as it has the same version as you specify. Maybe you need to use "com.googlecode.json-simple" % "json-simple" % "1.1.1" instead.


问:
Why do I get a Rust compilation error when combining higher-rank trait bounds with associated types?
I am writing some Rust code that involves generic traits and non-'static types, and as a result I have come across the need to approximate generic associated types. I understand that GATs can't be emulated elegantly in current Rust, but I thought I had figured out an (inelegant) workaround that would work for my specific situation, using traits with lifetime parameters and higher-rank trait bounds. However, I am getting compiler errors that I don't understand, regarding missing trait implementations for associated types.

The following code shows a minimal example that reproduces the error.

use std::fmt::Debug;

trait Resource<'r> {
    type Value;
}

struct ResourceImpl();

impl<'r> Resource<'r> for ResourceImpl {
    type Value = u32;
}

fn test_generic<R>()
where
    for<'r> R: Resource<'r>,
    for<'r> <R as Resource<'r>>::Value: Debug,
{
}

fn test_specific() {
    test_generic::<ResourceImpl>();
}
```

<p>When I try to compile this code (<code>rustc</code> 1.41.0), I get the following error message.</p>

<pre class="lang-none prettyprint-override"><code>error[E0277]: `<ResourceImpl as Resource<'r>>::Value` doesn't implement `std::fmt::Debug`
  --> src/lib.rs:21:5
   |
13 | fn test_generic<R>()
   |    ------------
...
16 |     for<'r> <R as Resource<'r>>::Value: Debug,
   |                                         ----- required by this bound in `test_generic`
...
21 |     test_generic::<ResourceImpl>();
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `<ResourceImpl as Resource<'r>>::Value` cannot be formatted using `{:?}` because it doesn't implement `std::fmt::Debug`
   |
   = help: the trait `for<'r> std::fmt::Debug` is not implemented for `<ResourceImpl as Resource<'r>>::Value`
</code>```

The error message sounds like it is saying u32 doesn't implement Debug, which wouldn't make sense. I must be misunderstanding what the error message means, but I can't figure out what the actual problem is.

答:
There is an open issue about this problem.

In your case a workaround could be to bind Debug to the associated type Resource::Value?

```<code>trait Resource<'r> {
    type Value: Debug;
}.
</code>```

Body:
I am writing some Rust code that involves generic traits and non-'static types, and as a result I have come across the need to approximate generic associated types. I understand that GATs can't be emulated elegantly in current Rust, but I thought I had figured out an (inelegant) workaround that would work for my specific situation, using traits with lifetime parameters and higher-rank trait bounds. However, I am getting compiler errors that I don't understand, regarding missing trait implementations for associated types.

The following code shows a minimal example that reproduces the error.

use std::fmt::Debug;

trait Resource<'r> {
    type Value;
}

struct ResourceImpl();

impl<'r> Resource<'r> for ResourceImpl {
    type Value = u32;
}

fn test_generic<R>()
where
    for<'r> R: Resource<'r>,
    for<'r> <R as Resource<'r>>::Value: Debug,
{
}

fn test_specific() {
    test_generic::<ResourceImpl>();
}

When I try to compile this code (rustc 1.41.0), I get the following error message.

error[E0277]: `<ResourceImpl as Resource<'r>>::Value` doesn't implement `std::fmt::Debug`
  --> src/lib.rs:21:5
   |
13 | fn test_generic<R>()
   |    ------------
...
16 |     for<'r> <R as Resource<'r>>::Value: Debug,
   |                                         ----- required by this bound in `test_generic`
...
21 |     test_generic::<ResourceImpl>();
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `<ResourceImpl as Resource<'r>>::Value` cannot be formatted using `{:?}` because it doesn't implement `std::fmt::Debug`
   |
   = help: the trait `for<'r> std::fmt::Debug` is not implemented for `<ResourceImpl as Resource<'r>>::Value`

The error message sounds like it is saying u32 doesn't implement Debug, which wouldn't make sense. I must be misunderstanding what the error message means, but I can't figure out what the actual problem is.

Body:
There is an open issue about this problem.

In your case a workaround could be to bind Debug to the associated type Resource::Value?

trait Resource<'r> {
    type Value: Debug;
}.


问:
Javascript: increase end variables
I would like to know a simple way to increase the end of a variable with an incremental number, then check it later.

For example creating var using with a for loop or a different method

Example:

```<code>var example0=new Date(property.time);
var example1=new Date(property.time);
var example2=new Date(property.time);
var example3=new Date(property.time);
</code>```

UPDATE

thanks for the answer, I don't know whether to open another discussion but I actually underestimated the question believing to solve my problem, in reality the situation is more complex, I explain myself better:
I tried to use an array like:

```<code>let startArray =[];
let endArray =[];

for(i=0; i< 4; i++) {
   for(j=1; j< 5; j++) {
      startArray.push new Date(demoTracks[0].properties.time[i]);
      endArray.push new Date(demoTracks[0].properties.time[j]);
   }
}

  // Get start/end times
  var timelineData = new vis.DataSet([{start: startArray[i], end:
  endArray[i],
  content: 'Tracks' }]);
}
</code>```

but for my distraction in writing (I thought I could solve this way) what I would need is to break start time from end time to get two separate fragments.

putting everything in an array and not getting the result because it cannot separate properties.time[0] from properties.time[1] which also need to be incremented separately. I show exactly what I need:

```<code>var startTime1 = new Date(demoTracks[0].properties.time[0]);
var endTime1 = new Date(demoTracks[0].properties.time[1]);
var startTime2 = new Date(demoTracks[0].properties.time[1]);
var endTime2 = new Date(demoTracks[0].properties.time[2]);
var startTime3 = new Date(demoTracks[0].properties.time[2]);
var endTime3 = new Date(demoTracks[0].properties.time[3]);
</code>```

to then call in:

```<code>var timelineData = new vis.DataSet([{start: startTime, end: endTime,
content: 'Tracks' },
</code>```

for this I meant as the question how to increase only the end of a variable (which is creating a problem for me) thanks again .

答:
Using you example data set , the below snippet explain in comment how to create a timeline  for one demoTrack feature, using the time array data .

var tillicum = { "type": "Feature", "geometry": { "type": "MultiPoint", "coordinates": [ [-123.77252789, 44.37857221 ], [-123.77317087, 44.37864694 ], [-123.77383407, 44.37875853 ] ] }, "properties": { "title": "tillicum", "path_options": { "color": "red" }, "time": [ 1580403952000, 1580403990000, 1580404202000 ], "altitude": [ 0, 0, 0 ], "raw": [] }, "bbox": [ [-124.09386637, 44.34348063 ], [-124.09386637, 44.56531305 ], [-123.26148271, 44.56531305 ], [-123.26148271, 44.34348063 ] ] };

var demoTracks = [tillicum];

// DOM element where the Timeline will be attached
var container = document.getElementById('timeline');

//get items array for dataset  from below created function
let trackItems = getItemArray(demoTracks[0]);
console.log(trackItems);

// create dataSet
let items = new vis.DataSet(trackItems);

// Configuration for the Timeline
var timelineOptions = {};

// crate vis dataset from items returned by below function

// Create a Timeline
var timeline = new vis.Timeline(container, items, timelineOptions);

// function that returns items in format to create vis dataset element
function getItemArray(demoTracksElement) {
  let timeArray = [];
  try {
    let iter = 0;
    // set length -1 to preent adding last elemnt as timeline element in graph
    for(iter; iter < demoTracksElement.properties.time.length -1 ; iter++ ) {
        timeArray.push({
          id: iter,
          content: 'Tracks '+iter,
          start: demoTracksElement.properties.time[iter],
          end:demoTracksElement.properties.time[iter+1]
        })
    }

    return timeArray;

  } catch (e) {
    console.log(e);
    alert("something went wong with sent data");
    return null;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis-timeline-graph2d.min.css" rel="stylesheet" />

<div id="timeline"></div></code>```

Title: Javascript: increase end variables

Body:
I would like to know a simple way to increase the end of a variable with an incremental number, then check it later.

For example creating var using with a for loop or a different method

Example:

var example0=new Date(property.time);
var example1=new Date(property.time);
var example2=new Date(property.time);
var example3=new Date(property.time);

UPDATE

thanks for the answer, I don't know whether to open another discussion but I actually underestimated the question believing to solve my problem, in reality the situation is more complex, I explain myself better:
I tried to use an array like:

let startArray =[];
let endArray =[];

for(i=0; i< 4; i++) {
   for(j=1; j< 5; j++) {
      startArray.push new Date(demoTracks[0].properties.time[i]);
      endArray.push new Date(demoTracks[0].properties.time[j]);
   }
}

  // Get start/end times
  var timelineData = new vis.DataSet([{start: startArray[i], end:
  endArray[i],
  content: 'Tracks' }]);
}

but for my distraction in writing (I thought I could solve this way) what I would need is to break start time from end time to get two separate fragments.

putting everything in an array and not getting the result because it cannot separate properties.time[0] from properties.time[1] which also need to be incremented separately. I show exactly what I need:

var startTime1 = new Date(demoTracks[0].properties.time[0]);
var endTime1 = new Date(demoTracks[0].properties.time[1]);
var startTime2 = new Date(demoTracks[0].properties.time[1]);
var endTime2 = new Date(demoTracks[0].properties.time[2]);
var startTime3 = new Date(demoTracks[0].properties.time[2]);
var endTime3 = new Date(demoTracks[0].properties.time[3]);

to then call in:

var timelineData = new vis.DataSet([{start: startTime, end: endTime,
content: 'Tracks' },

for this I meant as the question how to increase only the end of a variable (which is creating a problem for me) thanks again .

Body:
Using you example data set , the below snippet explain in comment how to create a timeline  for one demoTrack feature, using the time array data .

var tillicum = { "type": "Feature", "geometry": { "type": "MultiPoint", "coordinates": [ [-123.77252789, 44.37857221 ], [-123.77317087, 44.37864694 ], [-123.77383407, 44.37875853 ] ] }, "properties": { "title": "tillicum", "path_options": { "color": "red" }, "time": [ 1580403952000, 1580403990000, 1580404202000 ], "altitude": [ 0, 0, 0 ], "raw": [] }, "bbox": [ [-124.09386637, 44.34348063 ], [-124.09386637, 44.56531305 ], [-123.26148271, 44.56531305 ], [-123.26148271, 44.34348063 ] ] };

var demoTracks = [tillicum];

// DOM element where the Timeline will be attached
var container = document.getElementById('timeline');

//get items array for dataset  from below created function
let trackItems = getItemArray(demoTracks[0]);
console.log(trackItems);

// create dataSet
let items = new vis.DataSet(trackItems);

// Configuration for the Timeline
var timelineOptions = {};

// crate vis dataset from items returned by below function

// Create a Timeline
var timeline = new vis.Timeline(container, items, timelineOptions);

// function that returns items in format to create vis dataset element
function getItemArray(demoTracksElement) {
  let timeArray = [];
  try {
    let iter = 0;
    // set length -1 to preent adding last elemnt as timeline element in graph
    for(iter; iter < demoTracksElement.properties.time.length -1 ; iter++ ) {
        timeArray.push({
          id: iter,
          content: 'Tracks '+iter,
          start: demoTracksElement.properties.time[iter],
          end:demoTracksElement.properties.time[iter+1]
        })
    }

    return timeArray;

  } catch (e) {
    console.log(e);
    alert("something went wong with sent data");
    return null;
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis-timeline-graph2d.min.css" rel="stylesheet" />

<div id="timeline"></div>


问:
Hangire RecurringJob calling async method
I need to implement some recurring jobs via Hangfire, and I can't find anything about usage of async method inside RecurringJob.AddOrUpdate method.

RetrieveFriscoProductsJob is the class which has asynchronous method named ProcessAsync(). Should this work or not? Can we add async recurring job in Hangfire? If yes how we should do it properly?

```<code>RecurringJob.AddOrUpdate<RetrieveFriscoProductsJob>(x => x.ProcessAsync(), Cron.Daily, null);
</code>```

答:
Nowadays, Async methods are applicable to Hangfire RecurringJob.AddOrUpdate<>();, however it will be sync under-the-hood anyway.
More details on it

ContentLicense: CC BY-SA 3.0

Body:
I need to implement some recurring jobs via Hangfire, and I can't find anything about usage of async method inside RecurringJob.AddOrUpdate method.

RetrieveFriscoProductsJob is the class which has asynchronous method named ProcessAsync(). Should this work or not? Can we add async recurring job in Hangfire? If yes how we should do it properly?

RecurringJob.AddOrUpdate<RetrieveFriscoProductsJob>(x => x.ProcessAsync(), Cron.Daily, null);


问:
DatePicker Not Working while Cloning in MVC Editable
I am facing issue while executing and cloning datepicker. The base datepicker working fine, however the cloned datepicker not working. Can somebody please help me with this. Struggling to get is solve. Here is what I tried:</p>

```<code><input type="button" class="addbutton" id="addfield_button" style="font-size: x-small; color: blue; vertical-align: middle" value="Add" />

<table id="mitigationsTable">
    <tr><td>@(Html.Kendo().DatePicker().Name("datepicker").Value("10/10/2011").HtmlAttributes(new { type = "text" }))
        </td>
    </tr>
</table>

<script type="text/javascript">
    $(document).ready(function () {
        $("#addfield_button").click(function (e) {
            $("#mitigationsTable tr:first").clone().find("input").each(function () { }).end().appendTo("table");
        });
    });
</code>```

答:
Managed to solve this. Instead of using kendo datepicker to clone from, just make a generic editor in your HTML:

```<code>@Html.Editor("date_0", new { htmlAttributes = new { style="width:100%" } })
</code>```

Whenever you click your clone button, get the new input element and use JQuery to intialize it with kendo date picker:

```<code>$("#mitigationsTable tr:first").clone().find("input").kendoDatePicker();
</code>```

This will make the cloned elements have the datepicker.

In my case, I had the original input in a hidden div. If you make your first tr field hidden then did a clone with initialzing kendo datepicker on document ready, you should be able to have a datepicker by default when the page loads and then allow it to work for subsequent cloning.

Body:
I am facing issue while executing and cloning datepicker. The base datepicker working fine, however the cloned datepicker not working. Can somebody please help me with this. Struggling to get is solve. Here is what I tried:

<input type="button" class="addbutton" id="addfield_button" style="font-size: x-small; color: blue; vertical-align: middle" value="Add" />

@(Html.Kendo().DatePicker().Name("datepicker").Value("10/10/2011").HtmlAttributes(new { type = "text" }))

Body:
Managed to solve this. Instead of using kendo datepicker to clone from, just make a generic editor in your HTML:

@Html.Editor("date_0", new { htmlAttributes = new { style="width:100%" } })

Whenever you click your clone button, get the new input element and use JQuery to intialize it with kendo date picker:

$("#mitigationsTable tr:first").clone().find("input").kendoDatePicker();

This will make the cloned elements have the datepicker.

In my case, I had the original input in a hidden div. If you make your first tr field hidden then did a clone with initialzing kendo datepicker on document ready, you should be able to have a datepicker by default when the page loads and then allow it to work for subsequent cloning.


问:
SIFT, HOG and SURF c++, opencv
I have a simple question, which I want to know, what kind of libraries are available and can give good results for implementing SIFT, HOG(Histogram Oriented Gradient) and SURF in c++ or opencv?

Hence: 1- Give me the link for the code if you can, which I will be so appreciated.
2- If you know one of them or any kind of information to lead me to what I want, I will be so appreciated as well.

Thanks

答:
Example of surf code in openCV
https://code.ros.org/trac/opencv/browser/trunk/opencv/samples/cpp/matching_to_many_images.cpp</p>

ContentLicense: CC BY-SA 2.5

Title: SIFT, HOG and SURF c++, opencv


问:
What does (*(int *)&(w)) mean in c programming?
I'm learning processes and in the following code snippet:

```<code>/*
 * fork10 - Synchronizing with multiple children (wait)
 * Reaps children in arbitrary order
 * WIFEXITED and WEXITSTATUS to get info about terminated children
 */
void fork10()
{
    pid_t pid[N];
    int i, child_status;

    for (i = 0; i < N; i++)
    if ((pid[i] = fork()) == 0) {
        exit(100+i); /* Child */
    }
    for (i = 0; i < N; i++) { /* Parent */
        pid_t wpid = wait(&child_status);
        if (WIFEXITED(child_status))
            printf("Child %d terminated with exit status %d\n", wpid, WEXITSTATUS(child_status));
        else
            printf("Child %d terminate abnormally\n", wpid);
    }
}
</code>```

when I trace WIFEXITED function definition this is what I've got:

```<code>#define WIFEXITED(x)    (_WSTATUS(x) == 0)
#define _WSTATUS(x) (_W_INT(x) & 0177)
#define _W_INT(w)   (*(int *)&(w))  /* convert union wait to int */
</code>```

I have two questions:

Why use mask 0177 instead of 0b1111111, I've seen it many times, what's the benefits of using octal number over other formats? Personally I find binary more intuitive.

What's the meaning of (*(int *)&(w))?

Thanks!

答:
About your first question: Binary literals are not officially part of the C standard (and are only part of C++ since C++14), hence using octal literals instead of using them can improve portability.

About your second question: &w takes the address of w, which is then converted to a pointer to an int ((int*)&w) which is dereferenced. What that effectively does is read memory from w as though w were an int.

Body:
I'm learning processes and in the following code snippet:

/*
 * fork10 - Synchronizing with multiple children (wait)
 * Reaps children in arbitrary order
 * WIFEXITED and WEXITSTATUS to get info about terminated children
 */
void fork10()
{
    pid_t pid[N];
    int i, child_status;

    for (i = 0; i < N; i++)
    if ((pid[i] = fork()) == 0) {
        exit(100+i); /* Child */
    }
    for (i = 0; i < N; i++) { /* Parent */
        pid_t wpid = wait(&child_status);
        if (WIFEXITED(child_status))
            printf("Child %d terminated with exit status %d\n", wpid, WEXITSTATUS(child_status));
        else
            printf("Child %d terminate abnormally\n", wpid);
    }
}

when I trace WIFEXITED function definition this is what I've got:

#define WIFEXITED(x)    (_WSTATUS(x) == 0)
#define _WSTATUS(x) (_W_INT(x) & 0177)
#define _W_INT(w)   (*(int *)&(w))  /* convert union wait to int */

I have two questions:

Why use mask 0177 instead of 0b1111111, I've seen it many times, what's the benefits of using octal number over other formats? Personally I find binary more intuitive.

What's the meaning of (*(int *)&(w))?

Thanks!


问:
It seems schema.org/Review is not recognized by Google Search anymore or I made a mistake
I have received a message a couple of days ago that Google Search Engine has a problem identifying my ObjectType 'ItemReviewed'.

I am a collaborator on a moviesite and implement schema.org to my reviews.

```<code>    <div itemprop="review" itemscope itemtype="http://schema.org/Review">
    <span itemprop="reviewBody">

    <span itemprop="itemreviewed">Title of the movie</span>

    <IMG>itemprop="image"</IMG>

    <img border="0" src="https://example.com/wp-content/img/30star.png" alt="rating" />
    <div itemprop="reviewRating" itemscope itemtype="http://schema.org/Rating"><meta itemprop="worstRating" content = "0"/>Rating: <span itemprop="ratingValue">3</span> / <span itemprop="bestRating">5</span></div>
    Review by <span itemprop="author">Selina</span> op <meta itemprop="datePublished" content="2020-02-13">13 februari 2020<p></div>

</code>```

Can anybody help me. It worked fine for years up until a few days ago.

NOTE: I know google has recently changed the markup for businesses so the rating is not something self-serving, but this a movieblog and the ratings are rating the movie not the website. Should I use another markup?

We are talking about genuine, independent, and unpaid editorial reviews

答:
does this code looks 'ok' to you or should I add something else, cause there are a lot properties and I would like to have a minimum amount of them, cause I will have to make changes to up to 1000 movie reviews.

movie title
Alfred Hitchcock
<meta itemprop="datePublished" content="2020-02-19">19 februari 2020</meta>

name of the author of the review

<meta itemprop="worstRating" content = "0"/>
Rating: 1 / 5

```

Second question, should I use meta tags or span tags, or doesn't it matter?

Body:
I have received a message a couple of days ago that Google Search Engine has a problem identifying my ObjectType 'ItemReviewed'.

I am a collaborator on a moviesite and implement schema.org to my reviews.

    Title of the movie

    itemprop="image"

<meta itemprop="worstRating" content = "0"/>Rating: 3 / 5

    Review by Selina op <meta itemprop="datePublished" content="2020-02-13">13 februari 2020

Can anybody help me. It worked fine for years up until a few days ago.

NOTE: I know google has recently changed the markup for businesses so the rating is not something self-serving, but this a movieblog and the ratings are rating the movie not the website. Should I use another markup?

We are talking about genuine, independent, and unpaid editorial reviews

Body:
does this code looks 'ok' to you or should I add something else, cause there are a lot properties and I would like to have a minimum amount of them, cause I will have to make changes to up to 1000 movie reviews.

<div itemscope itemtype="http://schema.org/CriticReview">
     <div itemprop="itemReviewed" itemscope itemtype="http://schema.org/Movie">

<span itemprop="name">movie title</span>
<span itemprop="director">Alfred Hitchcock</span>
<meta itemprop="datePublished" content="2020-02-19">19 februari 2020</meta>

<a href="https://example.com/wp-content/img/img_2004_blu-ray.jpg"><img itemprop="image" src="https://example.com/wp-content/img/img_2004_blu-ray.2.jpg"/></a>

     </div>

<span itemprop="author">name of the author of the review</span>

<div itemprop="reviewRating" itemscope itemtype="http://schema.org/Rating">
<meta itemprop="worstRating" content = "0"/>
Rating: <span itemprop="ratingValue">1</span> / <span itemprop="bestRating">5</span>

</div>

Second question, should I use meta tags or span tags, or doesn't it matter?


问:
SQL: Remove two rows and insert a new row into table
I want to replace row pairs (row with name="aaa" appear first and row with name="bbb" appear later, both rows have same id) by a new row with the same id but name="ccc".

Original table:

```<code>timestamp(primary key)        id     name
2020-02-20...                 1      aaa
2020-02-20...                 1      aaa  -----> first row
2020-02-20...                 1      ddd
2020-02-20...                 1      bbb  -----> second row
2020-02-20...                 2      aaa
2020-02-20...                 2      ccc
2020-02-20...                 2      ddd
</code>```

New table:

```<code>timestamp(primary key)        id     name
2020-02-20...                 1      aaa
2020-02-20...                 1      aaa
2020-02-20...                 1      ccc  -----> replaced by this row
2020-02-20...                 1      ddd
2020-02-20...                 2      aaa
2020-02-20...                 2      ccc
2020-02-20...                 2      ddd
</code>```

timestamp is the primary key and it is increasing.

Is it possible to achieve this in PostgresSQL?

答:
If I understand correctly, this should do what you want:</p>

```<code>(select id, name
 from t
 where name not in ('aaa', 'bbb') or
       name = 'aaa' and not exists (select 1 from t t2 where t2.id = t.id and t2.name = 'bbb')  or
       name = 'bbb' and not exists (select 1 from t t2 where t2.id = t.id and t2.name = 'aaa')
) union all
(select id, 'ccc'
 from t
 where name in ('aaa', 'bbb')
 group by id
 having count(*) = 2
)
</code>```

Body:
I want to replace row pairs (row with name="aaa" appear first and row with name="bbb" appear later, both rows have same id) by a new row with the same id but name="ccc".

Original table:

timestamp(primary key)        id     name
2020-02-20...                 1      aaa
2020-02-20...                 1      aaa  -----> first row
2020-02-20...                 1      ddd
2020-02-20...                 1      bbb  -----> second row
2020-02-20...                 2      aaa
2020-02-20...                 2      ccc
2020-02-20...                 2      ddd

New table:

timestamp(primary key)        id     name
2020-02-20...                 1      aaa
2020-02-20...                 1      aaa
2020-02-20...                 1      ccc  -----> replaced by this row
2020-02-20...                 1      ddd
2020-02-20...                 2      aaa
2020-02-20...                 2      ccc
2020-02-20...                 2      ddd

timestamp is the primary key and it is increasing.

Is it possible to achieve this in PostgresSQL?

Body:
If I understand correctly, this should do what you want:

(select id, name
 from t
 where name not in ('aaa', 'bbb') or
       name = 'aaa' and not exists (select 1 from t t2 where t2.id = t.id and t2.name = 'bbb')  or
       name = 'bbb' and not exists (select 1 from t t2 where t2.id = t.id and t2.name = 'aaa')
) union all
(select id, 'ccc'
 from t
 where name in ('aaa', 'bbb')
 group by id
 having count(*) = 2
)


问:
why am I getting Postgres password authentication fails error?
I'm trying to learn and exercise with postgres.

I'm running on Ubuntu 16.04.

I installed Postgres docker and run it with the following command:

```<code>sudo docker run --rm   --name pg-docker -e POSTGRES_PASSWORD=docker -d -p 5433:5433 -v $HOME/amitliron/UserA/docker/volumes/postgres:/var/lib/postgresql/data  postgres
</code>```

(I'm using 5433 port, becuse when trying to use 5432 port I'm getting the following error:
 Error starting userland proxy: listen tcp 0.0.0.0:5432: bind: address already in use, I think it's not need to be problem, but writing here everying I did)

I'm trying to check the postgres docker with the following command:

```<code>psql -h localhost -U postgres -d postgres
</code>```

and entered the password: "docker" but I'm getting the following error:

```<code>Password for user postgres:
psql: FATAL:  password authentication failed for user "postgres"
FATAL:  password authentication failed for user "postgres"
</code>```

What am I missing ?

答:
I needed to specify the port:</p>

```<code>psql -h localhost -p 5433 -U postgres -d postgres
</code>```

Body:
I'm trying to learn and exercise with postgres.

I'm running on Ubuntu 16.04.

I installed Postgres docker and run it with the following command:

sudo docker run --rm   --name pg-docker -e POSTGRES_PASSWORD=docker -d -p 5433:5433 -v $HOME/amitliron/UserA/docker/volumes/postgres:/var/lib/postgresql/data  postgres

(I'm using 5433 port, becuse when trying to use 5432 port I'm getting the following error:
 Error starting userland proxy: listen tcp 0.0.0.0:5432: bind: address already in use, I think it's not need to be problem, but writing here everying I did)

I'm trying to check the postgres docker with the following command:

psql -h localhost -U postgres -d postgres

and entered the password: "docker" but I'm getting the following error:

Password for user postgres:
psql: FATAL:  password authentication failed for user "postgres"
FATAL:  password authentication failed for user "postgres"

What am I missing ?

Body:
I needed to specify the port:

psql -h localhost -p 5433 -U postgres -d postgres


问:
How to SET DATEFIRST equal to Wednesday in Amazon Redshift
In my DimDate table , Week Day start with "Wednesday" and Ends with " Tuesday" , Now i need to generate week numbers accordingly, To achieve that i need to set my date first to Wednesday ?
Is there any other possibilities to achieve the below requirement

Please find the below Sample data I need to populate.

As per 2017-01-01 day starts with Sunday which is default datefirst , but in my case i need to give daynumber for that is 2017-01-01 daynumber= 4 and week =1, 2017-01-02 daynumber =5, 2017-01-01 daynumber= 6 and week =1
next Wednesday 01-04-2017 is daynumebr = 0 and week = 2  and so on ......

答:
This will set your daynumber as 0 for Wednesday and ending with 6 for Tuesday:

```<code>case when date_part(dw,source_date)-3<0
     then date_part(dw,source_date)+4
     else date_part(dw,source_date)-3
end as daynumber
</code>```

Similarly, you could write another case statement to evaluate the weeknumber though it would be more complex than this.

Body:
This will set your daynumber as 0 for Wednesday and ending with 6 for Tuesday:

case when date_part(dw,source_date)-3<0
     then date_part(dw,source_date)+4
     else date_part(dw,source_date)-3
end as daynumber

Similarly, you could write another case statement to evaluate the weeknumber though it would be more complex than this.


问:
how return one of the function between OR operator?
I can not understand when the 'find' function will true or false in the else block. Here is the code:

```<code>function findSolution(target) {
  function find(current, history) {
    if(current == target) {
      return history;
    } else if (current > target) {
      return null;
    } else {
      return find(current + 5, `(${history} + 5 )`) || find(current * 3, `(${history} * 3)`);
    }
  }

  return find(1, "1");
}

console.log(findSolution(24));
</code>```

答:
|| works by first evaluating find(current + 5, `(${history} + 5 )`) and if it is truthy that is the final result. If it is falsy it will evaluate find(current * 3, `(${history} * 3)`) and whatever is the result will be the end result which is then returned.

You can replace return expra || exprb with code without || using if and bindings:

```<code>// expra and exprb can be any valid expression
// same as return expra || exprb;
const tmp = expra;
if (tmp) {
    return tmp;
}
return exprb;
</code>```

Body:
I can not understand when the 'find' function will true or false in the else block. Here is the code:

function findSolution(target) {
  function find(current, history) {
    if(current == target) {
      return history;
    } else if (current > target) {
      return null;
    } else {
      return find(current + 5, `(${history} + 5 )`) || find(current * 3, `(${history} * 3)`);
    }
  }

  return find(1, "1");
}

console.log(findSolution(24));

Body:
|| works by first evaluating find(current + 5, `(${history} + 5 )`) and if it is truthy that is the final result. If it is falsy it will evaluate find(current * 3, `(${history} * 3)`) and whatever is the result will be the end result which is then returned.

You can replace return expra || exprb with code without || using if and bindings:

// expra and exprb can be any valid expression
// same as return expra || exprb;
const tmp = expra;
if (tmp) {
    return tmp;
}
return exprb;


问:
Cassandra count with limit
I need to find out if the count of records in Cassandra table is greater than certain number, e.g 10000.

I still don't have large data set, but at a large scale, with possible billions of records, how would I be able to achieve this efficiently?

There could potentially be billions of records, or just thousands. I just need to know if there are more or less than 10K.

This below doesn't seem right, I think it would fail or be very slow for large number of records.

SELECT COUNT(*) FROM data WHERE sourceId = {id} AND timestamp <
  {endDate} AND timestamp > {startDate};

I could also do something like this:

SELECT * FROM data WHERE sourceId = {id} AND timestamp < {endDate} AND timestamp > {startDate} LIMIT 10000;

and count in memory

I can't have new table used for counting, e.g, when a new record is written, increase counter, that option is unacceptable.

Is there some other way to do this? Select with limit looks dumb, but seems most viable.

sourceId is partition key and timestamp is clustering key.

Cassandra version is 3.11.4, and I work in Spring if it has any relevance.

答:
The first query:

```<code>SELECT COUNT(*) FROM data WHERE sourceId = {id}
   AND timestamp < {endDate} AND timestamp > {startDate};
</code>```

should work if you have a table with following primary key: (sourceId, timestamp, ...) - in this case, aggregation operation is executed inside the single partition, so it won't involve the hitting of multiple nodes, etc.  It still may timeout if you have very slow disks, and too much data in given time range.

If you have another table structure, then you'll need to use something like Spark, that will read data from Cassandra, perform filtering, and counting...

Title: Cassandra count with limit

Body:
The first query:

SELECT COUNT(*) FROM data WHERE sourceId = {id}
   AND timestamp < {endDate} AND timestamp > {startDate};

should work if you have a table with following primary key: (sourceId, timestamp, ...) - in this case, aggregation operation is executed inside the single partition, so it won't involve the hitting of multiple nodes, etc.  It still may timeout if you have very slow disks, and too much data in given time range.

If you have another table structure, then you'll need to use something like Spark, that will read data from Cassandra, perform filtering, and counting...


问:
Multiple IF Statements with Multiple COUNTIFS with Multiple criteria
I'm trying to make a cell display a text value depending on a multiple criteria COUNTIFS statement nested inside multiple IF statements, I have got the first IF(COUNTIFS statement working, but I want to nest another IF statement along with that so the cell can display different text values depending on multiple COUNTIFS, here is what I currently have:

```<code>IF(
   COUNTIFS(
      B6:B55, "AERONOMAD",
      D6:D55, "",
      F6:F55, "M"
   ),
   FORMULA!A12,
   FORMULA!A10
),
IF(
   COUNTIFS(
      B6:B55, "AERO NOMAD",
      D6:D55, "",
      F6:F55, "O"
   ),
   FORMULA!A11,
   FORMULA!A10)
</code>```

I know this part works on its own:

```<code>IF(
   COUNTIFS(
      B6:B55, "AERONOMAD",
      D6:D55, "",
      F6:F55, "M"
   ),
   FORMULA!A12,
   FORMULA!A10)
</code>```

But when I try and add another IF statement for the same cell it won't allow me; does anyone know a solution for this please?

答:
I have solved this now with the following, I was using the IF function but IF only gives one result for a true value! now I am using IFS and it returns the first true value:
=IFS(COUNTIFS(B6:B55, "AERO NOMAD",D6:D55, "",F6:F55, "M"),FORMULA!A12,COUNTIFS(B6:B55, "AERO NOMAD",D6:D55, "",F6:F55, "O"),FORMULA!A11,TRUE,"10/8")

Body:
I'm trying to make a cell display a text value depending on a multiple criteria COUNTIFS statement nested inside multiple IF statements, I have got the first IF(COUNTIFS statement working, but I want to nest another IF statement along with that so the cell can display different text values depending on multiple COUNTIFS, here is what I currently have:

IF(
   COUNTIFS(
      B6:B55, "AERONOMAD",
      D6:D55, "",
      F6:F55, "M"
   ),
   FORMULA!A12,
   FORMULA!A10
),
IF(
   COUNTIFS(
      B6:B55, "AERO NOMAD",
      D6:D55, "",
      F6:F55, "O"
   ),
   FORMULA!A11,
   FORMULA!A10)

I know this part works on its own:

IF(
   COUNTIFS(
      B6:B55, "AERONOMAD",
      D6:D55, "",
      F6:F55, "M"
   ),
   FORMULA!A12,
   FORMULA!A10)

But when I try and add another IF statement for the same cell it won't allow me; does anyone know a solution for this please?


问:
Clearing user-created variables in Python
I am an absolute beginner in Python. I have been using R and Matlab for data analysis for quite some time. One of the great things about these languages (or tools) is that I could run clear all in Matlab or rm(list=ls()) in R to clear the variables I created. I could then continue to experiment with my snippet of code.

I am struggling to find such a solution in Python. I researched Is there a way to delete created variables, functions, etc from the memory of the interpreter? and found that there are two ways to accomplish what I am trying to do, but in reality they are not any close.

First method:

```<code>%Reset
</code>```

This command deletes all variables and imported setting in PyCharm to run interactive mode. That is, after running above command, I have to re-run

```<code>from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
</code>```

This is very annoying.

Second Method:

Another suggested method is to write a for loop and ignore functions starting with __. This also doesn't work for the reasons above. For instance, when I start my PyCharm, I run

```<code>from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
</code>```

to ensure that I am able to run a bunch of commands together just as I would do in Matlab and R (In PyCharm, the keyboard shortcut is [Alt + Shift + E; This is called as Execute Selection in Console]). I have noticed that the for loop mentioned in that Stackoverflow thread deletes some of the variables created by running above two lines of code. This means that I won't be able to execute statements by selecting them at a time. I would have to type them individually on the prompt, which is annoying. Another option would be to run above two lines of code every time I execute the for loop, which is annoying as well.

As an aside, I did some research to understand what happens after running above two lines of code. I ran dir() after running above two lines to get a list of all variables existing in my session.

The list looks like this

```<code>Out[4]:
['In',
 'InteractiveShell',
 'Out',
 '_',
 '_2',
 '__',
 '___',
......(continued)
 'sys']
</code>```

Is there any way, I can delete user-created variables without deleting above variables? In effect, I want to replicate what rm(list=ls()) would do for me in R.

I see that there are a number of people who have asked this question outside StackOverflow such as https://github.com/spyder-ide/spyder/issues/2563.

Thanks for any help. I am using PyCharm with the latest Conda distribution (3.6).

答:
Try this:

>>> x = 1
>>> x
1
>>> globals().clear()
>>> x
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    x
NameError: name 'x' is not defined
```

Note that the the docs don't actually say that you can safely modify the dictionary that globals() returns, nor that modifying this dictionary will have the effect you intend (or any effect at all). But if you're just doing it for convenience in the REPL, then if it works, it works.

Body:
I am an absolute beginner in Python. I have been using R and Matlab for data analysis for quite some time. One of the great things about these languages (or tools) is that I could run clear all in Matlab or rm(list=ls()) in R to clear the variables I created. I could then continue to experiment with my snippet of code.

I am struggling to find such a solution in Python. I researched Is there a way to delete created variables, functions, etc from the memory of the interpreter? and found that there are two ways to accomplish what I am trying to do, but in reality they are not any close.

First method:

%Reset

This command deletes all variables and imported setting in PyCharm to run interactive mode. That is, after running above command, I have to re-run

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

This is very annoying.

Second Method:

Another suggested method is to write a for loop and ignore functions starting with __. This also doesn't work for the reasons above. For instance, when I start my PyCharm, I run

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

to ensure that I am able to run a bunch of commands together just as I would do in Matlab and R (In PyCharm, the keyboard shortcut is [Alt + Shift + E; This is called as Execute Selection in Console]). I have noticed that the for loop mentioned in that Stackoverflow thread deletes some of the variables created by running above two lines of code. This means that I won't be able to execute statements by selecting them at a time. I would have to type them individually on the prompt, which is annoying. Another option would be to run above two lines of code every time I execute the for loop, which is annoying as well.

As an aside, I did some research to understand what happens after running above two lines of code. I ran dir() after running above two lines to get a list of all variables existing in my session.

The list looks like this

Out[4]:
['In',
 'InteractiveShell',
 'Out',
 '_',
 '_2',
 '__',
 '___',
......(continued)
 'sys']

Is there any way, I can delete user-created variables without deleting above variables? In effect, I want to replicate what rm(list=ls()) would do for me in R.

I see that there are a number of people who have asked this question outside StackOverflow such as https://github.com/spyder-ide/spyder/issues/2563.

Thanks for any help. I am using PyCharm with the latest Conda distribution (3.6).

Body:
Try this:

>>> x = 1
>>> x
1
>>> globals().clear()
>>> x
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    x
NameError: name 'x' is not defined

Note that the the docs don't actually say that you can safely modify the dictionary that globals() returns, nor that modifying this dictionary will have the effect you intend (or any effect at all). But if you're just doing it for convenience in the REPL, then if it works, it works.


问:
Cross Platform Desktop Application - Windows+Mac+Linux
I'm building an application for multiple desktop platforms: Windows, Mac, and maybe later for Linux.

I was wondering which programming language and IDE combination would be the best for me:

Programming language need to be whether C# (preferred) or Java.

Core libraries must be shared between all platforms, means all platforms must link to a single core library (by library I mean a list of classes and functions).

Windows and Mac are in priority, Linux app is for future plannings.

Design of the app is completely custom, it doesn't follow any guidelines of each platforms.

I'm stuck between these three solutions:

Use Xamarin.Mac + Visual Studio for Windows and link the core classes between them.

Use GTK# for the whole project and compile multiple builds for each platforms.

Use Java for the whole project and compile multiple builds for each platforms.

For #2 and #3, I need an advice that which language is more suitable for me, considering the design of my application. I mean, which one has a better GUI building ability for my goal?

BTW GTK# uses different libraries for each platforms, so that should be an clutter for my core architecture, or not?!

答: Probably your best bet is to use Nevron Open Vision. It is a cross-platform, C# based User Interface Platform, that implements most of the controls you need to build enterprise-ready applications. It is the framework behind MyDraw (www.mydraw.com) - a professional drawing program similar to Visio. MyDraw is built completely with Nevron Open Vision and does not require any other third-party libraries. We mainly develop it under Windows and just compile it to Mac. Soon we are going to add support for Linux and WebAssembly hosts.</p>


问:
how to use join and like mysql in mongodb
```<code>var query = req.params.query;
const messages = await Message.aggregate([

      {
        $lookup: {
          from: 'users',
          localField: 'reference_id',
          foreignField: '_id',
          as: 'users'
        }
      },

      {'text': {'$regex': `.*${query}.*`}}
    ])
</code>```

Getting error "message": "Arguments must be aggregate pipeline operators",

I wanted to join first_name and last_name from users table and search ability based on either first_name, last_name and text how can i achieve this

答:
```<code>function xyz = () => {
return new Promise((resolve, reject) => {
var query = req.params.query;
var aggregate = Message.aggregate();
 aggregate
        .lookup({
          from: 'users',
          localField: 'reference_id',
          foreignField: '_id',
          as: 'users'
        })
        .match({
           $text: {$search: "$query"}
        )}
         aggregate.exec(function(err, result) {
         if (err) return reject(err);
         return resolve(result);
    });
});
}
</code>```

Make sure your localField id and foreign field id matches.
I hope this help you!

Body:
var query = req.params.query;
const messages = await Message.aggregate([

      {
        $lookup: {
          from: 'users',
          localField: 'reference_id',
          foreignField: '_id',
          as: 'users'
        }
      },

      {'text': {'$regex': `.*${query}.*`}}
    ])

Getting error "message": "Arguments must be aggregate pipeline operators",

I wanted to join first_name and last_name from users table and search ability based on either first_name, last_name and text how can i achieve this

Body:
function xyz = () => {
return new Promise((resolve, reject) => {
var query = req.params.query;
var aggregate = Message.aggregate();
 aggregate
        .lookup({
          from: 'users',
          localField: 'reference_id',
          foreignField: '_id',
          as: 'users'
        })
        .match({
           $text: {$search: "$query"}
        )}
         aggregate.exec(function(err, result) {
         if (err) return reject(err);
         return resolve(result);
    });
});
}

Make sure your localField id and foreign field id matches.
I hope this help you!


问:
Accessing google sheets via the PHP API on a G-Suite account
I am a member of the organization and I set up a new project, enabled google sheets API and set up a service account with owner role, I downloaded the json file containing the credentials, including the cert and all that.

I went in and shared this sheet with the email generated for that service account.

When I run the PHP script and I call getSpreadsheetFeed(), the sheet does not show up at all.

When I take this same sheet and put it on my own personal google drive and share it with the same service account, it shows up as expected.

This sheet is in a "Shared Drive" folder.

```<code><?php
require __DIR__ . '/vendor/autoload.php';

use Google\Spreadsheet\DefaultServiceRequest;
use Google\Spreadsheet\ServiceRequestFactory;

putenv('GOOGLE_APPLICATION_CREDENTIALS=' . __DIR__ . '/client_secret.json');

$client = new Google_Client;
$client->useApplicationDefaultCredentials();

$client->setApplicationName("MSE Reader Application");
$client->setScopes(Google_Service_Sheets::SPREADSHEETS);

if ($client->isAccessTokenExpired()) {
    $client->refreshTokenWithAssertion();
}

$accessToken = $client->fetchAccessTokenWithAssertion()["access_token"];
ServiceRequestFactory::setInstance(
    new DefaultServiceRequest($accessToken)
);

$spreadsheets = (new Google\Spreadsheet\SpreadsheetService)->getSpreadsheetFeed();

print_r($spreadsheets);

?>
</code>```

答:
I have been able to solve this using the official client as https://github.com/asimlqt/php-google-spreadsheet-client seems to be outdated and is not actively maintained.

https://developers.google.com/sheets/api/quickstart/php

This quickstart works for me:

```<code>$service = new Google_Service_Sheets($client);

// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
$spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
$range = 'Class Data!A2:E';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();
</code>```

Body:
I am a member of the organization and I set up a new project, enabled google sheets API and set up a service account with owner role, I downloaded the json file containing the credentials, including the cert and all that.

I went in and shared this sheet with the email generated for that service account.

When I run the PHP script and I call getSpreadsheetFeed(), the sheet does not show up at all.

When I take this same sheet and put it on my own personal google drive and share it with the same service account, it shows up as expected.

This sheet is in a "Shared Drive" folder.

<?php
require __DIR__ . '/vendor/autoload.php';

use Google\Spreadsheet\DefaultServiceRequest;
use Google\Spreadsheet\ServiceRequestFactory;

putenv('GOOGLE_APPLICATION_CREDENTIALS=' . __DIR__ . '/client_secret.json');

$client = new Google_Client;
$client->useApplicationDefaultCredentials();

$client->setApplicationName("MSE Reader Application");
$client->setScopes(Google_Service_Sheets::SPREADSHEETS);

if ($client->isAccessTokenExpired()) {
    $client->refreshTokenWithAssertion();
}

$accessToken = $client->fetchAccessTokenWithAssertion()["access_token"];
ServiceRequestFactory::setInstance(
    new DefaultServiceRequest($accessToken)
);

$spreadsheets = (new Google\Spreadsheet\SpreadsheetService)->getSpreadsheetFeed();

print_r($spreadsheets);

?>

Body:
I have been able to solve this using the official client as https://github.com/asimlqt/php-google-spreadsheet-client seems to be outdated and is not actively maintained.

https://developers.google.com/sheets/api/quickstart/php

This quickstart works for me:

$service = new Google_Service_Sheets($client);

// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
$spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
$range = 'Class Data!A2:E';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();


答:
Binary constants such as 0b1111111 are not defined by the C standard and were introduced as an extension by some C implementations somewhat late, so earlier code necessarily used octal and hexadecimal constants, and programmers became accustomed to them. Additionally, octal is more compact, and I can count the number of set bits in 0177 more easily than in 0b1111111. One quickly becomes accustomed to knowing that 7 means three bits set.

In (*(int *)&(w)), &(w) takes the address of the object designated by w. Then (int *) converts that address from the type “pointer to type of w” to “pointer to int”. Then * dereferences that pointer, nominally producing an int value.

The intent is to access the first bytes of w as if they were an int, effectively getting the raw bits that are in w instead of interpreting it as a structure or whatever other type it is. This is called aliasing.

Aliasing in this way is not supported by the C standard, but many C implementations allow it, and the code you show appear to have been written specifically for such an implementation.

A supported way to get the raw bits of an object is to copy bytes individually, as with:

```<code>int b;
memcpy(&b, &w, sizeof b);
</code>```

Although this looks like a function call, good compilers recognize it as a request to access the first bytes of w as if they were an int and optimize it. The result may be a single load instruction. However, wrapping this into a macro that produces the int as a value involves some complications, which I will leave for further discussion elsewhere. (You can ask a new question about that, if desired.)

Title: What does (*(int *)&(w)) mean in c programming?

Body:
I'm learning processes and in the following code snippet:

/*
 * fork10 - Synchronizing with multiple children (wait)
 * Reaps children in arbitrary order
 * WIFEXITED and WEXITSTATUS to get info about terminated children
 */
void fork10()
{
    pid_t pid[N];
    int i, child_status;

    for (i = 0; i < N; i++)
    if ((pid[i] = fork()) == 0) {
        exit(100+i); /* Child */
    }
    for (i = 0; i < N; i++) { /* Parent */
        pid_t wpid = wait(&child_status);
        if (WIFEXITED(child_status))
            printf("Child %d terminated with exit status %d\n", wpid, WEXITSTATUS(child_status));
        else
            printf("Child %d terminate abnormally\n", wpid);
    }
}

when I trace WIFEXITED function definition this is what I've got:

#define WIFEXITED(x)    (_WSTATUS(x) == 0)
#define _WSTATUS(x) (_W_INT(x) & 0177)
#define _W_INT(w)   (*(int *)&(w))  /* convert union wait to int */

I have two questions:

Why use mask 0177 instead of 0b1111111, I've seen it many times, what's the benefits of using octal number over other formats? Personally I find binary more intuitive.

What's the meaning of (*(int *)&(w))?

Thanks!

Body:
Binary constants such as 0b1111111 are not defined by the C standard and were introduced as an extension by some C implementations somewhat late, so earlier code necessarily used octal and hexadecimal constants, and programmers became accustomed to them. Additionally, octal is more compact, and I can count the number of set bits in 0177 more easily than in 0b1111111. One quickly becomes accustomed to knowing that 7 means three bits set.

In (*(int *)&(w)), &(w) takes the address of the object designated by w. Then (int *) converts that address from the type “pointer to type of w” to “pointer to int”. Then * dereferences that pointer, nominally producing an int value.

The intent is to access the first bytes of w as if they were an int, effectively getting the raw bits that are in w instead of interpreting it as a structure or whatever other type it is. This is called aliasing.

Aliasing in this way is not supported by the C standard, but many C implementations allow it, and the code you show appear to have been written specifically for such an implementation.

A supported way to get the raw bits of an object is to copy bytes individually, as with:

int b;
memcpy(&b, &w, sizeof b);

Although this looks like a function call, good compilers recognize it as a request to access the first bytes of w as if they were an int and optimize it. The result may be a single load instruction. However, wrapping this into a macro that produces the int as a value involves some complications, which I will leave for further discussion elsewhere. (You can ask a new question about that, if desired.)


问:
How to start server with port from server.properties rather than yaml
how to get server port from server.properties rather than .yml?

I have my application which start at port 7799 which is placed in the .yml file in in /src/main/resources/

```<code>public static void main(String[] args) throws UnknownHostException {
        SpringApplication app = new SpringApplication(Application.class);
        SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
        addDefaultProfile(app, source);
        Environment env = app.run(args).getEnvironment();
        log.info("Access URLs:\n----------------------------------------------------------\n\t" +
                "Local: \t\thttp://127.0.0.1:{}\n\t" +
                "External: \thttp://{}:{}\n----------------------------------------------------------",
            env.getProperty("server.port"),
            InetAddress.getLocalHost().getHostAddress(),
            env.getProperty("server.port"));

    }
</code>```

I have server.properties file in location /config/ where I put all the database parameters.

How to get port from server.properties instead of .yml file?

答:
There are several ways to get any value from properties file.
One way is

You can have a separate class to get all the properties so that everything you will get it from here

```<code>@Component
@ConfigurationProperties(prefix = "server")
@PropertySource("classpath:server.properties")
public class ServerProperties {
    private String protocol;
    private String port;
    private String host;

    ...get and set methods here
}
</code>```

and just autowire them in your class by

```<code>@Autowired
private ServerProperties serverProperties;
</code>```

Second way of getting properties is

```<code>private static Properties prop = new Properties();
prop.load(DummyClass.class.getResourceAsStream("/server.properties"));
String port = prop.getProperty("server.port");
</code>```

Get port to run the app

```<code>@Configuration
public class ServletConfig {
private static Properties prop = new Properties();
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
   prop.load(DummyClass.class.getResourceAsStream("/server.properties"));
   String port = prop.getProperty("server.port");
   return (container -> {
     container.setPort(port);
    });
  }
}
</code>```

Body:
how to get server port from server.properties rather than .yml?

I have my application which start at port 7799 which is placed in the .yml file in in /src/main/resources/

public static void main(String[] args) throws UnknownHostException {
        SpringApplication app = new SpringApplication(Application.class);
        SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
        addDefaultProfile(app, source);
        Environment env = app.run(args).getEnvironment();
        log.info("Access URLs:\n----------------------------------------------------------\n\t" +
                "Local: \t\thttp://127.0.0.1:{}\n\t" +
                "External: \thttp://{}:{}\n----------------------------------------------------------",
            env.getProperty("server.port"),
            InetAddress.getLocalHost().getHostAddress(),
            env.getProperty("server.port"));

    }

I have server.properties file in location /config/ where I put all the database parameters.

How to get port from server.properties instead of .yml file?

Body:
There are several ways to get any value from properties file.
One way is

You can have a separate class to get all the properties so that everything you will get it from here

@Component
@ConfigurationProperties(prefix = "server")
@PropertySource("classpath:server.properties")
public class ServerProperties {
    private String protocol;
    private String port;
    private String host;

    ...get and set methods here
}

and just autowire them in your class by

@Autowired
private ServerProperties serverProperties;

Second way of getting properties is

private static Properties prop = new Properties();
prop.load(DummyClass.class.getResourceAsStream("/server.properties"));
String port = prop.getProperty("server.port");

Get port to run the app

@Configuration
public class ServletConfig {
private static Properties prop = new Properties();
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
   prop.load(DummyClass.class.getResourceAsStream("/server.properties"));
   String port = prop.getProperty("server.port");
   return (container -> {
     container.setPort(port);
    });
  }
}


问:
Possiblity using Kafka-Connector get Data from Python-Opcua-Client to Kafka-topic
what have is a python opcua client.
 datachange_notification(self, node, val, data) will be performed as part of python opcua clientwhenever new data is arrived by client, see the script below, does it possible to send the arrived data(in this context is val) to kafka-topic.

    def datachange_notification(self, node, val, data):
        saveData = save_file.Savefile()
        #save data locally when data arrived according to the nodeid=2
        if str(node) == "Node(NumericNodeId(ns=2;i=2))":
            if val != None and val != 0:
                print("Python: New data change event", node, val)
                saveData.saveBlockByClient(val)
        #save data locally when data arrived according to the nodeid=3
        if str(node) == "Node(NumericNodeId(ns=2;i=3))":
            if val != None and val != 0:
                print("Python: New data change event", node, val)
                saveData.saveSourceByValidator(str(val))
```

答:
Is it possible? Sure.

Import a Kafka library and new up a Producer instance then send a message

If you use the AsyncIO client mentioned in the comments, I'd suggest researching aiokafka python library


问:
How to generate a new data frame by matching common values in this case?
I have two data frames like this:

```<code>data_2019_dict = {'state': ['Ohio', 'Texas', 'Pennsylvania', 'Nevada', 'New York', 'Nevada', 'Ohio', 'Virginia', 'Louisiana', 'Florida', 'Nevada'],
 'industry': ['Agriculture', 'Agriculture', 'Agriculture', 'Agriculture', 'Medicine', 'Medicine', 'Medicine', 'Medicine', 'Manufacture', 'Manufacture', 'Manufacture'],
 'value': [3.6, 3.2, 2.9, 2.4, 3.1, 1.5, 1.4, 0.9, 4.4, 2.0, 1.9]}

data_2020_dict = {'state': ['Kansas', 'Texas', 'California', 'Idaho', 'Nevada', 'Ohio', 'Virginia', 'Louisiana', 'Texas', 'Nevada'],
 'industry': ['Agriculture', 'Agriculture', 'Agriculture', 'Medicine', 'Medicine', 'Finance', 'Finance', 'Manufacture', 'Manufacture', 'Manufacture'],
'value': [2.3, 1.8, 1.6, 7.2, 5.9, 4.1, 0.2, 5.1, 2.3, 2.2]}

data_2019 = pd.DataFrame(data_2019_dict)
data_2020 = pd.DataFrame(data_2020_dict)

</code>```

Each data frame shows that in a year, which states perform well in those industries. What I want to generate, but get stuck, is: For each state, what industries are performed well in both years? The resulting data frame will look like this:

```<code># Manually generated for illustration
data_both_dict = {'state': ['Ohio', 'Texas', 'Pennsylvania', 'Nevada', 'Nevada', 'New York', 'Virginia', 'Louisiana', 'Florida', 'Kansas', 'California', 'Idaho'],
             'common_industry': ['', 'Agriculture', '', 'Medicine', 'Manufacture', '', '', 'Manufacture', '', '', '', ''],
             'common_industry_count': [0, 1, 0, 2, 2, 0, 0, 1, 0, 0, 0, 0]
}
data_both = pd.DataFrame(data_both_dict)
</code>```

答:
First DataFrame.merge for common rows by both columns, rename column and add counts by Series.value_counts and Series.map:

```<code>df = (data_2019.merge(data_2020, on=['state','industry'])
               .rename(columns={'industry':'common_industry'}))
df['common_industry_count'] = df['state'].map(df['state'].value_counts())
df = df[['state','common_industry','common_industry_count']]
print (df)
       state common_industry  common_industry_count
0      Texas     Agriculture                      1
1     Nevada        Medicine                      2
2  Louisiana     Manufacture                      1
3     Nevada     Manufacture                      2
</code>```

Then get all states by concat with removed duplicates by Series.drop_duplicates and one column DataFrame by Series.to_frame:

```<code>both = pd.concat([data_2019['state'], data_2020['state']]).drop_duplicates().to_frame()
print (both)
          state
0          Ohio
1         Texas
2  Pennsylvania
3        Nevada
4      New York
7      Virginia
8     Louisiana
9       Florida
0        Kansas
2    California
3         Idaho
</code>```

Last merge with left join and replace missing values by Series.fillna:

```<code>df = both.merge(df, how='left')
df['common_industry_count'] = df['common_industry_count'].fillna(0).astype(int)
df['common_industry'] = df['common_industry'].fillna('')
print (df)
           state common_industry  common_industry_count
0           Ohio                                      0
1          Texas     Agriculture                      1
2   Pennsylvania                                      0
3         Nevada        Medicine                      2
4         Nevada     Manufacture                      2
5       New York                                      0
6       Virginia                                      0
7      Louisiana     Manufacture                      1
8        Florida                                      0
9         Kansas                                      0
10    California                                      0
11         Idaho                                      0
</code>```

Body:
I have two data frames like this:

data_2019_dict = {'state': ['Ohio', 'Texas', 'Pennsylvania', 'Nevada', 'New York', 'Nevada', 'Ohio', 'Virginia', 'Louisiana', 'Florida', 'Nevada'],
 'industry': ['Agriculture', 'Agriculture', 'Agriculture', 'Agriculture', 'Medicine', 'Medicine', 'Medicine', 'Medicine', 'Manufacture', 'Manufacture', 'Manufacture'],
 'value': [3.6, 3.2, 2.9, 2.4, 3.1, 1.5, 1.4, 0.9, 4.4, 2.0, 1.9]}

data_2020_dict = {'state': ['Kansas', 'Texas', 'California', 'Idaho', 'Nevada', 'Ohio', 'Virginia', 'Louisiana', 'Texas', 'Nevada'],
 'industry': ['Agriculture', 'Agriculture', 'Agriculture', 'Medicine', 'Medicine', 'Finance', 'Finance', 'Manufacture', 'Manufacture', 'Manufacture'],
'value': [2.3, 1.8, 1.6, 7.2, 5.9, 4.1, 0.2, 5.1, 2.3, 2.2]}

data_2019 = pd.DataFrame(data_2019_dict)
data_2020 = pd.DataFrame(data_2020_dict)

Each data frame shows that in a year, which states perform well in those industries. What I want to generate, but get stuck, is: For each state, what industries are performed well in both years? The resulting data frame will look like this:

# Manually generated for illustration
data_both_dict = {'state': ['Ohio', 'Texas', 'Pennsylvania', 'Nevada', 'Nevada', 'New York', 'Virginia', 'Louisiana', 'Florida', 'Kansas', 'California', 'Idaho'],
             'common_industry': ['', 'Agriculture', '', 'Medicine', 'Manufacture', '', '', 'Manufacture', '', '', '', ''],
             'common_industry_count': [0, 1, 0, 2, 2, 0, 0, 1, 0, 0, 0, 0]
}
data_both = pd.DataFrame(data_both_dict)

Body:
First DataFrame.merge for common rows by both columns, rename column and add counts by Series.value_counts and Series.map:

df = (data_2019.merge(data_2020, on=['state','industry'])
               .rename(columns={'industry':'common_industry'}))
df['common_industry_count'] = df['state'].map(df['state'].value_counts())
df = df[['state','common_industry','common_industry_count']]
print (df)
       state common_industry  common_industry_count
0      Texas     Agriculture                      1
1     Nevada        Medicine                      2
2  Louisiana     Manufacture                      1
3     Nevada     Manufacture                      2

Then get all states by concat with removed duplicates by Series.drop_duplicates and one column DataFrame by Series.to_frame:

both = pd.concat([data_2019['state'], data_2020['state']]).drop_duplicates().to_frame()
print (both)
          state
0          Ohio
1         Texas
2  Pennsylvania
3        Nevada
4      New York
7      Virginia
8     Louisiana
9       Florida
0        Kansas
2    California
3         Idaho

Last merge with left join and replace missing values by Series.fillna:

df = both.merge(df, how='left')
df['common_industry_count'] = df['common_industry_count'].fillna(0).astype(int)
df['common_industry'] = df['common_industry'].fillna('')
print (df)
           state common_industry  common_industry_count
0           Ohio                                      0
1          Texas     Agriculture                      1
2   Pennsylvania                                      0
3         Nevada        Medicine                      2
4         Nevada     Manufacture                      2
5       New York                                      0
6       Virginia                                      0
7      Louisiana     Manufacture                      1
8        Florida                                      0
9         Kansas                                      0
10    California                                      0
11         Idaho                                      0


问:
How to stop Spring batch job when error in processor
In my batch job, I have a single step with reading from Database , processing the record and writing back the same record to same table.(ie updating record with processed values or error reason if processing failed).

I am using AsyncItemProcessor for multi thread processing. When I get error in ItemProcessor.process() method, I throw an exception and batch job ends with FAILED status. This failed status is a requirement.

Because, its AsyncItemProcessor, I am unable to access ItemProcessListener.onProcessError().

How do I write the errorMessage to Item Table when there is an error ?

答:
This is a known limitation of using the AsyncItemProcessor which is mentioned in its Javadoc:

```<code>While not an exhaustive list, things like StepExecution.filterCount will not
reflect the number of filtered items and
ItemProcessListener.onProcessError(Object, Exception) will not be called.
</code>```

There is an open issue to update the reference documentation as well.

How do I write the errorMessage to Item Table when there is an error ?

The AsyncItemProcessor submits a FutureTask to the task executor and the only way to know if an exception happened in the task is by unwrapping the future (the exception will be actually wrapped in a java.util.concurrent.ExecutionException when the FutureTask.get is called). Now since the future is unwrapped in the AsyncItemWriter, you can use an ItemWriteListener and react to processing errors. You can find a complete example here.

Body:
This is a known limitation of using the AsyncItemProcessor which is mentioned in its Javadoc:

While not an exhaustive list, things like StepExecution.filterCount will not
reflect the number of filtered items and
ItemProcessListener.onProcessError(Object, Exception) will not be called.

There is an open issue to update the reference documentation as well.

How do I write the errorMessage to Item Table when there is an error ?

The AsyncItemProcessor submits a FutureTask to the task executor and the only way to know if an exception happened in the task is by unwrapping the future (the exception will be actually wrapped in a java.util.concurrent.ExecutionException when the FutureTask.get is called). Now since the future is unwrapped in the AsyncItemWriter, you can use an ItemWriteListener and react to processing errors. You can find a complete example here.


问:
Selenium block requests, scripts before page loaded
I am trying to block some requests for example; gAnalytics or gMaps and so on.  I used BrowserMobProxy before but for now, I am using the Tor network as my proxy.  Anyway, What I need to do is block some specific URLs before the driver opened or when the driver opened. I need it because the gMaps loading really takes time for my scraper.

Related topics:

enter link description here

enter link description here

enter link description here

enter link description here

答:
The solution is:

https://chrome.google.com/webstore/detail/http-request-blocker/eckpjmeijpoipmldfbckahppeonkoeko?hl=en

edit and install an extension like this. This can be a solution for request blocking.