问:
replicas of a service in docker swarm remain 0/1 forever
yes, I already tried this Question and ir doesnt a duplicate question

Im learning use the docker swarm and Im using the docker-play

I have a manager(node1) and 2 workers(node2 and node3)

```<code>$ docker node ls
ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS
j4maivz26wactwn9ghgosg219     node2               Ready               Active
p6cpvetwrsqu6oiqzfq2bxxsv     node3               Ready               Active
r7y5zktfore76l9z3n0keu7ae *   node1               Ready               Active              Leader
</code>```

so i created a service

```<code> docker service create --network ingress --name mysql -e MYSQL_ROOT_PASSWORD=demodocker -e MYSQL_DATABASE=wordpressdatabase -e M
YSQL_USER=root -e MYSQL_PASSWORD=demodocker mysql
</code>```

and the replicas remain 0/1 forever

```<code>$ docker service ls
ID                  NAME                MODE                REPLICAS            IMAGE               PORTS
jub3wh8yz2cd        mysql              replicated          0/1                 mysql:latest
</code>```

so i try:

```<code> docker service create --network ingress --name mysql2 -e MYSQL_ROOT_PASSWORD=demodocker -e MYSQL_DATABASE=wordpressdatabase -e M
YSQL_USER=root -e MYSQL_PASSWORD=demodocker mysql:latest top
</code>```

and i try:

```<code> docker service create --network ingress --replicas 1 --name mysql2 -e MYSQL_ROOT_PASSWORD=demodocker -e MYSQL_DATABASE=wordpressdatabase -e M
YSQL_USER=root -e MYSQL_PASSWORD=demodocker mysql:latest top
</code>```

I try the most simple code line:

```<code>docker service create --network ingress --name mysql -e MYSQL_ROOT_PASSWORD=demodoceker mysql
</code>```

but anything work, i looked this question too but i dont find none parameter wrong

more information:

```<code>$ docker service ps mysql
ID                  NAME                IMAGE               NODE                DESIRED STATE       CURRENT STATE        ERROR
           PORTS
j523hr6mnfqk        mysql            mysql:latest                            Running             New 13 minutes ago
</code>```

.

```<code>$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
wordpress           latest              ca96afcfa242        2 weeks ago         406MB
mysql               latest              e799c7f9ae9c        3 weeks ago         407MB
</code>```

Thank you ;)

答:
Don't attach services directly to the ingress network. That seems to be causing the issue as I don't experience the same when removing --network ingress. I can reproduce the above (with --network ingress set) and I don't see any logs (service or daemon) that might give a clue about why it's failing, so that's not great I guess. Maybe raise an issue with Docker for better logging / error here?

The ingress network is used when publishing ports for the service so let Docker manage attachments to that directly.

Edit: Btw, this will still fail after you take that out, for mysql reasons (failure to create table I believe? But the service itself is attempting to come up).

Body:
yes, I already tried this Question and ir doesnt a duplicate question

Im learning use the docker swarm and Im using the docker-play

I have a manager(node1) and 2 workers(node2 and node3)

$ docker node ls
ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS
j4maivz26wactwn9ghgosg219     node2               Ready               Active
p6cpvetwrsqu6oiqzfq2bxxsv     node3               Ready               Active
r7y5zktfore76l9z3n0keu7ae *   node1               Ready               Active              Leader

so i created a service

 docker service create --network ingress --name mysql -e MYSQL_ROOT_PASSWORD=demodocker -e MYSQL_DATABASE=wordpressdatabase -e M
YSQL_USER=root -e MYSQL_PASSWORD=demodocker mysql

and the replicas remain 0/1 forever

$ docker service ls
ID                  NAME                MODE                REPLICAS            IMAGE               PORTS
jub3wh8yz2cd        mysql              replicated          0/1                 mysql:latest

so i try:

 docker service create --network ingress --name mysql2 -e MYSQL_ROOT_PASSWORD=demodocker -e MYSQL_DATABASE=wordpressdatabase -e M
YSQL_USER=root -e MYSQL_PASSWORD=demodocker mysql:latest top

and i try:

 docker service create --network ingress --replicas 1 --name mysql2 -e MYSQL_ROOT_PASSWORD=demodocker -e MYSQL_DATABASE=wordpressdatabase -e M
YSQL_USER=root -e MYSQL_PASSWORD=demodocker mysql:latest top

I try the most simple code line:

docker service create --network ingress --name mysql -e MYSQL_ROOT_PASSWORD=demodoceker mysql

but anything work, i looked this question too but i dont find none parameter wrong

more information:

$ docker service ps mysql
ID                  NAME                IMAGE               NODE                DESIRED STATE       CURRENT STATE        ERROR
           PORTS
j523hr6mnfqk        mysql            mysql:latest                            Running             New 13 minutes ago

.

$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
wordpress           latest              ca96afcfa242        2 weeks ago         406MB
mysql               latest              e799c7f9ae9c        3 weeks ago         407MB

Thank you ;)


来源: stackexchange

问:
tbody focus does not work
I have the following table structure:

```<code><table>
 <tr>
  <th> </th>
  <th> </th>
  <th> </th>

</tr>
<tbody id="page-1">
 <tr>
    <td>  </td>
    <td>  </td>
    <td>  </td>
</tr>

<tr>
    <td>  </td>
    <td>  </td>
    <td>  </td>
</tr>
<tr>
    <td>  </td>
    <td>  </td>
    <td>  </td>
</tr>
<tr>
    <td>  </td>
    <td>  </td>
    <td>  </td>
</tr>
</tbody>
<tbody id="page-2">
 <tr>
    <td>  </td>
    <td>  </td>
    <td>  </td>

</tr>
<tr>
    <td>  </td>
    <td>  </td>
    <td>  </td>
</tr>
<tr>
    <td>  </td>
    <td>  </td>
    <td>  </td>
</tr>
</tbody>
</table>
</code>```

I have tried the following jquery code to make scroll to specific tbody by id like:

```<code>page = 1;
$("#page-"+page).focus()
</code>```

The above code failed to make scroll to the specified tbody. I also tried the following in order to get first tr but also failed:

```<code>page = 1;
$("#page-"+page+":first-child").focus()
</code>```

The last thing that I have to mention, that tbody is loaded via ajax request and console.log($("#page-"+page).html()) works fine and prints out the html of the tbody

答:
I have got the mistake. focus is not the suitable event for tbody in other words there is no point of focus for it. The solution is Run ScrollTop with offset of element by ID and using:

```<code>$('html, body').animate({
                 scrollTop: $('#page-'+page).offset().top -100
                }, 2000);
</code>```

ContentLicense: CC BY-SA 3.0

Title: tbody focus does not work

Body:
I have the following table structure:

I have tried the following jquery code to make scroll to specific tbody by id like:

page = 1;
$("#page-"+page).focus()

The above code failed to make scroll to the specified tbody. I also tried the following in order to get first tr but also failed:

page = 1;
$("#page-"+page+":first-child").focus()

The last thing that I have to mention, that tbody is loaded via ajax request and console.log($("#page-"+page).html()) works fine and prints out the html of the tbody

Body:
I have got the mistake. focus is not the suitable event for tbody in other words there is no point of focus for it. The solution is Run ScrollTop with offset of element by ID and using:

$('html, body').animate({
                 scrollTop: $('#page-'+page).offset().top -100
                }, 2000);


问:
PDOException “could not find driver”
I have just installed Debian Lenny with Apache, MySQL, and PHP and I am receiving a PDOException could not find driver.

This is the specific line of code it is referring to:

$dbh = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASS)

DB_HOST, DB_NAME, DB_USER, and DB_PASS are constants that I have defined. It works fine on the production server (and on my previous Ubuntu Server setup).

Is this something to do with my PHP installation?

Searching the internet has not helped, all I get is experts-exchange and examples, but no solutions.

答:
I had the same issue. The solution depends on OS. In my case, i have debian, so to solve it:

Updated my php version from (php5 to php7)

Install php-mysql and php7.0-mysql

```<code>apt-get install php-mysql
apt-get install php7.0-mysql
</code>```

I edited my php.ini locate at /etc/php/7.0/apache2/php.ini

```<code>uncomment the line : extension=php_pdo_mysql.dll
</code>```

Then restart apache:

```<code>service apache2 restart
</code>```

This solves my problem

ContentLicense: CC BY-SA 2.5

Title: PDOException “could not find driver”

Body:
I had the same issue. The solution depends on OS. In my case, i have debian, so to solve it:

Updated my php version from (php5 to php7)

Install php-mysql and php7.0-mysql

apt-get install php-mysql
apt-get install php7.0-mysql

I edited my php.ini locate at /etc/php/7.0/apache2/php.ini

uncomment the line : extension=php_pdo_mysql.dll

Then restart apache:

service apache2 restart

This solves my problem

ContentLicense: CC BY-SA 4.0


问:
AWS Lambda integration with SQS
Does AWS lambda provide support for listening to SQS queue? I found some examples which says one can do that but I am not sure if AWS lambda explicity provide support for that. When I create the lambda function, then I found one blueprint for SQS. So,</p>

答: I linked to it in your other thread - these are the supported event sources.  Notice that cloudwatch events are one of the possible event types.  You could set up a Lambda to, for example, run every minute and poll an SQS queue.  You cannot directly trigger a Lambda off of an SQS queue.</p>

Title: AWS Lambda integration with SQS


问:
Use Typescript Class without declare a object
someone knows how to use a typescript class without declare a object, on php is someting like MyClass::AnyFunction() or MyClass::attribute.

I can do it using (new MyClass()).MyFunctionOrAttribute, but i don't know if there is another way, yeah my english is bad.

答:
You are looking for static methods which TypeScript supports:</p>

```<code>class MyClass {
  static AnyFunction() {

  }
}

MyClass.AnyFunction(); // Works
</code>```

Body:
You are looking for static methods which TypeScript supports:

class MyClass {
  static AnyFunction() {

  }
}

MyClass.AnyFunction(); // Works


问:
Merging two text files using Shell script in VBA
I have three String varibales in my VBA code as below:

```<code>Dim FilePath As String
Dim FooterFilePath As String
Dim PlusChar As String

FilePath = Application.ActiveWorkbook.Path & "\Bin\file.txt"
FooterFilePath = Application.ActiveWorkbook.Path & "\Bin\footer.txt"
PlusChar = Chr(43)  'i.e. "+" sign
</code>```

Now I am trying to merge FilePath and FooterFilePath and write the combined result in FilePath again i.e. overwriting it. For that I am using followng line which doesn't work:

```<code>Shell "cmd.exe copy /c & FilePath & PlusChar & FooterFilePath & FilePath", 0
</code>```

I know I have syntaxing issue here but I just don't know how to pass three variables into Shell command.

答:
You have to put the variables outside the enclosing double-quotes. also you should insert blanks between the different names so that your command does not get the names combined in one name. Try this:

```<code>Shell "cmd.exe copy /c " & FilePath & " " & PlusChar & " " & FooterFilePath & " " & FilePath, 0
</code>```

But:

There's no reason to have a variable for the +

Your drive's name is missing in the paths

/C is an option for the cmd program, not for the copy command.

It is useful to print that expression in the immediate window to verify it before execution. To do so, you can put it in a String variable and debug.print it before execution:

This would be correct:

```<code>Dim FilePath As String, FooterFilePath As String, myCommand As String

FilePath = Application.ActiveWorkbook.Path & "C:\Bin\file.txt"
FooterFilePath = Application.ActiveWorkbook.Path & "C:\Bin\footer.txt"

myCommand = "cmd /c copy " & FilePath & " + " & FooterFilePath & " " & FilePath
Debug.Print myCommand
Shell myCommand, 0
</code>```

Body:
I have three String varibales in my VBA code as below:

Dim FilePath As String
Dim FooterFilePath As String
Dim PlusChar As String

FilePath = Application.ActiveWorkbook.Path & "\Bin\file.txt"
FooterFilePath = Application.ActiveWorkbook.Path & "\Bin\footer.txt"
PlusChar = Chr(43)  'i.e. "+" sign

Now I am trying to merge FilePath and FooterFilePath and write the combined result in FilePath again i.e. overwriting it. For that I am using followng line which doesn't work:

Shell "cmd.exe copy /c & FilePath & PlusChar & FooterFilePath & FilePath", 0

I know I have syntaxing issue here but I just don't know how to pass three variables into Shell command.

Body:
You have to put the variables outside the enclosing double-quotes. also you should insert blanks between the different names so that your command does not get the names combined in one name. Try this:

Shell "cmd.exe copy /c " & FilePath & " " & PlusChar & " " & FooterFilePath & " " & FilePath, 0

But:

There's no reason to have a variable for the +

Your drive's name is missing in the paths

/C is an option for the cmd program, not for the copy command.

It is useful to print that expression in the immediate window to verify it before execution. To do so, you can put it in a String variable and debug.print it before execution:

This would be correct:

Dim FilePath As String, FooterFilePath As String, myCommand As String

FilePath = Application.ActiveWorkbook.Path & "C:\Bin\file.txt"
FooterFilePath = Application.ActiveWorkbook.Path & "C:\Bin\footer.txt"

myCommand = "cmd /c copy " & FilePath & " + " & FooterFilePath & " " & FilePath
Debug.Print myCommand
Shell myCommand, 0


问:
Problem to connect mysql and Java
I am trying to connect Java code to mySQL. Here is the error that I got. I dont understand why no driver is found since I have put the connector jar at the classpath.

```<code>Class Not Found Exception:
No suitable driver found for jdbc:mysql://localhost/hpdata?user=root&password=12
3456
Exception in thread "main" java.lang.NullPointerException
    at edu.indiana.iucbrf.feature.featurespec.FeatureSpecRDB.open(FeatureSpe
cRDB.java:122)
    at edu.indiana.iucbrf.feature.featurespec.FeatureSpecRDB.<init>(FeatureS
pecRDB.java:66)
    at edu.indiana.iucbrf.domain.componentfactory.RDBComponentFactory.constr
uctProblemFeatureSpecCollection(RDBComponentFactory.java:112)
    at edu.indiana.iucbrf.domain.Domain.<init>(Domain.java:239)
    at edu.indiana.iucbrf.domain.Domain.<init>(Domain.java:197)
    at edu.indiana.iucbrf.examples.honeypotRDBTemplate.HDomainRDB.<in
it>(HDomainRDB.java:56)
    at edu.indiana.iucbrf.examples.hRDBTemplate.HSystemRDB.set
 upDomain(HSystemRDB.java:198)
    at edu.indiana.iucbrf.examples.hRDBTemplate.HSystemRDB.<in
it>(HSystemRDB.java:131)
    at edu.indiana.iucbrf.examples.hRDBTemplate.HTestClassRDB.
main(HTestClassRDB.java:65)
</code>```

Here is my code :

```<code>   private static void flush() {

  Class.forName("com.mysql.jdbc.Driver").newInstance();

    try {

   conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hpdata?user=root&password=123456");

      } catch (Exception e) {
          System.out.println("Class Not Found Exception:");
          System.out.println(e.getMessage());
      }
</code>```

答:
```<code>try {
 String driverName = "com.mysql.jdbc.Driver";
 Class.forName(driverName);

 String serverName = "localhost";
 String mydatabase = "hpdata";
 String url = "jdbc:mysql :// " + serverName + "/" + mydatabase;

 String username = "root";
 String password = "123456";
 connection = DriverManager.getConnection(url, username, password);
} catch(Exception e) {
 // appropriate action
}
</code>```

Title: Problem to connect mysql and Java

Body:
I am trying to connect Java code to mySQL. Here is the error that I got. I dont understand why no driver is found since I have put the connector jar at the classpath.

Class Not Found Exception:
No suitable driver found for jdbc:mysql://localhost/hpdata?user=root&password=12
3456
Exception in thread "main" java.lang.NullPointerException
    at edu.indiana.iucbrf.feature.featurespec.FeatureSpecRDB.open(FeatureSpe
cRDB.java:122)
    at edu.indiana.iucbrf.feature.featurespec.FeatureSpecRDB.<init>(FeatureS
pecRDB.java:66)
    at edu.indiana.iucbrf.domain.componentfactory.RDBComponentFactory.constr
uctProblemFeatureSpecCollection(RDBComponentFactory.java:112)
    at edu.indiana.iucbrf.domain.Domain.<init>(Domain.java:239)
    at edu.indiana.iucbrf.domain.Domain.<init>(Domain.java:197)
    at edu.indiana.iucbrf.examples.honeypotRDBTemplate.HDomainRDB.<in
it>(HDomainRDB.java:56)
    at edu.indiana.iucbrf.examples.hRDBTemplate.HSystemRDB.set
 upDomain(HSystemRDB.java:198)
    at edu.indiana.iucbrf.examples.hRDBTemplate.HSystemRDB.<in
it>(HSystemRDB.java:131)
    at edu.indiana.iucbrf.examples.hRDBTemplate.HTestClassRDB.
main(HTestClassRDB.java:65)

Here is my code :

   private static void flush() {

  Class.forName("com.mysql.jdbc.Driver").newInstance();

    try {

   conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hpdata?user=root&password=123456");

      } catch (Exception e) {
          System.out.println("Class Not Found Exception:");
          System.out.println(e.getMessage());
      }


问:
RESTful API - Flask -> Jquery - Error
I am studying about RESTful APIs and I decided to create a small server and a consumer to test.

I'm using Flask as a server and an example I took on the internet to consume this API. But I'm having some problems.

The error message on the console says this: XMLHttpRequest cannot load http://127.0.0.1:5000/api/tasks. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

But I do not know what it can be.

Flask server code:

```<code>from flask import Flask, jsonify

app = Flask(__name__)

tasks = [
    {
        'id':1,
        'title': u'Estudo',
        'description': u'Sistemas Distribuidos',
        'done':True
    },
    {
        'id':2,
        'title': u'Monitoria',
        'description': u'Programacao e Algoritmos',
        'done': False
    }
]

@app.route('/')
def index():
    return "URL PARA O ACESSO DA API: '/api/tasks'"

@app.route('/api/tasks', methods=['GET'])
def get_tasks():
    return jsonify({'tasks': tasks})

if __name__ == '__main__':
    app.run(debug=True)
</code>```

Example code using Jquery:

```<code><!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
  <meta charset="utf-8">
  <title>Mashape Query</title>
  <script>
    function doIt() {
 var output = $.ajax({
    url: 'http://127.0.0.1:5000/api/tasks', // The URL to the API. You can get this by clicking on "Show CURL example" from an API profile
    type: 'GET', // The HTTP Method, can be GET POST PUT DELETE etc
    data: {}, // Additional parameters here
    dataType: 'json',
    success: function(data) {
        //console.log(data);
        alert(data);
        document.getElementById("output").innerHTML = data.source;
        },
    error: function(err) { alert(err.getText); }
});

}

</script>
</head>
<body>

  <button onclick="doIt()">Run the request</button>
  <div id="output">The API request is:</div>

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

答:
Most likely the easiest is to install https://flask-cors.readthedocs.io/en/latest/.

From their Simple Usage guide:

```<code>from flask import Flask
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
    return "Hello, cross-origin-world!"
</code>```

If you don't want to install another package, you can try to use the solution from here https://stackoverflow.com/a/33091782/2525104 by Salvador Dali.

```<code>@app.route('your route', methods=['GET'])
def yourMethod(params):
    response = flask.jsonify({'some': 'data'})
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response
</code>```

Title: RESTful API - Flask -> Jquery - Error

Body:
I am studying about RESTful APIs and I decided to create a small server and a consumer to test.

I'm using Flask as a server and an example I took on the internet to consume this API. But I'm having some problems.

The error message on the console says this: XMLHttpRequest cannot load http://127.0.0.1:5000/api/tasks. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

But I do not know what it can be.

Flask server code:

from flask import Flask, jsonify

app = Flask(__name__)

tasks = [
    {
        'id':1,
        'title': u'Estudo',
        'description': u'Sistemas Distribuidos',
        'done':True
    },
    {
        'id':2,
        'title': u'Monitoria',
        'description': u'Programacao e Algoritmos',
        'done': False
    }
]

@app.route('/')
def index():
    return "URL PARA O ACESSO DA API: '/api/tasks'"

@app.route('/api/tasks', methods=['GET'])
def get_tasks():
    return jsonify({'tasks': tasks})

if __name__ == '__main__':
    app.run(debug=True)

Example code using Jquery:

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Mashape Query</title>

  <button onclick="doIt()">Run the request</button>

The API request is:

Body:
Most likely the easiest is to install https://flask-cors.readthedocs.io/en/latest/.

From their Simple Usage guide:

from flask import Flask
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
    return "Hello, cross-origin-world!"

If you don't want to install another package, you can try to use the solution from here https://stackoverflow.com/a/33091782/2525104 by Salvador Dali.

@app.route('your route', methods=['GET'])
def yourMethod(params):
    response = flask.jsonify({'some': 'data'})
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response


问:
Satellizer login JWT token is gone when page refresh

I am using the Angular-satellizer extension for the login/register feature but I am stuck at number 7.

Token was saved to localStorage but I when refresh the page it's gone and $auth.isAuthenticated() function is returning false.

```<code>.controller('loginCtrl', function($scope, $state, $auth, jwtHelper) {
  $scope.login = function() {
    $auth.login($scope.user)
      .then(function(response) {
        var gelenToken = response.data;
        var tokenPayload = jwtHelper.decodeToken(gelenToken.token);
        console.log(JSON.stringify(tokenPayload)); // Output:{"sub":"1","iat":1496346513,"exp":1497556113,"data":{"role":"admin"}}
        localStorage.setItem('token', JSON.stringify(tokenPayload));
        $state.go('baba.manga');
      })
  };
})
</code>```

答:
Maybe when you refresh the page , you are reseting the localStorage and your last token gone.

Try this

```<code>// if the localScore is not set then initialize it
if(localStorage.getItem('token') === null) {
     localStorage.setItem('token', JSON.stringify(tokenPayload));
}
</code>```

Body:
I am using the Angular-satellizer extension for the login/register feature but I am stuck at number 7.

Token was saved to localStorage but I when refresh the page it's gone and $auth.isAuthenticated() function is returning false.

.controller('loginCtrl', function($scope, $state, $auth, jwtHelper) {
  $scope.login = function() {
    $auth.login($scope.user)
      .then(function(response) {
        var gelenToken = response.data;
        var tokenPayload = jwtHelper.decodeToken(gelenToken.token);
        console.log(JSON.stringify(tokenPayload)); // Output:{"sub":"1","iat":1496346513,"exp":1497556113,"data":{"role":"admin"}}
        localStorage.setItem('token', JSON.stringify(tokenPayload));
        $state.go('baba.manga');
      })
  };
})

Body:
Maybe when you refresh the page , you are reseting the localStorage and your last token gone.

Try this

// if the localScore is not set then initialize it
if(localStorage.getItem('token') === null) {
     localStorage.setItem('token', JSON.stringify(tokenPayload));
}


问:
Finding the frequency of object key VALUES in an array of objects
I have an array of objects (police data, each one is a crime). The array of objects is 1000 in length.

Every object has a key/value such as community_area: 22.

I am trying to iterate over the array of objects to find the top three community areas that exist in the array. So if community areas 22, 70 and 1 had the most crime (each object occurrence) it would return those three.

What is an efficient way of doing this other than creating arrays of the 77 different community areas with the crimes then comparing the length?

答:
I came up with this code - it works.  Looks very similar to the other answer.

var testData = [{
  area: 22
}, {
  area: 23
}, {
  area: 17
}, {
  area: 12
}, {
  area: 45
}, {
  area: 12
}, {
  area: 17
}, {
  area: 23
}, {
  area: 34
}, {
  area: 22
}, {
  area: 12
}, {
  area: 45
}, {
  area: 45
}, {
  area: 45
}];

var result = testData.reduce((acc, obj) => {
  if (acc.hasOwnProperty(obj.area)) {
    acc[obj.area]++;
  } else {
    acc[obj.area] = 1;
  };
  return acc;
}, {});

var resultArr = [];
for ( var key in result ) { resultArr.push([key, result[key]]) }

resultArr.sort( (a, b) => b[1] - a[1] );
// now output the first 3 items
for ( var i = 0; i < resultArr.length && i < 3; i++) {
    console.log( `area: ${resultArr[i][0]} =  count ${resultArr[i][1]}`);
    }

    ```


问:
Returning words from a string array with symbols between them in java?
```<code>public String onGoogleCommand(String[] args) {
    if(args.length == 0){
        return "Type in a question after the google command!";
    }
    if(args.length >= 1){
        return "https://www.google.com/#q=" + args[0] + "+" + args[1] + "+" + args[2];
    }
    return "What?";
}
</code>```

What I am asking about is the part where I say return "https://www.google.com/#q=" + args[0] + "+" + args[1] + "+" + args[2];. Obviously, this probably isn't the best way to code a search function, but how can I automate this so that the words from the String[] args automatically get put into my return statement with "+" between each of the words so that it would return something like https://www.google.com/#q=please+help+me+with+this+question?

答:
You could iterate over the args[] array and build your query string:

```<code>public String onGoogleCommand(String[] args) {
    if(args == null || args.length == 0) {
        return "Type in a question after the google command!";
    }
    StringBuilder queryString = new StringBuilder("https://www.google.com/#q=");
    queryString.append(args[0]);
    for (int i=1; i < args.length; ++i) {
        queryString.append("+").append(args[i]);
    }

    return queryString.toString();
}
</code>```

Body:
public String onGoogleCommand(String[] args) {
    if(args.length == 0){
        return "Type in a question after the google command!";
    }
    if(args.length >= 1){
        return "https://www.google.com/#q=" + args[0] + "+" + args[1] + "+" + args[2];
    }
    return "What?";
}

What I am asking about is the part where I say return "https://www.google.com/#q=" + args[0] + "+" + args[1] + "+" + args[2];. Obviously, this probably isn't the best way to code a search function, but how can I automate this so that the words from the String[] args automatically get put into my return statement with "+" between each of the words so that it would return something like https://www.google.com/#q=please+help+me+with+this+question?

Body:
You could iterate over the args[] array and build your query string:

public String onGoogleCommand(String[] args) {
    if(args == null || args.length == 0) {
        return "Type in a question after the google command!";
    }
    StringBuilder queryString = new StringBuilder("https://www.google.com/#q=");
    queryString.append(args[0]);
    for (int i=1; i < args.length; ++i) {
        queryString.append("+").append(args[i]);
    }

    return queryString.toString();
}


问:
PHP script to output individual PDF for each SQL row - FPDF
I am in learnig process of php hoping to find some directions here on stack.

I am tring to write a simpe script that can output an individual pdf for all the rows of a specific table

Here is my script i get the $html variable printed on pdF but only 1 file and 1 row. Then the other problem is when i try to output the file instead of displaying it on browser I get this error.

```<code>Fatal error: Uncaught exception 'Exception' with message 'FPDF error:           Incorrect output destination: ./output/pdf_ganesh.pdf' in   C:\xampp\htdocs\crud\Classes\fpdf.php:271 Stack trace: #0 C:\xampp\htdocs\crud\Classes\fpdf.php(1028): FPDF->Error('Incorrect outpu...') #1 C:\xampp\htdocs\crud\makepdf.php(38): FPDF->Output('./output/pdf_ga...') #2 {main} thrown in C:\xampp\htdocs\crud\Classes\fpdf.php on line 271
</code>```

I would like the output to be in the project in a specific folder.

Thanks ahead.

```<code><?php

$databaseHost = 'localhost';
$databaseName = 'test';
$databaseUsername = 'root';
$databasePassword = '';
$db = mysqli_connect($databaseHost, $databaseUsername, $databasePassword,               $databaseName);

require('./Classes/fpdf.php');

$users = mysqli_query($db, "SELECT * FROM users ORDER BY id DESC");

foreach ($users as $user) {

 $pdf = new FPDF('P','mm','A4');

 $pdf->AddPage();

$on_id=$user['id'];
$on_name=$user['name'];
$on_age=$user['age'];
$on_email=$user['email'];
$on_safe_name=strtolower(str_replace(' ', '_', $on_name));
$on_filename="pdf_$on_safe_name.pdf";

$html = $on_name.'</br>'.$on_age.'</br>'.$on_email;
 }

 $pdf->SetFont('Arial','B',16);
 $pdf->Write(5, $html);
 $pdf->Output('./output/'.$on_filename);
 ?>
</code>```

答:
The error seems to be pointing to this line

$pdf->Output('./output/'.$on_filename);

Body:
I am in learnig process of php hoping to find some directions here on stack.

I am tring to write a simpe script that can output an individual pdf for all the rows of a specific table

Here is my script i get the $html variable printed on pdF but only 1 file and 1 row. Then the other problem is when i try to output the file instead of displaying it on browser I get this error.

Fatal error: Uncaught exception 'Exception' with message 'FPDF error:           Incorrect output destination: ./output/pdf_ganesh.pdf' in   C:\xampp\htdocs\crud\Classes\fpdf.php:271 Stack trace: #0 C:\xampp\htdocs\crud\Classes\fpdf.php(1028): FPDF->Error('Incorrect outpu...') #1 C:\xampp\htdocs\crud\makepdf.php(38): FPDF->Output('./output/pdf_ga...') #2 {main} thrown in C:\xampp\htdocs\crud\Classes\fpdf.php on line 271

I would like the output to be in the project in a specific folder.

Thanks ahead.

<?php

$databaseHost = 'localhost';
$databaseName = 'test';
$databaseUsername = 'root';
$databasePassword = '';
$db = mysqli_connect($databaseHost, $databaseUsername, $databasePassword,               $databaseName);

require('./Classes/fpdf.php');

$users = mysqli_query($db, "SELECT * FROM users ORDER BY id DESC");

foreach ($users as $user) {

 $pdf = new FPDF('P','mm','A4');

 $pdf->AddPage();

$on_id=$user['id'];
$on_name=$user['name'];
$on_age=$user['age'];
$on_email=$user['email'];
$on_safe_name=strtolower(str_replace(' ', '_', $on_name));
$on_filename="pdf_$on_safe_name.pdf";

$html = $on_name.'
'.$on_age.'
'.$on_email;
 }

 $pdf->SetFont('Arial','B',16);
 $pdf->Write(5, $html);
 $pdf->Output('./output/'.$on_filename);
 ?>


问:
Regular Expression (REGEX) to match : or . or '
i want to use regex to check if i have ' or . or :

i should add ? before it

for example

Rue de l'etrang

should be like this

Rue de l?'etrang

or

Rue de l'etrang: nancy

should be like this

Rue de l?'etrang?: nancy

答:
Here is some sample code for testing a match:</p>

```<code>$str = 'Rue de l\'etrang';
if(preg_match('/[:\'.]/i', $str))
{
    echo 'found match';
}
else
{
    echo 'match not found';
}
</code>```

Body:
Here is some sample code for testing a match:

$str = 'Rue de l\'etrang';
if(preg_match('/[:\'.]/i', $str))
{
    echo 'found match';
}
else
{
    echo 'match not found';
}


问:
undefined reference uuid_generate ubuntu
I have installed libuuid using the command below.

```<code>sudo apt-get install uuid-dev
</code>```

And is properly installed from the terminal.

Then, i include <uuid/uuid.h> header file.
  But while calling function uuid-generate as under it is giving  reference error

```<code>  uuid_t newUUID;
  uuid_generate(newUUID);
</code>```

答:
I have resolved the above issue. Instead of using terminal to install the uuid generator, following is my step that i followed:

call sudo apt-get install uuid-dev command on terminal

Go to properties menu item, under project menu and add uuid library by selecting add package option.

Then do include header #include uuid/uuid.h

Body:
I have installed libuuid using the command below.

sudo apt-get install uuid-dev

And is properly installed from the terminal.

Then, i include <uuid/uuid.h> header file.
  But while calling function uuid-generate as under it is giving  reference error

  uuid_t newUUID;
  uuid_generate(newUUID);


问:
Does reflection methods such as GetField and GetValue perform "referencing" or "access" in ECMA specification terms?
What I really want to know is which reflection methods will trigger type initialization? It's a bit unclear to me. Specifically, will the two mentioned methods, GetField and GetValue, trigger type initialization if applied to static fields? I've already tried looking into the matter, and as far as I understand performing actions such as referencing or accessing static fields will trigger type initialization of all static fields. Below I have quoted sections of the specification that I think are relevant, but the use of wording such as "referencing" and "access" is precisely where my hesitation stems:

What actions actually qualifies as "access"?

Does getting FieldInfo metadata for a field count as "referencing" or "accessing" the field?

Please help me find the relevant parts of the specifications so I know that my code* is safe and spec. compliant and doesn't simply "happen to work" because of some undocumented implementation detail or because the planets happen to be aligned just right.

*My code passes testing but relies on type initialization behavior. My code is not shown here because it is verbose and the question is not about me just wanting a "your code looks ok" reply, but rather I want to learn how and why such that I can asses whether my code is spec. compliant or not myself, and (assuming it is compliant) reason about what changes I can and cannot make to it without having to ask a new question every time I do so.

So far I know about the following pieces of the specifications, which uses the aforementioned terms "referencing" and "access":

I know about ECMA-334
(C# language specification), Static field initialization, section 17.4.5.1

If a static constructor (§17.11)
  exists in the class, execution of the static field initializers occurs immediately prior to executing that static
  constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to
  the first use of a static field of that class.

Also know about ECMA-334
(C# language specification), Static constructors, section 17.11

The static constructor for a non-generic class executes at most once in a given application domain. The static
  constructor for a generic class declaration executes at most once for each closed constructed type
  constructed from the class declaration (§25.1.5). The execution of a static constructor is triggered by the first
  of the following events to occur within an application domain:

An instance of the class is created.

Any of the static members of the class are referenced.

If a class contains the Main method (§10.1) in which execution begins, the static constructor for that class
  executes before the Main method is called. If a class contains any static fields with initializers, those
  initializers are executed in textual order immediately prior to executing the static constructor (§17.4.5).

And more relevantly ECMA-335
(CLI specification), Class type definition, part I, section 8.9.5

[...]
  The semantics of when and what triggers execution of such type initialization methods, is as follows:

A type can have a type-initializer method, or not.

A type can be specified as having a relaxed semantic for its type-initializer method (for convenience below, we call this relaxed semantic BeforeFieldInit).

If marked BeforeFieldInit then the type’s initializer method is executed at, or sometime before, first access to any static field defined for that type.

If not marked BeforeFieldInit then that type’s initializer method is executed at (i.e., is triggered by):

a. first access to any static field of that type, or

b. first invocation of any static method of that type, or

c. first invocation of any instance or virtual method of that type if it is a value type or

d. first invocation of any constructor for that type.

Execution of any type's initializer method will not trigger automatic execution of any initializer methods defined by its base type, nor of any interfaces that the type implements.

Related MSDN links:

Type.GetField Method

FieldInfo Class

FieldInfo.GetValue Method

答:
What I really want to know is which reflection methods will trigger type initialization?

[...]

Specifically, will the two mentioned methods, GetField and GetValue, trigger type initialization if applied to static fields?

FieldInfo.GetValue triggers the type initialization. It's from the experiment observation. It all depends on an implementation, and there will be no proofs. It will not necessary work in all cases, as Reflection does not need to follow any specs, as the specifications are not covering Reflection. There are some signs that you can get a uninitialized field, but I could not produce the code to make it happen.

typeof(), Type.GetType, and Type.GetField most likely do not trigger the type initialization. But again, this is from an observation.

If you need to make sure that your type initializer will be called at/before any particular time, you need to call RuntimeHelpers.RunClassConstructor method. This is the only method which guarantees that the type initializer will be invoked and only once in a lifetime of an app domain.

What actions actually qualifies as "access"?

None of these actions, as again reflections is not covered by the specs and so these terms do not apply here.

Does getting FieldInfo metadata for a field count as "referencing" or "accessing" the field?

Neither.

It's not clear from the specification, but this is how I understand the difference between "accessing" and "referencing":

Access is when you invoke this member (method or property) or get/set its value (field)

A method references a member when the body of the method has an access expression to this member.

PS: It's still not clear what you are asking and what particular problem you try to solve.


问:
chrome extension - update tab without changing url
I'm building a small chrome extension, that can open an page in a proxy
for example i'm opening www.mysite.com, and the clicking on my extension button, and it update the page to www.myproxy.net/q=www.mysite.com.
it's working like a charm, but i want to hide the chnage in the adress bar, so the url will remain the original site.
i made a few searches, but can't find out how to do such a thing.

can you please help me?

thanks

my manifest file

```<code>{
"name": "proxy",
"version": "1",
"browser_action": {
    "default_icon" : "icon.png"
},
"permissions": ["tabs"],
"manifest_version": 2,
"background":{
    "scripts": ["popup.js"]
},
"commands": {
  "_execute_browser_action": {
    "suggested_key": {
      "default": "Ctrl+B",
      "windows": "Ctrl+B"
    }
  }
}
</code>```

}

my popup.js

```<code>chrome.browserAction.onClicked.addListener(function(activeTab){
chrome.tabs.query({active: true, currentWindow: true}, function(tab) {
    var newURL = "http://myproxy.net/?q=" + tab[0].url;
    chrome.tabs.update(undefined, {url: newURL});
});
</code>```

});

答: AFAIK, this is not possible via Chrome API. The fact that you couldn't find searches means it's not doable yet. Unless maybe, you can write your own implementation.</p>

Body:
I'm building a small chrome extension, that can open an page in a proxy
for example i'm opening www.mysite.com, and the clicking on my extension button, and it update the page to www.myproxy.net/q=www.mysite.com.
it's working like a charm, but i want to hide the chnage in the adress bar, so the url will remain the original site.
i made a few searches, but can't find out how to do such a thing.

can you please help me?

thanks

my manifest file

{
"name": "proxy",
"version": "1",
"browser_action": {
    "default_icon" : "icon.png"
},
"permissions": ["tabs"],
"manifest_version": 2,
"background":{
    "scripts": ["popup.js"]
},
"commands": {
  "_execute_browser_action": {
    "suggested_key": {
      "default": "Ctrl+B",
      "windows": "Ctrl+B"
    }
  }
}

}

my popup.js

chrome.browserAction.onClicked.addListener(function(activeTab){
chrome.tabs.query({active: true, currentWindow: true}, function(tab) {
    var newURL = "http://myproxy.net/?q=" + tab[0].url;
    chrome.tabs.update(undefined, {url: newURL});
});

});


问:
Get checksum of the source codes in Android library
I am developing an android library and I want to apply a tamper-detection mechanism to my code, since it calls some sensitive financial web services.

What I'm going to implement is to calculate the checksum of the apk ( or important parts of it), programmatically on the runtime, so I can prevent a repackaged or recompiled apk from being able to do any harm (tamper prevention).

What I have come up with so far, is to calculate the checksum of the applicationInfo.publicSourceDir. but I'm not sure what happens with the apps that have multiple dex files or multiple splitApks.

What is the most reliable way to calculate checksum based on the code-base of an application in Android, programmatically?

答:
The checksum approach can be applied to single file or zip files. It will be a lengthy process to check the checksum of all files. I think you are in the wrong direction.

Firstly, There is no clear solution to this problem. Any app can be hacked - you can just make it hard to hack.

This is what is done to make it hard -

Encrypt the your apk - so that its hard to get to your source code.
refer - APK to protect apk from reverse engineering - Check obfuscating
tools.

Use data encryption while sending/receiving data from WebService. You can use HMAC to protect the data. Make sure your server is smart enough to block user/requesting-apps in case there are multiple bad calls. HMAC is easy to implement and there are libraries to generate HMAC keys.


问:
Convert a Class to a String to match == condition in lambda Query
I need a way to get matching records of the ProcessedBy column and user.Id (which in db share exact same string but in different tables).

Short: 'user' is an instance of the ApplicationUser Class and ProcessedBy is a property in LI class of type ApplicationUser.
Problem: If I apply ProcessedBy.ToString() there will be a error "Cannot convert ApplicationUser to string". ProcessedBy is a property of class ApplicationUser which contains Id directly, user is an object of class ApplicationUser which contains Id as a string property, not my design I need to figure this out.

```<code>public static void UpdateFilesProcessedByUser(ApplicationUser user)
{
    ApplicationDbContext db = new ApplicationDbContext();

    //Cannot convert ApplicationUser ProcessedBy to string, user.Id is a string
    IQueryableL<LI> DbQueryGet = db.LIs.Where(l =>
        l.ProcessedBy.ToString() == user.Id);

    var GetNumberOfFiles = DbQueryGet.ToList().Count();
    IQueryable<ApplicationUser> DbQueryUpdate = db.Users.Where(u => u.Id == user.Id);
    var GetUser = DbQueryUpdate.ToList();
    GetUser[0].FilesProcessed = GetNumberOfFiles;
    db.SaveChanges();
}
</code>```

And LI class which contains ProcessedBy :

```<code>[Table("LIs")]
public class LI
{
  .
  .
  .
  public virtual ApplicationUser ProcessedBy {get; set;}
}
</code>```

答:
Here is the solution , if i have understood your problem

I hope as a first thing , you want to convert the Applicationuser.id to the string ,by default Applicationuser.id is the guid id .here is the reference link:https://msdn.microsoft.com/en-us/magazine/dn818488.aspx?f=255&MSPPError=-2147217396

So to convert the guid to string ,here is the example:

```<code>Guid userid = user.Id;
string usrid = userid.ToString();
</code>```

Addition reference:https://www.codeproject.com/Questions/124616/converting-guid-to-string-and-vice-versa

Addition Info:

Below is the another way of how you can easily take the user id and user object

```<code>var user = UserManager.FindById(User.Identity.GetUserId());
</code>```

Outside controller:

```<code>System.Web.HttpContext.Current.User.Identity.GetUserId();
</code>```

Useful reference: https://stackoverflow.com/a/22835540/3397630

Hope the above information was useful.

Thanks
Karthik

Body:
I need a way to get matching records of the ProcessedBy column and user.Id (which in db share exact same string but in different tables).

Short: 'user' is an instance of the ApplicationUser Class and ProcessedBy is a property in LI class of type ApplicationUser.
Problem: If I apply ProcessedBy.ToString() there will be a error "Cannot convert ApplicationUser to string". ProcessedBy is a property of class ApplicationUser which contains Id directly, user is an object of class ApplicationUser which contains Id as a string property, not my design I need to figure this out.

public static void UpdateFilesProcessedByUser(ApplicationUser user)
{
    ApplicationDbContext db = new ApplicationDbContext();

    //Cannot convert ApplicationUser ProcessedBy to string, user.Id is a string
    IQueryableL
 DbQueryGet = db.LIs.Where(l =>
        l.ProcessedBy.ToString() == user.Id);

    var GetNumberOfFiles = DbQueryGet.ToList().Count();
    IQueryable<ApplicationUser> DbQueryUpdate = db.Users.Where(u => u.Id == user.Id);
    var GetUser = DbQueryUpdate.ToList();
    GetUser[0].FilesProcessed = GetNumberOfFiles;
    db.SaveChanges();
}

And LI class which contains ProcessedBy :

[Table("LIs")]
public class LI
{
  .
  .
  .
  public virtual ApplicationUser ProcessedBy {get; set;}
}

Body:
Here is the solution , if i have understood your problem

I hope as a first thing , you want to convert the Applicationuser.id to the string ,by default Applicationuser.id is the guid id .here is the reference link:https://msdn.microsoft.com/en-us/magazine/dn818488.aspx?f=255&MSPPError=-2147217396

So to convert the guid to string ,here is the example:

Guid userid = user.Id;
string usrid = userid.ToString();

Addition reference:https://www.codeproject.com/Questions/124616/converting-guid-to-string-and-vice-versa

Addition Info:

Below is the another way of how you can easily take the user id and user object

var user = UserManager.FindById(User.Identity.GetUserId());

Outside controller:

System.Web.HttpContext.Current.User.Identity.GetUserId();

Useful reference: https://stackoverflow.com/a/22835540/3397630

Hope the above information was useful.

Thanks
Karthik


问:
HTML text doesn't print to screen when using canvas in conjunction
In this snippet of code, even though I align the text far outside of the canvas boundaries, the text shows up below the canvas height.  I'm new to HTML and I question why using a canvas seems to block the whole row it's on.  I also want to know if there is a way around this, so I can have my canvas and have the text to the right of it on the same row.</p>

```<code><!DOCTYPE html>
<html>
<canvas id= "myCanvas" width="600" height="600">
</canvas>
<head>
<title>test</title>
<meta name="generator" content="BBEdit 11.6" />
</head>
<body>
<p style="text-align:right">JavaScript can change the content of an HTML element:</p>
</body>
</html>
</code>```

答:
```<code><!DOCTYPE html>
<html>
<canvas id="myCanvas" width="600" height="600" style="border:1px solid #000000;">
</canvas>

<head>
  <title>test</title>
  <meta name="generator" content="BBEdit 11.6" />
</head>

<body>
  <p style="text-align:right; display: inline-block;">JavaScript can change the content of an HTML element:</p>
</body>

</html>
</code>```

Body:
In this snippet of code, even though I align the text far outside of the canvas boundaries, the text shows up below the canvas height.  I'm new to HTML and I question why using a canvas seems to block the whole row it's on.  I also want to know if there is a way around this, so I can have my canvas and have the text to the right of it on the same row.

<!DOCTYPE html>

<canvas id= "myCanvas" width="600" height="600">
</canvas>

<title>test</title>
<meta name="generator" content="BBEdit 11.6" />

JavaScript can change the content of an HTML element:


问:
The "table" in sqlContext.table
I'm working my way through a book on Spark and I'm on a section dealing with the join method for dataframes. In this example, the "trips" table is being joined with the "stations" table:

```<code>trips = sqlContext.table("trips")
stations = sqlContext.table("stations")
joined = trips.join(stations, trips.start_terminal == stations.station_id)
joined.printSchema()
</code>```

The data is supposed to come from two spreadsheets, trips.csv and stations.csv, but I don't know how Spark is supposed to figure that out. It seems to me that there should be a line indicating where "trips" and "stations" are supposed to come from.

If I try something like

```<code>trips = sqlContext.table('/home/l_preamble/Documents/trips.csv')
</code>```

it doesn't like it "pyspark.sql.utils.ParseException: u"\nextraneous input '/' expecting {'SELECT', 'FROM', 'ADD'..."

So how can I point it in the direction of the data? Any help would be appreciated.

答:
I think, maybe you need this </p>

```<code>spark = SparkSession.builder.appName('MyApp').getOrCreate()
df_trips = spark.read.load(path='/home/l_preamble/Documents/trips.csv', format='csv', sep=',')
df_trips.createOrReplaceTempView('trips')
result = spark.sql("""select * from trips""")
</code>```

Title: The "table" in sqlContext.table

Body:
I'm working my way through a book on Spark and I'm on a section dealing with the join method for dataframes. In this example, the "trips" table is being joined with the "stations" table:

trips = sqlContext.table("trips")
stations = sqlContext.table("stations")
joined = trips.join(stations, trips.start_terminal == stations.station_id)
joined.printSchema()

The data is supposed to come from two spreadsheets, trips.csv and stations.csv, but I don't know how Spark is supposed to figure that out. It seems to me that there should be a line indicating where "trips" and "stations" are supposed to come from.

If I try something like

trips = sqlContext.table('/home/l_preamble/Documents/trips.csv')

it doesn't like it "pyspark.sql.utils.ParseException: u"\nextraneous input '/' expecting {'SELECT', 'FROM', 'ADD'..."

So how can I point it in the direction of the data? Any help would be appreciated.

Body:
I think, maybe you need this

spark = SparkSession.builder.appName('MyApp').getOrCreate()
df_trips = spark.read.load(path='/home/l_preamble/Documents/trips.csv', format='csv', sep=',')
df_trips.createOrReplaceTempView('trips')
result = spark.sql("""select * from trips""")


问:
Calculation with textWatcher android
In my project I have 7 EditText field.
User will only need to fill their own value in first two EditText.

I need a series calculation like this...

(after user input) subtract ed1-ed2 the result automatically show in ed3 field.

multiply ed3*2 = result show in ed4 field automatically.

multiply ed3*3= result will show in ed5 field.

multiply ed3*4=result will show in ed6 field.

Finally sum of ed4+ed5+ed6= result will show in ed7 field automatically.

So how to do it any one please help.
Thank you in Advance.

答:
All EditText use a same TextWatcher. A simple solution like this.</p>

```<code>    EditText et1;
    EditText et2;
    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            int num1 = Integer.valueOf(et1.getText().toString()); // Make sure you get a number
            int num2 = Integer.valueOf(et2.getText().toString());
            // do your calculation
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };
    et1.addTextChangedListener(textWatcher);
    et2.addTextChangedListener(textWatcher);
</code>```

Title: Calculation with textWatcher android

Body:
All EditText use a same TextWatcher. A simple solution like this.

    EditText et1;
    EditText et2;
    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            int num1 = Integer.valueOf(et1.getText().toString()); // Make sure you get a number
            int num2 = Integer.valueOf(et2.getText().toString());
            // do your calculation
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };
    et1.addTextChangedListener(textWatcher);
    et2.addTextChangedListener(textWatcher);


问:
How to run 2 loops at the same time using asyncio
I'm pretty new to asyncio, so lot of things are still way too far from my understanding yet, anyway.

I got a main while loop that basically just draws some stuff on the screen using PyGame, and what i'd like to do, is to run another while loop asynchronously, that keeps updating some data to be rendered.

```<code>async def update(reader, writer):
    while True:
        json_data = await reader.read(1000)
        self.json_data = json.loads(json_data)

def run(self):
    while True:
        self.draw()
</code>```

答:
Try threading:

```<code>import threading

async def update(reader, writer):
    while True:
        json_data = await,reader.read(1000)
        self.json_data = json.loads(json_data)

def run(self):
    while True:
        self.draw()

t = threading.Thread(target=update,args=(reader,writer))
t2 = threading.Thread(target=run,args=(self))
t.start()
t2.start()
</code>```

Threading will run both processes at once!

Body:
I'm pretty new to asyncio, so lot of things are still way too far from my understanding yet, anyway.

I got a main while loop that basically just draws some stuff on the screen using PyGame, and what i'd like to do, is to run another while loop asynchronously, that keeps updating some data to be rendered.

async def update(reader, writer):
    while True:
        json_data = await reader.read(1000)
        self.json_data = json.loads(json_data)

def run(self):
    while True:
        self.draw()

Body:
Try threading:

import threading

async def update(reader, writer):
    while True:
        json_data = await,reader.read(1000)
        self.json_data = json.loads(json_data)

def run(self):
    while True:
        self.draw()

t = threading.Thread(target=update,args=(reader,writer))
t2 = threading.Thread(target=run,args=(self))
t.start()
t2.start()

Threading will run both processes at once!


问:
Activating Anaconda Environment in VsCode
I have Anaconda working on my system and VsCode working, but how do I get VsCode to activate a specific environment when running my python script?</p>

答:
I found a hacky solution replace your environment variable for the original python file so instead it can just call from the python.exe from your anaconda folder, so when you reference python it will reference anaconda's python.

So your only python path in env var should be like:

```<code>"C:\Anaconda3\envs\py34\", or wherever the python executable lives
</code>```

If you need more details I don't mind explaining. :)

Body:
I found a hacky solution replace your environment variable for the original python file so instead it can just call from the python.exe from your anaconda folder, so when you reference python it will reference anaconda's python.

So your only python path in env var should be like:

"C:\Anaconda3\envs\py34\", or wherever the python executable lives

If you need more details I don't mind explaining. :)


问:
Removing an item from a list
I would like to remove to ignore duplicates in my list. For example, let's say the function checks for words that end with a ''.'' and puts them in a list. I would like to make sure that duplicate words don't go in the list.

Here is what I have so far:

```<code>def endwords(sent):
    list = []
    words = sent.split()
    for word in words:
        if "." in word:
            list.append(word)
        # bottom if statment does not work for some reason. thats the one i am trying to fix
        if (word == list):
            list.remove(word)
    return list
</code>```

答:
After statement

```<code>list = []
</code>```

you can't use built-in list class and to understand that you can spend about an hour or so, that's why we avoid names of built-ins for our objects.

More at this answer.

function checks for words that end with a ''.''

Statement

```<code>"." in word
</code>```

checks if word contains dot symbol (e.g. "." in "sample.text" will work ok while it simply doesn't end with dot), if you need to check that it ends with dot – use str.endswith method.

I would like to make sure that duplicate words don't go in the list.

just make sure before storing one that it hasn't been stored already.

Finally we can write

```<code>def endwords(sent, end='.'):
    unique_words = []
    words = sent.split()
    for word in words:
        if word.endswith(end) and word not in unique_words:
            unique_words.append(word)
    return unique_words
</code>```

Test

```<code>>>>sent = ' '.join(['some.', 'oth.er'] * 10)
>>>unique_words = endwords(sent)
>>>unique_words
['some.']
</code>```

P. S.

If order doesn't matter – use set, it will take care of duplicates (works only with hashable types, str is hashable):

```<code>def endwords(sent, end='.'):
    unique_words = set()
    words = sent.split()
    for word in words:
        if word.endswith(end) and word not in unique_words:
            unique_words.add(word)
    return unique_words
</code>```

or with set comprehension

```<code>def endwords(sent, end='.'):
    words = sent.split()
    return {word for word in words if word.endswith(end)}
</code>```

Title: Removing an item from a list

Body:
I would like to remove to ignore duplicates in my list. For example, let's say the function checks for words that end with a ''.'' and puts them in a list. I would like to make sure that duplicate words don't go in the list.

Here is what I have so far:

def endwords(sent):
    list = []
    words = sent.split()
    for word in words:
        if "." in word:
            list.append(word)
        # bottom if statment does not work for some reason. thats the one i am trying to fix
        if (word == list):
            list.remove(word)
    return list

Body:
After statement

list = []

you can't use built-in list class and to understand that you can spend about an hour or so, that's why we avoid names of built-ins for our objects.

More at this answer.

function checks for words that end with a ''.''

Statement

"." in word

checks if word contains dot symbol (e.g. "." in "sample.text" will work ok while it simply doesn't end with dot), if you need to check that it ends with dot – use str.endswith method.

I would like to make sure that duplicate words don't go in the list.

just make sure before storing one that it hasn't been stored already.

Finally we can write

def endwords(sent, end='.'):
    unique_words = []
    words = sent.split()
    for word in words:
        if word.endswith(end) and word not in unique_words:
            unique_words.append(word)
    return unique_words

Test

>>>sent = ' '.join(['some.', 'oth.er'] * 10)
>>>unique_words = endwords(sent)
>>>unique_words
['some.']

P. S.

If order doesn't matter – use set, it will take care of duplicates (works only with hashable types, str is hashable):

def endwords(sent, end='.'):
    unique_words = set()
    words = sent.split()
    for word in words:
        if word.endswith(end) and word not in unique_words:
            unique_words.add(word)
    return unique_words

or with set comprehension

def endwords(sent, end='.'):
    words = sent.split()
    return {word for word in words if word.endswith(end)}


问:
How can I get a full-sized UINavigationBar titleView
I am trying to add a custom control as the titleView in a UINavigationBar. When I do so, despite setting the frame and the properties that would normally assume full width, I get this:

The bright blue can be ignored as it is where I am hiding my custom control.  The issue is the narrow strips of navbar at the ends of the bar.  How can I get rid of these so my customview will stretch 100%?

```<code>CGRect frame = CGRectMake(self.view.bounds.origin.x, self.view.bounds.origin.y, self.view.width, kDefaultBarHeight);
UANavBarControlView *control = [[[UANavBarControlView alloc] initWithFrame:frame] autorelease];
control.autoresizingMask = UIViewAutoresizingFlexibleWidth;
self.navigationItem.titleView = control;
</code>```

PS - I know I can add the view by itself instead of being attached to a navigation bar and it would be very easy to position it myself. I have my reasons for needing it to be "on" the navigation bar, and those reasons are here

答:
Swift version of ksm's answer</p>

```<code>let leftOffset: CGFloat = 60
let rightOffset: CGFloat = 60

@objc override var frame: CGRect {
     didSet {
                let width: CGFloat = UIScreen.main.bounds.width - leftOffset - rightOffset
                let height: CGFloat = 44

                super.frame = CGRect(
                    x: leftOffset,
                    y: 20,
                    width: width,
                    height: height
                )
       }
}
</code>```

Body:
I am trying to add a custom control as the titleView in a UINavigationBar. When I do so, despite setting the frame and the properties that would normally assume full width, I get this:

The bright blue can be ignored as it is where I am hiding my custom control.  The issue is the narrow strips of navbar at the ends of the bar.  How can I get rid of these so my customview will stretch 100%?

CGRect frame = CGRectMake(self.view.bounds.origin.x, self.view.bounds.origin.y, self.view.width, kDefaultBarHeight);
UANavBarControlView *control = [[[UANavBarControlView alloc] initWithFrame:frame] autorelease];
control.autoresizingMask = UIViewAutoresizingFlexibleWidth;
self.navigationItem.titleView = control;

PS - I know I can add the view by itself instead of being attached to a navigation bar and it would be very easy to position it myself. I have my reasons for needing it to be "on" the navigation bar, and those reasons are here

Body:
Swift version of ksm's answer

let leftOffset: CGFloat = 60
let rightOffset: CGFloat = 60

@objc override var frame: CGRect {
     didSet {
                let width: CGFloat = UIScreen.main.bounds.width - leftOffset - rightOffset
                let height: CGFloat = 44

                super.frame = CGRect(
                    x: leftOffset,
                    y: 20,
                    width: width,
                    height: height
                )
       }
}


问:
Can I get a specific variable value from Gson converter without creating a bunch of models?
If I have a response like that

```<code>{
    "data": {
        "main_category": {"user":{"name":"Ali","age":5}}
    }
}
</code>```

the expected way to get my userModel >>

```<code>class User{
    String name;
    int age;
}

class MainCategory{
    User user;
}

class Data{
    MainCategory data;
}
</code>```

Is there any way to get my user model directly? Like that

```<code>class Data{
    @SerializedName("data/main_category/user")
    User user;
}
</code>```

答:
Create your custom deserializer:

```<code>class MyDeserializer implements JsonDeserializer<Content>
{
    @Override
    public Content deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
        throws JsonParseException
    {

        JsonElement data = je.getAsJsonObject().get("data");
        JsonElement mainCategory = je.getAsJsonObject().get("main_category");
        JsonElement user = je.getAsJsonObject().get("user");

        return new Gson().fromJson(user, User.class);
    }
}
</code>```

Then create a gson builder like this:

```<code>Gson gson =
    new GsonBuilder()
        .registerTypeAdapter(User.class, new MyDeserializer())
        .create();
</code>```

And finally, in your retrofit instance assign the gson builder:

```<code>retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
</code>```

Body:
If I have a response like that

{
    "data": {
        "main_category": {"user":{"name":"Ali","age":5}}
    }
}

the expected way to get my userModel >>

class User{
    String name;
    int age;
}

class MainCategory{
    User user;
}

class Data{
    MainCategory data;
}

Is there any way to get my user model directly? Like that

class Data{
    @SerializedName("data/main_category/user")
    User user;
}

Body:
Create your custom deserializer:

class MyDeserializer implements JsonDeserializer<Content>
{
    @Override
    public Content deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
        throws JsonParseException
    {

        JsonElement data = je.getAsJsonObject().get("data");
        JsonElement mainCategory = je.getAsJsonObject().get("main_category");
        JsonElement user = je.getAsJsonObject().get("user");

        return new Gson().fromJson(user, User.class);
    }
}

Then create a gson builder like this:

Gson gson =
    new GsonBuilder()
        .registerTypeAdapter(User.class, new MyDeserializer())
        .create();

And finally, in your retrofit instance assign the gson builder:

retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();


问:
Parse 2D-Array in Julia
In Julia I can create 2D-arrays with

```<code>[1 2 3 4 ; 5 6 7 8]
2×4 Array{Int64,2}:
1  2  3  4
5  6  7  8
</code>```

The problem is, that I need to parse a 2D-array supplied as an argument to a script - that is as a String.

For example

```<code>$ julia script.jl "[1 2 3 4 ; 5 6 7 8]"
</code>```

and in the script something like:

```<code>c = parse.(ARGS[1])
</code>```

and c should be a 2×4 array.

I am flexible regarding the format of the input String.

The usecase is, that I want to call an optimization problem implemented in Julia + JuMP from within Java.

答:
Check out the readdlm function, which will allow you to parse the text received from ARGS as an array:

```<code>using DelimitedFiles
a = readdlm(IOBuffer(ARGS[1]),',',';')
display(a)
</code>```

Running:

```<code>$ julia argscript.jl "1,2,3,4;5,6,7,8"
2×4 Array{Float64,2}:
 1.0  2.0  3.0  4.0
 5.0  6.0  7.0  8.0
</code>```

You can force the array element type in the script:

```<code>a = readdlm(IOBuffer(ARGS[1]),',',Int,';')
</code>```

You could even enforce the matrix dimensions by passing two more arguments:

```<code>using DelimitedFiles
n = parse(Int,ARGS[1])
m = parse(Int,ARGS[2])
a = readdlm(IOBuffer(ARGS[3]),',',Int,';',dims=(n,m))
</code>```

Running:

```<code>$ julia argscript.jl 2 3 "3,2,1;2,6,8"
2×3 Array{Int64,2}:
 3  2  1
 2  6  8

$ julia argscript.jl 2 4 "3,2,1;2,6,8"
ERROR: LoadError: at row 2, column 1 : ErrorException("missing value at row 1 column 4"))
</code>```

Title: Parse 2D-Array in Julia

Body:
In Julia I can create 2D-arrays with

[1 2 3 4 ; 5 6 7 8]
2×4 Array{Int64,2}:
1  2  3  4
5  6  7  8

The problem is, that I need to parse a 2D-array supplied as an argument to a script - that is as a String.

For example

$ julia script.jl "[1 2 3 4 ; 5 6 7 8]"

and in the script something like:

c = parse.(ARGS[1])

and c should be a 2×4 array.

I am flexible regarding the format of the input String.

The usecase is, that I want to call an optimization problem implemented in Julia + JuMP from within Java.

Body:
Check out the readdlm function, which will allow you to parse the text received from ARGS as an array:

using DelimitedFiles
a = readdlm(IOBuffer(ARGS[1]),',',';')
display(a)

Running:

$ julia argscript.jl "1,2,3,4;5,6,7,8"
2×4 Array{Float64,2}:
 1.0  2.0  3.0  4.0
 5.0  6.0  7.0  8.0

You can force the array element type in the script:

a = readdlm(IOBuffer(ARGS[1]),',',Int,';')

You could even enforce the matrix dimensions by passing two more arguments:

using DelimitedFiles
n = parse(Int,ARGS[1])
m = parse(Int,ARGS[2])
a = readdlm(IOBuffer(ARGS[3]),',',Int,';',dims=(n,m))

Running:

$ julia argscript.jl 2 3 "3,2,1;2,6,8"
2×3 Array{Int64,2}:
 3  2  1
 2  6  8

$ julia argscript.jl 2 4 "3,2,1;2,6,8"
ERROR: LoadError: at row 2, column 1 : ErrorException("missing value at row 1 column 4"))


问:
Returning words from a string array with symbols between them in java?
```<code>public String onGoogleCommand(String[] args) {
    if(args.length == 0){
        return "Type in a question after the google command!";
    }
    if(args.length >= 1){
        return "https://www.google.com/#q=" + args[0] + "+" + args[1] + "+" + args[2];
    }
    return "What?";
}
</code>```

What I am asking about is the part where I say return "https://www.google.com/#q=" + args[0] + "+" + args[1] + "+" + args[2];. Obviously, this probably isn't the best way to code a search function, but how can I automate this so that the words from the String[] args automatically get put into my return statement with "+" between each of the words so that it would return something like https://www.google.com/#q=please+help+me+with+this+question?

答:
You just need to use a foreach loop, something like this can help:

```<code>if(args.length >= 1){
    String finalStr="";
    for(String currentStr:args){
        finalStr+=currentStr+"+";
    }
    finalStr= finalStr.substring(0, finalStr.length()-1);
}
</code>```

Using this code you will have your search in finalStr, just append it's value to your URL, as you can see the symbol "+" is added after each element and I always remove the last element ("+") because it's unnecessary at the end of the String.

Body:
public String onGoogleCommand(String[] args) {
    if(args.length == 0){
        return "Type in a question after the google command!";
    }
    if(args.length >= 1){
        return "https://www.google.com/#q=" + args[0] + "+" + args[1] + "+" + args[2];
    }
    return "What?";
}

What I am asking about is the part where I say return "https://www.google.com/#q=" + args[0] + "+" + args[1] + "+" + args[2];. Obviously, this probably isn't the best way to code a search function, but how can I automate this so that the words from the String[] args automatically get put into my return statement with "+" between each of the words so that it would return something like https://www.google.com/#q=please+help+me+with+this+question?

Body:
You just need to use a foreach loop, something like this can help:

if(args.length >= 1){
    String finalStr="";
    for(String currentStr:args){
        finalStr+=currentStr+"+";
    }
    finalStr= finalStr.substring(0, finalStr.length()-1);
}

Using this code you will have your search in finalStr, just append it's value to your URL, as you can see the symbol "+" is added after each element and I always remove the last element ("+") because it's unnecessary at the end of the String.


问:
AS3: Can we skip an optional parameter and assign value to the parameter after the skipped one?
Can we skip an optional parameter and assign value to the parameter after the skipped one?

For example I have a function:

```<code>public function Dialog(message:String,title:String="Note",dialogsize:int=99):void
{
}
</code>```

I can easily call the function with a message and a title:

```<code> Dialog("HELLO","Intro");
</code>```

Is there a way to skip the title and just pass in the dialogsize? I've tried it but can't make it work:

```<code>Dialog("HELLO",,dialogsize);
</code>```

Is it possible to skip some optional parameters without using (rest) parameter?

答:
it's impossible, but you can do something like:

```<code>public function Dialog(message:String, optionalArgs: Object):void{
    var title: String = optionalArgs['title'] ? optionalArgs['title'] : 'default value';
    var dialogsize: int =  optionalArgs['dialogsize'] ? optionalArgs['dialogsize'] : 99;
    var smthElse: String =  optionalArgs['smthElse'] ? optionalArgs['smthElse'] : 'another default val';
}
</code>```

and:

Dialog('msg', {dialogsize: 250, smthElse: 'another value'});

Body:
Can we skip an optional parameter and assign value to the parameter after the skipped one?

For example I have a function:

public function Dialog(message:String,title:String="Note",dialogsize:int=99):void
{
}

I can easily call the function with a message and a title:

 Dialog("HELLO","Intro");

Is there a way to skip the title and just pass in the dialogsize? I've tried it but can't make it work:

Dialog("HELLO",,dialogsize);

Is it possible to skip some optional parameters without using (rest) parameter?

Body:
it's impossible, but you can do something like:

public function Dialog(message:String, optionalArgs: Object):void{
    var title: String = optionalArgs['title'] ? optionalArgs['title'] : 'default value';
    var dialogsize: int =  optionalArgs['dialogsize'] ? optionalArgs['dialogsize'] : 99;
    var smthElse: String =  optionalArgs['smthElse'] ? optionalArgs['smthElse'] : 'another default val';
}

and:

Dialog('msg', {dialogsize: 250, smthElse: 'another value'});