问:
What can I do to improve sklearn's Jaccard similarity score performance on 9000+ data

I am trying create a table of Jaccard similarity score on a list of vectors x with every other elements in the list that has over 9000 rows (so resulting to a roughly 9000, 9000 list):

```<code>[[  2   2  67   2   5   3  62  68  27]
[  2   9  67   2   1   3  20  62 139]
[  2  17  67   2   0   6   6  62  73]
[  2  17  67   2   0   6  39  68  92]
[  0   0  67   0   0   3  62  62  13]
...
</code>```

I'm a beginner so I tried to my implement shameful excuse of a code like this:

```<code>similarities_matrix = np.empty([len(x), len(x)])
for icounter, i in enumerate(x.as_matrix()):
    similarities_row = np.empty(len(x))
    for jcounter, j in enumerate(x.as_matrix()):
        similarities_row[jcounter] = jaccard_similarity_score(i, j)
    similarities_matrix[icounter] = similarities_row
pprint(similarities_matrix)
</code>```

But it runs impossibly slow.

Ideally I wanted my code to run within the span of my lifetime (preferably under 5 minutes.)

Currently, this code runs roughly a second per element to compute the similarity matrix.

答:
If you don't mind using scipy, you can use the function pdist from scipy.spatial.distance.  The value computed by sklearn.metrics.jaccard_similarity_score(u, v) is equivalent to 1 -scipy.spatial.distance.hamming(u, v). For example,

```<code>In [71]: from sklearn.metrics import jaccard_similarity_score

In [72]: from scipy.spatial.distance import hamming

In [73]: u = [2, 1, 3, 5]

In [74]: v = [2, 1, 4, 5]

In [75]: jaccard_similarity_score(u, v)
Out[75]: 0.75

In [76]: 1 - hamming(u, v)
Out[76]: 0.75
</code>```

'hamming' is one of the metrics provided by scipy.spatial.distance.pdist, so you can use that function to compute all the pairwise distances.  Here's a small x to use as an example:

```<code>In [77]: x = np.random.randint(0, 5, size=(8, 10))

In [78]: x
Out[78]:
array([[4, 2, 2, 3, 1, 2, 0, 0, 4, 0],
       [3, 1, 4, 2, 3, 1, 2, 3, 4, 4],
       [1, 1, 0, 1, 0, 2, 0, 3, 3, 4],
       [2, 3, 3, 3, 1, 2, 3, 2, 1, 2],
       [3, 2, 3, 2, 0, 0, 4, 4, 3, 4],
       [3, 0, 1, 0, 4, 2, 0, 2, 1, 0],
       [4, 3, 2, 4, 1, 2, 3, 3, 2, 4],
       [3, 0, 4, 1, 3, 3, 3, 3, 1, 3]])
</code>```

I'll use squareform to convert the output of pdist to the symmetric array of similarities.

```<code>In [79]: from scipy.spatial.distance import pdist, squareform

In [80]: squareform(1 - pdist(x, metric='hamming'))
Out[80]:
array([[ 1. ,  0.1,  0.2,  0.3,  0.1,  0.3,  0.4,  0. ],
       [ 0.1,  1. ,  0.3,  0. ,  0.3,  0.1,  0.2,  0.4],
       [ 0.2,  0.3,  1. ,  0.1,  0.3,  0.2,  0.3,  0.2],
       [ 0.3,  0. ,  0.1,  1. ,  0.1,  0.3,  0.4,  0.2],
       [ 0.1,  0.3,  0.3,  0.1,  1. ,  0.1,  0.1,  0.1],
       [ 0.3,  0.1,  0.2,  0.3,  0.1,  1. ,  0.1,  0.3],
       [ 0.4,  0.2,  0.3,  0.4,  0.1,  0.1,  1. ,  0.2],
       [ 0. ,  0.4,  0.2,  0.2,  0.1,  0.3,  0.2,  1. ]])
</code>```

I converted your code to this function:

```<code>def jaccard_sim_matrix(x):
    similarities_matrix = np.empty([len(x), len(x)])
    for icounter, i in enumerate(x):
        similarities_row = np.empty(len(x))
        for jcounter, j in enumerate(x):
            similarities_row[jcounter] = jaccard_similarity_score(i, j)
        similarities_matrix[icounter] = similarities_row
    return similarities_matrix
</code>```

so we can verify that the pdist result is the same as your calculation.

```<code>In [81]: jaccard_sim_matrix(x)
Out[81]:
array([[ 1. ,  0.1,  0.2,  0.3,  0.1,  0.3,  0.4,  0. ],
       [ 0.1,  1. ,  0.3,  0. ,  0.3,  0.1,  0.2,  0.4],
       [ 0.2,  0.3,  1. ,  0.1,  0.3,  0.2,  0.3,  0.2],
       [ 0.3,  0. ,  0.1,  1. ,  0.1,  0.3,  0.4,  0.2],
       [ 0.1,  0.3,  0.3,  0.1,  1. ,  0.1,  0.1,  0.1],
       [ 0.3,  0.1,  0.2,  0.3,  0.1,  1. ,  0.1,  0.3],
       [ 0.4,  0.2,  0.3,  0.4,  0.1,  0.1,  1. ,  0.2],
       [ 0. ,  0.4,  0.2,  0.2,  0.1,  0.3,  0.2,  1. ]])
</code>```

Here I'll compare the timing for a larger array:

```<code>In [82]: x = np.random.randint(0, 5, size=(500, 10))

In [83]: %timeit jaccard_sim_matrix(x)
14.9 s ± 192 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [84]: %timeit squareform(1 - pdist(x, metric='hamming'))
1.19 ms ± 2.23 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
</code>```

Finally, let's time the calculation for an input with shape (9000, 10):

```<code>In [94]: x = np.random.randint(0, 5, size=(9000, 10))

In [95]: %timeit squareform(1 - pdist(x, metric='hamming'))
1.34 s ± 9.13 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code>```

That's just 1.34 seconds--definitely within the span of a lifetime.

Body:
I am trying create a table of Jaccard similarity score on a list of vectors x with every other elements in the list that has over 9000 rows (so resulting to a roughly 9000, 9000 list):

[[  2   2  67   2   5   3  62  68  27]
[  2   9  67   2   1   3  20  62 139]
[  2  17  67   2   0   6   6  62  73]
[  2  17  67   2   0   6  39  68  92]
[  0   0  67   0   0   3  62  62  13]
...

I'm a beginner so I tried to my implement shameful excuse of a code like this:

similarities_matrix = np.empty([len(x), len(x)])
for icounter, i in enumerate(x.as_matrix()):
    similarities_row = np.empty(len(x))
    for jcounter, j in enumerate(x.as_matrix()):
        similarities_row[jcounter] = jaccard_similarity_score(i, j)
    similarities_matrix[icounter] = similarities_row
pprint(similarities_matrix)

But it runs impossibly slow.

Ideally I wanted my code to run within the span of my lifetime (preferably under 5 minutes.)

Currently, this code runs roughly a second per element to compute the similarity matrix.

Body:
If you don't mind using scipy, you can use the function pdist from scipy.spatial.distance.  The value computed by sklearn.metrics.jaccard_similarity_score(u, v) is equivalent to 1 -scipy.spatial.distance.hamming(u, v). For example,

In [71]: from sklearn.metrics import jaccard_similarity_score

In [72]: from scipy.spatial.distance import hamming

In [73]: u = [2, 1, 3, 5]

In [74]: v = [2, 1, 4, 5]

In [75]: jaccard_similarity_score(u, v)
Out[75]: 0.75

In [76]: 1 - hamming(u, v)
Out[76]: 0.75

'hamming' is one of the metrics provided by scipy.spatial.distance.pdist, so you can use that function to compute all the pairwise distances.  Here's a small x to use as an example:

In [77]: x = np.random.randint(0, 5, size=(8, 10))

In [78]: x
Out[78]:
array([[4, 2, 2, 3, 1, 2, 0, 0, 4, 0],
       [3, 1, 4, 2, 3, 1, 2, 3, 4, 4],
       [1, 1, 0, 1, 0, 2, 0, 3, 3, 4],
       [2, 3, 3, 3, 1, 2, 3, 2, 1, 2],
       [3, 2, 3, 2, 0, 0, 4, 4, 3, 4],
       [3, 0, 1, 0, 4, 2, 0, 2, 1, 0],
       [4, 3, 2, 4, 1, 2, 3, 3, 2, 4],
       [3, 0, 4, 1, 3, 3, 3, 3, 1, 3]])

I'll use squareform to convert the output of pdist to the symmetric array of similarities.

In [79]: from scipy.spatial.distance import pdist, squareform

In [80]: squareform(1 - pdist(x, metric='hamming'))
Out[80]:
array([[ 1. ,  0.1,  0.2,  0.3,  0.1,  0.3,  0.4,  0. ],
       [ 0.1,  1. ,  0.3,  0. ,  0.3,  0.1,  0.2,  0.4],
       [ 0.2,  0.3,  1. ,  0.1,  0.3,  0.2,  0.3,  0.2],
       [ 0.3,  0. ,  0.1,  1. ,  0.1,  0.3,  0.4,  0.2],
       [ 0.1,  0.3,  0.3,  0.1,  1. ,  0.1,  0.1,  0.1],
       [ 0.3,  0.1,  0.2,  0.3,  0.1,  1. ,  0.1,  0.3],
       [ 0.4,  0.2,  0.3,  0.4,  0.1,  0.1,  1. ,  0.2],
       [ 0. ,  0.4,  0.2,  0.2,  0.1,  0.3,  0.2,  1. ]])

I converted your code to this function:

def jaccard_sim_matrix(x):
    similarities_matrix = np.empty([len(x), len(x)])
    for icounter, i in enumerate(x):
        similarities_row = np.empty(len(x))
        for jcounter, j in enumerate(x):
            similarities_row[jcounter] = jaccard_similarity_score(i, j)
        similarities_matrix[icounter] = similarities_row
    return similarities_matrix

so we can verify that the pdist result is the same as your calculation.

In [81]: jaccard_sim_matrix(x)
Out[81]:
array([[ 1. ,  0.1,  0.2,  0.3,  0.1,  0.3,  0.4,  0. ],
       [ 0.1,  1. ,  0.3,  0. ,  0.3,  0.1,  0.2,  0.4],
       [ 0.2,  0.3,  1. ,  0.1,  0.3,  0.2,  0.3,  0.2],
       [ 0.3,  0. ,  0.1,  1. ,  0.1,  0.3,  0.4,  0.2],
       [ 0.1,  0.3,  0.3,  0.1,  1. ,  0.1,  0.1,  0.1],
       [ 0.3,  0.1,  0.2,  0.3,  0.1,  1. ,  0.1,  0.3],
       [ 0.4,  0.2,  0.3,  0.4,  0.1,  0.1,  1. ,  0.2],
       [ 0. ,  0.4,  0.2,  0.2,  0.1,  0.3,  0.2,  1. ]])

Here I'll compare the timing for a larger array:

In [82]: x = np.random.randint(0, 5, size=(500, 10))

In [83]: %timeit jaccard_sim_matrix(x)
14.9 s ± 192 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [84]: %timeit squareform(1 - pdist(x, metric='hamming'))
1.19 ms ± 2.23 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Finally, let's time the calculation for an input with shape (9000, 10):

In [94]: x = np.random.randint(0, 5, size=(9000, 10))

In [95]: %timeit squareform(1 - pdist(x, metric='hamming'))
1.34 s ± 9.13 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

That's just 1.34 seconds--definitely within the span of a lifetime.


来源: stackexchange

问:
Rearrange and delete fields with sed
I need help creating a sed command that will rearrange the fields in the file down below so that they are separated by a colon and their order is rearranged to this, state:lastName:restOfName:city (the street address gets dropped).

Mickey Mouse, 1111 Disney Dr., Orlando FL
Minnie Mouse, 1112 Disney Dr., Anaheim CA
Adam Voter, 902 Biscayne Blvd., Miami FL
```

<p>They are supposed to look like this when they are done.</p>

<pre class="lang-none prettyprint-override"><code>FL:Mouse:Mickey:Orlando
CA:Mouse:Minnie:Anaheim
FL:Voter:Adam:Miami
</code>```

This is homework and I can only use sed.

答:
You can use the following sed command, let me know if you need additional explanations about it:

```<code>sed -E -i.bak 's/^([^\s]*)\s+([^,]*),[^,]*,\s*([^\s]*)\s+([^\s]*)\s*$/\4:\2:\1:\3/g' test_add_file.in;
</code>```

TESTED on:

In a nutshell, you are define a regex that sed will use to look in your text file to fetch the required patterns, then you use backreferences to reuse the actual pattern that have been identified during the process.

For the exact syntax about the regex look at this link:

http://www.rexegg.com/regex-quickstart.html

Shortly:

^ beginning of line to fix the start of your pattern

([^\s]*) is used to get your Mickey, Minnie,... (repetition of 0 to N non blank char that will are between parenthesis since this will be reused as back ref

\s+ 1 or more spaces between Mickey and Mouse

([^,]*) will match the Mouse part of the string (repetition of 0 to N non comma char)

,[^,]*,\s* part between the 2 commas that is not used , 1112 Disney Dr.,

([^\s]*) used to fetch Orlando, Anaheim

\s+    1 or more spaces betweenOrlando and FL

([^\s]*) used to fetch FL, CA, ...

\s*$ fix the pattern end with $ at EOL with eventually trailing spaces

then in the replacement part of your sed command you reorder the patterns and you put column between them by \4:\2:\1:\3

ContentLicense: CC BY-SA 3.0

Title: Rearrange and delete fields with sed

Body:
I need help creating a sed command that will rearrange the fields in the file down below so that they are separated by a colon and their order is rearranged to this, state:lastName:restOfName:city (the street address gets dropped).

Mickey Mouse, 1111 Disney Dr., Orlando FL
Minnie Mouse, 1112 Disney Dr., Anaheim CA
Adam Voter, 902 Biscayne Blvd., Miami FL

They are supposed to look like this when they are done.

FL:Mouse:Mickey:Orlando
CA:Mouse:Minnie:Anaheim
FL:Voter:Adam:Miami

This is homework and I can only use sed.

Body:
You can use the following sed command, let me know if you need additional explanations about it:

sed -E -i.bak 's/^([^\s]*)\s+([^,]*),[^,]*,\s*([^\s]*)\s+([^\s]*)\s*$/\4:\2:\1:\3/g' test_add_file.in;

TESTED on:

In a nutshell, you are define a regex that sed will use to look in your text file to fetch the required patterns, then you use backreferences to reuse the actual pattern that have been identified during the process.

For the exact syntax about the regex look at this link:

http://www.rexegg.com/regex-quickstart.html

Shortly:

^ beginning of line to fix the start of your pattern

([^\s]*) is used to get your Mickey, Minnie,... (repetition of 0 to N non blank char that will are between parenthesis since this will be reused as back ref

\s+ 1 or more spaces between Mickey and Mouse

([^,]*) will match the Mouse part of the string (repetition of 0 to N non comma char)

,[^,]*,\s* part between the 2 commas that is not used , 1112 Disney Dr.,

([^\s]*) used to fetch Orlando, Anaheim

\s+    1 or more spaces betweenOrlando and FL

([^\s]*) used to fetch FL, CA, ...

\s*$ fix the pattern end with $ at EOL with eventually trailing spaces

then in the replacement part of your sed command you reorder the patterns and you put column between them by \4:\2:\1:\3


问:
Are Microsoft Azure Cognitive services available on AzureStack?
I'm planning to showcase exciting end user use-cases in AzureStack to potential customers.

This is an idea exploration.
https://azure.microsoft.com/en-us/services/cognitive-services/directory/

I expect Microsoft Azure Cognitive services to be available on AzureStack for Enterprise use-cases.

From my initial search on AzureStack Marketplace items from Azure I could not find Cognitive Services for AzureStack. What is the roadmap to bring these services to AzureStack in the future?

https://learn.microsoft.com/en-us/azure/azure-stack/azure-stack-marketplace-azure-items

Please help. Thanks.

答: All APIs on cognitive services here: https://azure.microsoft.com/en-us/services/cognitive-services/directory/ are on Azure. In fact, you buy access keys for these APIs from Azure portal: https://portal.azure.com/#create/Microsoft.CognitiveServicesBingSearch-v7.


问:
Google Sheets OnOpen() not updating the sheet on team drive
So I have written a script that automatically puts a date stamp in a specific cell. It works fine in my test environment (when opened normally and thru the debugger) and also works fine on the team drive when I run it thru the debugger. But it does not update the cell when run normally on the team drive. Any ideas?

function onOpen() {
  var AcksSheet           = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Acks");
  var RecruiterList       = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Lists");
  var RecruitersRange     = RecruiterList.getDataRange();
  var nLenRecruitersTable = RecruitersRange.getNumRows();
  var values              = RecruitersRange.getValues();
  var email               = Session.getActiveUser().getEmail();
  var nRecruiterRow       = 0
  for (var i = 0; i < nLenRecruitersTable; i++)
  {
    // check if active user email matches email in the recruiter table
    if (email == values[i][1])
    {
      // plus one as the range has one row header
      nRecruiterRow = i+1;
      AcksSheet.getRange(nRecruiterRow,2).setValue(new Date());
      AcksSheet.getRange(nRecruiterRow,2).setNumberFormat("MM/dd/yyyy hh:mm:ss");
      break;
    }
  }
}
```

答:
getMail returns an empty string when it's run from an simple onOpen() trigger. Use an on open installable trigger.

From https://developers.google.com/apps-script/reference/base/user#getemail

getEmail()

Gets the user's email address, if available. If security policies do
  not allow access to the user's email address, this method returns a
  blank string. The circumstances in which the email address is
  available vary: for example, the user's email address is not available
  in any context that allows a script to run without that user's
  authorization, like a simple onOpen(e) or onEdit(e) trigger, a custom
  function in Google Sheets, or a web app deployed to "execute as me"
  (that is, authorized by the developer instead of the user). However,
  these restrictions generally do not apply if the developer and the
  user belong to the same G Suite domain.


问:
Where is a value type object stored in swift?
I declared an object of Array, like:

```<code>let data = ["foo", "bar"]
</code>```

Array type in swift is value type, where is it stored? heap or stack?

I guess it is stored in heap, but how to access it?

And does it follow ARC rule, when will it release?

Can you give me the graphic of the object's memory?

答:
In Swift or other language, by default, Value type is stored in Stack and Reference Type is stored in Heap.

If the value is part of a reference type, then, it's stored in Heap.

So we don't need a reference counting and the value will be clean after the end of its scope, or in the other case, when the container is released.

In your example: the data of Array instance will be stored in Stack of the Application while its elements can be stored in Heap, depend on the element is reference type or value typed.

Body:
I declared an object of Array, like:

let data = ["foo", "bar"]

Array type in swift is value type, where is it stored? heap or stack?

I guess it is stored in heap, but how to access it?

And does it follow ARC rule, when will it release?

Can you give me the graphic of the object's memory?


问:
When I open the browser and enter my site it doesn't load the css on the first time, I have to reload the page to it to be loaded, why?
When I open the browser and enter my site it doesn't load the css on the first time, I have to reload the page to it to be loaded, why?

I just use this

```<code><link href="<c:url value='/css/all.css'/>" rel="stylesheet" type="text/css"/>
</code>```

Using firebug I see I got an error http 302

答:
```<code>Try to change:
<link href="<c:url value='/css/all.css'/>" rel="stylesheet" type="text/css"/>
To:
<link href="css/all.css" rel="stylesheet" type="text/css"/>
</code>```

Body:
When I open the browser and enter my site it doesn't load the css on the first time, I have to reload the page to it to be loaded, why?

I just use this

<link href="<c:url value='/css/all.css'/>" rel="stylesheet" type="text/css"/>

Using firebug I see I got an error http 302


问:
POST request with multiple params
I am trying to make an API call in my nodejs file, but am unable to do so. I continue to get an error

Incorrect number of arguments

in my http.post() call.

This is the code I am trying to use to call the data:

```<code>checkHash(username, password) {
                return new Promise(resolve => {
                        //var inData = ("/" + username + "/" + password);
                        console.log("below is username");
                        console.log(username);
                        console.log("below is password");
                        console.log(password);

                        this.http.post('http://url/checkHash/', username, '/' + password)
                        .subscribe(res => {
                                console.log("checkHash");
                                console.log(res);
                                resolve(res);
                        });
                });
        }
</code>```

I have the server endpoint running so when you call a post like so in postman it returns what I need: http://url/getHash/admin/admin the first parameter is supposed to be username, next is password.

答:
The commas that you're using in your post are creating 3 parameters to the post function, but you need to pass the URL as one parameter:

```<code>this.http.post('http://url/checkHash/' + username + '/' + password).subscribe(...)
</code>```

ContentLicense: CC BY-SA 4.0

Title: POST request with multiple params

Body:
I am trying to make an API call in my nodejs file, but am unable to do so. I continue to get an error

Incorrect number of arguments

in my http.post() call.

This is the code I am trying to use to call the data:

checkHash(username, password) {
                return new Promise(resolve => {
                        //var inData = ("/" + username + "/" + password);
                        console.log("below is username");
                        console.log(username);
                        console.log("below is password");
                        console.log(password);

                        this.http.post('http://url/checkHash/', username, '/' + password)
                        .subscribe(res => {
                                console.log("checkHash");
                                console.log(res);
                                resolve(res);
                        });
                });
        }

I have the server endpoint running so when you call a post like so in postman it returns what I need: http://url/getHash/admin/admin the first parameter is supposed to be username, next is password.

Body:
The commas that you're using in your post are creating 3 parameters to the post function, but you need to pass the URL as one parameter:

this.http.post('http://url/checkHash/' + username + '/' + password).subscribe(...)


问:
extract numbers from dates in C
I got an assignment to convert numbers from a date.

we get the dates as a char string like 18.2.2014 for example, and I need to extract the integers 18, 2, 2014.

my way is not perfect...

what is the best way in your opinion?

```<code>void luckChoice(char a[]){

    int month=10*(a[3]-'0')+(a[4]-'0');
    int day=(a[0]-'0')*10+(a[1]-'0');
    int year=(a[9]-'0')+(a[8]-'0')*10+(a[7]-'0')*100+(a[6]-'0')*1000;
</code>```

答:
I don't know if you are fine with it but you can directly do this in scanf() itself.

Just take the input as

```<code>if (scanf("%d.%d.%d", &dd, &mm, &yy) == 3) { …OK… } else { …failed… }
</code>```

This will ignore the '.' from input in specified sequence.

Else you can use sscanf() function as follows:

```<code>void luckChoice(char a[]){
     int dd,mm,yy;
     sscanf(a,"%d.%d.%d",&dd,&mm,&yy);
}
</code>```

Title: extract numbers from dates in C

Body:
I got an assignment to convert numbers from a date.

we get the dates as a char string like 18.2.2014 for example, and I need to extract the integers 18, 2, 2014.

my way is not perfect...

what is the best way in your opinion?

void luckChoice(char a[]){

    int month=10*(a[3]-'0')+(a[4]-'0');
    int day=(a[0]-'0')*10+(a[1]-'0');
    int year=(a[9]-'0')+(a[8]-'0')*10+(a[7]-'0')*100+(a[6]-'0')*1000;

Body:
I don't know if you are fine with it but you can directly do this in scanf() itself.

Just take the input as

if (scanf("%d.%d.%d", &dd, &mm, &yy) == 3) { …OK… } else { …failed… }

This will ignore the '.' from input in specified sequence.

Else you can use sscanf() function as follows:

void luckChoice(char a[]){
     int dd,mm,yy;
     sscanf(a,"%d.%d.%d",&dd,&mm,&yy);
}


问:
Access Store on different screens in react-native
I am using a 'react-native-navigation' module for navigation in my app. I have declared my screens as below

```<code>import Screen1 from '../container/Screen1';
import Screen2 from '../container/Screen2';

const store = myStore();

Navigation.registerComponent('Screen1',() => Screen1,store,Provider);
Navigation.registerComponent('Screen2',() => Screen2,store,Provider);

Navigation.startSingleScreenApp({

screen:{
    screen:'Screen1',
    title:'Screen1',
    navigatorStyle:{
        navBarHidden:true
    }
}
});
</code>```

My challenge is to use store on different screens so that i can dispatch an action. Is there any way i can achieve that?

Note: myStore is declared in another file fulfilling all reducer, thunk configuration.

答:
If I understand your question correctly, even though you pass store and Provider in registering each screen, you still just connect the components you want subscribed to the store and use Redux in the normal way. So:

```<code>export default connect(mapStateToProps, mapDispatchToProps)(Screen1)
</code>```

I'm assuming because you tagged your question with react-redux that you understand the use of that library. If not, check out Usage with React.

Body:
I am using a 'react-native-navigation' module for navigation in my app. I have declared my screens as below

import Screen1 from '../container/Screen1';
import Screen2 from '../container/Screen2';

const store = myStore();

Navigation.registerComponent('Screen1',() => Screen1,store,Provider);
Navigation.registerComponent('Screen2',() => Screen2,store,Provider);

Navigation.startSingleScreenApp({

screen:{
    screen:'Screen1',
    title:'Screen1',
    navigatorStyle:{
        navBarHidden:true
    }
}
});

My challenge is to use store on different screens so that i can dispatch an action. Is there any way i can achieve that?

Note: myStore is declared in another file fulfilling all reducer, thunk configuration.

Body:
If I understand your question correctly, even though you pass store and Provider in registering each screen, you still just connect the components you want subscribed to the store and use Redux in the normal way. So:

export default connect(mapStateToProps, mapDispatchToProps)(Screen1)

I'm assuming because you tagged your question with react-redux that you understand the use of that library. If not, check out Usage with React.


问:
How to limit the number of login failures in the MySQL root account
I use mysql5.7, my client needs to connect to mysql using navicat, use the root account to log in for 5 consecutive failures to lock the account for 15 minutes. However, googling has turned up no good results.</p>

答:
There are no such feature in Mysql. But you can do this using your application.That's: have a bit column named IsLocked bit and a RetryCount INT column. In your, application, check if it's subsequent login attempt and if it's then increase the RetryCount column.

Once, RetryCount column reaches to 5 (as per your need) update the table set IsLocked column to true.

So, any login attempt after that; just check if the IsLocked column is true and if yes then deny the login and throw validation error message to end user  and unlock account after 15 minutes.


问:
Types of Select Statement
This has been bothering me for quite some time but I do come across two ways of using select statement in SQL.

The first way is the obvious :

```<code>Select column_Name
from table_Name
</code>```

And then there is a second one:

```<code> Select column_Name a
 from table_Name
</code>```

What is the difference in using the second one?

答:
The second version is more properly written using as:

```<code>Select column_Name as a
</code>```

This produces a result set with one column. The column is called a. Without the alias, the column would be called column_name.

Although the as is optional, I strongly recommend using it for column aliases.

Title: Types of Select Statement

Body:
This has been bothering me for quite some time but I do come across two ways of using select statement in SQL.

The first way is the obvious :

Select column_Name
from table_Name

And then there is a second one:

 Select column_Name a
 from table_Name

What is the difference in using the second one?

Body:
The second version is more properly written using as:

Select column_Name as a

This produces a result set with one column. The column is called a. Without the alias, the column would be called column_name.

Although the as is optional, I strongly recommend using it for column aliases.


问:
facebook app, continuous redirect?
Does anybody have any idea why my facebook app keeps redirecting in a loop?</p>

```<code>http://apps.facebook.com/freemoviedb/
</code>```

答: I experienced the same problem because my server didn't support cURL requests for external servers - check cURL support.</p>

ContentLicense: CC BY-SA 2.5

Title: facebook app, continuous redirect?

Body:
Does anybody have any idea why my facebook app keeps redirecting in a loop?

http://apps.facebook.com/freemoviedb/


问:
How to get very first word before and after 'text'
I am after the very first word before v and after 'v'.

```<code>df = pd.DataFrame({'text': ["cans choc v macroni ice",
                            "chocolate sundaes v chocolate ice cream",
                            "Chocolate v sauce"]})
</code>```

I have a dataframe that looks like:

```<code>cans choc v macroni ice
chocolate sundaes v chocolate ice cream
Chocolate v sauce
</code>```

I want it to look like:

```<code>cans v macroni
chocolate v chocolate
Chocolate v sauce
</code>```

How can this be achieved in pandas?  The common element is 'v'.

答:
Let's try this:

```<code>df.text.str.split('v', expand=True)\
  .apply(lambda x: x.str.extract('(\w+)', expand=False))\
  .apply(lambda x: ' v '.join(x), 1)
</code>```

Output:

```<code>0           cans v macroni
1    chocolate v chocolate
2        Chocolate v sauce
</code>```

Body:
I am after the very first word before v and after 'v'.

df = pd.DataFrame({'text': ["cans choc v macroni ice",
                            "chocolate sundaes v chocolate ice cream",
                            "Chocolate v sauce"]})

I have a dataframe that looks like:

cans choc v macroni ice
chocolate sundaes v chocolate ice cream
Chocolate v sauce

I want it to look like:

cans v macroni
chocolate v chocolate
Chocolate v sauce

How can this be achieved in pandas?  The common element is 'v'.

Body:
Let's try this:

df.text.str.split('v', expand=True)\
  .apply(lambda x: x.str.extract('(\w+)', expand=False))\
  .apply(lambda x: ' v '.join(x), 1)

Output:

0           cans v macroni
1    chocolate v chocolate
2        Chocolate v sauce


问:
python: how to remove brackets of a nested list within a list
I have a list of different arrays of different sizes

```<code>list = [array1,array2,array3,array4,array5]
</code>```

now i want to use split function to split one of the array

```<code>newlist = [array1, np.vsplit(array2,3), array3,array4,array5]
</code>```

to make a new list

```<code>newlist = [array1,array21,array22,array23,array3,array4,array5]
</code>```

HOWEVER, what I got is always containing a list inside the newlist

```<code>newlist = [array1,[array21,array22,array23],array3,array4,array5]
</code>```

how can i remove the brackets and generate what i want?

I believe there should be a very simple solution, but i have tried searching and couldn't get a answer.

答:
split creates a list of arrays:

```<code>In [115]: np.split(np.arange(10),2)
Out[115]: [array([0, 1, 2, 3, 4]), array([5, 6, 7, 8, 9])]
</code>```

When you make a new list containing arrays plus such a list, you get a list within a list.  That's just normal list operations:

```<code>In [116]: [np.arange(3),np.split(np.arange(10),2),np.array([3,2])]
Out[116]:
[array([0, 1, 2]),
 [array([0, 1, 2, 3, 4]), array([5, 6, 7, 8, 9])],
 array([3, 2])]
</code>```

There are various ways of flattening or expanding such a nested list.  One is the * operator.  It's common in function arguments, e.g. func(*[alist]), but in new Pythons works in a list like this:

```<code>In [117]: [np.arange(3),*np.split(np.arange(10),2),np.array([3,2])]
Out[117]:
[array([0, 1, 2]),
 array([0, 1, 2, 3, 4]),
 array([5, 6, 7, 8, 9]),
 array([3, 2])]
</code>```

Simple list example:

```<code>In [118]: [1, [2,3,4], 5]
Out[118]: [1, [2, 3, 4], 5]
In [119]: [1, *[2,3,4], 5]
Out[119]: [1, 2, 3, 4, 5]
</code>```

(This doesn't work in Python2; There a list join is easier to use, [0] + [1,2,3] + [4], as @Psidom shows)

Body:
I have a list of different arrays of different sizes

list = [array1,array2,array3,array4,array5]

now i want to use split function to split one of the array

newlist = [array1, np.vsplit(array2,3), array3,array4,array5]

to make a new list

newlist = [array1,array21,array22,array23,array3,array4,array5]

HOWEVER, what I got is always containing a list inside the newlist

newlist = [array1,[array21,array22,array23],array3,array4,array5]

how can i remove the brackets and generate what i want?

I believe there should be a very simple solution, but i have tried searching and couldn't get a answer.

Body:
split creates a list of arrays:

In [115]: np.split(np.arange(10),2)
Out[115]: [array([0, 1, 2, 3, 4]), array([5, 6, 7, 8, 9])]

When you make a new list containing arrays plus such a list, you get a list within a list.  That's just normal list operations:

In [116]: [np.arange(3),np.split(np.arange(10),2),np.array([3,2])]
Out[116]:
[array([0, 1, 2]),
 [array([0, 1, 2, 3, 4]), array([5, 6, 7, 8, 9])],
 array([3, 2])]

There are various ways of flattening or expanding such a nested list.  One is the * operator.  It's common in function arguments, e.g. func(*[alist]), but in new Pythons works in a list like this:

In [117]: [np.arange(3),*np.split(np.arange(10),2),np.array([3,2])]
Out[117]:
[array([0, 1, 2]),
 array([0, 1, 2, 3, 4]),
 array([5, 6, 7, 8, 9]),
 array([3, 2])]

Simple list example:

In [118]: [1, [2,3,4], 5]
Out[118]: [1, [2, 3, 4], 5]
In [119]: [1, *[2,3,4], 5]
Out[119]: [1, 2, 3, 4, 5]

(This doesn't work in Python2; There a list join is easier to use, [0] + [1,2,3] + [4], as @Psidom shows)


问:
How to create a .R file from executing a .R file
I thought this would be simple to do, but apparently it isn't as straight forward as I thought.

I want to generate a .R file from the execution of another .R file.

I have tried running the following code:

```<code>temp = "library(data.table)
x = c(1:3)
x = data.table(x)
"
save(temp, file = 'Write_Script_Test.R')
</code>```

It does create the file; however, when I open the file it is just a bunch of encoded gibberish.

The desired result is the new .R file that contains the contents of the "temp" object:

```<code>library(data.table)
x = c(1:3)
x = data.table(x)
</code>```

答:
The problem is that save() is useful for saving R objects in binary format. If you're looking to generate a text file, the solution is the one Kevin Arseneau gave you. You must use writeLines() as follows:

```<code>temp = "library(data.table)
x = c(1:3)
x = data.table(x)
"
writeLines(text=temp, con='Write_Script_Test.R')
</code>```

You can configure an absolute or relative path for the file using the parameter con.

Body:
I thought this would be simple to do, but apparently it isn't as straight forward as I thought.

I want to generate a .R file from the execution of another .R file.

I have tried running the following code:

temp = "library(data.table)
x = c(1:3)
x = data.table(x)
"
save(temp, file = 'Write_Script_Test.R')

It does create the file; however, when I open the file it is just a bunch of encoded gibberish.

The desired result is the new .R file that contains the contents of the "temp" object:

library(data.table)
x = c(1:3)
x = data.table(x)

Body:
The problem is that save() is useful for saving R objects in binary format. If you're looking to generate a text file, the solution is the one Kevin Arseneau gave you. You must use writeLines() as follows:

temp = "library(data.table)
x = c(1:3)
x = data.table(x)
"
writeLines(text=temp, con='Write_Script_Test.R')

You can configure an absolute or relative path for the file using the parameter con.


问:
asp consuming a web service, what do do with recordset object?
Currently I run an classic (old) ASP webpage with recordset object used directly in bad old spagethi code fasion.

I'm thinking of implementing a data layer in asp.net as web serivce to improve manageability. This is also a first step towards upgrading the website to asp.net.
The site itself remains ASP for the moment...

Can anybody recommend a good way of replacing the recordset object type with a web service compatible type (like an array or something)?
What do I replace below with?:

```<code>set objRS = oConn.execute(SQL)
while not objRS.eof
   ...
   name = Cstr(objRS(1))
   ...
wend
</code>```

and also mutliple recordsets can be replaced with?
I'm talking :

```<code> set objRS = objRs.nextRecordset
</code>```

Anybody went through this and can recommend?

@AdditionalInfo - you asked for it :-)

Let me start at the beginning.
Existing Situation is:
I have an old ASP website with classical hierachical content (header, section, subsection, content) pulled out of database via stored procedures and content pages are in database also (a link to html file).

Now bad thing is, ASP code everywhere spread over many .asp files all doing their own database connections, reading, writing (u have to register for content). Recently we had problems with SQL injection attacks so I was called to fix it.

I could go change all the .asp pages to prevent sql injection but that would be madness. So I thought build a data layer - all pages using this layer to access database. Once place to fix and update db access code.

Coming to that decision I thought asp.net upgrade isn'f far away, why not start using asp.net for the data layer? This way it can be re-used when upgrading the site.

That brings me to the questions above!

答:
Too bad I did not see this question in 2008.
For me it looks like your site is using Justa framework.
Simple way is to modify Justa code for submit of search and data inputs to urlencode.
I did it and work perfectly for me.

Rest of the code secure enough to prevent any type os SQL injections or other attempt to get into database.

OwnerDisplayName: Johannes

Body:
Currently I run an classic (old) ASP webpage with recordset object used directly in bad old spagethi code fasion.

I'm thinking of implementing a data layer in asp.net as web serivce to improve manageability. This is also a first step towards upgrading the website to asp.net.
The site itself remains ASP for the moment...

Can anybody recommend a good way of replacing the recordset object type with a web service compatible type (like an array or something)?
What do I replace below with?:

set objRS = oConn.execute(SQL)
while not objRS.eof
   ...
   name = Cstr(objRS(1))
   ...
wend

and also mutliple recordsets can be replaced with?
I'm talking :

 set objRS = objRs.nextRecordset

Anybody went through this and can recommend?

@AdditionalInfo - you asked for it :-)

Let me start at the beginning.
Existing Situation is:
I have an old ASP website with classical hierachical content (header, section, subsection, content) pulled out of database via stored procedures and content pages are in database also (a link to html file).

Now bad thing is, ASP code everywhere spread over many .asp files all doing their own database connections, reading, writing (u have to register for content). Recently we had problems with SQL injection attacks so I was called to fix it.

I could go change all the .asp pages to prevent sql injection but that would be madness. So I thought build a data layer - all pages using this layer to access database. Once place to fix and update db access code.

Coming to that decision I thought asp.net upgrade isn'f far away, why not start using asp.net for the data layer? This way it can be re-used when upgrading the site.

That brings me to the questions above!

LastEditorDisplayName: Johannes


问:
Watson Speech To Text service works faster for which type of audio file?
I have tried the Watson Speech to Text API for MP3 as well as WAV files. As per my observation, the same length of audio takes less time if its given in MP3 format as compared to WAV. 10 consecutive API calls with different audios took on an average 8.7 seconds for MP3 files. On the other hand the same input in WAV format took average 11.1 seconds. Does the service response time depend on the file type? Which file type is recommended to use to obtain the results faster?</p>

答:
Different encoding formats have different bitrates. mp3 and opus are lossy compression formats (although suitable for speech recognition when bitrates are not too low) so they offer the lowest bitrates. If you need to push less bytes over the network that is typically better for latency, so depending on your network speed you can see shorter processing times when using encoding with lower bitrates.

However, regarding the actual speech recognition process (ignoring the data transfer over the network) all encodings are equally fast since before the recognition starts all the audio is uncompressed, if necessary, and converted to the sampling rate of the target model (broadband or narrowband).


问:
How to empty (clear) the logcat buffer in Android
How can I empty (clear) the logcat buffer in Android?

I use adb logcat from command line and pipe the output to a file, since the DDMS has a very limited buffer. At the moment, when I restart my app (after fixing bugs etc) the logcat buffer has data from the previous launch as well. Even uninstalling the app does not clear the buffer. The only way I've found so far to clear the buffer, is reboot. This is effective, but would like to know if there's an easier way.

答:
The following command will clear only non-rooted buffers (main, system ..etc).

```<code>adb logcat -c
</code>```

If you want to clear all the buffers (like radio, kernel..etc), Please use the following commands

```<code>adb root
adb logcat -b all -c
</code>```

or

```<code>adb root
adb shell logcat -b all -c
</code>```

Use the following commands to know the list of buffers that device supports

```<code>adb logcat -g
adb logcat -b all -g
adb shell logcat -b all -g
</code>```

Body:
The following command will clear only non-rooted buffers (main, system ..etc).

adb logcat -c

If you want to clear all the buffers (like radio, kernel..etc), Please use the following commands

adb root
adb logcat -b all -c

or

adb root
adb shell logcat -b all -c

Use the following commands to know the list of buffers that device supports

adb logcat -g
adb logcat -b all -g
adb shell logcat -b all -g


问:
TFS TLS 1.1/1.2
We are currently using TFS 2015.3 on Windows server 2012 R2. After using NARTAC to specify using TLS1.1/1.2 and disable TLS1.0, our build tier server cannot connect to application tier server.

Does any have the same issue and got it fixed? Thank you

Regards,

答:
Seems it's not supported for TLS 1.1 and TLS 1.2.

Ensure that your installation of TFS, the underlying .NET version(s), and Windows Server all support TLS 1.2 endpoints.

.NET Framework version(s) used by TFS must support TLS 1.2. Some .NET Framework versions may require additional registry settings for "SchUseStrongCrypto" as described here.

Whatever, you can have a try with the solution mentioned below:

By default .Net has a setting called “useStrongCrypto” that allows the
  client PC to use TLS 1.1 and higher.

To enable secure your local client PC to use TLS 1.1 and higher (or as
  Microsoft terms is “strong crypto”) you need to edit the following
  registry entries:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319\SchUseStrongCrypto = 00000001 HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319\SchUseStrongCrypto= 00000001

Or you could simply cut and paste the following into a .reg file and run it (only do this if you know what you’re doing).

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
    "SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
    "SchUseStrongCrypto"=dword:00000001

Source here : Getting WebDeploy working after disabling insecure Ciphers like SSL 3.0 and TLS 1.0

Also this article for your reference: Misbehaving HTTPS Servers impair TLS 1.1 and TLS 1.2

Title: TFS TLS 1.1/1.2


Title: Replace a char which in the string with another char

Body:
I want use the date format in list2 to list 1

list1 = ['1628 04 19 21:10:32', '1752 06 15 20:05:36', '1775 04 18 09:15:56', '1865 04 14 14:54:36', '1876 05 10 15:36:27', '1879 10 22 03:45:15', '2010 09 29 04:46:28']

list2 = ['1628  4 19 21:10:32', '1752  6 15 20:05:36', '1775  4 18 09:15:56', '1865  4 14 14:54:36', '1876  5 10 15:36:27', '1879 10 22 03:45:15', '2010  9 29 04:46:28']

Just replace the zero in single number months with space

Body:
Another solution is as follows:

list1 = ['1628 04 19 21:10:32', '1752 06 15 20:05:36', '1775 04 18 09:15:56', '1865 04 14 14:54:36', '1876 05 10 15:36:27', '1879 10 22 03:45:15', '2010 09 29 04:46:28']
list2 = []

for each_item in list1:
    if each_item[5] == '0':
        each_item = each_item[0:5] + ' ' + each_item[6:]
    list2.append(each_item)

print list2

output:

['1628  4 19 21:10:32', '1752  6 15 20:05:36', '1775  4 18 09:15:56', '1865  4 14 14:54:36', '1876  5 10 15:36:27', '1879 10 22 03:45:15', '2010  9 29 04:46:28']


问:
Trying to remove character EM DASH "—" (â€”) in python using regex
I got this stubborn EM DASH character that I'm trying to remove using regex, but for some reason I can't get it to work. This is the code I'm using.

```<code>editedSource = re.sub(r'\u2014','',str(source))
</code>```

What am I doing wrong here? I'm pretty sure I got the right character code. Here's the character:

—

and it shows up like

â€”

.

Thanks!

答:
The following code works in Python 3:</p>

```<code>editedSource = re.sub('\â€”','',str(source))
</code>```

Body:
I got this stubborn EM DASH character that I'm trying to remove using regex, but for some reason I can't get it to work. This is the code I'm using.

editedSource = re.sub(r'\u2014','',str(source))

What am I doing wrong here? I'm pretty sure I got the right character code. Here's the character:

—

and it shows up like

â€”

.

Thanks!

Body:
The following code works in Python 3:

editedSource = re.sub('\â€”','',str(source))


问:
Creating a dylib file on MacOS for use with Python wrapper of Steamworks API
I am a hobbyist programmer trying to integrate the SteamworksForPython API into a Python-based game. This API is a Python wrapper of the Steamworks API, which only officially supports C++. I am working on MacOS Sierra 10.12.6.

Blindly following the documentation, I have done the following:

I have downloaded the SteamworksForPython repo.

I have added the steam header directory from the Steamworks SDK (/sdk/public/steam) to that repo.

I have added to that repo the Steam API file appropriate to my operating system (in my case, libsteam_api.dylib from /sdk/redistributable_bin/osx32).

The next step listed in the documentation is to create a new dylib file. Unfortunately, the steps to do this haven't been described for MacOS yet.

Looking at the process for Linux and Windows, it seems like I need to create this dynamic library file using the repo's SteamworksPy.cpp file and the steam_api.h header file from the Steamworks SDK.

I have researched how to create a dylib file using Xcode and am currently trying to do it. The process seems similar to the one described by the documentation for Windows using Visual Studio.

I have done the following:

I have created a new Xcode project of type plain C++ dynamic library.

I have added SteamworksPy.cpp into the Compile Sources list.

I have added steam_api.h to the Headers list (under public, not private or project).

I have added libsteam_api.dylib to the Link Binary With Libraries section.

I am getting an error when I try to build, however. Here is a screenshot:

And here is a more explicit screenshot of the linker error:

After reading this, this, and this, I think the problem is that Xcode doesn't know where to look for the library I'm trying to link to, so I need to tell it where to look. This should be simple, but I can't manage to do it.

Can anyone give me advice on how to proceed?

Similar questions that were helpful, but didn't lead me to a solution:

How do I create a dynamic library (dylib) with Xcode?

Building and Using a DYLIB in Xcode

ld: library not found

ld: library not found for -lgsl

xcode library not found

答:
I managed to solve this problem.

Xcode couldn't find the location of the library I was trying to link to.

I noticed that under Build Settings I could specify Path to Link Map File. I tried to hardcode the path to where my library (libsteam_api.dylib) resided, but I got the same error described above.

Then I did something that worked.

I deleted the reference to the library in the Link Binary With Libraries section.

Then I moved the library from its original location into my Xcode project directory.

Then I used the file selection pane in the Link Binary With Libraries section to reselect the library from the Xcode directory.

When I built, everything worked fine.


问:
How to access Telerik's RadDataGrid cell content from code behind for UWP?
We have used DataGridTemplateColumn for our grid to display texbox under each column. We've a requirement to make the textboxes readonly if it contains any data (for data loading case). In order to achieve that, we need to access all text box controls under the radgrid. We've tried following approaches so far

Find all child controls using VisualTreeHelper - No textbox control was found

Tried with DataBindingComplete event

Is there any way to access the underlying cell's control from codebehind for RadDataGrid?

Alternative approach : Can we somehow user IsReadOnly property with some binding to check it's value and make the control readonly when value is there?

答:
Can we somehow user IsReadOnly property with some binding to check it's value and make the control readonly when value is there?

Yes. You could certainly achieve this by using Binding. You just need to define a bool property and bind the IsReadOnly property of TextBox to this property. Then, you could change this bool value according to the text of TextBox.

Please refer to my following code sample for reference:

```<code><telerikGrid:RadDataGrid x:Name="grid" AutoGenerateColumns="False" VerticalAlignment="Center">
        <telerikGrid:RadDataGrid.Columns>
            <telerikGrid:DataGridTemplateColumn Header="Country">
                <telerikGrid:DataGridTemplateColumn.CellContentTemplate>
                    <DataTemplate>
                        <TextBox Text="{Binding Country}" HorizontalAlignment="Center" VerticalAlignment="Center" IsReadOnly="{Binding IsReadOnly}"/>
                    </DataTemplate>
                </telerikGrid:DataGridTemplateColumn.CellContentTemplate>
            </telerikGrid:DataGridTemplateColumn>

            <telerikGrid:DataGridTemplateColumn Header="Flag">
                <telerikGrid:DataGridTemplateColumn.CellContentTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <TextBlock Text="{Binding Flag}" />
                        </StackPanel>
                    </DataTemplate>
                </telerikGrid:DataGridTemplateColumn.CellContentTemplate>
            </telerikGrid:DataGridTemplateColumn>
        </telerikGrid:RadDataGrid.Columns>
</telerikGrid:RadDataGrid>
</code>```

public sealed partial class MainPage : Page
{
    ObservableCollection<Data> list = new ObservableCollection<Data>();
    public MainPage()
    {
        this.InitializeComponent();

        list.Add(new Data { Country = "Argentina",Flag="A"});
        list.Add(new Data {Country=string.Empty,Flag="B"});
        list.Add(new Data { Country = "China",Flag="C"});
        this.grid.ItemsSource = list;
        this.Loaded += MainPage_Loaded;
    }

    private async void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        await Task.Delay(5000);
        list[1].Country = "Brazil";
    }
}

public class Data:INotifyPropertyChanged
{
    private string _Country;
    public string Country
    {
        get { return _Country; }
        set
        {
            _Country = value;
            if (string.IsNullOrEmpty(value))
            {
                IsReadOnly = true;
            }
            else
            {
                IsReadOnly = false;
            }
            RaisePropertyChanged("Country");
        }
    }

    private string _Flag;
    public string Flag
    {
        get { return _Flag;}
        set
        {
            _Flag = value;
            RaisePropertyChanged("Flag");
        }
    }

    private bool _IsReadOnly=false;
    public bool IsReadOnly
    {
        get { return _IsReadOnly; }
        set
        {
            _IsReadOnly = value;
            RaisePropertyChanged("IsReadOnly");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChanged(string PropertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this,new PropertyChangedEventArgs(PropertyName));
        }
    }
}
```

Body:
Can we somehow user IsReadOnly property with some binding to check it's value and make the control readonly when value is there?

Yes. You could certainly achieve this by using Binding. You just need to define a bool property and bind the IsReadOnly property of TextBox to this property. Then, you could change this bool value according to the text of TextBox.

Please refer to my following code sample for reference:

<telerikGrid:RadDataGrid x:Name="grid" AutoGenerateColumns="False" VerticalAlignment="Center">
        <telerikGrid:RadDataGrid.Columns>
            <telerikGrid:DataGridTemplateColumn Header="Country">
                <telerikGrid:DataGridTemplateColumn.CellContentTemplate>
                    <DataTemplate>
                        <TextBox Text="{Binding Country}" HorizontalAlignment="Center" VerticalAlignment="Center" IsReadOnly="{Binding IsReadOnly}"/>
                    </DataTemplate>
                </telerikGrid:DataGridTemplateColumn.CellContentTemplate>
            </telerikGrid:DataGridTemplateColumn>

            <telerikGrid:DataGridTemplateColumn Header="Flag">
                <telerikGrid:DataGridTemplateColumn.CellContentTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <TextBlock Text="{Binding Flag}" />
                        </StackPanel>
                    </DataTemplate>
                </telerikGrid:DataGridTemplateColumn.CellContentTemplate>
            </telerikGrid:DataGridTemplateColumn>
        </telerikGrid:RadDataGrid.Columns>
</telerikGrid:RadDataGrid>

public sealed partial class MainPage : Page
{
    ObservableCollection<Data> list = new ObservableCollection<Data>();
    public MainPage()
    {
        this.InitializeComponent();

        list.Add(new Data { Country = "Argentina",Flag="A"});
        list.Add(new Data {Country=string.Empty,Flag="B"});
        list.Add(new Data { Country = "China",Flag="C"});
        this.grid.ItemsSource = list;
        this.Loaded += MainPage_Loaded;
    }

    private async void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        await Task.Delay(5000);
        list[1].Country = "Brazil";
    }
}

public class Data:INotifyPropertyChanged
{
    private string _Country;
    public string Country
    {
        get { return _Country; }
        set
        {
            _Country = value;
            if (string.IsNullOrEmpty(value))
            {
                IsReadOnly = true;
            }
            else
            {
                IsReadOnly = false;
            }
            RaisePropertyChanged("Country");
        }
    }

    private string _Flag;
    public string Flag
    {
        get { return _Flag;}
        set
        {
            _Flag = value;
            RaisePropertyChanged("Flag");
        }
    }

    private bool _IsReadOnly=false;
    public bool IsReadOnly
    {
        get { return _IsReadOnly; }
        set
        {
            _IsReadOnly = value;
            RaisePropertyChanged("IsReadOnly");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChanged(string PropertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this,new PropertyChangedEventArgs(PropertyName));
        }
    }
}


问:
GWT: UiBinder or GWT Designer?
I have my first GWT project that I created using UiBinder (GWT 2.0 way) which I found to be easier than write my UI creation Java source code (GWT 1.0 way).

But I saw this thing called GWT Designer that Google are releasing for free. It has nice features and wizards which were missing with the standard Google Eclipse Plugin. I like it, but I still think that using UiBinder is better. I think GWT Designer will be really useful when it can help you write UiBinder XML files (GWT 2.0 way), and not just source code (GWT 1.0 way).

What do you think about it?
Do I need to migrate to GWT Designer project?
Will it be better if I migrate but still keep UiBinder UI creation?

答:
The latest GWT Designer now has support for UiBinder, and it works great.
http://download.instantiations.com/D2GWTDoc/continuous/latest/docs/html/wizards/gwt/uibinder_composite.html</p>

Title: GWT: UiBinder or GWT Designer?


问:
What does the enteredPassword = passwordEntry.get() command do?
What does the    enteredPassword = passwordEntry.get()    command do in this context:

```<code>import Tkinter as tk
window = tk.Tk()

def checkPassword():
    password = "Oranges"
    enteredPassword = passwordEntry.get()
    if password == enteredPassword:
        confirmLabel.config(text="Correct")
    else:
        confirmLabel.config(text="Incorrect")

passwordLabel = tk.Label(window, text="Password:")
passwordEntry = tk.Entry(window, show="*")

button = tk.Button(window, text="Enter", command=checkPassword)
confirmLabel = tk.Label(window)

passwordLabel.pack()
passwordEntry.pack()
button.pack()
confirmLabel.pack()

window.mainloop()
</code>```

Thank you!

答:
If you look at http://effbot.org/tkinterbook/entry.htm, you'll see that the .get() method returns the current text in a Tkinter Entry widget.

However, that is not usually the best way to interact with an Entry widget. Typically the best way is to assign a Tkinter.StringVar to the widget via the textvariable keyword, and then you can .get() and .set() the StringVar, and the text that you write to the StringVar will appear in the Entry's text area. But more importantly than this, you can set a 'trace' function on the StringVar which executes a callback function anytime you change the value of the StringVar, such as using the StringVar.set() method or by someone typing in some text in the Entry widget.  Powerful stuff!

Body:
What does the    enteredPassword = passwordEntry.get()    command do in this context:

import Tkinter as tk
window = tk.Tk()

def checkPassword():
    password = "Oranges"
    enteredPassword = passwordEntry.get()
    if password == enteredPassword:
        confirmLabel.config(text="Correct")
    else:
        confirmLabel.config(text="Incorrect")

passwordLabel = tk.Label(window, text="Password:")
passwordEntry = tk.Entry(window, show="*")

button = tk.Button(window, text="Enter", command=checkPassword)
confirmLabel = tk.Label(window)

passwordLabel.pack()
passwordEntry.pack()
button.pack()
confirmLabel.pack()

window.mainloop()

Thank you!


问:
can google signin scopes be "cleared"?
I am trying to write an android app to manage GMails.

Is there a way to programatically "clear" a confirmed permission (Scope)?

I have managed to request a Scope using:-

```<code>GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
  .requestScopes(new Scope("https://mail.google.com/"))
  .requestEmail().build();
</code>```

The first time running the app, I got a permissions confirmation screen and Confirmed. So after that I (correctly) don't get the confirmation screen again.  But I would like to test the permissions screen again. Not even uninstalling the app will provoke it.

I would prefer to just "clear" the Scope in my app. Any ideas?

答:
Use revokeAccess:

```<code>private void revokeAccess() {
    mGoogleSignInClient.revokeAccess()
            .addOnCompleteListener(this, new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    // ...
                }
            });
}
</code>```

This will revoke the scope grants recorded server-side and clear the local token cache on the device. See the documentation.

Title: can google signin scopes be "cleared"?

Body:
I am trying to write an android app to manage GMails.

Is there a way to programatically "clear" a confirmed permission (Scope)?

I have managed to request a Scope using:-

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
  .requestScopes(new Scope("https://mail.google.com/"))
  .requestEmail().build();

The first time running the app, I got a permissions confirmation screen and Confirmed. So after that I (correctly) don't get the confirmation screen again.  But I would like to test the permissions screen again. Not even uninstalling the app will provoke it.

I would prefer to just "clear" the Scope in my app. Any ideas?

Body:
Use revokeAccess:

private void revokeAccess() {
    mGoogleSignInClient.revokeAccess()
            .addOnCompleteListener(this, new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    // ...
                }
            });
}

This will revoke the scope grants recorded server-side and clear the local token cache on the device. See the documentation.


问:
How do I see if a symbol package has been published for a given Nuget package?
I want to use a debugger to step through the code of an open-source, public Nuget package that my project references. My understanding is that if the package publishes a symbol package I should be able to do this.

It's not working, and I can see that it's because the .pdb file can not be located:

Presumably this is because either:

a) I haven't correctly set up Visual Studio to load symbols from the right place (the info online about this is all very confusing and contradictory), or...

b) The package in question doesn't publish a symbols package.

How do I check if b is the issue? Is there an easy way to check if a symbol package has been published for a given NuGet package?

答:
How do I check if b is the issue? Is there an easy way to check if a symbol package has been published for a given NuGet package?

You can use the nuget.exe CLI Reference list to list the version of that package on the symbol sources:

https://learn.microsoft.com/en-us/nuget/tools/cli-ref-list

The list command:

```<code>nuget.exe list Microsoft.AspNetCore.Authentication.OpenIdConnect -AllVersion -Prerelease -source https://nuget.smbsrc.net
</code>```

After test, I found the symbol package of that package has not been published:

Note: The  package LSGTestNuGetPackage is a test symbol package, which I published before.

Body:
How do I check if b is the issue? Is there an easy way to check if a symbol package has been published for a given NuGet package?

You can use the nuget.exe CLI Reference list to list the version of that package on the symbol sources:

https://learn.microsoft.com/en-us/nuget/tools/cli-ref-list

The list command:

nuget.exe list Microsoft.AspNetCore.Authentication.OpenIdConnect -AllVersion -Prerelease -source https://nuget.smbsrc.net

After test, I found the symbol package of that package has not been published:

Note: The  package LSGTestNuGetPackage is a test symbol package, which I published before.


问:
Ubuntu 16.04 LTS Running low-graphics mode
This happens when I try to install/update the Nvidia driver on my system using cuda_8.0.61.2_linux.
Prompt dialog</p>

答:
This could be caused by conflicting x11 libs. Some of you might also experience similar issue on a different or older version of Ubuntu.

Prompt dialog

Perform Ctrl+Alt+F1 then a console will be displayed.

Enter your credentials...

(1) You need to reset the "lightdm" with the following:

```<code>sudo rm /etc/lightdm/lightdm.conf
sudo ucf -p /etc/lightdm/lightdm.conf
sudo apt-get install --reinstall lightdm
</code>```

(2) Then re-install "recommended driver" nvidia (can be found on your system current nvidia drivers)

```<code>sudo ubuntu-drivers devices
</code>```

You will see something like:

```<code>...
...
driver  :  nvidia-384 - distro non-free recommended
...
</code>```

You will use the nvidia specified as recommended which is on this example is nvidia-384

Finally, perform:

```<code>sudo apt-get install nvidia-384
</code>```

And reboot the system.

Body:
This could be caused by conflicting x11 libs. Some of you might also experience similar issue on a different or older version of Ubuntu.

Prompt dialog

Perform Ctrl+Alt+F1 then a console will be displayed.

Enter your credentials...

(1) You need to reset the "lightdm" with the following:

sudo rm /etc/lightdm/lightdm.conf
sudo ucf -p /etc/lightdm/lightdm.conf
sudo apt-get install --reinstall lightdm

(2) Then re-install "recommended driver" nvidia (can be found on your system current nvidia drivers)

sudo ubuntu-drivers devices

You will see something like:

...
...
driver  :  nvidia-384 - distro non-free recommended
...

You will use the nvidia specified as recommended which is on this example is nvidia-384

Finally, perform:

sudo apt-get install nvidia-384

And reboot the system.


问:
Hosting an HTML page on a Meteor app
I have a Meteor app and would like to host an HTML page.

I can put my index.html page and content inside meteors public/main/ folder, so it would be accessible by 127.0.0.1/main/index.html.

But surely there must be a better way. I have the Kadira FlowRouter package and Blaze templates if it helps.

I tried:

```<code>FlowRouter.route('/main', {
  action(params) {
    window.location.href=pathToPage;
  }
});
</code>```

But it didn't work when moving my page out of the public folder.

The page itself is an HTML and javascript page.

答:
Try using the static-html package.

From the package description:

Essentially, an alternative to the templating package that doesn't
  compile Blaze templates. Mostly useful if you want to use Angular or
  React as your view layer and just want to get some static HTML content
  on your page as a render target for your view framework.

This build plugin parses all of the .html files in your app and looks
  for top-level tags:

 - appended to the head section of your HTML  - appended
  to the body section of your HTML Attributes are supported on the
   tag, but not on .

Title: Hosting an HTML page on a Meteor app

Body:
I have a Meteor app and would like to host an HTML page.

I can put my index.html page and content inside meteors public/main/ folder, so it would be accessible by 127.0.0.1/main/index.html.

But surely there must be a better way. I have the Kadira FlowRouter package and Blaze templates if it helps.

I tried:

FlowRouter.route('/main', {
  action(params) {
    window.location.href=pathToPage;
  }
});

But it didn't work when moving my page out of the public folder.

The page itself is an HTML and javascript page.


问:
How can I visualize coordinates from a csv file using folium?
I have data in the cvs files:

```<code>ID,   Name,    Address,            Latitude,     Longitude.
FOO   BO    34 Zako, Kost str.55  49.2955102    19.95274595
FOO   B1    55 Vara, Dost str 44  49.4814       20.0303
ZOO   B2    56 XXXX, YYYY str 99  49.5551       21.6766
</code>```

I would like to visualize this data on the map using folium in python3.
The example code for coordinates is:

```<code>import folium

logo_url = 'https://upload.wikimedia.org/wikipedia/en/c/c6/Logo_link.png'

start_lat = 52.2138
start_lng = 20.9795
csv_data_lat = 49.2955102
csv_data_lng = 19.95274595

map_1 = folium.Map(location=[start_lat, start_lng], zoom_start=12,control_scale = True)

icon = folium.features.CustomIcon(logo_url, icon_size=(50, 50))

folium.Marker([csv_data_lat, csv_data_lng], popup='PKOBP', icon=icon).add_to(map_1)

map_1.save('map1.html')
</code>```

How to do it for data from csv files?

答:
I guess you could do something like this instead of the folium.Marker line:

```<code>def add_marker(row,map,icon):
   folium.Marker([row["latitude"], row["longitude"]], popup='PKOBP', icon=icon).add_to(map)

df = pd.read_csv('your_csv.csv')
df.apply(add_marker,axis=1,args=(map_1,icon,))
</code>```

Body:
I have data in the cvs files:

ID,   Name,    Address,            Latitude,     Longitude.
FOO   BO    34 Zako, Kost str.55  49.2955102    19.95274595
FOO   B1    55 Vara, Dost str 44  49.4814       20.0303
ZOO   B2    56 XXXX, YYYY str 99  49.5551       21.6766

I would like to visualize this data on the map using folium in python3.
The example code for coordinates is:

import folium

logo_url = 'https://upload.wikimedia.org/wikipedia/en/c/c6/Logo_link.png'

start_lat = 52.2138
start_lng = 20.9795
csv_data_lat = 49.2955102
csv_data_lng = 19.95274595

map_1 = folium.Map(location=[start_lat, start_lng], zoom_start=12,control_scale = True)

icon = folium.features.CustomIcon(logo_url, icon_size=(50, 50))

folium.Marker([csv_data_lat, csv_data_lng], popup='PKOBP', icon=icon).add_to(map_1)

map_1.save('map1.html')

How to do it for data from csv files?

Body:
I guess you could do something like this instead of the folium.Marker line:

def add_marker(row,map,icon):
   folium.Marker([row["latitude"], row["longitude"]], popup='PKOBP', icon=icon).add_to(map)

df = pd.read_csv('your_csv.csv')
df.apply(add_marker,axis=1,args=(map_1,icon,))


问:
Unable to get maxheight on resize
I have html and script like this. I want box1 box2 box display with the same height. But when I resize browser to check, the max height is not correct.

```<code><div class="pro_intro>"
   <div class="box box1">
     something 1
   </div>
   <div class="box box2">
     something 2
   </div>
   <div class="box box3">
     something 3
   </div>
</div>

$(window).on("resize", function () {
        var max = -1;
        $(".pro_intro .box").each(function() {
            var h = $(this).outerHeight();
            max = h > max ? h : max;
        });
        $(".pro_intro .box").css("height",max);
        $(".pro_intro .box").css({'visibility':'visible'});
}).resize();
</code>```

Any suggestion for this. Thank you so much

答:
You are missing a closing quotation mark for your pro_intro div.

Try this

```<code>$(window).on("resize", function () {
    $(".pro_intro .box").each(function() {
        $(this).css("height","");
    });
    var max = -1;
    $(".pro_intro .box").each(function() {
        var h = $(this).outerHeight();
        max = h > max ? h : max;
    });
    $(".pro_intro .box").each(function() {
    $(this).css({"height": max, "visibility": "visible"});
    });
});
</code>```

Title: Unable to get maxheight on resize

Body:
I have html and script like this. I want box1 box2 box display with the same height. But when I resize browser to check, the max height is not correct.

"

     something 1

     something 2

     something 3

$(window).on("resize", function () {
        var max = -1;
        $(".pro_intro .box").each(function() {
            var h = $(this).outerHeight();
            max = h > max ? h : max;
        });
        $(".pro_intro .box").css("height",max);
        $(".pro_intro .box").css({'visibility':'visible'});
}).resize();

Any suggestion for this. Thank you so much

Body:
You are missing a closing quotation mark for your pro_intro div.

Try this

$(window).on("resize", function () {
    $(".pro_intro .box").each(function() {
        $(this).css("height","");
    });
    var max = -1;
    $(".pro_intro .box").each(function() {
        var h = $(this).outerHeight();
        max = h > max ? h : max;
    });
    $(".pro_intro .box").each(function() {
    $(this).css({"height": max, "visibility": "visible"});
    });
});


问:
Caesar Cipher with Ascii Characters
I'm trying to encrypt a String using ascii characters with a key position integer. I've got two methods, one for encrypting, one for decrypting.

The problem is that when the character value is above 126, I try to mod 126 it and then add 32 back into it but I get numbers far out of these limits.

```<code>public static String encrypt(String s, int k) {
    char[] arr = s.toCharArray();
    int ascii;
    for(int i = 0; i < arr.length; i++) {
        ascii = (int) arr[i];
        ascii = ascii + k;
        // System.out.println(ascii);
        if (ascii > 126) {
            ascii = 32 + (126 % ascii);
            // System.out.print("Changed: " + ascii);
        }

        arr[i] = (char) ascii;
    }
    return String.valueOf(arr);
}
</code>```

The two commented out lines were for testing, and the changed values are crazy high, like instead of going from 127 % 126 = 1 + 32 for a total of 33 (intended value), I get 15870.

答:
First, as mypetlion mentioned, the modulo operation a % b equals the remainder when a is divided by b. E.g. 11 % 4 = 3, 8 % 15 = 8. To be precise, it is the value k that satisfies b * n + k = a, b * (n + 1) > a, k < b where n is an integer. There are more appropriate descriptions using discrete maths and I'm ignoring negative arguments but they are not important. So in your case you should be doing ascii % 128.

As of why the modulo should be 128 and not 126, 7 bit ascii code goes from 0-127, 128 values in total. Also I'm a bit confused as to what the +32 is for, since you already did +k.

Also you can omit your if block completely because c % 128 = c for any c in range [0, 128).

So I would write the following code:

```<code>public static String encrypt(String s, int k) {
    char[] arr = s.toCharArray();
    for(int i = 0; i < arr.length; i++){
        arr[i] = (char) ((arr[i] + k) % 128);
    }
    return String.valueOf(arr);
}
public static String decrypt(String s, int k) {
    char[] arr = s.toCharArray();
    for(int i = 0; i < arr.length; i++){
        arr[i] = (char) ((arr[i] + 128 - k % 128) % 128);
        // + 128 - k % 128 because I don't want do deal with negative numbers.
    }
    return String.valueOf(arr);
}
</code>```

I am confident my code will work (for all positive values of k), but I cannot explain why your code produced some crazy high ascii values. When I ran your code on my IDE it didn't do that nor could I see why it would from your code.

Finally, this cipher method will encrypt and decrypt alright, but note that ascii does contain lots of control characters that are not print-friendly. So if you want to limit your cipher vocabulary to only letters and punctuations, you would need to do some character mapping to limit the characters you want to encrypt and encrypt to. This will be much more complicated, not to mention that you would have to consider problems like CR+LF in Windows v. LF in Unix. The following is a simple example that only encrypts and decrypts letters.

```<code>public static int asciiToCustom(char ascii) {
// Maps 65-90 & 97-122 to 0-51.
    int customCode;
    if(ascii >= 65 && ascii <= 90){
        customCode = ascii - 65;
    }
    else if(ascii >= 97 && ascii <= 122){
        customCode = ascii - 71;
    }
    else{
        throw new RuntimeException("not a letter!");
    }
    return customCode;
}
public static char customToAscii(int custom) {
// Maps 0-51 to 65-90 & 97-122.
    int ascii;
    if(custom >= 0 && custom <= 25){
        ascii = custom + 65;
    }
    else if(custom >= 26 && custom <= 51){
        ascii = custom + 71;
    }
    else{
        throw new RuntimeException("not a valid custom code!");
    }
    return (char) ascii;
}
public static String encrypt(String s, int k) {
    char[] arr = s.toCharArray();
    for(int i = 0; i < arr.length; i++){
        if(Character.isLetter(arr[i])){
            arr[i] = customToAscii((asciiToCustom(arr[i]) + k) % 52);
        }
    }
    return String.valueOf(arr);
}
public static String decrypt(String s, int k) {
    char[] arr = s.toCharArray();
    for(int i = 0; i < arr.length; i++){
        if(Character.isLetter(arr[i])){
            arr[i] = customToAscii((asciiToCustom(arr[i]) + 52 - k % 52) % 52);
            // + 52 - k % 52 because I don't want do deal with negative numbers.
        }
    }
    return String.valueOf(arr);
}
</code>```

Title: Caesar Cipher with Ascii Characters

Body:
I'm trying to encrypt a String using ascii characters with a key position integer. I've got two methods, one for encrypting, one for decrypting.

The problem is that when the character value is above 126, I try to mod 126 it and then add 32 back into it but I get numbers far out of these limits.

public static String encrypt(String s, int k) {
    char[] arr = s.toCharArray();
    int ascii;
    for(int i = 0; i < arr.length; i++) {
        ascii = (int) arr[i];
        ascii = ascii + k;
        // System.out.println(ascii);
        if (ascii > 126) {
            ascii = 32 + (126 % ascii);
            // System.out.print("Changed: " + ascii);
        }

        arr[i] = (char) ascii;
    }
    return String.valueOf(arr);
}

The two commented out lines were for testing, and the changed values are crazy high, like instead of going from 127 % 126 = 1 + 32 for a total of 33 (intended value), I get 15870.

Body:
First, as mypetlion mentioned, the modulo operation a % b equals the remainder when a is divided by b. E.g. 11 % 4 = 3, 8 % 15 = 8. To be precise, it is the value k that satisfies b * n + k = a, b * (n + 1) > a, k < b where n is an integer. There are more appropriate descriptions using discrete maths and I'm ignoring negative arguments but they are not important. So in your case you should be doing ascii % 128.

As of why the modulo should be 128 and not 126, 7 bit ascii code goes from 0-127, 128 values in total. Also I'm a bit confused as to what the +32 is for, since you already did +k.

Also you can omit your if block completely because c % 128 = c for any c in range [0, 128).

So I would write the following code:

public static String encrypt(String s, int k) {
    char[] arr = s.toCharArray();
    for(int i = 0; i < arr.length; i++){
        arr[i] = (char) ((arr[i] + k) % 128);
    }
    return String.valueOf(arr);
}
public static String decrypt(String s, int k) {
    char[] arr = s.toCharArray();
    for(int i = 0; i < arr.length; i++){
        arr[i] = (char) ((arr[i] + 128 - k % 128) % 128);
        // + 128 - k % 128 because I don't want do deal with negative numbers.
    }
    return String.valueOf(arr);
}

I am confident my code will work (for all positive values of k), but I cannot explain why your code produced some crazy high ascii values. When I ran your code on my IDE it didn't do that nor could I see why it would from your code.

Finally, this cipher method will encrypt and decrypt alright, but note that ascii does contain lots of control characters that are not print-friendly. So if you want to limit your cipher vocabulary to only letters and punctuations, you would need to do some character mapping to limit the characters you want to encrypt and encrypt to. This will be much more complicated, not to mention that you would have to consider problems like CR+LF in Windows v. LF in Unix. The following is a simple example that only encrypts and decrypts letters.

public static int asciiToCustom(char ascii) {
// Maps 65-90 & 97-122 to 0-51.
    int customCode;
    if(ascii >= 65 && ascii <= 90){
        customCode = ascii - 65;
    }
    else if(ascii >= 97 && ascii <= 122){
        customCode = ascii - 71;
    }
    else{
        throw new RuntimeException("not a letter!");
    }
    return customCode;
}
public static char customToAscii(int custom) {
// Maps 0-51 to 65-90 & 97-122.
    int ascii;
    if(custom >= 0 && custom <= 25){
        ascii = custom + 65;
    }
    else if(custom >= 26 && custom <= 51){
        ascii = custom + 71;
    }
    else{
        throw new RuntimeException("not a valid custom code!");
    }
    return (char) ascii;
}
public static String encrypt(String s, int k) {
    char[] arr = s.toCharArray();
    for(int i = 0; i < arr.length; i++){
        if(Character.isLetter(arr[i])){
            arr[i] = customToAscii((asciiToCustom(arr[i]) + k) % 52);
        }
    }
    return String.valueOf(arr);
}
public static String decrypt(String s, int k) {
    char[] arr = s.toCharArray();
    for(int i = 0; i < arr.length; i++){
        if(Character.isLetter(arr[i])){
            arr[i] = customToAscii((asciiToCustom(arr[i]) + 52 - k % 52) % 52);
            // + 52 - k % 52 because I don't want do deal with negative numbers.
        }
    }
    return String.valueOf(arr);
}


问:
Tensorflow doesn't have Constant (but has everything else?)
I recently installed Tensorflow with pip on a new Python 3.6.3 installation.

The following code:

```<code>import tensorflow as tf

msgconst = tf.Constant("henlo wrlod lol <4")
thesession = tf.Session()
print(thesession.run(msgconst))
thesession.close()
</code>```

gives the error

```<code>Traceback (most recent call last):
  File "C:/Users/[my username]/PycharmProjects/TFlowTest/aergaetgaertgasrtg.py", line 3, in <module>
    msgconst = tf.Constant("henlo wrlod lol <4")
AttributeError: module 'tensorflow' has no attribute 'Constant'
</code>```

The issue is not that there is another file named tensorflow that is getting imported instead of the real library; everything else is present. I can do this just fine:

```<code>import tensorflow as tf
from tensorflow.python.framework import ops
ops.reset_default_graph()
print(tf.test.is_built_with_cuda())
print(tf.test.gpu_device_name())
</code>```

giving

```<code>True
2017-12-06 21:03:22.807800: I C:\tf_jenkins\home\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\core\platform\cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
2017-12-06 21:03:23.147288: I C:\tf_jenkins\home\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\core\common_runtime\gpu\gpu_device.cc:1030] Found device 0 with properties:
name: GeForce GTX 980M major: 5 minor: 2 memoryClockRate(GHz): 1.1265
pciBusID: 0000:01:00.0
totalMemory: 4.00GiB freeMemory: 3.32GiB
2017-12-06 21:03:23.147553: I C:\tf_jenkins\home\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\core\common_runtime\gpu\gpu_device.cc:1120] Creating TensorFlow device (/device:GPU:0) -> (device: 0, name: GeForce GTX 980M, pci bus id: 0000:01:00.0, compute capability: 5.2)
/device:GPU:0

Process finished with exit code 0
</code>```

This issues survives uninstalling and reinstalling Tensorflow; here's what pip prints while installing it

```<code>C:\Program Files\Python36-64\Scripts>pip install tensorflow-gpu --no-cache-dir
Collecting tensorflow-gpu
  Downloading tensorflow_gpu-1.4.0-cp36-cp36m-win_amd64.whl (67.6MB)
    100% |████████████████████████████████| 67.6MB ...
Requirement already satisfied: numpy>=1.12.1 in c:\program files\python36-64\lib\site-packages (from tensorflow-gpu)
Requirement already satisfied: wheel>=0.26 in c:\program files\python36-64\lib\site-packages (from tensorflow-gpu)
Requirement already satisfied: six>=1.10.0 in c:\program files\python36-64\lib\site-packages (from tensorflow-gpu)
Requirement already satisfied: enum34>=1.1.6 in c:\program files\python36-64\lib\site-packages (from tensorflow-gpu)
Requirement already satisfied: tensorflow-tensorboard<0.5.0,>=0.4.0rc1 in c:\program files\python36-64\lib\site-packages (from tensorflow-gpu)
Requirement already satisfied: protobuf>=3.3.0 in c:\program files\python36-64\lib\site-packages (from tensorflow-gpu)
Requirement already satisfied: html5lib==0.9999999 in c:\program files\python36-64\lib\site-packages (from tensorflow-tensorboard<0.5.0,>=0.4.0rc1->tensorflow-gpu)
Requirement already satisfied: werkzeug>=0.11.10 in c:\program files\python36-64\lib\site-packages (from tensorflow-tensorboard<0.5.0,>=0.4.0rc1->tensorflow-gpu)
Requirement already satisfied: markdown>=2.6.8 in c:\program files\python36-64\lib\site-packages (from tensorflow-tensorboard<0.5.0,>=0.4.0rc1->tensorflow-gpu)
Requirement already satisfied: bleach==1.5.0 in c:\program files\python36-64\lib\site-packages (from tensorflow-tensorboard<0.5.0,>=0.4.0rc1->tensorflow-gpu)
Requirement already satisfied: setuptools in c:\program files\python36-64\lib\site-packages (from protobuf>=3.3.0->tensorflow-gpu)
Installing collected packages: tensorflow-gpu
Successfully installed tensorflow-gpu-1.4.0
</code>```

Any suggestions?

答:
You're going to hate to hear this, but it's

```<code>tf.constant(
</code>```

not

```<code>tf.Constant(
</code>```

(Notice that the first one is not capitalized.)

I just played around with your code in my environment to notice this, so I can say that I did in fact have trouble with your code, but then it worked when using a small case constant.

Body:
I recently installed Tensorflow with pip on a new Python 3.6.3 installation.

The following code:

import tensorflow as tf

msgconst = tf.Constant("henlo wrlod lol <4")
thesession = tf.Session()
print(thesession.run(msgconst))
thesession.close()

gives the error

Traceback (most recent call last):
  File "C:/Users/[my username]/PycharmProjects/TFlowTest/aergaetgaertgasrtg.py", line 3, in <module>
    msgconst = tf.Constant("henlo wrlod lol <4")
AttributeError: module 'tensorflow' has no attribute 'Constant'

The issue is not that there is another file named tensorflow that is getting imported instead of the real library; everything else is present. I can do this just fine:

import tensorflow as tf
from tensorflow.python.framework import ops
ops.reset_default_graph()
print(tf.test.is_built_with_cuda())
print(tf.test.gpu_device_name())

giving

True
2017-12-06 21:03:22.807800: I C:\tf_jenkins\home\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\core\platform\cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
2017-12-06 21:03:23.147288: I C:\tf_jenkins\home\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\core\common_runtime\gpu\gpu_device.cc:1030] Found device 0 with properties:
name: GeForce GTX 980M major: 5 minor: 2 memoryClockRate(GHz): 1.1265
pciBusID: 0000:01:00.0
totalMemory: 4.00GiB freeMemory: 3.32GiB
2017-12-06 21:03:23.147553: I C:\tf_jenkins\home\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\core\common_runtime\gpu\gpu_device.cc:1120] Creating TensorFlow device (/device:GPU:0) -> (device: 0, name: GeForce GTX 980M, pci bus id: 0000:01:00.0, compute capability: 5.2)
/device:GPU:0

Process finished with exit code 0

This issues survives uninstalling and reinstalling Tensorflow; here's what pip prints while installing it

C:\Program Files\Python36-64\Scripts>pip install tensorflow-gpu --no-cache-dir
Collecting tensorflow-gpu
  Downloading tensorflow_gpu-1.4.0-cp36-cp36m-win_amd64.whl (67.6MB)
    100% |████████████████████████████████| 67.6MB ...
Requirement already satisfied: numpy>=1.12.1 in c:\program files\python36-64\lib\site-packages (from tensorflow-gpu)
Requirement already satisfied: wheel>=0.26 in c:\program files\python36-64\lib\site-packages (from tensorflow-gpu)
Requirement already satisfied: six>=1.10.0 in c:\program files\python36-64\lib\site-packages (from tensorflow-gpu)
Requirement already satisfied: enum34>=1.1.6 in c:\program files\python36-64\lib\site-packages (from tensorflow-gpu)
Requirement already satisfied: tensorflow-tensorboard<0.5.0,>=0.4.0rc1 in c:\program files\python36-64\lib\site-packages (from tensorflow-gpu)
Requirement already satisfied: protobuf>=3.3.0 in c:\program files\python36-64\lib\site-packages (from tensorflow-gpu)
Requirement already satisfied: html5lib==0.9999999 in c:\program files\python36-64\lib\site-packages (from tensorflow-tensorboard<0.5.0,>=0.4.0rc1->tensorflow-gpu)
Requirement already satisfied: werkzeug>=0.11.10 in c:\program files\python36-64\lib\site-packages (from tensorflow-tensorboard<0.5.0,>=0.4.0rc1->tensorflow-gpu)
Requirement already satisfied: markdown>=2.6.8 in c:\program files\python36-64\lib\site-packages (from tensorflow-tensorboard<0.5.0,>=0.4.0rc1->tensorflow-gpu)
Requirement already satisfied: bleach==1.5.0 in c:\program files\python36-64\lib\site-packages (from tensorflow-tensorboard<0.5.0,>=0.4.0rc1->tensorflow-gpu)
Requirement already satisfied: setuptools in c:\program files\python36-64\lib\site-packages (from protobuf>=3.3.0->tensorflow-gpu)
Installing collected packages: tensorflow-gpu
Successfully installed tensorflow-gpu-1.4.0

Any suggestions?

Body:
You're going to hate to hear this, but it's

tf.constant(

not

tf.Constant(

(Notice that the first one is not capitalized.)

I just played around with your code in my environment to notice this, so I can say that I did in fact have trouble with your code, but then it worked when using a small case constant.


问:
opencv knn TypeError: only length-1 arrays can be converted to Python scalars
I am trying to follow the tutorial http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_ml/py_knn/py_knn_opencv/py_knn_opencv.html and replaced KNearest with cv2.m1.KNearest_create() but  i am getting TypeError: only length-1 arrays can be converted to Python scalars

```<code>import numpy as np
import cv2
from matplotlib import pyplot as plt

img = cv2.imread('digits.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# Now we split the image to 5000 cells, each 20x20 size
cells = [np.hsplit(row,100) for row in np.vsplit(gray,50)]

# Make it into a Numpy array. It size will be (50,100,20,20)
x = np.array(cells)

# Now we prepare train_data and test_data.
train = x[:,:50].reshape(-1,400).astype(np.float32) # Size = (2500,400)
test = x[:,50:100].reshape(-1,400).astype(np.float32) # Size = (2500,400)

# Create labels for train and test data
k = np.arange(10)
train_labels = np.repeat(k,250)[:,np.newaxis]
test_labels = train_labels.copy()

# Initiate kNN, train the data, then test it with test data for k=1
cv2.m1.KNearest_create()
knn.train(train,train_labels)
ret,result,neighbours,dist = knn.find_nearest(test,k=5)

# Now we check the accuracy of classification
# For that, compare the result with test_labels and check which are wrong
matches = result==test_labels
correct = np.count_nonzero(matches)
accuracy = correct*100.0/result.size
print accuracy
</code>```

(i am using a raspberry pi and followed this tutorial to install open cv http://www.pyimagesearch.com/2015/10/26/how-to-install-opencv-3-on-raspbian-jessie/ subsequently i pip installed matplotlib)

答:
doc of opencv said that:

findNearest(...)  |      findNearest(samples, k[, results[,
  neighborResponses[, dist]]]) -> retval, results, neighborResponses,
  ...

not knn.find_nearest(test,k=5)

you can run

help(cv2.ml.KNearest_create())

then you will see.
by the way ,there are losts erros on opencv website

Body:
I am trying to follow the tutorial http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_ml/py_knn/py_knn_opencv/py_knn_opencv.html and replaced KNearest with cv2.m1.KNearest_create() but  i am getting TypeError: only length-1 arrays can be converted to Python scalars

import numpy as np
import cv2
from matplotlib import pyplot as plt

img = cv2.imread('digits.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# Now we split the image to 5000 cells, each 20x20 size
cells = [np.hsplit(row,100) for row in np.vsplit(gray,50)]

# Make it into a Numpy array. It size will be (50,100,20,20)
x = np.array(cells)

# Now we prepare train_data and test_data.
train = x[:,:50].reshape(-1,400).astype(np.float32) # Size = (2500,400)
test = x[:,50:100].reshape(-1,400).astype(np.float32) # Size = (2500,400)

# Create labels for train and test data
k = np.arange(10)
train_labels = np.repeat(k,250)[:,np.newaxis]
test_labels = train_labels.copy()

# Initiate kNN, train the data, then test it with test data for k=1
cv2.m1.KNearest_create()
knn.train(train,train_labels)
ret,result,neighbours,dist = knn.find_nearest(test,k=5)

# Now we check the accuracy of classification
# For that, compare the result with test_labels and check which are wrong
matches = result==test_labels
correct = np.count_nonzero(matches)
accuracy = correct*100.0/result.size
print accuracy

(i am using a raspberry pi and followed this tutorial to install open cv http://www.pyimagesearch.com/2015/10/26/how-to-install-opencv-3-on-raspbian-jessie/ subsequently i pip installed matplotlib)


问:
Python (Flask) and MQTT listening
I'm currently trying to get my Python (Flask) webserver to display what my MQTT script is doing. The MQTT script, In essence, it's subscribed to a topic and I would really like to categorize the info it gets and display/update it in real time. Something like a simple list displaying various the settings that gets updated regularly.

```<code>Setting1 = 9
Setting2 = 2
Setting3 = 5
</code>```

To begin with, I have a connect to page, so that you can fill-in an IP to which the Python (Flask) should connect to:

```<code>@app.route("/")
def my_form():
        return render_template("connect.html")

@app.route("/", methods=["POST"])
def my_form_post():
        text = request.form["text"]
        processed_text = text.upper()
</code>```

To which the connect.html looks like:

```<code><!DOCTYPE html>
<html lang="en">
<body>
    <h2>Fill in the IP in below:</h2>
    <form action="." method="POST">
        <input type="text" name="text">
        <input type="submit" name="my-form" value="Connect">
    </form>
</body>
</html>
</code>```

The connecting to the MQTT part is where the tricky part comes in and I will require some assistance. I was thinking of just adding the connect underneath but this just doesn't work right, it will just come back with an Internal Server Error.

Any help would really be appreciated!

Thanks!

答: try this:http://flask-mqtt.readthedocs.io/en/latest/#,a Flask extension that meant to facilitate the integration of a MQTT client into your web application</p>

Title: Python (Flask) and MQTT listening

Body:
I'm currently trying to get my Python (Flask) webserver to display what my MQTT script is doing. The MQTT script, In essence, it's subscribed to a topic and I would really like to categorize the info it gets and display/update it in real time. Something like a simple list displaying various the settings that gets updated regularly.

Setting1 = 9
Setting2 = 2
Setting3 = 5

To begin with, I have a connect to page, so that you can fill-in an IP to which the Python (Flask) should connect to:

@app.route("/")
def my_form():
        return render_template("connect.html")

@app.route("/", methods=["POST"])
def my_form_post():
        text = request.form["text"]
        processed_text = text.upper()

To which the connect.html looks like:

<!DOCTYPE html>

Fill in the IP in below:

    <form action="." method="POST">
        <input type="text" name="text">
        <input type="submit" name="my-form" value="Connect">
    </form>

The connecting to the MQTT part is where the tricky part comes in and I will require some assistance. I was thinking of just adding the connect underneath but this just doesn't work right, it will just come back with an Internal Server Error.

Any help would really be appreciated!

Thanks!


问:
opencv handling arrow keys with waitKey() function
I want to handling arrow keys. but when I print out the input value for waitKey() function, It's 0.
I don't know why.
I try to change from "int" to "char" , but It doesn't work.
How can I solve this problem.</p>

```<code>int pos = 100;
imshow("image", image);
onChange(pos, (void *)&image);
createTrackbar("threshold", "image", &pos, 255, onChange, (void*)&image);
while (1) {
    int Key = waitKey();
    cout << Key << endl;
    if (Key == 27) break;
    if (Key == 2490368) {
        pos--;
        onChange(pos, (void *)&image);
    }
    if(Key == 2621440){
        pos++;
        onChange(pos, (void *)&image);
    }
    if (pos < 0 || pos > 255) pos = 0;
}
</code>```

答:
Below is my temporary workaround</p>

```<code>#ifndef _WIN32
int myWaitKey(int wait) {
    int c = cv::waitKey(wait);
    return c;
}
#pragma message("linux..")
#else
#include <conio.h> // to support _getch
int myWaitKey(int wait) {
    int c = cvWaitKey(wait);
    if (c == 0) {
        int c = _getch();   //capture the key code and insert into c
        if (c == 0 || c == 224)
            c = _getch();
    }
    //if (c!=-1) printf("%d\n",c);
    return c;
}
#endif
</code>```

Body:
I want to handling arrow keys. but when I print out the input value for waitKey() function, It's 0.
I don't know why.
I try to change from "int" to "char" , but It doesn't work.
How can I solve this problem.

int pos = 100;
imshow("image", image);
onChange(pos, (void *)&image);
createTrackbar("threshold", "image", &pos, 255, onChange, (void*)&image);
while (1) {
    int Key = waitKey();
    cout << Key << endl;
    if (Key == 27) break;
    if (Key == 2490368) {
        pos--;
        onChange(pos, (void *)&image);
    }
    if(Key == 2621440){
        pos++;
        onChange(pos, (void *)&image);
    }
    if (pos < 0 || pos > 255) pos = 0;
}

Body:
Below is my temporary workaround

#ifndef _WIN32
int myWaitKey(int wait) {
    int c = cv::waitKey(wait);
    return c;
}
#pragma message("linux..")
#else
#include <conio.h> // to support _getch
int myWaitKey(int wait) {
    int c = cvWaitKey(wait);
    if (c == 0) {
        int c = _getch();   //capture the key code and insert into c
        if (c == 0 || c == 224)
            c = _getch();
    }
    //if (c!=-1) printf("%d\n",c);
    return c;
}
#endif


问:
Can't remotely connect to MongoDB through an SSH channel
I am having an issue connecting to a mongoDB through SSH. I commented out the bind_ip option (and then added the authorization option). But to no avail. I even allowed the port through my firewalls. I get this error

"Cannot establish SSH Tunnel (IP:22).
Error: Failed to create a SSH channel"

It is worth mentioning I am using Robo 3T, and the first step, connecting to the server passes.

答:
You can try this:

Select whether Compass should connect to a MongoDB cluster via an SSH tunnel, which automatically starts when you connect to MongoDB, and stops when you disconnect. If selected, choose either a password or an identity file to provide authentication.

Link: https://docs.mongodb.com/compass/master/connect/