问:
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 locations.output is a string, then you need to use JSON.parse(locations.output) in order to get a json object from it.

Once you do that, you will be able to loop through the predictions:

var output = JSON.parse(locations.output);
$.each(output.predictions, function(value, index) { ... });

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?


来源: stackexchange

问:
Number of CNN learnable parameters - Python / TensorFlow
In TensorFlow, is there any function to something I can do to find out the amount of learning parameters in my network?</p>

答:
No function I am aware of, but you can still count yourself using a for loop on the tf.trainable_variables():

```<code>total_parameters = 0
for variable in tf.trainable_variables():
    variable_parameters = 1
    for dim in variable.get_shape():
        variable_parameters *= dim.value
    total_parameters += variable_parameters

print("Total number of trainable parameters: %d" % total_parameters)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
No function I am aware of, but you can still count yourself using a for loop on the tf.trainable_variables():

total_parameters = 0
for variable in tf.trainable_variables():
    variable_parameters = 1
    for dim in variable.get_shape():
        variable_parameters *= dim.value
    total_parameters += variable_parameters

print("Total number of trainable parameters: %d" % total_parameters)


问:
Install PyEnv in Vagrantfile
PyEnv does not have a great installer, and it requires some post-install processing to get it to work correctly (such as modifying .bashrc to add to $PATH and make two pyenv calls). I'm wondering how anyone has been able to get PyEnv installed via Vagrantfile. I want to build a reusable image to develop on so that I don't have to go through the reinstall process if I destroy this VM.

I've tried running the installer and making the recommended edits to .bashrc to get pyenv working, but when I get into my Vagrant box pyenv is not installed. I've tried moving the pyenv script into /bin/pyenv but it is not there when the machine comes up. How do I make this work?

For reference, here is the script I'm currently running that fails to install PyEnv to a Vagrant machine during a Vagrant provision step in the Vagrantfile:

```<code>#! /usr/bin/env bash

# REQUIRES: curl, git

curl -L https://raw.githubusercontent.com/pyenv/pyenv-
installer/master/bin/pyenv-installer | bash

cat >> /home/ubuntu/.bashrc << 'EOF'

export PATH="$PATH:~/.pyenv/bin"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

EOF

exec $SHELL
</code>```

And trying to move pyenv under /bin:

```<code>#! /usr/bin/env bash

# REQUIRES: curl, git

curl -L https://raw.githubusercontent.com/pyenv/pyenv-installer/master/bin/pyenv-installer | bash
mv ~/.pyenv/bin/pyenv /bin/pyenv

cat >> /home/ubuntu/.bashrc << 'EOF'

eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

EOF

exec $SHELL
</code>```

Neither work. How do I get this installed?

答:
Your issue is that you're running the script through Vagrant shell provisioning as root so the update is done for your root user.
When you ssh into the VM, you're logged in with your vagrant user so its not available.

When you need to change is in your Vagrantfile to run the script using privileged option

```<code>config.vm.provision "shell", path: "xxx", privileged: false
</code>```

Title: Install PyEnv in Vagrantfile

Body:
PyEnv does not have a great installer, and it requires some post-install processing to get it to work correctly (such as modifying .bashrc to add to $PATH and make two pyenv calls). I'm wondering how anyone has been able to get PyEnv installed via Vagrantfile. I want to build a reusable image to develop on so that I don't have to go through the reinstall process if I destroy this VM.

I've tried running the installer and making the recommended edits to .bashrc to get pyenv working, but when I get into my Vagrant box pyenv is not installed. I've tried moving the pyenv script into /bin/pyenv but it is not there when the machine comes up. How do I make this work?

For reference, here is the script I'm currently running that fails to install PyEnv to a Vagrant machine during a Vagrant provision step in the Vagrantfile:

#! /usr/bin/env bash

# REQUIRES: curl, git

curl -L https://raw.githubusercontent.com/pyenv/pyenv-
installer/master/bin/pyenv-installer | bash

cat >> /home/ubuntu/.bashrc << 'EOF'

export PATH="$PATH:~/.pyenv/bin"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

EOF

exec $SHELL

And trying to move pyenv under /bin:

#! /usr/bin/env bash

# REQUIRES: curl, git

curl -L https://raw.githubusercontent.com/pyenv/pyenv-installer/master/bin/pyenv-installer | bash
mv ~/.pyenv/bin/pyenv /bin/pyenv

cat >> /home/ubuntu/.bashrc << 'EOF'

eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

EOF

exec $SHELL

Neither work. How do I get this installed?

Body:
Your issue is that you're running the script through Vagrant shell provisioning as root so the update is done for your root user.
When you ssh into the VM, you're logged in with your vagrant user so its not available.

When you need to change is in your Vagrantfile to run the script using privileged option

config.vm.provision "shell", path: "xxx", privileged: false


问:
Elasticsearch Sort Order
Im having trouble getting sort to work correctly in my query. I have tried a very simple example and get some unexpected results.

Query

```<code>{
  "query": {
    "match_all": {}
  },
  "sort": "name"
}
</code>```

The result is that the names with numbers in come higher than those without. For example Eurosport 1 will come before Animal Planet.

```<code>"sort": [
  "1"
]
</code>```

and

```<code>"sort": [
  "a"
]
</code>```

Is whats returned for each respectively.

Do I need something extra to have sort treat the fields as strings for sorting?

I can post more of the responses if its relevant.

答:
So it looks like elastic search behaves differently depending on if the field's index is analyzed or not_analyzed. In my case it was analyzed so it was treating "Eurosport 1" as two words due to the whitespace and sorting on that.

see analyzed or not_analyzed, what to choose

Title: Elasticsearch Sort Order

Body:
Im having trouble getting sort to work correctly in my query. I have tried a very simple example and get some unexpected results.

Query

{
  "query": {
    "match_all": {}
  },
  "sort": "name"
}

The result is that the names with numbers in come higher than those without. For example Eurosport 1 will come before Animal Planet.

"sort": [
  "1"
]

and

"sort": [
  "a"
]

Is whats returned for each respectively.

Do I need something extra to have sort treat the fields as strings for sorting?

I can post more of the responses if its relevant.


问:
header location does not work in facebook app
I'm trying to redirect users to the permission page in my facebook app if they have not added the app. The problem is that using the following just sends them to a page with a large blue facebook logo that the user has to click to see the permissions.

```<code>$login_url = $facebook->getLoginUrl(array(
    'req_perms' => 'email,user_birthday,status_update,publish_stream,user_photos,user_videos',

));

header("Location: ".$login_url);
</code>```

I am using an iframe app. Any help would be really appreciated.

答:
The only way to get redirects working properly within your Facebook Canvas app is through client-side redirect:</p>

```<code><script>
    top.location.href="<?php echo $login_url; ?>";
</script>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to redirect users to the permission page in my facebook app if they have not added the app. The problem is that using the following just sends them to a page with a large blue facebook logo that the user has to click to see the permissions.

$login_url = $facebook->getLoginUrl(array(
    'req_perms' => 'email,user_birthday,status_update,publish_stream,user_photos,user_videos',

));

header("Location: ".$login_url);

I am using an iframe app. Any help would be really appreciated.

Body:
The only way to get redirects working properly within your Facebook Canvas app is through client-side redirect:

<script>
    top.location.href="<?php echo $login_url; ?>";
</script>


问:
How to get name value from SelectList in mvc
I want to get the name value not ID value from SelectList in mvc.

Here is my code

Controller

```<code>var occupationList = new SelectList(new[]
{
    new { ID = 1, Name = "Student" },
    new { ID = 2, Name = "House Wife" },
    new { ID = 3, Name = "Business Man" },
    new { ID = 4, Name = "Service Man" },
},
"ID", "Name", 1);
ViewData["occupationList"] = occupationList;
return View();
</code>```

View

```<code>@Html.DropDownList("Occupation", ViewData["occupationList"] as SelectList, new {@class="control-label", style="width:250px;" })
</code>```

Now, when I select the item from dropdownlist at that time it shows the selected item but it store the ID value in the database.

For ex : I select the Student Name value from the dropdownlist and save it. Now, in database it store the 1 value.

But I dont want to store the ID value i.e. 1. I want to store the Name value i.e. Student in database.

Thank You.

答:
Use this code to save name in DB</p>

```<code>@Html.DropDownList("Occupation", new SelectList(ViewData["occupationList"] as SelectList, "Name", "Name") , new { @class = "control-label", style = "width:250px;" })
</code>```

Body:
I want to get the name value not ID value from SelectList in mvc.

Here is my code

Controller

var occupationList = new SelectList(new[]
{
    new { ID = 1, Name = "Student" },
    new { ID = 2, Name = "House Wife" },
    new { ID = 3, Name = "Business Man" },
    new { ID = 4, Name = "Service Man" },
},
"ID", "Name", 1);
ViewData["occupationList"] = occupationList;
return View();

View

@Html.DropDownList("Occupation", ViewData["occupationList"] as SelectList, new {@class="control-label", style="width:250px;" })

Now, when I select the item from dropdownlist at that time it shows the selected item but it store the ID value in the database.

For ex : I select the Student Name value from the dropdownlist and save it. Now, in database it store the 1 value.

But I dont want to store the ID value i.e. 1. I want to store the Name value i.e. Student in database.

Thank You.

Body:
Use this code to save name in DB

@Html.DropDownList("Occupation", new SelectList(ViewData["occupationList"] as SelectList, "Name", "Name") , new { @class = "control-label", style = "width:250px;" })


问:
Use cases of bootstrapping maven
I've seen some companies using maven bootstrap binary, instead of the one You get by the package manager.

What are the typical use cases of bootstrapping maven?

答: When you willing Docker as containers to build your app in clouds for example.</p>

Title: Use cases of bootstrapping maven


问:
Use inserted value as a parameter for other inserts
There is a db2 database with two tables. The first one, table1, has autoincrement column ID. It is the foreign key for the table2.

A am writing an HTML generator for SQL queries. So with some input parameters it generates a query or multiple queries. It is not connected to the database.
What I need is to get that autoincrement field and use it in next queries.
So basically, the scenario is:

insert into table1;

select autogenerated field ID;

insert into table2 using that ID;

insert into table2 using that ID;

...some more similar inserts...

insert into table2 using that ID;

And all that SQL query should be generated and then used as a single SQL script.

I was thinking about something like this:

SELECT ID FROM FINAL TABLE (INSERT INTO Table1 (t1column1, t1column2, etc.)
                     VALUES (t1value1, t1value2, etc.))

But I don't know, how I can write the result into a variable so I could use it in next queries like this:

INSERT INTO Table2 (foreignKeyCol, t2column1, t2column2, etc.)
                VALUES ($ID, t2value1, t2value2, etc.)

I could just paste that select instead of $ID, but the second query can be used several times with the same $ID and different values.

EDIT: DB2 10.5 on Linux.

答:
You can chain several inserts together using CTEs, like so:

```<code>WITH idcte (id) as (
 SELECT ID FROM FINAL TABLE (
   INSERT INTO Table1 (t1column1, t1column2, etc.)
   VALUES (t1value1, t1value2, etc.)
 )
),
ins1 (id) as (
  SELECT foreignKeyCol FROM FINAL TABLE (
    INSERT INTO Table2 (foreignKeyCol, t2column1, t2column2, etc.)
    SELECT id, t2value1, t2value2, etc.
    FROM idcte
  )
),
-- more CTEs
SELECT foreignKeyCol FROM FINAL TABLE (
    -- your last INSERT ... SELECT FROM
)
</code>```

Essentially you will have to wrap each INSERT into a SELECT FROM FINAL TABLE for this to work.

Alternatively, you can use a global variable to keep the ID value:

```<code>CREATE VARIABLE myNewId INT;
SET myNewId = (SELECT ID FROM FINAL TABLE (
   INSERT INTO Table1 (t1column1, t1column2, etc.)
   VALUES (t1value1, t1value2, etc.)
));
INSERT INTO Table2 (foreignKeyCol, t2column1, t2column2, etc.)
            VALUES (myNewId, t2value1, t2value2, etc.);
DROP VARIABLE myNewId;
</code>```

This assumes a recent version of Db2 for LUW.

Body:
You can chain several inserts together using CTEs, like so:

WITH idcte (id) as (
 SELECT ID FROM FINAL TABLE (
   INSERT INTO Table1 (t1column1, t1column2, etc.)
   VALUES (t1value1, t1value2, etc.)
 )
),
ins1 (id) as (
  SELECT foreignKeyCol FROM FINAL TABLE (
    INSERT INTO Table2 (foreignKeyCol, t2column1, t2column2, etc.)
    SELECT id, t2value1, t2value2, etc.
    FROM idcte
  )
),
-- more CTEs
SELECT foreignKeyCol FROM FINAL TABLE (
    -- your last INSERT ... SELECT FROM
)

Essentially you will have to wrap each INSERT into a SELECT FROM FINAL TABLE for this to work.

Alternatively, you can use a global variable to keep the ID value:

CREATE VARIABLE myNewId INT;
SET myNewId = (SELECT ID FROM FINAL TABLE (
   INSERT INTO Table1 (t1column1, t1column2, etc.)
   VALUES (t1value1, t1value2, etc.)
));
INSERT INTO Table2 (foreignKeyCol, t2column1, t2column2, etc.)
            VALUES (myNewId, t2value1, t2value2, etc.);
DROP VARIABLE myNewId;

This assumes a recent version of Db2 for LUW.


问:
Trim leading or trailing characters from a string?
How can I trim the leading or trailing characters from a string in java?

For example, the slash character "/" - I'm not interested in spaces, and am looking to trim either leading or trailing characters at different times.

答:
My version of trimming leading and/or trailing String s from String str. Both arguments may be null. When str does not has leading and/or trailing s, it is not changed.</p>

```<code>String trim(String str, String s) {
    String res = s == null ? str : str == null ? null : s.length() >= str.length() ? str : str.replaceFirst(s, "");
    if ((res != null) && (s != null) && (res.length() >= s.length())) {
        return res.substring(res.length() - s.length(), res.length()).equals(s) ? res.substring(0, res.length() - s.length()) : res;
    }
    return res;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My version of trimming leading and/or trailing String s from String str. Both arguments may be null. When str does not has leading and/or trailing s, it is not changed.

String trim(String str, String s) {
    String res = s == null ? str : str == null ? null : s.length() >= str.length() ? str : str.replaceFirst(s, "");
    if ((res != null) && (s != null) && (res.length() >= s.length())) {
        return res.substring(res.length() - s.length(), res.length()).equals(s) ? res.substring(0, res.length() - s.length()) : res;
    }
    return res;
}


问:
Insert array using codeigniter
I try to insert multiple arrays into database using codeigniter and ajax. After click the submit, database insert to mysql but all the value is blank. What did I miss?

My view:

```<code><input type="hidden" name="iduser[]" id="iduser[]" value="<?php echo $rowmyuser->iduser; ?>"/>
<input type="hidden" name="idproduk[]" id="idproduk[]" value="<?php echo $rowproduk->idproduct; ?>"/>
<input type="text" class="form-control input-sm" name="settarget[]" id="settarget[]"/>
</code>```

 Save

My controller:

```<code>public function inserttarget()
{
   $this->target_m->inserttarget_m();
}
</code>```

My model:

```<code>function inserttarget_m() {
        $iduser = $this->input->post("iduser");
        $idproduk = $this->input->post("idproduk");
        $settarget = $this->input->post("settarget");

        $temp = count($this->input->post("iduser"));

        $datatarget = array();

        for($i=0; $i < 3; $i++)
        {
        $datatarget[]=array(
        "iduser"=>$iduser[$i],
        "idproduct"=>$idproduk[$i],
        "target"=>$settarget[$i],
        );
    }
    $this->db->insert_batch("tbl_targetsales",$datatarget);
  }
</code>```

The Ajax code:

```<code>function insert_target()
{
  var DataString=$("#frm_target").serialize();
  document.getElementById("save_target").innerHTML = "<i class='fa fa-cog fa-spin fa-lg fa-fw'></i> Saving...";
  $.ajax({
        type: 'POST',
        url: '<?php echo base_url();?>target/inserttarget',
        data: DataString,
        success: function (data) {
      //jQuery("#attendence_report_holder").html(response);
        swal({
            text: 'success'
            });
      $("#frm_target")[0].reset();
      document.getElementById("save_target").innerHTML = "<i class='fa fa-save'>  </i>Save";
      window.location='<?php echo base_url(); ?>target';
    },
    error:function(data){
        swal({
            text: 'error',
            });
      document.getElementById("save_target").innerHTML = "<i class='fa fa-save'>  </i>Save";
    }
  });
}
</code>```

I need advice please, what is the problem in the code. Thanks in advance

答:
first you call wrong the inputs in your html for the inputs name are

```<code>iduser[]
idproduk[]
settarget[]
</code>```

and in your model you call with, and in the array you make to insert you call different variables that you save it

```<code>iduser
idproduct
target
</code>```

replace all you madel with (using the correct names from form and variables names)

```<code>function inserttarget_m() {
        $iduser = $this->input->post("iduser");
        $idproduct = $this->input->post("idproduk");
        $target = $this->input->post("settarget");

        $temp = count($iduser);

        $datatarget = array();

        for($i=0; $i < $temp; $i++){
            $datatarget[] = array(
                                 "iduser"    => $iduser[$i],
                                 "idproduct" => $idproduct[$i],
                                 "target"    => $target[$i],
                              );
    }

    $this->db->insert_batch("tbl_targetsales", $datatarget);
}
</code>```

Title: Insert array using codeigniter

Body:
I try to insert multiple arrays into database using codeigniter and ajax. After click the submit, database insert to mysql but all the value is blank. What did I miss?

My view:

<input type="hidden" name="iduser[]" id="iduser[]" value="<?php echo $rowmyuser->iduser; ?>"/>
<input type="hidden" name="idproduk[]" id="idproduk[]" value="<?php echo $rowproduk->idproduct; ?>"/>
<input type="text" class="form-control input-sm" name="settarget[]" id="settarget[]"/>

 Save

My controller:

public function inserttarget()
{
   $this->target_m->inserttarget_m();
}

My model:

function inserttarget_m() {
        $iduser = $this->input->post("iduser");
        $idproduk = $this->input->post("idproduk");
        $settarget = $this->input->post("settarget");

        $temp = count($this->input->post("iduser"));

        $datatarget = array();

        for($i=0; $i < 3; $i++)
        {
        $datatarget[]=array(
        "iduser"=>$iduser[$i],
        "idproduct"=>$idproduk[$i],
        "target"=>$settarget[$i],
        );
    }
    $this->db->insert_batch("tbl_targetsales",$datatarget);
  }

The Ajax code:

function insert_target()
{
  var DataString=$("#frm_target").serialize();
  document.getElementById("save_target").innerHTML = " Saving...";
  $.ajax({
        type: 'POST',
        url: '<?php echo base_url();?>target/inserttarget',
        data: DataString,
        success: function (data) {
      //jQuery("#attendence_report_holder").html(response);
        swal({
            text: 'success'
            });
      $("#frm_target")[0].reset();
      document.getElementById("save_target").innerHTML = "  Save";
      window.location='<?php echo base_url(); ?>target';
    },
    error:function(data){
        swal({
            text: 'error',
            });
      document.getElementById("save_target").innerHTML = "  Save";
    }
  });
}

I need advice please, what is the problem in the code. Thanks in advance

Body:
first you call wrong the inputs in your html for the inputs name are

iduser[]
idproduk[]
settarget[]

and in your model you call with, and in the array you make to insert you call different variables that you save it

iduser
idproduct
target

replace all you madel with (using the correct names from form and variables names)

function inserttarget_m() {
        $iduser = $this->input->post("iduser");
        $idproduct = $this->input->post("idproduk");
        $target = $this->input->post("settarget");

        $temp = count($iduser);

        $datatarget = array();

        for($i=0; $i < $temp; $i++){
            $datatarget[] = array(
                                 "iduser"    => $iduser[$i],
                                 "idproduct" => $idproduct[$i],
                                 "target"    => $target[$i],
                              );
    }

    $this->db->insert_batch("tbl_targetsales", $datatarget);
}


问:
R programming "Col="red"" error in plot
I'm trying to make a plot in R, the part of getting the drawing of the given values works correctly, I'm getting this:
plot without color

Using this code:

```<code>g<- function(x,y)
  + x**2+y**2-3*x+y+2
gb<- function(x) g(x[1],x[2])
x <- seq(-2,2,len=51)
y <- seq(-2,2,len=51)
gz<-outer(x,y,g)
contour(x,y,gz)
polygon(c(0,0,1),c(1,2,1))
</code>```

but when I want to add color to the polygon with this code:

```<code> g<- function(x,y)
  + x**2+y**2-3*x+y+2
gb<- function(x) g(x[1],x[2])
x <- seq(-2,2,len=51)
y <- seq(-2,2,len=51)
gz<-outer(x,y,g)
contour(x,y,gz)
polygon(c(0,0,1),c(1,2,1),
        + col="red",
        +density=c(30,40))
</code>```

I get the following error:

```<code>Error: unexpected '=' in:
"polygon(c(0,0,1),c(1,2,1),
        + col="
</code>```

The only package I am using for my program is: library(mosaicCalc)

答:
The error message tells you there is some mistake somewhere in the polygon(), so that's the line we'll focus on.

You pasted:

```<code>polygon(c(0,0,1),c(1,2,1),
    + col="red",
    +density=c(30,40))
</code>```

Which is the same as

```<code>polygon(c(0,0,1),c(1,2,1), + col="red", +density=c(30,40))
</code>```

The + are not supposed to be there and they are causing the error. Use

```<code>polygon(c(0,0,1),c(1,2,1), col="red", density=c(30,40))
</code>```

and you should be fine.

Sidenote: It seems like you have copy-pasted this code from somewhere and then ran into this error when running it yourself. If someone copies code from their console, it usually includes a + if multiple lines of code belong to the same statement. As you've learnt  now, you should remove those before you run the code.

Title: R programming "Col="red"" error in plot

Body:
I'm trying to make a plot in R, the part of getting the drawing of the given values works correctly, I'm getting this:
plot without color

Using this code:

g<- function(x,y)
  + x**2+y**2-3*x+y+2
gb<- function(x) g(x[1],x[2])
x <- seq(-2,2,len=51)
y <- seq(-2,2,len=51)
gz<-outer(x,y,g)
contour(x,y,gz)
polygon(c(0,0,1),c(1,2,1))

but when I want to add color to the polygon with this code:

 g<- function(x,y)
  + x**2+y**2-3*x+y+2
gb<- function(x) g(x[1],x[2])
x <- seq(-2,2,len=51)
y <- seq(-2,2,len=51)
gz<-outer(x,y,g)
contour(x,y,gz)
polygon(c(0,0,1),c(1,2,1),
        + col="red",
        +density=c(30,40))

I get the following error:

Error: unexpected '=' in:
"polygon(c(0,0,1),c(1,2,1),
        + col="

The only package I am using for my program is: library(mosaicCalc)

Body:
The error message tells you there is some mistake somewhere in the polygon(), so that's the line we'll focus on.

You pasted:

polygon(c(0,0,1),c(1,2,1),
    + col="red",
    +density=c(30,40))

Which is the same as

polygon(c(0,0,1),c(1,2,1), + col="red", +density=c(30,40))

The + are not supposed to be there and they are causing the error. Use

polygon(c(0,0,1),c(1,2,1), col="red", density=c(30,40))

and you should be fine.

Sidenote: It seems like you have copy-pasted this code from somewhere and then ran into this error when running it yourself. If someone copies code from their console, it usually includes a + if multiple lines of code belong to the same statement. As you've learnt  now, you should remove those before you run the code.


问:
Why is this map lambda function taking too much time when applied on pandas dataframe?
I want to copy each row from df_source to df_target that matches a simple condition (value of its col1 doesn't exist in a given list of values).

I'm trying to accomplish this by doing the following:

```<code>df_target = df_source[df_source['Col1'].map(lambda x: x not in id_list)].copy()
</code>```

Keep in mind len(id_list) = 300000, that contains string identifiers of the shape HF1D2R.
The dataframe df_source also contains 300000 rows and 11 columns of type strings and integers.

This takes over 10 minutes to complete, what's the issue here ?

答:
Use isin with ~ for inverse boolean mask:

```<code>df_target = df_source[~df_source['Col1'].isin(id_list)].copy()
</code>```

Body:
I want to copy each row from df_source to df_target that matches a simple condition (value of its col1 doesn't exist in a given list of values).

I'm trying to accomplish this by doing the following:

df_target = df_source[df_source['Col1'].map(lambda x: x not in id_list)].copy()

Keep in mind len(id_list) = 300000, that contains string identifiers of the shape HF1D2R.
The dataframe df_source also contains 300000 rows and 11 columns of type strings and integers.

This takes over 10 minutes to complete, what's the issue here ?

Body:
Use isin with ~ for inverse boolean mask:

df_target = df_source[~df_source['Col1'].isin(id_list)].copy()


问:
Django: Switched from single-settings file to multi-settings package, now I get: AttributeError: module 'core.settings' has no attribute '...'
I have a settings folder under core module with an __init.py and a prod.py, dev.py, base.py.

I added a variable to my base.pycalled SITE_DIRECTORY.

Then, I modify this variable in my dev.py which is set as my DJANGO_SETTINGS_MODULE through an ENV variable.

When I run the following code:

```<code>from core import settings

urlpatterns = [
    url(r'^' + settings.SITE_DIRECTORY, include('frontend.urls'), name='frontend'),
    url(r'^' + settings.SITE_DIRECTORY + 'admin/', admin.site.urls),
    url(r'^' + settings.SITE_DIRECTORY + 'static/(?P<path>.*)$', views.serve),
]
</code>```

I get:

AttributeError: module 'core.settings' has no attribute
  'SITE_DIRECTORY'

I have no idea why... Since I am now using a multi-settings package, do I have to change my import statement from from core import settings to something else?

答:
Your import statement from core import settings is wrong, it should be from django.conf import settings

Edit: You should read the documentation about how to use the settings in django: https://docs.djangoproject.com/en/1.11/topics/settings/#using-settings-in-python-code

Body:
I have a settings folder under core module with an __init.py and a prod.py, dev.py, base.py.

I added a variable to my base.pycalled SITE_DIRECTORY.

Then, I modify this variable in my dev.py which is set as my DJANGO_SETTINGS_MODULE through an ENV variable.

When I run the following code:

from core import settings

urlpatterns = [
    url(r'^' + settings.SITE_DIRECTORY, include('frontend.urls'), name='frontend'),
    url(r'^' + settings.SITE_DIRECTORY + 'admin/', admin.site.urls),
    url(r'^' + settings.SITE_DIRECTORY + 'static/(?P<path>.*)$', views.serve),
]

I get:

AttributeError: module 'core.settings' has no attribute
  'SITE_DIRECTORY'

I have no idea why... Since I am now using a multi-settings package, do I have to change my import statement from from core import settings to something else?


问:
GET-only api for Google Sheets or similar
I have a Tableau workbook that helps surface interesting cases in a large dataset.  Once an interesting case is identified, I'd like to add it to an external list that allows me to take action on it later.  Ideally, I'd like to use the URL action to drive a separate app, like Google Sheets, and add a line with the ID of the currently selected item.  Like this completely made-up example:

http://sheets.googleapis.com/SheetName?op=AddRow&data={id:123,title:"foo"}

I can do all of these things in Tableau to get the URL built how I want, but I am stuck with just an http GET, with no post payload.  I don't see any way to get google sheets to work with a simple GET request.

Questions:

Is there any way to get Google Sheets to behave how I want, where I
can add a row with just a GET request?  I can't find anything in the docs that would suggest this is possible.

Is there an alternative to Google Sheets that I can use that is authenticated?  (OneNote, for example, seems to have the same POST limitation)

Is there some sort of intermediary I can use to bridge the divide, like IFTTT?  I can't seem to figure out a way to kick off an IFTTT type of action with just a GET request from a browser.

答: The available option in Sheets v4 as mentioned in Insert an empty row or column is to use spreadsheets.batchUpdate. That's a POST request and not a GET request. GET requests are for reading purposes only or as mentioned here, to retrieve data. Whenever you're writing, you use POST or PUT methods so I don't what you're doing is possible thru GET.</p>


问:
Hmisc separate column headings with rowname = NULL
I'm trying to have column headings and the horizontal line underneath the headings separated by the groups. When I do the following it works,

```<code>library(Hmisc)
data(mtcars)
latex(mtcars, file ='', cgroup = c("Group 1", "Group 2"), n.cgroup = c(5, 6))
</code>```

but when I try to remove the rownames, the line under Group 1 & 2 merge into the same line

```<code>library(Hmisc)
data(mtcars)
latex(mtcars, file ='', cgroup = c("Group 1", "Group 2"), n.cgroup = c(5, 6), rowname = NULL)
</code>```

Does anyone know of a way to fix this?

答:
The latex functionlatex.default does not use the column group argument when rownames=NULL. In the function we have :

```<code>if (length(rowname)) {
    cx <- cbind(rowname, cx)
    col.just <- c(rowlabel.just, col.just)
    if (length(extracolheads))
        extracolheads <- c("", extracolheads)
    collabel.just <- c(rowlabel.just, collabel.just)
    if (length(cgroup) == 0L)
        colheads <- c(rowlabel, colheads)
    else {
        colheads <- c("", colheads)
        cgroup <- c(rowlabel, cgroup)
        rlj <- ifelse(rowlabel.just == "l", "l", "c")
        cgroup.just <- c(rlj, cgroup.just)
        n.cgroup <- c(1, n.cgroup)
        cgroup.cols <- 1 + cgroup.cols
        cline <- paste(sl, "cline{", cgroup.cols[, 1], "-", cgroup.cols[,
            2], "}", sep = "", collapse = " ")
    }
    nc <- 1 + nc
}
</code>```

with cgroup.cols as the first and last columns computed from the n.cgroup argument

```<code>     first.col last.col
[1,]         1        5
[2,]         7       12
</code>```

I think it's a bug. So currently the only way to go is to edit your tex output manually,  using this function, in which your repeat the arguments that you passed to your latex for the name of your tex file and n.cgroup :

```<code>change_cline <- function(file,n.cgroup){
  file_to_edit <-readLines(file)
  pos <- grep("cline",file_to_edit) # get the position of cline in the tex file
  cgroup.cols <- matrix(c(1,n.cgroup[2]+1,n.cgroup[1],sum(n.cgroup)+1), nrow=2)
  file_to_edit[pos]<- paste("\\cline{", cgroup.cols[, 1], "-", cgroup.cols[,
          2], "}", sep = "", collapse = " ")
  cat(file_to_edit, file = file,sep="\n")
  return(invisible(NULL))
}
</code>```

Final script :

```<code>data(mtcars)
la<-latex(mtcars, file ='mtcars2.tex', cgroup = c("Group 1", "Group 2"), n.cgroup = c(5, 6), rowname = NULL)
change_cline(file='mtcars2.tex',n.cgroup = c(5 ,6))
</code>```

which produces the correct format

Body:
I'm trying to have column headings and the horizontal line underneath the headings separated by the groups. When I do the following it works,

library(Hmisc)
data(mtcars)
latex(mtcars, file ='', cgroup = c("Group 1", "Group 2"), n.cgroup = c(5, 6))

but when I try to remove the rownames, the line under Group 1 & 2 merge into the same line

library(Hmisc)
data(mtcars)
latex(mtcars, file ='', cgroup = c("Group 1", "Group 2"), n.cgroup = c(5, 6), rowname = NULL)

Does anyone know of a way to fix this?

Body:
The latex functionlatex.default does not use the column group argument when rownames=NULL. In the function we have :

if (length(rowname)) {
    cx <- cbind(rowname, cx)
    col.just <- c(rowlabel.just, col.just)
    if (length(extracolheads))
        extracolheads <- c("", extracolheads)
    collabel.just <- c(rowlabel.just, collabel.just)
    if (length(cgroup) == 0L)
        colheads <- c(rowlabel, colheads)
    else {
        colheads <- c("", colheads)
        cgroup <- c(rowlabel, cgroup)
        rlj <- ifelse(rowlabel.just == "l", "l", "c")
        cgroup.just <- c(rlj, cgroup.just)
        n.cgroup <- c(1, n.cgroup)
        cgroup.cols <- 1 + cgroup.cols
        cline <- paste(sl, "cline{", cgroup.cols[, 1], "-", cgroup.cols[,
            2], "}", sep = "", collapse = " ")
    }
    nc <- 1 + nc
}

with cgroup.cols as the first and last columns computed from the n.cgroup argument

     first.col last.col
[1,]         1        5
[2,]         7       12

I think it's a bug. So currently the only way to go is to edit your tex output manually,  using this function, in which your repeat the arguments that you passed to your latex for the name of your tex file and n.cgroup :

change_cline <- function(file,n.cgroup){
  file_to_edit <-readLines(file)
  pos <- grep("cline",file_to_edit) # get the position of cline in the tex file
  cgroup.cols <- matrix(c(1,n.cgroup[2]+1,n.cgroup[1],sum(n.cgroup)+1), nrow=2)
  file_to_edit[pos]<- paste("\\cline{", cgroup.cols[, 1], "-", cgroup.cols[,
          2], "}", sep = "", collapse = " ")
  cat(file_to_edit, file = file,sep="\n")
  return(invisible(NULL))
}

Final script :

data(mtcars)
la<-latex(mtcars, file ='mtcars2.tex', cgroup = c("Group 1", "Group 2"), n.cgroup = c(5, 6), rowname = NULL)
change_cline(file='mtcars2.tex',n.cgroup = c(5 ,6))

which produces the correct format


问:
Generic type bounded by another generic
Suppose I have this:

```<code>interface Shape {}
interface Square extends Shape {}
interface Circle extends Shape {}

interface ShapeBuilder<S extends Shape> {}
</code>```

I want something like this:

```<code>class ShapeBuilderFactory<SB extends ShapeBuilder> {
    SB<Square> getSquareBuilder(){...}
    SB<Circle> getCircleBuilder(){...}
}
</code>```

This code doesn't compile (because ShapeBuilder is a raw type), but I hope you understand the idea.
Is it possible to do something like this in java? How?

(the real problem isn't with shapes builders and factories, I used this example for simplicity)

Edit (more context)

I have different kind of builders:

```<code>interface RegularShapeBuilder<S extends Shape> extends ShapeBuilder<S> {}
interface FunnyShapeBuilder<S extends Shape> extends ShapeBuilder<S> {}

class RegularSquareBuilder extends RegularShapeBuilder<Square> {}
class FunnySquareBuilder extends FunnyShapeBuilder<Square> {}
class RegularCircleBuilder extends RegularShapeBuilder<Circle> {}
class FunnyCircleBuilder extends FunnyShapeBuilder<Circle> {}
</code>```

And I want the factory to do things like this:

```<code>ShapeBuilderFactory<FunnyShapeBuilder> funnyShapeBuilderFactory = ...;
FunnyShapeBuilder<Square> funnySquareBuilder = funnyShapeBuilderFactory.getSquareBuilder();
</code>```

答:
Drop the generics on the factory class, do something like :</p>

```<code>interface Shape {}
interface Square extends Shape {}
interface Circle extends Shape {}

interface ShapeBuilder<S extends Shape> {}

class ShapeBuilderFactory {
    ShapeBuilder<Square> getSquareBuilder(){...}
    ShapeBuilder<Circle> getCircleBuilder(){...}
}
</code>```

Title: Generic type bounded by another generic

Body:
Suppose I have this:

interface Shape {}
interface Square extends Shape {}
interface Circle extends Shape {}

interface ShapeBuilder<S extends Shape> {}

I want something like this:

class ShapeBuilderFactory<SB extends ShapeBuilder> {
    SB<Square> getSquareBuilder(){...}
    SB<Circle> getCircleBuilder(){...}
}

This code doesn't compile (because ShapeBuilder is a raw type), but I hope you understand the idea.
Is it possible to do something like this in java? How?

(the real problem isn't with shapes builders and factories, I used this example for simplicity)

Edit (more context)

I have different kind of builders:

interface RegularShapeBuilder<S extends Shape> extends ShapeBuilder<S> {}
interface FunnyShapeBuilder<S extends Shape> extends ShapeBuilder<S> {}

class RegularSquareBuilder extends RegularShapeBuilder<Square> {}
class FunnySquareBuilder extends FunnyShapeBuilder<Square> {}
class RegularCircleBuilder extends RegularShapeBuilder<Circle> {}
class FunnyCircleBuilder extends FunnyShapeBuilder<Circle> {}

And I want the factory to do things like this:

ShapeBuilderFactory<FunnyShapeBuilder> funnyShapeBuilderFactory = ...;
FunnyShapeBuilder<Square> funnySquareBuilder = funnyShapeBuilderFactory.getSquareBuilder();

Body:
Drop the generics on the factory class, do something like :

interface Shape {}
interface Square extends Shape {}
interface Circle extends Shape {}

interface ShapeBuilder<S extends Shape> {}

class ShapeBuilderFactory {
    ShapeBuilder<Square> getSquareBuilder(){...}
    ShapeBuilder<Circle> getCircleBuilder(){...}
}


问:
Hive Partition Performance
I would like to ask about Hive partitioning performance.
How many records (in term of rows) would I need in order to see the partitioning performance?

Currently, I have 2 million+ records and I have split the table into 2 partitions.
My partitioning condition is as follow:

ADD PARTITION (year_month=’2017_07’)

ADD PARTITION (year_month=’2017_08’)

INSERT OVERWRITE TABLE T PARTITION (year_month='2017_07')
SELECT * FROM T WHERE st_time < '2017_08_01 00:00:00.0';

INSERT OVERWRITE TABLE T PARTITION (year_month='2017_08')
SELECT * FROM T WHERE st_time >= '2017_08_01 00:00:00.0';

When I tried to do some performance testing between the partitioned table and non-partitioned table, the performance of both tables is relatively the same.
My performance testing query is as follows:

SELECT * FROM T WHERE st_time < '2017_08_01 00:00:00.0';

SELECT * FROM non_part_table WHERE st_time < '2017_08_01 00:00:00.0';

Am I missing out on some important points?

Also, does partition work on derived column/function? E.g. date_format(st_time, yyyy-MM)

Any help or advice is greatly appreciated.

答:
the performance of both tables is relatively the same

You forgot the WHERE clause against the partition. Partitions only improve performance when you are selecting data within them.

```<code>SELECT * FROM T
WHERE year_month = '2017_07'
-- AND st_time < '2017_08_01 00:00:00.0'
;
</code>```

Without this, you're still scanning the whole table for the st_time values.

You can add an EXPLAIN to the queries to see the difference

You'll get additional performance improvements by converting data into Parquet or ORC

Title: Hive Partition Performance

Body:
the performance of both tables is relatively the same

You forgot the WHERE clause against the partition. Partitions only improve performance when you are selecting data within them.

SELECT * FROM T
WHERE year_month = '2017_07'
-- AND st_time < '2017_08_01 00:00:00.0'
;

Without this, you're still scanning the whole table for the st_time values.

You can add an EXPLAIN to the queries to see the difference

You'll get additional performance improvements by converting data into Parquet or ORC


问:
Morse code program i just need a little bit of guide with neatness
this is my code for making typing out Morse code

```<code>def main ():

    morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
                  "m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}

    phrase = input("please enter your word or words: ")
    print("your word or sentence translated to morse code is : ")
    for key in phrase:
        if not key.isdigit():
            print(morse_code[key], end = " ")

retry()

def retry ():
    main ()
</code>```

When the program restarts it starts on the same line the type Morse code is at, and i don't know where to put a error print, so that if someone types a number it says try again or error before restarting

Body:
this is my code for making typing out Morse code

def main ():

    morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
                  "m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}

    phrase = input("please enter your word or words: ")
    print("your word or sentence translated to morse code is : ")
    for key in phrase:
        if not key.isdigit():
            print(morse_code[key], end = " ")

retry()

def retry ():
    main ()

When the program restarts it starts on the same line the type Morse code is at, and i don't know where to put a error print, so that if someone types a number it says try again or error before restarting

Body:
Here you go:-

def main():
    morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
                "m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}

    phrase = input("please enter your word or words: ")

    if any(char.isdigit() for char in phrase):
        print("try again")
    else:
        print("your word or sentence translated to morse code is : ", end = '')
        code = ' '.join(morse_code[key] for key in phrase)
        print(code)

def retry():
    main()
retry()


问:
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?

答:
There are few issues here. The first issue is you are iterating over a string, instead you need to parse it as a javascript object. Second issue, you need to iterate over an array, not an object. it would look something like this:

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

You could also use jquery JSON parse method.

```<code>$.each($.parseJSON(locations.output.predictions), function (index, value) {
    console.log(value, value.description);
})
</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:
There are few issues here. The first issue is you are iterating over a string, instead you need to parse it as a javascript object. Second issue, you need to iterate over an array, not an object. it would look something like this:

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

You could also use jquery JSON parse method.

$.each($.parseJSON(locations.output.predictions), function (index, value) {
    console.log(value, value.description);
})


问:
how to sort the records by another field for the top_hit in ES
I have data such as:

```<code>Id  name startTime(timestamp)
1    c     1510000000000
2    c     1500000000000
3    a     1510000000000
4    a     1500000000000
5    b     1500662700000
</code>```

I want to get the max startTime record for each name, and then sort by name.
the result should be:

```<code>Id  name startTime(timestamp)
1    a     1510000000000
5    b     1500662700000
2    c     1510000000000
</code>```

currently, I can get the max startTime group by each name, but I don't know how to sort by name for the results.

Here is my query:

```<code>GET index/default/_search
{
  "aggs": {
    "group": {
      "terms": {
        "field": "name"
      },
      "aggs": {
        "tops": {
          "top_hits": {
            "sort": [
              {
                "startTime": {
                  "order": "desc"
                }
              }
            ],
            "size": 1
          }
        }
      }
    }
  },
  "size": 0
}
</code>```

答:
As I'm understand, except for top_hits sort, you want the name buckets to be sorted by the name.

Have a look at Terms Aggregation order. All you have to do is to add order by key under the terms aggregation.

Here is my suggestion:

```<code>{
  "aggs": {
    "group": {
      "terms": {
        "field": "name",
        "order": {        --> this will do the trick
          "_term": "asc"
        }
      },
      "aggs": {
        "tops": {
          "top_hits": {
            "sort": [
              {
                "startTime": {
                  "order": "desc"
                }
              }
            ],
            "size": 1
          }
        }
      }
    }
  },
  "size": 0
}
</code>```

Body:
I have data such as:

Id  name startTime(timestamp)
1    c     1510000000000
2    c     1500000000000
3    a     1510000000000
4    a     1500000000000
5    b     1500662700000

I want to get the max startTime record for each name, and then sort by name.
the result should be:

Id  name startTime(timestamp)
1    a     1510000000000
5    b     1500662700000
2    c     1510000000000

currently, I can get the max startTime group by each name, but I don't know how to sort by name for the results.

Here is my query:

GET index/default/_search
{
  "aggs": {
    "group": {
      "terms": {
        "field": "name"
      },
      "aggs": {
        "tops": {
          "top_hits": {
            "sort": [
              {
                "startTime": {
                  "order": "desc"
                }
              }
            ],
            "size": 1
          }
        }
      }
    }
  },
  "size": 0
}

Body:
As I'm understand, except for top_hits sort, you want the name buckets to be sorted by the name.

Have a look at Terms Aggregation order. All you have to do is to add order by key under the terms aggregation.

Here is my suggestion:

{
  "aggs": {
    "group": {
      "terms": {
        "field": "name",
        "order": {        --> this will do the trick
          "_term": "asc"
        }
      },
      "aggs": {
        "tops": {
          "top_hits": {
            "sort": [
              {
                "startTime": {
                  "order": "desc"
                }
              }
            ],
            "size": 1
          }
        }
      }
    }
  },
  "size": 0
}


问:
Hyperledger Composer Multiple user mode for REST server throws 401 error
I have been following the tutorials which are provided in Hyperledger Composer docs, but I am not getting the results that they are supposed to I should be getting. Specifically, when I try to enable the multiple user mode for the REST server and I try to call one of the business network REST API operations using the REST API explorer I always get a HTTP 401 Authorization Required. According to the Tutorial, I if get this error is due to I have not authenticated correctly to the REST API, but it does not mention why this error occurs or how I may fix it.

It is very important for application development to be able to authenticate each user who wants to make requests to the API.

答:
What version of Hyperledger Composer are you using?
The tutorial/document you refer to is correct for v0.15.0 and works a little differently for prior versions.

Are you seeing an Access token at the top of the Browser Window - this indicates that you have successfully authenticated and can continue with the steps for the Wallet.

If you are not seeing an Access token displayed, then make sure you hit your REST server with a URL similar to http://localhost:3000/auth/github again and login.

If you are still experiencing problems I would suggest going back to just using authentication without multiuser mode and verify that the authentication works properly from there.


问:
How to remove string with specific value from a string using JavaScript?
Suppose my string is like:

```<code>var str = "USA;UK;AUS;NZ"
</code>```

Now from some a source I am getting one value like:

```<code>country.data = "AUS"
</code>```

Now in this case I want to remove "AUS" from my string.

Can anyone please suggest how to achieve this.

Here is what I have tried:

```<code>var someStr= str.substring(0, str.indexOf(country.data))
</code>```

In this case I got the same result.

答:
You can use split and filter:

var str = "USA;UK;AUS;NZ"
var toBeRemoved = "AUS";
var res = str.split(';').filter(s => s !== toBeRemoved).join(';');
console.log(res);```

Body:
Suppose my string is like:

var str = "USA;UK;AUS;NZ"

Now from some a source I am getting one value like:

country.data = "AUS"

Now in this case I want to remove "AUS" from my string.

Can anyone please suggest how to achieve this.

Here is what I have tried:

var someStr= str.substring(0, str.indexOf(country.data))

In this case I got the same result.


问:
Select different columns for each row
Suppose I have the following array:

```<code>>>> a = np.arange(25).reshape((5, 5))
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])
</code>```

Now I want to select different columns for each row based on the following index array:

```<code>>>> i = np.array([0, 1, 2, 1, 0])
</code>```

This index array denotes the start column for each row and the selections should be of similar range, e.g. 3. Thus I want to obtain the following result:

```<code>>>> ???
array([[ 0,  1,  2],
       [ 6,  7,  8],
       [12, 13, 14],
       [16, 17, 18],
       [20, 21, 22]])
</code>```

I know that I can select a single column per row via

```<code>>>> a[np.arange(a.shape[0]), i]
</code>```

but how about multiple columns?

Title: Select different columns for each row

Body:
Suppose I have the following array:

>>> a = np.arange(25).reshape((5, 5))
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

Now I want to select different columns for each row based on the following index array:

>>> i = np.array([0, 1, 2, 1, 0])

This index array denotes the start column for each row and the selections should be of similar range, e.g. 3. Thus I want to obtain the following result:

>>> ???
array([[ 0,  1,  2],
       [ 6,  7,  8],
       [12, 13, 14],
       [16, 17, 18],
       [20, 21, 22]])

I know that I can select a single column per row via

>>> a[np.arange(a.shape[0]), i]

but how about multiple columns?

Body:
Use advanced indexing with properly broadcasted 2d array as index.

a[np.arange(a.shape[0])[:,None], i[:,None] + np.arange(3)]
#array([[ 0,  1,  2],
#       [ 6,  7,  8],
#       [12, 13, 14],
#       [16, 17, 18],
#       [20, 21, 22]])

idx_row = np.arange(a.shape[0])[:,None]
idx_col = i[:,None] + np.arange(3)

idx_row
#array([[0],
#       [1],
#       [2],
#       [3],
#       [4]])

idx_col
#array([[0, 1, 2],
#       [1, 2, 3],
#       [2, 3, 4],
#       [1, 2, 3],
#       [0, 1, 2]])

a[idx_row, idx_col]
#array([[ 0,  1,  2],
#       [ 6,  7,  8],
#       [12, 13, 14],
#       [16, 17, 18],
#       [20, 21, 22]])


问:
Paypal Vault card number is masked
In sandbox mode i am able to store credit card numbers, however when i retrieve it the card number is masked IE "xxxxxxxxxxxx1111".
The documentation states that it should be a numeric string.
Is this how it is supposed to work or does it just do this in the sandbox?</p>

答:
This is correct functionality. The full card number is hidden in the response, so the above information is accurate.

You'll find the information in the developer's page under Vaulted Credit Cards:
"The credit card number. Valid value is a string of numeric characters with no spaces or punctuation. Must conform to modulo and the length required by its credit card type. Redacted in responses."

https://developer.paypal.com/docs/api/vault/#credit-card_create_response

Title: Paypal Vault card number is masked


答:
Try this : </p>

```<code>var result = str.replace(country.data + ';','');
</code>```

<p>Thanks to comments, this should work more efficently : </p>

```<code>var tmp = str.replace(country.data ,'');
var result = tmp.replace(';;' ,';');
</code>```

Title: How to remove string with specific value from a string using JavaScript?

Body:
Try this :

var result = str.replace(country.data + ';','');

Thanks to comments, this should work more efficently :

var tmp = str.replace(country.data ,'');
var result = tmp.replace(';;' ,';');


问:
Proper usage of std::promise and std::future, segfaults
I've been trying my luck on a small threadpool implementation.
However, after conceptualizing and implementing i've hit a brick wall.
I've confirmed that the worker threads ate starting up and sleeping correctly, also that they pick up and execute stored tasks correctly.
However, my program segfaults - i'm pretty sure its at promise.set_value.

Im not sure how i could provide a complete, verifiable example (given that i can hardly upload the whole code) but i'll include the segments
i believe to be relevant to this problem.
First off, workers are created like this:

```<code>worker = [this](){
    while(true)
    {
        std::unique_lock<std::mutex> lock(mStatusMutex); //CV for status updates
        mCV.wait(lock);
        if(mStatus != Running) //If threadpool status does not imply running
            break; //Break out of loop, ending thread in the process
        else //If threadpool is in running state
        {
            lock.unlock(); //Unlock state
            while(true) //Loop until no tasks are left
            {
                mTasksMutex.lock(); //Lock task queue
                if(mTasks.empty()) //IF no tasks left, break out of loop and return to waiting
                {
                    mTasksMutex.unlock();
                    break;
                }
                else //Else, retrieve a task, unlock the task queue and execute the task
                {
                    std::function<void()> task = mTasks.front();
                    mTasks.pop();
                    mTasksMutex.unlock();
                    task(); //Execute task
                }
            }
        }
    }
};
</code>```

And then started and stored into a std::vector<std::thread> like this:

```<code>std::thread tWorker(worker);
mWorkers.push_back(std::move(tWorker));
</code>```

Now, the tricky part i believe to be the following is when adding/executing tasks to the task queue, which is a std::queue<std::function<void()>>.
The following two functions are relevant here:

```<code>template<typename RT>
inline std::future<RT> queueTask(std::function<RT()> _task, bool _execute = false)
{
    std::promise<RT> promise;
    std::function<void()> func([&_task, &promise]() -> RT {
        RT val = _task();
        promise.set_value(val);
    });

    mTasksMutex.lock();
    mTasks.emplace(func);
    mTasksMutex.unlock();
    if(_execute) flush();
    return promise.get_future();
}
inline void flush()
{
    mCV.notify_all();
}
</code>```

Is there anything principally wrong with this approach?
For anyone who believes this to be a bad question, feel free to tell me how i can improve it.
Full code is hosted on my github repo.

答:
The main problem is that the promise is already dead. When queueTask is done, the promise is destroyed, and the task now just has a dangling reference. The task must share ownership of the promise in order for it to live long enough to fulfill it.

The same is true of the underlying std::function object _task, since you're capturing it by reference.

You're using std::function, which requires copyable objects, hence... shared_ptr:

```<code>template<typename RT>
inline std::future<RT> queueTask(std::function<RT()> _task, bool _execute = false)
{
    auto promise = std::make_shared<std::promise<RT>>();
    std::function<void()> func([promise, task=std::move(_task)]{
        RT val = _task();
        promise->set_value(val);
    });

    {
        std::lock_guard<std::mutex> lk(mTasksMutex); // NB: no manual lock()/unlock()!!
        mTasks.emplace(func);
    }
    if(_execute) flush();
    return promise->get_future();
}
</code>```

Consider std::packaged_task instead.

Body:
I've been trying my luck on a small threadpool implementation.
However, after conceptualizing and implementing i've hit a brick wall.
I've confirmed that the worker threads ate starting up and sleeping correctly, also that they pick up and execute stored tasks correctly.
However, my program segfaults - i'm pretty sure its at promise.set_value.

Im not sure how i could provide a complete, verifiable example (given that i can hardly upload the whole code) but i'll include the segments
i believe to be relevant to this problem.
First off, workers are created like this:

worker = [this](){
    while(true)
    {
        std::unique_lock<std::mutex> lock(mStatusMutex); //CV for status updates
        mCV.wait(lock);
        if(mStatus != Running) //If threadpool status does not imply running
            break; //Break out of loop, ending thread in the process
        else //If threadpool is in running state
        {
            lock.unlock(); //Unlock state
            while(true) //Loop until no tasks are left
            {
                mTasksMutex.lock(); //Lock task queue
                if(mTasks.empty()) //IF no tasks left, break out of loop and return to waiting
                {
                    mTasksMutex.unlock();
                    break;
                }
                else //Else, retrieve a task, unlock the task queue and execute the task
                {
                    std::function<void()> task = mTasks.front();
                    mTasks.pop();
                    mTasksMutex.unlock();
                    task(); //Execute task
                }
            }
        }
    }
};

And then started and stored into a std::vector<std::thread> like this:

std::thread tWorker(worker);
mWorkers.push_back(std::move(tWorker));

Now, the tricky part i believe to be the following is when adding/executing tasks to the task queue, which is a std::queue<std::function<void()>>.
The following two functions are relevant here:

template<typename RT>
inline std::future<RT> queueTask(std::function<RT()> _task, bool _execute = false)
{
    std::promise<RT> promise;
    std::function<void()> func([&_task, &promise]() -> RT {
        RT val = _task();
        promise.set_value(val);
    });

    mTasksMutex.lock();
    mTasks.emplace(func);
    mTasksMutex.unlock();
    if(_execute) flush();
    return promise.get_future();
}
inline void flush()
{
    mCV.notify_all();
}

Is there anything principally wrong with this approach?
For anyone who believes this to be a bad question, feel free to tell me how i can improve it.
Full code is hosted on my github repo.

Body:
The main problem is that the promise is already dead. When queueTask is done, the promise is destroyed, and the task now just has a dangling reference. The task must share ownership of the promise in order for it to live long enough to fulfill it.

The same is true of the underlying std::function object _task, since you're capturing it by reference.

You're using std::function, which requires copyable objects, hence... shared_ptr:

template<typename RT>
inline std::future<RT> queueTask(std::function<RT()> _task, bool _execute = false)
{
    auto promise = std::make_shared<std::promise<RT>>();
    std::function<void()> func([promise, task=std::move(_task)]{
        RT val = _task();
        promise->set_value(val);
    });

    {
        std::lock_guard<std::mutex> lk(mTasksMutex); // NB: no manual lock()/unlock()!!
        mTasks.emplace(func);
    }
    if(_execute) flush();
    return promise->get_future();
}

Consider std::packaged_task instead.


问:
How to open a file from the integrated terminal in Visual Studio Code?
Is there a way of opening a file from the terminal in Visual Studio Code that opens in the same vscode instance that runs the terminal? Similar to c9 tool in Cloud9.

I'm aware of the code tool, but when you run code something.php from the integrated terminal it opens a new vscode instance, which is not what I want...

答: I use code -r . to open the current directory in the main window.


问:
Break string naturally instead of using Can Grow
I've got a string that sometimes is longer than the space on a table I have allocated. The issue I have is I cannot use the "can grow" feature to let it go to a second line as I have followup rows as detail sub-sections.

So what I'm thinking is if I can figure out how to naturally (ie on a space) break the line, similar to how "can grow" would break the line, via a formula, then I can create a formula that will match the second, third, etc. lines based on whether the follow up detail sub-sections are shown or suppressed.

ie:
Details A - has the initial row.

Details B - might have text, might be suppressed.

Details C - might have text, might be suppressed.

Details D - might have text, might be suppressed.

So I can create a formula so if Details B is not suppressed then the second line shows under Details B. With some fancy if statements (or other method?) I can have the followup lines show on Details B and/or C and/or D, depending on content, so the entire string can be displayed. I just haven't figured out how to break the initial string in a "natural" way like word wrap would.

DevLibSubType is the field that may be longer than the space and I want to be able to word wrap.
The subreports in Details B, C, and D are the subreports that may or may not have information that needs to be printed.

答:
You can achieve this effect with 4 Formulas, but you'll need to specify an appropriate number of characters for each line. (In theory you could calculate the length of each letter individually, but that's way overkill.) So instead assume that 100 characters per line is just right.

Your Details A formula might look like:

```<code>LEFT({yourString},100)
</code>```

Details B might look like:

```<code>IF LEN({yourString}) > 100 THEN MID({yourString},101,100)
</code>```

Details C would be like:

```<code>IF LEN({yourString}) > 200 THEN MID({yourString},201,100)
</code>```

And so on. You can add additional clauses if you want to break the line based on spaces or punctuation by iterating through the characters backwards until you encounter one of these. Then push the resulting length into a shared variable for the next formula to use.

Body:
You can achieve this effect with 4 Formulas, but you'll need to specify an appropriate number of characters for each line. (In theory you could calculate the length of each letter individually, but that's way overkill.) So instead assume that 100 characters per line is just right.

Your Details A formula might look like:

LEFT({yourString},100)

Details B might look like:

IF LEN({yourString}) > 100 THEN MID({yourString},101,100)

Details C would be like:

IF LEN({yourString}) > 200 THEN MID({yourString},201,100)

And so on. You can add additional clauses if you want to break the line based on spaces or punctuation by iterating through the characters backwards until you encounter one of these. Then push the resulting length into a shared variable for the next formula to use.


问:
How can I give access to certain objects in Firebase database based on id
I have this data structure:

The red arrows points at animal IDs, and the blue arrow points at user IDs. Every user have one or many animals.

I have tried different methods for showing only the animals that have id that is stored in the current user node.

Example: If I have UID = 48onHXIxgDP465j5WW16oo7psNm2 (the first one in "users") I want to show the data from: "dog2" and "dog3".

Now iIhave the following code that gets snapshot from the "animals" node in the database, and then gets data from every child.

```<code>     myAnimalRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            list = new ArrayList<AnimalCard>();
            for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){

                AnimalCard value = dataSnapshot1.getValue(AnimalCard.class);
                AnimalCard animal = new AnimalCard();
                String name = value.getName();
                int age = value.getAge();
                String url = value.getUrl();
                animal.setName(name);
                animal.setAge(age);
                animal.setUrl(url);
                list.add(animal);

            }
            recyclerViewSetAdapter();
            progressDialog.dismiss();

        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.d(TAG1, "failed to read value: " + databaseError.toException());
        }
    });
</code>```

How can get my code to filter out every animal that does not have their ID in the user node?

The reason I want to make the user get access with an UID stored in the database is because later on I want to make it so that multiple users can get access to the same animal.

答:
To achieve this, you need to query your database twice. Please use the following code:

```<code>FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
String uid = firebaseUser.getUid();

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = usersRef.child("users").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String aid = ds.getKey();

            DatabaseReference animalRef = rootRef.child("animals").child(aid);
            ValueEventListener valueEventListener = new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dSnapshot) {
                    int age = dSnapshot.child("age").getValue(Integer.class);
                    String name = dSnapshot.child("name").getValue(String.class);
                    String url = dSnapshot.child("url").getValue(String.class);
                    Log.d("TAG", age + " / " + name + " / " + url);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {}
            };
            animalRef.addListenerForSingleValueEvent(valueEventListener);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);
</code>```

In which uid is the id of the logged-in user and aid is the id of the animal. Your output will be:

```<code>11 / dog1 / http...
12 / dog2 / http...
</code>```

Body:
I have this data structure:

The red arrows points at animal IDs, and the blue arrow points at user IDs. Every user have one or many animals.

I have tried different methods for showing only the animals that have id that is stored in the current user node.

Example: If I have UID = 48onHXIxgDP465j5WW16oo7psNm2 (the first one in "users") I want to show the data from: "dog2" and "dog3".

Now iIhave the following code that gets snapshot from the "animals" node in the database, and then gets data from every child.

     myAnimalRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            list = new ArrayList<AnimalCard>();
            for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){

                AnimalCard value = dataSnapshot1.getValue(AnimalCard.class);
                AnimalCard animal = new AnimalCard();
                String name = value.getName();
                int age = value.getAge();
                String url = value.getUrl();
                animal.setName(name);
                animal.setAge(age);
                animal.setUrl(url);
                list.add(animal);

            }
            recyclerViewSetAdapter();
            progressDialog.dismiss();

        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.d(TAG1, "failed to read value: " + databaseError.toException());
        }
    });

How can get my code to filter out every animal that does not have their ID in the user node?

The reason I want to make the user get access with an UID stored in the database is because later on I want to make it so that multiple users can get access to the same animal.

Body:
To achieve this, you need to query your database twice. Please use the following code:

FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
String uid = firebaseUser.getUid();

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = usersRef.child("users").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String aid = ds.getKey();

            DatabaseReference animalRef = rootRef.child("animals").child(aid);
            ValueEventListener valueEventListener = new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dSnapshot) {
                    int age = dSnapshot.child("age").getValue(Integer.class);
                    String name = dSnapshot.child("name").getValue(String.class);
                    String url = dSnapshot.child("url").getValue(String.class);
                    Log.d("TAG", age + " / " + name + " / " + url);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {}
            };
            animalRef.addListenerForSingleValueEvent(valueEventListener);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);

In which uid is the id of the logged-in user and aid is the id of the animal. Your output will be:

11 / dog1 / http...
12 / dog2 / http...