问:
Change a marker depending on the clicked option from a select dropdown list
I have a map with two markers (a from point and a to point), with a calculation of the distance between the two points. I am trying to make a dropdown list that when an option is clicked, the second point (to point) is changed and so with the calculated distance.

I am stuck on thinking how to implement it and have no solutions in mind. My goal is that when either Cebu City or Davao City is selected from the dropdown, then their respective points show up on the map and the calculated distance from Manila (which is the point of reference) is displayed:

    window.onload = function() {

    var coords = {
      manila: {name: "Manila", lat: 14.590, lon: 120.979},
      cebu:  {name: "Cebu", lat: 10.309, lon: 123.893},
      davao: {name: "Davao", lat: 7.063, lon: 125.608}
    };

    var map = L.map('mapid').setView([coords.manila.lat,coords.manila.lon], 13);

    // add layer to map:
    L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        'attribution': 'Map data © OpenStreetMap contributors'
    }).addTo(map);

    L.marker([coords.manila.lat,coords.manila.lon]).addTo(map);

    function createMarker()
    {
      var markerFrom = L.circleMarker([coords.manila.lat, coords.manila.lon], { color: "#F00", radius: 10 });
      var markerTo =  L.circleMarker([coords.cebu.lat, coords.cebu.lon], { color: "#4AFF00", radius: 10 });
      var from = markerFrom.getLatLng();
      var to = markerTo.getLatLng();
      markerFrom.bindPopup(coords.manila.name + ' ' + (from).toString());
      markerTo.bindPopup(coords.cebu.name + ' ' + (to).toString());
      map.addLayer(markerTo);
      map.addLayer(markerFrom);
      getDistance(from, to);
    }

    function getDistance(from, to)
    {
     var container = document.getElementById('distance');
        container.innerHTML = (coords.manila.name + " to " + coords.cebu.name + " - " + (from.distanceTo(to)).toFixed(0)/1000) + ' km';
    }

    createMarker();
    };```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#mapid { width: 400px; height: 300px;"}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.5.1/leaflet.css" rel="stylesheet"/>

<select>
<option value="manila">Manila</option>
<option value="cebu">Cebu City</option>
<option value="davao">Davao City</option>
</select>```

答:
You need to keep track of your markers if you want to change/delete them. So, instead of creating local variables in your createMarker function, create public variables where you can access them later.

Step 1:

```<code>var markerFrom;
var markerTo;

function createMarker()
{
     markerFrom = L.circleMarker([coords.manila.lat, coords.manila.lon], { color: "#F00", radius: 10 });
     markerTo =  L.circleMarker([coords.cebu.lat, coords.cebu.lon], { color: "#4AFF00", radius: 10 });
     var from = markerFrom.getLatLng();
     var to = markerTo.getLatLng();
     markerFrom.bindPopup(coords.manila.name + ' ' + (from).toString());
     markerTo.bindPopup(coords.cebu.name + ' ' + (to).toString());
     map.addLayer(markerTo);
     map.addLayer(markerFrom);
     getDistance(from, to);
}
</code>```

next you need to know when the value of your select changes.

Step 2:

add change listener to your select.

```<code>var destinationSelect = document.getElementById("cmbDestination");

destinationSelect.addEventListener("change", function() {

});
</code>```

inside your change function you need to remove your current destination marker, add new destination marker and update your distance.

Step 3:

```<code>destinationSelect.addEventListener("change", function() {
    // remove marker
    map.removeLayer(markerTo);

   // get selected value of select
   markerTo = // set selected value from select

   // add new marker according to the selected value
   map.addLayer(markerTo);

   // calculate distance
   var from = markerFrom.getLatLng();
   var to = markerTo.getLatLng();
   getDistance(from);
});
</code>```

Body:
I have a map with two markers (a from point and a to point), with a calculation of the distance between the two points. I am trying to make a dropdown list that when an option is clicked, the second point (to point) is changed and so with the calculated distance.

I am stuck on thinking how to implement it and have no solutions in mind. My goal is that when either Cebu City or Davao City is selected from the dropdown, then their respective points show up on the map and the calculated distance from Manila (which is the point of reference) is displayed:

    window.onload = function() {

    var coords = {
      manila: {name: "Manila", lat: 14.590, lon: 120.979},
      cebu:  {name: "Cebu", lat: 10.309, lon: 123.893},
      davao: {name: "Davao", lat: 7.063, lon: 125.608}
    };

    var map = L.map('mapid').setView([coords.manila.lat,coords.manila.lon], 13);

    // add layer to map:
    L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        'attribution': 'Map data © OpenStreetMap contributors'
    }).addTo(map);

    L.marker([coords.manila.lat,coords.manila.lon]).addTo(map);

    function createMarker()
    {
      var markerFrom = L.circleMarker([coords.manila.lat, coords.manila.lon], { color: "#F00", radius: 10 });
      var markerTo =  L.circleMarker([coords.cebu.lat, coords.cebu.lon], { color: "#4AFF00", radius: 10 });
      var from = markerFrom.getLatLng();
      var to = markerTo.getLatLng();
      markerFrom.bindPopup(coords.manila.name + ' ' + (from).toString());
      markerTo.bindPopup(coords.cebu.name + ' ' + (to).toString());
      map.addLayer(markerTo);
      map.addLayer(markerFrom);
      getDistance(from, to);
    }

    function getDistance(from, to)
    {
     var container = document.getElementById('distance');
        container.innerHTML = (coords.manila.name + " to " + coords.cebu.name + " - " + (from.distanceTo(to)).toFixed(0)/1000) + ' km';
    }

    createMarker();
    };

#mapid { width: 400px; height: 300px;"}

<link href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.5.1/leaflet.css" rel="stylesheet"/>

<select>
<option value="manila">Manila</option>
<option value="cebu">Cebu City</option>
<option value="davao">Davao City</option>
</select>

Body:
You need to keep track of your markers if you want to change/delete them. So, instead of creating local variables in your createMarker function, create public variables where you can access them later.

Step 1:

var markerFrom;
var markerTo;

function createMarker()
{
     markerFrom = L.circleMarker([coords.manila.lat, coords.manila.lon], { color: "#F00", radius: 10 });
     markerTo =  L.circleMarker([coords.cebu.lat, coords.cebu.lon], { color: "#4AFF00", radius: 10 });
     var from = markerFrom.getLatLng();
     var to = markerTo.getLatLng();
     markerFrom.bindPopup(coords.manila.name + ' ' + (from).toString());
     markerTo.bindPopup(coords.cebu.name + ' ' + (to).toString());
     map.addLayer(markerTo);
     map.addLayer(markerFrom);
     getDistance(from, to);
}

next you need to know when the value of your select changes.

Step 2:

add change listener to your select.

var destinationSelect = document.getElementById("cmbDestination");

destinationSelect.addEventListener("change", function() {

});

inside your change function you need to remove your current destination marker, add new destination marker and update your distance.

Step 3:

destinationSelect.addEventListener("change", function() {
    // remove marker
    map.removeLayer(markerTo);

   // get selected value of select
   markerTo = // set selected value from select

   // add new marker according to the selected value
   map.addLayer(markerTo);

   // calculate distance
   var from = markerFrom.getLatLng();
   var to = markerTo.getLatLng();
   getDistance(from);
});


来源: stackexchange

问:
Nodejs and MySQL, How to use NodeJs variable in MySQL INSERT statement
So basically, I have this JavaScript variable which stores this certain value, and I need to put this variable in MySQL Query statement.

Source Code:

```<code>var Pollution_Reading = 25;
DatabaseConnection.query('INSERT INTO Air_Pollution_Record (Air_Pollution_Reading) VALUES ('"Pollution_Reading"')');
</code>```

I've tried every way that I know, but I still can't insert the value that the variable is holding into the database. What should I do?

答:
Try doing this:</p>

```<code>//reading  post data
const useremail = req.body.useremail;
const password = req.body.password;
//save into db start
var sql = "INSERT INTO `users` (`UserName`, `UserPassword`) VALUES ('"+useremail+"','"+ password+"')";
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So basically, I have this JavaScript variable which stores this certain value, and I need to put this variable in MySQL Query statement.

Source Code:

var Pollution_Reading = 25;
DatabaseConnection.query('INSERT INTO Air_Pollution_Record (Air_Pollution_Reading) VALUES ('"Pollution_Reading"')');

I've tried every way that I know, but I still can't insert the value that the variable is holding into the database. What should I do?

Body:
Try doing this:

//reading  post data
const useremail = req.body.useremail;
const password = req.body.password;
//save into db start
var sql = "INSERT INTO `users` (`UserName`, `UserPassword`) VALUES ('"+useremail+"','"+ password+"')";

ContentLicense: CC BY-SA 4.0


问:
Inserting contact to Samsung I9000 Galaxy S returns an exception
I have this code for inserting contacts tested on all HTC devices and it seems to be working fine until I tried it on a Samsung I9000 Galaxy S which gives me a java.lang.NullPointerException on this particular line of code

```<code>String strDisplayName = "First Name" + " " + "LastName";
values.put(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, strDisplayName);
Uri rawContactUri = context.getContentResolver().insert(RawContacts.CONTENT_URI, values); //java.lang.NullPointerException here
</code>```

It seems like this URI doesn't exist or maybe samsung has a different way on inserting contacts. Has anyone experience this on samsung galaxy device? Please share your thoughts.

Thanks

答:
You are inserting into RawContacts but this does not have a column DISPLAY_NAME column. This is part of the RawContacts.Data entity.
Your insert should look like this:

```<code>ArrayList<ContentProviderOperation> ops =
          new ArrayList<ContentProviderOperation>();

 int rawContactInsertIndex = ops.size();
 ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
          .build());

 ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
          .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
          .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
          .withValue(StructuredName.DISPLAY_NAME, strDisplayName)
          .build());

 getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
</code>```

This code won't run on all devices though as you should also specifiy and account to create the contact in. Where do you want to create the contact? A phone contact? A google contact? IIRC I think on Galaxy S to create a phone contact you should set the account type and name to blank (not null). That would change the first operation to:

```<code> ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
          .withValue(RawContacts.ACCOUNT_TYPE, "")
          .withValue(RawContacts.ACCOUNT_NAME, "")
          .build());
</code>```

Body:
I have this code for inserting contacts tested on all HTC devices and it seems to be working fine until I tried it on a Samsung I9000 Galaxy S which gives me a java.lang.NullPointerException on this particular line of code

String strDisplayName = "First Name" + " " + "LastName";
values.put(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, strDisplayName);
Uri rawContactUri = context.getContentResolver().insert(RawContacts.CONTENT_URI, values); //java.lang.NullPointerException here

It seems like this URI doesn't exist or maybe samsung has a different way on inserting contacts. Has anyone experience this on samsung galaxy device? Please share your thoughts.

Thanks

Body:
You are inserting into RawContacts but this does not have a column DISPLAY_NAME column. This is part of the RawContacts.Data entity.
Your insert should look like this:

ArrayList<ContentProviderOperation> ops =
          new ArrayList<ContentProviderOperation>();

 int rawContactInsertIndex = ops.size();
 ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
          .build());

 ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
          .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
          .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
          .withValue(StructuredName.DISPLAY_NAME, strDisplayName)
          .build());

 getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);

This code won't run on all devices though as you should also specifiy and account to create the contact in. Where do you want to create the contact? A phone contact? A google contact? IIRC I think on Galaxy S to create a phone contact you should set the account type and name to blank (not null). That would change the first operation to:

 ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
          .withValue(RawContacts.ACCOUNT_TYPE, "")
          .withValue(RawContacts.ACCOUNT_NAME, "")
          .build());


问:
Identifying duplicates in a table and kicking duplicate records to a another table
I have some employee records in my table and we are identifying duplicates in them based on one field called workno. My data in TABLE_A is shown below

```<code>NAME  WORKNO       DATE
---------------------------
John     30000  09-JAN-2012
Franklin 40000  08-DEC-2014
Alicia   25000  19-JUL-2013
Jennifer 43000  20-JUL-2015
Gary     38000  15-SEP-2016
Joyce    25000  31-JAN-2017
Ahmad    25000  29-MAR-2017
James    55000  10-APR-2017
Jill     43000  12-OCT-2017
Jack     55000  18-JAN-2018
</code>```

Imagine there are close to a million records here. So need help with efficiency

My required output:-

Scenario 1: Keeping the records which has no duplicate(based on workno) in table_A itself. from the above table only John, Franklin and Gary should be there at the end since they have no duplicates with workno.

Scenario 2: the first record for a particular workno(incase of duplicates) should be written to table_B. "Alicia" with workno 25000 would be kicked into Table_B

Scenario 3: After writing the first duplicate to table_B the remaining records should be inserted into table_C. "Joyce" and "Ahmad" with workno would be kicked into table_C

I have tried to write my query which works fine for scenario 1 and 2. Need help if there is a better way if doing. But the insert part throws me error(query part works fine though).

Error report:

SQL Error: ORA-01847: day of month must be between 1 and last day of month
  01847. 00000 -  "day of month must be between 1 and last day of month"
  *Cause:

  *Action:

```<code>Insert into ztempo
Select *
from (SELECT fname, minit, lname, bdate, address, sex, salary, superssn, dno,
             ROW_NUMBER() OVER (PARTITION BY salary ORDER BY rownum) num
      from  Select *
            from ztemp
            where salary in (Select salary from ztemp group by salary having Count(*) > 1)

           )

     )
where num = 1;
</code>```

I guess I can use the same code with some tweaking at the end "where num > 1" for scenario 3. But have problem inserting. Please help

Need help completing it. Thanks in advance.

答:
--SCENARIO 1: Deleting the duplicates from source table after inserting to other tables

```<code>Delete from table_a where workno in ( Select workno from table_a group by workno having count(*) > 1);
</code>```

--SCENARIO 2: Inserting the first duplicate

```<code>Insert into table_b Select fname, Workno, ord_date
from
(
     SELECT fname, workno, ord_date,
     ROW_NUMBER() OVER (PARTITION BY workno ORDER BY rownum) num from
     (
     Select * from table_a
     where workno in (
                      Select workno from table_a group by workno having count(*) > 1
                      )
      )
)
     where num = 1;
</code>```

--SCENARIO 3: Inserting the other duplicate rows

```<code>Insert into table_c Select fname, Workno, ord_date
from
(
      SELECT fname, workno, ord_date,
      ROW_NUMBER() OVER (PARTITION BY workno ORDER BY rownum) num from
      (
      Select * from table_a
      where workno in (
                       Select workno from table_a group by workno having count(*) > 1
                       )
       )
)
      where num > 1;
</code>```

Is this the efficient way to go through a million records. Let me know if there is any other solution. Thanks!

Body:
I have some employee records in my table and we are identifying duplicates in them based on one field called workno. My data in TABLE_A is shown below

NAME  WORKNO       DATE
---------------------------
John     30000  09-JAN-2012
Franklin 40000  08-DEC-2014
Alicia   25000  19-JUL-2013
Jennifer 43000  20-JUL-2015
Gary     38000  15-SEP-2016
Joyce    25000  31-JAN-2017
Ahmad    25000  29-MAR-2017
James    55000  10-APR-2017
Jill     43000  12-OCT-2017
Jack     55000  18-JAN-2018

Imagine there are close to a million records here. So need help with efficiency

My required output:-

Scenario 1: Keeping the records which has no duplicate(based on workno) in table_A itself. from the above table only John, Franklin and Gary should be there at the end since they have no duplicates with workno.

Scenario 2: the first record for a particular workno(incase of duplicates) should be written to table_B. "Alicia" with workno 25000 would be kicked into Table_B

Scenario 3: After writing the first duplicate to table_B the remaining records should be inserted into table_C. "Joyce" and "Ahmad" with workno would be kicked into table_C

I have tried to write my query which works fine for scenario 1 and 2. Need help if there is a better way if doing. But the insert part throws me error(query part works fine though).

Error report:

SQL Error: ORA-01847: day of month must be between 1 and last day of month
  01847. 00000 -  "day of month must be between 1 and last day of month"
  *Cause:

  *Action:

Insert into ztempo
Select *
from (SELECT fname, minit, lname, bdate, address, sex, salary, superssn, dno,
             ROW_NUMBER() OVER (PARTITION BY salary ORDER BY rownum) num
      from  Select *
            from ztemp
            where salary in (Select salary from ztemp group by salary having Count(*) > 1)

           )

     )
where num = 1;

I guess I can use the same code with some tweaking at the end "where num > 1" for scenario 3. But have problem inserting. Please help

Need help completing it. Thanks in advance.

Body:
--SCENARIO 1: Deleting the duplicates from source table after inserting to other tables

Delete from table_a where workno in ( Select workno from table_a group by workno having count(*) > 1);

--SCENARIO 2: Inserting the first duplicate

Insert into table_b Select fname, Workno, ord_date
from
(
     SELECT fname, workno, ord_date,
     ROW_NUMBER() OVER (PARTITION BY workno ORDER BY rownum) num from
     (
     Select * from table_a
     where workno in (
                      Select workno from table_a group by workno having count(*) > 1
                      )
      )
)
     where num = 1;

--SCENARIO 3: Inserting the other duplicate rows

Insert into table_c Select fname, Workno, ord_date
from
(
      SELECT fname, workno, ord_date,
      ROW_NUMBER() OVER (PARTITION BY workno ORDER BY rownum) num from
      (
      Select * from table_a
      where workno in (
                       Select workno from table_a group by workno having count(*) > 1
                       )
       )
)
      where num > 1;

Is this the efficient way to go through a million records. Let me know if there is any other solution. Thanks!


问:
Is 5.5.56 version Mariadb dump is compatible with Mariadb 5.5.60?
I want to take mariadb database dump (version 5.5.56) and I want to import on mariadb (5.5.60), Is it compatible? Can I import it?

Also do I need to take dump of whole databases? or just individual databases? if so, do I need to import inbuilt schema also "information_schema", "performance_schema", "mysql" ? what is advisable?

```<code> mysqldump -S '/var/lib/mysql/mysql.sock' -u root -proot --host=localhost --single-transaction --all-databases --master-data=1 > ~/hadoopMYSQL.out
</code>```

答:
Minor versions (5.5.xx to 5.5.yy) should always be compatible.  Major (5.5 to 5.6) may be compatible.  But...

Do not try to import information_schema or performance_schema.  mysql is iffy -- it may need mysql_upgrade to be applied if there are schema changes.  And it is very likely to be 'wrong' to import that into 8.0.

Body:
I want to take mariadb database dump (version 5.5.56) and I want to import on mariadb (5.5.60), Is it compatible? Can I import it?

Also do I need to take dump of whole databases? or just individual databases? if so, do I need to import inbuilt schema also "information_schema", "performance_schema", "mysql" ? what is advisable?

 mysqldump -S '/var/lib/mysql/mysql.sock' -u root -proot --host=localhost --single-transaction --all-databases --master-data=1 > ~/hadoopMYSQL.out


问:
How to handle evaluation of list of functions in R
I'm trying to figure out how to deal with custom aggregation function which will work with dplyr's evaluation principles. I'd like to create a function of a shape:

```<code>custom_aggregation <- function (data, stat_funs = list(mean, median), agg_col, ...)
</code>```

where data is a data.frame, stat_funs is a list of functions to apply, agg_col indicates on which column the functions will be applied, ... are grouping columns.

For a single aggreation function I use code like this:

```<code>custom_aggregation <- function (data, stat_fun, agg_col, ...) {

  groups <- enquos(...)
  agg_col <- enquo(agg_col)
  stat_fun_enq <- enquo(stat_fun)
  agg_name <- paste0(quo_name(agg_col), '', quo_name(stat_fun_enq))

  data %>%
    group_by(!!!groups) %>%
    summarise(!!agg_name := stat_fun(!!agg_col))
}

# I can try to call the function on mtcars data.frame:
custom_aggregation(mtcars, stat_fun = mean, agg_col = qsec, cyl, am)
</code>```

I have no idea how to handle a list of function (stat_fun argument).

I tried:

```<code>map(stat_fun, enquo) # and the basic lapply equivalent with variants

lapply(stat_fun, function(i) {
  stat_fun_enq <- enquo(i)
})

lapply(seq_along(stat_fun), function(i) {
  stat_fun_enq <- enquo(stat_fun[[i]])
})
</code>```

Can someone guide me with what I'm doing wrong?

答:
An option would be pass the functions as a quosure list and then map through the list, evaluate (!!) to apply the function

```<code>library(tidyverse)
custom_aggregation <- function (data, stat_fun, agg_col, ...) {

  groups <- enquos(...)
  agg_col <- enquo(agg_col)
  agg_name <- rlang::as_name(stat_fun)
  data %>%
        group_by(!!! groups) %>%
         summarise((!!agg_name) := (!!stat_fun)(!!agg_col))

}
</code>```

Not clear about the expected output format

```<code>quos(mean, median)  %>%
      map(~ custom_aggregation(mtcars, stat_fun = .x, agg_col = qsec, cyl, am))
#[[1]]
# A tibble: 6 x 3
# Groups:   cyl [3]
#    cyl    am  mean
#  <dbl> <dbl> <dbl>
#1     4     0  21.0
#2     4     1  18.4
#3     6     0  19.2
#4     6     1  16.3
#5     8     0  17.1
#6     8     1  14.6

#[[2]]
# A tibble: 6 x 3
# Groups:   cyl [3]
#    cyl    am median
#  <dbl> <dbl>  <dbl>
#1     4     0   20.0
#2     4     1   18.6
#3     6     0   19.2
#4     6     1   16.5
#5     8     0   17.4
#6     8     1   14.6
</code>```

Update

If we need in a single dataset

```<code>library(rlang)
custom_aggregation <- function (data, stat_fun, agg_col, ...) {

  groups <- enquos(...)
  agg_col <- enquo(agg_col)

  nm1 <- str_c(rlang::as_name(agg_col),
       map_chr(rlang::call_args(rlang::enexpr(stat_fun)),
             rlang::as_name), sep="_")

  data %>%
         group_by(!!! groups) %>%
         summarise_at(vars(rlang::as_name(agg_col)), stat_fun) %>%
         rename_at(vars(starts_with('fn')), ~ nm1)

}
</code>```

-testing

```<code>custom_aggregation(mtcars, stat_fun = list(sum), agg_col = qsec, cyl, am)    # A tibble: 6 x 3
# Groups:   cyl [3]
#    cyl    am  qsec
#  <dbl> <dbl> <dbl>
#1     4     0  62.9
#2     4     1 148.
#3     6     0  76.9
#4     6     1  49.0
#5     8     0 206.
#6     8     1  29.1

custom_aggregation(mtcars, stat_fun = list(sum, max), agg_col = qsec, cyl, am)
# A tibble: 6 x 4
# Groups:   cyl [3]
#    cyl    am qsec_sum qsec_max
#  <dbl> <dbl>    <dbl>    <dbl>
#1     4     0     62.9     22.9
#2     4     1    148.      19.9
#3     6     0     76.9     20.2
#4     6     1     49.0     17.0
#5     8     0    206.      18
#6     8     1     29.1     14.6

custom_aggregation(mtcars, stat_fun = list(sum, min, max), agg_col = qsec, cyl, am)
# A tibble: 6 x 5
# Groups:   cyl [3]
#    cyl    am qsec_sum qsec_min qsec_max
#  <dbl> <dbl>    <dbl>    <dbl>    <dbl>
#1     4     0     62.9     20       22.9
#2     4     1    148.      16.7     19.9
#3     6     0     76.9     18.3     20.2
#4     6     1     49.0     15.5     17.0
#5     8     0    206.      15.4     18
#6     8     1     29.1     14.5     14.6
</code>```

Body:
I'm trying to figure out how to deal with custom aggregation function which will work with dplyr's evaluation principles. I'd like to create a function of a shape:

custom_aggregation <- function (data, stat_funs = list(mean, median), agg_col, ...)

where data is a data.frame, stat_funs is a list of functions to apply, agg_col indicates on which column the functions will be applied, ... are grouping columns.

For a single aggreation function I use code like this:

custom_aggregation <- function (data, stat_fun, agg_col, ...) {

  groups <- enquos(...)
  agg_col <- enquo(agg_col)
  stat_fun_enq <- enquo(stat_fun)
  agg_name <- paste0(quo_name(agg_col), '', quo_name(stat_fun_enq))

  data %>%
    group_by(!!!groups) %>%
    summarise(!!agg_name := stat_fun(!!agg_col))
}

# I can try to call the function on mtcars data.frame:
custom_aggregation(mtcars, stat_fun = mean, agg_col = qsec, cyl, am)

I have no idea how to handle a list of function (stat_fun argument).

I tried:

map(stat_fun, enquo) # and the basic lapply equivalent with variants

lapply(stat_fun, function(i) {
  stat_fun_enq <- enquo(i)
})

lapply(seq_along(stat_fun), function(i) {
  stat_fun_enq <- enquo(stat_fun[[i]])
})

Can someone guide me with what I'm doing wrong?

Body:
An option would be pass the functions as a quosure list and then map through the list, evaluate (!!) to apply the function

library(tidyverse)
custom_aggregation <- function (data, stat_fun, agg_col, ...) {

  groups <- enquos(...)
  agg_col <- enquo(agg_col)
  agg_name <- rlang::as_name(stat_fun)
  data %>%
        group_by(!!! groups) %>%
         summarise((!!agg_name) := (!!stat_fun)(!!agg_col))

}

Not clear about the expected output format

quos(mean, median)  %>%
      map(~ custom_aggregation(mtcars, stat_fun = .x, agg_col = qsec, cyl, am))
#[[1]]
# A tibble: 6 x 3
# Groups:   cyl [3]
#    cyl    am  mean
#  <dbl> <dbl> <dbl>
#1     4     0  21.0
#2     4     1  18.4
#3     6     0  19.2
#4     6     1  16.3
#5     8     0  17.1
#6     8     1  14.6

#[[2]]
# A tibble: 6 x 3
# Groups:   cyl [3]
#    cyl    am median
#  <dbl> <dbl>  <dbl>
#1     4     0   20.0
#2     4     1   18.6
#3     6     0   19.2
#4     6     1   16.5
#5     8     0   17.4
#6     8     1   14.6

Update

If we need in a single dataset

library(rlang)
custom_aggregation <- function (data, stat_fun, agg_col, ...) {

  groups <- enquos(...)
  agg_col <- enquo(agg_col)

  nm1 <- str_c(rlang::as_name(agg_col),
       map_chr(rlang::call_args(rlang::enexpr(stat_fun)),
             rlang::as_name), sep="_")

  data %>%
         group_by(!!! groups) %>%
         summarise_at(vars(rlang::as_name(agg_col)), stat_fun) %>%
         rename_at(vars(starts_with('fn')), ~ nm1)

}

-testing

custom_aggregation(mtcars, stat_fun = list(sum), agg_col = qsec, cyl, am)    # A tibble: 6 x 3
# Groups:   cyl [3]
#    cyl    am  qsec
#  <dbl> <dbl> <dbl>
#1     4     0  62.9
#2     4     1 148.
#3     6     0  76.9
#4     6     1  49.0
#5     8     0 206.
#6     8     1  29.1

custom_aggregation(mtcars, stat_fun = list(sum, max), agg_col = qsec, cyl, am)
# A tibble: 6 x 4
# Groups:   cyl [3]
#    cyl    am qsec_sum qsec_max
#  <dbl> <dbl>    <dbl>    <dbl>
#1     4     0     62.9     22.9
#2     4     1    148.      19.9
#3     6     0     76.9     20.2
#4     6     1     49.0     17.0
#5     8     0    206.      18
#6     8     1     29.1     14.6

custom_aggregation(mtcars, stat_fun = list(sum, min, max), agg_col = qsec, cyl, am)
# A tibble: 6 x 5
# Groups:   cyl [3]
#    cyl    am qsec_sum qsec_min qsec_max
#  <dbl> <dbl>    <dbl>    <dbl>    <dbl>
#1     4     0     62.9     20       22.9
#2     4     1    148.      16.7     19.9
#3     6     0     76.9     18.3     20.2
#4     6     1     49.0     15.5     17.0
#5     8     0    206.      15.4     18
#6     8     1     29.1     14.5     14.6


问:
"Port 4200 is already in use". Killing all the processes associated with 4200 did not work.
I'm trying to get angular running on my Mac OS X 10.11.3 El Capitan.

I installed nodeJS and npm. Through npm I installed angular-cli.

I created a new app via the command sudo ng new first-app

I navigated into the app folder and ran sudo ng serve.

It threw the following error :

```<code>Could not start watchman; falling back to NodeWatcher for file system events.
Visit http://ember-cli.com/user-guide/#watchman for more info.
Port 4200 is already in use.
</code>```

With reference from another answer, I tried the following :

```<code>sudo kill $(sudo lsof -t -i:4200)
</code>```

It did not help.

Actually, I have re-installed nodejs, npm, angular-cli. When I had installed it before there was some build error as there was some bower issue. Not sure what. When I accessed localhost:4200 that time, the page showed up but with the error log on it. Now the page doesn't even load. The loading symbol just keeps circling near the favicon. I don't know if this could be a lead.

Thanks. I need to get angular running pronto. Lots to learn !

答:
Try this:</p>

```<code>fuser -n tcp -k 4200 -f
</code>```

Body:
I'm trying to get angular running on my Mac OS X 10.11.3 El Capitan.

I installed nodeJS and npm. Through npm I installed angular-cli.

I created a new app via the command sudo ng new first-app

I navigated into the app folder and ran sudo ng serve.

It threw the following error :

Could not start watchman; falling back to NodeWatcher for file system events.
Visit http://ember-cli.com/user-guide/#watchman for more info.
Port 4200 is already in use.

With reference from another answer, I tried the following :

sudo kill $(sudo lsof -t -i:4200)

It did not help.

Actually, I have re-installed nodejs, npm, angular-cli. When I had installed it before there was some build error as there was some bower issue. Not sure what. When I accessed localhost:4200 that time, the page showed up but with the error log on it. Now the page doesn't even load. The loading symbol just keeps circling near the favicon. I don't know if this could be a lead.

Thanks. I need to get angular running pronto. Lots to learn !

Body:
Try this:

fuser -n tcp -k 4200 -f


问:
Check points inside a given radious using only an array
I'm creating an app that's using leaftlet to register GPS location of a specific place or multiple places and saves them on a Table [lat,lng] , this happens only on the backoffice.
On the frontend I will get the current position and I would like to create a "n" Km radious based on that position and after that filter all records in given radious.

Now the issue, I will not display any map on the frontend, the goal is only to list the records inside that radious, leaflet is not displayed due to traffic.

Any Idea how can this be done?

答:
If you do not display a map, you probably do not Leaflet.

While Leaflet provides you with methods to compute distances, there are many other geospatial libraries that offer similar feature, without the need to display anything. E.g. you might be interested in Turfjs's distance:

var from = turf.point([-75.343, 39.984]);
var to = turf.point([-75.534, 39.123]);
var options = {units: 'miles'};

var distance = turf.distance(from, to, options);
```

That being said, if you have a lot of data points in your database, you might investigate the possibility of implementing the filtering directly in backend database, by using spatial query, if your database supports it.

Body:
If you do not display a map, you probably do not Leaflet.

While Leaflet provides you with methods to compute distances, there are many other geospatial libraries that offer similar feature, without the need to display anything. E.g. you might be interested in Turfjs's distance:

var from = turf.point([-75.343, 39.984]);
var to = turf.point([-75.534, 39.123]);
var options = {units: 'miles'};

var distance = turf.distance(from, to, options);

That being said, if you have a lot of data points in your database, you might investigate the possibility of implementing the filtering directly in backend database, by using spatial query, if your database supports it.


问:
How to prevent trigger container's event when trigger children's events in JQuery?
E.g:

My HTML code structure is:

```<code><ul>
  <li class="container_event_click">
    <div class="child_event_click">click fired but doesn't want to trigger container's event</div>
  </li>
</ul>
</code>```

I mean: the container LI has its own click event.Just like selected or not.And the child div has its own click event like show something info of container.But my problem is when I click the child's event it also trigger the container's event.So,how can I resolve this problem.

Thank you very much!!

答:
```<code>   $('#child').click(function(event){
       event.stopPropagation();
   });

    $("div").delegate("", "click", function(e){
       e.stopPropagation();
       alert('test');
    });
</code>```

Here's a working link:

http://jsfiddle.net/MN5KK/1/

Body:
E.g:

My HTML code structure is:

click fired but doesn't want to trigger container's event

I mean: the container LI has its own click event.Just like selected or not.And the child div has its own click event like show something info of container.But my problem is when I click the child's event it also trigger the container's event.So,how can I resolve this problem.

Thank you very much!!

Body:
   $('#child').click(function(event){
       event.stopPropagation();
   });

    $("div").delegate("", "click", function(e){
       e.stopPropagation();
       alert('test');
    });

Here's a working link:

http://jsfiddle.net/MN5KK/1/


问:
RegEx for matching special patterns
I'm trying to match a String like this:62.00|LQ+2*2,FP,MD*3 "Description"
Where the decimal value is 2 digits optional, each user is characterized by two Chars and it can be followed by

(\+[\d]+)? or (\*[\d]+)? or none, or both, or both in different order

like:

LQ*2+4 | LQ+4*2 | LQ*2 | LQ+8 | LQ

Description is also optional

What i have tried is this:

```<code>Pattern.compile("^(?<number>[\\d]+(\\.[\\d]{2})?)\\|(?<users>([A-Z]{2}){1}(((\\+[\\d]+)?(\\*[\\d]+)?)|((\\+[\\d]+)?(\\*[\\d]+)?))((,[A-Z]{2})(((\\+[\\d]+)?(\\*[\\d]+)?)|((\\+[\\d]+)?(\\*[\\d]+)?)))*)(\\s\\\"(?<message>.+)\\\")?$");
</code>```

I need to get all the users so i can split them by ',' and then further regex my way into it.But i cannot grab anything out of it.The desired output from

62.00|LQ+2*2,FP,MD*3 "Description"

Should be:

62.00

LQ+2*2,FP,MD*3

Description

Accepted inputs should be of these kind:

62.00|LQ+2*2,FP,MD*3

30|LQ "Burgers"

35.15|LQ*2,FP+2*4,MD*3+4 "Potatoes"

35.15|LQ,FP,MD

答:
The precise regex to match the inputs you described should be fulfilled by this regex,

```<code>^(\d+(?:\.\d{1,2})?)\|([a-zA-Z]{2}(?:(?:\+\d+(?:\*\d+)?)|(?:\*\d+(?:\+\d+)?))?(?:,[a-zA-Z]{2}(?:(?:\+\d+(?:\*\d+)?)|(?:\*\d+(?:\+\d+)?))?)*)(?: +(.+))?$
</code>```

Where group1 will contain the number that can have optional decimals upto two digits and group2 will have the comma separated inputs as you described in your post and group3 will contain the optional description if present.

Explanation of regex:

^ - Start of string

(\d+(?:\.\d{1,2})?) - Matches the number which can have optional 2 digits after decimal and captures it in group1

\| - Matches literal | present in your input after the number

([a-zA-Z]{2}(?:(?:\+\d+(?:\*\d+)?)|(?:\*\d+(?:\+\d+)?))?(?:,[a-zA-Z]{2}(?:(?:\+\d+(?:\*\d+)?)|(?:\*\d+(?:\+\d+)?))?)*) - This part matches two letters followed by any combination of + followed by number and optionally having * followed by number OR * followed by number and optionally having + followed by number exactly either once or whole of it being optional and captures it in group2

(?: +(.+))? - This matches the optional description and captures it in group3

$ - Marks end of input

Regex Demo

Title: RegEx for matching special patterns

Body:
I'm trying to match a String like this:62.00|LQ+2*2,FP,MD*3 "Description"
Where the decimal value is 2 digits optional, each user is characterized by two Chars and it can be followed by

(\+[\d]+)? or (\*[\d]+)? or none, or both, or both in different order

like:

LQ*2+4 | LQ+4*2 | LQ*2 | LQ+8 | LQ

Description is also optional

What i have tried is this:

Pattern.compile("^(?<number>[\\d]+(\\.[\\d]{2})?)\\|(?<users>([A-Z]{2}){1}(((\\+[\\d]+)?(\\*[\\d]+)?)|((\\+[\\d]+)?(\\*[\\d]+)?))((,[A-Z]{2})(((\\+[\\d]+)?(\\*[\\d]+)?)|((\\+[\\d]+)?(\\*[\\d]+)?)))*)(\\s\\\"(?<message>.+)\\\")?$");

I need to get all the users so i can split them by ',' and then further regex my way into it.But i cannot grab anything out of it.The desired output from

62.00|LQ+2*2,FP,MD*3 "Description"

Should be:

62.00

LQ+2*2,FP,MD*3

Description

Accepted inputs should be of these kind:

62.00|LQ+2*2,FP,MD*3

30|LQ "Burgers"

35.15|LQ*2,FP+2*4,MD*3+4 "Potatoes"

35.15|LQ,FP,MD

Body:
The precise regex to match the inputs you described should be fulfilled by this regex,

^(\d+(?:\.\d{1,2})?)\|([a-zA-Z]{2}(?:(?:\+\d+(?:\*\d+)?)|(?:\*\d+(?:\+\d+)?))?(?:,[a-zA-Z]{2}(?:(?:\+\d+(?:\*\d+)?)|(?:\*\d+(?:\+\d+)?))?)*)(?: +(.+))?$

Where group1 will contain the number that can have optional decimals upto two digits and group2 will have the comma separated inputs as you described in your post and group3 will contain the optional description if present.

Explanation of regex:

^ - Start of string

(\d+(?:\.\d{1,2})?) - Matches the number which can have optional 2 digits after decimal and captures it in group1

\| - Matches literal | present in your input after the number

([a-zA-Z]{2}(?:(?:\+\d+(?:\*\d+)?)|(?:\*\d+(?:\+\d+)?))?(?:,[a-zA-Z]{2}(?:(?:\+\d+(?:\*\d+)?)|(?:\*\d+(?:\+\d+)?))?)*) - This part matches two letters followed by any combination of + followed by number and optionally having * followed by number OR * followed by number and optionally having + followed by number exactly either once or whole of it being optional and captures it in group2

(?: +(.+))? - This matches the optional description and captures it in group3

$ - Marks end of input

Regex Demo


问:
Is CreateCompatibleDC() necessary working with windows on one display?
This example code manually reads a bitmap file, uses CreateDIBSection() to make GDI allocate memory for it, and create an hbitmap handle.  Then it uses a MemoryDC to draw the bitmap to a window DC:

ftp://ftp.oreilly.com/examples/9781572319950/cd_contents/Chap15/DibSect/DibSect.c

```<code>hdc = BeginPaint (hwnd, &ps) ;
...
hdcMem = CreateCompatibleDC (hdc) ;
</code>```

Why can't we use GetDC() with NULL or with hwndDesktop instead?  Why can't we cache the device context instead of repeatedly creating it?

If the machine has only one display device and we are only drawing to windows why do we need to constantly harmonize bitmaps and device contexts?  Once the pixeldata is copied to the buffer provided by GDI, does GDI update it when that HBITMAP is loaded into a DC and drawn on?  If the user also wishes to draw on it is it necessary to synchronize access?  (By calling GDIFlush() first?)

It's hard to figure this out when most all of the object properties are opaque and abstracted.  I've read almost all of the related MSDN, a lot of Petzold's book, and some articles:

Display Device Contexts

CreateCompatibleDC()

CreateDIBSection()

Memory Device Contexts

Guide to Win32 Memory DC

Guide to WIN32 Paint for Intermediates

Programming Windows®, Fifth Edition

Edit:

I think my question boils down to this:

Is a device context a TYPE of display or is it an INSTANCE of graphical data that is able to be displayed.  A computer typically has only a handful of displays but it could have hundreds of things to display on them.

答:
I think your problem is that you are getting hung up on Microsoft's names for things, Microsoft's name "device context" and the names for calls like "CreateCompatibleDC".

"Device Context" is a bad name. The Win32 documentation will tell you that a device context is a data structure for storing the state of a particular device used for rendering graphics commands. This is only partially true. Look at the different kinds of DCs that exist: (1) screen device contexts, (2) printer device contexts, (3) the device context used by a bitmap in memory, and (4) metafile device contexts. Of these only (1) or (2) are actually doing exactly what the documentation claims they are doing. In the other cases device contexts serve as a target for drawing calls but not as containers for the state of some physical device. (This is really noticeably true in the case of metafile DC's: metafiles were an old Win32 thing that basically just cache the GDI calls going in to them to be replayed later, kind of a crude vector format.)

In a hypothetical object oriented programming version of Win32, device contexts could be instances of some class that implements an interface that exposes graphics drawing calls. A better name for such a class would be something like "Graphics" and indeed in GDI+ this is what the analogous construct is actually called. When we "Create" -- via CreateDC, CreateCompatibleDC, etc. -- we create one of these objects. When we GetDC we grab such an object that already exists.

To answer your questions:

Is a device context a TYPE of display or is it an INSTANCE of graphical data that is able to be displayed. ?

They are in so sense types of displays. You can think of them as instances of a class of objects with private implementations that expose a public interface exposing drawing commands.

Why can't we use GetDC() with NULL or with hwndDesktop instead?

You can't use GetDC(NULL) as the device context into which you are going to select an in memory bitmap because in such a situation you need to create a device context that does not already exist; GetDC(NULL) is like a singleton instance that is already in use.

So instead you usually CreateCompatibleDC(NULL) or CreateCompatibleDC(hdcScreen). Again CreateCompatibleDC(...) is a confusing name. Imagine the hypothetical object-oriented version of what is going on here. Say there is an IGraphics interface that is implemented by RasterGraphics, PrinterGraphics, and MetafileGraphics. Imagine the "RasterGraphics" class is used for both the screen and for in memory bitmaps. Then CreateCompatibleDC(...) would be would be like a factory call Graphics.CreateFrom(IGraphics g) that return a new instance of the same concrete type with perhaps some state variables initialized.

Why can't we cache the device context instead of repeatedly creating it?

You can. You do not need to delete device contexts across function calls. The only reason people often do is that they are a shared, finite resource and creating them is cheap. I think actually that they used to be very limited under old versions of Windows so old Win32 programmers tend to not cache them out of muscle memory from the old days, from Windows 95 days.

If the machine has only one display device and we are only drawing to windows why do we need to constantly harmonize bitmaps and device contexts?

Don't think of the "compatible" in CreateCompatibleDC(...) to be about "harmonizing with the screen" think of it as meaning "Okay Windows I want to create one of your graphics interface objects and I want the kind like this one, which is a normal raster graphics one and not for printers or for metafiles."

Body:
This example code manually reads a bitmap file, uses CreateDIBSection() to make GDI allocate memory for it, and create an hbitmap handle.  Then it uses a MemoryDC to draw the bitmap to a window DC:

ftp://ftp.oreilly.com/examples/9781572319950/cd_contents/Chap15/DibSect/DibSect.c

hdc = BeginPaint (hwnd, &ps) ;
...
hdcMem = CreateCompatibleDC (hdc) ;

Why can't we use GetDC() with NULL or with hwndDesktop instead?  Why can't we cache the device context instead of repeatedly creating it?

If the machine has only one display device and we are only drawing to windows why do we need to constantly harmonize bitmaps and device contexts?  Once the pixeldata is copied to the buffer provided by GDI, does GDI update it when that HBITMAP is loaded into a DC and drawn on?  If the user also wishes to draw on it is it necessary to synchronize access?  (By calling GDIFlush() first?)

It's hard to figure this out when most all of the object properties are opaque and abstracted.  I've read almost all of the related MSDN, a lot of Petzold's book, and some articles:

Display Device Contexts

CreateCompatibleDC()

CreateDIBSection()

Memory Device Contexts

Guide to Win32 Memory DC

Guide to WIN32 Paint for Intermediates

Programming Windows®, Fifth Edition

Edit:

I think my question boils down to this:

Is a device context a TYPE of display or is it an INSTANCE of graphical data that is able to be displayed.  A computer typically has only a handful of displays but it could have hundreds of things to display on them.


问:
Can't get the usage of PVC through kubelet metrics
I have a Kubernetes 1.9.11 cluster on baremetal machines running Coreos 1576.5.0.

Recently I deployed a Glusterfs 4.1.7 cluster, managed by Heketi 8, and created a lot of PVCs to be used by some statfulset applications. The problem is, I can't get metrics about these PVCs through Kublet's 10250 port:

```<code>curl -k https://aa05:10250/metrics 2>/dev/null | grep kubelet_volume_stats | wc -l
0
</code>```

So, how can I get these metrics?

Any hints will be appreciated.

答: It looks like kubelet is implementing metrics for volumes in release-1.9.x,but their naming is quite different from what you are grepping for. Try to grep for volume_stats.

Body:
I have a Kubernetes 1.9.11 cluster on baremetal machines running Coreos 1576.5.0.

Recently I deployed a Glusterfs 4.1.7 cluster, managed by Heketi 8, and created a lot of PVCs to be used by some statfulset applications. The problem is, I can't get metrics about these PVCs through Kublet's 10250 port:

curl -k https://aa05:10250/metrics 2>/dev/null | grep kubelet_volume_stats | wc -l
0

So, how can I get these metrics?

Any hints will be appreciated.


问:
Consuming a void service operation in a WCF data service
from a Wcf data service client (inherited from System.Data.Services.Client.DataServiceContext) I would like to invoke a service operation defined on a Wcf Data Service that returns void

```<code>[WebGet]
public void Operation()
{
  // logic
}
</code>```

The only reasonable method I found is the Execute, but how could I use it with a void operation?

Thank you

答:
I have found a workaround for this problem.
This website solved me quite a few problems before, so I thought it would be nice to share back.

The quick answer to your question is:

```<code> string empty = context.Execute<string>(new Uri("Operation", UriKind.Relative)).FirstOrDefault();
</code>```

The "empty" string should be null or empty upon response. It "works around" the HttpWebRequest method mentioned on the post above.

Further more, it is also possible to get primitive types back using this technique.
Lets say I have this Method:

```<code>[WebGet]
public bool Authenticate(string Username, string Password)
{...do stuff here...}
</code>```

When you try the normal execution it fails (Vitek Karas explains it well in his reponse above):

```<code>    var query = context.CreateQuery<bool>("Authenticate").AddQueryOption("Username", "'itye'").AddQueryOption("Password","'123456'");
DataServiceCollection<bool> list = new DataServiceCollection<bool>();
list.Load(query);
</code>```

But the following will do the trick:

```<code>var query = context.CreateQuery<bool>("Authenticate").AddQueryOption("Username", "'itye'").AddQueryOption("Password","'123456'");

bool authenticated = context.Execute<bool>(new Uri(query.RequestUri.ToString().Replace("Authenticate()", "Authenticate"))).FirstOrDefault();
</code>```

Please note the Replace("Authenticate()", "Authenticate"), which omits () from the query string (otherwise it will cause error).

Hope it helps.
- Itye

ContentLicense: CC BY-SA 2.5

Body:
from a Wcf data service client (inherited from System.Data.Services.Client.DataServiceContext) I would like to invoke a service operation defined on a Wcf Data Service that returns void

[WebGet]
public void Operation()
{
  // logic
}

The only reasonable method I found is the Execute, but how could I use it with a void operation?

Thank you

Body:
I have found a workaround for this problem.
This website solved me quite a few problems before, so I thought it would be nice to share back.

The quick answer to your question is:

 string empty = context.Execute<string>(new Uri("Operation", UriKind.Relative)).FirstOrDefault();

The "empty" string should be null or empty upon response. It "works around" the HttpWebRequest method mentioned on the post above.

Further more, it is also possible to get primitive types back using this technique.
Lets say I have this Method:

[WebGet]
public bool Authenticate(string Username, string Password)
{...do stuff here...}

When you try the normal execution it fails (Vitek Karas explains it well in his reponse above):

    var query = context.CreateQuery<bool>("Authenticate").AddQueryOption("Username", "'itye'").AddQueryOption("Password","'123456'");
DataServiceCollection<bool> list = new DataServiceCollection<bool>();
list.Load(query);

But the following will do the trick:

var query = context.CreateQuery<bool>("Authenticate").AddQueryOption("Username", "'itye'").AddQueryOption("Password","'123456'");

bool authenticated = context.Execute<bool>(new Uri(query.RequestUri.ToString().Replace("Authenticate()", "Authenticate"))).FirstOrDefault();

Please note the Replace("Authenticate()", "Authenticate"), which omits () from the query string (otherwise it will cause error).

Hope it helps.
- Itye


问:
Having trouble to get the real part of an array obtained from the fun.eval
I used the eval function to evaluate a function. the code is written below:

```<code>import numpy as np
import sympy
from sympy import Symbol, Add
s = sympy.Symbol('s')
x = [ s, s+1, 10*s**2, 5]
a = [1 + 1j, 2 , 3 , 4 , 5]
fun = Add(*x) # Create a function by adding all terms. * is to unpack all the values

def F(fun, v):
    return fun.evalf(subs={s: v}) # Evaluate the function at s=v

f_dis = [F(fun, v) for v in a]
print (f_dis)
fit3 = np.asanyarray(f_dis)
print ("fit3 =", fit3)
realpart = fit3.real[0]
print ("real =", realpart)

</code>```

the result of f_dis is

```<code>[8.0 + 22.0*I, 50.0000000000000, 102.000000000000, 174.000000000000, 266.000000000000]
</code>```

The point here is that the code shows the 8.0 + 22.0*I as the real part of the first element, instead of showing 8 only.
What should I do to solve this issue?
Thanks.

答:
You can use re from Sympy to get only the real part of the evaluated expression

```<code>import numpy as np
from sympy import Symbol, Add, re

s = Symbol('s')
x = [ s, s+1, 10*s**2, 5]
a = [1 + 1j, 2 , 3 , 4 , 5]
fun = Add(*x) # Create a function by adding all terms. * is to unpack all the values

def F(fun, v):
    return fun.evalf(subs={s: v}) # Evaluate the function at s=v

f_dis = [re(F(fun, v)) for v in a] # <---- Use re() here
print (f_dis)
# [8.00000000000000, 50.0000000000000, 102.000000000000, 174.000000000000, 266.000000000000]
</code>```

Body:
I used the eval function to evaluate a function. the code is written below:

import numpy as np
import sympy
from sympy import Symbol, Add
s = sympy.Symbol('s')
x = [ s, s+1, 10*s**2, 5]
a = [1 + 1j, 2 , 3 , 4 , 5]
fun = Add(*x) # Create a function by adding all terms. * is to unpack all the values

def F(fun, v):
    return fun.evalf(subs={s: v}) # Evaluate the function at s=v

f_dis = [F(fun, v) for v in a]
print (f_dis)
fit3 = np.asanyarray(f_dis)
print ("fit3 =", fit3)
realpart = fit3.real[0]
print ("real =", realpart)

the result of f_dis is

[8.0 + 22.0*I, 50.0000000000000, 102.000000000000, 174.000000000000, 266.000000000000]

The point here is that the code shows the 8.0 + 22.0*I as the real part of the first element, instead of showing 8 only.
What should I do to solve this issue?
Thanks.

Body:
You can use re from Sympy to get only the real part of the evaluated expression

import numpy as np
from sympy import Symbol, Add, re

s = Symbol('s')
x = [ s, s+1, 10*s**2, 5]
a = [1 + 1j, 2 , 3 , 4 , 5]
fun = Add(*x) # Create a function by adding all terms. * is to unpack all the values

def F(fun, v):
    return fun.evalf(subs={s: v}) # Evaluate the function at s=v

f_dis = [re(F(fun, v)) for v in a] # <---- Use re() here
print (f_dis)
# [8.00000000000000, 50.0000000000000, 102.000000000000, 174.000000000000, 266.000000000000]


问:
How to do equivalent of block_reduce on a masked array?
I'm calculating an aggregate value over smaller blocks in a 2D numpy array. I'd like to exclude values 0 from the aggregation operation in an efficient manner (rather than for and if statements).

I'm using skimage.measure.block_reduce and numpy.ma.masked_equal, but it looks like block_reduce ignores the mask.

import numpy as np
import skimage
a = np.array([[2,4,0,12,5,7],[6,0,8,4,3,9]])
zeros_included = skimage.measure.block_reduce(a,(2,2),np.mean)
```

<p>includes 0s and (correctly) produces</p>

<pre class="lang-py prettyprint-override"><code>zeros_included
array([[3., 6., 6.]])
</code>```

I was hoping

masked = np.ma.masked_equal(a,0)
zeros_excluded = skimage.measure.block_reduce(masked,(2,2),np.mean)
```

<p>would do the trick, but still produces</p>

<pre class="lang-py prettyprint-override"><code>zeros_excluded
array([[3., 6., 6.]])
</code>```

The desired result would be:

array([[4., 8., 6.]])
```

I'm looking for a pythonesque way to achieve the correct result, use of skimage is optional. Of course my actual arrays and blocks are much bigger than in this example, hence the need for efficiency.

Thanks for your interest.

答:
The core code of block_reduce is

```<code>blocked = view_as_blocks(image, block_size)
return func(blocked, axis=tuple(range(image.ndim, blocked.ndim)))
</code>```

view_as_blocks uses as_strided to create a different view of the array:

```<code>In [532]: skimage.util.view_as_blocks(a,(2,2))
Out[532]:
array([[[[ 2,  4],
         [ 6,  0]],

        [[ 0, 12],
         [ 8,  4]],

        [[ 5,  7],
         [ 3,  9]]]])
</code>```

When applied to the masked array it produces the same thing.  In effect it works with masked.data, or np.asarray(masked).  Some actions preserve subclasses, this does not.

```<code>In [533]: skimage.util.view_as_blocks(masked,(2,2))
Out[533]:
array([[[[ 2,  4],
         [ 6,  0]],
         ...
</code>```

That's why the np.mean applied to the (2,3) axes does not respond to the masking.

np.mean applied to a masked array delegates the action to the arrays own method, so is sensitive to the masking:

```<code>In [544]: np.mean(masked[:,:2])
Out[544]: 4.0
In [545]: masked[:,:2].mean()
Out[545]: 4.0
In [547]: [masked[:,i:i+2].mean() for i in range(0,6,2)]
Out[547]: [4.0, 8.0, 6.0]
</code>```

np.nanmean works with view_as_blocks because it doesn't depend on the array being a special subclass.

I can define a function that applies masking to the block view:

```<code>def foo(arr,axis):
    return np.ma.masked_equal(arr,0).mean(axis)

In [552]: skimage.measure.block_reduce(a,(2,2),foo)
Out[552]:
masked_array(data=[[4.0, 8.0, 6.0]],
             mask=[[False, False, False]],
       fill_value=1e+20)
</code>```

====

Since your blocks aren't overlapping, I create the blocks with reshaping and swapping axes.

```<code>In [554]: masked.reshape(2,3,2).transpose(1,0,2)
Out[554]:
masked_array(
  data=[[[2, 4],
         [6, --]],

        [[--, 12],
         [8, 4]],

        [[5, 7],
         [3, 9]]],
  mask=[[[False, False],
         [False,  True]],

        [[ True, False],
         [False, False]],

        [[False, False],
         [False, False]]],
  fill_value=0)
</code>```

and then apply mean to the last 2 axes:

```<code>In [555]: masked.reshape(2,3,2).transpose(1,0,2).mean((1,2))
Out[555]:
masked_array(data=[4.0, 8.0, 6.0],
             mask=[False, False, False],
       fill_value=1e+20)
</code>```

Body:
I'm calculating an aggregate value over smaller blocks in a 2D numpy array. I'd like to exclude values 0 from the aggregation operation in an efficient manner (rather than for and if statements).

I'm using skimage.measure.block_reduce and numpy.ma.masked_equal, but it looks like block_reduce ignores the mask.

import numpy as np
import skimage
a = np.array([[2,4,0,12,5,7],[6,0,8,4,3,9]])
zeros_included = skimage.measure.block_reduce(a,(2,2),np.mean)

includes 0s and (correctly) produces

zeros_included
array([[3., 6., 6.]])

I was hoping

masked = np.ma.masked_equal(a,0)
zeros_excluded = skimage.measure.block_reduce(masked,(2,2),np.mean)

would do the trick, but still produces

zeros_excluded
array([[3., 6., 6.]])

The desired result would be:

array([[4., 8., 6.]])

I'm looking for a pythonesque way to achieve the correct result, use of skimage is optional. Of course my actual arrays and blocks are much bigger than in this example, hence the need for efficiency.

Thanks for your interest.

Body:
The core code of block_reduce is

blocked = view_as_blocks(image, block_size)
return func(blocked, axis=tuple(range(image.ndim, blocked.ndim)))

view_as_blocks uses as_strided to create a different view of the array:

In [532]: skimage.util.view_as_blocks(a,(2,2))
Out[532]:
array([[[[ 2,  4],
         [ 6,  0]],

        [[ 0, 12],
         [ 8,  4]],

        [[ 5,  7],
         [ 3,  9]]]])

When applied to the masked array it produces the same thing.  In effect it works with masked.data, or np.asarray(masked).  Some actions preserve subclasses, this does not.

In [533]: skimage.util.view_as_blocks(masked,(2,2))
Out[533]:
array([[[[ 2,  4],
         [ 6,  0]],
         ...

That's why the np.mean applied to the (2,3) axes does not respond to the masking.

np.mean applied to a masked array delegates the action to the arrays own method, so is sensitive to the masking:

In [544]: np.mean(masked[:,:2])
Out[544]: 4.0
In [545]: masked[:,:2].mean()
Out[545]: 4.0
In [547]: [masked[:,i:i+2].mean() for i in range(0,6,2)]
Out[547]: [4.0, 8.0, 6.0]

np.nanmean works with view_as_blocks because it doesn't depend on the array being a special subclass.

I can define a function that applies masking to the block view:

def foo(arr,axis):
    return np.ma.masked_equal(arr,0).mean(axis)

In [552]: skimage.measure.block_reduce(a,(2,2),foo)
Out[552]:
masked_array(data=[[4.0, 8.0, 6.0]],
             mask=[[False, False, False]],
       fill_value=1e+20)

====

Since your blocks aren't overlapping, I create the blocks with reshaping and swapping axes.

In [554]: masked.reshape(2,3,2).transpose(1,0,2)
Out[554]:
masked_array(
  data=[[[2, 4],
         [6, --]],

        [[--, 12],
         [8, 4]],

        [[5, 7],
         [3, 9]]],
  mask=[[[False, False],
         [False,  True]],

        [[ True, False],
         [False, False]],

        [[False, False],
         [False, False]]],
  fill_value=0)

and then apply mean to the last 2 axes:

In [555]: masked.reshape(2,3,2).transpose(1,0,2).mean((1,2))
Out[555]:
masked_array(data=[4.0, 8.0, 6.0],
             mask=[False, False, False],
       fill_value=1e+20)


问:
How to toggle tab navigation
Trying to get navigation tabs to toggle content based on it's tab selected but content is not toggling and all content is being displayed and not hidden on default.

I have tried onclick=showBody("tabid") with no luck.

Right now code is as follows;

```<code><section class="border-black">
    <div class="container sr-subresults-nav">
        <ul class="sr-navigation">
        <li class="sr-subnav-item" onclick=showBody("bridgerectifiers")>Bridge Rectifiers</li>
        <li class="sr-subnav-item" onclick=showBody("limitingdiodes")>Limiting Diodes</li>
        <li class="sr-subnav-item" onclick=showBody("sfrecovery")><a class="sr-nav-link" href="">SF Recovery</li>
        </ul>
    </div>

<section class="pt-1 mb-0 border-black">
    <div id="product-results">
        <div id="bridgerectifiers" class="search-result-products">
            <div class="diodes-rectifiers-content" id="bridge-rectifiers-diodes-filter-div">
                <h6>Bridge Rectifiers</h6>
                content for bridge rectifiers goes here
            </div>
        </div>
        <div id="limitingdiodes" class="search-result-products">
            <div class="diodes-rectifiers-content" id="current-limiting-diodes-filter-div">
                <h6>Current Limiting Diodes</h6>
                content for current limiting diodes goes here
            </div>
        </div>
        <div id="sfrecovery" class="search-result-products">
            <div class="diodes-rectifiers-content" id="super-fast-recovery-diodes-filter-div">
                <h6>Super Fast Recovery Diodes</h6>
                content for super fast recovery diodes goes here
            </div>
        </div>
    </div>
</section>
</code>```

JS

```<code>function showBody(item) {
    hideBody();
    if (item == "bridgerectifiers") {
    $("#bridgerectifiers").show();
    $("#bridgerectifiers").hidden = false;
}
    if (item == "limitingdiodes") {
    $("#limitingdiodes").show();
    $("#limitingdiodes").hidden = false;
    }
};

    function hideBody() {
    $("#bridgerectifiers").hide();
    $("#bridgerectifiers").hidden = false;
    $("#limitingdiodes").hide();
    $("#limitingdiodes").hidden = false;
}
</code>```

Would like to get all content hidden on default and the tab selected to show the content related to that tab while all other content is hidden or not displayed. New to js and jquery so open to other options other than onclick.

答:
In hideBody() function, you should remove $("#bridgerectifiers").hidden = false; and $("#limitingdiodes").hidden = false;.
They're code to show elements again.

You can also remove $("#bridgerectifiers").hidden = false; and $("#limitingdiodes").hidden = false; from showBody() function because they do same as $("#bridgerectifiers").show();.

Or you just use the following code.

function showBody(item) {
    hideBody();
    $("#" + item).show();
};

function hideBody() {
    $(".search-result-products").hide();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="border-black">
    <div class="container sr-subresults-nav">
        <ul class="sr-navigation">
            <li class="sr-subnav-item" onclick='showBody("bridgerectifiers")'>Bridge Rectifiers</li>
            <li class="sr-subnav-item" onclick='showBody("limitingdiodes")'>Limiting Diodes</li>
            <li class="sr-subnav-item" onclick='showBody("sfrecovery")'>SF Recovery</li>
        </ul>
    </div>
</section>
<section class="pt-1 mb-0 border-black">
    <div id="product-results">
        <div id="bridgerectifiers" class="search-result-products">
            <div class="diodes-rectifiers-content" id="bridge-rectifiers-diodes-filter-div">
                <h6>Bridge Rectifiers</h6>
                content for bridge rectifiers goes here
            </div>
        </div>
        <div id="limitingdiodes" class="search-result-products">
            <div class="diodes-rectifiers-content" id="current-limiting-diodes-filter-div">
                <h6>Current Limiting Diodes</h6>
                content for current limiting diodes goes here
            </div>
        </div>
        <div id="sfrecovery" class="search-result-products">
            <div class="diodes-rectifiers-content" id="super-fast-recovery-diodes-filter-div">
                <h6>Super Fast Recovery Diodes</h6>
                content for super fast recovery diodes goes here
            </div>
        </div>
    </div>
</section></code>```

Title: How to toggle tab navigation

Body:
Trying to get navigation tabs to toggle content based on it's tab selected but content is not toggling and all content is being displayed and not hidden on default.

I have tried onclick=showBody("tabid") with no luck.

Right now code is as follows;

Bridge Rectifiers

Limiting Diodes

SF Recovery

Bridge Rectifiers

                content for bridge rectifiers goes here

Current Limiting Diodes

                content for current limiting diodes goes here

Super Fast Recovery Diodes

                content for super fast recovery diodes goes here

JS

function showBody(item) {
    hideBody();
    if (item == "bridgerectifiers") {
    $("#bridgerectifiers").show();
    $("#bridgerectifiers").hidden = false;
}
    if (item == "limitingdiodes") {
    $("#limitingdiodes").show();
    $("#limitingdiodes").hidden = false;
    }
};

    function hideBody() {
    $("#bridgerectifiers").hide();
    $("#bridgerectifiers").hidden = false;
    $("#limitingdiodes").hide();
    $("#limitingdiodes").hidden = false;
}

Would like to get all content hidden on default and the tab selected to show the content related to that tab while all other content is hidden or not displayed. New to js and jquery so open to other options other than onclick.

Body:
In hideBody() function, you should remove $("#bridgerectifiers").hidden = false; and $("#limitingdiodes").hidden = false;.
They're code to show elements again.

You can also remove $("#bridgerectifiers").hidden = false; and $("#limitingdiodes").hidden = false; from showBody() function because they do same as $("#bridgerectifiers").show();.

Or you just use the following code.

function showBody(item) {
    hideBody();
    $("#" + item).show();
};

function hideBody() {
    $(".search-result-products").hide();
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="border-black">
    <div class="container sr-subresults-nav">
        <ul class="sr-navigation">
            <li class="sr-subnav-item" onclick='showBody("bridgerectifiers")'>Bridge Rectifiers</li>
            <li class="sr-subnav-item" onclick='showBody("limitingdiodes")'>Limiting Diodes</li>
            <li class="sr-subnav-item" onclick='showBody("sfrecovery")'>SF Recovery</li>
        </ul>
    </div>
</section>
<section class="pt-1 mb-0 border-black">
    <div id="product-results">
        <div id="bridgerectifiers" class="search-result-products">
            <div class="diodes-rectifiers-content" id="bridge-rectifiers-diodes-filter-div">
                <h6>Bridge Rectifiers</h6>
                content for bridge rectifiers goes here
            </div>
        </div>
        <div id="limitingdiodes" class="search-result-products">
            <div class="diodes-rectifiers-content" id="current-limiting-diodes-filter-div">
                <h6>Current Limiting Diodes</h6>
                content for current limiting diodes goes here
            </div>
        </div>
        <div id="sfrecovery" class="search-result-products">
            <div class="diodes-rectifiers-content" id="super-fast-recovery-diodes-filter-div">
                <h6>Super Fast Recovery Diodes</h6>
                content for super fast recovery diodes goes here
            </div>
        </div>
    </div>
</section>


问:
JavaScript implementation of Gzip
I'm writing a Web application that needs to store JSON data in a small, fixed-size server-side cache via AJAX (think: Opensocial quotas). I do not have control over the server.

I need to reduce the size of the stored data to stay within a server-side quota, and was hoping to be able to gzip the stringified JSON in the browser before sending it up to the server.

However, I cannot find much in the way of JavaScript implementations of Gzip. Any suggestions for how I can compress the data on the client side before sending it up?

答:
I had another problem, I did not want to encode data in gzip but to decode gzipped data.
I am running javascript code outside of the browser so I need to decode it using pure javascript.

It took me some time but i found that in the JSXGraph library there is a way to read gzipped data.

Here is where I found the library: http://jsxgraph.uni-bayreuth.de/wp/2009/09/29/jsxcompressor-zlib-compressed-javascript-code/
There is even a standalone utility that can do that, JSXCompressor, and the code is LGPL licencied.

Just include the jsxcompressor.js file in your project and then you will be able to read a base 64 encoded gzipped data:

```<code><!doctype html>
</head>
<title>Test gzip decompression page</title>
<script src="jsxcompressor.js"></script>
</head>
<body>
<script>
    document.write(JXG.decompress('<?php
        echo base64_encode(gzencode("Try not. Do, or do not. There is no try."));
    ?>'));
</script>
</html>
</code>```

I understand it is not what you wanted but I still reply here because I suspect it will help some people.

OwnerDisplayName: David Citron

Title: JavaScript implementation of Gzip

LastEditorDisplayName: David Citron

Body:
I had another problem, I did not want to encode data in gzip but to decode gzipped data.
I am running javascript code outside of the browser so I need to decode it using pure javascript.

It took me some time but i found that in the JSXGraph library there is a way to read gzipped data.

Here is where I found the library: http://jsxgraph.uni-bayreuth.de/wp/2009/09/29/jsxcompressor-zlib-compressed-javascript-code/
There is even a standalone utility that can do that, JSXCompressor, and the code is LGPL licencied.

Just include the jsxcompressor.js file in your project and then you will be able to read a base 64 encoded gzipped data:

<!doctype html>
</head>
<title>Test gzip decompression page</title>
<script src="jsxcompressor.js"></script>
</head>
<body>
<script>
    document.write(JXG.decompress('<?php
        echo base64_encode(gzencode("Try not. Do, or do not. There is no try."));
    ?>'));
</script>
</html>

I understand it is not what you wanted but I still reply here because I suspect it will help some people.


问:
Python delete dictionary items with same values
How would I remove dictionary items that have different keys but identical values? I am sure there a better way than my novice algorithm...?

Example: (abends with error "dictionary changed size during iteration")

The goal of this example is to remove either 'car_id' or 'truck_id' from dict.

```<code>key_fields_obj = {}
key_fields_obj['car_id'] = 'bob'
key_fields_obj['bike_id'] = 'sam'
key_fields_obj['truck_id'] = 'bob' #goal: remove this one, so left with only car_id and bike_id

for item in key_fields_obj:
    tst = key_fields_obj[item]
    for comp in key_fields_obj:
        if item == comp:
            continue
        cmp = key_fields_obj[comp]
        if cmp == tst:
            del key_fields_obj[comp]

print(key_fields_obj)
</code>```

答:
```<code>seem_values = set()

for key, value in list(key_fields_obj.items()):
   if value in seem_values:
       del key_fields_obj[key]
   else:
       seem_values.add(value)
</code>```

Body:
How would I remove dictionary items that have different keys but identical values? I am sure there a better way than my novice algorithm...?

Example: (abends with error "dictionary changed size during iteration")

The goal of this example is to remove either 'car_id' or 'truck_id' from dict.

key_fields_obj = {}
key_fields_obj['car_id'] = 'bob'
key_fields_obj['bike_id'] = 'sam'
key_fields_obj['truck_id'] = 'bob' #goal: remove this one, so left with only car_id and bike_id

for item in key_fields_obj:
    tst = key_fields_obj[item]
    for comp in key_fields_obj:
        if item == comp:
            continue
        cmp = key_fields_obj[comp]
        if cmp == tst:
            del key_fields_obj[comp]

print(key_fields_obj)


问:
How to make an if statement to disable select option?
I have three select menus where the user selects a subject, year and season. However, I want it so that if the user selects the year '2019', the 'Fall' option will get disabled.

<select name="Subject">
    <option value="Math">Math</option>
    <option value="Physics">Physics</option>
    <option value="Chemistry">Chemistry</option>
    <option value="Biology">Biology</option>
</select>

<select name="Year">
    <option value="2019">2019</option>
    <option value="2018">2018</option>
    <option value="2017">2017</option>
    <option value="2016">2016</option>
</select>

<select name="Season">
    <option value="Spring">Spring</option>
    <option value="Fall">Fall</option>
</select>```

答:
You can onchange event and bind callback to it that get season select element and enable and disable Fall season according to selection value

```<code>  <select name="Subject">
    <option value="Math">Math</option>
    <option value="Physics">Physics</option>
    <option value="Chemistry">Chemistry</option>
    <option value="Biology">Biology</option>
</select>

<select name="Year" onchange="changeYear(this.value)">
    <option value="2019">2019</option>
    <option value="2018">2018</option>
    <option value="2017">2017</option>
    <option value="2016">2016</option>
</select>

<select name="Season">
    <option value="Spring" >Spring</option>
    <option value="Fall" disabled>Fall</option>
</select>

<script>
function changeYear(value)
{
    var seasons = document.getElementsByName("Season")[0].options;
    var fallSeason = Array.apply(null, seasons).find(season => season.value === 'Fall');
    fallSeason.disabled = (value==='2019')
}
</script>
</code>```

Body:
You can onchange event and bind callback to it that get season select element and enable and disable Fall season according to selection value

  <select name="Subject">
    <option value="Math">Math</option>
    <option value="Physics">Physics</option>
    <option value="Chemistry">Chemistry</option>
    <option value="Biology">Biology</option>
</select>

<select name="Year" onchange="changeYear(this.value)">
    <option value="2019">2019</option>
    <option value="2018">2018</option>
    <option value="2017">2017</option>
    <option value="2016">2016</option>
</select>

<select name="Season">
    <option value="Spring" >Spring</option>
    <option value="Fall" disabled>Fall</option>
</select>

<script>
function changeYear(value)
{
    var seasons = document.getElementsByName("Season")[0].options;
    var fallSeason = Array.apply(null, seasons).find(season => season.value === 'Fall');
    fallSeason.disabled = (value==='2019')
}
</script>


问:
Read list from a file
I want to read a simple list from a file. But can't separate list elements from one another.

Here's my file:

```<code>"11","Arial","red","white","black","200x200","My Project"
</code>```

Here's my read function:

def fread(file_name):
    user_file=open('{}'.format(file_name),"r")
    file_content=user_file.read()
    user_file.close()
    return str(file_content)
```

<p>Here's the part that does not work:</p>

<pre class="lang-py prettyprint-override"><code>conf_file=fread("settings")
conf_file.split(",")
print(conf_file[2])
</code>```

This returns 1 instead of red

答:
str.split does not mutate strings as they are immutable. You need to assign the return value back to the variable:

```<code>conf_file = fread("settings")
conf_file = conf_file.split(",")
print(conf_file[2])
</code>```

The line containing:

```<code>open('{}'.format(file_name), 'r')
</code>```

Can just be written as the following if you do not need to amend the input string:

```<code>open(file_name, 'r')
</code>```

Since all of your items are enclosed within double quotes, Python will include them in the string. If you want to only use the values inside the strings, you need to use a slice of the string to remove them. Add this line after you split by commas:

```<code>conf_file = [value[1:-1] for value in conf_file]
</code>```

Now data like '"11"' will just be '11'. Note that this does not convert the string 11 into the int 11.

Title: Read list from a file

Body:
I want to read a simple list from a file. But can't separate list elements from one another.

Here's my file:

"11","Arial","red","white","black","200x200","My Project"

Here's my read function:

def fread(file_name):
    user_file=open('{}'.format(file_name),"r")
    file_content=user_file.read()
    user_file.close()
    return str(file_content)

Here's the part that does not work:

conf_file=fread("settings")
conf_file.split(",")
print(conf_file[2])

This returns 1 instead of red

Body:
str.split does not mutate strings as they are immutable. You need to assign the return value back to the variable:

conf_file = fread("settings")
conf_file = conf_file.split(",")
print(conf_file[2])

The line containing:

open('{}'.format(file_name), 'r')

Can just be written as the following if you do not need to amend the input string:

open(file_name, 'r')

Since all of your items are enclosed within double quotes, Python will include them in the string. If you want to only use the values inside the strings, you need to use a slice of the string to remove them. Add this line after you split by commas:

conf_file = [value[1:-1] for value in conf_file]

Now data like '"11"' will just be '11'. Note that this does not convert the string 11 into the int 11.


问:
ServiceUrl "https://smba.trafficmanager.net/apac/" is not working
I have a MS Teams bot. I have installed the bot for couple of users in tenant. Now when I'm starting conversation, for few users it is responding and few it is not.

I investigated further and found out that for users who are getting reply from bot, the serviceurl is "https://smba.trafficmanager.net/in/".

For users who are not getting reply from bot, the serviceurl is "https://smba.trafficmanager.net/apac/".

Exception message: Operation returned an invalid status code 'NotFound'

```<code>private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
     var activity = await result as Activity;
     var reply = activity.CreateReply();
     reply.Text = "Hi there";
     await context.PostAsync(reply);
}
</code>```

答:
This sounds like it's possibly a TrustServiceUrl Issue (despite the 500 vs 401 error message).

You can fix it by adding all of your ServiceUrls to the list of trusted URLs:

```<code>private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
     var activity = await result as Activity;
     var serviceUrl = activity.ServiceUrl;
     MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);
     var reply = activity.CreateReply();
     reply.Text = "Hi there";
     await context.PostAsync(reply);
}
</code>```

This should ensure that your bot "trusts" the ServiceUrl of any message that it receives.

Let me know how that goes. I'm 90% sure this is the issue, but it might not be.

Here's a link to the library, if that helps. Otherwise, browsing these issues should help.

Note to others:

This "Trust Service URL Issue" doesn't apply to just Teams. This happens for lots of other URLs when trying to use Proactive messaging. Just replace serviceUrl with whatever is appropriate for your use case. And yes, if you're using multiple channels, you can add multiple URLs when using MicrosoftAppCredentials.TrustServiceUrl() by calling it multiple times.

Here's the method definition. Note: you can add expiration for this, as well.

I've submitted a PR for this, which so far has resulted in some updated docs

Body:
I have a MS Teams bot. I have installed the bot for couple of users in tenant. Now when I'm starting conversation, for few users it is responding and few it is not.

I investigated further and found out that for users who are getting reply from bot, the serviceurl is "https://smba.trafficmanager.net/in/".

For users who are not getting reply from bot, the serviceurl is "https://smba.trafficmanager.net/apac/".

Exception message: Operation returned an invalid status code 'NotFound'

private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
     var activity = await result as Activity;
     var reply = activity.CreateReply();
     reply.Text = "Hi there";
     await context.PostAsync(reply);
}

Body:
This sounds like it's possibly a TrustServiceUrl Issue (despite the 500 vs 401 error message).

You can fix it by adding all of your ServiceUrls to the list of trusted URLs:

private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
     var activity = await result as Activity;
     var serviceUrl = activity.ServiceUrl;
     MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);
     var reply = activity.CreateReply();
     reply.Text = "Hi there";
     await context.PostAsync(reply);
}

This should ensure that your bot "trusts" the ServiceUrl of any message that it receives.

Let me know how that goes. I'm 90% sure this is the issue, but it might not be.

Here's a link to the library, if that helps. Otherwise, browsing these issues should help.

Note to others:

This "Trust Service URL Issue" doesn't apply to just Teams. This happens for lots of other URLs when trying to use Proactive messaging. Just replace serviceUrl with whatever is appropriate for your use case. And yes, if you're using multiple channels, you can add multiple URLs when using MicrosoftAppCredentials.TrustServiceUrl() by calling it multiple times.

Here's the method definition. Note: you can add expiration for this, as well.

I've submitted a PR for this, which so far has resulted in some updated docs


问:
Transform text value to lower case when indexing
Any idea how can I transform text value to lower case when indexing in firestore function. I have tried this

```<code>const newRef = db.collection("user").where("profile.companyName".toLowerCase(), ">=", data.value.toLowerCase())
</code>```

but it give me an error at this part

```<code>"profile.companyName".toLowerCase()
</code>```

Is it even possible to do it? I really don't want to save all names to lowercase to be able to properly indexing through my names and then  capitalise them

答: Firestore doesn't have an API or mechanism to do this for you.  You will have to store the lowercased version of the string in a field, and use that field to make your query.</p>

Body:
Any idea how can I transform text value to lower case when indexing in firestore function. I have tried this

const newRef = db.collection("user").where("profile.companyName".toLowerCase(), ">=", data.value.toLowerCase())

but it give me an error at this part

"profile.companyName".toLowerCase()

Is it even possible to do it? I really don't want to save all names to lowercase to be able to properly indexing through my names and then  capitalise them


问:
Getting stack trace from NullPointerException
my servlet is throwing a NullPointerException. I want to show the full stack call trace so that I can find out the line number the exception is being thrown at.

How can I do that? I have already used fillInStackTrace(). it is not printing the line number.

答: Try Thread.dumpStack()</p>

Body: Try Thread.dumpStack()


问:
Error Handling in VBA when Connection is not present
I'm trying to put together a simple macro that does the following.

Unlocks my password protected sheet

Refresh a Query (Obtains info from an Access database on network drive)

locks sheet with password.

I've put in an error handler to simply relock the spreadsheet and prompt a message box.  However that error handler doesn't work when there is no internet connection. It works fine if there is a network connection, and say for example I've moved the Access Database to a different location than the one stored in the Query.

I get a Run-time error 1004:
[DataFormat.Error] Your Network access was interrupted.  To continue, close the database, and them open it again.

What am I doing wrong?

```<code>Sub RefreshItemTable()

    ActiveSheet.Unprotect Password:="password"

    Worksheets("Item List").Range("A1").ListObject.QueryTable.Refresh

    On Error GoTo connError

    DoEvents

    ActiveSheet.Protect Password:="password", DrawingObjects:=True, Contents:=True, Scenarios:=True _
        , AllowFormattingColumns:=True, AllowFiltering:=True

    Exit Sub

    connError:
    ActiveSheet.Protect Password:="password", DrawingObjects:=True, Contents:=True, Scenarios:=True _
        , AllowFormattingColumns:=True, AllowFiltering:=True
    MsgBox ("Unable to Connect")

End Sub
</code>```

答:
Make the On Error statement the first executable statement in the procedure's scope.

The way you have it, you start handling errors only after QueryTable.Refresh runs (and fails).

Body:
I'm trying to put together a simple macro that does the following.

Unlocks my password protected sheet

Refresh a Query (Obtains info from an Access database on network drive)

locks sheet with password.

I've put in an error handler to simply relock the spreadsheet and prompt a message box.  However that error handler doesn't work when there is no internet connection. It works fine if there is a network connection, and say for example I've moved the Access Database to a different location than the one stored in the Query.

I get a Run-time error 1004:
[DataFormat.Error] Your Network access was interrupted.  To continue, close the database, and them open it again.

What am I doing wrong?

Sub RefreshItemTable()

    ActiveSheet.Unprotect Password:="password"

    Worksheets("Item List").Range("A1").ListObject.QueryTable.Refresh

    On Error GoTo connError

    DoEvents

    ActiveSheet.Protect Password:="password", DrawingObjects:=True, Contents:=True, Scenarios:=True _
        , AllowFormattingColumns:=True, AllowFiltering:=True

    Exit Sub

    connError:
    ActiveSheet.Protect Password:="password", DrawingObjects:=True, Contents:=True, Scenarios:=True _
        , AllowFormattingColumns:=True, AllowFiltering:=True
    MsgBox ("Unable to Connect")

End Sub


问:
How can I compare model saved data in django from controller?
I built a django powered webapps,where I used a model field called average CGPA(avg_cgpa) which is a DecimalField in Django model. Also I used a for loop on controller/template to generate all separate data about a student.Now my intention is to compare avg_cgpa data for every row of model to generate a new
 tag.Where it will be print different result for each student.
Like, if avg_cgpa > 2.00 it will be print pass,otherwise fail !
I did tried as you have seen on template but its not working,please come up with your helpfull answer.

(Django model here)

class Management(models.Model):
    student_id = models.CharField(max_length=100)
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    father_name = models.CharField(max_length=200)
    mother_name = models.CharField(max_length=200)
    Present_address = models.TextField(max_length=400)
    Permanent_address = models.TextField(max_length=400)
    contact = models.CharField(max_length=11)
    avg_cgpa = models.DecimalField(max_digits=20,decimal_places=2)

    def __str__(self):
        return self.student_id
```

<pre class="lang-html prettyprint-override"><code>(Here is the template)

{% load static %}
{% include 'base.html' %}
{% block content %}
{% include 'navbar.html' %}
{% include 'banner.html' %}

<div class = "container">
    <div class="row">
        {% for x in student %}
        <div class="col-md-4">
            <div class="card" style="width: 18rem;">
                  <div class="card-body">
                    <h5 class="card-title"><strong>ID : </strong> {{ x.student_id }}</h5>
                     <hr class="my-4">
                    <img class="card-img-top" src="{% static "images/hat.png" %}"><hr class="my-4">
                    <h6 class="card-subtitle mb-2 text-muted"><strong><i class="far fa-user-circle"></i> </strong> {{ x.first_name }} {{ x.last_name }}</h6>
                    <hr class="my-4">
                    <p class="card-text">Father's Name : <strong>{{ x.father_name }}</strong></p>
                    <p class="card-text">Mother's Name : <strong>{{ x.mother_name }}</strong></p>
                    <p class="card-text">Address : <strong>{{ x.Permanent_address }}</strong></p>
                   <p class="card-text"><strong><i class="fas fa-phone"></i> {{ x.contact }}</strong> </p>
                   <p class="card-text">Avg CGPA : <strong>{{ x.avg_cgpa }}</strong></p>
                   {% if x.avg_cgpa > "2" %}
                        <p class="card-text">Condition : <strong>Pass</strong></p>
                   {% endif %}
                  </div>
              </div>
              </br>
        </div>
        {% endfor %}
    </br>
</div>

{% include 'footer.html' %}
{% endblock%}

</code>```

I did tried if condition within for loop,but no result as outcome.Is it possible to retrieve data by comparing model data in django ?

答:
I would consider adding a property to your model that returns whether it is a pass or not

```<code>class Management(models.Model):

   @property
   def passed(self):
       return self.avg_cgpa > 2
</code>```

This can then be used in the template {% if x.passed %}, it can also be used in other parts of your code and is a bit more readable

Body:
I built a django powered webapps,where I used a model field called average CGPA(avg_cgpa) which is a DecimalField in Django model. Also I used a for loop on controller/template to generate all separate data about a student.Now my intention is to compare avg_cgpa data for every row of model to generate a new
 tag.Where it will be print different result for each student.
Like, if avg_cgpa > 2.00 it will be print pass,otherwise fail !
I did tried as you have seen on template but its not working,please come up with your helpfull answer.

(Django model here)

class Management(models.Model):
    student_id = models.CharField(max_length=100)
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    father_name = models.CharField(max_length=200)
    mother_name = models.CharField(max_length=200)
    Present_address = models.TextField(max_length=400)
    Permanent_address = models.TextField(max_length=400)
    contact = models.CharField(max_length=11)
    avg_cgpa = models.DecimalField(max_digits=20,decimal_places=2)

    def __str__(self):
        return self.student_id

(Here is the template)

{% load static %}
{% include 'base.html' %}
{% block content %}
{% include 'navbar.html' %}
{% include 'banner.html' %}

        {% for x in student %}

ID :  {{ x.student_id }}

  {{ x.first_name }} {{ x.last_name }}

Father's Name : {{ x.father_name }}

Mother's Name : {{ x.mother_name }}

Address : {{ x.Permanent_address }}

 {{ x.contact }}

Avg CGPA : {{ x.avg_cgpa }}

                   {% if x.avg_cgpa > "2" %}

Condition : Pass

                   {% endif %}

        {% endfor %}

{% include 'footer.html' %}
{% endblock%}

I did tried if condition within for loop,but no result as outcome.Is it possible to retrieve data by comparing model data in django ?

Body:
I would consider adding a property to your model that returns whether it is a pass or not

class Management(models.Model):

   @property
   def passed(self):
       return self.avg_cgpa > 2

This can then be used in the template {% if x.passed %}, it can also be used in other parts of your code and is a bit more readable


问:
How to convert EventCallback<T> to EventCallback<bool>
Blazor has a generic class named EventCallback

How can I cast a

```<code>protected EventCallback<T> ValueChanged { get; set; }
</code>```

to

```<code>EventCallback<bool> BoolChanged
   {
     get
     {
       if (typeof(T) == typeof(bool))
         return ValueChanged; //<== Error needs cast some how?
     }
   }
</code>```

答:
@Steven,can the following code represent and clarify your question ?

suppose I've the following components

```<code>@*Parent.razor*@

@page "/Parent"

<div>
    <Child Data="@Data" ValueChanged="@ValueChanged">
    </Child>
</div>

@functions {
    List<Item> Data = new List<Item>();

    private void ValueChanged(Item item)
    {
    }
}

    @*Child.razor*@

@typeparam TData

<div>
    @foreach (var item in Data)
    {
        <button onclick="@(() => ValueChanged.InvokeAsync(item))"></button>
    }
</div>

@functions {
    [Parameter]
    public IEnumerable<TData> Data { get; set; }

    [Parameter]
    protected EventCallback<TData> ValueChanged { get; set; }
}

  // Item.cs
public class Item
{
     public Item()
     {

     }
}
</code>```

As you can see I've two components, and am using generics(typeparam)
  with EventCallback... Now, I want to define EventCallback property
  with a get accessor that checks if the type of TData is bool, and if
  it does, coverts the ValueChanged delegate to EventCallback

```<code>EventCallback<bool> BoolChanged {
    get
    {
       if (typeof(TData) == typeof(bool)) return ValueChanged; // Needs conversion, but how
    }
 }
</code>```

Body:
Blazor has a generic class named EventCallback

How can I cast a

protected EventCallback<T> ValueChanged { get; set; }

to

EventCallback<bool> BoolChanged
   {
     get
     {
       if (typeof(T) == typeof(bool))
         return ValueChanged; //<== Error needs cast some how?
     }
   }

Body:
@Steven,can the following code represent and clarify your question ?

suppose I've the following components

@*Parent.razor*@

@page "/Parent"

<div>
    <Child Data="@Data" ValueChanged="@ValueChanged">
    </Child>
</div>

@functions {
    List<Item> Data = new List<Item>();

    private void ValueChanged(Item item)
    {
    }
}

    @*Child.razor*@

@typeparam TData

<div>
    @foreach (var item in Data)
    {
        <button onclick="@(() => ValueChanged.InvokeAsync(item))"></button>
    }
</div>

@functions {
    [Parameter]
    public IEnumerable<TData> Data { get; set; }

    [Parameter]
    protected EventCallback<TData> ValueChanged { get; set; }
}

  // Item.cs
public class Item
{
     public Item()
     {

     }
}

As you can see I've two components, and am using generics(typeparam)
  with EventCallback... Now, I want to define EventCallback property
  with a get accessor that checks if the type of TData is bool, and if
  it does, coverts the ValueChanged delegate to EventCallback

EventCallback<bool> BoolChanged {
    get
    {
       if (typeof(TData) == typeof(bool)) return ValueChanged; // Needs conversion, but how
    }
 }


问:
How to use javascript with php to obtain large content from mysql
i have combined javascript with php as shown in this code below. but is not working for me.
it doesn't display the content. but it display the id when is requested.</p>

```<code>function content24(){
          document.getElementById("dailypost_content").innerHTML = '<?php
          $query = "SELECT`dpost_content` FROM `daily_POST` WHERE `id`=
                   '24'";
          $query_run = mysqli_query($host_connection, $query);
          $query_row = mysqli_fetch_assoc($query_run);
          $content = $query_row['dpost_content'];
          echo '<span id "daily_caption"> <strong><u>Daily Inspiration</u>
          </strong><br></span>';
          echo $content;
          ?>';
    }
</code>```

答:
There is lots of thing wrong with what you are doing. I formatted the code you provided to be better. Keep the php out as much as possible. Please read up on the difference between client-side and server side programming.</p>

```<code>    <?php
      $query = "SELECT `dpost_content` FROM `daily_POST` WHERE `id`='24'";
      $query_run = mysqli_query($host_connection, $query);
      $query_row = mysqli_fetch_assoc($query_run);
      $content = $query_row['dpost_content'];
    ?>
    function content24(){
      document.getElementById("dailypost_content").innerHTML = '<span id "daily_caption"> <strong><u>Daily Inspiration</u>  </strong><br></span>'+'<?php echo $content; ?>';
    }
</code>```

Body:
i have combined javascript with php as shown in this code below. but is not working for me.
it doesn't display the content. but it display the id when is requested.

function content24(){
          document.getElementById("dailypost_content").innerHTML = '<?php
          $query = "SELECT`dpost_content` FROM `daily_POST` WHERE `id`=
                   '24'";
          $query_run = mysqli_query($host_connection, $query);
          $query_row = mysqli_fetch_assoc($query_run);
          $content = $query_row['dpost_content'];
          echo ' Daily Inspiration

';
          echo $content;
          ?>';
    }

Body:
There is lots of thing wrong with what you are doing. I formatted the code you provided to be better. Keep the php out as much as possible. Please read up on the difference between client-side and server side programming.

    <?php
      $query = "SELECT `dpost_content` FROM `daily_POST` WHERE `id`='24'";
      $query_run = mysqli_query($host_connection, $query);
      $query_row = mysqli_fetch_assoc($query_run);
      $content = $query_row['dpost_content'];
    ?>
    function content24(){
      document.getElementById("dailypost_content").innerHTML = '<span id "daily_caption"> <strong><u>Daily Inspiration</u>  </strong><br></span>'+'<?php echo $content; ?>';
    }