问:
Would this be the right way of accessing variable from other class?
Would this be a right thing to do? I am trying to access the variable A defined in class random and read the variable 'A' value in some_other_class. Would this be the right way of accessing the variables from a different class?  </p>

```<code>public class random{
       int A = 10;

       public random(){
          // Does something
       }

    }

    public class some_other_class{

       //Creating a Class datatype variable to access vars from other class
       random accessing_random_class_vars;

       public some_other_class(){
          if(accessing_random_class_vars.A){
                 //Do something
             }
       }

    }
</code>```

答:
You should make variable A a private one and create getter and setter for variable A with public access modifier.

In the class some_other_class, call the getter and setter to access value of A.

This will encapsulate your class variables and protects them being updated outside of class. In the setA method you can add your conditions on which A can be modified.

```<code> public class random(){
      private int A = 10;

 public int getA(){ return A;}

 public void setA(int A){ this.A=A;}

       public random(){
          // Does something
       }

    }

    public class some_other_class {

       //Creating a Class datatype variable to access vars from other class
       random accessing_random_class_vars;

       public some_other_class(){
          if(accessing_random_class_vars.getA()){
                 //Do something
             }
       }

    }
</code>```

Body:
Would this be a right thing to do? I am trying to access the variable A defined in class random and read the variable 'A' value in some_other_class. Would this be the right way of accessing the variables from a different class?

public class random{
       int A = 10;

       public random(){
          // Does something
       }

    }

    public class some_other_class{

       //Creating a Class datatype variable to access vars from other class
       random accessing_random_class_vars;

       public some_other_class(){
          if(accessing_random_class_vars.A){
                 //Do something
             }
       }

    }

Body:
You should make variable A a private one and create getter and setter for variable A with public access modifier.

In the class some_other_class, call the getter and setter to access value of A.

This will encapsulate your class variables and protects them being updated outside of class. In the setA method you can add your conditions on which A can be modified.

 public class random(){
      private int A = 10;

 public int getA(){ return A;}

 public void setA(int A){ this.A=A;}

       public random(){
          // Does something
       }

    }

    public class some_other_class {

       //Creating a Class datatype variable to access vars from other class
       random accessing_random_class_vars;

       public some_other_class(){
          if(accessing_random_class_vars.getA()){
                 //Do something
             }
       }

    }


来源: stackexchange

问:
How to optimize API calls for a large dataset using Python?
Objective: Send a list of addresses to an API and extract certain information(eg: a flag which indicates if an address is in a flood zone or not).

Solution: Working Python script for small data.

Problem: I want to optimize my current solution for large input. How to improve the performance of the API calls. If I have 100,000 addresses will my current solution fail? Will this slow down the HTTP calls? Will I get a request TIME out? Does the API resist the number of API calls being made?

Input: a list of addresses

Sample input

777 Brockton Avenue, Abington MA 2351

30 Memorial Drive, Avon MA 2322

Output: A data frame of all addresses and a flag which indicates if it is in a flood zone or not.

API: https://hazards.fema.gov/gis/nfhl/rest/services/public/NFHL/MapServer/28/query.

My current solution works well for a small dataset.

```<code># Creating a function to get lat & long of the existing adress and then detecting the zone in fema
def zonedetect(addrs):
    global geolocate
    geocode_result = geocode(address=addrs, as_featureset=True)
    latitude = geocode_result.features[0].geometry.x
    longitude = geocode_result.features[0].geometry.y
    url = "https://hazards.fema.gov/gis/nfhl/rest/services/public/NFHL/MapServer/28/query?where=1%3D1&text=&objectIds=&time=&geometry="+str(latitude)+"%2C"+str(longitude)+"&geometryType=esriGeometryPoint&inSR=4326&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=*&returnGeometry=true&returnTrueCurves=false&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&returnDistinctValues=false&resultOffset=&resultRecordCount=&queryByDistance=&returnExtentsOnly=false&datumTransformation=&parameterValues=&rangeValues=&f=json"
    response = req.get(url)
    parsed_data = json.loads(response.text)
    formatted_data = json_normalize(parsed_data["features"])
    formatted_data["Address_1"] = addrs

    #Exception handling
    if response.status_code == 200:
        geolocate = geolocate.append(formatted_data, ignore_index = True)
    else:
        print("Request to {} failed".format(postcode))

# Reading every adress from existing dataframe
for i in range(len(df.index)):
    zonedetect(df["Address"][i])
</code>```

Instead of using the for loop above is there an alternative. Can I process this logic in a batch?

答:
Sending 100,000 requests to the hazards.fema.gov server will definitely cause some slow downs on their server but it will mostly impact your script as you will need to wait for every single HTTP request to be queued and responded to which could take an extremely long time to process.

What would be better is to send one REST query for everything you will need and then handle the logic afterwards. Looking at the REST API, you can find that the geometry URL parameter is able to accept a geometryMultiPoint from the docs. Here is an example of a multiPoint:

```<code>{
  "points" : [[-97.06138,32.837],[-97.06133,32.836],[-97.06124,32.834],[-97.06127,32.832]],
  "spatialReference" : {"wkid" : 4326}
}
</code>```

So what you can do is make an object to store all the points you want to query:

```<code>multipoint = { points: [], spatialReference: { wkid: 4326}
</code>```

And when you loop, append the lat/long point to the multipoint list:

```<code>for i in range(len(df.index)):
    address = df["Address"][i]
    geocode_result = geocode(address=addrs, as_featureset=True)
    latitude = geocode_result.features[0].geometry.x
    longitude = geocode_result.features[0].geometry.y
    multiPoint.points.append([latitude, longitude])
</code>```

Then you can set the multipoint as the geometry in your query which results in just one API request instead of one for each point.

ContentLicense: CC BY-SA 4.0

Body:
Objective: Send a list of addresses to an API and extract certain information(eg: a flag which indicates if an address is in a flood zone or not).

Solution: Working Python script for small data.

Problem: I want to optimize my current solution for large input. How to improve the performance of the API calls. If I have 100,000 addresses will my current solution fail? Will this slow down the HTTP calls? Will I get a request TIME out? Does the API resist the number of API calls being made?

Input: a list of addresses

Sample input

777 Brockton Avenue, Abington MA 2351

30 Memorial Drive, Avon MA 2322

Output: A data frame of all addresses and a flag which indicates if it is in a flood zone or not.

API: https://hazards.fema.gov/gis/nfhl/rest/services/public/NFHL/MapServer/28/query.

My current solution works well for a small dataset.

# Creating a function to get lat & long of the existing adress and then detecting the zone in fema
def zonedetect(addrs):
    global geolocate
    geocode_result = geocode(address=addrs, as_featureset=True)
    latitude = geocode_result.features[0].geometry.x
    longitude = geocode_result.features[0].geometry.y
    url = "https://hazards.fema.gov/gis/nfhl/rest/services/public/NFHL/MapServer/28/query?where=1%3D1&text=&objectIds=&time=&geometry="+str(latitude)+"%2C"+str(longitude)+"&geometryType=esriGeometryPoint&inSR=4326&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=*&returnGeometry=true&returnTrueCurves=false&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&returnDistinctValues=false&resultOffset=&resultRecordCount=&queryByDistance=&returnExtentsOnly=false&datumTransformation=&parameterValues=&rangeValues=&f=json"
    response = req.get(url)
    parsed_data = json.loads(response.text)
    formatted_data = json_normalize(parsed_data["features"])
    formatted_data["Address_1"] = addrs

    #Exception handling
    if response.status_code == 200:
        geolocate = geolocate.append(formatted_data, ignore_index = True)
    else:
        print("Request to {} failed".format(postcode))

# Reading every adress from existing dataframe
for i in range(len(df.index)):
    zonedetect(df["Address"][i])

Instead of using the for loop above is there an alternative. Can I process this logic in a batch?

Body:
Sending 100,000 requests to the hazards.fema.gov server will definitely cause some slow downs on their server but it will mostly impact your script as you will need to wait for every single HTTP request to be queued and responded to which could take an extremely long time to process.

What would be better is to send one REST query for everything you will need and then handle the logic afterwards. Looking at the REST API, you can find that the geometry URL parameter is able to accept a geometryMultiPoint from the docs. Here is an example of a multiPoint:

{
  "points" : [[-97.06138,32.837],[-97.06133,32.836],[-97.06124,32.834],[-97.06127,32.832]],
  "spatialReference" : {"wkid" : 4326}
}

So what you can do is make an object to store all the points you want to query:

multipoint = { points: [], spatialReference: { wkid: 4326}

And when you loop, append the lat/long point to the multipoint list:

for i in range(len(df.index)):
    address = df["Address"][i]
    geocode_result = geocode(address=addrs, as_featureset=True)
    latitude = geocode_result.features[0].geometry.x
    longitude = geocode_result.features[0].geometry.y
    multiPoint.points.append([latitude, longitude])

Then you can set the multipoint as the geometry in your query which results in just one API request instead of one for each point.


问:
Blazor select bind to a value in a list
I was able to bind an int type (which is the first element of the list SelectedDiagnosisIdList) variable to the selected element of a html select:

```<code><div>
    <label>Diagnosis:</label>
    <div>
        <select @bind="@userInfo.SelectedDiagnosisIdList[0]">
            @foreach (var item in diagnoses)
            {
                <option value="@item.Id">@item.Name</option>
            }
        </select>
        <p>@userInfo.SelectedDiagnosisIdList[0]"</p>
    </div>
</div>

@code
{
    List<int> SelectedDiagnosisIdList = new List<int>() { 0 };
    List<Diagnosis> diagnoses; //  populated from db in OnInitializedAsync

}
</code>```

This nicely works, the value of the paragraph changes when I change the selected value on the UI.

Now, I want to add more Diagnoses, so I am trying to maintain more s and add more elements to the SelectedDiagnosisIdList:

```<code><div>
    <label>Diagnosis:</label>
    <div>
        @for(int i = 0; i < userInfo.SelectedDiagnosisIdList.Count; i++)
            <select @bind="@userInfo.SelectedDiagnosisIdList[i]">
                @foreach (var item in diagnoses)
                {
                    <option value="@item.Id">@item.Name</option>
                }
            </select>
            <p>@userInfo.SelectedDiagnosisIdList[i]</p>
        }
    </div>
</div>

@code
{
    List<int> SelectedDiagnosisIdList = new List<int>() { 0 };
    List<Diagnosis> diagnoses; //  populated from db in OnInitializedAsync

}
</code>```

This will spoil the program, nothing happens on the UI when I select an item and on the console:

```<code>blazor.webassembly.js:1 WASM: Unhandled exception rendering component:
blazor.webassembly.js:1 WASM: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
WASM: Parameter name: index
blazor.webassembly.js:1 WASM:   at (wrapper managed-to-native) System.Reflection.RuntimeMethodInfo.InternalInvoke(System.Reflection.RuntimeMethodInfo,object,object[],System.Exception&)
blazor.webassembly.js:1 WASM:   at System.Reflection.RuntimeMethodInfo.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) <0x20c1360 + 0x000ce> in <71c4fd446b1842ba93fd332e5f4f9c06>:0
blazor.webassembly.js:1 WASM: --- End of stack trace from previous location where exception was thrown ---
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion (System.Threading.Tasks.Task task) <0x269de40 + 0x000e6> in <cbf249d7f04d4fa18d15bfae8ef7f389>:0
WASM:   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask (System.Threading.Tasks.Task taskToHandle) <0x269e988 + 0x000c2> in <cbf249d7f04d4fa18d15bfae8ef7f389>:0
</code>```

I dont' understand what is the problem and how could I make it work... Please help

答:
I guess your issue is related to for loop. You should define a local variable in your loop as follows:

```<code>    <div>
    @for(int i = 0; i < userInfo.SelectedDiagnosisIdList.Count; i++)
      {
        int local = i;
        <select id=$"dropdown{local+1}"
               @bind="@userInfo.SelectedDiagnosisIdList[local]">
            @foreach (var item in diagnoses)
            {
                <option value="@item.Id">@item.Name</option>
            }
        </select>
        <p>@userInfo.SelectedDiagnosisIdList[local]</p>
    }
    </div>
</code>```

Hope this helps...

Title: Blazor select bind to a value in a list

Body:
I was able to bind an int type (which is the first element of the list SelectedDiagnosisIdList) variable to the selected element of a html select:

    Diagnosis:

        <select @bind="@userInfo.SelectedDiagnosisIdList[0]">
            @foreach (var item in diagnoses)
            {
                <option value="@item.Id">@item.Name</option>
            }
        </select>

@userInfo.SelectedDiagnosisIdList[0]"

@code
{
    List<int> SelectedDiagnosisIdList = new List<int>() { 0 };
    List<Diagnosis> diagnoses; //  populated from db in OnInitializedAsync

}

This nicely works, the value of the paragraph changes when I change the selected value on the UI.

Now, I want to add more Diagnoses, so I am trying to maintain more s and add more elements to the SelectedDiagnosisIdList:

    Diagnosis:

        @for(int i = 0; i < userInfo.SelectedDiagnosisIdList.Count; i++)
            <select @bind="@userInfo.SelectedDiagnosisIdList[i]">
                @foreach (var item in diagnoses)
                {
                    <option value="@item.Id">@item.Name</option>
                }
            </select>

@userInfo.SelectedDiagnosisIdList[i]

        }

@code
{
    List<int> SelectedDiagnosisIdList = new List<int>() { 0 };
    List<Diagnosis> diagnoses; //  populated from db in OnInitializedAsync

}

This will spoil the program, nothing happens on the UI when I select an item and on the console:

blazor.webassembly.js:1 WASM: Unhandled exception rendering component:
blazor.webassembly.js:1 WASM: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
WASM: Parameter name: index
blazor.webassembly.js:1 WASM:   at (wrapper managed-to-native) System.Reflection.RuntimeMethodInfo.InternalInvoke(System.Reflection.RuntimeMethodInfo,object,object[],System.Exception&)
blazor.webassembly.js:1 WASM:   at System.Reflection.RuntimeMethodInfo.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) <0x20c1360 + 0x000ce> in <71c4fd446b1842ba93fd332e5f4f9c06>:0
blazor.webassembly.js:1 WASM: --- End of stack trace from previous location where exception was thrown ---
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion (System.Threading.Tasks.Task task) <0x269de40 + 0x000e6> in <cbf249d7f04d4fa18d15bfae8ef7f389>:0
WASM:   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask (System.Threading.Tasks.Task taskToHandle) <0x269e988 + 0x000c2> in <cbf249d7f04d4fa18d15bfae8ef7f389>:0

I dont' understand what is the problem and how could I make it work... Please help

Body:
I guess your issue is related to for loop. You should define a local variable in your loop as follows:

    <div>
    @for(int i = 0; i < userInfo.SelectedDiagnosisIdList.Count; i++)
      {
        int local = i;
        <select id=$"dropdown{local+1}"
               @bind="@userInfo.SelectedDiagnosisIdList[local]">
            @foreach (var item in diagnoses)
            {
                <option value="@item.Id">@item.Name</option>
            }
        </select>
        <p>@userInfo.SelectedDiagnosisIdList[local]</p>
    }
    </div>

Hope this helps...


问:
How to plot geographic points on a map with different colours and legend?
So I currently have a map (it's quite ugly, see attached)

I found a way to plot them on a top down view, but I would like to attach different colours and have it as a legend (and maybe zoom in), instead of the lettering on top of the points as shown in the first picture. Can anyone help me with this? Here's the ideal picture, but with a legend and different colours:

```<code>#libraries

  library(readr)
  library(sp)
  library(rgdal)
  library(raster)
  library(GISTools)
  library(sf)

#col_coor points to be plotted
 SUB        POP      LON   LAT
   <chr>      <chr>  <dbl> <dbl>
 1 mandtii    AK    -156.   71.2
 2 ultimus    NU     -82.5  65.9
 3 ultimus    GR     -70.2  76.5
 4 arcticus   LB     -61.7  56.6
 5 arcticus   NF     -53.6  47.3
 6 arcticus   ST     -69.7  47.8
 7 arcticus   NS     -61.5  45.1
 8 arcticus   NB     -66.8  44.6
 9 arcticus   ME     -68.2  44.2
10 islandicus IC     -22.9  65.4
11 grylle     FI      19.3  60.2

# Convert Lat & Lon data into a SPDF
col_loc <- sp::SpatialPointsDataFrame(col_coor[,3:4], col_coor)

# Assign a coordinate reference system
crs(col_loc) <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"

 radius <- 75000
  ColBuff<-raster::buffer(col_loc, width=(radius), filename='1000', doEdge=FALSE)

# Plot maximum flight radius polygons on base raster with continent boundaries
  data("wrld_simpl", package = "maptools")
  world_map <- crop(wrld_simpl, extent(-180, 180, 35, 90))
  plot(world_map, col="grey")
  plot(ColBuff, pch=20, col="red",add=TRUE)

# Convert WGS84 to Arctic polar stereographic projection (STERE)
  proj <- "+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 +k=1 +x_0=0 +y_0=0 +a=6378273 +b=6356889.449 +units=m +no_defs"
  wm_stere <- spTransform(world_map, CRSobj = CRS(proj))
  plot(wm_stere, col="grey")
  cb_stere <- spTransform(ColBuff, CRSobj = CRS(proj))
  plot(cb_stere, pch=20, col="red",add=TRUE)
</code>```

答:
I'm not 100% sure that I understand your questions but do you want to create something like this?

# packages
library(sf)
#> Linking to GEOS 3.6.1, GDAL 2.2.3, PROJ 4.9.3
library(magrittr)
library(tmap)

# points data
col_coor <- data.frame(
  SUB = c(
    "mandtii", "ultimus", "ultimus", "arcticus", "arcticus", "arcticus",
    "arcticus", "arcticus", "arcticus", "islandicus", "grylle"
  ),
  POP = c("AK", "NU", "GR", "LB", "NF", "ST", "NS", "NB", "ME", "IC", "FI"),
  LON = c(-156, -82.5, -70.2, -61.7, -53.6, -69.7, -61.5, -66.8, -68.2, -22.9, 19.3),
  LAT = c(71.2, 65.9, 76.5, 56.6, 47.3, 47.8, 45.1, 44.6, 44.2, 65.4, 60.2),
  stringsAsFactors = FALSE
)

new_crs <- "+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 +k=1 +x_0=0 +y_0=0 +a=6378273 +b=6356889.449 +units=m +no_defs"

col_coor <- col_coor %>%
  st_as_sf(coords = c("LON", "LAT"), crs = 4326) %>%
  st_transform(crs = new_crs)

# world data
data("wrld_simpl", package = "maptools")
wrld_simpl <- st_as_sf(wrld_simpl) %>%
  st_crop(xmin = -180, xmax = 180, ymin = 35, ymax = 90) %>%
  st_transform(crs = new_crs)
#> although coordinates are longitude/latitude, st_intersection assumes that they are planar
#> Warning: attribute variables are assumed to be spatially constant throughout all
#> geometries

# plot
tm_shape(wrld_simpl) +
  tm_polygons() +
  tm_shape(col_coor) +
  tm_dots(col = "POP", size = 0.33) +
  tm_layout(legend.outside = TRUE, legend.text.size = 1.25, legend.title.size = 1.25)
#> Warning: The shape wrld_simpl is invalid. See sf::st_is_valid
```

Created on 2020-02-14 by the reprex package (v0.3.0)

You can read several more details about tmap here: https://geocompr.robinlovelace.net/adv-map.html

Body:
So I currently have a map (it's quite ugly, see attached)

I found a way to plot them on a top down view, but I would like to attach different colours and have it as a legend (and maybe zoom in), instead of the lettering on top of the points as shown in the first picture. Can anyone help me with this? Here's the ideal picture, but with a legend and different colours:

#libraries

  library(readr)
  library(sp)
  library(rgdal)
  library(raster)
  library(GISTools)
  library(sf)

#col_coor points to be plotted
 SUB        POP      LON   LAT
   <chr>      <chr>  <dbl> <dbl>
 1 mandtii    AK    -156.   71.2
 2 ultimus    NU     -82.5  65.9
 3 ultimus    GR     -70.2  76.5
 4 arcticus   LB     -61.7  56.6
 5 arcticus   NF     -53.6  47.3
 6 arcticus   ST     -69.7  47.8
 7 arcticus   NS     -61.5  45.1
 8 arcticus   NB     -66.8  44.6
 9 arcticus   ME     -68.2  44.2
10 islandicus IC     -22.9  65.4
11 grylle     FI      19.3  60.2

# Convert Lat & Lon data into a SPDF
col_loc <- sp::SpatialPointsDataFrame(col_coor[,3:4], col_coor)

# Assign a coordinate reference system
crs(col_loc) <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"

 radius <- 75000
  ColBuff<-raster::buffer(col_loc, width=(radius), filename='1000', doEdge=FALSE)

# Plot maximum flight radius polygons on base raster with continent boundaries
  data("wrld_simpl", package = "maptools")
  world_map <- crop(wrld_simpl, extent(-180, 180, 35, 90))
  plot(world_map, col="grey")
  plot(ColBuff, pch=20, col="red",add=TRUE)

# Convert WGS84 to Arctic polar stereographic projection (STERE)
  proj <- "+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 +k=1 +x_0=0 +y_0=0 +a=6378273 +b=6356889.449 +units=m +no_defs"
  wm_stere <- spTransform(world_map, CRSobj = CRS(proj))
  plot(wm_stere, col="grey")
  cb_stere <- spTransform(ColBuff, CRSobj = CRS(proj))
  plot(cb_stere, pch=20, col="red",add=TRUE)

Body:
I'm not 100% sure that I understand your questions but do you want to create something like this?

# packages
library(sf)
#> Linking to GEOS 3.6.1, GDAL 2.2.3, PROJ 4.9.3
library(magrittr)
library(tmap)

# points data
col_coor <- data.frame(
  SUB = c(
    "mandtii", "ultimus", "ultimus", "arcticus", "arcticus", "arcticus",
    "arcticus", "arcticus", "arcticus", "islandicus", "grylle"
  ),
  POP = c("AK", "NU", "GR", "LB", "NF", "ST", "NS", "NB", "ME", "IC", "FI"),
  LON = c(-156, -82.5, -70.2, -61.7, -53.6, -69.7, -61.5, -66.8, -68.2, -22.9, 19.3),
  LAT = c(71.2, 65.9, 76.5, 56.6, 47.3, 47.8, 45.1, 44.6, 44.2, 65.4, 60.2),
  stringsAsFactors = FALSE
)

new_crs <- "+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 +k=1 +x_0=0 +y_0=0 +a=6378273 +b=6356889.449 +units=m +no_defs"

col_coor <- col_coor %>%
  st_as_sf(coords = c("LON", "LAT"), crs = 4326) %>%
  st_transform(crs = new_crs)

# world data
data("wrld_simpl", package = "maptools")
wrld_simpl <- st_as_sf(wrld_simpl) %>%
  st_crop(xmin = -180, xmax = 180, ymin = 35, ymax = 90) %>%
  st_transform(crs = new_crs)
#> although coordinates are longitude/latitude, st_intersection assumes that they are planar
#> Warning: attribute variables are assumed to be spatially constant throughout all
#> geometries

# plot
tm_shape(wrld_simpl) +
  tm_polygons() +
  tm_shape(col_coor) +
  tm_dots(col = "POP", size = 0.33) +
  tm_layout(legend.outside = TRUE, legend.text.size = 1.25, legend.title.size = 1.25)
#> Warning: The shape wrld_simpl is invalid. See sf::st_is_valid

Created on 2020-02-14 by the reprex package (v0.3.0)

You can read several more details about tmap here: https://geocompr.robinlovelace.net/adv-map.html


问:
Css: Bootstrap, importing only tables
How do I import only tables from the Bootstrap framework?

What I want to do: I have found a couple of table examples from Bootstrap that I really like which I would like to import into my project.

The issue: When importing Bootstrap, in addition to tables, there are changes to other tags such as h1, h2, title and html.

What I tried: I got a minimized/customized Bootstrap that supposedly has only tables, but there are still changes to h1, h2, etc.

答:
With bootstrap3 you were able to customize the package and just choose tables: https://getbootstrap.com/docs/3.4/customize/

With bootstrap4 this option is gone. So I you basically have two choices:

download the full package as unminified version and delete everything you don't need

download the bootstrap sources (SASS) and only compile the table stuff

Title: Css: Bootstrap, importing only tables


问:
Google apps script search in two columns get matching rows as 2D array
the following gs code is working well

```<code>function getData00(e) {
  var id = "SHEET_ID";
  var sheetname = "SHEET";
  var data = SpreadsheetApp.openById(id).getSheetByName(sheetname).getDataRange().getValues();
  var ar = [];
  data.forEach(function(f) {
    if (~f.indexOf(e.color)) {
      ar.push(f);
    }
  });
  return ar;
}
</code>```

So i can search in column for specific "color" value and get the corresponding row values.
Now i need to add another criteria to search also in another column and get the combined row values.

my spreadsheet:

```<code>Number |   color   |   level   |   price   |   size   |   type
1      |   red     |   first   |    25     |    4     |   local
2      |   blue    |   third   |    30     |    3     |   global
3      |   green   |   second  |    40     |    6     |   local
4      |   blue    |   second  |    60     |    5     |   global

</code>```

i need to search for "blue" in column B and for "local" in column F to get the matching rows values.

Result i am looking for:

```<code>2,blue,third,30,3,global
4,blue,second,60,5,global
</code>```

HTML:

```<code><html>
<body>
<p id="demo"></p>
</body>
</html>
<script>
function dispData(ar) {
 document.getElementById("demo").innerHTML = ar;
}
function getData00(e) {
  google.script.run.withSuccessHandler(dispData).getData00(e);
}
</script>
</code>```

Thanks in advance and appreciate any help

答:
You could use Array.filter to filter the source array to get the rows you want.

```<code>var matchingRows = data.filter(function(row){
    // check if column B equals "blue" and column F equals "local"
    return row[1] == "blue" && row[5] == "local";
});
</code>```

Column B is in the 2nd place, which is the 1st index in the array for each row. Column F is in the 6th place, which is the 5th index in the array for each row.

Body:
the following gs code is working well

function getData00(e) {
  var id = "SHEET_ID";
  var sheetname = "SHEET";
  var data = SpreadsheetApp.openById(id).getSheetByName(sheetname).getDataRange().getValues();
  var ar = [];
  data.forEach(function(f) {
    if (~f.indexOf(e.color)) {
      ar.push(f);
    }
  });
  return ar;
}

So i can search in column for specific "color" value and get the corresponding row values.
Now i need to add another criteria to search also in another column and get the combined row values.

my spreadsheet:

Number |   color   |   level   |   price   |   size   |   type
1      |   red     |   first   |    25     |    4     |   local
2      |   blue    |   third   |    30     |    3     |   global
3      |   green   |   second  |    40     |    6     |   local
4      |   blue    |   second  |    60     |    5     |   global

i need to search for "blue" in column B and for "local" in column F to get the matching rows values.

Result i am looking for:

2,blue,third,30,3,global
4,blue,second,60,5,global

HTML:

Thanks in advance and appreciate any help

Body:
You could use Array.filter to filter the source array to get the rows you want.

var matchingRows = data.filter(function(row){
    // check if column B equals "blue" and column F equals "local"
    return row[1] == "blue" && row[5] == "local";
});

Column B is in the 2nd place, which is the 1st index in the array for each row. Column F is in the 6th place, which is the 5th index in the array for each row.


问:
Iteratively INSERTing from a Dataframe
My question may be out of pure ignorance. Given an arbitrary dataframe of say 5 rows. I want to insert that dataframe into a DB (in my case it's postgresSQL). General code to do that is along the lines of:

```<code>   postgres_insert_query = """ INSERT INTO table (ID, MODEL, PRICE) VALUES (%s,%s,%s)"""    record_to_insert = (1, 'A', 100)    cursor.execute(postgres_insert_query, record_to_insert)
</code>```

Is it a common practice that when inserting more than one row of data, you iterate over your rows and do that?
It appears that every article or example I see is about inserting a single row to a DB.

答:
In python you could simply loop over your data frame and then do your inserts.

```<code>for record in dataframe:
    sql = '''INSERT INTO table (col1, col2, col3)
             VALUES ('{}', '{}', '{}')
          '''.format(record[1], record[0], record[2])
    dbo.execute(sql)
</code>```

This is highly simplistic. You may want to use something like sqlalchemy and make surre you use prepared statements. Never overlook security.

Title: Iteratively INSERTing from a Dataframe

Body:
My question may be out of pure ignorance. Given an arbitrary dataframe of say 5 rows. I want to insert that dataframe into a DB (in my case it's postgresSQL). General code to do that is along the lines of:

   postgres_insert_query = """ INSERT INTO table (ID, MODEL, PRICE) VALUES (%s,%s,%s)"""    record_to_insert = (1, 'A', 100)    cursor.execute(postgres_insert_query, record_to_insert)

Is it a common practice that when inserting more than one row of data, you iterate over your rows and do that?
It appears that every article or example I see is about inserting a single row to a DB.

Body:
In python you could simply loop over your data frame and then do your inserts.

for record in dataframe:
    sql = '''INSERT INTO table (col1, col2, col3)
             VALUES ('{}', '{}', '{}')
          '''.format(record[1], record[0], record[2])
    dbo.execute(sql)

This is highly simplistic. You may want to use something like sqlalchemy and make surre you use prepared statements. Never overlook security.


问:
Is it possible to getElementsByClassName with partial name on Vanilla Javascript?
I need to get all innerText of all elements that partially match a given string.

Heres a snippet of the code:

```<code><span class="18794221455sarasa">Some text</span>
</code>```

The class always ends with 'sarasa' the numbers are dynamic.
I want to run it on a chrome extension that's why I need it to be on plain Javascript

答:
No, you can't use getElementsByClassName like that.

But you can use querySelectorAll with a CSS attribute selector:

```<code>document.querySelectorAll('[class$="sarasa"]')
</code>```

will give you a collection of the DOM elements you want.

See an explanation of this selector here

Body:
I need to get all innerText of all elements that partially match a given string.

Heres a snippet of the code:

Some text

The class always ends with 'sarasa' the numbers are dynamic.
I want to run it on a chrome extension that's why I need it to be on plain Javascript

Body:
No, you can't use getElementsByClassName like that.

But you can use querySelectorAll with a CSS attribute selector:

document.querySelectorAll('[class$="sarasa"]')

will give you a collection of the DOM elements you want.

See an explanation of this selector here


问:
SQL select only last entry of date from a calculated field
Hey I'm trying to visualize a past 30 days trend as a line graph in metabase and therefore have to query the data in a right way.

The table looks like this:

```<code>    DATE                          SCORE
September 7, 2019, 12:00 AM         3
September 7, 2019, 12:00 AM         4
September 8, 2019, 12:00 AM         9
September 9, 2019, 12:00 AM         10
</code>```

I tried this query which calculates the NPS and the rolling sum over the last 30 rows.

```<code>select DATE,
        CASE
            WHEN SCORE <= 6 THEN '-1'
            WHEN SCORE <= 8 THEN '0'
            WHEN SCORE > 8 THEN '1'
        END AS NPS
        ,SUM(NPS) OVER(ORDER BY DATE ROWS BETWEEN 30 PRECEDING AND CURRENT ROW) AS NPSTotal
FROM Table;
</code>```

Which looks like this

```<code>    DATE                          NPS    NPSTotal
September 7, 2019, 12:00 AM         -1    -1
September 7, 2019, 12:00 AM         -1    -2
September 8, 2019, 12:00 AM         1     -1
September 9, 2019, 12:00 AM         1      0
</code>```

However, if I want to plot the results in metabase and put the date on the x-axis it naturally aggregates the NPSTotal, giving me a -3 for the 7 September instead of -2. I think the result of my query should look like this.

```<code>    DATE                        NPSTotal
September 7, 2019, 12:00 AM       -2
September 8, 2019, 12:00 AM       -1
September 9, 2019, 12:00 AM        0
</code>```

So I need two things:
1. Sum the NPS over the date of the column and all votes from the last 30 days instead of rows.
2. The output should give out only one NPSTotal entry per date, which should be the last value.

Would be happy if somebody has a solution for this.

答:
Here's the code I use in Mode to show NPS over many window sizes, over the last while but also only show windows where the start of the window is after the time point where we start collecting data.

```<code>WITH scores AS (
  SELECT score, date_Created::date AS date
  FROM db_name.nps.survey_answers
), days AS (
    SELECT column1 AS days FROM (values (1),(14),(35),(91),(105))
), wins_end AS (
    SELECT dateadd('day',ROW_NUMBER() over (order by SEQ8()),current_date) as win_date_end
    FROM table(generator(rowcount => 365*2.5))
), wins AS (
    SELECT d.days
        ,w.win_date_end
        ,dateadd('day',-d.days, w.win_date_end) AS win_date_start
    FROM days AS d
    JOIN wins_end AS w
)
SELECT w.days::text AS days
    ,w.win_date_end
    ,w.win_date_start
    ,AVG(score) AS a_score
    ,SUM(iff(score > 8,1,0)) AS promoter
    ,SUM(iff(score = 7 or score = 8,1,0)) AS pASsive
    ,SUM(iff(score < 7,1,0)) AS detractor
    ,COUNT(*) AS total
    ,ROUND((100*promoter/total)-(100*detractor/total),1) AS nps
FROM scores AS s
JOIN wins w ON s.date >= w.win_date_start AND s.date <= w.win_date_end
GROUP BY 1,2,3
HAVING win_date_start >= '2017-06-01'
</code>```

This gives to a sliding window start/end for each window size for the last 2.5 years (that bit could be made simpler) and the calculates the NPS for the window against the data set.

Body:
Hey I'm trying to visualize a past 30 days trend as a line graph in metabase and therefore have to query the data in a right way.

The table looks like this:

    DATE                          SCORE
September 7, 2019, 12:00 AM         3
September 7, 2019, 12:00 AM         4
September 8, 2019, 12:00 AM         9
September 9, 2019, 12:00 AM         10

I tried this query which calculates the NPS and the rolling sum over the last 30 rows.

select DATE,
        CASE
            WHEN SCORE <= 6 THEN '-1'
            WHEN SCORE <= 8 THEN '0'
            WHEN SCORE > 8 THEN '1'
        END AS NPS
        ,SUM(NPS) OVER(ORDER BY DATE ROWS BETWEEN 30 PRECEDING AND CURRENT ROW) AS NPSTotal
FROM Table;

Which looks like this

    DATE                          NPS    NPSTotal
September 7, 2019, 12:00 AM         -1    -1
September 7, 2019, 12:00 AM         -1    -2
September 8, 2019, 12:00 AM         1     -1
September 9, 2019, 12:00 AM         1      0

However, if I want to plot the results in metabase and put the date on the x-axis it naturally aggregates the NPSTotal, giving me a -3 for the 7 September instead of -2. I think the result of my query should look like this.

    DATE                        NPSTotal
September 7, 2019, 12:00 AM       -2
September 8, 2019, 12:00 AM       -1
September 9, 2019, 12:00 AM        0

So I need two things:
1. Sum the NPS over the date of the column and all votes from the last 30 days instead of rows.
2. The output should give out only one NPSTotal entry per date, which should be the last value.

Would be happy if somebody has a solution for this.

Body:
Here's the code I use in Mode to show NPS over many window sizes, over the last while but also only show windows where the start of the window is after the time point where we start collecting data.

WITH scores AS (
  SELECT score, date_Created::date AS date
  FROM db_name.nps.survey_answers
), days AS (
    SELECT column1 AS days FROM (values (1),(14),(35),(91),(105))
), wins_end AS (
    SELECT dateadd('day',ROW_NUMBER() over (order by SEQ8()),current_date) as win_date_end
    FROM table(generator(rowcount => 365*2.5))
), wins AS (
    SELECT d.days
        ,w.win_date_end
        ,dateadd('day',-d.days, w.win_date_end) AS win_date_start
    FROM days AS d
    JOIN wins_end AS w
)
SELECT w.days::text AS days
    ,w.win_date_end
    ,w.win_date_start
    ,AVG(score) AS a_score
    ,SUM(iff(score > 8,1,0)) AS promoter
    ,SUM(iff(score = 7 or score = 8,1,0)) AS pASsive
    ,SUM(iff(score < 7,1,0)) AS detractor
    ,COUNT(*) AS total
    ,ROUND((100*promoter/total)-(100*detractor/total),1) AS nps
FROM scores AS s
JOIN wins w ON s.date >= w.win_date_start AND s.date <= w.win_date_end
GROUP BY 1,2,3
HAVING win_date_start >= '2017-06-01'

This gives to a sliding window start/end for each window size for the last 2.5 years (that bit could be made simpler) and the calculates the NPS for the window against the data set.


问:
django mutlipleChoiceField how to validate?
i have the form below :

forms.py :

```<code>class enrolForm(forms.Form):
    CHOICES = [('male','male'),('female','female')]
    students = forms.MultipleChoiceField(choices = CHOICES)
</code>```

views.py :

```<code> form = enrolForm(request.POST)
 if form.is_valid():
            print "creating student"
            exam = models.Exam.objects.get(name=examName)
            .
            .#more code .......
</code>```

it NEVER  gets to ( print "creating student" ), the form is never valid  . why is that ?
how do i validate such a form
please help

EDIT :
it says in the form.errors :

 students

This field is required.

EDIT:

views.py :

```<code>def enrol(request,examName):
    print "EXAm naaame"
    form = enrolForm()
    allStudents = models.User.objects.filter(groups__name="students")
    myList = []

    for i in allStudents:
        myList.append((i,i))

    print allStudents,'33333333333333333333'

    form.fields['students'].choices = myList

    if request.method == 'POST':
        form = enrolForm(request.POST)

        if form.is_valid():
            exam = models.Exam.objects.get(name=examName)
            for i in form.cleaned_data['students']:

                user= models.User.objects.get(username=i)
                exam = models.Exam.objects.get(name= examName)
                models.Exam_Student.objects.create(user,exam)

            return render_to_response('enrol.html',RequestContext(request,{'form':form}))

    variables = RequestContext(request,{'form':form})
    return render_to_response("enrol.html",variables)
</code>```

答:
What's wrong with using a standard ChoiceField?

```<code>class enrolForm(forms.Form):
    CHOICES = [('male','male'),('female','female')]
    students = forms.ChoiceField(choices = CHOICES)
</code>```

Also doing this to view the errors and letting us know would be helpful:

```<code>if form.is_valid():
    print "creating student"
    exam = models.Exam.objects.get(name=examName)
    ...
else:
    print 'ERRORS:', form.errors
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i have the form below :

forms.py :

class enrolForm(forms.Form):
    CHOICES = [('male','male'),('female','female')]
    students = forms.MultipleChoiceField(choices = CHOICES)

views.py :

 form = enrolForm(request.POST)
 if form.is_valid():
            print "creating student"
            exam = models.Exam.objects.get(name=examName)
            .
            .#more code .......

it NEVER  gets to ( print "creating student" ), the form is never valid  . why is that ?
how do i validate such a form
please help

EDIT :
it says in the form.errors :

 students

This field is required.

EDIT:

views.py :

def enrol(request,examName):
    print "EXAm naaame"
    form = enrolForm()
    allStudents = models.User.objects.filter(groups__name="students")
    myList = []

    for i in allStudents:
        myList.append((i,i))

    print allStudents,'33333333333333333333'

    form.fields['students'].choices = myList

    if request.method == 'POST':
        form = enrolForm(request.POST)

        if form.is_valid():
            exam = models.Exam.objects.get(name=examName)
            for i in form.cleaned_data['students']:

                user= models.User.objects.get(username=i)
                exam = models.Exam.objects.get(name= examName)
                models.Exam_Student.objects.create(user,exam)

            return render_to_response('enrol.html',RequestContext(request,{'form':form}))

    variables = RequestContext(request,{'form':form})
    return render_to_response("enrol.html",variables)

Body:
What's wrong with using a standard ChoiceField?

class enrolForm(forms.Form):
    CHOICES = [('male','male'),('female','female')]
    students = forms.ChoiceField(choices = CHOICES)

Also doing this to view the errors and letting us know would be helpful:

if form.is_valid():
    print "creating student"
    exam = models.Exam.objects.get(name=examName)
    ...
else:
    print 'ERRORS:', form.errors


问:
Passing argument from fragment to activity using SafeArgs
Using navigation graph, when i navigate from fragment to activity and also passing argument using safeargs, in activity, I cannot get argument. How can I get argument passing from fragment???

In fragment, I can get argument by getArgument() function, but not in activity.

In fragment I switch to another activity by:

```<code>findNavController().navigate(AFragmentDirections.actionAFragmentToBActivity(1)
</code>```

and in B activity get argument in onCreate by :

```<code>val args = BActivityArgs.fromBundle(savedInstanceState!!)
</code>```

but my app crash immediately.

答:
The accepted answer is not an answer to your question. As you point out: you cannot use getArguments() in your Activity, you can only do that in a fragment. However, in an activity you can get the data like this (java syntax):

```<code>String aField = BActivityArgs.fromBundle(getIntent().getExtras()).getAField()
</code>```

So, just replace getArguments() with getIntent().getExtras() if you have an Activity on the receiving end.

Body:
Using navigation graph, when i navigate from fragment to activity and also passing argument using safeargs, in activity, I cannot get argument. How can I get argument passing from fragment???

In fragment, I can get argument by getArgument() function, but not in activity.

In fragment I switch to another activity by:

findNavController().navigate(AFragmentDirections.actionAFragmentToBActivity(1)

and in B activity get argument in onCreate by :

val args = BActivityArgs.fromBundle(savedInstanceState!!)

but my app crash immediately.

Body:
The accepted answer is not an answer to your question. As you point out: you cannot use getArguments() in your Activity, you can only do that in a fragment. However, in an activity you can get the data like this (java syntax):

String aField = BActivityArgs.fromBundle(getIntent().getExtras()).getAField()

So, just replace getArguments() with getIntent().getExtras() if you have an Activity on the receiving end.


问:
What does sklearn.linear_model RidgeCV normalize= parameter exactly do
I am confused by what normalized= exactly do in RidgeCV from sklearn.linear_model.

The documentation says:

normalize : bool, default=False
      This parameter is ignored when fit_intercept is set to False.
      If True, the regressors X will be normalized before regression by
      subtracting the mean and dividing by the l2-norm.
      If you wish to standardize, please use
      :class:sklearn.preprocessing.StandardScaler before calling fit
      on an estimator with normalize=False.

We generally refer to standardize as subtracting mean and divide by l2-norm. But the documentation is referring it as "normalize".

If I understand the documentation correctly, I should use the third block of code (last block) by following

```<code>If you wish to standardize, please use
:class:`sklearn.preprocessing.StandardScaler` before calling ``fit``
on an estimator with ``normalize=False``.
</code>```

But then, how do I interpret the coefficients?  Are these standardized coefficients? But looking at their magnitude, I doubt they are standardized coefficients.

Overall, I am not sure I have followed the documentation on this normalize parameter.

I will be testing similar code in other languages and see what I get.

```<code>from sklearn.datasets import load_diabetes
from sklearn.linear_model import RidgeCV
X, y = load_diabetes(return_X_y=True)
</code>```

without standardize

```<code>clf = RidgeCV(normalize=False,alphas=[1e-3, 1e-2, 1e-1, 1]).fit(X, y)
clf.coef_
print(clf.alpha_)
print(clf.score(X,y))
print(clf.coef_)
0.01
0.5166287840315846
[ -7.19945679 -234.55293001 520.58313622 320.52335582 -380.60706569 150.48375154 -78.59123221 130.31305868 592.34958662 71.1337681 ]

</code>```

standardize and normalize=True

```<code>from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X)
X_std = scaler.transform(X)
clf = RidgeCV(normalize=True,alphas=[1e-3, 1e-2, 1e-1, 1]).fit(X_std, y)
print("standardize and normalize=True")
print(clf.alpha_)
print(clf.score(X_std,y))
print(clf.coef_)

standardize and normalize=True
0.01
0.5166287840315843
[ -0.34244324 -11.15654516  24.76161466  15.24574131 -18.10363195
   7.15778213  -3.7382037    6.19836011  28.17519659   3.38348831]
</code>```

standardize and normalize=False

```<code>clf = RidgeCV(normalize=False,alphas=[1e-3, 1e-2, 1e-1, 1]).fit(X_std, y)
print("standardize and normalize=False")
print(clf.alpha_)
print(clf.score(X_std,y))
print(clf.coef_)

standardize and normalize=False
1.0
0.5175831607267165
[ -0.43127609 -11.33381407  24.77096198  15.37375716 -30.08858903
  16.65328714   1.46208255   7.5211415   32.84392268   3.26632702]
</code>```

答:
One has to interprete that normalize parameter to be standardize in sklearn.linear_model Ridge or RidgeCV.

This is a problem of the documentation in sklearn, which can cause confusions.  That parameter normalize should be corrected to standardize.

Anyway, I have verified the following with SAS PROC REG using the boston housing dataset, which is not standardized.

```<code>from sklearn.datasets import load_boston
dataset =load_boston()
X =dataset.data
y=dataset.target

clf = RidgeCV(normalize=True,alphas=[1e-3, 1e-2, 1e-1, 1]).fit(X, y)
clf.coef_
print(clf.alpha_)
print(clf.score(X,y))
print(clf.coef_)
coef =pd.DataFrame(zip(dataset.feature_names,clf.coef_)) #match SAS closely

0.01  (alpha)
0.7403788769476067 (R square)
0      CRIM  -0.103542
1        ZN   0.043406
2     INDUS   0.005200
3      CHAS   2.746307
4       NOX -16.625596
5        RM   3.865188
6       AGE  -0.000341
7       DIS  -1.413550
8       RAD   0.269159
9       TAX  -0.010577
10  PTRATIO  -0.934596
11        B   0.009288
12    LSTAT  -0.515911
</code>```

There is very negligible difference in the coefficients (the 6th decimal place), which could be due to rounding.

Body:
I am confused by what normalized= exactly do in RidgeCV from sklearn.linear_model.

The documentation says:

normalize : bool, default=False
      This parameter is ignored when fit_intercept is set to False.
      If True, the regressors X will be normalized before regression by
      subtracting the mean and dividing by the l2-norm.
      If you wish to standardize, please use
      :class:sklearn.preprocessing.StandardScaler before calling fit
      on an estimator with normalize=False.

We generally refer to standardize as subtracting mean and divide by l2-norm. But the documentation is referring it as "normalize".

If I understand the documentation correctly, I should use the third block of code (last block) by following

If you wish to standardize, please use
:class:`sklearn.preprocessing.StandardScaler` before calling ``fit``
on an estimator with ``normalize=False``.

But then, how do I interpret the coefficients?  Are these standardized coefficients? But looking at their magnitude, I doubt they are standardized coefficients.

Overall, I am not sure I have followed the documentation on this normalize parameter.

I will be testing similar code in other languages and see what I get.

from sklearn.datasets import load_diabetes
from sklearn.linear_model import RidgeCV
X, y = load_diabetes(return_X_y=True)

without standardize

clf = RidgeCV(normalize=False,alphas=[1e-3, 1e-2, 1e-1, 1]).fit(X, y)
clf.coef_
print(clf.alpha_)
print(clf.score(X,y))
print(clf.coef_)
0.01
0.5166287840315846
[ -7.19945679 -234.55293001 520.58313622 320.52335582 -380.60706569 150.48375154 -78.59123221 130.31305868 592.34958662 71.1337681 ]

standardize and normalize=True

from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X)
X_std = scaler.transform(X)
clf = RidgeCV(normalize=True,alphas=[1e-3, 1e-2, 1e-1, 1]).fit(X_std, y)
print("standardize and normalize=True")
print(clf.alpha_)
print(clf.score(X_std,y))
print(clf.coef_)

standardize and normalize=True
0.01
0.5166287840315843
[ -0.34244324 -11.15654516  24.76161466  15.24574131 -18.10363195
   7.15778213  -3.7382037    6.19836011  28.17519659   3.38348831]

standardize and normalize=False

clf = RidgeCV(normalize=False,alphas=[1e-3, 1e-2, 1e-1, 1]).fit(X_std, y)
print("standardize and normalize=False")
print(clf.alpha_)
print(clf.score(X_std,y))
print(clf.coef_)

standardize and normalize=False
1.0
0.5175831607267165
[ -0.43127609 -11.33381407  24.77096198  15.37375716 -30.08858903
  16.65328714   1.46208255   7.5211415   32.84392268   3.26632702]

Body:
One has to interprete that normalize parameter to be standardize in sklearn.linear_model Ridge or RidgeCV.

This is a problem of the documentation in sklearn, which can cause confusions.  That parameter normalize should be corrected to standardize.

Anyway, I have verified the following with SAS PROC REG using the boston housing dataset, which is not standardized.

from sklearn.datasets import load_boston
dataset =load_boston()
X =dataset.data
y=dataset.target

clf = RidgeCV(normalize=True,alphas=[1e-3, 1e-2, 1e-1, 1]).fit(X, y)
clf.coef_
print(clf.alpha_)
print(clf.score(X,y))
print(clf.coef_)
coef =pd.DataFrame(zip(dataset.feature_names,clf.coef_)) #match SAS closely

0.01  (alpha)
0.7403788769476067 (R square)
0      CRIM  -0.103542
1        ZN   0.043406
2     INDUS   0.005200
3      CHAS   2.746307
4       NOX -16.625596
5        RM   3.865188
6       AGE  -0.000341
7       DIS  -1.413550
8       RAD   0.269159
9       TAX  -0.010577
10  PTRATIO  -0.934596
11        B   0.009288
12    LSTAT  -0.515911

There is very negligible difference in the coefficients (the 6th decimal place), which could be due to rounding.


问:
ERROR in importing tensorflow. DLL load failed
I installed tensorflow 1.8.0 using the command

```<code>pip3 install --upgrade tensorflow
</code>```

It was installed properly, but when I typed the command

```<code>`import tensorflow as tf`
</code>```

the following errors came:

```<code>  Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 14, in swig_import_helper
    return importlib.import_module(mname)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 658, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 571, in module_from_spec
  File "<frozen importlib._bootstrap_external>", line 922, in create_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
ImportError: DLL load failed: %1 is not a valid Win32 application.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 17, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 16, in swig_import_helper
    return importlib.import_module('_pywrap_tensorflow_internal')
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named '_pywrap_tensorflow_internal'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    import tensorflow as tf
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 14, in swig_import_helper
    return importlib.import_module(mname)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 658, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 571, in module_from_spec
  File "<frozen importlib._bootstrap_external>", line 922, in create_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
ImportError: DLL load failed: %1 is not a valid Win32 application.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 17, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 16, in swig_import_helper
    return importlib.import_module('_pywrap_tensorflow_internal')
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named '_pywrap_tensorflow_internal'

Failed to load the native TensorFlow runtime.
</code>```

I searched a lot. I even installed tensorflow once more, but in vain.
I could not find any solution in internet. Can someone help me? Thank you in advance. :)

答: I had exactly the same problem in my Windows 7 64 bits. In my case,  TensorFlow 2.1 for Python 3.7.6 has installed OK. When I run a small demo gives this error. So I've installed the Microsoft Visual C++ Redistributable for Visual Studio 2015, 2017 and 2019, X64 version and everything works as charm.

Body:
I installed tensorflow 1.8.0 using the command

pip3 install --upgrade tensorflow

It was installed properly, but when I typed the command

`import tensorflow as tf`

the following errors came:

  Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 14, in swig_import_helper
    return importlib.import_module(mname)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 658, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 571, in module_from_spec
  File "<frozen importlib._bootstrap_external>", line 922, in create_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
ImportError: DLL load failed: %1 is not a valid Win32 application.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 17, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 16, in swig_import_helper
    return importlib.import_module('_pywrap_tensorflow_internal')
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named '_pywrap_tensorflow_internal'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    import tensorflow as tf
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 14, in swig_import_helper
    return importlib.import_module(mname)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 658, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 571, in module_from_spec
  File "<frozen importlib._bootstrap_external>", line 922, in create_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
ImportError: DLL load failed: %1 is not a valid Win32 application.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 17, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 16, in swig_import_helper
    return importlib.import_module('_pywrap_tensorflow_internal')
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named '_pywrap_tensorflow_internal'

Failed to load the native TensorFlow runtime.

I searched a lot. I even installed tensorflow once more, but in vain.
I could not find any solution in internet. Can someone help me? Thank you in advance. :)


问:
Powershell looping through files to pass to a program as a parameter
I have the following two cmd.exe commands, but I need to convert them to Powershell, and I've failed miserably trying to figure it out. Line 1 is finding a dll, but only when in a bin folder and line two then takes all the entries it finds and runs a command with it, e.g. bin\Debug\file, bin\Release\file

Can anyone help? The only limitation is this is inside a yaml runner file so I don't think I can split lines for each part, e.g. I don't think a Foreach-Object will work.

```<code>dir /s /b RunnerUnitTest.dll | findstr /r bin\\ > tests_list.txt
for /f %f in (tests_list.txt) do vstest.console.exe "%f"
</code>```

I got as far as this

```<code>(gci -r RunnerUnitTest.dll).FullName | select-string bin
</code>```

thanks.

答:
Write a multi-line powershell script to do the work and then call that script from your yaml runner. </p>

```<code>powershell -file "c:\myscripts\runtests.ps1" "c:\mydlls\RunnerUnitTest.dll" "c:\mytests\tests_list.txt"
</code>```

Body:
I have the following two cmd.exe commands, but I need to convert them to Powershell, and I've failed miserably trying to figure it out. Line 1 is finding a dll, but only when in a bin folder and line two then takes all the entries it finds and runs a command with it, e.g. bin\Debug\file, bin\Release\file

Can anyone help? The only limitation is this is inside a yaml runner file so I don't think I can split lines for each part, e.g. I don't think a Foreach-Object will work.

dir /s /b RunnerUnitTest.dll | findstr /r bin\\ > tests_list.txt
for /f %f in (tests_list.txt) do vstest.console.exe "%f"

I got as far as this

(gci -r RunnerUnitTest.dll).FullName | select-string bin

thanks.

Body:
Write a multi-line powershell script to do the work and then call that script from your yaml runner.

powershell -file "c:\myscripts\runtests.ps1" "c:\mydlls\RunnerUnitTest.dll" "c:\mytests\tests_list.txt"


问:
How can I check which file is a function in?
I'm working with PHP and sometimes, I want to find where the function being used is located. How can I do this easily without tracing through everything?</p>

答: you can use the notepad++ find in files function, works wonders.</p>


问:
Rename Parameter in Lambda Expression C#
I have the following problem in my lambda expression: I need to rename the property because it will be passed from entity to entity. In other words: I need to use the same expression in more than one query in different entities.

For example:

```<code>var expr = x => x.Id == converterId
</code>```

To be

```<code>var expr = x => x.ConverterId == converterId
</code>```

I have tried to do the following

```<code>var oldParam = expr.Parameters[0];
var newParam = Expression.Parameter(oldParam.Type, "ConverterId");
</code>```

This code replaces x not Id`

答:
This isn't trivial, but can be done my writing (subclassing) an ExpressionVisitor, and overriding VisitMember, making the substitution for a different Expression.Property, but using the original target expression (from the expression in the original lambda)

However, for simple cases, it is probably easier to forget that, and just build the expression-tree manually from first principles, rather than using a lambda.

The following shows both approaches:

using System;
using System.Linq.Expressions;

static class P
{
    static void Main()
    {
        // the compiler-generated expression-tree from the question
        Console.WriteLine(Baseline(42));

        // build our own epression trees manually
        Console.WriteLine(ByName(42, nameof(Foo.Id)));
        Console.WriteLine(ByName(42, nameof(Foo.ConverterId)));

        // take the compiler-generated expression tree, and rewrite it with a visitor
        Console.WriteLine(Convert(Baseline(42), nameof(Foo.Id), nameof(Foo.ConverterId)));
    }
    static Expression<Func<Foo, bool>> Baseline(int converterId)
    {
        // note this uses a "captured variable", so the output
        // looks uglier than you might expect
        return x => x.Id == converterId;
    }
    static Expression<Func<Foo, bool>> ByName(int converterId, string propertyOrFieldName)
    {
        var p = Expression.Parameter(typeof(Foo), "x");
        var body = Expression.Equal(
            Expression.PropertyOrField(p, propertyOrFieldName),
            Expression.Constant(converterId, typeof(int))
            );
        return Expression.Lambda<Func<Foo, bool>>(body, p);
    }

    static Expression<Func<Foo, bool>> Convert(
        Expression<Func<Foo, bool>> lambda, string from, string to)
    {
        var visitor = new ConversionVisitor(from, to);
        return (Expression<Func<Foo, bool>>)visitor.Visit(lambda);
    }
    class ConversionVisitor : ExpressionVisitor
    {
        private readonly string _from, _to;
        public ConversionVisitor(string from, string to)
        {
            _from = from;
            _to = to;
        }
        protected override Expression VisitMember(MemberExpression node)
        {
            if(node.Member.Name == _from)
            {
                return Expression.PropertyOrField(
                    node.Expression, _to);
            }
            return base.VisitMember(node);
        }

    }
}
class Foo
{
    public int Id { get; set; }

    public int ConverterId { get; set; }
}
```

Body:
I have the following problem in my lambda expression: I need to rename the property because it will be passed from entity to entity. In other words: I need to use the same expression in more than one query in different entities.

For example:

var expr = x => x.Id == converterId

To be

var expr = x => x.ConverterId == converterId

I have tried to do the following

var oldParam = expr.Parameters[0];
var newParam = Expression.Parameter(oldParam.Type, "ConverterId");

This code replaces x not Id`


问:
R Group by with conditional and sum other columns using data.table
I want to sum all columns except one specific column based on the condition by groups.

For example:

```<code>Col1    Col2   Condition   Name    P1    P2    P3    P4
1990    1      0           APPLE   10    20    20    30
1990    1      1           BAN     30    40    50    50
1990    1      1           CAR     40    40    30    40
1990    2      0           DOG     100   20    30    40
1990    2      1           APPLE   10    20    20    30
1990    2      1           APPLE   50    20    20    30
</code>```

I want to SUM P2, P3, P4 and then APPEND P1 when Condition equals to "0" by Col1 and Col2.

So the result will be:

```<code>Col1    Col2   Condition     P1    P2     P3    P4
1990    1      0             10    100    100   120
1990    2      0             100   60     70    100
</code>```

I know how to add in data.table but have no idea with this.

```<code>DT[, .(lapply(.SD, sum, na.rm=TRUE), by=.(Col1, Col2), .SDcols=c("P2", "P3", "P4")]
</code>```

It seems that DT[, setdiff(names(DT), c("P2", "P3", "P4")), with = FALSE] is a key but still have no idea.

答:
We can group by 'Col1', 'Col2', then summarise_at the columns that starts_with 'P' (changed to range of columns as per OP's request) to get the sum of values where 'Condition' is 0 and then create a 'Condition' column of 0

```<code>library(dplyr)
df1 %>%
  group_by(Col1, Col2) %>%
  group_by(P1 = sum(P1[Condition == 0]), add = TRUE) %>%
  summarise_at(vars(P2:P4), sum) %>%
  mutate(Condition = 0) %>%
  ungroup
# A tibble: 2 x 7
#   Col1  Col2    P1    P2    P3    P4 Condition
#  <int> <int> <int> <int> <int> <int>     <dbl>
#1  1990     1    10   100   100   120         0
#2  1990     2   100    60    70   100         0
</code>```

Or using data.table

```<code>library(data.table)
setDT(df1)[,  P1 := sum(P1[Condition == 0]), .(Col1, Col2)][,
     lapply(.SD, sum) , .(Col1, Col2, P1), .SDcols = P2:P4]
</code>```

Body:
I want to sum all columns except one specific column based on the condition by groups.

For example:

Col1    Col2   Condition   Name    P1    P2    P3    P4
1990    1      0           APPLE   10    20    20    30
1990    1      1           BAN     30    40    50    50
1990    1      1           CAR     40    40    30    40
1990    2      0           DOG     100   20    30    40
1990    2      1           APPLE   10    20    20    30
1990    2      1           APPLE   50    20    20    30

I want to SUM P2, P3, P4 and then APPEND P1 when Condition equals to "0" by Col1 and Col2.

So the result will be:

Col1    Col2   Condition     P1    P2     P3    P4
1990    1      0             10    100    100   120
1990    2      0             100   60     70    100

I know how to add in data.table but have no idea with this.

DT[, .(lapply(.SD, sum, na.rm=TRUE), by=.(Col1, Col2), .SDcols=c("P2", "P3", "P4")]

It seems that DT[, setdiff(names(DT), c("P2", "P3", "P4")), with = FALSE] is a key but still have no idea.

Body:
We can group by 'Col1', 'Col2', then summarise_at the columns that starts_with 'P' (changed to range of columns as per OP's request) to get the sum of values where 'Condition' is 0 and then create a 'Condition' column of 0

library(dplyr)
df1 %>%
  group_by(Col1, Col2) %>%
  group_by(P1 = sum(P1[Condition == 0]), add = TRUE) %>%
  summarise_at(vars(P2:P4), sum) %>%
  mutate(Condition = 0) %>%
  ungroup
# A tibble: 2 x 7
#   Col1  Col2    P1    P2    P3    P4 Condition
#  <int> <int> <int> <int> <int> <int>     <dbl>
#1  1990     1    10   100   100   120         0
#2  1990     2   100    60    70   100         0

Or using data.table

library(data.table)
setDT(df1)[,  P1 := sum(P1[Condition == 0]), .(Col1, Col2)][,
     lapply(.SD, sum) , .(Col1, Col2, P1), .SDcols = P2:P4]


问:
Web Audio API: performance problems?
I've got a little chime maker going here. It generates several overtones at once, and uses variable gain on each overtone to produce a rich chime sound. I call a function to play a series of these in sequence. But if I rapidly press the button a few times, the sound output stops, as though it's running out of memory:

https://codepen.io/ophello/pen/OJVRMQe

function ding(freq) {
    var toneGen = new AudioContext()
    var duration = 15
    var T = toneGen.currentTime
    var overtones = [1,2.76,5.4,8.93,13.34,18.64]
    overtones.forEach(function(overtone,i) {
        var osc = toneGen.createOscillator()
        osc.type = "sine"
        var freqVal = freq * overtone
        if (freqVal <= 22050) {
            osc.frequency.value = freq * overtone
            var envelope = toneGen.createGain()
            osc.connect(envelope)
            envelope.gain.setValueAtTime(0.1/Math.pow((i+1),5), T)
            envelope.gain.exponentialRampToValueAtTime(0.00001, T + duration)
            envelope.connect(toneGen.destination)
            osc.start(T)
            osc.stop(T + duration)
        }
    })
}

var hzValues = [216, 288, 324, 405, 432, 648]

$("#b1").mousedown(() => {
    hzValues.forEach((thisHz,i) => {
        setTimeout(() => { ding(thisHz) }, 100 * i);
    })
})
```

Why does this stop working after a few presses? Am I missing something critical here? I don't know where in the console to look for any problems with this. Is this a memory issue?

答:
Thanks to dandavis above, I got this working by adding a timeout function:

```<code>setTimeout(toneGen.close.bind(toneGen), duration*1000);
</code>```

Update: Improved by moving the audio context outside the main function!

Title: Web Audio API: performance problems?

Body:
I've got a little chime maker going here. It generates several overtones at once, and uses variable gain on each overtone to produce a rich chime sound. I call a function to play a series of these in sequence. But if I rapidly press the button a few times, the sound output stops, as though it's running out of memory:

https://codepen.io/ophello/pen/OJVRMQe

function ding(freq) {
    var toneGen = new AudioContext()
    var duration = 15
    var T = toneGen.currentTime
    var overtones = [1,2.76,5.4,8.93,13.34,18.64]
    overtones.forEach(function(overtone,i) {
        var osc = toneGen.createOscillator()
        osc.type = "sine"
        var freqVal = freq * overtone
        if (freqVal <= 22050) {
            osc.frequency.value = freq * overtone
            var envelope = toneGen.createGain()
            osc.connect(envelope)
            envelope.gain.setValueAtTime(0.1/Math.pow((i+1),5), T)
            envelope.gain.exponentialRampToValueAtTime(0.00001, T + duration)
            envelope.connect(toneGen.destination)
            osc.start(T)
            osc.stop(T + duration)
        }
    })
}

var hzValues = [216, 288, 324, 405, 432, 648]

$("#b1").mousedown(() => {
    hzValues.forEach((thisHz,i) => {
        setTimeout(() => { ding(thisHz) }, 100 * i);
    })
})

Why does this stop working after a few presses? Am I missing something critical here? I don't know where in the console to look for any problems with this. Is this a memory issue?

Body:
Thanks to dandavis above, I got this working by adding a timeout function:

setTimeout(toneGen.close.bind(toneGen), duration*1000);

Update: Improved by moving the audio context outside the main function!


问:
Why my nested If statement is not generating cout?
I have two problems with my code. The first one is when the code is executed for second time and so on, it skip the first cin command but it does generate the first cout. My second problem is that if I input a value true for the lowers if statement I don't generate the cout. Everything else is working correctly except for does two thing</p>

```<code>#include "pch.h"
#include <iostream>
#include <string>
#include <random>
#include <ctime>>

using namespace std;
int main()
{
    mt19937 generator;
    generator.seed(time(0));
    uniform_int_distribution<uint32_t>dice(1000, 9999);

    int ownderID=dice(generator);
    string ownerName;
    string dogName;
    string dogBreed;
    float dogAge;
    float dogWgt;
    int exits;
    int weekCost = 0;
    int dogAmount = 0;
    int dailyPrice = 0;

    do
    {
        cout << "Owner Name: ";
        getline(cin, ownerName);
        cout << endl;

        cout << "Dog Name: ";
        getline(cin, dogName);
        cout << endl;

        cout << "Dog Breed: ";
        getline(cin, dogBreed);
        cout << endl;

        cout << "Dog Age: ";
        cin >> dogAge;
        cout << endl;

        cout << "Dog Weight in lb: ";
        cin >> dogWgt;
        cout << endl;

        cout << "Daily Bill" << endl;
        cout << "Owner Name: " << ownerName << " ID" << "[" << ownderID << "]" << endl;
        cout << "Dog Name: " << dogName << endl;
        cout << "Dog Age: " << dogAge << endl;
        cout << "Dog Breed: " << dogBreed << endl;

        if (0<dogWgt && dogWgt <= 15)
        {
            dailyPrice = 55;
            weekCost += 55;
            if (15 < dogWgt && dogWgt <= 30)
            {
                dailyPrice = 75;
                weekCost += 75;
                if (30 < dogWgt && dogWgt <= 80)
                {
                    dailyPrice = 105;
                    weekCost += 105;
                    if (dogWgt > 80)
                    {
                        dailyPrice = 125;
                        cout << "Daily Cost for (" << dogWgt << ") is $" << dailyPrice << endl;
                        weekCost += 125;
                    }
                }
            }
        }

        cout << "To terminate enter -1; To add another dog information enter 1: ";
        cin >> exits;
        cout << endl;

        dogAmount += 1;

    } while (exits != -1);
    cout << "Total week cost: " << weekCost << endl;
    cout << "Total number of daycare entries: " << dogAmount << " dogs" << endl;
    system("PAUSE");
}
</code>```

答:
In the very end of the do-while loop insert the following call to remove the new line character from the input stream that is leaved there after this statement

```<code>cin >> exits;
</code>```

That is

```<code>#include <limits>

//...

    cin >> exits;
    cout << endl;
    std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

    dogAmount += 1;

} while (exits != -1);
</code>```

Substitute these nested if statements

```<code>    if (0<dogWgt && dogWgt <= 15)
    {
        dailyPrice = 55;
        weekCost += 55;
        if (15 < dogWgt && dogWgt <= 30)
        {
            dailyPrice = 75;
            weekCost += 75;
            if (30 < dogWgt && dogWgt <= 80)
            {
                dailyPrice = 105;
                weekCost += 105;
                if (dogWgt > 80)
                {
                    dailyPrice = 125;
                    cout << "Daily Cost for (" << dogWgt << ") is $" << dailyPrice << endl;
                    weekCost += 125;
                }
            }
        }
    }
</code>```

for if-else statements like

```<code>    if (0<dogWgt && dogWgt <= 15)
    {
        dailyPrice = 55;
        weekCost += 55;
    }
    else if (15 < dogWgt && dogWgt <= 30)
    {
        dailyPrice = 75;
        weekCost += 75;
    }
    else if (30 < dogWgt && dogWgt <= 80)
    {
        dailyPrice = 105;
        weekCost += 105;
    }
    else // (dogWgt > 80)
    {
        dailyPrice = 125;
        cout << "Daily Cost for (" << dogWgt << ") is $" << dailyPrice << endl;
        weekCost += 125;
    }
</code>```

Or maybe you mean that the last else statement should be

```<code>    else // (dogWgt > 80)
    {
        dailyPrice = 125;
        weekCost += 125;
    }
</code>```

after which this statement follows

```<code>    cout << "Daily Cost for (" << dogWgt << ") is $" << dailyPrice << endl;
</code>```

Body:
I have two problems with my code. The first one is when the code is executed for second time and so on, it skip the first cin command but it does generate the first cout. My second problem is that if I input a value true for the lowers if statement I don't generate the cout. Everything else is working correctly except for does two thing

#include "pch.h"
#include <iostream>
#include <string>
#include <random>
#include <ctime>>

using namespace std;
int main()
{
    mt19937 generator;
    generator.seed(time(0));
    uniform_int_distribution<uint32_t>dice(1000, 9999);

    int ownderID=dice(generator);
    string ownerName;
    string dogName;
    string dogBreed;
    float dogAge;
    float dogWgt;
    int exits;
    int weekCost = 0;
    int dogAmount = 0;
    int dailyPrice = 0;

    do
    {
        cout << "Owner Name: ";
        getline(cin, ownerName);
        cout << endl;

        cout << "Dog Name: ";
        getline(cin, dogName);
        cout << endl;

        cout << "Dog Breed: ";
        getline(cin, dogBreed);
        cout << endl;

        cout << "Dog Age: ";
        cin >> dogAge;
        cout << endl;

        cout << "Dog Weight in lb: ";
        cin >> dogWgt;
        cout << endl;

        cout << "Daily Bill" << endl;
        cout << "Owner Name: " << ownerName << " ID" << "[" << ownderID << "]" << endl;
        cout << "Dog Name: " << dogName << endl;
        cout << "Dog Age: " << dogAge << endl;
        cout << "Dog Breed: " << dogBreed << endl;

        if (0<dogWgt && dogWgt <= 15)
        {
            dailyPrice = 55;
            weekCost += 55;
            if (15 < dogWgt && dogWgt <= 30)
            {
                dailyPrice = 75;
                weekCost += 75;
                if (30 < dogWgt && dogWgt <= 80)
                {
                    dailyPrice = 105;
                    weekCost += 105;
                    if (dogWgt > 80)
                    {
                        dailyPrice = 125;
                        cout << "Daily Cost for (" << dogWgt << ") is $" << dailyPrice << endl;
                        weekCost += 125;
                    }
                }
            }
        }

        cout << "To terminate enter -1; To add another dog information enter 1: ";
        cin >> exits;
        cout << endl;

        dogAmount += 1;

    } while (exits != -1);
    cout << "Total week cost: " << weekCost << endl;
    cout << "Total number of daycare entries: " << dogAmount << " dogs" << endl;
    system("PAUSE");
}

Body:
In the very end of the do-while loop insert the following call to remove the new line character from the input stream that is leaved there after this statement

cin >> exits;

That is

#include <limits>

//...

    cin >> exits;
    cout << endl;
    std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

    dogAmount += 1;

} while (exits != -1);

Substitute these nested if statements

    if (0<dogWgt && dogWgt <= 15)
    {
        dailyPrice = 55;
        weekCost += 55;
        if (15 < dogWgt && dogWgt <= 30)
        {
            dailyPrice = 75;
            weekCost += 75;
            if (30 < dogWgt && dogWgt <= 80)
            {
                dailyPrice = 105;
                weekCost += 105;
                if (dogWgt > 80)
                {
                    dailyPrice = 125;
                    cout << "Daily Cost for (" << dogWgt << ") is $" << dailyPrice << endl;
                    weekCost += 125;
                }
            }
        }
    }

for if-else statements like

    if (0<dogWgt && dogWgt <= 15)
    {
        dailyPrice = 55;
        weekCost += 55;
    }
    else if (15 < dogWgt && dogWgt <= 30)
    {
        dailyPrice = 75;
        weekCost += 75;
    }
    else if (30 < dogWgt && dogWgt <= 80)
    {
        dailyPrice = 105;
        weekCost += 105;
    }
    else // (dogWgt > 80)
    {
        dailyPrice = 125;
        cout << "Daily Cost for (" << dogWgt << ") is $" << dailyPrice << endl;
        weekCost += 125;
    }

Or maybe you mean that the last else statement should be

    else // (dogWgt > 80)
    {
        dailyPrice = 125;
        weekCost += 125;
    }

after which this statement follows

    cout << "Daily Cost for (" << dogWgt << ") is $" << dailyPrice << endl;


问:
confusion related to implicit contructors and constructor chaining
As per constructor chaining base constructor should be called when a derived class object is created and assigned to base class reference.
And there is no default constructor in base class but then there is an explicit parameterized constructor, so java compiler does not provide default constroctor.
Without the statement "this(10);" compiler complains but then as soon as its added, compiler is fine with it. WHY??

I mean why does it not try to call the base class default constructor after adding "this(10);". It should have done a super call and then executed the added statement.

```<code>class Parent{
    public Parent(int a) {
        System.out.println(a);
    }
}
class Child extends Parent{
    public Child(){
        this(10);//default value
    }
    public Child(int a) {
        super(a);
        System.out.println(a);
    }
}
</code>```

答:
Because if you don't add this() to Child() constructor - compiler will insert super() statement and thus expect no-arg constructor in Parent class.

```<code>class Parent{
    public Parent(int a) {
        System.out.println(a);
    }
}
class Child extends Parent{
    public Child(){
        // this(10);// Commenting this(10) as if it did not exist.
        super() // inserted by compiler unless you put this() or super() yourself
    }
    public Child(int a) {
        super(a);
        System.out.println(a);
    }
}
</code>```

Body:
As per constructor chaining base constructor should be called when a derived class object is created and assigned to base class reference.
And there is no default constructor in base class but then there is an explicit parameterized constructor, so java compiler does not provide default constroctor.
Without the statement "this(10);" compiler complains but then as soon as its added, compiler is fine with it. WHY??

I mean why does it not try to call the base class default constructor after adding "this(10);". It should have done a super call and then executed the added statement.

class Parent{
    public Parent(int a) {
        System.out.println(a);
    }
}
class Child extends Parent{
    public Child(){
        this(10);//default value
    }
    public Child(int a) {
        super(a);
        System.out.println(a);
    }
}

Body:
Because if you don't add this() to Child() constructor - compiler will insert super() statement and thus expect no-arg constructor in Parent class.

class Parent{
    public Parent(int a) {
        System.out.println(a);
    }
}
class Child extends Parent{
    public Child(){
        // this(10);// Commenting this(10) as if it did not exist.
        super() // inserted by compiler unless you put this() or super() yourself
    }
    public Child(int a) {
        super(a);
        System.out.println(a);
    }
}


答:
you can use:</p>

```<code>document.querySelectorAll("[class$=sarasa]")
</code>```

Title: Is it possible to getElementsByClassName with partial name on Vanilla Javascript?

Body:
I need to get all innerText of all elements that partially match a given string.

Heres a snippet of the code:

Some text

The class always ends with 'sarasa' the numbers are dynamic.
I want to run it on a chrome extension that's why I need it to be on plain Javascript

Body:
you can use:

document.querySelectorAll("[class$=sarasa]")


问:
Python: Condense DataFrame column values into a single cell
If I have a DataFrame df:

```<code>import pandas as pd

d = {'col1': ['Google','Yahoo','LinkedIn'],
     'col2': ['Microsoft', 'Oracle', 'Uber']}
df = pd.DataFrame(data=d)
</code>```

How can I concatenate these columns values into single cells joined with "&", like:

```<code>       col1                          col2
0     'Google'&'Yahoo'&'LinkedIn'   'Microsoft'&'Oracle'&'Uber'
</code>```

Thanks.

答:
Is this what you're after?

Just create a list from the Series (column) values and use the str.join() function to concatenate the values.  Then, add back into a new DataFrame.

Sample Code:

```<code>import pandas as pd

# Initial dataset.
data1 = {'col1': ['Google','Yahoo','LinkedIn'],
         'col2': ['Microsoft', 'Oracle', 'Uber']}
df = pd.DataFrame(data=data1)

# Derived dataset.
data2 = {'col1': '&'.join(df['col1'].tolist()),
         'col2': '&'.join(df['col2'].tolist())}
df2 = pd.DataFrame(data2, index=[0])
</code>```

Output:

```<code>    col1                    col2
0   Google&Yahoo&LinkedIn   Microsoft&Oracle&Uber
</code>```

Body:
If I have a DataFrame df:

import pandas as pd

d = {'col1': ['Google','Yahoo','LinkedIn'],
     'col2': ['Microsoft', 'Oracle', 'Uber']}
df = pd.DataFrame(data=d)

How can I concatenate these columns values into single cells joined with "&", like:

       col1                          col2
0     'Google'&'Yahoo'&'LinkedIn'   'Microsoft'&'Oracle'&'Uber'

Thanks.

Body:
Is this what you're after?

Just create a list from the Series (column) values and use the str.join() function to concatenate the values.  Then, add back into a new DataFrame.

Sample Code:

import pandas as pd

# Initial dataset.
data1 = {'col1': ['Google','Yahoo','LinkedIn'],
         'col2': ['Microsoft', 'Oracle', 'Uber']}
df = pd.DataFrame(data=data1)

# Derived dataset.
data2 = {'col1': '&'.join(df['col1'].tolist()),
         'col2': '&'.join(df['col2'].tolist())}
df2 = pd.DataFrame(data2, index=[0])

Output:

    col1                    col2
0   Google&Yahoo&LinkedIn   Microsoft&Oracle&Uber