问:
Google Sign in button not working on server
I am getting a weird issue. Google sing in button is working fine on my local system (using url: localhost) but it is not working on the server.
It keep giving me error 400 Error: invalid_request

I have added my server url on google console and even verified my URL

I am using example code from here

See my demo here

答:
For use with requests from a web server. This is the path in your
  application that users are redirected to after they have authenticated
  with Google. The path will be appended with the authorization code for
  access. Must have a protocol. Cannot contain URL fragments or relative
  paths. Cannot be a public IP address.

Your redirect URI should probably look more like this.

```<code>http://ec2-54-175-82-188.compute-1.amazonaws.com/user/auth
</code>```

When your code runs it has built the following request (Put this in any web browser.)

https://accounts.google.com/o/oauth2/auth?redirect_uri=storagerelay%3A%2F%2Fhttp%2Fec2-54-175-82-188.compute-1.amazonaws.com%3Fid%3Dauth315255&response_type=permission%20id_token&scope=email%20profile%20openid&openid.realm=&client_id=651551554260-60j7jq0i2gjsfm1mm0rh74ie4m80md5i.apps.googleusercontent.com&ss_domain=http%3A%2F%2Fec2-54-175-82-188.compute-1.amazonaws.com&fetch_basic_profile=true&gsiwebsdk=2

If you look at the redirect URI.

```<code>storagerelay%3A%2F%2Fhttp%2Fec2-54-175-82-188.compute-1.amazonaws.com%3Fid%3Dauth315255
</code>```

Its not correct.   It should be the page on your website that is designed to handle the authentication.

Body:
For use with requests from a web server. This is the path in your
  application that users are redirected to after they have authenticated
  with Google. The path will be appended with the authorization code for
  access. Must have a protocol. Cannot contain URL fragments or relative
  paths. Cannot be a public IP address.

Your redirect URI should probably look more like this.

http://ec2-54-175-82-188.compute-1.amazonaws.com/user/auth

When your code runs it has built the following request (Put this in any web browser.)

https://accounts.google.com/o/oauth2/auth?redirect_uri=storagerelay%3A%2F%2Fhttp%2Fec2-54-175-82-188.compute-1.amazonaws.com%3Fid%3Dauth315255&response_type=permission%20id_token&scope=email%20profile%20openid&openid.realm=&client_id=651551554260-60j7jq0i2gjsfm1mm0rh74ie4m80md5i.apps.googleusercontent.com&ss_domain=http%3A%2F%2Fec2-54-175-82-188.compute-1.amazonaws.com&fetch_basic_profile=true&gsiwebsdk=2

If you look at the redirect URI.

storagerelay%3A%2F%2Fhttp%2Fec2-54-175-82-188.compute-1.amazonaws.com%3Fid%3Dauth315255

Its not correct.   It should be the page on your website that is designed to handle the authentication.


来源: stackexchange

问:
How to insert and update two form same data into single table but different rows using php
I have to insert and update two form data on single submit click to mysql table. Please help me how can I do this. Just provide me a hint.

Thank you...

答:
On Submit Button Click : You must call mysql_query() for every query.

For Example :

```<code>if($_POST['submit']){
    $sql1 = "INSERT INTO table1 ...";
    $sql2 = "INSERT INTO table1 ...";
    mysql_query($sql1, $con);
    mysql_query($sql2, $con);
}
</code>```

Important

mysql_query() is deprecated! Please use mysqli_query() http://php.net/manual/de/book.mysqli.php

You can also use mysqli_multi_query() http://php.net/manual/de/mysqli.multi-query.php

```<code>$query = "INSERT INTO table1 ...; INSERT INTO donatie ...;";
mysqli_multi_query($link, $query);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
On Submit Button Click : You must call mysql_query() for every query.

For Example :

if($_POST['submit']){
    $sql1 = "INSERT INTO table1 ...";
    $sql2 = "INSERT INTO table1 ...";
    mysql_query($sql1, $con);
    mysql_query($sql2, $con);
}

Important

mysql_query() is deprecated! Please use mysqli_query() http://php.net/manual/de/book.mysqli.php

You can also use mysqli_multi_query() http://php.net/manual/de/mysqli.multi-query.php

$query = "INSERT INTO table1 ...; INSERT INTO donatie ...;";
mysqli_multi_query($link, $query);


问:
SkSpritenode normal texture not restoring even with restore on?
Ok. I am having a very odd problem with SKTextures and animating through - I have created a sprite node like this and set the normal texture to the last image in the array of sktextures I will eventually animate through. The texture (not normal texture) is set to the first image in the array.

```<code>theSprite = SKSpriteNode()
        theSprite.texture = atlas[0]
        theSprite.normalTexture = atlas[atlas.count-1]
        theSprite.size = CGSize(width: 500, height: 1491)
        theSprite.position = CGPoint(x: basePos.x+1, y: basePos.y+2)
        superScene.addChild(theSprite)
</code>```

when clicked it runs this func and as I read here https://developer.apple.com/reference/spritekit/skaction/1417810-animate I have restore set to TRUE so it SHOULD end on the last frame of the array:

```<code> let anim = SKAction.animate(with: atlas, timePerFrame: animSpeed, resize: false, restore: true)
            theSprite.run(anim, completion: {() -> Void in

            })
</code>```

It should go back to normal texture (which is a blank image), but it doesn't. The only way it goes back to this is if I don't set the texture to begin with, which I need to do. How can I make it restore?

答:
Suggested Solutions

Try setting your sprite to the last texture in the atlas like this: theSprite.texture = atlas[atlas.count-1]. Then run your code again. You should see that it restores to back to atlas[atlas.count-1].

If your animation stops at a texture other than your last atlas texture, then you could try this. Set theSprite.texture = atlas[atlas.count-1] within your animation's completion block. You would also set restore to false in this case. This will animate your sprite then set the final texture to whatever you want, in this case it will be set to the last atlas texture.

Explanation

Restore will return your sprite back to the texture that it had before the animation began. So in your case with your current code, it should end the animation with the texture atlas[0]. It is not meant to end on the last frame of the array as you stated.

According to the Apple dev reference, if restore is true:

When the action completes, the sprite’s texture is restored to the
  texture it had before the action completed.
  https://developer.apple.com/reference/spritekit/skaction/1417810-animate

Body:
Ok. I am having a very odd problem with SKTextures and animating through - I have created a sprite node like this and set the normal texture to the last image in the array of sktextures I will eventually animate through. The texture (not normal texture) is set to the first image in the array.

theSprite = SKSpriteNode()
        theSprite.texture = atlas[0]
        theSprite.normalTexture = atlas[atlas.count-1]
        theSprite.size = CGSize(width: 500, height: 1491)
        theSprite.position = CGPoint(x: basePos.x+1, y: basePos.y+2)
        superScene.addChild(theSprite)

when clicked it runs this func and as I read here https://developer.apple.com/reference/spritekit/skaction/1417810-animate I have restore set to TRUE so it SHOULD end on the last frame of the array:

 let anim = SKAction.animate(with: atlas, timePerFrame: animSpeed, resize: false, restore: true)
            theSprite.run(anim, completion: {() -> Void in

            })

It should go back to normal texture (which is a blank image), but it doesn't. The only way it goes back to this is if I don't set the texture to begin with, which I need to do. How can I make it restore?


问:
Remove everything after multiple patterns regex
I'm trying to remove the end of strings with three different patterns

Example of strings (this is not a block, these are three independant strings) :

```<code>BP342
Rue Du Docteur Ichon BP 60 Site de BRESSUIRE
CESEL - Hôtel Dieu 34 Rue du Dr Maunoury - B.P. 30407
</code>```

I wrote this regex pattern to detect each case of BP I can get :

```<code>[B][P]|[[:space:]][B][P]|[-][[:space:]][B][.][P][.]
</code>```

But now I want to delete everything that follows one of each pattern. I tried to put at the end of each pattern .$ but when I do this, it doesn't recognize anymore the previous pattern. So how do I remove the end of the string after matching the pattern ?

Expected results :

```<code>(nothing)
Rue Du Docteur Ichon
CESEL - Hôtel Dieu 34 Rue du Dr Maunoury
</code>```

I'm making these examples with this site : https://regex101.com/r/QXYtyv/3

答:
You can match using this regex:

```<code>(?:\s*-)?\s*B\.?P\.?.*$
</code>```

And replace using an empty string.

This regex matches an optional hyphen followed by BP with optional DOT in front of both letters. Using .*$ it matches everything till end of line.

RegEx Demo

Body:
I'm trying to remove the end of strings with three different patterns

Example of strings (this is not a block, these are three independant strings) :

BP342
Rue Du Docteur Ichon BP 60 Site de BRESSUIRE
CESEL - Hôtel Dieu 34 Rue du Dr Maunoury - B.P. 30407

I wrote this regex pattern to detect each case of BP I can get :

[B][P]|[[:space:]][B][P]|[-][[:space:]][B][.][P][.]

But now I want to delete everything that follows one of each pattern. I tried to put at the end of each pattern .$ but when I do this, it doesn't recognize anymore the previous pattern. So how do I remove the end of the string after matching the pattern ?

Expected results :

(nothing)
Rue Du Docteur Ichon
CESEL - Hôtel Dieu 34 Rue du Dr Maunoury

I'm making these examples with this site : https://regex101.com/r/QXYtyv/3

Body:
You can match using this regex:

(?:\s*-)?\s*B\.?P\.?.*$

And replace using an empty string.

This regex matches an optional hyphen followed by BP with optional DOT in front of both letters. Using .*$ it matches everything till end of line.

RegEx Demo


问:
How do I implement a "phonetical"-like search
Currently I'm trying to enhance my search algorithm.

For better understanding, here's the current logic behind it:

we have objects with attached n keywords in db. in database this is solved via 2 tables (Object, Keyword) where the Keyword-table has a FK to Object. When i'm building my searchtrees I create a line-value (ad: remove umlauts, convert to lower-case, ...) of all keywords of an object. the same convertion-routine (NormalizeSearchPattern()) is done with the search-patterns. I'm supporting AND-search and keywords with minimum length of 2 characters only!

The search-algorithm is currently a variant of fast-reverse-search (this example is not optimized):

```<code>bool IsMatch(string source, string searchPattern)
{
    // example:
    // source: "hello world"
    // searchPattern: "hello you freaky funky world"
    // patterns[]: { "hello", "you", "freaky", "funky", "world" }

    searchPattern = NormalizeSearchPattern(searchPattern);
    var patterns = MagicMethodToSplitPatternIntoPatterns(searchPattern);
    foreach (var pattern in patterns)
    {
        var success = false;
        var patternLength = pattern.Length;
        var firstChar = pattern[0];
        var secondChar = pattern[1];

        var lengthDifference = input.Length - patternLength;
        while (lengthDifference >= 0)
        {
            if (source[lengthDifference--] != firstChar)
            {
                continue;
            }
            if (source[lengthDifference + 2] != secondChar)
            {
                continue;
            }

            var l = lengthDifference + 3;
            var m = 2;
            while (m < patternLength)
            {
                if (input[l] != pattern[m])
                {
                    break;
                }
                l++;
                m++;
            }

            if (m == patternLength)
            {
                success = true;
            }
        }
        if (!success)
        {
            return false;
        }
    }
    return true;
}
</code>```

Normalization is done with (this example is not optimized)

```<code>    string RemoveTooShortKeywords(string keywords)
    {
        while (Regex.IsMatch(keywords, TooShortKeywordPattern, RegexOptions.Compiled | RegexOptions.Singleline))
        {
            keywords = Regex.Replace(keywords, TooShortKeywordPattern, " ", RegexOptions.Compiled | RegexOptions.Singleline);
        }

        return keywords;
    }

    string RemoveNonAlphaDigits(string value)
    {
        value = value.ToLower();
        value = value.Replace("ä", "ae");
        value = value.Replace("ö", "oe");
        value = value.Replace("ü", "ue");
        value = value.Replace("ß", "ss");

        return Regex.Replace(value, "[^a-z 0-9]", " ", RegexOptions.Compiled | RegexOptions.Singleline);
    }

    string NormalizeSearchPattern(string searchPattern)
    {
        var resultNonAlphaDigits = RemoveNonAlphaDigits(searchPattern);
        var resultTrimmed = RemoveTooShortKeywords(resultNonAlphaDigits);
        return resultTrimmed;
    }
</code>```

So this is pretty straight forward, thus it's obvious, that I can only cope with variants of source and searchPattern which I've implemented in NormalizeSearchPattern() (as mentioned above: umlauts, case-differences, …).

But how should I enhance the algorithm (or NormalizeSearchPattern()) to be non-sensitive when it comes down to:

singular/plural

misstyping (eg. "hauserr" <-> "hauser")

...

Just to know more about the design:

This app is done in c#, it stores the searchtrees and objects in a static variable (to query the database only once at init), the performance has to be outstanding (currently 500.000 lineValues are queried within less than 300msec).

答:
You should investigate the Soundex algorithm.  It's an algorithm for converting words into a phonetic space, such that similar sounding words (and slightly misspelled) words map to the same (or similar) values.  There's a list of other phonetic algorithms on wikipedia:

Soundex, which was developed to
  encode surnames for use in censuses.
  Soundex codes are four-character
  strings composed of one letter
  followed by three numbers.

Daitch–Mokotoff Soundex, which is a refinement of Soundex designed to
  better match surnames of Slavic and
  Germanic origin. Daitch–Mokotoff
  Soundex codes are strings composed of
  six numeric digits.

Kölner Phonetik which is similar to Soundex, but more suitable for
  German words.

Metaphone and Double Metaphone, which is suitable for use with most
  English words, not just names.
  Metaphone algorithms are the basis for
  many popular spell checkers.

Miracode

New York State Identification and Intelligence System (NYSIIS),
  which maps similar phonemes to the
  same letter. The result is a string
  that can be pronounced by the reader
  without decoding.

Match Rating Approach developed by Western Airlines in 1977 - this
  algorithm has an encoding and range
  comparison technique.

Body:
Currently I'm trying to enhance my search algorithm.

For better understanding, here's the current logic behind it:

we have objects with attached n keywords in db. in database this is solved via 2 tables (Object, Keyword) where the Keyword-table has a FK to Object. When i'm building my searchtrees I create a line-value (ad: remove umlauts, convert to lower-case, ...) of all keywords of an object. the same convertion-routine (NormalizeSearchPattern()) is done with the search-patterns. I'm supporting AND-search and keywords with minimum length of 2 characters only!

The search-algorithm is currently a variant of fast-reverse-search (this example is not optimized):

bool IsMatch(string source, string searchPattern)
{
    // example:
    // source: "hello world"
    // searchPattern: "hello you freaky funky world"
    // patterns[]: { "hello", "you", "freaky", "funky", "world" }

    searchPattern = NormalizeSearchPattern(searchPattern);
    var patterns = MagicMethodToSplitPatternIntoPatterns(searchPattern);
    foreach (var pattern in patterns)
    {
        var success = false;
        var patternLength = pattern.Length;
        var firstChar = pattern[0];
        var secondChar = pattern[1];

        var lengthDifference = input.Length - patternLength;
        while (lengthDifference >= 0)
        {
            if (source[lengthDifference--] != firstChar)
            {
                continue;
            }
            if (source[lengthDifference + 2] != secondChar)
            {
                continue;
            }

            var l = lengthDifference + 3;
            var m = 2;
            while (m < patternLength)
            {
                if (input[l] != pattern[m])
                {
                    break;
                }
                l++;
                m++;
            }

            if (m == patternLength)
            {
                success = true;
            }
        }
        if (!success)
        {
            return false;
        }
    }
    return true;
}

Normalization is done with (this example is not optimized)

    string RemoveTooShortKeywords(string keywords)
    {
        while (Regex.IsMatch(keywords, TooShortKeywordPattern, RegexOptions.Compiled | RegexOptions.Singleline))
        {
            keywords = Regex.Replace(keywords, TooShortKeywordPattern, " ", RegexOptions.Compiled | RegexOptions.Singleline);
        }

        return keywords;
    }

    string RemoveNonAlphaDigits(string value)
    {
        value = value.ToLower();
        value = value.Replace("ä", "ae");
        value = value.Replace("ö", "oe");
        value = value.Replace("ü", "ue");
        value = value.Replace("ß", "ss");

        return Regex.Replace(value, "[^a-z 0-9]", " ", RegexOptions.Compiled | RegexOptions.Singleline);
    }

    string NormalizeSearchPattern(string searchPattern)
    {
        var resultNonAlphaDigits = RemoveNonAlphaDigits(searchPattern);
        var resultTrimmed = RemoveTooShortKeywords(resultNonAlphaDigits);
        return resultTrimmed;
    }

So this is pretty straight forward, thus it's obvious, that I can only cope with variants of source and searchPattern which I've implemented in NormalizeSearchPattern() (as mentioned above: umlauts, case-differences, …).

But how should I enhance the algorithm (or NormalizeSearchPattern()) to be non-sensitive when it comes down to:

singular/plural

misstyping (eg. "hauserr" <-> "hauser")

...

Just to know more about the design:

This app is done in c#, it stores the searchtrees and objects in a static variable (to query the database only once at init), the performance has to be outstanding (currently 500.000 lineValues are queried within less than 300msec).

ContentLicense: CC BY-SA 2.5


问:
How does stripe createToken verify that the card is not invalid?
The error test cards only work when processing charge.

In a scenario where a bad card is successfully tokenized and the vendor-client transaction is processed (e.g. goods being sent), and then later the vendor needs to charge using the saved token but the charge fails, how can she protect herself against this?

答:
When you create a new card on a customer, Stripe automatically runs a $0/$1 authorization with the bank to make sure the card is valid and accepted. If the bank rejects the authorization, they will simply fail the card creation and return an error.

This allows you to catch expired or rejected cards upfront but it doesn't guarantee that future charges will succeed though even if the card is valid. The only way to confirm this is to charge the card and see what the bank responds.

In your situation, you'll want to charge the customer for the price of the goods before shipping anything. Once the charge succeeds, you're sure that you will get the funds.


问:
Prolog why the following term doesn't unify?
In prolog = is used for unification, as far as I understand if the two terms can be matched maybe with the help if variable instantiation, they are unified.

So why the following query fails

```<code>?- 2+2 = 4.
</code>```

Although 2+2 yields into 4 which is the same number as the other term.

答:
When you write

2 + 2 = 4

the answer is no, because prolog will compare a number (4) to a formula (2+2), which are not the same.  To make it right, you need prolog to evaluate the formula 2 + 2 before comparing it to 4. For that, use the is operator:

The is operator is meant specifically for mathematical functions. The left argument has to be a variable and the right argument has to be a mathematical function with all variables instantiated.

The = operator is used for unification of variables and can be used with any two arguments (although it will fail if the two arguments aren't the same and can't be made the same by instantiating variables a certain way) [source].

So in your example:

```<code>4 is 2+2
</code>```

Will evaluate to yes.

Body:
In prolog = is used for unification, as far as I understand if the two terms can be matched maybe with the help if variable instantiation, they are unified.

So why the following query fails

?- 2+2 = 4.

Although 2+2 yields into 4 which is the same number as the other term.

Body:
When you write

2 + 2 = 4

the answer is no, because prolog will compare a number (4) to a formula (2+2), which are not the same.  To make it right, you need prolog to evaluate the formula 2 + 2 before comparing it to 4. For that, use the is operator:

The is operator is meant specifically for mathematical functions. The left argument has to be a variable and the right argument has to be a mathematical function with all variables instantiated.

The = operator is used for unification of variables and can be used with any two arguments (although it will fail if the two arguments aren't the same and can't be made the same by instantiating variables a certain way) [source].

So in your example:

4 is 2+2

Will evaluate to yes.


问:
How to debug Unit Tests with Karma/Jasmine in Visual Studio Code?
I'd like to be able to debug unit tests in Visual Studio Code, but so far it has been a mixed bag.

My setup:

launch.json

```<code>{
   "version": "0.2.0",
   "configurations": [
           {
              "name": "Debug tests",
              "type": "chrome",
              "request": "attach",
              "port": 9222,
              "sourceMaps": true,
              "webRoot": "${workspaceRoot}"
           }
   ]
}
</code>```

karma.config.js

```<code>customLaunchers: {
   Chrome_with_debugging: {
     base: 'Chrome',
     flags: ['--remote-debugging-port=9222']
   }
}
</code>```

This does seem to work in a way, if I launch the VS Code debugger it appears to attach (bottom bar turns orange). If I make a change, Karma kicks in and the debugger, too - but it invariably pauses in zone.js (this is an Angular project by the way) without me interfering in any way:

If I hit 'Continue' it actually hits my breakpoint

and I can inspect some variables but not all of them,

For example, I can't see the value of actual passed into Jasmine's expect method.

So a) Why does the debugger always pause inside zone.js - the tested code is from a Redux reducer and is invoked outside of any Angular context, and b) What am I missing in regards to not being able to inspect local variables (which is a showstopper right now)?

答:
In karma.conf.js I updated added debug option in your version.

```<code>customLaunchers: {
   Chrome_with_debugging: {
     base: 'Chrome',
     flags: ['--remote-debugging-port=9222'],
     debug: true
}}
</code>```

launch.json
Add below snippet as launch configuration,

```<code>{
    "name": "Debug tests",
    "type": "chrome",
    "request": "attach",
    "port": 9222,
    "sourceMaps": true,
    "webRoot": "${workspaceRoot}"
}
</code>```

Then triggered the tests using below command,

ng test --browsers Chrome_with_debugging

Use Visual Studio Code debug option "Debug tests" to get attached to UT. With this I am able to debug unit tests using breakpoints in "Visual Studio Code + Debugger for Chrome extension".

Body:
I'd like to be able to debug unit tests in Visual Studio Code, but so far it has been a mixed bag.

My setup:

launch.json

{
   "version": "0.2.0",
   "configurations": [
           {
              "name": "Debug tests",
              "type": "chrome",
              "request": "attach",
              "port": 9222,
              "sourceMaps": true,
              "webRoot": "${workspaceRoot}"
           }
   ]
}

karma.config.js

customLaunchers: {
   Chrome_with_debugging: {
     base: 'Chrome',
     flags: ['--remote-debugging-port=9222']
   }
}

This does seem to work in a way, if I launch the VS Code debugger it appears to attach (bottom bar turns orange). If I make a change, Karma kicks in and the debugger, too - but it invariably pauses in zone.js (this is an Angular project by the way) without me interfering in any way:

If I hit 'Continue' it actually hits my breakpoint

and I can inspect some variables but not all of them,

For example, I can't see the value of actual passed into Jasmine's expect method.

So a) Why does the debugger always pause inside zone.js - the tested code is from a Redux reducer and is invoked outside of any Angular context, and b) What am I missing in regards to not being able to inspect local variables (which is a showstopper right now)?

Body:
In karma.conf.js I updated added debug option in your version.

customLaunchers: {
   Chrome_with_debugging: {
     base: 'Chrome',
     flags: ['--remote-debugging-port=9222'],
     debug: true
}}

launch.json
Add below snippet as launch configuration,

{
    "name": "Debug tests",
    "type": "chrome",
    "request": "attach",
    "port": 9222,
    "sourceMaps": true,
    "webRoot": "${workspaceRoot}"
}

Then triggered the tests using below command,

ng test --browsers Chrome_with_debugging

Use Visual Studio Code debug option "Debug tests" to get attached to UT. With this I am able to debug unit tests using breakpoints in "Visual Studio Code + Debugger for Chrome extension".

ContentLicense: CC BY-SA 4.0


问:
how to use wget to download directory with latest timestamp
i have an internal Linux http server where directories with a specific naming convention will be uploaded on a daily basis from a remote site.

```<code>url: http://10.10.10.10/test

Contents

test123
test124
test125
test126
</code>```

All directories will be having date and timestamp as well. Is there any way i can download the latest directory starting with test using wget or curl to my local machine? in this example it is test126

Kindly help

答:
wget doesn't do that automatically, you can do it in two steps:

download http://10.10.10.10/test, parse it, get the last entry

feed the result to wget -r

In these cases though the best solution is to set a symlink on the server that points always to the last directory, in your case:

http://10.10.10.10/test/latest -> http://10.10.10.10/test/test126

Body:
i have an internal Linux http server where directories with a specific naming convention will be uploaded on a daily basis from a remote site.

url: http://10.10.10.10/test

Contents

test123
test124
test125
test126

All directories will be having date and timestamp as well. Is there any way i can download the latest directory starting with test using wget or curl to my local machine? in this example it is test126

Kindly help


问:
AWS Lambda not returning list of alarms
I have a small node.js lambda in AWS (see code below). When it runs, it reports "success", but does not print a list of CloudWatch alarms as I would expect it to.

The AWS Javascript SDK leads me to believe what I'm doing should work. We do have a number of alarms setup, so I'm a bit at a loss for why the lambda is not listing the names of all of the alarms.

Any ideas why this isn't working?

//generated from TypeScript

"use strict";
Object.defineProperty(exports, "__esModule", {
  value: true
});
var AWS = require("aws-sdk");

function handler(event, context) {
  var cw = new AWS.CloudWatch();
  var params = {};
  cw.describeAlarms(params, function(err, data) {
    if (err) {
      console.log('Error: ', err);
    }
    data.MetricAlarms.forEach(function(alarm) {
      console.log('Alarm: ', alarm.AlarmName);
    });
  });
  context.succeed("Success");
}
exports.handler = handler;```

答:
There are at least two potential issues to check.  I was able to use your code and describe alarms after verifying both of the following were correct:

context.succeed is Incorrectly Scoped

Your context.succeed method is incorrectly scoped -- since it occurs right after describeAlarms outside the scope of its response, it is being processed right after you make the request without waiting for it to complete.

Move it into your callback scope, like this:

```<code>  cw.describeAlarms(params, function(err, data) {
    if (err) {
      console.log('Error: ', err);
    }
    data.MetricAlarms.forEach(function(alarm) {
      console.log('Alarm: ', alarm.AlarmName);
    });

    context.succeed("Success");
  });
</code>```

Lambda Execution Role

Your lambda's execution role will need permission to talk to the CloudWatch API. Execution roles are IAM roles that define what AWS services your lambda can interact with.

A good place to start would be to attach a managed CloudWatch Read Only Access policy, and then whittle down your required permissions down from there:

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "autoscaling:Describe*",
        "cloudwatch:Describe*",
        "cloudwatch:Get*",
        "cloudwatch:List*",
        "logs:Get*",
        "logs:Describe*",
        "logs:TestMetricFilter",
        "sns:Get*",
        "sns:List*"
      ],
      "Effect": "Allow",
      "Resource": "*"
    }
  ]
}
</code>```

Further Reading

AWS Compute Blog - Everything Depends on Context or, The Fine Art of nodejs Coding in AWS Lambda

AWS Documentation - AWS Lambda Permissions Model

AWS Documentation - AWS Managed (Predefined) Policies for CloudWatch

Title: AWS Lambda not returning list of alarms

Body:
There are at least two potential issues to check.  I was able to use your code and describe alarms after verifying both of the following were correct:

context.succeed is Incorrectly Scoped

Your context.succeed method is incorrectly scoped -- since it occurs right after describeAlarms outside the scope of its response, it is being processed right after you make the request without waiting for it to complete.

Move it into your callback scope, like this:

  cw.describeAlarms(params, function(err, data) {
    if (err) {
      console.log('Error: ', err);
    }
    data.MetricAlarms.forEach(function(alarm) {
      console.log('Alarm: ', alarm.AlarmName);
    });

    context.succeed("Success");
  });

Lambda Execution Role

Your lambda's execution role will need permission to talk to the CloudWatch API. Execution roles are IAM roles that define what AWS services your lambda can interact with.

A good place to start would be to attach a managed CloudWatch Read Only Access policy, and then whittle down your required permissions down from there:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "autoscaling:Describe*",
        "cloudwatch:Describe*",
        "cloudwatch:Get*",
        "cloudwatch:List*",
        "logs:Get*",
        "logs:Describe*",
        "logs:TestMetricFilter",
        "sns:Get*",
        "sns:List*"
      ],
      "Effect": "Allow",
      "Resource": "*"
    }
  ]
}

Further Reading

AWS Compute Blog - Everything Depends on Context or, The Fine Art of nodejs Coding in AWS Lambda

AWS Documentation - AWS Lambda Permissions Model

AWS Documentation - AWS Managed (Predefined) Policies for CloudWatch


问:
Android Firebase Messaging: How Update UI from onMessageReceived()
I have successfully implemented Firebase messaging in my app. Works great in the background and onMessageReceived() gets called when the app is in the foreground (yippee!).

The issue I have is that I need to update the UI dynamically and I am stuck on the best way to achieve this. I don't want to send the user an in-app notification (as the sample code shows), I'm not sure I want to send a broadcast, all I want to do is to access the MainActivity in order to call a method already there, however I have no reference to the MainActivity in the service.

```<code>@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    if (remoteMessage.getNotification().getBody() != null) {
        Log.d(LOG_TAG, "Message received: " + remoteMessage.getNotification().getBody());
    } else {
        Log.d(LOG_TAG, "Message received: " + remoteMessage.getData().get("message"));
    }

    // Call method in MainActivity
    // <<< What goes Here?>>>>

}
</code>```

This seems a simple use case but I can't find anything online to help.

Thanks in advance

答:
Yes, you can update UI and pass value to your activity by using Local Broadcast

In your onMessageReceived() Firebase Service.

```<code>broadcaster = LocalBroadcastManager.getInstance(getBaseContext());

   Intent intent = new Intent(REQUEST_ACCEPT);
   intent.putExtra("Key", value);
   intent.putExtra("key", value);
   broadcaster.sendBroadcast(intent);
</code>```

and register local Broadcast in your Activity or fragment method

```<code> @Override
    public void onStart() {
        super.onStart();
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver((receiver),
                new IntentFilter(PushNotificationService.REQUEST_ACCEPT)
        );
    }

    @Override
        public void onStop() {
             super.onStop();
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);

        }
</code>```

and Handle Your update event like this, do your update UI work Here, it will call automatically when notification received and onMessageReceived() send a broadcast.

```<code>receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try {
                    String   value= intent.getStringExtra("key");
                    String value= intent.getStringExtra("key");

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        };
</code>```

Body:
I have successfully implemented Firebase messaging in my app. Works great in the background and onMessageReceived() gets called when the app is in the foreground (yippee!).

The issue I have is that I need to update the UI dynamically and I am stuck on the best way to achieve this. I don't want to send the user an in-app notification (as the sample code shows), I'm not sure I want to send a broadcast, all I want to do is to access the MainActivity in order to call a method already there, however I have no reference to the MainActivity in the service.

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    if (remoteMessage.getNotification().getBody() != null) {
        Log.d(LOG_TAG, "Message received: " + remoteMessage.getNotification().getBody());
    } else {
        Log.d(LOG_TAG, "Message received: " + remoteMessage.getData().get("message"));
    }

    // Call method in MainActivity
    // <<< What goes Here?>>>>

}

This seems a simple use case but I can't find anything online to help.

Thanks in advance

Body:
Yes, you can update UI and pass value to your activity by using Local Broadcast

In your onMessageReceived() Firebase Service.

broadcaster = LocalBroadcastManager.getInstance(getBaseContext());

   Intent intent = new Intent(REQUEST_ACCEPT);
   intent.putExtra("Key", value);
   intent.putExtra("key", value);
   broadcaster.sendBroadcast(intent);

and register local Broadcast in your Activity or fragment method

 @Override
    public void onStart() {
        super.onStart();
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver((receiver),
                new IntentFilter(PushNotificationService.REQUEST_ACCEPT)
        );
    }

    @Override
        public void onStop() {
             super.onStop();
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);

        }

and Handle Your update event like this, do your update UI work Here, it will call automatically when notification received and onMessageReceived() send a broadcast.

receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try {
                    String   value= intent.getStringExtra("key");
                    String value= intent.getStringExtra("key");

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        };


问:
Why was function overloading added to C++?
I have a C background. I was just wondering why was function overloading added to C++? C doesn't have function overloading but C++ does, what was the need for it?

What went across the mind of the language designer at that time?

答:
It increases maintainability. If you have a type T and you call a function with it, then you need to change T, if the function has been overloaded for the new T then you can recompile instantly. In C you would have to go back and dig through all the call sites and change the function called. Take sqrt(). If you want to sqrt() a float, then you have to change to sqrtf().

Not just that, but the volume and complexity of C++'s type system is far more than in C, and having to have separate function names for every possible overload would quickly exhaust the reasonable pool of names for functions that serve the same purpose but take different arguments, because now there's a lot more arguments to take.

For example, compare the C and C++ string libraries. The C string library offers one method to append to a string - strcat(). C++'s std::string::append has eight overloads. What do you want to call them? append_a, append_b, etc? That's ridiculous- they all serve the same function, just in different ways.

Edit: It is actually worth mentioning that append is a really bad example, many of the C++ string overloads are very redundant. However, this is more general case than that and not all of those overloads redundant.


问:
Expection in thread "main" java.lang.UnsatisfiedLinkError: JNItest2.helloworld()V
I made libcc.so from my test.cpp in ubuntu, and used the instruction ldd to check it linking no problem with opencv2.4.2, ffmpeg0.11.1, and others.

But when I tried to use eclipse to load libcc.so, I get the error:

```<code>Exception in thread "main" java.lang.UnsatisfiedLinkError: JNItest2.helloworld()V
at JNItest2.helloworld(Native Method)
at JNItest2.main(JNItest2.java:28)
</code>```

Java code:

```<code>public class JNItest2 {
  public native void helloworld();
  static{
      String libPath= "/home/sun/workspace/JNItest2/src";
      System.setProperty("java.library.path",libPath);
      String Path = System.getProperty("java.library.path");
      System.out.println("java.library.path=" + Path);
      System.loadLibrary("cc");
  }
  public static void main(String[] args){
     new JNItest2().helloworld();
  }
}
</code>```

.h code:

```<code>/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class JNItest2 */

#ifndef _Included_JNItest2
#define _Included_JNItest2
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     JNItest2
 * Method:    helloworld
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_JNItest2_helloworld
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif
</code>```

test.cpp

```<code>#include <jni.h>
#include "JNItest2.h"
#include <stdio.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <ctype.h>
#include <unistd.h>
#include <signal.h>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <fstream>
#include <iostream>
#include <vector>
#include <list>
#include <string>
IplImage* image = 0;
IplImage* prev_image = 0;
CvCapture* capture = 0;
JNIEXPORT void JNICALL
Java_JNItest2_helloworld(JNIEnv *env,jobject object,int argc,char ** argv)
{
    signal(SIGSEGV,sighandler);
    int frameNum = 0;
    char* video=null;
    char* video = argv[1];
    capture = cvCreateFileCapture(video);
    if( !capture ) {
        printf( "Could not initialize capturing..\n" );
        return ;
    }
    while(true)
    {
        frameNum += 1;
        IplImage* frame = 0;
        int i, j, c;

        frame = cvQueryFrame( capture );
        if( !frame )
            break;

        if( !image ) {
            image =  cvCreateImage( cvSize(frame->width,frame->height), 8, 3);
            image->origin = frame->origin;
        }

        cvCopy( frame, image, 0 );
        std::cerr << "The " << frameNum << "-th frame" << std::endl;
        frameNum++;
    }

    return;
}
</code>```

I am searching for a long time on net. But I can't solve my problem. Please help or try to give me some ideas.

答:
The signature in your .h file doesn't match the one in your .cpp file.

```<code>JNIEXPORT void JNICALL Java_JNItest2_helloworld(JNIEnv *, jobject);

JNIEXPORT void JNICALL Java_JNItest2_helloworld(JNIEnv *env,jobject object,int argc,char ** argv)
</code>```

The method you're trying to call is the one from your header file. But it's missing an implementation.

If you want to pass arguments to the C side, you will have to declare them with your native methhod:

```<code>public native void helloworld(String[] args);
</code>```

The resulting signature would be:

```<code>JNIEXPORT void JNICALL Java_Main_helloworld(JNIEnv *, jobject, jobjectArray);
</code>```

But this String[] is not converted into argc and argv, you will have to use the JNI api to do that manually:

```<code>#include <stdio.h>
#include <stdlib.h>

JNIEXPORT void JNICALL Java_Main_helloworld(JNIEnv *env, jobject o, jobjectArray args) {
    int argc = (*env)->GetArrayLength(env, args);
    const char* argv[argc];

    // convert String[] to const char**
    for(int i = 0; i < argc; i++) {
        jstring string = (jstring) (*env)->GetObjectArrayElement(env, args, i);
        int slength = (*env)->GetStringLength(env, string);
        const wchar_t* wchars = (*env)->GetStringChars(env, string, NULL);

        argv[i] = malloc(slength + 1); // + 1 for terminator
        wcstombs(argv[i], wchars, slength + 1);

        (*env)->ReleaseStringChars(env, string, wchars);
    }

    // use argc and argv
}
</code>```

Body:
I made libcc.so from my test.cpp in ubuntu, and used the instruction ldd to check it linking no problem with opencv2.4.2, ffmpeg0.11.1, and others.

But when I tried to use eclipse to load libcc.so, I get the error:

Exception in thread "main" java.lang.UnsatisfiedLinkError: JNItest2.helloworld()V
at JNItest2.helloworld(Native Method)
at JNItest2.main(JNItest2.java:28)

Java code:

public class JNItest2 {
  public native void helloworld();
  static{
      String libPath= "/home/sun/workspace/JNItest2/src";
      System.setProperty("java.library.path",libPath);
      String Path = System.getProperty("java.library.path");
      System.out.println("java.library.path=" + Path);
      System.loadLibrary("cc");
  }
  public static void main(String[] args){
     new JNItest2().helloworld();
  }
}

.h code:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class JNItest2 */

#ifndef _Included_JNItest2
#define _Included_JNItest2
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     JNItest2
 * Method:    helloworld
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_JNItest2_helloworld
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

test.cpp

#include <jni.h>
#include "JNItest2.h"
#include <stdio.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <ctype.h>
#include <unistd.h>
#include <signal.h>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <fstream>
#include <iostream>
#include <vector>
#include <list>
#include <string>
IplImage* image = 0;
IplImage* prev_image = 0;
CvCapture* capture = 0;
JNIEXPORT void JNICALL
Java_JNItest2_helloworld(JNIEnv *env,jobject object,int argc,char ** argv)
{
    signal(SIGSEGV,sighandler);
    int frameNum = 0;
    char* video=null;
    char* video = argv[1];
    capture = cvCreateFileCapture(video);
    if( !capture ) {
        printf( "Could not initialize capturing..\n" );
        return ;
    }
    while(true)
    {
        frameNum += 1;
        IplImage* frame = 0;
        int i, j, c;

        frame = cvQueryFrame( capture );
        if( !frame )
            break;

        if( !image ) {
            image =  cvCreateImage( cvSize(frame->width,frame->height), 8, 3);
            image->origin = frame->origin;
        }

        cvCopy( frame, image, 0 );
        std::cerr << "The " << frameNum << "-th frame" << std::endl;
        frameNum++;
    }

    return;
}

I am searching for a long time on net. But I can't solve my problem. Please help or try to give me some ideas.

Body:
The signature in your .h file doesn't match the one in your .cpp file.

JNIEXPORT void JNICALL Java_JNItest2_helloworld(JNIEnv *, jobject);

JNIEXPORT void JNICALL Java_JNItest2_helloworld(JNIEnv *env,jobject object,int argc,char ** argv)

The method you're trying to call is the one from your header file. But it's missing an implementation.

If you want to pass arguments to the C side, you will have to declare them with your native methhod:

public native void helloworld(String[] args);

The resulting signature would be:

JNIEXPORT void JNICALL Java_Main_helloworld(JNIEnv *, jobject, jobjectArray);

But this String[] is not converted into argc and argv, you will have to use the JNI api to do that manually:

#include <stdio.h>
#include <stdlib.h>

JNIEXPORT void JNICALL Java_Main_helloworld(JNIEnv *env, jobject o, jobjectArray args) {
    int argc = (*env)->GetArrayLength(env, args);
    const char* argv[argc];

    // convert String[] to const char**
    for(int i = 0; i < argc; i++) {
        jstring string = (jstring) (*env)->GetObjectArrayElement(env, args, i);
        int slength = (*env)->GetStringLength(env, string);
        const wchar_t* wchars = (*env)->GetStringChars(env, string, NULL);

        argv[i] = malloc(slength + 1); // + 1 for terminator
        wcstombs(argv[i], wchars, slength + 1);

        (*env)->ReleaseStringChars(env, string, wchars);
    }

    // use argc and argv
}


问:
return from hook function hangs
I have hooked my own fopen function which calls fopen through dlsym .The process hangs after the execution of the function .Have been searching on internet and couldn't get more information on this . Have put prints in the code and there's hang during the function return .

```<code>FILE *mfopen(const char *pathname, const char *mode){

FILE * (*dfopen)(const char *, const char *);

  void *handle;
  FILE *fp;
  char *error;

  printf("dlopen function \n");

  handle = dlopen ("/lib32/libc.so.6", RTLD_NOW);

  if(!handle){

    printf("Unable to open -->fopen library \n");
    printf("fopen error = %s \n",dlerror());
    return NULL;

  }

   printf("dlsym call  \n");
  //dfopen = dlsym(RTLD_NEXT,"fopen");
  dfopen = dlsym(handle,"fopen");

 if((error = dlerror()) != NULL){

     printf("fopen failure \n");
     return NULL;
  }

  dlclose(handle);

  printf("fopen call  \n");
  fp = (*dfopen)(pathname,mode);

  printf("return call  \n");
  return fp;
}
</code>```

output

```<code>dlsym call
fopen call
return call
***
</code>```

答:
In your code you are calling dlclose immediately after dlsym and then are trying to call the function at the address returned by dlsym. This is incorrect and leads to the problem.

When you do a dlclose, there is a high possibility that the OS will remove the shared library from memory and the address returned from dlsym may no longer be active unless there are other dlopen's active for the library which is causing the OS to keep the library in memory.

Nevertheless, better follow the practice of calling dlclose only after all the work on the address retured from dlsym is complete and you have nothing further to do with the library.

Title: return from hook function hangs

Body:
I have hooked my own fopen function which calls fopen through dlsym .The process hangs after the execution of the function .Have been searching on internet and couldn't get more information on this . Have put prints in the code and there's hang during the function return .

FILE *mfopen(const char *pathname, const char *mode){

FILE * (*dfopen)(const char *, const char *);

  void *handle;
  FILE *fp;
  char *error;

  printf("dlopen function \n");

  handle = dlopen ("/lib32/libc.so.6", RTLD_NOW);

  if(!handle){

    printf("Unable to open -->fopen library \n");
    printf("fopen error = %s \n",dlerror());
    return NULL;

  }

   printf("dlsym call  \n");
  //dfopen = dlsym(RTLD_NEXT,"fopen");
  dfopen = dlsym(handle,"fopen");

 if((error = dlerror()) != NULL){

     printf("fopen failure \n");
     return NULL;
  }

  dlclose(handle);

  printf("fopen call  \n");
  fp = (*dfopen)(pathname,mode);

  printf("return call  \n");
  return fp;
}

output

dlsym call
fopen call
return call
***


问:
Excel Sheet VBA code works on one but not the others
I've been working on a piece of VBA code that has caused me quite some pain. I'm trying to get this:

```<code>Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim numCell As Range

If Target.Count <> 1 Then Exit Sub

If Target.Value = "+" Then
    Set numCell = Target.Offset(0, -1)
    numCell.Select
    numCell.Value = numCell.Value + 1
ElseIf Target.Value = "-" Then
    Set numCell = Target.Offset(0, 1)
    numCell.Select
    numCell.Value = numCell.Value - 1
End If
    End Sub
</code>```

to work on multiple different Excel sheets. For now, on one sheet (the original) it works perfectly. But then I copy-paste the layout of the first sheet to the next, and now the + and - don't work anymore on the new sheet.

Even by making the "Sub" private, it still doesn't change anything.

It is a simple add and subtract code that on each sheet should work in the same way.

Thanks for any advice you could give!

答:
It should work if you copy this code to another sheet module.
Open a blank workbook and add this code on more than one sheet's module to see if that works in the new workbook.

Though if you want to implement this code for all the sheets in the workbook, instead placing this code on specific sheet module, place it on ThisWorkbook Module.

The code will be as below...

```<code>Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
Dim numCell As Range

If Target.Count <> 1 Then Exit Sub

If Target.Value = "+" Then
    Set numCell = Target.Offset(0, -1)
    numCell.Select
    numCell.Value = numCell.Value + 1
ElseIf Target.Value = "-" Then
    Set numCell = Target.Offset(0, 1)
    numCell.Select
    numCell.Value = numCell.Value - 1
End If

End Sub
</code>```

Body:
I've been working on a piece of VBA code that has caused me quite some pain. I'm trying to get this:

Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim numCell As Range

If Target.Count <> 1 Then Exit Sub

If Target.Value = "+" Then
    Set numCell = Target.Offset(0, -1)
    numCell.Select
    numCell.Value = numCell.Value + 1
ElseIf Target.Value = "-" Then
    Set numCell = Target.Offset(0, 1)
    numCell.Select
    numCell.Value = numCell.Value - 1
End If
    End Sub

to work on multiple different Excel sheets. For now, on one sheet (the original) it works perfectly. But then I copy-paste the layout of the first sheet to the next, and now the + and - don't work anymore on the new sheet.

Even by making the "Sub" private, it still doesn't change anything.

It is a simple add and subtract code that on each sheet should work in the same way.

Thanks for any advice you could give!

Body:
It should work if you copy this code to another sheet module.
Open a blank workbook and add this code on more than one sheet's module to see if that works in the new workbook.

Though if you want to implement this code for all the sheets in the workbook, instead placing this code on specific sheet module, place it on ThisWorkbook Module.

The code will be as below...

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
Dim numCell As Range

If Target.Count <> 1 Then Exit Sub

If Target.Value = "+" Then
    Set numCell = Target.Offset(0, -1)
    numCell.Select
    numCell.Value = numCell.Value + 1
ElseIf Target.Value = "-" Then
    Set numCell = Target.Offset(0, 1)
    numCell.Select
    numCell.Value = numCell.Value - 1
End If

End Sub


问:
Android driver issue
I am new to mobile automation with appium.i am getting error message "The constructor AndriodDriver (Capabilities) refers to the missing type Capabilities ".</p>

```<code>driver=new AndriodDriver (new URL("127.0.0.1:4723"),
Capabilities);
</code>```

答:
Go through the below links. Those might be help full

http://toolsqa.com/mobile-automation/appium/download-and-install-nodejs/

http://www.software-testing-tutorials-automation.com/2015/09/appium-tutorials.html

Title: Android driver issue

Body:
I am new to mobile automation with appium.i am getting error message "The constructor AndriodDriver (Capabilities) refers to the missing type Capabilities ".

driver=new AndriodDriver (new URL("127.0.0.1:4723"),
Capabilities);


问:
how to do post in nsurlconection?
http://[domain]/functionsdata.php?action=get_projectdetails
This is my url how to do post city and how to fetch data based on city key in nsurlconnection in objective c  ios? </p>

答:
I've made that code for my own project, but it should suit for your problem as well. This is the needed code to use it. You can add it to two separated files or the same file that is going to use it.

```<code>@implementation NSString (VMMStringWebStructure)
-(NSString*)stringToWebStructure
{
    NSString* webString = [self stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    webString = [webString stringByReplacingOccurrencesOfString:@"&" withString:@"%26"];
    webString = [webString stringByReplacingOccurrencesOfString:@"?" withString:@"%3F"];
    webString = [webString stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
    webString = [webString stringByReplacingOccurrencesOfString:@"=" withString:@"%3D"];

    return webString;
}
@end

@implementation NSWebUtilities
+(NSString*)launchURL:(NSURL*)url withPostString:(NSString*)post
{
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];

    NSError *error = nil;
    NSHTTPURLResponse *response = nil;
    NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    if (response.statusCode >= 200 && response.statusCode < 300)
    {
        NSString *responseData = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
        if (responseData.length > 0) return responseData;
    }
    else
    {
        if (error) return [error localizedDescription];
        return [NSString stringWithFormat:NSLocalizedString(@"Received invalid status code: %d.",nil),response.statusCode];
    }

    return nil;
}
+(NSString*)launchURL:(NSURL*)url withPostValues:(NSDictionary*)postDict
{
    NSArray* postKeys = postDict.allKeys;
    NSMutableArray* postLines = [[NSMutableArray alloc] init];

    for (NSString* key in postKeys)
    {
        [postLines addObject:[NSString stringWithFormat:@"%@=%@",key,[postDict[key] stringToWebStructure]]];
    }

    return [self launchURL:url withPostString:[postLines componentsJoinedByString:@"&"]];
}
@end
</code>```

In your case, you could use it in that way:

```<code>NSString* urlString = @"http://[domain]/functionsdata.php?action=get_projectdetails";
NSURL *url = [NSURL URLWithString:urlString];

NSDictionary* postValues = @{@"city",@"<city name goes here>"};
NSString* output = [NSWebUtilities launchURL:url withPostValues:postValues];
</code>```

That will retrieve the output has a NSString called output.

Title: how to do post in nsurlconection?

Body:
I've made that code for my own project, but it should suit for your problem as well. This is the needed code to use it. You can add it to two separated files or the same file that is going to use it.

@implementation NSString (VMMStringWebStructure)
-(NSString*)stringToWebStructure
{
    NSString* webString = [self stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    webString = [webString stringByReplacingOccurrencesOfString:@"&" withString:@"%26"];
    webString = [webString stringByReplacingOccurrencesOfString:@"?" withString:@"%3F"];
    webString = [webString stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
    webString = [webString stringByReplacingOccurrencesOfString:@"=" withString:@"%3D"];

    return webString;
}
@end

@implementation NSWebUtilities
+(NSString*)launchURL:(NSURL*)url withPostString:(NSString*)post
{
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];

    NSError *error = nil;
    NSHTTPURLResponse *response = nil;
    NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    if (response.statusCode >= 200 && response.statusCode < 300)
    {
        NSString *responseData = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
        if (responseData.length > 0) return responseData;
    }
    else
    {
        if (error) return [error localizedDescription];
        return [NSString stringWithFormat:NSLocalizedString(@"Received invalid status code: %d.",nil),response.statusCode];
    }

    return nil;
}
+(NSString*)launchURL:(NSURL*)url withPostValues:(NSDictionary*)postDict
{
    NSArray* postKeys = postDict.allKeys;
    NSMutableArray* postLines = [[NSMutableArray alloc] init];

    for (NSString* key in postKeys)
    {
        [postLines addObject:[NSString stringWithFormat:@"%@=%@",key,[postDict[key] stringToWebStructure]]];
    }

    return [self launchURL:url withPostString:[postLines componentsJoinedByString:@"&"]];
}
@end

In your case, you could use it in that way:

NSString* urlString = @"http://[domain]/functionsdata.php?action=get_projectdetails";
NSURL *url = [NSURL URLWithString:urlString];

NSDictionary* postValues = @{@"city",@"<city name goes here>"};
NSString* output = [NSWebUtilities launchURL:url withPostValues:postValues];

That will retrieve the output has a NSString called output.


问:
Brace initialization prevents non-const use of temporary
I want to create a temporary copy of a const object and use it in a non-const way:

```<code>struct S {
    S& f() { return *this; }
};

int main() {
    const S a{};
    S{a}.f(); // Error on this line
    return 0;
}
</code>```

Using msvc (Visual Studio 2017, C++14), I get this error:

Error C2662   'S &S::f(void)': cannot convert 'this' pointer from 'const S' to 'S &'

If I change the brace initialization to classic initialization, it works:

```<code>S{a}.f(); // Does not work
S(a).f(); // Works
</code>```

Both variants compile fine in gcc. Am I missing something or is this a compiler bug?

答:
Seems like another MSVC bug.

S{a} is deduced as const struct S, and that alone is bug.

```<code>#include <string>
#include <iostream>

template < class T >
std::string type_name()
{
    std::string p = __FUNCSIG__;
    return p.substr( 106, p.length() - 106 - 7 );
}

struct S {
    S& f() { return *this; }
};

int main() {
    const S a{};
    //S{a}.f(); // Error on this line
    std::cout << type_name<decltype(S{a})>() << std::endl;
    return 0;
}
</code>```

Output:

```<code>const struct S
</code>```

Body:
I want to create a temporary copy of a const object and use it in a non-const way:

struct S {
    S& f() { return *this; }
};

int main() {
    const S a{};
    S{a}.f(); // Error on this line
    return 0;
}

Using msvc (Visual Studio 2017, C++14), I get this error:

Error C2662   'S &S::f(void)': cannot convert 'this' pointer from 'const S' to 'S &'

If I change the brace initialization to classic initialization, it works:

S{a}.f(); // Does not work
S(a).f(); // Works

Both variants compile fine in gcc. Am I missing something or is this a compiler bug?

Body:
Seems like another MSVC bug.

S{a} is deduced as const struct S, and that alone is bug.

#include <string>
#include <iostream>

template < class T >
std::string type_name()
{
    std::string p = __FUNCSIG__;
    return p.substr( 106, p.length() - 106 - 7 );
}

struct S {
    S& f() { return *this; }
};

int main() {
    const S a{};
    //S{a}.f(); // Error on this line
    std::cout << type_name<decltype(S{a})>() << std::endl;
    return 0;
}

Output:

const struct S


问:
How can I emit event on app launch from notification tap?
i'm using react native for my android app. i have a background service that listens for clipboard events. if something the app is interested in is in clipboard, app sends a push notification to the user. if the app is running on the background, i can emit an event and it's working perfect however if the app is closed and launched by the tap on the notification, nothing is emitted. react context is also empty. how can i emit this event on notification launch?

import android.app.Application;
import android.content.Intent;
import android.view.View;
import android.util.Log;
import android.os.Bundle;
import android.app.NotificationManager;
import android.support.v4.content.LocalBroadcastManager;
import com.facebook.react.modules.core.DeviceEventManagerModule;

import com.facebook.react.bridge.ReactContext;
import com.facebook.react.ReactActivity;
import com.facebook.react.common.LifecycleState;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.shell.MainReactPackage;

public class MainActivity extends ReactActivity {

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "PurchaseButton";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onNewIntent(getIntent());
    }

    @Override
    public void onNewIntent(Intent intent) {
        setIntent(intent);
        Bundle bundle = intent.getExtras();

        if (bundle != null) {
            String result = bundle.getString("response");
            int nid = bundle.getInt("nid");
            NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            mNotifyMgr.cancel(nid);

            ReactContext ctx = getReactInstanceManager().getCurrentReactContext();
            if (ctx != null) {
                ctx.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("my.custom.event", result);
                Log.d("PB", "sent broadcast..");
            } else {
                Log.d("PB", "react context is null...");
            }
        }
    }
}
```

答:
in case anyone wonders about this. here's the question answered for react native 0.42.0.

android has activity lifecycles and React Context is not available / instantiated on onCreate and onStart life cycle methods but onResume. we need React Context because this is how we can emit an event to our react native frontend. hence the way to successfully emit events, you must create a handler task, delay it 5 seconds and when it runs, you'll be able to emit the event. it's worth noting that, in my case, if you delay even 1 sec, you get the context however the frontend is not ready to listen for events. here's a sample code:

```<code>package com.purchasebutton;

import android.app.Application;
import android.content.Intent;
import android.view.View;
import android.util.Log;
import android.os.Bundle;
import android.os.Handler;
import android.app.NotificationManager;
import android.support.v4.content.LocalBroadcastManager;
import com.facebook.react.modules.core.DeviceEventManagerModule;

import com.facebook.react.bridge.ReactContext;
import com.facebook.react.ReactActivity;
import com.facebook.react.common.LifecycleState;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.shell.MainReactPackage;

public class MainActivity extends ReactActivity {

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "PurchaseButton";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onNewIntent(getIntent());
    }

    @Override
    protected void onResume() {
        super.onResume();
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ReactContext ctx = getReactInstanceManager().getCurrentReactContext();
                    if (ctx != null) {
                        Intent intent = getIntent();
                        Bundle bundle = intent.getExtras();
                        if (bundle != null) {
                            String result = bundle.getString("response");
                            int nid = bundle.getInt("nid");
                            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                            notificationManager.cancel(nid);
                            ctx.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("product.changed", result);
                        }
                    }
                }
            }, 5000);
    }

    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }
}
</code>```

Body:
in case anyone wonders about this. here's the question answered for react native 0.42.0.

android has activity lifecycles and React Context is not available / instantiated on onCreate and onStart life cycle methods but onResume. we need React Context because this is how we can emit an event to our react native frontend. hence the way to successfully emit events, you must create a handler task, delay it 5 seconds and when it runs, you'll be able to emit the event. it's worth noting that, in my case, if you delay even 1 sec, you get the context however the frontend is not ready to listen for events. here's a sample code:

package com.purchasebutton;

import android.app.Application;
import android.content.Intent;
import android.view.View;
import android.util.Log;
import android.os.Bundle;
import android.os.Handler;
import android.app.NotificationManager;
import android.support.v4.content.LocalBroadcastManager;
import com.facebook.react.modules.core.DeviceEventManagerModule;

import com.facebook.react.bridge.ReactContext;
import com.facebook.react.ReactActivity;
import com.facebook.react.common.LifecycleState;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.shell.MainReactPackage;

public class MainActivity extends ReactActivity {

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "PurchaseButton";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onNewIntent(getIntent());
    }

    @Override
    protected void onResume() {
        super.onResume();
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ReactContext ctx = getReactInstanceManager().getCurrentReactContext();
                    if (ctx != null) {
                        Intent intent = getIntent();
                        Bundle bundle = intent.getExtras();
                        if (bundle != null) {
                            String result = bundle.getString("response");
                            int nid = bundle.getInt("nid");
                            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                            notificationManager.cancel(nid);
                            ctx.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("product.changed", result);
                        }
                    }
                }
            }, 5000);
    }

    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }
}


问:
How to add
 with  link into a textarea as simple text?
I would like to be able to add links with an  tag based on user input.

HTML

```<code><div id="linkRef">
  <button type="button" class="btn btn-default link-list">Aggiungi un link</button>
  <ul class="main_ul">
  </ul>
</div>

<div id="linkData">
  <textarea></textarea>
</div>
</code>```

JS

```<code>$('body').on('click', 'button.link-list', function() {
  $("#linkRef").on("DOMSubtreeModified", updateTree);
  $('.main_ul').append(
    $('<li><div class="form-group"><input  placeholder="Dai un nome al link...." class="link_name form-control" type="text"></div><div class="form-group"><input placeholder="inserisci il link..." class="form-control" type="text"></div></li>')
  );
});

function updateTree() {
   var myLinks = $("#linkRef ul");
   $("#linkData textarea").val(myLinks.html() + "\n");
 }

$("#linkRef").on("DOMSubtreeModified", updateTree);
$("#linkRef").on('keyup', '.form-group input', updateTree);
</code>```

The above inserts the added list but it inserts the inputs and buttons and all the html in it too, yet not the actual values, i didn't insert the  code as i was trying to work out the basic first.

The output within the textarea that I am expecting would be:

```<code><ul>
   <li>
     <a href="www.example.com">Example</a>
   </li>
   <li>
     <a href="www.example2.com">Example2</a>
   </li>
</ul>
</code>```

I made a JsFiddle playground

And this is another JsFiddle for another case I had and I was trying to work this new question out based on that but i didn't manage it

答:
as far as i know you cannot add HTML to a textarea

instead you could use an editable div ( that behaves like a textarea )

example :

and also use outerHtml so you get also the

plus. i don't see any a in your .main ul html ( ?? )

see jsfiddle or snippet below

$('body').on('click', 'button.link-list', function() {
 $("#linkRef").on("DOMSubtreeModified", updateTree);
  $('.main_ul').append(
    $('

<input  placeholder="Dai un nome al link...." class="link_name form-control" type="text">

<input placeholder="inserisci il link..." class="form-control" type="text">

')
    );
});

function updateTree() {
  var myLinks = $("#linkRef ul");
   $("#linkData .texthere").html(myLinks.prop("outerHTML") + "\n");
 }

$("#linkRef").on("DOMSubtreeModified", updateTree);
$("#linkRef").on('keyup', '.form-group input', updateTree);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>textarea {
  width: 500px;
  height: 300px;
}

input {
  width: 400px;
  height: 40px;
  margin-bottom: 10px;
}

.margin-top-20 {
  margin-top: 20px;
}</code>```

  <button type="button" class="btn btn-default link-list">Aggiungi un link</button>

```

Title: How to add <ul> with <a> link into a textarea as simple text?

Body:
I would like to be able to add links with an  tag based on user input.

HTML

  <button type="button" class="btn btn-default link-list">Aggiungi un link</button>

  <textarea></textarea>

JS

$('body').on('click', 'button.link-list', function() {
  $("#linkRef").on("DOMSubtreeModified", updateTree);
  $('.main_ul').append(
    $('

<input  placeholder="Dai un nome al link...." class="link_name form-control" type="text">

<input placeholder="inserisci il link..." class="form-control" type="text">

')
  );
});

function updateTree() {
   var myLinks = $("#linkRef ul");
   $("#linkData textarea").val(myLinks.html() + "\n");
 }

$("#linkRef").on("DOMSubtreeModified", updateTree);
$("#linkRef").on('keyup', '.form-group input', updateTree);

The above inserts the added list but it inserts the inputs and buttons and all the html in it too, yet not the actual values, i didn't insert the  code as i was trying to work out the basic first.

The output within the textarea that I am expecting would be:

     Example

     Example2

I made a JsFiddle playground

And this is another JsFiddle for another case I had and I was trying to work this new question out based on that but i didn't manage it

Body:
as far as i know you cannot add HTML to a textarea

instead you could use an editable div ( that behaves like a textarea )

example : <div class="texthere" contenteditable="true"></div>

and also use outerHtml so you get also the <ul></ul>

plus. i don't see any a in your .main ul html ( ?? )

see jsfiddle or snippet below

$('body').on('click', 'button.link-list', function() {
 $("#linkRef").on("DOMSubtreeModified", updateTree);
  $('.main_ul').append(
    $('<li><div class="form-group"><input  placeholder="Dai un nome al link...." class="link_name form-control" type="text"></div><div class="form-group"><input placeholder="inserisci il link..." class="form-control" type="text"></div></li>')
    );
});

function updateTree() {
  var myLinks = $("#linkRef ul");
   $("#linkData .texthere").html(myLinks.prop("outerHTML") + "\n");
 }

$("#linkRef").on("DOMSubtreeModified", updateTree);
$("#linkRef").on('keyup', '.form-group input', updateTree);

textarea {
  width: 500px;
  height: 300px;
}

input {
  width: 400px;
  height: 40px;
  margin-bottom: 10px;
}

.margin-top-20 {
  margin-top: 20px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="linkRef">
  <button type="button" class="btn btn-default link-list">Aggiungi un link</button>
  <ul class="main_ul">
  </ul>
</div>

<div id="linkData">

<div class="texthere" contenteditable="true"></div>

</div>


问:
unintended redirect with react router
I have a simple react app with a react router set up like this. It sits at my app's root (/)

```<code>import React, {Component} from 'react';
import { render } from 'react-dom'
import { Router, Route, hashHistory, IndexRoute } from 'react-router'

import Main from "./components/main";
import Index from "./components/polls/index";
import New from "./components/polls/new";
import Show from "./components/polls/show";
import PollAdmin from "./components/polls/poll_admin"

render((
  <Router history={hashHistory}>
    <Route path="/" component={Main}>
      <IndexRoute component={Index}/>
      // more components here, removed for brevity
    </Route>

  </Router>
), document.getElementById('app'))
</code>```

When the user logs in (not part of the router), they are redirected back to /.
Once they do so, the Index component responds (see below).
The browser then visits /api/polls, which is not what's intended.
/api/polls is an api end point to fetch data to display.
I confirmed this by removing the componentDidMount function. With that function gone, the browser does not visit /api/polls

Why is the browser visiting /api/polls instead of making an asynchronous request? How do I properly redirect back to /?

```<code>import React, {Component} from 'react';
import { Link } from 'react-router';
import axios from 'axios';

class Index extends React.Component {

  constructor(props){

    super(props);
    this.state = {
      polls: []
    }
  }

  componentDidMount() {
    var _this = this;

      axios('/api/polls')
        .then(function(result){
          _this.setState({
            polls: result.data.polls
          })
        })
        .catch(function(err){
        })

  }

  ...
  }

}

export default Index;
</code>```

答:
After a little more poking around I solved the problem. When first visiting / the component Index makes an async request to /api/polls. Then the user logs in via Twitter. Here are the relevant routes:

```<code>router.get('/auth/twitter', passport.authenticate('twitter'));
router.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
</code>```

The problem was that req.session.returnTo stored /api/polls as the last "visited" url. After logging in the browser redirects to /api/polls rendering some ugly json on the page. For my purposes, this was an easy fix. I just changed the route to:

```<code>router.get('/auth/linkedin/callback', passport.authenticate('linkedin', { failureRedirect: '/login' }), function(req, res) {
  res.redirect('/');
});
</code>```

Users are always redirected back to / which is exactly what I want. I'm not certain what to do if you want to redirect back to the user's last page.

Title: unintended redirect with react router

Body:
I have a simple react app with a react router set up like this. It sits at my app's root (/)

import React, {Component} from 'react';
import { render } from 'react-dom'
import { Router, Route, hashHistory, IndexRoute } from 'react-router'

import Main from "./components/main";
import Index from "./components/polls/index";
import New from "./components/polls/new";
import Show from "./components/polls/show";
import PollAdmin from "./components/polls/poll_admin"

render((
  <Router history={hashHistory}>
    <Route path="/" component={Main}>
      <IndexRoute component={Index}/>
      // more components here, removed for brevity
    </Route>

  </Router>
), document.getElementById('app'))

When the user logs in (not part of the router), they are redirected back to /.
Once they do so, the Index component responds (see below).
The browser then visits /api/polls, which is not what's intended.
/api/polls is an api end point to fetch data to display.
I confirmed this by removing the componentDidMount function. With that function gone, the browser does not visit /api/polls

Why is the browser visiting /api/polls instead of making an asynchronous request? How do I properly redirect back to /?

import React, {Component} from 'react';
import { Link } from 'react-router';
import axios from 'axios';

class Index extends React.Component {

  constructor(props){

    super(props);
    this.state = {
      polls: []
    }
  }

  componentDidMount() {
    var _this = this;

      axios('/api/polls')
        .then(function(result){
          _this.setState({
            polls: result.data.polls
          })
        })
        .catch(function(err){
        })

  }

  ...
  }

}

export default Index;

Body:
After a little more poking around I solved the problem. When first visiting / the component Index makes an async request to /api/polls. Then the user logs in via Twitter. Here are the relevant routes:

router.get('/auth/twitter', passport.authenticate('twitter'));
router.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});

The problem was that req.session.returnTo stored /api/polls as the last "visited" url. After logging in the browser redirects to /api/polls rendering some ugly json on the page. For my purposes, this was an easy fix. I just changed the route to:

router.get('/auth/linkedin/callback', passport.authenticate('linkedin', { failureRedirect: '/login' }), function(req, res) {
  res.redirect('/');
});

Users are always redirected back to / which is exactly what I want. I'm not certain what to do if you want to redirect back to the user's last page.


问:
DataFrameGroupBy diff() on condition
Suppose i have a DataFrame:

```<code>df = pd.DataFrame({'CATEGORY':['a','b','c','b','b','a','b'],
                   'VALUE':[pd.np.NaN,1,0,0,5,0,4]})
</code>```

which looks like

```<code>    CATEGORY    VALUE
0      a         NaN
1      b         1
2      c         0
3      b         0
4      b         5
5      a         0
6      b         4
</code>```

I group it:

```<code>df = df.groupby(by='CATEGORY')
</code>```

And now, let me show, what i want with the help of example on one group 'b':

```<code>df.get_group('b')
</code>```

group b:

```<code>    CATEGORY    VALUE
1      b          1
3      b          0
4      b          5
6      b          4
</code>```

I need: In the scope of each group, count diff() between VALUE values, skipping all NaNs and 0s. So the result should be:

```<code>    CATEGORY    VALUE  DIFF
1      b          1      -
3      b          0      -
4      b          5      4
6      b          4     -1
</code>```

答:
Sounds like a job for a pd.Series.shift() operation along with a notnull mask.

First we remove the unwanted values, before we group the data

```<code>nonull_df = df[(df['VALUE'] != 0) & df['VALUE'].notnull()]
groups = nonull_df.groupby(by='CATEGORY')
</code>```

Now we can shift internally in the groups and calculate the diff

```<code>nonull_df['next_value'] = groups['VALUE'].shift(1)
nonull_df['diff'] = nonull_df['VALUE'] - nonull_df['next_value']
</code>```

Lastly and optionally you can copy the data back to the original dataframe

```<code>df.loc[nonull_df.index] = nonull_df

df
  CATEGORY  VALUE  next_value  diff
0        a    NaN         NaN   NaN
1        b    1.0         NaN   NaN
2        c    0.0         NaN   NaN
3        b    0.0         1.0  -1.0
4        b    5.0         1.0   4.0
5        a    0.0         NaN   NaN
6        b    4.0         5.0  -1.0
</code>```

Title: DataFrameGroupBy diff() on condition

Body:
Suppose i have a DataFrame:

df = pd.DataFrame({'CATEGORY':['a','b','c','b','b','a','b'],
                   'VALUE':[pd.np.NaN,1,0,0,5,0,4]})

which looks like

    CATEGORY    VALUE
0      a         NaN
1      b         1
2      c         0
3      b         0
4      b         5
5      a         0
6      b         4

I group it:

df = df.groupby(by='CATEGORY')

And now, let me show, what i want with the help of example on one group 'b':

df.get_group('b')

group b:

    CATEGORY    VALUE
1      b          1
3      b          0
4      b          5
6      b          4

I need: In the scope of each group, count diff() between VALUE values, skipping all NaNs and 0s. So the result should be:

    CATEGORY    VALUE  DIFF
1      b          1      -
3      b          0      -
4      b          5      4
6      b          4     -1

Body:
Sounds like a job for a pd.Series.shift() operation along with a notnull mask.

First we remove the unwanted values, before we group the data

nonull_df = df[(df['VALUE'] != 0) & df['VALUE'].notnull()]
groups = nonull_df.groupby(by='CATEGORY')

Now we can shift internally in the groups and calculate the diff

nonull_df['next_value'] = groups['VALUE'].shift(1)
nonull_df['diff'] = nonull_df['VALUE'] - nonull_df['next_value']

Lastly and optionally you can copy the data back to the original dataframe

df.loc[nonull_df.index] = nonull_df

df
  CATEGORY  VALUE  next_value  diff
0        a    NaN         NaN   NaN
1        b    1.0         NaN   NaN
2        c    0.0         NaN   NaN
3        b    0.0         1.0  -1.0
4        b    5.0         1.0   4.0
5        a    0.0         NaN   NaN
6        b    4.0         5.0  -1.0


问:
Google charts - Main title and axis size
I'm trying to change the font size for the main title and axis titles but I cannot with this code:

```<code>  var options = {
    title: 'Ratio de supervivencia de aerolíneas europeas',
    chartArea:{
         top: 20,
         bottom: 50,
         height: '75%'
    },
    width: 800,
    height: 600,
    hAxis: {title: 'Nº total de aerolíneas históricas', titleFontSize: 24},
    vAxis: {title: 'Ratio de supervivencia', format: 'percent', maxValue: 0.7, titleFontSize: 24},
    bubble: {textStyle: {fontSize: 11}}
  };
</code>```

Could someone help me?

Thanks in advance & regards,
Luis

答:
there is no option for --> titleFontSize

instead, use the option for --> titleTextStyle

e.g.

```<code>hAxis: {
  titleTextStyle: {
    fontSize: 24
  }
}
</code>```

see configuration options for more...

Body:
I'm trying to change the font size for the main title and axis titles but I cannot with this code:

  var options = {
    title: 'Ratio de supervivencia de aerolíneas europeas',
    chartArea:{
         top: 20,
         bottom: 50,
         height: '75%'
    },
    width: 800,
    height: 600,
    hAxis: {title: 'Nº total de aerolíneas históricas', titleFontSize: 24},
    vAxis: {title: 'Ratio de supervivencia', format: 'percent', maxValue: 0.7, titleFontSize: 24},
    bubble: {textStyle: {fontSize: 11}}
  };

Could someone help me?

Thanks in advance & regards,
Luis

Body:
there is no option for --> titleFontSize

instead, use the option for --> titleTextStyle

e.g.

hAxis: {
  titleTextStyle: {
    fontSize: 24
  }
}

see configuration options for more...


问:
Looking for duplicates in arrays inside arrays (multi-dimensional array)
I've gotten into a bit of a jam and was wondering if someone could clear it up.
What I want to do is:

Opening a bunch of data containing .txt files

Creating a multidimensional array that holds @array[@filenames][@data]

Find which files are duplicates of eachother in terms of data

Here I slurp a file into a variable, use regex to obtain my data and put it into an array:

```<code>    while (my $row = <$fh>) {
        unless ($. == 0) {
            {
            local $/; # enable slurp
            @datalist = <$fh> =~ /\s*\d*\/\s*\d*\|\s*(.*?)\|.*?(?:.*?\|){4}\s*(\S*)\|(\S*).*\|/g; #extract article numbers # $1 = article number, $2 = quantity, $3 = unit
            }
            push(@arrayofarrays,[@datalist]);
            push(@filenames,$file);
            last;
            }
        }
        $numr++;
}
open(my $feh,">","test.txt");
print {$feh} Dumper \@arrayofarrays;
</code>```

A Dumper shows that my data looks fine (pseudoresults to make it easy to read and short):

```<code>$VAR1 = [
          [
            'data type1',
            'data type2',
            'data type3',
            'data type1',
            'data type2',
            'data type3',
            ...
          ],
          [
            'data type1',
            'data type2',
            'data type3',
            ...
          ],
        ...
     ];
</code>```

So I'm wondering if anyone knows an easy way to check for duplicates between sets of data? I know I can print individual data sets using

What I tried might give a better idea as to what I need to do:

```<code>my $i = 0;
my $j = 0;
while ( $i <= scalar @arrayofarrays) {
    $j = 0;
    while ( $j <= scalar @arrayofarrays) {
        if (@{$arrayofarrays[$i]} eq @{$arrayofarrays[$j]}) {
            print "\n'$filenames[$i]' is duplicate to '$filenames[$j]'.";
            } $j++;
        } $i++;
    }
</code>```

答:
When you create the @dataList, create a key for it and check for that key before you do the push, something like:</p>

```<code>my %checkHash=undef;
my $key=arrayKey(\@datalist);
if (!$checkHash{$key}) {
    push(@arrayofarrays,[@datalist]);
    push(@filenames,$file);
    $checkHash{$key}=1;
    last;
}

sub arrayKey($) {
    my $arrayRef = shift;
    my $output=undef;
    for (@$arrayRef) {
        if (ref($_) eq 'ARRAY') {
            $output.="[";
            $output.=arrayKey($_);
            $output.="]";
        }
        else {
            $output.="$_,";
        }
    }
    return $output;
}
</code>```

Body:
I've gotten into a bit of a jam and was wondering if someone could clear it up.
What I want to do is:

Opening a bunch of data containing .txt files

Creating a multidimensional array that holds @array[@filenames][@data]

Find which files are duplicates of eachother in terms of data

Here I slurp a file into a variable, use regex to obtain my data and put it into an array:

    while (my $row = <$fh>) {
        unless ($. == 0) {
            {
            local $/; # enable slurp
            @datalist = <$fh> =~ /\s*\d*\/\s*\d*\|\s*(.*?)\|.*?(?:.*?\|){4}\s*(\S*)\|(\S*).*\|/g; #extract article numbers # $1 = article number, $2 = quantity, $3 = unit
            }
            push(@arrayofarrays,[@datalist]);
            push(@filenames,$file);
            last;
            }
        }
        $numr++;
}
open(my $feh,">","test.txt");
print {$feh} Dumper \@arrayofarrays;

A Dumper shows that my data looks fine (pseudoresults to make it easy to read and short):

$VAR1 = [
          [
            'data type1',
            'data type2',
            'data type3',
            'data type1',
            'data type2',
            'data type3',
            ...
          ],
          [
            'data type1',
            'data type2',
            'data type3',
            ...
          ],
        ...
     ];

So I'm wondering if anyone knows an easy way to check for duplicates between sets of data? I know I can print individual data sets using

What I tried might give a better idea as to what I need to do:

my $i = 0;
my $j = 0;
while ( $i <= scalar @arrayofarrays) {
    $j = 0;
    while ( $j <= scalar @arrayofarrays) {
        if (@{$arrayofarrays[$i]} eq @{$arrayofarrays[$j]}) {
            print "\n'$filenames[$i]' is duplicate to '$filenames[$j]'.";
            } $j++;
        } $i++;
    }

Body:
When you create the @dataList, create a key for it and check for that key before you do the push, something like:

my %checkHash=undef;
my $key=arrayKey(\@datalist);
if (!$checkHash{$key}) {
    push(@arrayofarrays,[@datalist]);
    push(@filenames,$file);
    $checkHash{$key}=1;
    last;
}

sub arrayKey($) {
    my $arrayRef = shift;
    my $output=undef;
    for (@$arrayRef) {
        if (ref($_) eq 'ARRAY') {
            $output.="[";
            $output.=arrayKey($_);
            $output.="]";
        }
        else {
            $output.="$_,";
        }
    }
    return $output;
}


问:
How to map Character and Integer Columns in hibernate
Currently i have two tables

userdetails

userid_bankid

Both are mapped with column userId , userId in first table is Integer and second table is charterer.

```<code>@JoinColumn(name = "userId",referencedColumnName="userId" nullable = false , insertable = false, updatable = false)
</code>```

i am getting typecast error

答: Have a look at This question I think this might solve your problem or help you to solve your problem.</p>

Body:
Currently i have two tables

userdetails

userid_bankid

Both are mapped with column userId , userId in first table is Integer and second table is charterer.

@JoinColumn(name = "userId",referencedColumnName="userId" nullable = false , insertable = false, updatable = false)

i am getting typecast error


问:
MySQL insert error : ER_BAD_FIELD_ERROR: Unknown column '2525' in 'field list'
```<code>var convID = 2525;
var contactUsername = 'blabla';
var userId = 100;
var contactId = 200;

var sql = "INSERT INTO contacts (FK_OWNERID, FK_USERID, FC_CONTACTNAME, `CONVERSATION_ID`)
                     VALUES (" + mysql.escape(userId) + "," + mysql.escape(contactId) + "," + mysql.escape(contactUsername) + "," + convID + "),
                     (" + mysql.escape(contactId) + "," + mysql.escape(userId) + "," + mysql.escape(username) + "," + convID + ")";
</code>```

`Error: ER_BAD_FIELD_ERROR: Unknown column '2525' in 'field list'
Fields are varchar(32) for both CONVERSATION_ID and FC_CONTACTNAME and ints for the 2 others.

What's wrong with this query? I even put the backticks around CONVERSATION_ID and it thinks the convID variable is a column...

Edit:

If my query is just that, then it works:

```<code>        var sql = "INSERT INTO contacts (`FK_OWNERID`, `FK_USERID`, `FC_CONTACTNAME`)
                 VALUES (" + mysql.escape(userId) + "," + mysql.escape(contactId) + "," + mysql.escape(contactUsername) + "),
                 (" + mysql.escape(contactId) + "," + mysql.escape(userId) + "," + mysql.escape(username) + ")";
</code>```

答:
I recently encountered a similar issue while trying to pass a parameter into a string in Node JS.

In the end, I was able to get a dynamic insertion into my MySQL database by using this line :

insertIntoNodeDirectory( '2', '"' + testMacAddress[0] + '"', '1');

This would enter the integer value 2, the string value contained in the testMacAddress array at index 0, and the integer value 1.

If i used this line:
insertIntoNodeDirectory( '2', '" + testMacAddress[0] + "', '1');

without the additional single quotes around testMacAddress, the value inserted into the database was the string 'testMacAddress[0]'. Not what I wanted.

Body:
var convID = 2525;
var contactUsername = 'blabla';
var userId = 100;
var contactId = 200;

var sql = "INSERT INTO contacts (FK_OWNERID, FK_USERID, FC_CONTACTNAME, `CONVERSATION_ID`)
                     VALUES (" + mysql.escape(userId) + "," + mysql.escape(contactId) + "," + mysql.escape(contactUsername) + "," + convID + "),
                     (" + mysql.escape(contactId) + "," + mysql.escape(userId) + "," + mysql.escape(username) + "," + convID + ")";

`Error: ER_BAD_FIELD_ERROR: Unknown column '2525' in 'field list'
Fields are varchar(32) for both CONVERSATION_ID and FC_CONTACTNAME and ints for the 2 others.

What's wrong with this query? I even put the backticks around CONVERSATION_ID and it thinks the convID variable is a column...

Edit:

If my query is just that, then it works:

        var sql = "INSERT INTO contacts (`FK_OWNERID`, `FK_USERID`, `FC_CONTACTNAME`)
                 VALUES (" + mysql.escape(userId) + "," + mysql.escape(contactId) + "," + mysql.escape(contactUsername) + "),
                 (" + mysql.escape(contactId) + "," + mysql.escape(userId) + "," + mysql.escape(username) + ")";


问:
Display a table using for twig
I'm using symfony and html2pdf bundle to generate a pdf file so here's the code that I used to display a table in the pdf file:

```<code> <table class="border" width="100%" align="center">
    <thead>
        <tr>
             <th>Kilometrage</th>
             <th>Liste des Interventions</th>
        </tr>
    </thead>
    <tbody>
        <tr>

            {% if voitures.kilometrage-voitures.kilometragederniervidange<20000 and voitures.kilometrage-voitures.kilometragederniervidange>=10000%}
            {% for intervention1 in interventions1 %}
                <td>{{ voitures.kilometragederniervidange+10000 }}</td>
                <td>***{{ intervention1.interventions }}</td>
            {% endfor %}{% endif %}

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

and here's what I get as a result:

and what I want to do is to show each line separately. What should I do exactly? ?

答:
You have probably misplaced the for cycle, try this:

```<code> <table class="border" width="100%" align="center">
     <thead>
         <tr>
              <th>Kilometrage</th>
              <th>Liste des Interventions</th>
         </tr>
     </thead>
     <tbody>
         {% if voitures.kilometrage-voitures.kilometragederniervidange<20000 and voitures.kilometrage-voitures.kilometragederniervidange>=10000%}
             {% for intervention1 in interventions1 %}
             <tr>
                 <td>{{ voitures.kilometragederniervidange+10000 }}</td>
                 <td>***{{ intervention1.interventions }}</td>
             </tr>
             {% endfor %}
         {% endif %}
     </tbody>
 </table>
</code>```

This will insert new table row for every record / run of the for cycle.

Title: Display a table using for twig

Body:
I'm using symfony and html2pdf bundle to generate a pdf file so here's the code that I used to display a table in the pdf file:

             Kilometrage
             Liste des Interventions

            {% if voitures.kilometrage-voitures.kilometragederniervidange<20000 and voitures.kilometrage-voitures.kilometragederniervidange>=10000%}
            {% for intervention1 in interventions1 %}
                {{ voitures.kilometragederniervidange+10000 }}
                ***{{ intervention1.interventions }}
            {% endfor %}{% endif %}

and here's what I get as a result:

and what I want to do is to show each line separately. What should I do exactly? ?

Body:
You have probably misplaced the for cycle, try this:

 <table class="border" width="100%" align="center">
     <thead>
         <tr>
              <th>Kilometrage</th>
              <th>Liste des Interventions</th>
         </tr>
     </thead>
     <tbody>
         {% if voitures.kilometrage-voitures.kilometragederniervidange<20000 and voitures.kilometrage-voitures.kilometragederniervidange>=10000%}
             {% for intervention1 in interventions1 %}
             <tr>
                 <td>{{ voitures.kilometragederniervidange+10000 }}</td>
                 <td>***{{ intervention1.interventions }}</td>
             </tr>
             {% endfor %}
         {% endif %}
     </tbody>
 </table>

This will insert new table row for every record / run of the for cycle.