问:
Storing access token globally, re-loading when expires it a thread-safe way
I have an API client that connects to a 3rd party API service.

The problem is I first have to authenticate, and then I get an expiring token that I use.

How can I use my API in my ASP.NET MVC application, and also keep track if the token expires I have to re-authenticate and then make the API call that failed (when the token expires).

```<code>List<User> users = api.getUsers();
</code>```

If the api clients token expires, it has to re-authenticate and then make the call.  Is there a way to re-call api.getUsers after it re-authenticates because intially the call will fail with "expired token".

Thoughts?

答:
If there is service call that allows validating the token, have your authentication object check the token in the getter and authenticate anytime it is not valid.

If not, I would use a try/catch and handle the expired token exception by authenticating and repeating the request. The repeat either needs to be a stand-alone block of code in the catch or you need an object to check the last time authenticate was called and throw an exception after n attempts.

I'm sure there are several other approaches, these are what come immediately to mind.

Body:
I have an API client that connects to a 3rd party API service.

The problem is I first have to authenticate, and then I get an expiring token that I use.

How can I use my API in my ASP.NET MVC application, and also keep track if the token expires I have to re-authenticate and then make the API call that failed (when the token expires).

List<User> users = api.getUsers();

If the api clients token expires, it has to re-authenticate and then make the call.  Is there a way to re-call api.getUsers after it re-authenticates because intially the call will fail with "expired token".

Thoughts?


来源: stackexchange

问:
Decrease version number
I'm creating a while loop which stops when it reaches a specific version.
The issue is that if I have version 1.1.4 and want to go down to 1.0.9, my awk command that I've found on this forum doesn't do well.

I'm using something like this:

```<code>while compare versions; do

    current version=

    if [[ actual version != current version ]]; then

        currentver=

        previous version=`echo $ current version | awk -F. -v OFS=. \
              'NF==1{print ++$NF};
               NF>1{if(length($NF+1)>length($NF))$(NF-1)++;
               $NF=sprintf("%0*d", length($NF), ($NF-1)%(10^length($NF)));
               print}'`

        Go back to $ previous version

        do something
</code>```

What I get is:

```<code>Go back to 1.1.4

Go back to 1.1.3

Go back to 1.1.2

Go back to 1.1.1

Go back to 1.1.0

Go back to 1.1.-1

Go back to 1.1.-2
</code>```

I want the version number to go to 1.0.9.

How can I change the awk command not to go below 0?

ContentLicense: CC BY-SA 3.0

Title: Decrease version number

Body:
I'm creating a while loop which stops when it reaches a specific version.
The issue is that if I have version 1.1.4 and want to go down to 1.0.9, my awk command that I've found on this forum doesn't do well.

I'm using something like this:

while compare versions; do

    current version=

    if [[ actual version != current version ]]; then

        currentver=

        previous version=`echo $ current version | awk -F. -v OFS=. \
              'NF==1{print ++$NF};
               NF>1{if(length($NF+1)>length($NF))$(NF-1)++;
               $NF=sprintf("%0*d", length($NF), ($NF-1)%(10^length($NF)));
               print}'`

        Go back to $ previous version

        do something

What I get is:

Go back to 1.1.4

Go back to 1.1.3

Go back to 1.1.2

Go back to 1.1.1

Go back to 1.1.0

Go back to 1.1.-1

Go back to 1.1.-2

I want the version number to go to 1.0.9.

How can I change the awk command not to go below 0?

Body:
A little bash and sed:

echo "version_1."{104..099} | sed 's/ /\n/g' | sed 's/.\(.$\)/.\1/g;y/_/ /'

Output:

version 1.1.4
version 1.1.3
version 1.1.2
version 1.1.1
version 1.1.0
version 1.0.9

Another similar method:

echo "version_"{114..109} | sed 's/ /\n/g;y/_/ /;s/\([0-9]\)\([0-9]\)/\1.\2./g'


问:
Get size of entries in ehcache 3
I want to use ehcache3. For some junit tests, I need to know the size of entries in the cache. I dont find a method.
How can get the size of entries (not memory) in ehcache 3?

Greets

Benjamin

答:
Since it's only for test, your best bet is</p>

```<code>    int count = 0;
    for(Cache.Entry<Long, String> entry : cache) {
        count++;
    }
</code>```

Title: Get size of entries in ehcache 3

Body:
Since it's only for test, your best bet is

    int count = 0;
    for(Cache.Entry<Long, String> entry : cache) {
        count++;
    }


问:
Python TypeError: not enough arguments for format string
Here's the output.  These are utf-8 strings I believe... some of these can be NoneType but it fails immediately, before ones like that...

```<code>instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname, procversion, int(percent), exe, description, company, procurl
</code>```

TypeError: not enough arguments for format string

Its 7 for 7 though?

答: I got the same error when using % as a percent character in my format string.  The solution to this is to double up the %%.

Body:
Here's the output.  These are utf-8 strings I believe... some of these can be NoneType but it fails immediately, before ones like that...

instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname, procversion, int(percent), exe, description, company, procurl

TypeError: not enough arguments for format string

Its 7 for 7 though?

ContentLicense: CC BY-SA 4.0


问:
WPF AvalonEdit SQL xhsd request
I've looked on the internet (over and over) and I couldn't find an SQL.vshd file for AvalonEdit, I've used the old format version but it makes the editor bug (it doesn't show anymore at all), So I'm wondering maybe someone has done such a file because I don't want to waste my time doing this if it's been already done.

If you could share yours with me that'd be appreciated :)

Thanks in advance

答:
```<code><?xml version="1.0"?>
<SyntaxDefinition name="sql" extensions=".sql"
                  xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
  <Color name="String" foreground="Olive" exampleText="string text = "Hello, World!""/>
  <Color name="String2" foreground="#993" exampleText="string text = "Hello, World!""/>
  <Color name="Comment" foreground="Green" exampleText="string text = "Hello, World!""/>
   <Color name="Punctuation" foreground="Red" exampleText="string text = "Hello, World!""/>
  <RuleSet  ignoreCase="true">
    <Span color="String" multiline="true" >
      <Begin>'</Begin>
      <End>'</End>

    </Span>

    <Span color="String2" multiline="true"  >
      <Begin>"</Begin>
      <End>"</End>
    </Span>
    <!-- span for escape sequences -->
    <Span  color="Comment" begin="--" end="\n"/>
    <Span color="Comment"  multiline="true">
      <Begin>/\*</Begin>
      <End>\*/</End>
    </Span>

    <Keywords fontWeight="bold" foreground="Blue" >
      <Word>ABORT</Word>
      <Word>BETWEEN</Word>
      <Word>CRASH</Word>
      <Word>DIGITS</Word>
      <Word>ACCEPT</Word>
      <Word>BINARY_INTEGER</Word>
      <Word>CREATE</Word>
      <Word>DISPOSE</Word>
      <Word>ACCESS</Word>
      <Word>BODY</Word>
      <Word>CURRENT</Word>
      <Word>DISTINCT</Word>
      <Word>ADD</Word>
      <Word>BOOLEAN</Word>
      <Word>CURRVAL</Word>
      <Word>DO</Word>
      <Word>ALL</Word>
      <Word>BY</Word>
      <Word>CURSOR</Word>
      <Word>DROP</Word>
      <Word>ALTER</Word>
      <Word>CASE</Word>
      <Word>DATABASE</Word>
      <Word>ELSE</Word>
      <Word>AND</Word>
      <Word>CHAR</Word>
      <Word>DATA_BASE</Word>
      <Word>ELSIF</Word>
      <Word>ANY</Word>
      <Word>CHAR_BASE</Word>
      <Word>DATE</Word>
      <Word>END</Word>
      <Word>ARRAY</Word>
      <Word>CHECK</Word>
      <Word>DBA</Word>
      <Word>ENTRY</Word>
      <Word>ARRAYLEN</Word>
      <Word>CLOSE</Word>
      <Word>DEBUGOFF</Word>
      <Word>EXCEPTION</Word>
      <Word>AS</Word>
      <Word>CLUSTER</Word>
      <Word>DEBUGON</Word>
      <Word>EXCEPTION_INIT</Word>
      <Word>ASC</Word>
      <Word>CLUSTERS</Word>
      <Word>DECLARE</Word>
      <Word>EXISTS</Word>
      <Word>ASSERT</Word>
      <Word>COLAUTH</Word>
      <Word>DECIMAL</Word>
      <Word>EXIT</Word>
      <Word>ASSIGN</Word>
      <Word>COLUMNS</Word>
      <Word>DEFAULT</Word>
      <Word>FALSE</Word>
      <Word>AT</Word>
      <Word>COMMIT</Word>
      <Word>DEFINITION</Word>
      <Word>FETCH</Word>
      <Word>AUTHORIZATION</Word>
      <Word>COMPRESS</Word>
      <Word>DELAY</Word>
      <Word>FLOAT</Word>
      <Word>AVG</Word>
      <Word>CONNECT</Word>
      <Word>DELETE</Word>
      <Word>FOR</Word>
      <Word>BASE_TABLE</Word>
      <Word>CONSTANT</Word>
      <Word>DELTA</Word>
      <Word>FORM</Word>
      <Word>BEGIN</Word>
      <Word>COUNT</Word>
      <Word>DESC</Word>
      <Word>FROM</Word>
      <Word>FUNCTION</Word>
      <Word>NEW</Word>
      <Word>RELEASE</Word>
      <Word>SUM</Word>
      <Word>GENERIC</Word>
      <Word>NEXTVAL</Word>
      <Word>REMR</Word>
      <Word>TABAUTH</Word>
      <Word>GOTO</Word>
      <Word>NOCOMPRESS</Word>
      <Word>RENAME</Word>
      <Word>TABLE</Word>
      <Word>GRANT</Word>
      <Word>NOT</Word>
      <Word>RESOURCE</Word>
      <Word>TABLES</Word>
      <Word>GROUP</Word>
      <Word>NULL</Word>
      <Word>RETURN</Word>
      <Word>TASK</Word>
      <Word>HAVING</Word>
      <Word>NUMBER</Word>
      <Word>REVERSE</Word>
      <Word>TERMINATE</Word>
      <Word>IDENTIFIED</Word>
      <Word>NUMBER_BASE</Word>
      <Word>REVOKE</Word>
      <Word>THEN</Word>
      <Word>IF</Word>
      <Word>OF</Word>
      <Word>ROLLBACK</Word>
      <Word>TO</Word>
      <Word>IN</Word>
      <Word>ON</Word>
      <Word>ROWID</Word>
      <Word>TRUE</Word>
      <Word>INDEX</Word>
      <Word>OPEN</Word>
      <Word>ROWLABEL</Word>
      <Word>TYPE</Word>
      <Word>INDEXES</Word>
      <Word>OPTION</Word>
      <Word>ROWNUM</Word>
      <Word>UNION</Word>
      <Word>INDICATOR</Word>
      <Word>OR</Word>
      <Word>ROWTYPE</Word>
      <Word>UNIQUE</Word>
      <Word>INSERT</Word>
      <Word>ORDER</Word>
      <Word>RUN</Word>
      <Word>UPDATE</Word>
      <Word>INTEGER</Word>
      <Word>OTHERS</Word>
      <Word>SAVEPOINT</Word>
      <Word>USE</Word>
      <Word>INTERSECT</Word>
      <Word>OUT</Word>
      <Word>SCHEMA</Word>
      <Word>VALUES</Word>
      <Word>INTO</Word>
      <Word>PACKAGE</Word>
      <Word>SELECT</Word>
      <Word>VARCHAR</Word>
      <Word>IS</Word>
      <Word>PARTITION</Word>
      <Word>SEPARATE</Word>
      <Word>VARCHAR2</Word>
      <Word>LEVEL</Word>
      <Word>PCTFREE</Word>
      <Word>SET</Word>
      <Word>VARIANCE</Word>
      <Word>LIKE</Word>
      <Word>POSITIVE</Word>
      <Word>SIZE</Word>
      <Word>VIEW</Word>
      <Word>LIMITED</Word>
      <Word>PRAGMA</Word>
      <Word>SMALLINT</Word>
      <Word>VIEWS</Word>
      <Word>LOOP</Word>
      <Word>PRIOR</Word>
      <Word>SPACE</Word>
      <Word>WHEN</Word>
      <Word>MAX</Word>
      <Word>PRIVATE</Word>
      <Word>SQL</Word>
      <Word>WHERE</Word>
      <Word>MIN</Word>
      <Word>PROCEDURE</Word>
      <Word>SQLCODE</Word>
      <Word>WHILE</Word>
      <Word>MINUS</Word>
      <Word>PUBLIC</Word>
      <Word>SQLERRM</Word>
      <Word>WITH</Word>
      <Word>MLSLABEL</Word>
      <Word>RAISE</Word>
      <Word>START</Word>
      <Word>WORK</Word>
      <Word>MOD</Word>
      <Word>RANGE</Word>
      <Word>STATEMENT</Word>
      <Word>XOR</Word>
      <Word>MODE</Word>
      <Word>REAL</Word>
      <Word>STDDEV</Word>
      <Word>NATURAL</Word>
      <Word>RECORD</Word>
      <Word>SUBTYPE</Word>
    </Keywords>
    <Rule color="Punctuation">
      [?,.;()\[\]{}+\-/%*<>^+~!|&]+
    </Rule>

  </RuleSet>

</SyntaxDefinition>
</code>```

ContentLicense: CC BY-SA 2.5

Title: WPF AvalonEdit SQL xhsd request

Body:
<?xml version="1.0"?>
<SyntaxDefinition name="sql" extensions=".sql"
                  xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
  <Color name="String" foreground="Olive" exampleText="string text = &quot;Hello, World!&quot;"/>
  <Color name="String2" foreground="#993" exampleText="string text = &quot;Hello, World!&quot;"/>
  <Color name="Comment" foreground="Green" exampleText="string text = &quot;Hello, World!&quot;"/>
   <Color name="Punctuation" foreground="Red" exampleText="string text = &quot;Hello, World!&quot;"/>
  <RuleSet  ignoreCase="true">
    <Span color="String" multiline="true" >
      <Begin>'</Begin>
      <End>'</End>

    </Span>

    <Span color="String2" multiline="true"  >
      <Begin>"</Begin>
      <End>"</End>
    </Span>
    <!-- span for escape sequences -->
    <Span  color="Comment" begin="--" end="\n"/>
    <Span color="Comment"  multiline="true">
      <Begin>/\*</Begin>
      <End>\*/</End>
    </Span>

    <Keywords fontWeight="bold" foreground="Blue" >
      <Word>ABORT</Word>
      <Word>BETWEEN</Word>
      <Word>CRASH</Word>
      <Word>DIGITS</Word>
      <Word>ACCEPT</Word>
      <Word>BINARY_INTEGER</Word>
      <Word>CREATE</Word>
      <Word>DISPOSE</Word>
      <Word>ACCESS</Word>
      <Word>BODY</Word>
      <Word>CURRENT</Word>
      <Word>DISTINCT</Word>
      <Word>ADD</Word>
      <Word>BOOLEAN</Word>
      <Word>CURRVAL</Word>
      <Word>DO</Word>
      <Word>ALL</Word>
      <Word>BY</Word>
      <Word>CURSOR</Word>
      <Word>DROP</Word>
      <Word>ALTER</Word>
      <Word>CASE</Word>
      <Word>DATABASE</Word>
      <Word>ELSE</Word>
      <Word>AND</Word>
      <Word>CHAR</Word>
      <Word>DATA_BASE</Word>
      <Word>ELSIF</Word>
      <Word>ANY</Word>
      <Word>CHAR_BASE</Word>
      <Word>DATE</Word>
      <Word>END</Word>
      <Word>ARRAY</Word>
      <Word>CHECK</Word>
      <Word>DBA</Word>
      <Word>ENTRY</Word>
      <Word>ARRAYLEN</Word>
      <Word>CLOSE</Word>
      <Word>DEBUGOFF</Word>
      <Word>EXCEPTION</Word>
      <Word>AS</Word>
      <Word>CLUSTER</Word>
      <Word>DEBUGON</Word>
      <Word>EXCEPTION_INIT</Word>
      <Word>ASC</Word>
      <Word>CLUSTERS</Word>
      <Word>DECLARE</Word>
      <Word>EXISTS</Word>
      <Word>ASSERT</Word>
      <Word>COLAUTH</Word>
      <Word>DECIMAL</Word>
      <Word>EXIT</Word>
      <Word>ASSIGN</Word>
      <Word>COLUMNS</Word>
      <Word>DEFAULT</Word>
      <Word>FALSE</Word>
      <Word>AT</Word>
      <Word>COMMIT</Word>
      <Word>DEFINITION</Word>
      <Word>FETCH</Word>
      <Word>AUTHORIZATION</Word>
      <Word>COMPRESS</Word>
      <Word>DELAY</Word>
      <Word>FLOAT</Word>
      <Word>AVG</Word>
      <Word>CONNECT</Word>
      <Word>DELETE</Word>
      <Word>FOR</Word>
      <Word>BASE_TABLE</Word>
      <Word>CONSTANT</Word>
      <Word>DELTA</Word>
      <Word>FORM</Word>
      <Word>BEGIN</Word>
      <Word>COUNT</Word>
      <Word>DESC</Word>
      <Word>FROM</Word>
      <Word>FUNCTION</Word>
      <Word>NEW</Word>
      <Word>RELEASE</Word>
      <Word>SUM</Word>
      <Word>GENERIC</Word>
      <Word>NEXTVAL</Word>
      <Word>REMR</Word>
      <Word>TABAUTH</Word>
      <Word>GOTO</Word>
      <Word>NOCOMPRESS</Word>
      <Word>RENAME</Word>
      <Word>TABLE</Word>
      <Word>GRANT</Word>
      <Word>NOT</Word>
      <Word>RESOURCE</Word>
      <Word>TABLES</Word>
      <Word>GROUP</Word>
      <Word>NULL</Word>
      <Word>RETURN</Word>
      <Word>TASK</Word>
      <Word>HAVING</Word>
      <Word>NUMBER</Word>
      <Word>REVERSE</Word>
      <Word>TERMINATE</Word>
      <Word>IDENTIFIED</Word>
      <Word>NUMBER_BASE</Word>
      <Word>REVOKE</Word>
      <Word>THEN</Word>
      <Word>IF</Word>
      <Word>OF</Word>
      <Word>ROLLBACK</Word>
      <Word>TO</Word>
      <Word>IN</Word>
      <Word>ON</Word>
      <Word>ROWID</Word>
      <Word>TRUE</Word>
      <Word>INDEX</Word>
      <Word>OPEN</Word>
      <Word>ROWLABEL</Word>
      <Word>TYPE</Word>
      <Word>INDEXES</Word>
      <Word>OPTION</Word>
      <Word>ROWNUM</Word>
      <Word>UNION</Word>
      <Word>INDICATOR</Word>
      <Word>OR</Word>
      <Word>ROWTYPE</Word>
      <Word>UNIQUE</Word>
      <Word>INSERT</Word>
      <Word>ORDER</Word>
      <Word>RUN</Word>
      <Word>UPDATE</Word>
      <Word>INTEGER</Word>
      <Word>OTHERS</Word>
      <Word>SAVEPOINT</Word>
      <Word>USE</Word>
      <Word>INTERSECT</Word>
      <Word>OUT</Word>
      <Word>SCHEMA</Word>
      <Word>VALUES</Word>
      <Word>INTO</Word>
      <Word>PACKAGE</Word>
      <Word>SELECT</Word>
      <Word>VARCHAR</Word>
      <Word>IS</Word>
      <Word>PARTITION</Word>
      <Word>SEPARATE</Word>
      <Word>VARCHAR2</Word>
      <Word>LEVEL</Word>
      <Word>PCTFREE</Word>
      <Word>SET</Word>
      <Word>VARIANCE</Word>
      <Word>LIKE</Word>
      <Word>POSITIVE</Word>
      <Word>SIZE</Word>
      <Word>VIEW</Word>
      <Word>LIMITED</Word>
      <Word>PRAGMA</Word>
      <Word>SMALLINT</Word>
      <Word>VIEWS</Word>
      <Word>LOOP</Word>
      <Word>PRIOR</Word>
      <Word>SPACE</Word>
      <Word>WHEN</Word>
      <Word>MAX</Word>
      <Word>PRIVATE</Word>
      <Word>SQL</Word>
      <Word>WHERE</Word>
      <Word>MIN</Word>
      <Word>PROCEDURE</Word>
      <Word>SQLCODE</Word>
      <Word>WHILE</Word>
      <Word>MINUS</Word>
      <Word>PUBLIC</Word>
      <Word>SQLERRM</Word>
      <Word>WITH</Word>
      <Word>MLSLABEL</Word>
      <Word>RAISE</Word>
      <Word>START</Word>
      <Word>WORK</Word>
      <Word>MOD</Word>
      <Word>RANGE</Word>
      <Word>STATEMENT</Word>
      <Word>XOR</Word>
      <Word>MODE</Word>
      <Word>REAL</Word>
      <Word>STDDEV</Word>
      <Word>NATURAL</Word>
      <Word>RECORD</Word>
      <Word>SUBTYPE</Word>
    </Keywords>
    <Rule color="Punctuation">
      [?,.;()\[\]{}+\-/%*&lt;&gt;^+~!|&amp;]+
    </Rule>

  </RuleSet>

</SyntaxDefinition>


问:
An app which has complete control of the device
I would like to create an app which is preinstalled on a device and has complete control of it (no way to exit it), this is for devices handed out for a specific purpose. It will have some pages/navigation as well as the ability to run certain whitelisted apps.

Is there anything out there helping with this, or would this kind of an app have to be a custom build of Android? Thanks.

答:
The way was in progress to implement this was with a custom compiled OS that signed a launcher with the key provided by the hardware vendor.

You can certainly fake most of this with your own launcher but to get it to be the system default launcher you need to have the vendor key I believe.


问:
compare two dictionary, one with list of float value per key, the other one a value per key (python)
I have a query sequence that I blasted online using NCBIWWW.qblast. In my xml blast file result I obtained for a query sequence a list of hit (i.e: gi|). Each hit or gi| have multiple hsp. I made a dictionary my_dict1 where I placed gi| as key and I appended the bit score as value. So multiple values for each key.

```<code>my_dict1 = {

gi|1002819492|: [437.702, 384.47, 380.86, 380.86, 362.83],

gi|675820360| : [2617.97, 2614.37, 122.112],

gi|953764029| : [414.258, 318.66, 122.112, 86.158],

gi|675820410| : [450.653, 388.08, 386.27] }
</code>```

Then I looked for max value in each key using:

```<code>for key, value in my_dict1.items():

    max_value = max(value)
</code>```

And made a second dictionary my_dict2:

```<code>my_dict2 = {

gi|1002819492|: 437.702,

gi|675820360| : 2617.97,

gi|953764029| : 414.258,

gi|675820410| : 450.653 }

I want to compare both dictionary. So I can extract the hsp with the highest score bits. I am also including other parameters like query coverage and identity percentage (Not shown here). The finality is to get the best gi| with the highest bit scores, coverage and identity percentage.

I tried many things to compare both dictionary like this :
</code>```

First code :

```<code>matches[]

if my_dict1.keys() not in my_dict2.keys():

    matches[hit_id] = bit_score

else:

    matches = matches[hit_id], bit_score
</code>```

Second code:

```<code>if hit_id not in matches.keys():

    matches[hit_id]= bit_score

else:

    matches = matches[hit_id], bit_score
</code>```

Third code:

```<code>intersection = set(set(my_dict1.items()) & set(my_dict2.items()))
</code>```

Howerver I always end up with 2 types of errors:

1 ) TypeError: list indices must be integers, not unicode

2 ) ... float not iterable...

Please I need some help and guidance. Thank you very much in advance for your time. Best regards.

答:
It's not clear what you're trying to do. What is hit_id? What is bit_score? It looks like your second dict is always going to have the same keys as your first if you're creating it by pulling the max value for each key of the first dict.

You say you're trying to compare them, but don't really state what you're actually trying to do. Find those with values under a certain max? Find those with the highest max?

Your first code doesn't work because I'm assuming you're trying to use a dict key value as an index to matches, which you define as a list. That's probably where your first error is coming from, though you haven't given the lines where the error is actually occurring.

See in-code comments below:

```<code># First off, this needs to be a dict.
matches{}

# This will never happen if you've created these dicts as you stated.
if my_dict1.keys() not in my_dict2.keys():

    matches[hit_id] = bit_score  # Not clear what bit_score is?

else:
    # Also not sure what you're trying to do here. This will assign a tuple
    # to matches with whatever the value of matches[hit_id] is and bit_score.
    matches = matches[hit_id], bit_score
</code>```

Regardless, we really need more information and the full code to figure out your actual goal and what's going wrong.

Body:
I have a query sequence that I blasted online using NCBIWWW.qblast. In my xml blast file result I obtained for a query sequence a list of hit (i.e: gi|). Each hit or gi| have multiple hsp. I made a dictionary my_dict1 where I placed gi| as key and I appended the bit score as value. So multiple values for each key.

my_dict1 = {

gi|1002819492|: [437.702, 384.47, 380.86, 380.86, 362.83],

gi|675820360| : [2617.97, 2614.37, 122.112],

gi|953764029| : [414.258, 318.66, 122.112, 86.158],

gi|675820410| : [450.653, 388.08, 386.27] }

Then I looked for max value in each key using:

for key, value in my_dict1.items():

    max_value = max(value)

And made a second dictionary my_dict2:

my_dict2 = {

gi|1002819492|: 437.702,

gi|675820360| : 2617.97,

gi|953764029| : 414.258,

gi|675820410| : 450.653 }

I want to compare both dictionary. So I can extract the hsp with the highest score bits. I am also including other parameters like query coverage and identity percentage (Not shown here). The finality is to get the best gi| with the highest bit scores, coverage and identity percentage.

I tried many things to compare both dictionary like this :

First code :

matches[]

if my_dict1.keys() not in my_dict2.keys():

    matches[hit_id] = bit_score

else:

    matches = matches[hit_id], bit_score

Second code:

if hit_id not in matches.keys():

    matches[hit_id]= bit_score

else:

    matches = matches[hit_id], bit_score

Third code:

intersection = set(set(my_dict1.items()) & set(my_dict2.items()))

Howerver I always end up with 2 types of errors:

1 ) TypeError: list indices must be integers, not unicode

2 ) ... float not iterable...

Please I need some help and guidance. Thank you very much in advance for your time. Best regards.

Body:
It's not clear what you're trying to do. What is hit_id? What is bit_score? It looks like your second dict is always going to have the same keys as your first if you're creating it by pulling the max value for each key of the first dict.

You say you're trying to compare them, but don't really state what you're actually trying to do. Find those with values under a certain max? Find those with the highest max?

Your first code doesn't work because I'm assuming you're trying to use a dict key value as an index to matches, which you define as a list. That's probably where your first error is coming from, though you haven't given the lines where the error is actually occurring.

See in-code comments below:

# First off, this needs to be a dict.
matches{}

# This will never happen if you've created these dicts as you stated.
if my_dict1.keys() not in my_dict2.keys():

    matches[hit_id] = bit_score  # Not clear what bit_score is?

else:
    # Also not sure what you're trying to do here. This will assign a tuple
    # to matches with whatever the value of matches[hit_id] is and bit_score.
    matches = matches[hit_id], bit_score

Regardless, we really need more information and the full code to figure out your actual goal and what's going wrong.


问:
Xamarin Button border issue
I'm trying to make an app using Xamarin.forms. The problem is that in Android version, button border are displayed, and I would like to remove them. I tried BorderColor="Transparent" but it didn't work.

Also, I've some problems with Text. In fact, I would like to have some padding between Icons and text (for example between F and Facebook). Is there a way to do that ? And how can I handle problems about the size of the text on, for example, iPhone 5 and "Fa...ook" ? I tried to put a smaller police but I guess there is a best solution ?

Here is my Xaml code:

```<code><Grid Margin="0,20,0,0">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="100"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <Label Text="Waka'Lokos" Margin="0,20,0,0" HorizontalOptions="Center" FontSize="22.5" TextColor="White" Grid.Row="0" Grid.Column="1"/>
    <Button BackgroundColor="Transparent" FontSize="10" ContentLayout="Top" HorizontalOptions="Center" VerticalOptions="Center" x:Name="fb" Text="Facebook" Grid.Row="1" Grid.Column="0" Image="fb.png" TextColor="#FEF4CA"/>
    <Button BackgroundColor="Transparent" FontSize="10" ContentLayout="Top" HorizontalOptions="Center" VerticalOptions="Center" x:Name="contact" Text="Contact" Grid.Row="1" Grid.Column="1" Image="call.png" TextColor="#FEF4CA"/>
    <Button BackgroundColor="Transparent" FontSize="10" ContentLayout="Top" HorizontalOptions="Center" VerticalOptions="Center" x:Name="insta" Text="Insta" Grid.Row="1" Grid.Column="2" Image="insta.png" TextColor="#FEF4CA"/>
    <Button BackgroundColor="Transparent" FontSize="10" ContentLayout="Top" HorizontalOptions="Center" VerticalOptions="Center" x:Name="chants" Text="Chants" Grid.Row="2" Grid.Column="0" Image="micro.png" TextColor="#FEF4CA"/>
    <Button BackgroundColor="Transparent" FontSize="10" ContentLayout="Top" HorizontalOptions="Center" VerticalOptions="Center" x:Name="communaute" Text="Team" Grid.Row="2" Grid.Column="1" Image="team.png" TextColor="#FEF4CA"/>
    <Button BackgroundColor="Transparent" FontSize="10" ContentLayout="Top" HorizontalOptions="Center" VerticalOptions="Center" x:Name="youtube" Text="Youtube" Grid.Row="2" Grid.Column="2" Image="yt.png" TextColor="#FEF4CA"/>
    <Button BackgroundColor="Transparent" FontSize="10" ContentLayout="Top" HorizontalOptions="Center" VerticalOptions="Center" x:Name="partenaires" Text="Partner" Grid.Row="3" Grid.Column="0" Image="partner.png" TextColor="#FEF4CA"/>
    <Button BackgroundColor="Transparent" FontSize="10" ContentLayout="Top" HorizontalOptions="Center" VerticalOptions="Center" x:Name="plans" Text="Bons Plans" Grid.Row="3" Grid.Column="1" Image="money.png" TextColor="#FEF4CA"/>
    <Button BackgroundColor="Transparent" FontSize="10" ContentLayout="Top" HorizontalOptions="Center" VerticalOptions="Center" x:Name="agenda" Text="Agenda" Grid.Row="3" Grid.Column="2" Image="agenda.png" TextColor="#FEF4CA"/>
</Grid>
</code>```

答:
For buttons that contain both text and images, I've always found it easiest to just use a stacklayout with an image and a label and then add a tap gesture to it. That way you have way more control over the positioning and scaling of the image as well as the text (and it takes care of your border problem). So something like:

XAML:

```<code><StackLayout x:Name="buttonStack" WidthRequest="50">
    <Image Source="fb.png" Aspect="AspectFit" HorizontalOptions="CenterAndExpand"/>
    <Label Text="Facebook" HorizontalOptions="CenterAndExpand" HorizontalTextAlignment="Center"/>
</StackLayout>
</code>```

XAML.CS

```<code>  ...
  TapGestureRecognizer tap = new TapGestureRecognizer();
  tap.Tapped += HandleClickEvent;

  buttonStack.GestureRecognizers.Add(tap);
}

private void HandleClickEvent(object sender, EventArgs e)
{
  //some code here
}
</code>```

if you want to fake a button tap animation you can try this instead. You can tweak the 250 milliseconds to something else to get the feel right:

```<code>private async void HandleClickEvent(object sender, EventArgs e)
{
  await buttonStack.FadeTo(0,250);
  buttonStack.FadeTo(1,250);
  //some code here
}
</code>```

Title: Xamarin Button border issue

Body:
I'm trying to make an app using Xamarin.forms. The problem is that in Android version, button border are displayed, and I would like to remove them. I tried BorderColor="Transparent" but it didn't work.

Also, I've some problems with Text. In fact, I would like to have some padding between Icons and text (for example between F and Facebook). Is there a way to do that ? And how can I handle problems about the size of the text on, for example, iPhone 5 and "Fa...ook" ? I tried to put a smaller police but I guess there is a best solution ?

Here is my Xaml code:

<Grid Margin="0,20,0,0">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="100"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <Button BackgroundColor="Transparent" FontSize="10" ContentLayout="Top" HorizontalOptions="Center" VerticalOptions="Center" x:Name="fb" Text="Facebook" Grid.Row="1" Grid.Column="0" Image="fb.png" TextColor="#FEF4CA"/>
    <Button BackgroundColor="Transparent" FontSize="10" ContentLayout="Top" HorizontalOptions="Center" VerticalOptions="Center" x:Name="contact" Text="Contact" Grid.Row="1" Grid.Column="1" Image="call.png" TextColor="#FEF4CA"/>
    <Button BackgroundColor="Transparent" FontSize="10" ContentLayout="Top" HorizontalOptions="Center" VerticalOptions="Center" x:Name="insta" Text="Insta" Grid.Row="1" Grid.Column="2" Image="insta.png" TextColor="#FEF4CA"/>
    <Button BackgroundColor="Transparent" FontSize="10" ContentLayout="Top" HorizontalOptions="Center" VerticalOptions="Center" x:Name="chants" Text="Chants" Grid.Row="2" Grid.Column="0" Image="micro.png" TextColor="#FEF4CA"/>
    <Button BackgroundColor="Transparent" FontSize="10" ContentLayout="Top" HorizontalOptions="Center" VerticalOptions="Center" x:Name="communaute" Text="Team" Grid.Row="2" Grid.Column="1" Image="team.png" TextColor="#FEF4CA"/>
    <Button BackgroundColor="Transparent" FontSize="10" ContentLayout="Top" HorizontalOptions="Center" VerticalOptions="Center" x:Name="youtube" Text="Youtube" Grid.Row="2" Grid.Column="2" Image="yt.png" TextColor="#FEF4CA"/>
    <Button BackgroundColor="Transparent" FontSize="10" ContentLayout="Top" HorizontalOptions="Center" VerticalOptions="Center" x:Name="partenaires" Text="Partner" Grid.Row="3" Grid.Column="0" Image="partner.png" TextColor="#FEF4CA"/>
    <Button BackgroundColor="Transparent" FontSize="10" ContentLayout="Top" HorizontalOptions="Center" VerticalOptions="Center" x:Name="plans" Text="Bons Plans" Grid.Row="3" Grid.Column="1" Image="money.png" TextColor="#FEF4CA"/>
    <Button BackgroundColor="Transparent" FontSize="10" ContentLayout="Top" HorizontalOptions="Center" VerticalOptions="Center" x:Name="agenda" Text="Agenda" Grid.Row="3" Grid.Column="2" Image="agenda.png" TextColor="#FEF4CA"/>
</Grid>

Body:
For buttons that contain both text and images, I've always found it easiest to just use a stacklayout with an image and a label and then add a tap gesture to it. That way you have way more control over the positioning and scaling of the image as well as the text (and it takes care of your border problem). So something like:

XAML:

<StackLayout x:Name="buttonStack" WidthRequest="50">
    <Image Source="fb.png" Aspect="AspectFit" HorizontalOptions="CenterAndExpand"/>
    <Label Text="Facebook" HorizontalOptions="CenterAndExpand" HorizontalTextAlignment="Center"/>
</StackLayout>

XAML.CS

  ...
  TapGestureRecognizer tap = new TapGestureRecognizer();
  tap.Tapped += HandleClickEvent;

  buttonStack.GestureRecognizers.Add(tap);
}

private void HandleClickEvent(object sender, EventArgs e)
{
  //some code here
}

if you want to fake a button tap animation you can try this instead. You can tweak the 250 milliseconds to something else to get the feel right:

private async void HandleClickEvent(object sender, EventArgs e)
{
  await buttonStack.FadeTo(0,250);
  buttonStack.FadeTo(1,250);
  //some code here
}


问:
c# Adding Directory.GetFiles to Zip File
I have lots of logs in a folder, I would like to only grab files that have todays date and put them in the zip file.

Here is my code:

```<code>static void Main(string[] args)
{
    //Specify todays date
    DateTime todaysDate = DateTime.Today;

    //Create a zip file with the name logs + todays date
    string zipPath = @"C:\Users\Desktop\ZIP\logs" + todaysDate.ToString("yyyyMMdd") + ".zip";
    string myPath = @"C:\Users\Desktop\LOG SEARCH";

    var files = System.IO.Directory.GetFiles(myPath, "*" + todaysDate.ToString("yyyyMMdd") + "*");

    foreach (var file in files)
    {
        Console.WriteLine(file);
    }
}
</code>```

How do I zip files ?

答:
So what you can do is create a temporary folder and then add each file that matches the current date in it. Once that's done you can ZipFile.CreateFromDirectory and then delete the temporary folder

```<code>DateTime todaysDate = DateTime.Today;

//Create a zip file with the name logs + todays date
string zipPath = @"C:\Users\Desktop\ZIP\logs" + todaysDate.ToString("yyyyMMdd") + ".zip";
string myPath = @"C:\Users\Desktop\LOG SEARCH";

string tempPath = @"C:\Users\Desktop\ZIP\logs" + todaysDate.ToString("yyyyMMdd");

var files = System.IO.Directory.GetFiles(myPath, "*" + todaysDate.ToString("yyyyMMdd") + "*");

Directory.CreateDirectory(tempPath);

foreach (var file in files)
{
    File.Copy(file, tempPath + @"\" + System.IO.Path.GetFileName(file));
}

ZipFile.CreateFromDirectory(tempPath, zipPath);

Directory.Delete(tempPath, true);
</code>```

Body:
I have lots of logs in a folder, I would like to only grab files that have todays date and put them in the zip file.

Here is my code:

static void Main(string[] args)
{
    //Specify todays date
    DateTime todaysDate = DateTime.Today;

    //Create a zip file with the name logs + todays date
    string zipPath = @"C:\Users\Desktop\ZIP\logs" + todaysDate.ToString("yyyyMMdd") + ".zip";
    string myPath = @"C:\Users\Desktop\LOG SEARCH";

    var files = System.IO.Directory.GetFiles(myPath, "*" + todaysDate.ToString("yyyyMMdd") + "*");

    foreach (var file in files)
    {
        Console.WriteLine(file);
    }
}

How do I zip files ?

Body:
So what you can do is create a temporary folder and then add each file that matches the current date in it. Once that's done you can ZipFile.CreateFromDirectory and then delete the temporary folder

DateTime todaysDate = DateTime.Today;

//Create a zip file with the name logs + todays date
string zipPath = @"C:\Users\Desktop\ZIP\logs" + todaysDate.ToString("yyyyMMdd") + ".zip";
string myPath = @"C:\Users\Desktop\LOG SEARCH";

string tempPath = @"C:\Users\Desktop\ZIP\logs" + todaysDate.ToString("yyyyMMdd");

var files = System.IO.Directory.GetFiles(myPath, "*" + todaysDate.ToString("yyyyMMdd") + "*");

Directory.CreateDirectory(tempPath);

foreach (var file in files)
{
    File.Copy(file, tempPath + @"\" + System.IO.Path.GetFileName(file));
}

ZipFile.CreateFromDirectory(tempPath, zipPath);

Directory.Delete(tempPath, true);


问:
Getting Nuget Package missing error
I am getting the following issue while compiling my project. It is a MVC 5 application. Here is the error:

Severity    Code    Description Project File    Line    Suppression State
Error       This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is ..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props.    WikidoctorAdmin E:\My Projects\Wiki-Doctor\Wiki-Doctor.com\Wiki-Doctor.com\WikidoctorAdmin\WikidoctorAdmin.csproj   2107

Please help me how to solve this error.

答:
I've got the same problem, and I solved this way:
- erase every obj and bin folders under the solution projects,
- using the NuGet Package manager to restore and update all packages.
Hope it helps.</p>

Title: Getting Nuget Package missing error


问:
Sync text and audio
How can i Sync text with the audio i have a given text and audio i just want a hint how can i sync them</p>

答:
you have to write a file with timecodes, then you can show the text at the given time.

Like SubRip

```<code>1
00:00:20,000 --> 00:00:24,400
Altocumulus clouds occur between six thousand

2
00:00:24,600 --> 00:00:27,800
and twenty thousand feet above ground level.
</code>```

cheers Simon

Title: Sync text and audio

Body:
you have to write a file with timecodes, then you can show the text at the given time.

Like SubRip

1
00:00:20,000 --> 00:00:24,400
Altocumulus clouds occur between six thousand

2
00:00:24,600 --> 00:00:27,800
and twenty thousand feet above ground level.

cheers Simon


问:
How do I do encryption/decryption without generating keypairs again?
I have been working on a project myself and using this website's codes as a guide. Is there any way, I can put the generation of keys into 1 file and encryption/decryption into another. How do I define bob_box without having to generate another pair of keys?

GEN.PY:

```<code>import libnacl.public

def genkeys():

    bob = libnacl.public.SecretKey()
    alice = libnacl.public.SecretKey()

    bob_box = libnacl.public.Box(bob.sk, alice.pk)
    alice_box = libnacl.public.Box(alice.sk, bob.pk)

genkeys()
</code>```

ENDEcrypt:

```<code>import libnacl.public
from GEN import genkeys

msg = '1234'

# Bob's box encrypts messages for Alice
bob_ctxt = bob_box.encrypt(msg)

# Alice's box decrypts messages from Bob
bclear = alice_box.decrypt(bob_ctxt)

# Alice can send encrypted messages which only Bob can decrypt
alice_ctxt = alice_box.encrypt(msg)
aclear = bob_box.decrypt(alice_ctxt)
</code>```

output when I run ENDEcrypt:

```<code>Traceback (most recent call last):
File "/home/pi/Desktop/BOBALICE/endecrypt.py", line 7, in <module>
bob_ctxt = bob_box.encrypt(msg)
NameError: name 'bob_box' is not defined
</code>```

答:
The API of libnacl is designed in such a way that two parties that want to communicate securely must somehow exchange their public keys. Let's say Alice wants to send a message to Bob.

```<code># Alice's computer:                             Bob's computer:
alice_sign = libnacl.public.SecretKey()         bob_enc = libnacl.public.SecretKey()
alice_spk_h = alice_sign.hex_pk()               bob_epk_h = bob_enc.hex_pk()

# magic happens where alice_spk_h goes to Bob and bob_epk_h goes to alice (i.e. by phone)

bob_epk = libnacl.public.PublicKey(bob_epk_h)   alice_spk = libnacl.public.PublicKey(
                                                        alice_spk_h)
alice_box = libnacl.public.Box(                 bob_box = libnacl.public.Box(
        alice_sign.sk, bob_epk)                         bob_enc.sk, alice_spk)

# preparation is done, let's start encrypting...

ct = alice_box.encrypt(msg)

# send ct to Bob (the message is protected)

                                                msg = bob_box.decrypt(ct)
</code>```

As you can see, you need to treat the public and secret keys separately to send them between machine of the communicating parties. You cannot combine them into one method, because that would contradict the usage scenario of libnacl's public-key encryption.

Keep in mind that with a single key pair per party, it is only permissible to send the encrypted messages in one direction. If you need to send messages back, then each party needs to have two keys (one for signing and one for encryption; note that I named Alice's and Bob's keys in a certain way to make that clear).

Is there a way to do the generation of keys in one file and the storing of keys into a box + encryption/decryption into another file?

Yes, but here you have to think about what these files are doing. A Python file is code. If you run the code that generates the SecretKey from a command line, you need to store it in some way, because running the code again would change the key.

gen.py

```<code>import libnacl.public

def genkey():
    return libnacl.public.SecretKey()

def gen_keys_and_save():
    # Generate two key pairs and store them for later use
    enc = genkey()
    enc.save('myencsecret.key')
    with open('myencpublic.key', 'w') as pkf:
        pkf.write(enc.hex_pk())

    sign = genkey()
    sign.save('mysignsecret.key')
    with open('mysignpublic.key', 'w') as pkf:
        pkf.write(sign.hex_pk())

if __name__ == "__main__":
    # this code only runs when executed directly (i.e. from command line)
    gen_keys_and_save()
</code>```

enc.py

```<code>import libnacl.public
import libnacl.utils

def encrypt(mysignsecret, theirencpublic, data):
    box = libnacl.public.Box(mysignsecret, theirencpublic)
    return box.encrypt(data)

def parse_and_encrypt(mysignsecretfile, theirencpublicfile, data):
    sk = libnacl.utils.load_key(mysignsecretfile)
    with open(theirencpublicfile, 'r') as pkf:
        pk = libnacl.public.PublicKey(pkf.read())
    return encrypt(sk, pk, data)

if __name__ == "__main__":
    parse_and_encrypt('mysignsecret.key', 'theirencpublic.key', 'some kind of msg')
</code>```

dec.py

```<code>import libnacl.public

def decrypt(myencsecret, theirsignpublic, ciphertext):
    box = libnacl.public.Box(myencsecret, theirsignpublic)
    return box.decrypt(ciphertext)

# similar to enc.py ...
</code>```

Now you can run it like this:

```
$ python gen.py
```

Now you need to receive theirencpublic.key and send mysignpublic.key. When you've done that, you can do that:

```
$ python enc.py
```

Body:
I have been working on a project myself and using this website's codes as a guide. Is there any way, I can put the generation of keys into 1 file and encryption/decryption into another. How do I define bob_box without having to generate another pair of keys?

GEN.PY:

import libnacl.public

def genkeys():

    bob = libnacl.public.SecretKey()
    alice = libnacl.public.SecretKey()

    bob_box = libnacl.public.Box(bob.sk, alice.pk)
    alice_box = libnacl.public.Box(alice.sk, bob.pk)

genkeys()

ENDEcrypt:

import libnacl.public
from GEN import genkeys

msg = '1234'

# Bob's box encrypts messages for Alice
bob_ctxt = bob_box.encrypt(msg)

# Alice's box decrypts messages from Bob
bclear = alice_box.decrypt(bob_ctxt)

# Alice can send encrypted messages which only Bob can decrypt
alice_ctxt = alice_box.encrypt(msg)
aclear = bob_box.decrypt(alice_ctxt)

output when I run ENDEcrypt:

Traceback (most recent call last):
File "/home/pi/Desktop/BOBALICE/endecrypt.py", line 7, in <module>
bob_ctxt = bob_box.encrypt(msg)
NameError: name 'bob_box' is not defined

Body:
The API of libnacl is designed in such a way that two parties that want to communicate securely must somehow exchange their public keys. Let's say Alice wants to send a message to Bob.

# Alice's computer:                             Bob's computer:
alice_sign = libnacl.public.SecretKey()         bob_enc = libnacl.public.SecretKey()
alice_spk_h = alice_sign.hex_pk()               bob_epk_h = bob_enc.hex_pk()

# magic happens where alice_spk_h goes to Bob and bob_epk_h goes to alice (i.e. by phone)

bob_epk = libnacl.public.PublicKey(bob_epk_h)   alice_spk = libnacl.public.PublicKey(
                                                        alice_spk_h)
alice_box = libnacl.public.Box(                 bob_box = libnacl.public.Box(
        alice_sign.sk, bob_epk)                         bob_enc.sk, alice_spk)

# preparation is done, let's start encrypting...

ct = alice_box.encrypt(msg)

# send ct to Bob (the message is protected)

                                                msg = bob_box.decrypt(ct)

As you can see, you need to treat the public and secret keys separately to send them between machine of the communicating parties. You cannot combine them into one method, because that would contradict the usage scenario of libnacl's public-key encryption.

Keep in mind that with a single key pair per party, it is only permissible to send the encrypted messages in one direction. If you need to send messages back, then each party needs to have two keys (one for signing and one for encryption; note that I named Alice's and Bob's keys in a certain way to make that clear).

Is there a way to do the generation of keys in one file and the storing of keys into a box + encryption/decryption into another file?

Yes, but here you have to think about what these files are doing. A Python file is code. If you run the code that generates the SecretKey from a command line, you need to store it in some way, because running the code again would change the key.

gen.py

import libnacl.public

def genkey():
    return libnacl.public.SecretKey()

def gen_keys_and_save():
    # Generate two key pairs and store them for later use
    enc = genkey()
    enc.save('myencsecret.key')
    with open('myencpublic.key', 'w') as pkf:
        pkf.write(enc.hex_pk())

    sign = genkey()
    sign.save('mysignsecret.key')
    with open('mysignpublic.key', 'w') as pkf:
        pkf.write(sign.hex_pk())

if __name__ == "__main__":
    # this code only runs when executed directly (i.e. from command line)
    gen_keys_and_save()

enc.py

import libnacl.public
import libnacl.utils

def encrypt(mysignsecret, theirencpublic, data):
    box = libnacl.public.Box(mysignsecret, theirencpublic)
    return box.encrypt(data)

def parse_and_encrypt(mysignsecretfile, theirencpublicfile, data):
    sk = libnacl.utils.load_key(mysignsecretfile)
    with open(theirencpublicfile, 'r') as pkf:
        pk = libnacl.public.PublicKey(pkf.read())
    return encrypt(sk, pk, data)

if __name__ == "__main__":
    parse_and_encrypt('mysignsecret.key', 'theirencpublic.key', 'some kind of msg')

dec.py

import libnacl.public

def decrypt(myencsecret, theirsignpublic, ciphertext):
    box = libnacl.public.Box(myencsecret, theirsignpublic)
    return box.decrypt(ciphertext)

# similar to enc.py ...

Now you can run it like this:

$ python gen.py

Now you need to receive theirencpublic.key and send mysignpublic.key. When you've done that, you can do that:

$ python enc.py


问:
Javascript change table contents on click
I have a table where information changes depending on what has been clicked by the button. currently it works when i use the toggle() command but having toggle() leaves selecting multiple buttons at once which results in displaying wrong data. I have tried .show() method and it does not work. Is there a way that i can enforce only one button to be toggled at once, or remove the toggle and just have one button be shown at a time.

```<code><button type="button" class="btn btn-primary" id="one" value="Toggle table">Example 1</button>
<button type="button" class="btn btn-primary" id="two">Example 2</button>
<button type="button" class="btn btn-primary" id="three">Example 3</button>
<button type="button" class="btn btn-primary" id="four">Example 4</button>
<button type="button" class="btn btn-primary" id="five">Example 5</button>
<button type="button" class="btn btn-primary" id="six">Example 6</button>
<button type="button" class="btn btn-primary" id="seven">Example 7</button>

<!--Table code -->
<div class="tab-content">
<table class="table table-condensed" id="table">
<!--Table code -->
</table>
</div>

<!-- Javascript -->
$(document).ready(function()
{
$("#one").click(function()

{
    var $day1 = $("#table tbody tr").filter(function () {
    return $.trim($(this).find("td").eq(0).text()) !== "0"
}).show();
});

 $("#two").on("click", function()
{
    var $rowsNo = $("#table tbody tr").filter(function () {
    return $.trim($(this).find("td").eq(0).text()) !== "1"
}).show();
});

$("#three").on("click", function()
{
    var $rowsNo = $("#table tbody tr").filter(function () {
    return $.trim($(this).find("td").eq(0).text()) !== "2"
}).show();
});

$("#four").on("click", function()
{
    var $rowsNo = $("#table tbody tr").filter(function () {
    return $.trim($(this).find("td").eq(0).text()) !== "3"
}).toggle();
});

$("#five").on("click", function()
{
    var $rowsNo = $("#table tbody tr").filter(function () {
    return $.trim($(this).find("td").eq(0).text()) !== "4"
}).toggle();
});
</code>```

As stated above toggle works, but multiple buttons can be toggled at once resulting in bad data shown in the table. Is there a way to limit one button to be toggled? If not the show() command is not working when clicked.

答:
Add hide() before filter() so your show() only displays what is wanted

```<code>$("#one").click(function() {
   $("#table tbody tr").hide().filter(function() {
    return $.trim($(this).find("td").eq(0).text()) !== "0"
  }).show();
});
</code>```

You could simplify this for all buttons also by adding a common class and a data attribute for the filter values.

```<code><button  class="btn btn-primary filter-btn" data-filter="1">Example 2</button>

$(".filter-btn").click(function() {
   var filterVal = $(this).attr('data-filter');
   $("#table tbody tr").hide().filter(function() {
    return $.trim($(this).find("td").eq(0).text()) !== filterVal ;
  }).show();
});
</code>```

Body:
I have a table where information changes depending on what has been clicked by the button. currently it works when i use the toggle() command but having toggle() leaves selecting multiple buttons at once which results in displaying wrong data. I have tried .show() method and it does not work. Is there a way that i can enforce only one button to be toggled at once, or remove the toggle and just have one button be shown at a time.

<button type="button" class="btn btn-primary" id="one" value="Toggle table">Example 1</button>
<button type="button" class="btn btn-primary" id="two">Example 2</button>
<button type="button" class="btn btn-primary" id="three">Example 3</button>
<button type="button" class="btn btn-primary" id="four">Example 4</button>
<button type="button" class="btn btn-primary" id="five">Example 5</button>
<button type="button" class="btn btn-primary" id="six">Example 6</button>
<button type="button" class="btn btn-primary" id="seven">Example 7</button>

$(document).ready(function()
{
$("#one").click(function()

{
    var $day1 = $("#table tbody tr").filter(function () {
    return $.trim($(this).find("td").eq(0).text()) !== "0"
}).show();
});

 $("#two").on("click", function()
{
    var $rowsNo = $("#table tbody tr").filter(function () {
    return $.trim($(this).find("td").eq(0).text()) !== "1"
}).show();
});

$("#three").on("click", function()
{
    var $rowsNo = $("#table tbody tr").filter(function () {
    return $.trim($(this).find("td").eq(0).text()) !== "2"
}).show();
});

$("#four").on("click", function()
{
    var $rowsNo = $("#table tbody tr").filter(function () {
    return $.trim($(this).find("td").eq(0).text()) !== "3"
}).toggle();
});

$("#five").on("click", function()
{
    var $rowsNo = $("#table tbody tr").filter(function () {
    return $.trim($(this).find("td").eq(0).text()) !== "4"
}).toggle();
});

As stated above toggle works, but multiple buttons can be toggled at once resulting in bad data shown in the table. Is there a way to limit one button to be toggled? If not the show() command is not working when clicked.

Body:
Add hide() before filter() so your show() only displays what is wanted

$("#one").click(function() {
   $("#table tbody tr").hide().filter(function() {
    return $.trim($(this).find("td").eq(0).text()) !== "0"
  }).show();
});

You could simplify this for all buttons also by adding a common class and a data attribute for the filter values.

<button  class="btn btn-primary filter-btn" data-filter="1">Example 2</button>

$(".filter-btn").click(function() {
   var filterVal = $(this).attr('data-filter');
   $("#table tbody tr").hide().filter(function() {
    return $.trim($(this).find("td").eq(0).text()) !== filterVal ;
  }).show();
});


问:
preg_match always returns true/1
Sorry if this is a stupid question but I'm new to regex. For some reason no matter what I set $id to it always returns true.

```<code>$id = "tt0944557";

if( preg_match( "/tt\\d{7}/", $id ) ) {
    echo "match";
} else {
    echo "no match";
}
</code>```

$id will always start with "tt" then 7 numbers

答:
Try this code:

```<code>$id = "tt0944557";

if( preg_match( "/(tt\d{7})/", $id ) ) {
    echo "match";
} else {
    echo "no match";
}
</code>```

What we need to focus on is obviously the pattern, (tt\d{7}).

The parenthesis mean group, as this is one selection, the whole thing is one group. The next part is the tt, these are literals. It finds the literal string "tt" in the input. The next part is \d{7}. The \d means any digit and the {7} means exactly # in this case, 7. So therefore it makes up the string as tt#######.

I built this pattern by using regex101

Title: preg_match always returns true/1

Body:
Sorry if this is a stupid question but I'm new to regex. For some reason no matter what I set $id to it always returns true.

$id = "tt0944557";

if( preg_match( "/tt\\d{7}/", $id ) ) {
    echo "match";
} else {
    echo "no match";
}

$id will always start with "tt" then 7 numbers

Body:
Try this code:

$id = "tt0944557";

if( preg_match( "/(tt\d{7})/", $id ) ) {
    echo "match";
} else {
    echo "no match";
}

What we need to focus on is obviously the pattern, (tt\d{7}).

The parenthesis mean group, as this is one selection, the whole thing is one group. The next part is the tt, these are literals. It finds the literal string "tt" in the input. The next part is \d{7}. The \d means any digit and the {7} means exactly # in this case, 7. So therefore it makes up the string as tt#######.

I built this pattern by using regex101


问:
Is it worth pooling byte[] and char[] arrays or is it better to just create
My code does a lot of Input/Output and this often involves the creation of temporary arrays to hold bytes or chars of some size - i often use 4096. Im starting to wonder - without actual tests - to verify if it would be better to pool these arrays. My code would change to something like this

```<code>take array from pool
try {
   read from one inputStream
   write to another outputstream using array
} finally {
   return array to pool
}
</code>```

it is quicker to take or simply create a byte with 4096 which means some work is required to alloc mem on the heap, clear the 4096 bytes etc.

a pool seems simpler after all its probably just checking a list taking from the list and returning the array.

UPDATE
I wrote a small program that did two things, created arrays and used an apache commons pool. Both looped a lot of times (100*100*100) and created/took, filled array, then released. I added a few goes in the beginning to warm up the jit and ignored the results of those. Each run ran the create and pool forms a dozen times, alternating between the two.

There was little difference between the pool and create forms. However if i added a clear array to the callback that is fired by apache commons pool when an instance is returned to a pool, the pool became that much slower thanthe created form.

答: I would not implement pooling until a performance problem was demonstrated.</p>

Body:
My code does a lot of Input/Output and this often involves the creation of temporary arrays to hold bytes or chars of some size - i often use 4096. Im starting to wonder - without actual tests - to verify if it would be better to pool these arrays. My code would change to something like this

take array from pool
try {
   read from one inputStream
   write to another outputstream using array
} finally {
   return array to pool
}

it is quicker to take or simply create a byte with 4096 which means some work is required to alloc mem on the heap, clear the 4096 bytes etc.

a pool seems simpler after all its probably just checking a list taking from the list and returning the array.

UPDATE
I wrote a small program that did two things, created arrays and used an apache commons pool. Both looped a lot of times (100*100*100) and created/took, filled array, then released. I added a few goes in the beginning to warm up the jit and ignored the results of those. Each run ran the create and pool forms a dozen times, alternating between the two.

There was little difference between the pool and create forms. However if i added a clear array to the callback that is fired by apache commons pool when an instance is returned to a pool, the pool became that much slower thanthe created form.


问:
Having drop down colored backgrounds persist once selected

<select>
    <option value="apple" style="background: red">Apple</option>
    <option value="banana" style="background: yellow">Banana</option>
    <option value="pear" style="background: green">Pear</option>
</select>```

So I have an HTML drop down with options that have background colors. However, once I select one of these options from the list, the background color goes away...

Is there a way to make it so once an option is selected, the background color persists?

答:
i have create a  JSFiddle

Following is the code:

.Red {
  background-color: #ff0000;
}

.Green {
  background-color: #00ff00;
}

.Blue {
  background-color: #0000ff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="select" class="Red" onchange="this.className = this.options[this.selectedIndex].className">
     <option class="Red" value="1">Red</option>
     <option class="Green" value="2">Green</option>
     <option class="Blue" value="3">Blue</option>
</select></code>```

Body:
<select>
    <option value="apple" style="background: red">Apple</option>
    <option value="banana" style="background: yellow">Banana</option>
    <option value="pear" style="background: green">Pear</option>
</select>

So I have an HTML drop down with options that have background colors. However, once I select one of these options from the list, the background color goes away...

Is there a way to make it so once an option is selected, the background color persists?

Body:
i have create a  JSFiddle

Following is the code:

.Red {
  background-color: #ff0000;
}

.Green {
  background-color: #00ff00;
}

.Blue {
  background-color: #0000ff;
}

<select name="select" class="Red" onchange="this.className = this.options[this.selectedIndex].className">
     <option class="Red" value="1">Red</option>
     <option class="Green" value="2">Green</option>
     <option class="Blue" value="3">Blue</option>
</select>


答:
```<code><select style="background:pink">
    <option value="apple" style="background: red">Apple</option>
    <option value="banana" style="background: yellow">Banana</option>
    <option value="pear" style="background: green">Pear</option>
</select>
</code>```

The selected item is a whole other object in the DOM, other style is applied to it.
You can use JavaScript or JQuery to get the color of the selected option and than apply it on the selected item.

Title: Having drop down colored backgrounds persist once selected

Body:
<select style="background:pink">
    <option value="apple" style="background: red">Apple</option>
    <option value="banana" style="background: yellow">Banana</option>
    <option value="pear" style="background: green">Pear</option>
</select>

The selected item is a whole other object in the DOM, other style is applied to it.
You can use JavaScript or JQuery to get the color of the selected option and than apply it on the selected item.


问:
Upload of APK to Google Play fails because of different package names
I have a problem uploading my APK to the Google Play store because of different package names.

What I've done is the following:

I uploaded the APK without any problems.

The app is not published yet; the state is announced with "design".

Now I renamed the Java packages.

I changed the "package" attribute in AndroidManifest.xml to the new name.

I changed the android:versionCode from 1 to 2.

Then I built the APK and tried to upload to Google Dev Console but it fails with the message that the package names are different.

Is there a way to solve this conflict? I know I could "reset" my Java project to the old name but I want to keep the new package name and publish this one to Google Play for all future versions.

答:
You should also change the application id in your app.gradle :
android {</p>

```<code>defaultConfig {
    applicationId "type the new app Id here "

}
</code>```

Body:
You should also change the application id in your app.gradle :
android {

defaultConfig {
    applicationId "type the new app Id here "

}


问:
Map function str to list of class instance variables
I have a class with several properties. I want just the values for each property to be on one line each.

I tried using map however it is pointing to the instance of each class (<task_Backlog_Puller.Case object at 0x7ff2018f0240>) in the list and I need to get the values of each of the class properties. I cannot import libraries from 3rd party.

```<code>class Case:
    def __init__(self, case_number, owner, title, status, priority, date_created):
        self.case_number = case_number
        self.owner = owner
        self.title = title
        self.status = status
        self.priority = priority
        self.date_created = date_created

def create_report_of_cases_older_than_30_days(total_number_of_all_cases, number_of_cases_older_than_30_days, cases_older_than_30_days):
    report = "Total number of cases in team backlog is " + str(total_number_of_all_cases) + '\n'
    report += "Total number of cases older than 30 days is " + str(number_of_cases_older_than_30_days) + '\n'
    report += '\n'
    report += '\n'.join(map(str, cases_older_than_30_days))
    logger.info("Report -> {}".format(report))
    return str(report)
</code>```

```<code>2017-07-06 18:27:00,422 [    INFO] task_Backlog_Puller.116 --- Report -> Total number of cases in team backlog is 17
Total number of cases older than 30 days is 9

<task_Backlog_Puller.Case object at 0x7ff2018f0240>
<task_Backlog_Puller.Case object at 0x7ff202540a20>
<task_Backlog_Puller.Case object at 0x7ff1fe3b45f8>
<task_Backlog_Puller.Case object at 0x7ff20043ee80>
<task_Backlog_Puller.Case object at 0x7ff20043ee10>
<task_Backlog_Puller.Case object at 0x7ff2018d16a0>
<task_Backlog_Puller.Case object at 0x7ff2018d1cf8>
<task_Backlog_Puller.Case object at 0x7ff2018d1a58>
<task_Backlog_Puller.Case object at 0x7ff2018d1e80>
</code>```

答:
In order to control how a python class is cast to string, you can define a __str__ function in the class definition.

```<code>class Case:
    def __init__(self, case_number, owner, title, status, priority, date_created):
        self.case_number = case_number
        self.owner = owner
        self.title = title
        self.status = status
        self.priority = priority
        self.date_created = date_created

    def __str__(self):
        return # create a string here based on the properties of self

str(case) # will call case.__str__()
</code>```

Body:
I have a class with several properties. I want just the values for each property to be on one line each.

I tried using map however it is pointing to the instance of each class (<task_Backlog_Puller.Case object at 0x7ff2018f0240>) in the list and I need to get the values of each of the class properties. I cannot import libraries from 3rd party.

class Case:
    def __init__(self, case_number, owner, title, status, priority, date_created):
        self.case_number = case_number
        self.owner = owner
        self.title = title
        self.status = status
        self.priority = priority
        self.date_created = date_created

def create_report_of_cases_older_than_30_days(total_number_of_all_cases, number_of_cases_older_than_30_days, cases_older_than_30_days):
    report = "Total number of cases in team backlog is " + str(total_number_of_all_cases) + '\n'
    report += "Total number of cases older than 30 days is " + str(number_of_cases_older_than_30_days) + '\n'
    report += '\n'
    report += '\n'.join(map(str, cases_older_than_30_days))
    logger.info("Report -> {}".format(report))
    return str(report)

2017-07-06 18:27:00,422 [    INFO] task_Backlog_Puller.116 --- Report -> Total number of cases in team backlog is 17
Total number of cases older than 30 days is 9

<task_Backlog_Puller.Case object at 0x7ff2018f0240>
<task_Backlog_Puller.Case object at 0x7ff202540a20>
<task_Backlog_Puller.Case object at 0x7ff1fe3b45f8>
<task_Backlog_Puller.Case object at 0x7ff20043ee80>
<task_Backlog_Puller.Case object at 0x7ff20043ee10>
<task_Backlog_Puller.Case object at 0x7ff2018d16a0>
<task_Backlog_Puller.Case object at 0x7ff2018d1cf8>
<task_Backlog_Puller.Case object at 0x7ff2018d1a58>
<task_Backlog_Puller.Case object at 0x7ff2018d1e80>

Body:
In order to control how a python class is cast to string, you can define a __str__ function in the class definition.

class Case:
    def __init__(self, case_number, owner, title, status, priority, date_created):
        self.case_number = case_number
        self.owner = owner
        self.title = title
        self.status = status
        self.priority = priority
        self.date_created = date_created

    def __str__(self):
        return # create a string here based on the properties of self

str(case) # will call case.__str__()


问:
Android library written in Kotlin, provide support for Java apps
I am writing an Android library in Kotlin. But when used in Android apps written in Java the support is very poor. For example default parameters in Kotlin are still required in Java. Another one is, non-null parameters does not accept null in Kotlin app (compile time error) but throws run time exception when null is passed in Java. I know about null checks but they make the code look dirty.

What is the proper way to support Android Java apps? Direction, suggestions, examples are welcome. Thanks.

答:
When a function has default arguments you can use the @JvmOverloads annotation to create separate methods for Java users. There are also more similar enhancements to Java support in Kotlin. Here is a list what you can do.

You can also use @Nullable and @NotNull annotations on local variables and fields to improve IDE support for nullable values (also more likely the compiler will fail at compile time rather than runtime).

IntelliJ Idea auto generates not null checks for you when you use the @NotNull annotation.


问:
Change excel form checkbox name
I am using Excel 2010. I would like to chagne the name of an excel form checkbox I've added. How can I do that, not in VBA?</p>

答:
To change the name of a selected object, use the Name Box above and to the left of cell A1.

If by chance you are trying to only change the capitalization of some characters, however, Excel doesn't accept this as a change, and it will revert to the original once you hit Enter.

For example - if it's called CheckBox5 and you want to change it to checkBox5, you have to rename it to something different first, then to checkBox5.

Title: Change excel form checkbox name


问:
Python 3.6 installing statsmodels failed with exit status 127
Trying to install statsmodels via pip install statsmodels. I am using Win10 and Python 3.6. I already installed NumPy, SciPy, Pandas and all the other dependencies. I have Visual Studio Community 2017 installed with C++ and Python related stuff.
I get this error:

```<code>    ...

    building 'statsmodels.tsa.kalmanf.kalman_loglike' extension
    creating build\temp.win-amd64-3.6
    creating build\temp.win-amd64-3.6\Release
    creating build\temp.win-amd64-3.6\Release\statsmodels
    creating build\temp.win-amd64-3.6\Release\statsmodels\tsa
    creating build\temp.win-amd64-3.6\Release\statsmodels\tsa\kalmanf
    cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Istatsmodels/src -I"c:\program files\python36\lib\site-packages\numpy\core\include" -I"c:\program files\python36\include" -I"c:\program files\python36\include" /Tcstatsmodels/tsa/kalmanf/kalman_loglike.c /Fobuild\temp.win-amd64-3.6\Release\statsmodels/tsa/kalmanf/kalman_loglike.obj

    error: Command "cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Istatsmodels/src -I"c:\program files\python36\lib\site-packages\numpy\core\include" -I"c:\program files\python36\include" -I"c:\program files\python36\include" /Tcstatsmodels/tsa/kalmanf/kalman_loglike.c /Fobuild\temp.win-amd64-3.6\Release\statsmodels/tsa/kalmanf/kalman_loglike.obj" failed with exit status 127

    ----------------------------------------
Command ""c:\program files\python36\python.exe" -u -c "import setuptools, tokenize;__file__='C:\\Users\\me\\AppData\\Local\\Temp\\pip-build-7jsmv60z\\statsmodels\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\me\AppData\Local\Temp\pip-kpya7eq2-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\me\AppData\Local\Temp\pip-build-7jsmv60z\statsmodels\
</code>```

What caught my attention was the "failed with exit status 127" part, but I couldn't find anything useful related to this.

Why is this happening? What can I do?

答:
I would recommend using either Anaconda or Miniconda for a very simple install. Anaconda brings all needed packages with it.

With Miniconda I would recommend to create an environment:

```<code>conda create -n py36 python=3.6
</code>```

activate it:

```<code>conda activate py36
</code>```

and install your packages:

```<code>(py36) conda install numpy scipy pandas statsmodel
</code>```

Body:
Trying to install statsmodels via pip install statsmodels. I am using Win10 and Python 3.6. I already installed NumPy, SciPy, Pandas and all the other dependencies. I have Visual Studio Community 2017 installed with C++ and Python related stuff.
I get this error:

    ...

    building 'statsmodels.tsa.kalmanf.kalman_loglike' extension
    creating build\temp.win-amd64-3.6
    creating build\temp.win-amd64-3.6\Release
    creating build\temp.win-amd64-3.6\Release\statsmodels
    creating build\temp.win-amd64-3.6\Release\statsmodels\tsa
    creating build\temp.win-amd64-3.6\Release\statsmodels\tsa\kalmanf
    cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Istatsmodels/src -I"c:\program files\python36\lib\site-packages\numpy\core\include" -I"c:\program files\python36\include" -I"c:\program files\python36\include" /Tcstatsmodels/tsa/kalmanf/kalman_loglike.c /Fobuild\temp.win-amd64-3.6\Release\statsmodels/tsa/kalmanf/kalman_loglike.obj

    error: Command "cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Istatsmodels/src -I"c:\program files\python36\lib\site-packages\numpy\core\include" -I"c:\program files\python36\include" -I"c:\program files\python36\include" /Tcstatsmodels/tsa/kalmanf/kalman_loglike.c /Fobuild\temp.win-amd64-3.6\Release\statsmodels/tsa/kalmanf/kalman_loglike.obj" failed with exit status 127

    ----------------------------------------
Command ""c:\program files\python36\python.exe" -u -c "import setuptools, tokenize;__file__='C:\\Users\\me\\AppData\\Local\\Temp\\pip-build-7jsmv60z\\statsmodels\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\me\AppData\Local\Temp\pip-kpya7eq2-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\me\AppData\Local\Temp\pip-build-7jsmv60z\statsmodels\

What caught my attention was the "failed with exit status 127" part, but I couldn't find anything useful related to this.

Why is this happening? What can I do?

Body:
I would recommend using either Anaconda or Miniconda for a very simple install. Anaconda brings all needed packages with it.

With Miniconda I would recommend to create an environment:

conda create -n py36 python=3.6

activate it:

conda activate py36

and install your packages:

(py36) conda install numpy scipy pandas statsmodel


问:
How to set the id to each new array in an array of objects?
I have array of objects like this

```<code>[
    {
        "name": "qwe",
        "password": "qwe"
    },
    {
        "name": "qwe1",
        "password": "qwe1"
    }
]
</code>```

I need add id each pair of "name" and "password", it must be like this

```<code>[
    {
        "name": "qwe",
        "password": "qwe"
        "id":"0"
    },
    {
        "name": "qwe1",
        "password": "qwe1"
        "id":"1"
    }
]
</code>```

I'm trying to move an array using foreach

```<code>$users[] = array('name' => $name, 'password' => $password);
    $i = 0;
    foreach ($users as $key => $value, "id" => 0) {
        $value['id'] = $i;
        $i++;
}
</code>```

I'm beginner in php, help please.What i do wrong?

答:
When you iterate through an array using: foreach($array as $key => $value), the $value will be a copy of the original object. Changing the copy will have no effect on the original array.

You need to make sure you update the original value. There are two ways you can do this.

Accessing the original array directly:

```<code>foreach ($users as $key => $value) {
    // Access the original array directly
    $users[$key]['id'] = $i;
    $i++;
}
</code>```

Using references (The &-sign):

```<code>foreach ($users as $key => &$value) {
    // The & will make it a reference to the original value instead of a copy
    $value['id'] = $i;
    $i++;
}
</code>```

Body:
I have array of objects like this

[
    {
        "name": "qwe",
        "password": "qwe"
    },
    {
        "name": "qwe1",
        "password": "qwe1"
    }
]

I need add id each pair of "name" and "password", it must be like this

[
    {
        "name": "qwe",
        "password": "qwe"
        "id":"0"
    },
    {
        "name": "qwe1",
        "password": "qwe1"
        "id":"1"
    }
]

I'm trying to move an array using foreach

$users[] = array('name' => $name, 'password' => $password);
    $i = 0;
    foreach ($users as $key => $value, "id" => 0) {
        $value['id'] = $i;
        $i++;
}

I'm beginner in php, help please.What i do wrong?

Body:
When you iterate through an array using: foreach($array as $key => $value), the $value will be a copy of the original object. Changing the copy will have no effect on the original array.

You need to make sure you update the original value. There are two ways you can do this.

Accessing the original array directly:

foreach ($users as $key => $value) {
    // Access the original array directly
    $users[$key]['id'] = $i;
    $i++;
}

Using references (The &-sign):

foreach ($users as $key => &$value) {
    // The & will make it a reference to the original value instead of a copy
    $value['id'] = $i;
    $i++;
}


问:
Upload python package without rebuild
I would like to build a python package, run tests against the build artifact and then upload the python package to a PyPI w/o re-building the package.

We are building a CI/CD pipeline and want to make sure that the exact package we built and tested is what gets published, not a re-built version after the fact.

Currently, if I run the following:

```<code>$ python setup.py egg_info -b .$BUILD_NUM sdist bdist_wheel
</code>```

Then run my tests and run:

```<code>$ python setup.py egg_info -b .$BUILD_NUM sdist bdist_wheel upload
</code>```

Then the timestamp on the files shows the file was re-built the second time.

Is there a way to submit the files without re-building them?

答:
By using sdist and bdist_wheel in your command you explicitly order setup.py to rebuild packages. If you want to upload without rebuilding just use python setup.py upload. Or even better, use twine; it's the recommended way to upload to PyPI.

```<code>twine upload dist/*
</code>```

twine looks into dist, gets the package name and version and uploads packages.

Title: Upload python package without rebuild

Body:
I would like to build a python package, run tests against the build artifact and then upload the python package to a PyPI w/o re-building the package.

We are building a CI/CD pipeline and want to make sure that the exact package we built and tested is what gets published, not a re-built version after the fact.

Currently, if I run the following:

$ python setup.py egg_info -b .$BUILD_NUM sdist bdist_wheel

Then run my tests and run:

$ python setup.py egg_info -b .$BUILD_NUM sdist bdist_wheel upload

Then the timestamp on the files shows the file was re-built the second time.

Is there a way to submit the files without re-building them?

Body:
By using sdist and bdist_wheel in your command you explicitly order setup.py to rebuild packages. If you want to upload without rebuilding just use python setup.py upload. Or even better, use twine; it's the recommended way to upload to PyPI.

twine upload dist/*

twine looks into dist, gets the package name and version and uploads packages.


答: Can you create a new APK with the updated names and then put the new APK in Google Play?</p>

Title: Upload of APK to Google Play fails because of different package names

Body:
I have a problem uploading my APK to the Google Play store because of different package names.

What I've done is the following:

I uploaded the APK without any problems.

The app is not published yet; the state is announced with "design".

Now I renamed the Java packages.

I changed the "package" attribute in AndroidManifest.xml to the new name.

I changed the android:versionCode from 1 to 2.

Then I built the APK and tried to upload to Google Dev Console but it fails with the message that the package names are different.

Is there a way to solve this conflict? I know I could "reset" my Java project to the old name but I want to keep the new package name and publish this one to Google Play for all future versions.


问:
Sorting HTML ul
So my question is it possible to sort list items by number in strong tag, when i try with JavaScript code below it sort numbers and but get them out of div tag.
(I use these js code for sorting by Name and it work fine when b = ...(LI))
HTML:

```<code><section>
<button class="sortbynum" onclick="sortListNum()">Sort By Num</button>
<ul id="sort">
    <li>
       <div><h2>Name</h2></div>
       <a href=""><img src=""/></a>
       <div><span>Something:...</span></div>
       <div><span>something:...</span></div>
       <div><span>HHJS: <strong class="sortNum">456</strong></span></div>
    </li>
    <li>again</li>
</ul>
</code>```

JavaScript:

```<code>function sortListNum() {var list, i, switching, b, shouldSwitch, dir,switchcount = 0;list = document.getElementById("sort");switching = true;dir = "asc"; while (switching) {switching = false;b = list.getElementsByClassName("sortNum");
for (i = 0; i < (b.length - 1); i++) {
  shouldSwitch = false;
  if (dir == "asc") {
    if (b[i].innerHTML.toLowerCase() > b[i + 1].innerHTML.toLowerCase()) {
      shouldSwitch= true;
      break;
    }
  } else if (dir == "desc") {
    if (b[i].innerHTML.toLowerCase() < b[i + 1].innerHTML.toLowerCase()) {
      shouldSwitch= true;
      break;
    }
  }
}
if (shouldSwitch) {
  b[i].parentNode.insertBefore(b[i + 1], b[i]);
  switching = true;
  switchcount ++;
} else {
  if (switchcount == 0 && dir == "asc") {
    dir = "desc";
    switching = true;
  }
}}}
</code>```

答:
I've managed to extrapolate from this that you're asking if you can extract text from inline elements.

You can select them like anything else, but it's a little more interesting that.

innerHTML returns HTML, which can be HTML or plain text or both.

innerText returns plain text.

textContent returns all of the contained plain text concatenated into one string, only separated by newline characters when the next element is on a new line.

Since you have more text than just the number within the element, just select the strong tag and call innerText:

```<code>document.querySelector('#sort .sortNum').innerText
</code>```

Title: Sorting HTML ul

Body:
So my question is it possible to sort list items by number in strong tag, when i try with JavaScript code below it sort numbers and but get them out of div tag.
(I use these js code for sorting by Name and it work fine when b = ...(LI))
HTML:

<button class="sortbynum" onclick="sortListNum()">Sort By Num</button>

Name

Something:...

something:...

HHJS: 456

again

JavaScript:

function sortListNum() {var list, i, switching, b, shouldSwitch, dir,switchcount = 0;list = document.getElementById("sort");switching = true;dir = "asc"; while (switching) {switching = false;b = list.getElementsByClassName("sortNum");
for (i = 0; i < (b.length - 1); i++) {
  shouldSwitch = false;
  if (dir == "asc") {
    if (b[i].innerHTML.toLowerCase() > b[i + 1].innerHTML.toLowerCase()) {
      shouldSwitch= true;
      break;
    }
  } else if (dir == "desc") {
    if (b[i].innerHTML.toLowerCase() < b[i + 1].innerHTML.toLowerCase()) {
      shouldSwitch= true;
      break;
    }
  }
}
if (shouldSwitch) {
  b[i].parentNode.insertBefore(b[i + 1], b[i]);
  switching = true;
  switchcount ++;
} else {
  if (switchcount == 0 && dir == "asc") {
    dir = "desc";
    switching = true;
  }
}}}

Body:
I've managed to extrapolate from this that you're asking if you can extract text from inline elements.

You can select them like anything else, but it's a little more interesting that.

innerHTML returns HTML, which can be HTML or plain text or both.

innerText returns plain text.

textContent returns all of the contained plain text concatenated into one string, only separated by newline characters when the next element is on a new line.

Since you have more text than just the number within the element, just select the strong tag and call innerText:

document.querySelector('#sort .sortNum').innerText


问:
Read spss file with Cyrillic into R
I am trying to read several SPSS files into R that include Cyrillic text. All of the files are in Cyrillic text. When I read most of them into R, the console says "re-encoding from CP1251". However, when I read some of the files, also in Cyrillic text, it says "re-encoding from CP1252" which I think is a Latin script. The CP1251 files read into R with no problem. However, the CP1252 files become gibberish in R.  I’ve tried the foreign, haven and hmisc packages for reading in the SPSS files and none have worked. I've also tried including reencode='utf-8'. When I do this, the Cyrillic text all becomes NA. The problem occurs whether I'm working in R or RStudio.

```<code>x1<- read.spss("cp1251_file.sav", to.data.frame = T) #1251 file reads in fine

x2<- read.spss("cp1252_file.sav", to.data.frame = T) #1252 file becomes gibberish

x2<- read.spss("cp1252_file.sav", to.data.frame = T, reencode='utf-8') #Cyrillic text in CP1252 file becomes NA
</code>```

Thanks for your help.

答:
Looks like it works if I use the memisc package and I tell R that the file is CP1251 even though it thinks it is CP1252 when using read.spss. Thanks!:

df <- spss.system.file("file.sav")
df <- Iconv(df,from="CP1251",to="UTF-8")
df1<-as.data.frame(as.data.set(df))

Title: Read spss file with Cyrillic into R

Body:
I am trying to read several SPSS files into R that include Cyrillic text. All of the files are in Cyrillic text. When I read most of them into R, the console says "re-encoding from CP1251". However, when I read some of the files, also in Cyrillic text, it says "re-encoding from CP1252" which I think is a Latin script. The CP1251 files read into R with no problem. However, the CP1252 files become gibberish in R.  I’ve tried the foreign, haven and hmisc packages for reading in the SPSS files and none have worked. I've also tried including reencode='utf-8'. When I do this, the Cyrillic text all becomes NA. The problem occurs whether I'm working in R or RStudio.

x1<- read.spss("cp1251_file.sav", to.data.frame = T) #1251 file reads in fine

x2<- read.spss("cp1252_file.sav", to.data.frame = T) #1252 file becomes gibberish

x2<- read.spss("cp1252_file.sav", to.data.frame = T, reencode='utf-8') #Cyrillic text in CP1252 file becomes NA

Thanks for your help.


问:
Tensorflow predictions all come out true
In my tensorflow application, all the predictions are coming out True. I'm trying to adapt the MNIST example to my problem, but I'm worried that it's wrong to use that technique since its for multiple classes, and I have binary classification.

```<code># In[1]:

import tensorflow as tf
import numpy

# In[2]:

X = tf.placeholder(tf.float32, [None, 3], "training-data")
W1 = tf.Variable(tf.truncated_normal([3, 2]), "W")
b1 = tf.Variable(tf.zeros([2]), "B") # number of neurons

W2 = tf.Variable(tf.truncated_normal([2, 1]), "W1")
b2 = tf.Variable(tf.zeros([1]), "B1") # number of neurons

# In[9]:

Y = tf.nn.sigmoid(tf.matmul(X, W1) + b1)
Y1 = tf.nn.softmax(tf.matmul(Y, W2) + b2)
Y_ = tf.placeholder(tf.float32, [None, 1], "labels") # labels

#cross_entropy = -tf.reduce_sum(Y_ * tf.log(Y1)) # error function
cross_entropy = tf.reduce_sum(tf.abs(Y1 - Y_))
is_correct = tf.equal(Y1, Y_)
# All the predictions are coming out True ?!?
accuracy = tf.reduce_sum(tf.cast(is_correct, tf.int32)) / tf.size(is_correct)

print("X", X)
print("Y", Y)
print("Y1", Y1)
print("Y_", Y_)
print("cross-entropy", cross_entropy)
print("is-correct", is_correct)
print("accuracy", accuracy)

# In[10]:

optimizer = tf.train.GradientDescentOptimizer(0.005)
train_step = optimizer.minimize(cross_entropy)

# In[11]:

def load(filename):
    filename_queue = tf.train.string_input_producer([filename])
    key, value = tf.TextLineReader(skip_header_lines=1).read(filename_queue)
    col1, col2, col3, col4, col5 = tf.decode_csv(records = value, record_defaults=[[1.0], [1.0], [1.0], [1.0], [1.0]])
    batch_size=100
    # A tensor for each column of the CSV
    load_time, is_east, is_west, is_europe, labels = tf.train.shuffle_batch([col1, col2, col3, col4, col5], batch_size=batch_size, capacity=batch_size*50, min_after_dequeue=batch_size)
    #features = tf.stack([load_time, is_east, is_west, is_europe], 1)
    features = tf.stack([is_east, is_west, is_europe], 1)
    return features, tf.reshape(labels, [-1, 1])

# In[12]:

features, labels = load("/Users/andrew.ehrlich/Desktop/labelled_clicks.csv")

# In[13]:

# Run!

test_features = numpy.loadtxt(open("/Users/andrew.ehrlich/Desktop/labelled_clicks_test.csv", "rb"), delimiter=",", skiprows=1, usecols = [1,2,3])
test_labels = numpy.loadtxt(open("/Users/andrew.ehrlich/Desktop/labelled_clicks_test.csv", "rb"), delimiter=",", skiprows=1, usecols = [4], ndmin = 2)

summ = tf.reduce_sum(test_labels)
size = tf.size(test_labels)

with tf.Session() as sess:
    file_writer = tf.summary.FileWriter('/Users/andrew.ehrlich/tf.log', sess.graph)
    init = tf.global_variables_initializer()

    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)

    sess.run(init)
    for i in range(1000):

        ran_features = sess.run(features)
        ran_labels = sess.run(labels)

        train_data = {X: ran_features, Y_: ran_labels}
        sess.run(train_step, feed_dict=train_data) # I guess this updates the tensors behind train_step (W and b)

        if (i % 100 == 0):
            train_acc, train_ent = sess.run([accuracy, cross_entropy], feed_dict=train_data)

            test_data = {X: test_features, Y_: test_labels}
            test_acc, test_ent = sess.run([accuracy, cross_entropy], feed_dict=test_data)

            size = sess.run(tf.size(ran_labels))
            print("batch size: %d [TRAIN - acc:%1.4f ent: %10.4f]    [TEST - acc:%1.4f ent: %10.4f]" % (size, train_acc, train_ent, test_acc, test_ent))

# In[ ]:
</code>```

Output:

```<code>batch size: 100 [TRAIN - acc:0.4100 ent:    59.0000]    [TEST - acc:0.4787 ent:  9423.0000]
batch size: 100 [TRAIN - acc:0.5300 ent:    47.0000]    [TEST - acc:0.4787 ent:  9423.0000]
batch size: 100 [TRAIN - acc:0.5900 ent:    41.0000]    [TEST - acc:0.4787 ent:  9423.0000]
batch size: 100 [TRAIN - acc:0.4700 ent:    53.0000]    [TEST - acc:0.4787 ent:  9423.0000]
batch size: 100 [TRAIN - acc:0.5200 ent:    48.0000]    [TEST - acc:0.4787 ent:  9423.0000]
batch size: 100 [TRAIN - acc:0.6000 ent:    40.0000]    [TEST - acc:0.4787 ent:  9423.0000]
batch size: 100 [TRAIN - acc:0.5500 ent:    45.0000]    [TEST - acc:0.4787 ent:  9423.0000]
batch size: 100 [TRAIN - acc:0.6100 ent:    39.0000]    [TEST - acc:0.4787 ent:  9423.0000]
batch size: 100 [TRAIN - acc:0.4100 ent:    59.0000]    [TEST - acc:0.4787 ent:  9423.0000]
batch size: 100 [TRAIN - acc:0.5300 ent:    47.0000]    [TEST - acc:0.4787 ent:  9423.0000]
</code>```

Accuracy doesn't change because the values of Y_ are always all True which results in a number that just shows the number of positive labels in the test set. Please let me know any feedback! I'm grateful!

答:
When your using softmax on your last layer and then calculating cross_entropy, combine together to a numerically stable tf.softmax_cross_entropy_with_logits. Once you see that the loss is decreasing, but your accuracy is not good, then you can add complexity to the network by adding more layers.

Make the following changes:

```<code>Y1 = (tf.matmul(Y, W2) + b2)
cross_entropy = tf.reduce_mean(tf.softmax_cross_entropy_with_logits(logits=Y1, labels=Y_))
</code>```

Body:
In my tensorflow application, all the predictions are coming out True. I'm trying to adapt the MNIST example to my problem, but I'm worried that it's wrong to use that technique since its for multiple classes, and I have binary classification.

# In[1]:

import tensorflow as tf
import numpy

# In[2]:

X = tf.placeholder(tf.float32, [None, 3], "training-data")
W1 = tf.Variable(tf.truncated_normal([3, 2]), "W")
b1 = tf.Variable(tf.zeros([2]), "B") # number of neurons

W2 = tf.Variable(tf.truncated_normal([2, 1]), "W1")
b2 = tf.Variable(tf.zeros([1]), "B1") # number of neurons

# In[9]:

Y = tf.nn.sigmoid(tf.matmul(X, W1) + b1)
Y1 = tf.nn.softmax(tf.matmul(Y, W2) + b2)
Y_ = tf.placeholder(tf.float32, [None, 1], "labels") # labels

#cross_entropy = -tf.reduce_sum(Y_ * tf.log(Y1)) # error function
cross_entropy = tf.reduce_sum(tf.abs(Y1 - Y_))
is_correct = tf.equal(Y1, Y_)
# All the predictions are coming out True ?!?
accuracy = tf.reduce_sum(tf.cast(is_correct, tf.int32)) / tf.size(is_correct)

print("X", X)
print("Y", Y)
print("Y1", Y1)
print("Y_", Y_)
print("cross-entropy", cross_entropy)
print("is-correct", is_correct)
print("accuracy", accuracy)

# In[10]:

optimizer = tf.train.GradientDescentOptimizer(0.005)
train_step = optimizer.minimize(cross_entropy)

# In[11]:

def load(filename):
    filename_queue = tf.train.string_input_producer([filename])
    key, value = tf.TextLineReader(skip_header_lines=1).read(filename_queue)
    col1, col2, col3, col4, col5 = tf.decode_csv(records = value, record_defaults=[[1.0], [1.0], [1.0], [1.0], [1.0]])
    batch_size=100
    # A tensor for each column of the CSV
    load_time, is_east, is_west, is_europe, labels = tf.train.shuffle_batch([col1, col2, col3, col4, col5], batch_size=batch_size, capacity=batch_size*50, min_after_dequeue=batch_size)
    #features = tf.stack([load_time, is_east, is_west, is_europe], 1)
    features = tf.stack([is_east, is_west, is_europe], 1)
    return features, tf.reshape(labels, [-1, 1])

# In[12]:

features, labels = load("/Users/andrew.ehrlich/Desktop/labelled_clicks.csv")

# In[13]:

# Run!

test_features = numpy.loadtxt(open("/Users/andrew.ehrlich/Desktop/labelled_clicks_test.csv", "rb"), delimiter=",", skiprows=1, usecols = [1,2,3])
test_labels = numpy.loadtxt(open("/Users/andrew.ehrlich/Desktop/labelled_clicks_test.csv", "rb"), delimiter=",", skiprows=1, usecols = [4], ndmin = 2)

summ = tf.reduce_sum(test_labels)
size = tf.size(test_labels)

with tf.Session() as sess:
    file_writer = tf.summary.FileWriter('/Users/andrew.ehrlich/tf.log', sess.graph)
    init = tf.global_variables_initializer()

    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)

    sess.run(init)
    for i in range(1000):

        ran_features = sess.run(features)
        ran_labels = sess.run(labels)

        train_data = {X: ran_features, Y_: ran_labels}
        sess.run(train_step, feed_dict=train_data) # I guess this updates the tensors behind train_step (W and b)

        if (i % 100 == 0):
            train_acc, train_ent = sess.run([accuracy, cross_entropy], feed_dict=train_data)

            test_data = {X: test_features, Y_: test_labels}
            test_acc, test_ent = sess.run([accuracy, cross_entropy], feed_dict=test_data)

            size = sess.run(tf.size(ran_labels))
            print("batch size: %d [TRAIN - acc:%1.4f ent: %10.4f]    [TEST - acc:%1.4f ent: %10.4f]" % (size, train_acc, train_ent, test_acc, test_ent))

# In[ ]:

Output:

batch size: 100 [TRAIN - acc:0.4100 ent:    59.0000]    [TEST - acc:0.4787 ent:  9423.0000]
batch size: 100 [TRAIN - acc:0.5300 ent:    47.0000]    [TEST - acc:0.4787 ent:  9423.0000]
batch size: 100 [TRAIN - acc:0.5900 ent:    41.0000]    [TEST - acc:0.4787 ent:  9423.0000]
batch size: 100 [TRAIN - acc:0.4700 ent:    53.0000]    [TEST - acc:0.4787 ent:  9423.0000]
batch size: 100 [TRAIN - acc:0.5200 ent:    48.0000]    [TEST - acc:0.4787 ent:  9423.0000]
batch size: 100 [TRAIN - acc:0.6000 ent:    40.0000]    [TEST - acc:0.4787 ent:  9423.0000]
batch size: 100 [TRAIN - acc:0.5500 ent:    45.0000]    [TEST - acc:0.4787 ent:  9423.0000]
batch size: 100 [TRAIN - acc:0.6100 ent:    39.0000]    [TEST - acc:0.4787 ent:  9423.0000]
batch size: 100 [TRAIN - acc:0.4100 ent:    59.0000]    [TEST - acc:0.4787 ent:  9423.0000]
batch size: 100 [TRAIN - acc:0.5300 ent:    47.0000]    [TEST - acc:0.4787 ent:  9423.0000]

Accuracy doesn't change because the values of Y_ are always all True which results in a number that just shows the number of positive labels in the test set. Please let me know any feedback! I'm grateful!

Body:
When your using softmax on your last layer and then calculating cross_entropy, combine together to a numerically stable tf.softmax_cross_entropy_with_logits. Once you see that the loss is decreasing, but your accuracy is not good, then you can add complexity to the network by adding more layers.

Make the following changes:

Y1 = (tf.matmul(Y, W2) + b2)
cross_entropy = tf.reduce_mean(tf.softmax_cross_entropy_with_logits(logits=Y1, labels=Y_))


问:
How would a compiler optimize temporary objects away?
I am reading about move semantics and this code is given:

```<code>#include <iostream>

using namespace std;

vector<int> doubleValues (const vector<int>& v)
{
    vector<int> new_values;
    new_values.reserve(v.size());
    for (auto itr = v.begin(), end_itr = v.end(); itr != end_itr; ++itr )
    {
        new_values.push_back( 2 * *itr );
    }
    return new_values;
}

int main()
{
    vector<int> v;
    for ( int i = 0; i < 100; i++ )
    {
        v.push_back( i );
    }
    v = doubleValues( v );
}
</code>```

So the author states that after the return of doubleValues, there could be up to two copies happening

one into a temporary object to be returned, and a second when the
  vector assignment operator runs on the line v = doubleValues( v );

He also states that the first copy may be optimized away.

Here is what I do not get:

What does he mean when saying "one into a temporary object to be returned"? Isn't it a temporary object that is returned by the function? If so, I do not see why anything should be copied to another temporary object.

He states that this temporary object could be optimized away. How would a temporary object be optimized away, like what is considered an optimization?

答:
You need to understand that if a function returns a value by value, then it is returned via a temporary. It means, a non-optimizing compiler will:

copy new_values into a temporary, at return

copy from this temporary to v at the last line if main()

The standard permits a compiler to elide any of these copies, if it can. For example, it can pass a hidden reference parameter to v in doubleValues, and doubleValues can use this hidden reference instead of new_values. This way, no copy will be performed.

Note: a c++11 compilant compiler will use move instead of copy

Body:
I am reading about move semantics and this code is given:

#include <iostream>

using namespace std;

vector<int> doubleValues (const vector<int>& v)
{
    vector<int> new_values;
    new_values.reserve(v.size());
    for (auto itr = v.begin(), end_itr = v.end(); itr != end_itr; ++itr )
    {
        new_values.push_back( 2 * *itr );
    }
    return new_values;
}

int main()
{
    vector<int> v;
    for ( int i = 0; i < 100; i++ )
    {
        v.push_back( i );
    }
    v = doubleValues( v );
}

So the author states that after the return of doubleValues, there could be up to two copies happening

one into a temporary object to be returned, and a second when the
  vector assignment operator runs on the line v = doubleValues( v );

He also states that the first copy may be optimized away.

Here is what I do not get:

What does he mean when saying "one into a temporary object to be returned"? Isn't it a temporary object that is returned by the function? If so, I do not see why anything should be copied to another temporary object.

He states that this temporary object could be optimized away. How would a temporary object be optimized away, like what is considered an optimization?