问:
Output Cookie value into html form
Im trying to implement some cookies on my website. Ideally I would like to save the user html form input into cookies so that it is automatically set for later reference. However this form also sends the values to the database, like so:

```<code><?php
session_start();
?>
<?php

if($_POST['formSubmit'] == "Submit")
{
    $errorMessage = false;

    if(empty($_POST['formName']))
    {
        $errorMessage = true;
    }
    if(empty($_POST['formEmail']))
    {
$errorMessage = true;       }
    if(empty($_POST['formAddress']))
    {
$errorMessage = true;       }
if(empty($_POST['formPrice']))
    {
$errorMessage = true;    }

$varName = $_POST['formName'];
    $varEmail = $_POST['formEmail'];
    $varAddress = $_POST['formAddress'];
$varPrice = $_POST['formPrice'];
    $varComments = $_POST['formComments'];

     if($errorMessage == false)
    {

     $db = mysql_connect("","","");
  if(!$db) die("Error connecting to MySQL database.");
  mysql_select_db("" ,$db);

        $sql = "INSERT INTO formdata (name, email, address, price, comments)
VALUES (".
                        PrepSQL($varName) . ", " .
                        PrepSQL($varEmail) . ", " .
                        PrepSQL($varAddress) . ", " .
          PrepSQL($varPrice) . ", " .
                        PrepSQL($varComments) . ")";
        mysql_query($sql);

        header("Location: thankyou.php");
        exit();
    }
}

//sql injection protection..
function PrepSQL($value)
{

    if(get_magic_quotes_gpc())
    {
        $value = stripslashes($value);
    }

    $value = "'" . mysql_real_escape_string($value) . "'";

    return($value);
}

?>
<!DOCTYPE html>
<html>
<body>

<div class="Formm">
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
    <?php
    if ( $errorMessage == true ) {
        echo( "<h3>PLEASE FILL IN ALL QUESTIONS WITH A STAR.</h3>" );

    }

    $result = mysqli_query( $link, "SELECT * FROM `formdata` WHERE user=$user ORDER BY id ASC LIMIT 1" );

    if ( mysqli_num_rows( $result ) > 0 ) {
        // output data of each row
        while ( $row = mysqli_fetch_assoc( $result ) ) {
            $id = $row[ "id" ];
            $varname = $row[ "varname" ];
            $varemail = $row[ "varemail" ];
            $varaddress = $row[ "varaddress" ];
            $varprice = $row[ "varprice" ];
            $varcomments = $row[ "varcomments" ];
        }
    }

    ?>
    <p>

        <label for='formName'>Venue name*</label><br/>
        <input type="text" name="formName" maxlength="100" value="<? echo($varName); ?>"/>
    </p>

    <p>
        <label for='formEmail'>Email*</label><br/>
        <input type="text" name="formEmail" maxlength="100" value="<? echo($varEmail);?>"/>
    </p>
    <p>
        <label for='formAddress'>Address*</label><br/>
        <input type="text" name="formAddress" maxlength="100" value="<? echo($varAddress);?>"/>
    </p>
    <p>
        <label for='formPrice'>Estimated price*</label><br/>
        <input type="text" name="formPrice" maxlength="100" value="<?php echo($varPrice);?>"/>
    </p>
    <p>
        <label for='formComments'>Any comments associated with the Venue that the artist should be aware of?</label><br/>
        <input type="text" name="formComments" maxlength="250" value="<? echo($varComments);?>"/>
    </p>
    <input type="submit" name="formSubmit" value="Submit"/>
</form>

<?php
include 'footer.php';
?>

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

NEW EDITIm trying to implement some cookies on my website. Ideally I would like to save the user html form input into cookies so that it is automatically set for later reference. However this form also sends the values to the database, like so:

答:
You can use your database for this. Make a script that get's the last entered data from the user and place it in the form

Example:

```<code>//query
$result = mysqli_query( $link, "SELECT * FROM `formdata` WHERE user=$user ORDER BY id ASC LIMIT 1" );

if ( mysqli_num_rows( $result ) > 0 ) {
    // output data of each row
    while ( $row = mysqli_fetch_assoc( $result ) ) {
        $id = $row[ "id" ];
        $name = $row[ "name" ];
        $email = $row[ "email" ];
        $address = $row[ "address" ];
        $price = $row[ "price" ];
        $comments = $row[ "comments" ];
        }
}
</code>```

EDIT:

This fits your need:

```<code><div class="Formm">
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
    <?php
    if ( $errorMessage == true ) {
        echo( "<h3>PLEASE FILL IN ALL QUESTIONS WITH A STAR.</h3>" );

    }

    $result = mysqli_query( $link, "SELECT * FROM `formdata` WHERE user=$user ORDER BY id ASC LIMIT 1" );

    if ( mysqli_num_rows( $result ) > 0 ) {
        // output data of each row
        while ( $row = mysqli_fetch_assoc( $result ) ) {
            $id = $row[ "id" ];
            $varname = $row[ "varname" ];
            $varemail = $row[ "varemail" ];
            $varaddress = $row[ "varaddress" ];
            $varprice = $row[ "varprice" ];
            $varcomments = $row[ "varcomments" ];
        }
    }

    ?>
    <p>

        <label for='formName'>Venue name*</label><br/>
        <input type="text" name="formName" maxlength="100" value="<? echo($varName); ?>"/>
    </p>

    <p>
        <label for='formEmail'>Email*</label><br/>
        <input type="text" name="formEmail" maxlength="100" value="<? echo($varEmail);?>"/>
    </p>
    <p>
        <label for='formAddress'>Address*</label><br/>
        <input type="text" name="formAddress" maxlength="100" value="<? echo($varAddress);?>"/>
    </p>
    <p>
        <label for='formPrice'>Estimated price*</label><br/>
        <input type="text" name="formPrice" maxlength="100" value="<? echo($varPrice);?>"/>
    </p>
    <p>
        <label for='formComments'>Any comments associated with the Venue that the artist should be aware of?</label><br/>
        <input type="text" name="formComments" maxlength="250" value="<? echo($varComments);?>"/>
    </p>
    <input type="submit" name="formSubmit" value="Submit"/>
</form>
</code>```

Title: Output Cookie value into html form

Body:
Im trying to implement some cookies on my website. Ideally I would like to save the user html form input into cookies so that it is automatically set for later reference. However this form also sends the values to the database, like so:

<?php
session_start();
?>
<?php

if($_POST['formSubmit'] == "Submit")
{
    $errorMessage = false;

    if(empty($_POST['formName']))
    {
        $errorMessage = true;
    }
    if(empty($_POST['formEmail']))
    {
$errorMessage = true;       }
    if(empty($_POST['formAddress']))
    {
$errorMessage = true;       }
if(empty($_POST['formPrice']))
    {
$errorMessage = true;    }

$varName = $_POST['formName'];
    $varEmail = $_POST['formEmail'];
    $varAddress = $_POST['formAddress'];
$varPrice = $_POST['formPrice'];
    $varComments = $_POST['formComments'];

     if($errorMessage == false)
    {

     $db = mysql_connect("","","");
  if(!$db) die("Error connecting to MySQL database.");
  mysql_select_db("" ,$db);

        $sql = "INSERT INTO formdata (name, email, address, price, comments)
VALUES (".
                        PrepSQL($varName) . ", " .
                        PrepSQL($varEmail) . ", " .
                        PrepSQL($varAddress) . ", " .
          PrepSQL($varPrice) . ", " .
                        PrepSQL($varComments) . ")";
        mysql_query($sql);

        header("Location: thankyou.php");
        exit();
    }
}

//sql injection protection..
function PrepSQL($value)
{

    if(get_magic_quotes_gpc())
    {
        $value = stripslashes($value);
    }

    $value = "'" . mysql_real_escape_string($value) . "'";

    return($value);
}

?>
<!DOCTYPE html>

<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
    <?php
    if ( $errorMessage == true ) {
        echo( "
PLEASE FILL IN ALL QUESTIONS WITH A STAR.
" );

    }

    $result = mysqli_query( $link, "SELECT * FROM `formdata` WHERE user=$user ORDER BY id ASC LIMIT 1" );

    if ( mysqli_num_rows( $result ) > 0 ) {
        // output data of each row
        while ( $row = mysqli_fetch_assoc( $result ) ) {
            $id = $row[ "id" ];
            $varname = $row[ "varname" ];
            $varemail = $row[ "varemail" ];
            $varaddress = $row[ "varaddress" ];
            $varprice = $row[ "varprice" ];
            $varcomments = $row[ "varcomments" ];
        }
    }

    ?>

        Venue name*

        <input type="text" name="formName" maxlength="100" value="<? echo($varName); ?>"/>

        Email*

        <input type="text" name="formEmail" maxlength="100" value="<? echo($varEmail);?>"/>

        Address*

        <input type="text" name="formAddress" maxlength="100" value="<? echo($varAddress);?>"/>

        Estimated price*

        <input type="text" name="formPrice" maxlength="100" value="<?php echo($varPrice);?>"/>

        Any comments associated with the Venue that the artist should be aware of?

        <input type="text" name="formComments" maxlength="250" value="<? echo($varComments);?>"/>

    <input type="submit" name="formSubmit" value="Submit"/>
</form>

<?php
include 'footer.php';
?>

NEW EDITIm trying to implement some cookies on my website. Ideally I would like to save the user html form input into cookies so that it is automatically set for later reference. However this form also sends the values to the database, like so:

Body:
You can use your database for this. Make a script that get's the last entered data from the user and place it in the form

Example:

//query
$result = mysqli_query( $link, "SELECT * FROM `formdata` WHERE user=$user ORDER BY id ASC LIMIT 1" );

if ( mysqli_num_rows( $result ) > 0 ) {
    // output data of each row
    while ( $row = mysqli_fetch_assoc( $result ) ) {
        $id = $row[ "id" ];
        $name = $row[ "name" ];
        $email = $row[ "email" ];
        $address = $row[ "address" ];
        $price = $row[ "price" ];
        $comments = $row[ "comments" ];
        }
}

EDIT:

This fits your need:

<div class="Formm">
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
    <?php
    if ( $errorMessage == true ) {
        echo( "<h3>PLEASE FILL IN ALL QUESTIONS WITH A STAR.</h3>" );

    }

    $result = mysqli_query( $link, "SELECT * FROM `formdata` WHERE user=$user ORDER BY id ASC LIMIT 1" );

    if ( mysqli_num_rows( $result ) > 0 ) {
        // output data of each row
        while ( $row = mysqli_fetch_assoc( $result ) ) {
            $id = $row[ "id" ];
            $varname = $row[ "varname" ];
            $varemail = $row[ "varemail" ];
            $varaddress = $row[ "varaddress" ];
            $varprice = $row[ "varprice" ];
            $varcomments = $row[ "varcomments" ];
        }
    }

    ?>
    <p>

        <label for='formName'>Venue name*</label><br/>
        <input type="text" name="formName" maxlength="100" value="<? echo($varName); ?>"/>
    </p>

    <p>
        <label for='formEmail'>Email*</label><br/>
        <input type="text" name="formEmail" maxlength="100" value="<? echo($varEmail);?>"/>
    </p>
    <p>
        <label for='formAddress'>Address*</label><br/>
        <input type="text" name="formAddress" maxlength="100" value="<? echo($varAddress);?>"/>
    </p>
    <p>
        <label for='formPrice'>Estimated price*</label><br/>
        <input type="text" name="formPrice" maxlength="100" value="<? echo($varPrice);?>"/>
    </p>
    <p>
        <label for='formComments'>Any comments associated with the Venue that the artist should be aware of?</label><br/>
        <input type="text" name="formComments" maxlength="250" value="<? echo($varComments);?>"/>
    </p>
    <input type="submit" name="formSubmit" value="Submit"/>
</form>


来源: stackexchange

问:
Regex how to match the group that was matched
Like for example here:

```<code>/(\.\s)|(\!\s)|(\?\s)|(\:\s)/
</code>```

So for example if the ? is matched I want it to be replaced with itself. Obviously matching with "$1" wouldn't work too well here.

EDIT: It seems it needs more explanation. So if I have this string:

```<code>OK good. And this sentence? And maybe even this one!
</code>```

Then I can match the endings. So its matching the punctuation.

答:
You can use every capture group in the replacement and only the matched group will have a value. So for the regex you've provided use:

```<code>$1$2$3$4
</code>```

If the third capture group is matched $3 will be populated and all others empty.

ContentLicense: CC BY-SA 3.0

Body:
Like for example here:

/(\.\s)|(\!\s)|(\?\s)|(\:\s)/

So for example if the ? is matched I want it to be replaced with itself. Obviously matching with "$1" wouldn't work too well here.

EDIT: It seems it needs more explanation. So if I have this string:

OK good. And this sentence? And maybe even this one!

Then I can match the endings. So its matching the punctuation.

Body:
You can use every capture group in the replacement and only the matched group will have a value. So for the regex you've provided use:

$1$2$3$4

If the third capture group is matched $3 will be populated and all others empty.


问:
How to wait inside a beforeEach in Angular 4/Jasmine
One of my components uses a setTimeout inside ngOnInit, e.g:

```<code>ngOnInit() {
  setTimeout(() => {
      // do some setup stuff using FormBuilder
  }, 100);
}
</code>```

In the unit tests for this component, I need to spy on one of the methods of one of the controls which are built programmatically using FormBuilder, so I am doing this in a beforeEach:

```<code>describe('testing something', () => {

    beforeEach(() => {
        spyOn(component.form.controls.myControl, 'enable');
    });

    it('does something', () => {
      // test stuff
    });

});
</code>```

Before the timeout was added, the test was working perfectly. How can I make the beforeEach wait for the 100 ms timeout in the ngOnInit method?

I've tried adding async and fakeAsync to the outer describe, e.g. like this:

```<code> describe('testing something', <any>fakeAsync(() => {
     ...
 }));
</code>```

or

```<code>describe('testing something', async(() => {
     ...
 }));
</code>```

But in the first case, with fakeAsync I see a message in the test runner Error: Expected to be running in 'ProxyZone', but it was not found., and in the second case it just doesn't even run the test. I also tried wrapping the it methods in fakeAsync but that doesn't do anything to delay the beforeEach

I've tried wrapping the spyOn method inside the beforeEach in a setTimeout and this doesn't appear to have any effect, i.e. the test fails in the same way.

I've also tried using fakeAsync with the beforeEach, like this:

```<code>beforeEach(<any>fakeAsync(() => {
    tick(100);
    spyOn(component.modelForm.controls.myControl, 'enable');

  }));
</code>```

But this doesn't work either. It doesn't result in any errors, but the method I want to spy on doesn't exist yet, even after the tick.

How can I force the beforeEach to wait for the timeout in ngOnInit()? Is it even possible?

答:
I was able to fix this using Jasmine's done callback inside the beforeEach, like this:

```<code>beforeEach((done) => {
    component.ngOnInit();

    setTimeout(() => {
      spyOn(component.modelForm.controls.myControl, 'enable');

      done();
    }, 100);
  });
</code>```

Seems so intuitive!

Body:
One of my components uses a setTimeout inside ngOnInit, e.g:

ngOnInit() {
  setTimeout(() => {
      // do some setup stuff using FormBuilder
  }, 100);
}

In the unit tests for this component, I need to spy on one of the methods of one of the controls which are built programmatically using FormBuilder, so I am doing this in a beforeEach:

describe('testing something', () => {

    beforeEach(() => {
        spyOn(component.form.controls.myControl, 'enable');
    });

    it('does something', () => {
      // test stuff
    });

});

Before the timeout was added, the test was working perfectly. How can I make the beforeEach wait for the 100 ms timeout in the ngOnInit method?

I've tried adding async and fakeAsync to the outer describe, e.g. like this:

 describe('testing something', <any>fakeAsync(() => {
     ...
 }));

or

describe('testing something', async(() => {
     ...
 }));

But in the first case, with fakeAsync I see a message in the test runner Error: Expected to be running in 'ProxyZone', but it was not found., and in the second case it just doesn't even run the test. I also tried wrapping the it methods in fakeAsync but that doesn't do anything to delay the beforeEach

I've tried wrapping the spyOn method inside the beforeEach in a setTimeout and this doesn't appear to have any effect, i.e. the test fails in the same way.

I've also tried using fakeAsync with the beforeEach, like this:

beforeEach(<any>fakeAsync(() => {
    tick(100);
    spyOn(component.modelForm.controls.myControl, 'enable');

  }));

But this doesn't work either. It doesn't result in any errors, but the method I want to spy on doesn't exist yet, even after the tick.

How can I force the beforeEach to wait for the timeout in ngOnInit()? Is it even possible?

Body:
I was able to fix this using Jasmine's done callback inside the beforeEach, like this:

beforeEach((done) => {
    component.ngOnInit();

    setTimeout(() => {
      spyOn(component.modelForm.controls.myControl, 'enable');

      done();
    }, 100);
  });

Seems so intuitive!


问:
Rails loop thru attachments and show the first
I have implemented a basic search and I would like to show each result aligned with an image.
I'm using the carrierwave gem on my app and trying loop thru attachments in order to show only the first one as thumbnail.

```<code><div class="container">
  <div class="img-thumbnail" style="display: inline-block;">
    <% if @items.present? %>
        <% @items.each do |item| %>
        <% item.attachments.each do |attachment| %>
            <%= image_tag attachment.url(:mini).first unless attachment.blank? %>
            <% end %>
      <% end %>
   <% end %>
 </div>

create_table "items", force: :cascade do |t|
  t.string "title"
  t.string "description"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.json "attachments"
end
</code>```

But unfortunately the image does not show, no errors etheir just a blank thumbnail. Any ideas how to implement this?

答:
In your answer, you iterate over attachments and add an index to the iteration. But the only purpose of the iteration is to choose an attachment whose index == 0. A much easier way to express the same thing is just to retrieve the attachment at index 0 directly using attachments[0]. To be more Ruby-idiomatic, we can use attachments.first.

So we can do away with the inner iteration entirely. All we need is to check if @items is present, then iterate over items, pick the first attachment of each, and retrieve the url.

Here's a simplified version:

```<code><% if @items.present? %>
    <% @items.each do |item|%>
         <%= image_tag item.attachments.first.url(:mini) %>
    <% end %>
<% end %>
</code>```

Note that this will fail (your code will too) if any item has no attachments. You may want to guard against this by using Ruby's safe-navigation operator (which works in Ruby 2.3+). You can replace the third line with this:

```<code>         <%= image_tag item.attachments.first&.url(:mini) %>
# This prevents error if `.first` return nil ^
</code>```

Body:
I have implemented a basic search and I would like to show each result aligned with an image.
I'm using the carrierwave gem on my app and trying loop thru attachments in order to show only the first one as thumbnail.

    <% if @items.present? %>
        <% @items.each do |item| %>
        <% item.attachments.each do |attachment| %>
            <%= image_tag attachment.url(:mini).first unless attachment.blank? %>
            <% end %>
      <% end %>
   <% end %>

create_table "items", force: :cascade do |t|
  t.string "title"
  t.string "description"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.json "attachments"
end

But unfortunately the image does not show, no errors etheir just a blank thumbnail. Any ideas how to implement this?

Body:
In your answer, you iterate over attachments and add an index to the iteration. But the only purpose of the iteration is to choose an attachment whose index == 0. A much easier way to express the same thing is just to retrieve the attachment at index 0 directly using attachments[0]. To be more Ruby-idiomatic, we can use attachments.first.

So we can do away with the inner iteration entirely. All we need is to check if @items is present, then iterate over items, pick the first attachment of each, and retrieve the url.

Here's a simplified version:

<% if @items.present? %>
    <% @items.each do |item|%>
         <%= image_tag item.attachments.first.url(:mini) %>
    <% end %>
<% end %>

Note that this will fail (your code will too) if any item has no attachments. You may want to guard against this by using Ruby's safe-navigation operator (which works in Ruby 2.3+). You can replace the third line with this:

         <%= image_tag item.attachments.first&.url(:mini) %>
# This prevents error if `.first` return nil ^


问:
How to Sinon spy a Vue component method triggered by a Vue event?
The basic setup that I've done in order to describe my problem:

Using vue-cli 2.8.2, I generated a new project based on webpack template (vue init webpack vue-test-sinon-spy) keeping all the defaults of vue-cli (with the irrelevant exception of disabling eslint).

Changes done in this vue-cli generated project:

I attached an event on h2 tag from Hello.vue:

Essential Links

```

<ol start="2">
<li>I added a method in Hello component</li>
</ol>

<pre class="lang-html prettyprint-override"><code><script>
export default {
  ...
  methods: {
    sayHello() {
      console.log('hello!')
    }
  }
}
</script>
</code>```

I added a new test in Hello.spec.js

describe('Hello.vue', () => {
  // ...

  it('should handle click on h2 tag', () => {
    const Constructor = Vue.extend(Hello)
    const vm = new Constructor().$mount()
    sinon.spy(vm, 'sayHello')

    // [A] if I run the line below, vm.sayHello.callCount will be 0 - not as expected
    vm.$el.querySelector('h2').click()

    // [B] if I run the line below, vm.sayHello.callCount will be 1 - as expected
    // vm.sayHello()

    // vm.sayHello.callCount will be 0 or 1, depending on
    //    what line I execute ([A] or [B]),
    //    even if in both cases sayHello method is really executed
    console.log('###', vm.sayHello.callCount)
  })
})
```

When I programmatically click the html tag (using vm.$el.querySelector('h2').click()), spy won't capture the execution of the method sayHello, thus vm.sayHello.callCount will be 0. Not what I like.

But, if I directly call sayHello (using vm.sayHello()), vm.sayHello.callCount will be 1. As I expect.

How can I make spy capture the call of sayHello (so that vm.sayHello.callCount will be 1), if I want to simulate the click on the html tag (vm.$el.querySelector('h2').click()), and not directly calling sayHello (no vm.sayHello())?

Thanks

答:
The problem here is that callback is being bound to the event when the component is mounted. I'm not sure exactly how it works in the background but it's like its a copy of the sayHello method within the click event scope. You can't modify it after it has been bound.

You are creating the spy after that on the components method. They act the same but they are not. One is a spy and one is not.

wrapper.vm.sayHello() executes the method (spied on)
wrapper.find('h2').trigger('click') executes the callback (not spied on)

Create the spy on the component Class before mounting rather than the instance afterwards and it should work as expected.

```<code>it('should handle click on h2 tag - vue-test-utils + dummy click version', () =>     {
    const clickSpy = sinon.spy(Hello.methods, 'sayHello')
    const wrapper = mount(Hello)
    ...
})
</code>```

Body:
The basic setup that I've done in order to describe my problem:

Using vue-cli 2.8.2, I generated a new project based on webpack template (vue init webpack vue-test-sinon-spy) keeping all the defaults of vue-cli (with the irrelevant exception of disabling eslint).

Changes done in this vue-cli generated project:

I attached an event on h2 tag from Hello.vue:

Essential Links

I added a method in Hello component

I added a new test in Hello.spec.js

describe('Hello.vue', () => {
  // ...

  it('should handle click on h2 tag', () => {
    const Constructor = Vue.extend(Hello)
    const vm = new Constructor().$mount()
    sinon.spy(vm, 'sayHello')

    // [A] if I run the line below, vm.sayHello.callCount will be 0 - not as expected
    vm.$el.querySelector('h2').click()

    // [B] if I run the line below, vm.sayHello.callCount will be 1 - as expected
    // vm.sayHello()

    // vm.sayHello.callCount will be 0 or 1, depending on
    //    what line I execute ([A] or [B]),
    //    even if in both cases sayHello method is really executed
    console.log('###', vm.sayHello.callCount)
  })
})

When I programmatically click the html tag (using vm.$el.querySelector('h2').click()), spy won't capture the execution of the method sayHello, thus vm.sayHello.callCount will be 0. Not what I like.

But, if I directly call sayHello (using vm.sayHello()), vm.sayHello.callCount will be 1. As I expect.

How can I make spy capture the call of sayHello (so that vm.sayHello.callCount will be 1), if I want to simulate the click on the html tag (vm.$el.querySelector('h2').click()), and not directly calling sayHello (no vm.sayHello())?

Thanks

Body:
The problem here is that callback is being bound to the event when the component is mounted. I'm not sure exactly how it works in the background but it's like its a copy of the sayHello method within the click event scope. You can't modify it after it has been bound.

You are creating the spy after that on the components method. They act the same but they are not. One is a spy and one is not.

wrapper.vm.sayHello() executes the method (spied on)
wrapper.find('h2').trigger('click') executes the callback (not spied on)

Create the spy on the component Class before mounting rather than the instance afterwards and it should work as expected.

it('should handle click on h2 tag - vue-test-utils + dummy click version', () =>     {
    const clickSpy = sinon.spy(Hello.methods, 'sayHello')
    const wrapper = mount(Hello)
    ...
})


问:
merging tweets by date
I hope this is not to basic a question,
I have a dataframe of tweets (in R).
My aim is to calculate the sentiment by date.

I would be so grateful if anyone would advise me,
how to concatenate tweets tweet$text by date, where
each observation becomes a string of merged tweets/text

For example, if I had:

```<code>Created_Date       Tweet

2014-01-04         "the iphone is magnificent"

2014-01-04         "the iphone's screen is poor"

2014-01-04         "I will always use Apple products"

2014-01-03         "iphone is overpriced, but I love it"

2014-01-03         "Siri is very sluggish"

2014-01-03         "iphone's maps app is poor compared to Android"
</code>```

I would like a loop/function to merge the tweets by Created_Date
resulting in something like this

```<code>Created_Date       Tweet

2014-01-04         "the iphone is magnificent", "the iphone's screen is poor",              "I will always use Apple products"

2014-01-03         "iphone is overpriced, but I love it", "Siri is very sluggish", "iphone's maps app is poor compared to Android"
</code>```

Here are my data

```<code> dat <-   structure(list(Created_Date = structure(c(1388793600, 1388793600,
    1388793600, 1388707200, 1388707200, 1388707200), class = c("POSIXct",
    "POSIXt"), tzone = "UTC"), Tweet = c("the iphone is magnificent",
    "the iphone's screen is poor", "I will always use Apple products",
    "iphone is overpriced, but I love it", "Siri is very sluggish",
    "iphone's maps app is poor compared to Android")), .Names = c("Created_Date",
    "Tweet"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
    -6L))
</code>```

答:
If you are using the corpus library, then you can use the group argument to term_counts or term_matrix to aggregate (sum) by date.

In your case, if you are interested in counting the number of positive, negative, and neutral words, you can first create a "stemmer" that maps  words to these categories:

```<code>library(corpus)
# map terms in the AFINN dictionary to Positive/Negative; others to Neutral
stem_sent <- new_stemmer(sentiment_afinn$term,
                         ifelse(sentiment_afinn$score > 0, "Positive", "Negative"),
                         default = "Neutral")
</code>```

Then, you can use this as a stemmer and get the counts by group:

```<code>term_counts(dat$Tweet, group = dat$Created_Date, stemmer = stem_sent)
##   group      term     count
## 1 2014-01-03 Negative     2
## 2 2014-01-04 Negative     1
## 3 2014-01-03 Neutral     17
## 4 2014-01-04 Neutral     14
## 5 2014-01-03 Positive     1
</code>```

Or get a matrix of counts:

```<code>term_matrix(dat$Tweet, group = dat$Created_Date, stemmer = stem_sent)
## 2 x 3 sparse Matrix of class "dgCMatrix"
##            Negative Neutral Positive
## 2014-01-03        2      17        1
## 2014-01-04        1      14        .
</code>```

Title: merging tweets by date

Body:
I hope this is not to basic a question,
I have a dataframe of tweets (in R).
My aim is to calculate the sentiment by date.

I would be so grateful if anyone would advise me,
how to concatenate tweets tweet$text by date, where
each observation becomes a string of merged tweets/text

For example, if I had:

Created_Date       Tweet

2014-01-04         "the iphone is magnificent"

2014-01-04         "the iphone's screen is poor"

2014-01-04         "I will always use Apple products"

2014-01-03         "iphone is overpriced, but I love it"

2014-01-03         "Siri is very sluggish"

2014-01-03         "iphone's maps app is poor compared to Android"

I would like a loop/function to merge the tweets by Created_Date
resulting in something like this

Created_Date       Tweet

2014-01-04         "the iphone is magnificent", "the iphone's screen is poor",              "I will always use Apple products"

2014-01-03         "iphone is overpriced, but I love it", "Siri is very sluggish", "iphone's maps app is poor compared to Android"

Here are my data

 dat <-   structure(list(Created_Date = structure(c(1388793600, 1388793600,
    1388793600, 1388707200, 1388707200, 1388707200), class = c("POSIXct",
    "POSIXt"), tzone = "UTC"), Tweet = c("the iphone is magnificent",
    "the iphone's screen is poor", "I will always use Apple products",
    "iphone is overpriced, but I love it", "Siri is very sluggish",
    "iphone's maps app is poor compared to Android")), .Names = c("Created_Date",
    "Tweet"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
    -6L))

Body:
If you are using the corpus library, then you can use the group argument to term_counts or term_matrix to aggregate (sum) by date.

In your case, if you are interested in counting the number of positive, negative, and neutral words, you can first create a "stemmer" that maps  words to these categories:

library(corpus)
# map terms in the AFINN dictionary to Positive/Negative; others to Neutral
stem_sent <- new_stemmer(sentiment_afinn$term,
                         ifelse(sentiment_afinn$score > 0, "Positive", "Negative"),
                         default = "Neutral")

Then, you can use this as a stemmer and get the counts by group:

term_counts(dat$Tweet, group = dat$Created_Date, stemmer = stem_sent)
##   group      term     count
## 1 2014-01-03 Negative     2
## 2 2014-01-04 Negative     1
## 3 2014-01-03 Neutral     17
## 4 2014-01-04 Neutral     14
## 5 2014-01-03 Positive     1

Or get a matrix of counts:

term_matrix(dat$Tweet, group = dat$Created_Date, stemmer = stem_sent)
## 2 x 3 sparse Matrix of class "dgCMatrix"
##            Negative Neutral Positive
## 2014-01-03        2      17        1
## 2014-01-04        1      14        .


问:
day instead of month is saved in db when updating cell in gridview in webforms
When I try to save the new value in a gridview's cell (it is asp.net - webforms) - the date - it is saved in a wrong way - day is set to month and month is set to day in databae after updating.
This is a the line of binding the field in gridview:

```<code><asp:BoundField HeaderText="Date" DataField="AcDate" DataFormatString="{0:dd-MM-yyyy HH:mm:ss}" ApplyFormatInEditMode="true" htmlencode="False" SortExpression="AcDate" />
</code>```

For example there was 05-04-2013 17:00:00 before updating. After updating (without making any changes manually - just entering the edit mode and saving after that) - 04-05-2013 17:00:00
What is the problem?

答:
I think this issue is being caused by the DataFormatString attribute. If I understood your question correctly, the input date is in the format month-day-year, and then, after updating, it converts the date to day-month-year format correct?

If this is the case, you can fix this issue by changing the value of the DataFormatString attribute to the following:

DataFormatString="{0:MM-dd-yyyy HH:mm:ss}"

See this link for more information on .NET framework DateTime format strings and this link for more information about the BoundField.DataFormatString attribute.

Body:
When I try to save the new value in a gridview's cell (it is asp.net - webforms) - the date - it is saved in a wrong way - day is set to month and month is set to day in databae after updating.
This is a the line of binding the field in gridview:

<asp:BoundField HeaderText="Date" DataField="AcDate" DataFormatString="{0:dd-MM-yyyy HH:mm:ss}" ApplyFormatInEditMode="true" htmlencode="False" SortExpression="AcDate" />

For example there was 05-04-2013 17:00:00 before updating. After updating (without making any changes manually - just entering the edit mode and saving after that) - 04-05-2013 17:00:00
What is the problem?


问:
Jar file run on a server background with close putty session
I have tried the run spring boot jar file using putty. but the problem is after closed the putty session service was stopped. </p>

答:
then i tried up the jar file with following command. its working fine .

**nohup java -jar /web/server.jar **

ContentLicense: CC BY-SA 4.0


问:
Auto add a coupon discount only when cart items are from 3 different product categories
IN WooCommerce I would like to add 10% of discount with WooCommerce Coupon feature, only when customer purchases products from 3 different product categories (like Category1, Category2, Category3).

How this can be done with WooCommerce Coupon feature?

Any help on this will be appreciated.

Update note: I only 3 parent product categories with no sub categories. Each product is assigned to one category. Some products are variable and some others are simple.

答:
To handle this functionality with a coupon you will need to have one product category by product or one parent category by product, because a product can have many categories and subcategories set for it.

This custom function will add a coupon discount when cart items are from 3 different product categories. If cart items are removed from cart and there is not anymore 3 different product categories, the coupon code will be auto removed.

Also you will need to set in the function the coupon code name and an array of all your matching product categories IDs.

Here is the code:

```<code>add_action( 'woocommerce_before_calculate_totals', 'add_discount_for_3_diff_cats', 10, 1 );
function add_discount_for_3_diff_cats( $wc_cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // HERE set your coupon code and your parent product categories in the array
    $coupon_code_to_apply = 'summer';
    // HERE define your product categories IDs in the array
    $your_categories = array( 11, 13, 14 ); // IDs

    // If coupon is already set
    if( $wc_cart->has_discount( $coupon_code_to_apply ) )
        $has_coupon = true;

    foreach( $wc_cart->get_cart() as $cart_item ) {
        $product_id = $cart_item['product_id'];
        $product = wc_get_product($product_id);
        foreach( $product->get_category_ids() as $category_id ) {
            if( has_term( $your_categories, 'product_cat', $product_id ) && in_array( $category_id, $your_categories ) ){
                // Set the categories in an array (avoiding duplicates)
                $categories[$category_id] = $category_id;
            }
        }
    }

    $count_cats = count($categories);
    $has_discount = $wc_cart->has_discount( $coupon_code_to_apply );

    if ( 3 <= $count_cats && ! $has_discount ) {
        $wc_cart->add_discount($coupon_code_to_apply);
    } elseif ( 3 > $count_cats && $has_discount ) {
        $wc_cart->remove_coupon($coupon_code_to_apply);
    }
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works with simple and variable products…

Body:
To handle this functionality with a coupon you will need to have one product category by product or one parent category by product, because a product can have many categories and subcategories set for it.

This custom function will add a coupon discount when cart items are from 3 different product categories. If cart items are removed from cart and there is not anymore 3 different product categories, the coupon code will be auto removed.

Also you will need to set in the function the coupon code name and an array of all your matching product categories IDs.

Here is the code:

add_action( 'woocommerce_before_calculate_totals', 'add_discount_for_3_diff_cats', 10, 1 );
function add_discount_for_3_diff_cats( $wc_cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // HERE set your coupon code and your parent product categories in the array
    $coupon_code_to_apply = 'summer';
    // HERE define your product categories IDs in the array
    $your_categories = array( 11, 13, 14 ); // IDs

    // If coupon is already set
    if( $wc_cart->has_discount( $coupon_code_to_apply ) )
        $has_coupon = true;

    foreach( $wc_cart->get_cart() as $cart_item ) {
        $product_id = $cart_item['product_id'];
        $product = wc_get_product($product_id);
        foreach( $product->get_category_ids() as $category_id ) {
            if( has_term( $your_categories, 'product_cat', $product_id ) && in_array( $category_id, $your_categories ) ){
                // Set the categories in an array (avoiding duplicates)
                $categories[$category_id] = $category_id;
            }
        }
    }

    $count_cats = count($categories);
    $has_discount = $wc_cart->has_discount( $coupon_code_to_apply );

    if ( 3 <= $count_cats && ! $has_discount ) {
        $wc_cart->add_discount($coupon_code_to_apply);
    } elseif ( 3 > $count_cats && $has_discount ) {
        $wc_cart->remove_coupon($coupon_code_to_apply);
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works with simple and variable products…


问:
Is storing configurations in vuex store a good practice?
Is storing configurations in vuex store a good practice?</p>

```<code>export default {
  state: {
    app: {
      name: 'A project using vuex'
    }
  }
}
</code>```

答: Well, to some extent, it could be, but it really depends on what you're trying to do, Vuex should not be used in the first place in smaller applications, but if you are going for making a medium to large sized application, it is more than just good practice and can make it much easier and the code much cleaner, so, yes, to some extent.</p>

Body:
Is storing configurations in vuex store a good practice?

export default {
  state: {
    app: {
      name: 'A project using vuex'
    }
  }
}


问:
Authentification NodeJS Sequelize Express
I'm trying implement NodeJS authentification with express, sequelize, and mysql, but i'm blocked. I get login and password values by webservice. I want to match them with database value :

```<code>app.get('/login', function (req, res, err) {
    var whereUser = {
        login: req.query.login,
        password: req.query.password
    }

    if (!req.query.login || !req.query.password) {
        res.send('login failed');
//Here my code is wrong !
I try to compare login and password values with database login and passwword values
            } else if (req.query.login && req.query.password == UsrPerson.findOne({ where: whereUser })) {
                console.log("auth ok")
                req.session.user = "amy";
                req.session.admin = true;
                res.send("login success!");
            } else {
                console.log("ERROR")
                res.send(err)
            }
        });
</code>```

How can I do that ? Thank you

答:
The findOne method from sequelize return an instance object of the model.
that means than you can't compare a password to an instance.

The second problem is the findOne method is asynchronous, you  need to await it and have an async method.

```<code>app.get('/login', async function (req, res, err) {
    var whereUser = {
        login: req.query.login,
        password: req.query.password
    }

   if (!req.query.login || !req.query.password) {
       res.send('login failed');
    } else {
        // The following code return an instance of the user if it was found.
       const user = await UsrPerson.findOne({ where: whereUser }))

       // If the user was not found that means the credentials was wrong.
       if (user) {
           console.log("auth ok")
           req.session.user = "amy";
           req.session.admin = true;
           res.send("login success!");
       } else {
           console.log("ERROR")
           res.send(err)
       }
   }
});
</code>```

Body:
I'm trying implement NodeJS authentification with express, sequelize, and mysql, but i'm blocked. I get login and password values by webservice. I want to match them with database value :

app.get('/login', function (req, res, err) {
    var whereUser = {
        login: req.query.login,
        password: req.query.password
    }

    if (!req.query.login || !req.query.password) {
        res.send('login failed');
//Here my code is wrong !
I try to compare login and password values with database login and passwword values
            } else if (req.query.login && req.query.password == UsrPerson.findOne({ where: whereUser })) {
                console.log("auth ok")
                req.session.user = "amy";
                req.session.admin = true;
                res.send("login success!");
            } else {
                console.log("ERROR")
                res.send(err)
            }
        });

How can I do that ? Thank you

Body:
The findOne method from sequelize return an instance object of the model.
that means than you can't compare a password to an instance.

The second problem is the findOne method is asynchronous, you  need to await it and have an async method.

app.get('/login', async function (req, res, err) {
    var whereUser = {
        login: req.query.login,
        password: req.query.password
    }

   if (!req.query.login || !req.query.password) {
       res.send('login failed');
    } else {
        // The following code return an instance of the user if it was found.
       const user = await UsrPerson.findOne({ where: whereUser }))

       // If the user was not found that means the credentials was wrong.
       if (user) {
           console.log("auth ok")
           req.session.user = "amy";
           req.session.admin = true;
           res.send("login success!");
       } else {
           console.log("ERROR")
           res.send(err)
       }
   }
});


问:
can anyone explain how can we make a universal software updates checker?
I need only all possible suggestions preferably using java or python, I tried doing it by creating a database of all possible software.
But it was not an efficient solution.
any suggestions?</p>

答:
I would strongly suggest to use your OS's package manager and distribution format (i.e: apt and deb packages on Debian/Ubuntu; yum and rpm on RedHat/CentOS). Adding a private repository if needed.

If you are using Windows or OSX you could use some of the de-facto package managers like Chocolatey and Brew.

For instance, Chocolatey Package Updater is a solution to update packages automatically.


问:
Plot won't show in Jupyter
I'm new to python and I began to teach myself how to use pandas on jupyter using the exercise from this link:

http://nbviewer.jupyter.org/github/jvns/pandas-cookbook/blob/v0.1/cookbook/Chapter%201%20-%20Reading%20from%20a%20CSV.ipynb

I have the problem that the plot at 1.3 won't appear when I do it in Jupyter, I only get the following output:

```<code>matplotlib.axes._subplots.AxesSubplot at 0x8ad24a8>"
</code>```

However it does appear when I run the same code in Spyder. Does anyone know why this is?  This is my code:

```<code> import pandas as pd
import os
fixed_df = pd.read_csv('bikes.csv', sep=';', encoding='latin1', parse_dates=['Date'], dayfirst=True, index_col='Date')
fixed_df['Berri1'].plot()
</code>```

答:
add the code below before your plots:</p>

```<code>%matplotlib inline
</code>```

Title: Plot won't show in Jupyter

Body:
I'm new to python and I began to teach myself how to use pandas on jupyter using the exercise from this link:

http://nbviewer.jupyter.org/github/jvns/pandas-cookbook/blob/v0.1/cookbook/Chapter%201%20-%20Reading%20from%20a%20CSV.ipynb

I have the problem that the plot at 1.3 won't appear when I do it in Jupyter, I only get the following output:

matplotlib.axes._subplots.AxesSubplot at 0x8ad24a8>"

However it does appear when I run the same code in Spyder. Does anyone know why this is?  This is my code:

 import pandas as pd
import os
fixed_df = pd.read_csv('bikes.csv', sep=';', encoding='latin1', parse_dates=['Date'], dayfirst=True, index_col='Date')
fixed_df['Berri1'].plot()

Body:
add the code below before your plots:

%matplotlib inline


问:
Where to get comparing list of papervision3d vs Away3d?
So I know that PV3d looks quite dead. But it is documented over the internet much better. So I decided to develope my product using old but good PV3d engine. Time goes on so I plan to port it sooner or later to Away3d. So I need a list of things that aere not in Away3d that I have in PV3d. And a list of generall use diffrencies (use of cameras, viewports, etc). So where to get comparing list of papervision3d vs Away3d, or could any one please write it down here?</p>

答:
I would advise against this. Away3d was a fork of PV3D and there are a lot of similarities, but it looks like pv3d is dead, while we know for sure that Away3d is working on the molehill beta to create the new version. Once that comes out you might be wishing you would have gone with Away3d. There is also Alternativa and flare3D that are also working with molehill, but away3d is easier to start if you've worked with PV3d

http://www.bytearray.org/?p=2310

anyway, that's my $0.02

ContentLicense: CC BY-SA 2.5


问:
Questions re: Gmail Sidebar Gadget Deprecation
We stumbled across a deprecation notice for the Gmail sidebar gadgets at https://developers.google.com/gmail/sidebar_gadgets which states that

Warning: Gmail sidebar gadgets are now deprecated and will soon cease to be supported.

This statement and the website are unclear and we cannot find any deprecation notice with specific dates and impact.

Additionally, since the add gadget by URL lab was deprecated, most of this page can't be used anyway.

However, we deployed a gadget via the marketplace which is crucial to our operation of Google Apps because of the Google Apps 50K contacts limit.

I've submitted a ticket to the GWSC with the following questions but I figured I would mention it here as well since we are a bit shocked to have stumbled on this notice and that it hasn't been shared via any channels we have found.  Perhaps I missed it?

Does this sidebar_gadget deprecation apply to marketplace apps such as the one USAID wrote and is using?

Can you please point me to the official deprecation notice and especially the date of impact?

What will be replacing the sidebar gadget as this is an integral part of our day to day use of Google Apps?

Any input appreciated as I'm specifically worried that Google did not anticipate people doing things with sidebar in marketplace apps and when they took away the gadget by URL lab, they thought they killed the only avenue to using these gadgets.  Hopefully, I'm worried for naught and marketplace apps are fine but...

Regards,
KAM

答:
Google usually perform spring-cleanings. Usually announces around march-april which features will be removed, and by july-august performs removal. However marking a feature as deprecated does not necesarilly mean immediate removal.

Also, maybe this is related to Google G-suite marketplace: https://gsuite.google.com/marketplace/

BTW: in any situation, combine something that "is crucial to our operation" and something that depends on a closed SaaS or cloud plattform it's usually not a good idea, except if your data/services/developments can be moved to other platformS.


问:
Why do I get TypeError: $.ajax is not a function when I make an Ajax Request?
I'm building an application and when I make an Ajax request to the server I get the following error:

TypeError: $.ajax is not a function

I checked online and especially on Stackoverflow, discovering a lot of questions asked by people with my same problem but none of the accepted answers solved my problem:

I have a not slim version of jQuery included in my HTML

I included the jQuery's source file before the inclusion of the javascript which contains my function

I think there's no mistake in parentheses, as in some of the questions

This is how I have included jQuery:

```<code><script src="./src/jquery-3.2.1.js"> type="text/javascript"</script>
</code>```

I attach part of the code for clarity:

```<code>function verifyUsername(success, error) {
  console.log("start check complete");
  $.ajax({
    type: "POST",
    url: '/username',
    contentType: 'application/json',
    data: JSON.stringify({
      username: document.getElementById("username").value
    }),
    done: /*success*/ alert("OK"),
    fail: /*error*/ alert("NO")
  });
}

function verifyBirthPlace(success, error) {
  console.log("pl check complete");
  $.ajax({
    type: "POST",
    url: '/birthplace',
    contentType: 'application/json',
    data: JSON.stringify({
      birthplace_provincia: document.getElementById("birthProvince").value,
      birthplace: document.getElementById("birthTown").value
    }),
    done: success,
    fail: error
  });
}

function checkRegistration() {

  verifyUsername(
    verifyBirthPlace(
      function() {

        if (checkPwdStrenght() == false || comparePwds() == false || checkDate() == false || checkTaxCode() == false) {
          console.log("f")
          return false;
        } else {
          console.log("t")
          return true;
        }
      },
      function(data) {
        console.log("error from place" + data);
      })

    ,
    function(data) {
      console.log("ERROR from user" + data);
    });
}
</code>```

For now I have only console logs instead of the real behaviour of the functions because I'm still stuck with the Ajax error. checkRegistration() is called on click in the HTML:

```<code><button class="btn btn-primary" id="subSignUp" onclick="checkRegistration()">Submit</button>
</code>```

Any Ideas?

答:
The function needs to self-invoke, for some reason. That is: </p>

```<code>(function($) {
    $.ajax(/* etc. */)
})(jQuery);
</code>```

Body:
I'm building an application and when I make an Ajax request to the server I get the following error:

TypeError: $.ajax is not a function

I checked online and especially on Stackoverflow, discovering a lot of questions asked by people with my same problem but none of the accepted answers solved my problem:

I have a not slim version of jQuery included in my HTML

I included the jQuery's source file before the inclusion of the javascript which contains my function

I think there's no mistake in parentheses, as in some of the questions

This is how I have included jQuery:

I attach part of the code for clarity:

function verifyUsername(success, error) {
  console.log("start check complete");
  $.ajax({
    type: "POST",
    url: '/username',
    contentType: 'application/json',
    data: JSON.stringify({
      username: document.getElementById("username").value
    }),
    done: /*success*/ alert("OK"),
    fail: /*error*/ alert("NO")
  });
}

function verifyBirthPlace(success, error) {
  console.log("pl check complete");
  $.ajax({
    type: "POST",
    url: '/birthplace',
    contentType: 'application/json',
    data: JSON.stringify({
      birthplace_provincia: document.getElementById("birthProvince").value,
      birthplace: document.getElementById("birthTown").value
    }),
    done: success,
    fail: error
  });
}

function checkRegistration() {

  verifyUsername(
    verifyBirthPlace(
      function() {

        if (checkPwdStrenght() == false || comparePwds() == false || checkDate() == false || checkTaxCode() == false) {
          console.log("f")
          return false;
        } else {
          console.log("t")
          return true;
        }
      },
      function(data) {
        console.log("error from place" + data);
      })

    ,
    function(data) {
      console.log("ERROR from user" + data);
    });
}

For now I have only console logs instead of the real behaviour of the functions because I'm still stuck with the Ajax error. checkRegistration() is called on click in the HTML:

<button class="btn btn-primary" id="subSignUp" onclick="checkRegistration()">Submit</button>

Any Ideas?

Body:
The function needs to self-invoke, for some reason. That is:

(function($) {
    $.ajax(/* etc. */)
})(jQuery);


问:
RestTemplate not working with S3 pre-signed put URLs
I have a server generate AWS S3 pre-signed PUT URLs and then I'm trying to uploading a byte[] into that URL using RestTemplate with this code:

```<code>RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.ALL));
HttpEntity<byte[]> entity = new HttpEntity<>("Testing testing testing".getBytes(), headers);
System.out.println(restTemplate.exchange(putUrl, HttpMethod.PUT, entity, String.class));
</code>```

When I run that code, I get this error:

```<code>Exception in thread "JavaFX Application Thread" org.springframework.web.client.HttpClientErrorException: 400 Bad Request
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:531)
    at tech.dashman.dashman.controllers.RendererAppController.lambda$null$2(RendererAppController.java:95)
</code>```

Unfortunately, there's nothing in the AWS S3 logs, so, I'm not sure what's going on. If I take that exact same URL and put it in the REST Client of IntelliJ IDEA, it just works (it creates an empty file in S3).

Any ideas what's wrong with my Java code?

Here's a full example that does the signing and tries to uploading a small payload to S3:

```<code>import com.amazonaws.HttpMethod;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import org.joda.time.DateTime;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;
import java.util.Date;

public class S3PutIssue {
    static public void main(String[] args) {
        String awsAccessKeyId = "";
        String awsSecretKey = "";
        String awsRegion = "";
        String path = "";
        String awsBucketName = "";
        BasicAWSCredentials awsCredentials = new BasicAWSCredentials(awsAccessKeyId, awsSecretKey);
        AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(awsRegion).
                withCredentials(new AWSStaticCredentialsProvider(awsCredentials)).build();
        Date expiration = new DateTime().plusDays(1).toDate();
        GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(awsBucketName, path);
        urlRequest.setMethod(HttpMethod.PUT);
        urlRequest.setExpiration(expiration);
        String putUrl = s3Client.generatePresignedUrl(urlRequest).toString();

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<byte[]> entity = new HttpEntity<>("Testing testing testing".getBytes(), headers);
        restTemplate.exchange(putUrl, org.springframework.http.HttpMethod.PUT, entity, Void.class);
    }
}
</code>```

答:
The source of issue is a double encoding of url characters. There are / in extended secret key which are encoded as %2 by s3Client.generatePresignedUrl. When already encoded string is passed to restTemplate.exchange it's internally converted to URI and encoded for the second time as %252 by UriTemplateHandler in RestTemplate source code.

```<code>@Override
@Nullable
public <T> T execute(String url, HttpMethod method, @Nullable RequestCallback requestCallback,
        @Nullable ResponseExtractor<T> responseExtractor, Object... uriVariables) throws RestClientException {

    URI expanded = getUriTemplateHandler().expand(url, uriVariables);
    return doExecute(expanded, method, requestCallback, responseExtractor);
}
</code>```

So the easiest solution is to convert URL to URI using URL.toURI(). If you don't have URI and have String when RestTemplate is invoked then two options are possible.

Pass URI instead for string to exchange method.

```<code>restTemplate.exchange(new URI(putUrl.toString()), HttpMethod.PUT, entity, Void.class);
</code>```

Create default UriTemplateHandler with NONE encoding mode and pass it to RestTemplate.

```<code>DefaultUriBuilderFactory defaultUriBuilderFactory = new DefaultUriBuilderFactory();
defaultUriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE);
restTemplate.setUriTemplateHandler(defaultUriBuilderFactory);
restTemplate.exchange(putUrl.toString(), org.springframework.http.HttpMethod.PUT, entity, Void.class);
</code>```

Body:
I have a server generate AWS S3 pre-signed PUT URLs and then I'm trying to uploading a byte[] into that URL using RestTemplate with this code:

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.ALL));
HttpEntity<byte[]> entity = new HttpEntity<>("Testing testing testing".getBytes(), headers);
System.out.println(restTemplate.exchange(putUrl, HttpMethod.PUT, entity, String.class));

When I run that code, I get this error:

Exception in thread "JavaFX Application Thread" org.springframework.web.client.HttpClientErrorException: 400 Bad Request
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:531)
    at tech.dashman.dashman.controllers.RendererAppController.lambda$null$2(RendererAppController.java:95)

Unfortunately, there's nothing in the AWS S3 logs, so, I'm not sure what's going on. If I take that exact same URL and put it in the REST Client of IntelliJ IDEA, it just works (it creates an empty file in S3).

Any ideas what's wrong with my Java code?

Here's a full example that does the signing and tries to uploading a small payload to S3:

import com.amazonaws.HttpMethod;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import org.joda.time.DateTime;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;
import java.util.Date;

public class S3PutIssue {
    static public void main(String[] args) {
        String awsAccessKeyId = "";
        String awsSecretKey = "";
        String awsRegion = "";
        String path = "";
        String awsBucketName = "";
        BasicAWSCredentials awsCredentials = new BasicAWSCredentials(awsAccessKeyId, awsSecretKey);
        AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(awsRegion).
                withCredentials(new AWSStaticCredentialsProvider(awsCredentials)).build();
        Date expiration = new DateTime().plusDays(1).toDate();
        GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(awsBucketName, path);
        urlRequest.setMethod(HttpMethod.PUT);
        urlRequest.setExpiration(expiration);
        String putUrl = s3Client.generatePresignedUrl(urlRequest).toString();

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<byte[]> entity = new HttpEntity<>("Testing testing testing".getBytes(), headers);
        restTemplate.exchange(putUrl, org.springframework.http.HttpMethod.PUT, entity, Void.class);
    }
}

Body:
The source of issue is a double encoding of url characters. There are / in extended secret key which are encoded as %2 by s3Client.generatePresignedUrl. When already encoded string is passed to restTemplate.exchange it's internally converted to URI and encoded for the second time as %252 by UriTemplateHandler in RestTemplate source code.

@Override
@Nullable
public <T> T execute(String url, HttpMethod method, @Nullable RequestCallback requestCallback,
        @Nullable ResponseExtractor<T> responseExtractor, Object... uriVariables) throws RestClientException {

    URI expanded = getUriTemplateHandler().expand(url, uriVariables);
    return doExecute(expanded, method, requestCallback, responseExtractor);
}

So the easiest solution is to convert URL to URI using URL.toURI(). If you don't have URI and have String when RestTemplate is invoked then two options are possible.

Pass URI instead for string to exchange method.

restTemplate.exchange(new URI(putUrl.toString()), HttpMethod.PUT, entity, Void.class);

Create default UriTemplateHandler with NONE encoding mode and pass it to RestTemplate.

DefaultUriBuilderFactory defaultUriBuilderFactory = new DefaultUriBuilderFactory();
defaultUriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE);
restTemplate.setUriTemplateHandler(defaultUriBuilderFactory);
restTemplate.exchange(putUrl.toString(), org.springframework.http.HttpMethod.PUT, entity, Void.class);


问:
Anybody ever used PayPal Website Payments Standard with SESSION variables?
Note: Our site is built in PHP and uses MySQL databases. I already manage another site with shopping cart in its entirety using Authorize.net so please dont respond with suggestions to use another provider. A new product/service we are releasing is classified as "High Risk" to the merchant providers and they want to charge us out the a**. In response, I figured setting up a Website Payments Standard account on Paypal.com was the best alternative for the following reasons:

1) no monthly charges, only pay for what is used

2) trust brand and people are comfortable with Paypal

The rates are quite a bit higher than we are used to but any High Risk Merchant account is so that is irrelevant. The issue I am running into is this:

1) throughout the registration process on our site, we collect quite a bit of user information and pass it from page to page using SESSION variables. When you use Website Payments Standard, you are forced to pass the consumer off to a Paypal owned webpage to submit their payment information. Upon successful completion, they are able to direct them back to a 'confirmation' page on our site but it is my understanding there is NO way to keep the old SESSION variables in tact. This is very important to us because the overall concept is to store the SESSION variables ONLY after successful payment has been made.

2) Using Website Payments Standard, I am unable to find a way to send a Pay-Amount variable (everything must be dictated up front, i.e. T-shirt is $2.99). Our site allows the consumer to enrollee multiple persons and have several 'add-ons' for each person so there are literally over 100 end check out amount possibilities. I am not sure if it is possible to override this.

Has ANYBODY had luck using Website Payments Standard on Paypal acknowledging the information above?

答:
I'm months too late for my answer... but I also had the same problem...losing sessions and cookies after redirection to the return url.

For those who will be encountering the same problem, here is the solution I came up with,

In the paypal form you add

```<code><input type='hidden' name='return' value='".http_dir."shop/return.php'>
<input type='hidden' name='custom' value='$session_id'>
</code>```

where $session_id = session_id( );

and in shop/return.php, I tested if it works with

```<code>echo '```';
print_r($_SESSION);
echo '```';

echo '```';
print_r($_COOKIE);
echo '```';

echo '```';
print_r($_GET);
echo '```';
</code>```

When you do not include 'custom' parameter in the form, it will return an empty array. It's crazy how just two lines change everything. I thought I was gonna repeat the whole shopping cart logic, oh boy.

Hope this would help someone in the future... Cheers^^

Source: WPS HTML Variables

Body:
I'm months too late for my answer... but I also had the same problem...losing sessions and cookies after redirection to the return url.

For those who will be encountering the same problem, here is the solution I came up with,

In the paypal form you add

<input type='hidden' name='return' value='".http_dir."shop/return.php'>
<input type='hidden' name='custom' value='$session_id'>

where $session_id = session_id( );

and in shop/return.php, I tested if it works with

echo '<pre>';
print_r($_SESSION);
echo '</pre>';

echo '<pre>';
print_r($_COOKIE);
echo '</pre>';

echo '<pre>';
print_r($_GET);
echo '</pre>';

When you do not include 'custom' parameter in the form, it will return an empty array. It's crazy how just two lines change everything. I thought I was gonna repeat the whole shopping cart logic, oh boy.

Hope this would help someone in the future... Cheers^^

Source: WPS HTML Variables


问:
How can I parse a string in JS which is the result of google location api?
Here is the result of ajax request:

```<code>console.log(locations.output);
/*
{
   "predictions" : [
      {
         "description" : "Tehran Province, Iran",
         "id" : "4c45c924b261e2bb262360fb5a25d4b9a94088a7",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJf5Us9YQBjj8R0OohvHQms1U",
         "reference" : "CjQtAAAA6j_9DtMr30DQ9h8dzemfD2NaWEWBgf5yFlQ92XW4EZvHXqZ8Ob6wGkedetO1xNiZEhCGeIk7jBXCQP_ad4V0R-YeGhSIcGtxcxPh-G4e2DMT97Be4xdfkg",
         "structured_formatting" : {
            "main_text" : "Tehran Province",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Province"
            },
            {
               "offset" : 17,
               "value" : "Iran"
            }
         ],
         "types" : [ "administrative_area_level_1", "political", "geocode" ]
      },
      {
         "description" : "Tehran, Tehran Province, Iran",
         "id" : "14788d031b564588682273730e2e16d2617d3548",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJ2dzzH0kAjj8RvCRwVnxps_A",
         "reference" : "CkQ1AAAAGXsNCFct3XK9JukMD-C7D7j1f0b-Rk0uBZFULZ9TKziZVKz2HWeNWZ5xWU-aNIceYEioJRxHmYS_O7DhMW32YBIQzGS_zTt6aijJx_onRU9DTRoU-cPuoOF16KrzlFY_4EGlwVf1Izk",
         "structured_formatting" : {
            "main_text" : "Tehran",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran"
            },
            {
               "offset" : 8,
               "value" : "Tehran Province"
            },
            {
               "offset" : 25,
               "value" : "Iran"
            }
         ],
         "types" : [ "locality", "political", "geocode" ]
      },
      {
         "description" : "Tehranpars, Tehran, Tehran Province, Iran",
         "id" : "09a979a1ac286c1ff2ee94c5d36258910d7f6ec6",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJX5PM9hwdjj8R6zn_mu5suoE",
         "reference" : "ClRBAAAACKbtLWiAm5kV0JzYtPOLhQTuMxlMMIXxPGRmuLUF7xuAlx7Mueo91OuJmB4mTwo3T0NhnNhamVDUsKFE0fNffkZi1Bv-ZQs1TcXLNx195C0SELOTSsOMn6pYeSnFMtvVqsIaFCxWipFk_wIxDKVoLi8Cd8g993cG",
         "structured_formatting" : {
            "main_text" : "Tehranpars",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehranpars"
            },
            {
               "offset" : 12,
               "value" : "Tehran"
            },
            {
               "offset" : 20,
               "value" : "Tehran Province"
            },
            {
               "offset" : 37,
               "value" : "Iran"
            }
         ],
         "types" : [ "neighborhood", "political", "geocode" ]
      },
      {
         "description" : "Tehran Now, Tehran, Tehran Province, Iran",
         "id" : "1f7583f258e7e92f03b818ba10c48e20d2bd9f59",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJ61k7RLICjj8RnvjuZpbZeEM",
         "reference" : "ClRBAAAAydlnsS8Fjw9ibBXXX-XS4xuY4-7yEqMSZNTz66Q-4hRNnGdEGyOICqFbm4VQ4-ZV7O8fftoznes6-u-6sZyvz8Gp3N3hPLASFvtoWeJBPS8SEE8pPnxD20v8_NPnWLANDG8aFPfquA7RBNHvpEgiH5Q0eIqmtl5k",
         "structured_formatting" : {
            "main_text" : "Tehran Now",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Now"
            },
            {
               "offset" : 12,
               "value" : "Tehran"
            },
            {
               "offset" : 20,
               "value" : "Tehran Province"
            },
            {
               "offset" : 37,
               "value" : "Iran"
            }
         ],
         "types" : [ "sublocality_level_1", "sublocality", "political", "geocode" ]
      },
      {
         "description" : "Tehran Bazaar, Tehran, Tehran Province, Iran",
         "id" : "7a97ba4c05dcb1b11c2153bd39673b6737aa5748",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJJX5my-8Bjj8RfAUG71zqw8s",
         "reference" : "ClREAAAABs4mvt65BUJ7Z2arVA_cv7V0tdPJKoVy010IOFrlS-L6VfhrEmIQAuxTXVQhnAA19fjEtVbPag3lfb-UrsmnMROnzvXiffA7MKUvgASMwvwSEGx-aGYRXyP1Q9Bxr7HmMVIaFKaxQEb8tg4L7IlRIbITWpG4F5Mf",
         "structured_formatting" : {
            "main_text" : "Tehran Bazaar",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Bazaar"
            },
            {
               "offset" : 15,
               "value" : "Tehran"
            },
            {
               "offset" : 23,
               "value" : "Tehran Province"
            },
            {
               "offset" : 40,
               "value" : "Iran"
            }
         ],
         "types" : [ "neighborhood", "political", "geocode" ]
      }
   ],
   "status" : "OK"
}
</code>```

Now I need to make an autocomplete list of the result. I mean I need to make such a thing:

```<code><ul>
  <li>Tehran Province, Iran</li>
  <li>Tehran, Tehran Province, Iran</li>
  <li>Tehranpars, Tehran, Tehran Province, Iran</li>
  <li>Tehran Bazaar, Tehran, Tehran Province, Iran</li>
</ul>
</code>```

But I don't know how can I select the value of description of the result. Here is my code:

```<code>var html = "<ul>";
$.each(locations.output, function (index, value) {
    console.log(value);
})
var html += "</ul>";

/*
"
p
r
e
d
.
.
.
</code>```

As you can see, the result is lots of single characters. How can I get that values?

答:
If the result is a JSON string, then you need to convert to a JSON object to iterate through. For demonstration purposes locations.output is equivalent to locationsJSONString in my snippet. See snippet and comments below.

JSfiddle link

var locationsJSONString = '{"predictions": [{"description": "Tehran Province, Iran","id": "4c45c924b261e2bb262360fb5a25d4b9a94088a7","matched_substrings": [{"length": 6,"offset": 0}],"place_id": "ChIJf5Us9YQBjj8R0OohvHQms1U","reference": "CjQtAAAA6j_9DtMr30DQ9h8dzemfD2NaWEWBgf5yFlQ92XW4EZvHXqZ8Ob6wGkedetO1xNiZEhCGeIk7jBXCQP_ad4V0R-YeGhSIcGtxcxPh-G4e2DMT97Be4xdfkg","structured_formatting": {"main_text": "Tehran Province","main_text_matched_substrings": [{"length": 6,"offset": 0}],"secondary_text": "Iran"},"terms": [{"offset": 0,"value": "Tehran Province"},{"offset": 17,"value": "Iran"}],"types": ["administrative_area_level_1", "political", "geocode"]},{"description": "Tehran, Tehran Province, Iran","id": "14788d031b564588682273730e2e16d2617d3548","matched_substrings": [{"length": 6,"offset": 0}],"place_id": "ChIJ2dzzH0kAjj8RvCRwVnxps_A","reference": "CkQ1AAAAGXsNCFct3XK9JukMD-C7D7j1f0b-Rk0uBZFULZ9TKziZVKz2HWeNWZ5xWU-aNIceYEioJRxHmYS_O7DhMW32YBIQzGS_zTt6aijJx_onRU9DTRoU-cPuoOF16KrzlFY_4EGlwVf1Izk","structured_formatting": {"main_text": "Tehran","main_text_matched_substrings": [{"length": 6,"offset": 0}],"secondary_text": "Tehran Province, Iran"},"terms": [{"offset": 0,"value": "Tehran"},{"offset": 8,"value": "Tehran Province"},{"offset": 25,"value": "Iran"}],"types": ["locality", "political", "geocode"]},{"description": "Tehranpars, Tehran, Tehran Province, Iran","id": "09a979a1ac286c1ff2ee94c5d36258910d7f6ec6","matched_substrings": [{"length": 6,"offset": 0}],"place_id": "ChIJX5PM9hwdjj8R6zn_mu5suoE","reference": "ClRBAAAACKbtLWiAm5kV0JzYtPOLhQTuMxlMMIXxPGRmuLUF7xuAlx7Mueo91OuJmB4mTwo3T0NhnNhamVDUsKFE0fNffkZi1Bv-ZQs1TcXLNx195C0SELOTSsOMn6pYeSnFMtvVqsIaFCxWipFk_wIxDKVoLi8Cd8g993cG","structured_formatting": {"main_text": "Tehranpars","main_text_matched_substrings": [{"length": 6,"offset": 0}],"secondary_text": "Tehran, Tehran Province, Iran"},"terms": [{"offset": 0,"value": "Tehranpars"},{"offset": 12,"value": "Tehran"},{"offset": 20,"value": "Tehran Province"},{"offset": 37,"value": "Iran"}],"types": ["neighborhood", "political", "geocode"]},{"description": "Tehran Now, Tehran, Tehran Province, Iran","id": "1f7583f258e7e92f03b818ba10c48e20d2bd9f59","matched_substrings": [{"length": 6,"offset": 0}],"place_id": "ChIJ61k7RLICjj8RnvjuZpbZeEM","reference": "ClRBAAAAydlnsS8Fjw9ibBXXX-XS4xuY4-7yEqMSZNTz66Q-4hRNnGdEGyOICqFbm4VQ4-ZV7O8fftoznes6-u-6sZyvz8Gp3N3hPLASFvtoWeJBPS8SEE8pPnxD20v8_NPnWLANDG8aFPfquA7RBNHvpEgiH5Q0eIqmtl5k","structured_formatting": {"main_text": "Tehran Now","main_text_matched_substrings": [{"length": 6,"offset": 0}],"secondary_text": "Tehran, Tehran Province, Iran"},"terms": [{"offset": 0,"value": "Tehran Now"},{"offset": 12,"value": "Tehran"},{"offset": 20,"value": "Tehran Province"},{"offset": 37,"value": "Iran"}],"types": ["sublocality_level_1", "sublocality", "political", "geocode"]},{"description": "Tehran Bazaar, Tehran, Tehran Province, Iran","id": "7a97ba4c05dcb1b11c2153bd39673b6737aa5748","matched_substrings": [{"length": 6,"offset": 0}],"place_id": "ChIJJX5my-8Bjj8RfAUG71zqw8s","reference": "ClREAAAABs4mvt65BUJ7Z2arVA_cv7V0tdPJKoVy010IOFrlS-L6VfhrEmIQAuxTXVQhnAA19fjEtVbPag3lfb-UrsmnMROnzvXiffA7MKUvgASMwvwSEGx-aGYRXyP1Q9Bxr7HmMVIaFKaxQEb8tg4L7IlRIbITWpG4F5Mf","structured_formatting": {"main_text": "Tehran Bazaar","main_text_matched_substrings": [{"length": 6,"offset": 0}],"secondary_text": "Tehran, Tehran Province, Iran"},"terms": [{"offset": 0,"value": "Tehran Bazaar"},{"offset": 15,"value": "Tehran"},{"offset": 23,"value": "Tehran Province"},{"offset": 40,"value": "Iran"}],"types": ["neighborhood", "political", "geocode"]}], "status": "OK"}';

// convert the JSON string into an object
var locationsJSONObj = JSON.parse(locationsJSONString);

// the results are stored in the "predictions" property of the object
// the value is an array which we assign to the variable below
// to iterate over
var locationsPredictionsArray = locationsJSONObj.predictions;

// format result in list element
var html = '
';

$.each(locationsPredictionsArray, function (index, value) {
 // add item for each location description
  html += '
' + value.description + '
';
});
html += '
';

$('#output').html(html); // show output in html element```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div></code>```

Body:
Here is the result of ajax request:

console.log(locations.output);
/*
{
   "predictions" : [
      {
         "description" : "Tehran Province, Iran",
         "id" : "4c45c924b261e2bb262360fb5a25d4b9a94088a7",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJf5Us9YQBjj8R0OohvHQms1U",
         "reference" : "CjQtAAAA6j_9DtMr30DQ9h8dzemfD2NaWEWBgf5yFlQ92XW4EZvHXqZ8Ob6wGkedetO1xNiZEhCGeIk7jBXCQP_ad4V0R-YeGhSIcGtxcxPh-G4e2DMT97Be4xdfkg",
         "structured_formatting" : {
            "main_text" : "Tehran Province",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Province"
            },
            {
               "offset" : 17,
               "value" : "Iran"
            }
         ],
         "types" : [ "administrative_area_level_1", "political", "geocode" ]
      },
      {
         "description" : "Tehran, Tehran Province, Iran",
         "id" : "14788d031b564588682273730e2e16d2617d3548",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJ2dzzH0kAjj8RvCRwVnxps_A",
         "reference" : "CkQ1AAAAGXsNCFct3XK9JukMD-C7D7j1f0b-Rk0uBZFULZ9TKziZVKz2HWeNWZ5xWU-aNIceYEioJRxHmYS_O7DhMW32YBIQzGS_zTt6aijJx_onRU9DTRoU-cPuoOF16KrzlFY_4EGlwVf1Izk",
         "structured_formatting" : {
            "main_text" : "Tehran",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran"
            },
            {
               "offset" : 8,
               "value" : "Tehran Province"
            },
            {
               "offset" : 25,
               "value" : "Iran"
            }
         ],
         "types" : [ "locality", "political", "geocode" ]
      },
      {
         "description" : "Tehranpars, Tehran, Tehran Province, Iran",
         "id" : "09a979a1ac286c1ff2ee94c5d36258910d7f6ec6",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJX5PM9hwdjj8R6zn_mu5suoE",
         "reference" : "ClRBAAAACKbtLWiAm5kV0JzYtPOLhQTuMxlMMIXxPGRmuLUF7xuAlx7Mueo91OuJmB4mTwo3T0NhnNhamVDUsKFE0fNffkZi1Bv-ZQs1TcXLNx195C0SELOTSsOMn6pYeSnFMtvVqsIaFCxWipFk_wIxDKVoLi8Cd8g993cG",
         "structured_formatting" : {
            "main_text" : "Tehranpars",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehranpars"
            },
            {
               "offset" : 12,
               "value" : "Tehran"
            },
            {
               "offset" : 20,
               "value" : "Tehran Province"
            },
            {
               "offset" : 37,
               "value" : "Iran"
            }
         ],
         "types" : [ "neighborhood", "political", "geocode" ]
      },
      {
         "description" : "Tehran Now, Tehran, Tehran Province, Iran",
         "id" : "1f7583f258e7e92f03b818ba10c48e20d2bd9f59",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJ61k7RLICjj8RnvjuZpbZeEM",
         "reference" : "ClRBAAAAydlnsS8Fjw9ibBXXX-XS4xuY4-7yEqMSZNTz66Q-4hRNnGdEGyOICqFbm4VQ4-ZV7O8fftoznes6-u-6sZyvz8Gp3N3hPLASFvtoWeJBPS8SEE8pPnxD20v8_NPnWLANDG8aFPfquA7RBNHvpEgiH5Q0eIqmtl5k",
         "structured_formatting" : {
            "main_text" : "Tehran Now",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Now"
            },
            {
               "offset" : 12,
               "value" : "Tehran"
            },
            {
               "offset" : 20,
               "value" : "Tehran Province"
            },
            {
               "offset" : 37,
               "value" : "Iran"
            }
         ],
         "types" : [ "sublocality_level_1", "sublocality", "political", "geocode" ]
      },
      {
         "description" : "Tehran Bazaar, Tehran, Tehran Province, Iran",
         "id" : "7a97ba4c05dcb1b11c2153bd39673b6737aa5748",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJJX5my-8Bjj8RfAUG71zqw8s",
         "reference" : "ClREAAAABs4mvt65BUJ7Z2arVA_cv7V0tdPJKoVy010IOFrlS-L6VfhrEmIQAuxTXVQhnAA19fjEtVbPag3lfb-UrsmnMROnzvXiffA7MKUvgASMwvwSEGx-aGYRXyP1Q9Bxr7HmMVIaFKaxQEb8tg4L7IlRIbITWpG4F5Mf",
         "structured_formatting" : {
            "main_text" : "Tehran Bazaar",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Bazaar"
            },
            {
               "offset" : 15,
               "value" : "Tehran"
            },
            {
               "offset" : 23,
               "value" : "Tehran Province"
            },
            {
               "offset" : 40,
               "value" : "Iran"
            }
         ],
         "types" : [ "neighborhood", "political", "geocode" ]
      }
   ],
   "status" : "OK"
}

Now I need to make an autocomplete list of the result. I mean I need to make such a thing:

Tehran Province, Iran

Tehran, Tehran Province, Iran

Tehranpars, Tehran, Tehran Province, Iran

Tehran Bazaar, Tehran, Tehran Province, Iran

But I don't know how can I select the value of description of the result. Here is my code:

var html = "
";
$.each(locations.output, function (index, value) {
    console.log(value);
})
var html += "
";

/*
"
p
r
e
d
.
.
.

As you can see, the result is lots of single characters. How can I get that values?

Body:
If the result is a JSON string, then you need to convert to a JSON object to iterate through. For demonstration purposes locations.output is equivalent to locationsJSONString in my snippet. See snippet and comments below.

JSfiddle link

var locationsJSONString = '{"predictions": [{"description": "Tehran Province, Iran","id": "4c45c924b261e2bb262360fb5a25d4b9a94088a7","matched_substrings": [{"length": 6,"offset": 0}],"place_id": "ChIJf5Us9YQBjj8R0OohvHQms1U","reference": "CjQtAAAA6j_9DtMr30DQ9h8dzemfD2NaWEWBgf5yFlQ92XW4EZvHXqZ8Ob6wGkedetO1xNiZEhCGeIk7jBXCQP_ad4V0R-YeGhSIcGtxcxPh-G4e2DMT97Be4xdfkg","structured_formatting": {"main_text": "Tehran Province","main_text_matched_substrings": [{"length": 6,"offset": 0}],"secondary_text": "Iran"},"terms": [{"offset": 0,"value": "Tehran Province"},{"offset": 17,"value": "Iran"}],"types": ["administrative_area_level_1", "political", "geocode"]},{"description": "Tehran, Tehran Province, Iran","id": "14788d031b564588682273730e2e16d2617d3548","matched_substrings": [{"length": 6,"offset": 0}],"place_id": "ChIJ2dzzH0kAjj8RvCRwVnxps_A","reference": "CkQ1AAAAGXsNCFct3XK9JukMD-C7D7j1f0b-Rk0uBZFULZ9TKziZVKz2HWeNWZ5xWU-aNIceYEioJRxHmYS_O7DhMW32YBIQzGS_zTt6aijJx_onRU9DTRoU-cPuoOF16KrzlFY_4EGlwVf1Izk","structured_formatting": {"main_text": "Tehran","main_text_matched_substrings": [{"length": 6,"offset": 0}],"secondary_text": "Tehran Province, Iran"},"terms": [{"offset": 0,"value": "Tehran"},{"offset": 8,"value": "Tehran Province"},{"offset": 25,"value": "Iran"}],"types": ["locality", "political", "geocode"]},{"description": "Tehranpars, Tehran, Tehran Province, Iran","id": "09a979a1ac286c1ff2ee94c5d36258910d7f6ec6","matched_substrings": [{"length": 6,"offset": 0}],"place_id": "ChIJX5PM9hwdjj8R6zn_mu5suoE","reference": "ClRBAAAACKbtLWiAm5kV0JzYtPOLhQTuMxlMMIXxPGRmuLUF7xuAlx7Mueo91OuJmB4mTwo3T0NhnNhamVDUsKFE0fNffkZi1Bv-ZQs1TcXLNx195C0SELOTSsOMn6pYeSnFMtvVqsIaFCxWipFk_wIxDKVoLi8Cd8g993cG","structured_formatting": {"main_text": "Tehranpars","main_text_matched_substrings": [{"length": 6,"offset": 0}],"secondary_text": "Tehran, Tehran Province, Iran"},"terms": [{"offset": 0,"value": "Tehranpars"},{"offset": 12,"value": "Tehran"},{"offset": 20,"value": "Tehran Province"},{"offset": 37,"value": "Iran"}],"types": ["neighborhood", "political", "geocode"]},{"description": "Tehran Now, Tehran, Tehran Province, Iran","id": "1f7583f258e7e92f03b818ba10c48e20d2bd9f59","matched_substrings": [{"length": 6,"offset": 0}],"place_id": "ChIJ61k7RLICjj8RnvjuZpbZeEM","reference": "ClRBAAAAydlnsS8Fjw9ibBXXX-XS4xuY4-7yEqMSZNTz66Q-4hRNnGdEGyOICqFbm4VQ4-ZV7O8fftoznes6-u-6sZyvz8Gp3N3hPLASFvtoWeJBPS8SEE8pPnxD20v8_NPnWLANDG8aFPfquA7RBNHvpEgiH5Q0eIqmtl5k","structured_formatting": {"main_text": "Tehran Now","main_text_matched_substrings": [{"length": 6,"offset": 0}],"secondary_text": "Tehran, Tehran Province, Iran"},"terms": [{"offset": 0,"value": "Tehran Now"},{"offset": 12,"value": "Tehran"},{"offset": 20,"value": "Tehran Province"},{"offset": 37,"value": "Iran"}],"types": ["sublocality_level_1", "sublocality", "political", "geocode"]},{"description": "Tehran Bazaar, Tehran, Tehran Province, Iran","id": "7a97ba4c05dcb1b11c2153bd39673b6737aa5748","matched_substrings": [{"length": 6,"offset": 0}],"place_id": "ChIJJX5my-8Bjj8RfAUG71zqw8s","reference": "ClREAAAABs4mvt65BUJ7Z2arVA_cv7V0tdPJKoVy010IOFrlS-L6VfhrEmIQAuxTXVQhnAA19fjEtVbPag3lfb-UrsmnMROnzvXiffA7MKUvgASMwvwSEGx-aGYRXyP1Q9Bxr7HmMVIaFKaxQEb8tg4L7IlRIbITWpG4F5Mf","structured_formatting": {"main_text": "Tehran Bazaar","main_text_matched_substrings": [{"length": 6,"offset": 0}],"secondary_text": "Tehran, Tehran Province, Iran"},"terms": [{"offset": 0,"value": "Tehran Bazaar"},{"offset": 15,"value": "Tehran"},{"offset": 23,"value": "Tehran Province"},{"offset": 40,"value": "Iran"}],"types": ["neighborhood", "political", "geocode"]}], "status": "OK"}';

// convert the JSON string into an object
var locationsJSONObj = JSON.parse(locationsJSONString);

// the results are stored in the "predictions" property of the object
// the value is an array which we assign to the variable below
// to iterate over
var locationsPredictionsArray = locationsJSONObj.predictions;

// format result in list element
var html = '<ul>';

$.each(locationsPredictionsArray, function (index, value) {
 // add item for each location description
  html += '<li>' + value.description + '</li>';
});
html += '</ul>';

$('#output').html(html); // show output in html element

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>


问:
Sum up values in a cell separated by comma in a dataframe column using python
I have a dataframe column with numerical values separated by commas(,). I am trying to find the sum of the values in each cell of that column and create a new column.

Input:
df:

```<code>       id Scores
       1  10,12
       2  11
       3  1,2,3
</code>```

Output required:

```<code>      id Scores Sum
      1  10,12   22
      2  11      11
      3  1,2,3   6
</code>```

Code: I have tried writing a custom function, so that I can make use of apply function in python

```<code>def sum_of_number(listx):
    a=[]
    n=0
    if len(listx)==1:
        a=listx
        n=a
    else:
        a=str(listx).split(',')
        for i in range(0,len(a)):
            n=n+int(a[i])
    return n

df['Sum']=df.Scores.apply(sum_of_number)
</code>```

But I am not able to get the intended result.

Edit:
Thanks to DeepSpace for providing the solution

```<code>df['Sum'] = df['Scores'].apply(lambda x: sum(map(float, x.split(','))))
</code>```

Can the same be applied to get median

```<code>      id Scores Median
      1  10,12   11
      2  11      11
      3  1,2,3   2
</code>```

答:
You can use a much simpler code by combining sum, map and int (or float, based on your needs):

```<code>import pandas as pd

df = pd.DataFrame({'Scores': ['10,12', '11', '1,2,3']})
df['Sum'] = df['Scores'].apply(lambda x: sum(map(int, x.split(','))))
# or df['Sum'] = df['Scores'].apply(lambda x: sum(map(float, x.split(','))))
print(df)

#    Scores  Sum
#  0  10,12   22
#  1  11      11
#  2  1,2,3    6
</code>```

The above assumes the values are strings. If the values are actual list of integers it is even easier:

```<code>import pandas as pd

df = pd.DataFrame({'Scores': [[10, 12], [11], [1, 2, 3]]})
df['Sum'] = df['Scores'].apply(sum)
print(df)

#        Scores  Sum
#  0   [10, 12]   22
#  1       [11]   11
#  2  [1, 2, 3]    6
</code>```

Body:
I have a dataframe column with numerical values separated by commas(,). I am trying to find the sum of the values in each cell of that column and create a new column.

Input:
df:

       id Scores
       1  10,12
       2  11
       3  1,2,3

Output required:

      id Scores Sum
      1  10,12   22
      2  11      11
      3  1,2,3   6

Code: I have tried writing a custom function, so that I can make use of apply function in python

def sum_of_number(listx):
    a=[]
    n=0
    if len(listx)==1:
        a=listx
        n=a
    else:
        a=str(listx).split(',')
        for i in range(0,len(a)):
            n=n+int(a[i])
    return n

df['Sum']=df.Scores.apply(sum_of_number)

But I am not able to get the intended result.

Edit:
Thanks to DeepSpace for providing the solution

df['Sum'] = df['Scores'].apply(lambda x: sum(map(float, x.split(','))))

Can the same be applied to get median

      id Scores Median
      1  10,12   11
      2  11      11
      3  1,2,3   2

Body:
You can use a much simpler code by combining sum, map and int (or float, based on your needs):

import pandas as pd

df = pd.DataFrame({'Scores': ['10,12', '11', '1,2,3']})
df['Sum'] = df['Scores'].apply(lambda x: sum(map(int, x.split(','))))
# or df['Sum'] = df['Scores'].apply(lambda x: sum(map(float, x.split(','))))
print(df)

#    Scores  Sum
#  0  10,12   22
#  1  11      11
#  2  1,2,3    6

The above assumes the values are strings. If the values are actual list of integers it is even easier:

import pandas as pd

df = pd.DataFrame({'Scores': [[10, 12], [11], [1, 2, 3]]})
df['Sum'] = df['Scores'].apply(sum)
print(df)

#        Scores  Sum
#  0   [10, 12]   22
#  1       [11]   11
#  2  [1, 2, 3]    6