问:
How to add markers to different layers in leaflet using onEachFeature and geojson
My current code merely binds markers according to the data from this json file

```<code>{"type": "FeatureCollection",
    "features": [{
"geometry": {"type": "Point", "coordinates": [53.8460456,-38.9135742]},
"type": "Feature",
"properties":{"name": "red"}]}
</code>```

and my code looks something like this:

```<code>      var blueLayer = new L.LayerGroup();
        var redLayer = new L.LayerGroup();

    var map = L.map('mapid', {
        center: [53.8460456,-38.9135742],
        zoom: 12,
        layers: [blueLayer, redLayer]
    });
    L.tileLayer('https://api.mapbox.com/styles/v1/n-alathba/cj2fzxjgl00bl2rqno6mtb9wg/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1Ijoibi1hbGF0aGJhIiwiYSI6ImNqMmZ6bTQ2cDAwNDIyeW8wY2hidjFxdjUifQ.TyQ2WNEMtCO3Q84PYXlAEA', {
        attribution: 'Tiles by <a href="http://mapc.org">MAPC</a>, Data by <a href="http://mass.gov/mgis">MassGIS</a>',
        maxZoom: 18,
        minZoom: 1,
    }).addTo(map);

 function onEachFeature(feature, layer) {
    return;
   }

 var link = './data/events2.json' //file above
 $.getJSON(link, function(events) {
     L.geoJSON(events, {
        style: function(feature) {
            return feature.properties && feature.properties.style;
       },
     onEachFeature: onEachFeature,
     pointToLayer: function(feature, latlng) {
     return L.marker(latlng); }
    }).addTo(map);
</code>```

However, I would like to add markers to different layers instead of binding them all directly to the map so I can do something like this:

```<code>function onEachFeature(feature,layer){
      if(feature.properties.name == "red"){ //do something that binds associated marker to red layer)
       else{//do something that binds associated marker to bluelayer}}
</code>```

答:
I believe you are nearly there. In your onEachFeature function, you can simply add layers to your different Layer Groups accordingly. Then, you can add the Layer Groups to the map whenever you want. Try this out:

```<code>function onEachFeature(feature,layer) {
    if(feature.properties.name == "red") {
        // add only 'red' markers to Layer Group
        redLayer.addLayer(layer);
    } else {
        // add only 'blue' markers to Layer Group (assuming just red/blue markers)
        blueLayer.addLayer(layer);
    }
}
</code>```

Now somewhere else in your code you can add these layers to your map:

```<code>redLayer.addTo(mapid);
blueLayer.addTo(mapid);
</code>```

Just make sure to remove the .addTo() method after the L.geoJSON() unless you want all the markers on the map initially. Hope this helps!

Body:
My current code merely binds markers according to the data from this json file

{"type": "FeatureCollection",
    "features": [{
"geometry": {"type": "Point", "coordinates": [53.8460456,-38.9135742]},
"type": "Feature",
"properties":{"name": "red"}]}

and my code looks something like this:

      var blueLayer = new L.LayerGroup();
        var redLayer = new L.LayerGroup();

    var map = L.map('mapid', {
        center: [53.8460456,-38.9135742],
        zoom: 12,
        layers: [blueLayer, redLayer]
    });
    L.tileLayer('https://api.mapbox.com/styles/v1/n-alathba/cj2fzxjgl00bl2rqno6mtb9wg/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1Ijoibi1hbGF0aGJhIiwiYSI6ImNqMmZ6bTQ2cDAwNDIyeW8wY2hidjFxdjUifQ.TyQ2WNEMtCO3Q84PYXlAEA', {
        attribution: 'Tiles by MAPC, Data by MassGIS',
        maxZoom: 18,
        minZoom: 1,
    }).addTo(map);

 function onEachFeature(feature, layer) {
    return;
   }

 var link = './data/events2.json' //file above
 $.getJSON(link, function(events) {
     L.geoJSON(events, {
        style: function(feature) {
            return feature.properties && feature.properties.style;
       },
     onEachFeature: onEachFeature,
     pointToLayer: function(feature, latlng) {
     return L.marker(latlng); }
    }).addTo(map);

However, I would like to add markers to different layers instead of binding them all directly to the map so I can do something like this:

function onEachFeature(feature,layer){
      if(feature.properties.name == "red"){ //do something that binds associated marker to red layer)
       else{//do something that binds associated marker to bluelayer}}

Body:
I believe you are nearly there. In your onEachFeature function, you can simply add layers to your different Layer Groups accordingly. Then, you can add the Layer Groups to the map whenever you want. Try this out:

function onEachFeature(feature,layer) {
    if(feature.properties.name == "red") {
        // add only 'red' markers to Layer Group
        redLayer.addLayer(layer);
    } else {
        // add only 'blue' markers to Layer Group (assuming just red/blue markers)
        blueLayer.addLayer(layer);
    }
}

Now somewhere else in your code you can add these layers to your map:

redLayer.addTo(mapid);
blueLayer.addTo(mapid);

Just make sure to remove the .addTo() method after the L.geoJSON() unless you want all the markers on the map initially. Hope this helps!


来源: stackexchange

问:
Is it possible that I request an EC2 instance but can't get fulfilled?
Edit: This question is NOT to ask about "Spot Instances"; this question is to ask regular "On Demand Instance". I think I need to clarify this, after reading comments below.

Basically, my question is about whether I should consider the risk that when I need to launch an EC2 instance, but that EC2 region has run out of capacity and can't fulfill my request.

I understand the chance for the above situation is extremely low, but I'd like to understand if AWS has any SLA to make sure that situation/risk won't happen.

答: Yes. I've had API calls to create EC2 resources fail many times due to lack of available AWS resources. I most commonly see this when attempting to create a new EC2 instance with Dedicated Tenancy in a specific Availability Zone.</p>

ContentLicense: CC BY-SA 3.0


问:
How do I copy from keyword to keyword in Python 2.7?
How might I copy lines keyword by keyword in one file fileA to another file fileB in Python 2.7? The query should include the keywords in the output.</p>

答:
If your question was to copy part of the original file which is between startWord and endWord, you can use this which is very slightly modified from
Extract subset of file in bash or Python</p>

```<code>begin = 'BEGINSTRING'
end = 'ENDSTRING'

with open(f, 'r') as input_file:
  tmp = []
  flag = False

  for line in input_file.readlines():

    if begin in line:
      flag = True
      index = line.find(begin)
      tmp.append(line[index:])
      continue
    elif flag:
      tmp.append(line)
    elif end in line:
      index = line.find(end)
      tmp.append(line[:index+1])
      break
    else:
      pass

with open(f + '_new', 'w') as output_file:
  for line in tmp:
  output_file.write(line)
</code>```

Body:
If your question was to copy part of the original file which is between startWord and endWord, you can use this which is very slightly modified from
Extract subset of file in bash or Python

begin = 'BEGINSTRING'
end = 'ENDSTRING'

with open(f, 'r') as input_file:
  tmp = []
  flag = False

  for line in input_file.readlines():

    if begin in line:
      flag = True
      index = line.find(begin)
      tmp.append(line[index:])
      continue
    elif flag:
      tmp.append(line)
    elif end in line:
      index = line.find(end)
      tmp.append(line[:index+1])
      break
    else:
      pass

with open(f + '_new', 'w') as output_file:
  for line in tmp:
  output_file.write(line)


问:
Android Studio extracting data from json object not working.
Given the below successfully returned json object, how to extract the two data fields I've noted:

```<code>{
  "Meta Data": {
    "1. Information": "Daily Prices (open, high, low, close) and Volumes",
    "2. Symbol": "^DJI",
    "3. Last Refreshed": "2017-06-08",
    "4. Output Size": "Compact",
    "5. Time Zone": "US/Eastern"
  },
  "Time Series (Daily)": {
    "2017-06-08": {
      "1. open": "21169.7598",   <--------- I want this one.
      "2. high": "21265.6895",
      "3. low": "21138.1602",
      "4. close": "21182.5293",  <--------- and this one.
      "5. volume": "323461038"
    },
    "2017-06-07": {
      "1. open": "21171.5703",
      "2. high": "21189.8398",
      "3. low": "21113.3105",
      "4. close": "21173.6895",
      "5. volume": "273400000"
    }, etc, etc...
</code>```

I've tried various methods, the below seems to be the proper one, but it raises a json exception and data[0] and data[1] log nothing.

```<code>String[] data = new String[3];
try {
    //Log.d("res2 = ", responseBody);
    JSONObject json_object = new JSONObject(responseBody);
    //json_object = json_object.getJSONObject("Meta Data");
    List<Map<String, String>> tickerData = new ArrayList<Map<String, String>>();
    HashMap<String, String> m = new HashMap<String, String>();
    m.put("1. open", json_object.getJSONObject("1. open").toString());
    m.put("4. close", json_object.getJSONObject("4. close").toString());
    tickerData.add(m);
    data[0] = tickerData.get(0).get("1. open");
    data[1] = tickerData.get(1).get("4. close");
    Log.d("data[0]=", data[0]);
    Log.d("data[1]", data[1]);
    }
catch (JSONException e) {
   Log.d("err ", "json exception at getIndexData()");
}
</code>```

答:
You can parse like this,

```<code>public class FeedParser {
    public static void parse(String response) {
        try {
            JSONObject baseObject = new JSONObject(response);

            if (baseObject == null) {
                return;
            }

            // You need Time Series (Daily) so we are going directly there.
            // Time Series (Daily) is inside baseObject
            JSONObject timeSeriesObj = baseObject.optJSONObject("Time Series (Daily)");

            if (timeSeriesObj == null) {
                return;
            }

            // We have list of dates inside Time Series (Daily) object we can iterate it using keys
            Iterator<String> iterator = timeSeriesObj.keys();

            List<Map<String, String>> tickerData = new ArrayList<Map<String, String>>();

            while (iterator.hasNext()) {
                String key = iterator.next();

                if (key != null) {
                    HashMap<String, String> m = new HashMap<String, String>();

                    JSONObject finalObj = timeSeriesObj.optJSONObject(key);

                    m.put("1. open", finalObj.optString("1. open"));
                    m.put("2. high", finalObj.optString("2. high"));
                    m.put("3. low", finalObj.optString("3. low"));
                    m.put("4. close", finalObj.optString("4. close"));
                    m.put("5. volume", finalObj.optString("5. volume"));

                    tickerData.add(m);
                }
            }

            // Below commented code you can use if your want to store the date as well
//            Map<String, Metric> values = new HashMap<>();
//
//            while (iterator.hasNext()) {
//                String key = iterator.next();
//
//                if (key != null) {
//                    HashMap<String, String> m = new HashMap<String, String>();
//                    Metric metric = new Metric();
//
//                    JSONObject finalObj = timeSeriesObj.optJSONObject(key);
//
//                    metric.open = finalObj.optString("1. open");
//                    metric.high = finalObj.optString("2. high");
//                    metric.low = finalObj.optString("3. low");
//                    metric.close = finalObj.optString("4. close");
//                    metric.volume = finalObj.optString("5. volume");
//
//                    values.put(key, metric);
//                }
//            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
</code>```

This below code is optional if you use the commented code

```<code>class Metric {
    String open;
    String high;
    String low;
    String close;
    String volume;
}
</code>```

Body:
Given the below successfully returned json object, how to extract the two data fields I've noted:

{
  "Meta Data": {
    "1. Information": "Daily Prices (open, high, low, close) and Volumes",
    "2. Symbol": "^DJI",
    "3. Last Refreshed": "2017-06-08",
    "4. Output Size": "Compact",
    "5. Time Zone": "US/Eastern"
  },
  "Time Series (Daily)": {
    "2017-06-08": {
      "1. open": "21169.7598",   <--------- I want this one.
      "2. high": "21265.6895",
      "3. low": "21138.1602",
      "4. close": "21182.5293",  <--------- and this one.
      "5. volume": "323461038"
    },
    "2017-06-07": {
      "1. open": "21171.5703",
      "2. high": "21189.8398",
      "3. low": "21113.3105",
      "4. close": "21173.6895",
      "5. volume": "273400000"
    }, etc, etc...

I've tried various methods, the below seems to be the proper one, but it raises a json exception and data[0] and data[1] log nothing.

String[] data = new String[3];
try {
    //Log.d("res2 = ", responseBody);
    JSONObject json_object = new JSONObject(responseBody);
    //json_object = json_object.getJSONObject("Meta Data");
    List<Map<String, String>> tickerData = new ArrayList<Map<String, String>>();
    HashMap<String, String> m = new HashMap<String, String>();
    m.put("1. open", json_object.getJSONObject("1. open").toString());
    m.put("4. close", json_object.getJSONObject("4. close").toString());
    tickerData.add(m);
    data[0] = tickerData.get(0).get("1. open");
    data[1] = tickerData.get(1).get("4. close");
    Log.d("data[0]=", data[0]);
    Log.d("data[1]", data[1]);
    }
catch (JSONException e) {
   Log.d("err ", "json exception at getIndexData()");
}

Body:
You can parse like this,

public class FeedParser {
    public static void parse(String response) {
        try {
            JSONObject baseObject = new JSONObject(response);

            if (baseObject == null) {
                return;
            }

            // You need Time Series (Daily) so we are going directly there.
            // Time Series (Daily) is inside baseObject
            JSONObject timeSeriesObj = baseObject.optJSONObject("Time Series (Daily)");

            if (timeSeriesObj == null) {
                return;
            }

            // We have list of dates inside Time Series (Daily) object we can iterate it using keys
            Iterator<String> iterator = timeSeriesObj.keys();

            List<Map<String, String>> tickerData = new ArrayList<Map<String, String>>();

            while (iterator.hasNext()) {
                String key = iterator.next();

                if (key != null) {
                    HashMap<String, String> m = new HashMap<String, String>();

                    JSONObject finalObj = timeSeriesObj.optJSONObject(key);

                    m.put("1. open", finalObj.optString("1. open"));
                    m.put("2. high", finalObj.optString("2. high"));
                    m.put("3. low", finalObj.optString("3. low"));
                    m.put("4. close", finalObj.optString("4. close"));
                    m.put("5. volume", finalObj.optString("5. volume"));

                    tickerData.add(m);
                }
            }

            // Below commented code you can use if your want to store the date as well
//            Map<String, Metric> values = new HashMap<>();
//
//            while (iterator.hasNext()) {
//                String key = iterator.next();
//
//                if (key != null) {
//                    HashMap<String, String> m = new HashMap<String, String>();
//                    Metric metric = new Metric();
//
//                    JSONObject finalObj = timeSeriesObj.optJSONObject(key);
//
//                    metric.open = finalObj.optString("1. open");
//                    metric.high = finalObj.optString("2. high");
//                    metric.low = finalObj.optString("3. low");
//                    metric.close = finalObj.optString("4. close");
//                    metric.volume = finalObj.optString("5. volume");
//
//                    values.put(key, metric);
//                }
//            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

This below code is optional if you use the commented code

class Metric {
    String open;
    String high;
    String low;
    String close;
    String volume;
}


问:
Cleaning up table output in sage
As the title suggests, I am trying to change the look of my output in Sage while it is formatted as a table. For a smaller amount of data, it looks fine, e.g.

However, once the right columns have too much data, it overflows like so:

As you can see, not only do the line breaks seem to go haywire, but also the right column can overflow into the left, making the data appear incorrectly. How might I reformat the latter scenario so that it appears as in the first example? Thank you in advance for any and all help!

EDIT

This is what I’m using right now:

```<code>dictionary_right_sets = dict(...)

my_table = table([dictionary_right_sets.keys(), dictionary_right_sets.values()],
                 frame=True,
                 header_column=['Right set', 'Element(s) whose right set is contained in this right set'])
result_table = my_table.transpose()
print result_table
</code>```

答: If you are using one of the notebook interfaces (either Jupyter or SageNB), try just evaluating result_table rather than print result_table. Does that give you what you want?

Title: Cleaning up table output in sage

Body:
As the title suggests, I am trying to change the look of my output in Sage while it is formatted as a table. For a smaller amount of data, it looks fine, e.g.

However, once the right columns have too much data, it overflows like so:

As you can see, not only do the line breaks seem to go haywire, but also the right column can overflow into the left, making the data appear incorrectly. How might I reformat the latter scenario so that it appears as in the first example? Thank you in advance for any and all help!

EDIT

This is what I’m using right now:

dictionary_right_sets = dict(...)

my_table = table([dictionary_right_sets.keys(), dictionary_right_sets.values()],
                 frame=True,
                 header_column=['Right set', 'Element(s) whose right set is contained in this right set'])
result_table = my_table.transpose()
print result_table


问:
What changes to netbeans or server configs do i need to make to allow my project to run php code properly
I have a php file for the login page below. The username and password from the form on the connected html page are in the database but when I click submit I get the connection was reset error page. What am i missing? This was made in netbeans and I am using mysql server and apache web server. THere is also an attached logout option that selecting it just causes the browser to prompt for what to do with it (save or open). I have tried changing the values of userId and passID to values in the data base but it still does not work. What am i doing wrong? After some moving files around i got the message below.

Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, string given in C:\WampDeveloper\Websites\DefaultWebsite\webroot\Loginpage.php on line 14 Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, string given in C:\WampDeveloper\Websites\DefaultWebsite\webroot\Loginpage.php on line 15 Acess denied

```<code><?php
    session_start();
    include("dbconfig.php");
    $dbname="sailingdb";
    $errorvar = "";
    if (isset($_POST['submit'])) {
        if (empty($_POST['user']) || empty($_POST["pass"])) {
            $errorvar = "Both field are required";
        } else {
            //defining and injection protecting data
            $userID=$_POST['user'];
            $passID=$_POST["pass"];
            $userID=stripslashes($userID);
            $passID=stripslashes($passID);
            $userID=mysqli_real_escape_string($dbname, $userID);
            $passID=mysqli_real_escape_string($dbname, $passID);
            $passID=md5($passID);

            $query = "SELECT * FROM users where userName = '$userID' AND pass = '$passID'";
            $queryresult=mysqli_query($dbname,$query);
            $row = mysqli_fetch_array($queryresult,MYSQLI_ASSOC);
            if (mysqli_num_rows($queryresult)==1) {
                $_SESSION['userName'] = $userID;
                header("MainMenu.html");
            } else {
                header("MainMenu.html");
                echo "Acess denied";
            }
       }
    }
?>
</code>```

The dbconfig.php code is below.

```<code><?php
    $servername="localhost";
    $user="root";
    $passw="*****";
    $dbname="Sailingdb";
    $conn=new mysqli($servername, $user, $passw, $dbname);
    if (mysqli_connect_error()) {
        die("Databse connection failed:    " . mysqli_connect_error());
    }
?>
</code>```

答:
The message says:

mysqli_real_escape_string() expects parameter 1 to be mysqli, string
  given

Since you have this in your dbconfig.php:

```<code>$conn=new mysqli($servername, $user, $passw, $dbname);
</code>```

You may try to do it like that:

```<code>$userID=mysqli_real_escape_string($conn, $userID);
$passID=mysqli_real_escape_string($conn, $passID);
</code>```

Body:
I have a php file for the login page below. The username and password from the form on the connected html page are in the database but when I click submit I get the connection was reset error page. What am i missing? This was made in netbeans and I am using mysql server and apache web server. THere is also an attached logout option that selecting it just causes the browser to prompt for what to do with it (save or open). I have tried changing the values of userId and passID to values in the data base but it still does not work. What am i doing wrong? After some moving files around i got the message below.

Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, string given in C:\WampDeveloper\Websites\DefaultWebsite\webroot\Loginpage.php on line 14 Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, string given in C:\WampDeveloper\Websites\DefaultWebsite\webroot\Loginpage.php on line 15 Acess denied

<?php
    session_start();
    include("dbconfig.php");
    $dbname="sailingdb";
    $errorvar = "";
    if (isset($_POST['submit'])) {
        if (empty($_POST['user']) || empty($_POST["pass"])) {
            $errorvar = "Both field are required";
        } else {
            //defining and injection protecting data
            $userID=$_POST['user'];
            $passID=$_POST["pass"];
            $userID=stripslashes($userID);
            $passID=stripslashes($passID);
            $userID=mysqli_real_escape_string($dbname, $userID);
            $passID=mysqli_real_escape_string($dbname, $passID);
            $passID=md5($passID);

            $query = "SELECT * FROM users where userName = '$userID' AND pass = '$passID'";
            $queryresult=mysqli_query($dbname,$query);
            $row = mysqli_fetch_array($queryresult,MYSQLI_ASSOC);
            if (mysqli_num_rows($queryresult)==1) {
                $_SESSION['userName'] = $userID;
                header("MainMenu.html");
            } else {
                header("MainMenu.html");
                echo "Acess denied";
            }
       }
    }
?>

The dbconfig.php code is below.

<?php
    $servername="localhost";
    $user="root";
    $passw="*****";
    $dbname="Sailingdb";
    $conn=new mysqli($servername, $user, $passw, $dbname);
    if (mysqli_connect_error()) {
        die("Databse connection failed:    " . mysqli_connect_error());
    }
?>

Body:
The message says:

mysqli_real_escape_string() expects parameter 1 to be mysqli, string
  given

Since you have this in your dbconfig.php:

$conn=new mysqli($servername, $user, $passw, $dbname);

You may try to do it like that:

$userID=mysqli_real_escape_string($conn, $userID);
$passID=mysqli_real_escape_string($conn, $passID);


问:
Reference parent class of method when `this` seems to been reset
I'm using react google charts and am trying to use the chartEvents method to hook into the selection event.

This works:

```<code>const ChartClass = React.createClass({
  getInitialState () {
    return {
      showModal: false
    }
  },
  handleShowModal () {
    this.setState((prev, props) => {
       return {
         showModal: true
       }
    })
  },
  chartEvents: [
    {
      eventName: 'select',
      callback: function (Chart) {
         this.handleShowModal()
      }
    }
  ],
  render () {
    return (
      <Chart
        chartEvents={this.chartEvents}
        data={this.props.data}
      />
    )
  }
})
</code>```

However within that callback I would like to call some other methods

```<code>this.handleOpenModal(ChartObj) // TypeError: this.handleOpenModal is not a function
this.sthElse()
</code>```

because within this callback this is being set to event itself

```<code>console.log(this) //object {eventName: "select", callback: function}
</code>```

Is there any way to reference the parent class so I can use its methods? I don't think I can simply place the function outside of the class because it needs to use this.setState

答:
You need to bind "this" in the callback

This can be done by

Using an arrow function

```<code>   chartEvents: [
     {
       eventName: 'select',
       callback:  Chart => {
         console.log('component', Chart.chart.getSelection()) //yep, shows the selection
       }
     }
   ],
</code>```

Binding

```<code>   chartEvents: [
     {
       eventName: 'select',
       callback: function (Chart) {
         console.log('component', Chart.chart.getSelection()) //yep, shows the selection
       }.bind(this)
     }
   ],
</code>```

Body:
I'm using react google charts and am trying to use the chartEvents method to hook into the selection event.

This works:

const ChartClass = React.createClass({
  getInitialState () {
    return {
      showModal: false
    }
  },
  handleShowModal () {
    this.setState((prev, props) => {
       return {
         showModal: true
       }
    })
  },
  chartEvents: [
    {
      eventName: 'select',
      callback: function (Chart) {
         this.handleShowModal()
      }
    }
  ],
  render () {
    return (
      <Chart
        chartEvents={this.chartEvents}
        data={this.props.data}
      />
    )
  }
})

However within that callback I would like to call some other methods

this.handleOpenModal(ChartObj) // TypeError: this.handleOpenModal is not a function
this.sthElse()

because within this callback this is being set to event itself

console.log(this) //object {eventName: "select", callback: function}

Is there any way to reference the parent class so I can use its methods? I don't think I can simply place the function outside of the class because it needs to use this.setState

Body:
You need to bind "this" in the callback

This can be done by

Using an arrow function

   chartEvents: [
     {
       eventName: 'select',
       callback:  Chart => {
         console.log('component', Chart.chart.getSelection()) //yep, shows the selection
       }
     }
   ],

Binding

   chartEvents: [
     {
       eventName: 'select',
       callback: function (Chart) {
         console.log('component', Chart.chart.getSelection()) //yep, shows the selection
       }.bind(this)
     }
   ],


问:
Handle global variable in node.js server
I have a node.js server that reads messages from a rabbitmq server. Every message contains an url that returns a json object whit specifications to download some jsx code.

The node.js server gets the code from the urls and compiles it with webpack.
My problem is that I need to keep aware of the information of the json objects in the webpack compilation instance, because I need to print the downloaded objects in the index page.

Node Server -- Get messages --> RabbitMQ Server

RabbitMQ Server -- Return messages --> Node Server

Node Server -- Get code [from URL] --> URL service

URL service -- Return code --> Node Server

Node Server: Compile downloaded code.

I don't know if I was clear. I tried to use global variables and module.exports, but did not work. Maybe I am missing something, I am a kind of beginner in JS, node and webpack.

答:
Could you cache those in memory, that way they would be available to access.

One of the popular module is memory-cache

Though memory caching comes in with it's own set of limitations.

Hope I understood the question correct.


问:
Psycopg2 Insert Into Table with Placeholders
This might be a rather silly question but what am I doing wrong here? It creates the table but the INSERT INTO doesn't work, I guess I'm doing something wrong with the placeholders?

```<code>conn = psycopg2.connect("dbname=postgres user=postgres")
cur = conn.cursor()
escaped_name = "TOUR_2"
cur.execute('CREATE TABLE %s(id serial PRIMARY KEY, day date, elapsed_time varchar,    net_time varchar, length float, average_speed float, geometry GEOMETRY);' % escaped_name)

cur.execute('INSERT INTO %s (day,elapsed_time, net_time, length, average_speed, geometry) VALUES (%s, %s, %s, %s, %s, %s)', (escaped_name, day ,time_length,  time_length_net, length_km, avg_speed,  myLine_ppy))

conn.commit()
cur.close()
conn.close()
</code>```

The INSERT INTO call doesn't work, it gives me

```<code>cur.execute('INSERT INTO %s (day,elapsed_time, net_time, length, average_speed,
geometry) VALUES (%s, %s, %s, %s, %s, %s)'% (escaped_name, day ,time_length,
time_length_net, length_km, avg_speed,  myLine_ppy))
psycopg2.ProgrammingError: syntax error at or near ":"
LINE 1: ...h, average_speed, geometry) VALUES (2013/09/01 , 2:56:59, 02...
</code>```

Can someone help me on this one? Thanks a bunch!

答: As of psycopg2 v2.7 there is a supported way to do this: see the psycopg2.sql docs.

Body:
This might be a rather silly question but what am I doing wrong here? It creates the table but the INSERT INTO doesn't work, I guess I'm doing something wrong with the placeholders?

conn = psycopg2.connect("dbname=postgres user=postgres")
cur = conn.cursor()
escaped_name = "TOUR_2"
cur.execute('CREATE TABLE %s(id serial PRIMARY KEY, day date, elapsed_time varchar,    net_time varchar, length float, average_speed float, geometry GEOMETRY);' % escaped_name)

cur.execute('INSERT INTO %s (day,elapsed_time, net_time, length, average_speed, geometry) VALUES (%s, %s, %s, %s, %s, %s)', (escaped_name, day ,time_length,  time_length_net, length_km, avg_speed,  myLine_ppy))

conn.commit()
cur.close()
conn.close()

The INSERT INTO call doesn't work, it gives me

cur.execute('INSERT INTO %s (day,elapsed_time, net_time, length, average_speed,
geometry) VALUES (%s, %s, %s, %s, %s, %s)'% (escaped_name, day ,time_length,
time_length_net, length_km, avg_speed,  myLine_ppy))
psycopg2.ProgrammingError: syntax error at or near ":"
LINE 1: ...h, average_speed, geometry) VALUES (2013/09/01 , 2:56:59, 02...

Can someone help me on this one? Thanks a bunch!


问:
How to Restrict Private Content?
I have a website that has some private content that should only be viewable after the user has paid. I am thinking about using something like Google Checkout (other recommendations are fine too), but from a coding standpoint, how would you go about securely flagging a user as 'paid' and give them access to the private pages? Google checkout seems to be able to accept payments, but how do I know the payment went through programmatically?

Is this something that wordpress or drupal is good for?

答:
You can integrate your application through the Google Checkout API. That API should return a success message once the payment has been approved. The Google Checkout page for order processing mentions these three options:

If you do a custom integration of order processing:

You'll be notified of new orders via an SSL-secured callback URL that you
  define.

You can continue to process orders through the existing order management
  system you used before integrating
  with Google Checkout. Google will send
  you order information in XML messages
  if you use the XML API or name-value
  pairs if you use the HTML API as
  defined by the Notification API.

You can then issue order processing commands over an SSL-secured channel.

You may still use the Google Merchant Center to process orders if you'd like.

Once you have the success message in your app, you can simply flag their account as paid. Nothing overly complicated.

If you're interested in packages that already integrate with Google Checkout, you can look at this page:

Google Checkout Integration Partners

ContentLicense: CC BY-SA 2.5

Title: How to Restrict Private Content?


问:
How to write a macro that finds a cell based on length?
I am new to excel and trying to find a way to search through a column to find a 4-character ID. The spreadsheet is sorted so that all of the information falls under corresponding ID's and to pull out the ID's I need to find the cells with 4 alphanumeric characters in a column.

I have been trying to use .Find, however there is no what:= to search because the characters are all different but only the length is the same. Also, I don't believe I can run a do until loop as I need to call the macro multiple times to retrieve all the ID's that will be present in a column whereas I think the do until loop will just keep giving back the first 4 character ID, although I might be incorrect.

Thank you in advance!

答:
The following might help you. Assuming you have a single contiguous range of cells, some of which contain a 4 character code, you can do

```<code>Sub test()
Dim r As Range
Set r = Range("A1:A6")

For Each c In r.Cells
  If Len(c) = 4 Then
    Debug.Print "cell ", c.Address(), " had four characters: ", c.Value()
  End If
Next c
End Sub
</code>```

When I run this on a spreadsheet where the first 6 cells in column A are

```<code>This
is
a
list
of
words
</code>```

The output in the debug window is

```<code>cell $A$1 had four characters: this
cell $A$4 had four characters: list
</code>```

This is for inspiration only, as your problem was really not very well described. Can you take it from here?

Body:
The following might help you. Assuming you have a single contiguous range of cells, some of which contain a 4 character code, you can do

Sub test()
Dim r As Range
Set r = Range("A1:A6")

For Each c In r.Cells
  If Len(c) = 4 Then
    Debug.Print "cell ", c.Address(), " had four characters: ", c.Value()
  End If
Next c
End Sub

When I run this on a spreadsheet where the first 6 cells in column A are

This
is
a
list
of
words

The output in the debug window is

cell $A$1 had four characters: this
cell $A$4 had four characters: list

This is for inspiration only, as your problem was really not very well described. Can you take it from here?


问:
Use numpy to get permutations of multiple lists' items
For example, if I have the following arrays:

```<code>arraya = ['z', 'q']
arrayb = ['t', 'f']
</code>```

I'd like to use the items from each list to create 'pairs' and get the following output:

```<code>['zt', 'zf', 'qt', 'qf']
</code>```

I know I can figure out a jury-rigged way to write a function that produces this result, but a prebuilt function would be better for my purposes.

答:
This is as close to a built-in as you'll be able to get.

```<code>>>> import itertools
>>> [''.join(x) for x in itertools.product(arraya, arrayb)]
['zt', 'zf', 'qt', 'qf']
</code>```

Find the cartesian product of the 2 lists/arrays and then concatenate the product.

Body:
For example, if I have the following arrays:

arraya = ['z', 'q']
arrayb = ['t', 'f']

I'd like to use the items from each list to create 'pairs' and get the following output:

['zt', 'zf', 'qt', 'qf']

I know I can figure out a jury-rigged way to write a function that produces this result, but a prebuilt function would be better for my purposes.

Body:
This is as close to a built-in as you'll be able to get.

>>> import itertools
>>> [''.join(x) for x in itertools.product(arraya, arrayb)]
['zt', 'zf', 'qt', 'qf']

Find the cartesian product of the 2 lists/arrays and then concatenate the product.


问:
How load a model saved using `saver.save` in Tensorflow's Java API
I am trying to read a model from disk using the new Java API.

The one example to use Tensorflow's Java API shows how to read a .pb model file that has both graph definition and the parameter weights.

On the Python side, Tensorflow suggests to use a Saver object to save a model to disk. It creates a .meta file that has the definition and has .data files for the weights. In Python, I use new_saver=tf.train.import_meta_graph(var_filename)
new_saver.restore(sess, model_filename) to read the model from the disk.

How do I do it in the Java API?

答:
I'm doing something similar, train the model on a hadoop cluster using the python interface and use the model and the learned parameters to predict in java.

To save the model

you have to use SavedModelBuilder. Here you find guidance:
https://tensorflow.github.io/serving/serving_basic.html
and you can use their mnist example con construct the function signatures
https://github.com/tensorflow/serving/blob/master/tensorflow_serving/example/mnist_saved_model.py

Usage is very simple on the java side:

```<code>SavedModelBundle load = SavedModelBundle.load(modelDir, "serve");
        float[][] resultArray;
        try (Graph g = load.graph()) {
            try (Session s = load.session();
                 Tensor result = s.runner().feed("data", data).fetch("prediction").run().get(0)) {
                resultArray = result.copyTo(new float[10][1]);
            }
        }
        load.close();
        return resultArray;
</code>```

To get the names of the feed and the fetched operations you can print your signatures, and use the input and output value names.

```<code>print(prediction_signature)
</code>```

https://github.com/tensorflow/serving/blob/master/tensorflow_serving/example/mnist_saved_model.py#L119

Body:
I'm doing something similar, train the model on a hadoop cluster using the python interface and use the model and the learned parameters to predict in java.

To save the model

you have to use SavedModelBuilder. Here you find guidance:
https://tensorflow.github.io/serving/serving_basic.html
and you can use their mnist example con construct the function signatures
https://github.com/tensorflow/serving/blob/master/tensorflow_serving/example/mnist_saved_model.py

Usage is very simple on the java side:

SavedModelBundle load = SavedModelBundle.load(modelDir, "serve");
        float[][] resultArray;
        try (Graph g = load.graph()) {
            try (Session s = load.session();
                 Tensor result = s.runner().feed("data", data).fetch("prediction").run().get(0)) {
                resultArray = result.copyTo(new float[10][1]);
            }
        }
        load.close();
        return resultArray;

To get the names of the feed and the fetched operations you can print your signatures, and use the input and output value names.

print(prediction_signature)

https://github.com/tensorflow/serving/blob/master/tensorflow_serving/example/mnist_saved_model.py#L119


问:
How to tell if you're currently in the last row of an HTML table?
I have a keydown event that I'm using to add a blank row to a table.
But I only want the new row to be added if the keydown event happens when the cursor is in last row of the table.

This is my current jQuery event.
.glCreditValue is the class of an input textbox that resides in the last TD of the table row.
So when the user tabs out of that input, IF the TD that the input is inside of is in the last row of the table, I want to add a new row.

Being that the table data is generated dynamically, every row's final TD has an input textbox with the class .glCreditValue.

```<code>$(".glCreditValue").keydown(function(event) {
        var keycode = event.keyCode;
        if (keycode == 9) {
            //HERE i would like to make sure that i'm in the last row of the table
            AddNewRow();
        }
    });
</code>```

I'm trying to make use of the tr:last selector, but I'm not sure quite where to go from here.

答:
There are a few ways to do this, for example you could check the .closest() parent
 and see if it .is() a :last-child, like this:

```<code>$(".glCreditValue").keydown(function(event) {
  if (event.which == 9 && $(this).closest("tr").is(":last-child")) {
      AddNewRow();
  }
});
</code>```

Body:
I have a keydown event that I'm using to add a blank row to a table.
But I only want the new row to be added if the keydown event happens when the cursor is in last row of the table.

This is my current jQuery event.
.glCreditValue is the class of an input textbox that resides in the last TD of the table row.
So when the user tabs out of that input, IF the TD that the input is inside of is in the last row of the table, I want to add a new row.

Being that the table data is generated dynamically, every row's final TD has an input textbox with the class .glCreditValue.

$(".glCreditValue").keydown(function(event) {
        var keycode = event.keyCode;
        if (keycode == 9) {
            //HERE i would like to make sure that i'm in the last row of the table
            AddNewRow();
        }
    });

I'm trying to make use of the tr:last selector, but I'm not sure quite where to go from here.

Body:
There are a few ways to do this, for example you could check the .closest() parent <tr> and see if it .is() a :last-child, like this:

$(".glCreditValue").keydown(function(event) {
  if (event.which == 9 && $(this).closest("tr").is(":last-child")) {
      AddNewRow();
  }
});


问:
condense an if/else if statement using logical operators with javascript
I'm learning AngularJS, trying to make a simple calculator, and I'm trying to condense this if/else if statement to 1-2 lines, using the Javascript logical Operators (&&, ||, !)

Given this example, how could I reduce it?
(if you don't understand $scope, ignore it. Its basically a view. So when someone clicks 9, the calculator will display 9 on the answer screen)

```<code>$scope.setOperand = function (operandEntered) {

    if ($scope.leftOperand === null) {
        $scope.leftOperand = operandEntered;
    }
    else if ($scope.operator === null) {
        $scope.leftOperand = $scope.leftOperand + operandEntered;
    }
    else if ($scope.rightOperand === null) {
        $scope.rightOperand = operandEntered;
    }
    else if ($scope.answer === null) {
        $scope.rightOperand = $scope.rightOperand + operandEntered;
    }
 };
</code>```

答:
short answer  - all of the code is further above in a previous answer i made. edited, good to go. </p>

```<code>$scope.setOperand = function (operandEntered) {
        if ($scope.operator){
            $scope.rightOperand += operandEntered;
        }
        else {
            $scope.leftOperand += operandEntered;
        };
    };
</code>```

Body:
I'm learning AngularJS, trying to make a simple calculator, and I'm trying to condense this if/else if statement to 1-2 lines, using the Javascript logical Operators (&&, ||, !)

Given this example, how could I reduce it?
(if you don't understand $scope, ignore it. Its basically a view. So when someone clicks 9, the calculator will display 9 on the answer screen)

$scope.setOperand = function (operandEntered) {

    if ($scope.leftOperand === null) {
        $scope.leftOperand = operandEntered;
    }
    else if ($scope.operator === null) {
        $scope.leftOperand = $scope.leftOperand + operandEntered;
    }
    else if ($scope.rightOperand === null) {
        $scope.rightOperand = operandEntered;
    }
    else if ($scope.answer === null) {
        $scope.rightOperand = $scope.rightOperand + operandEntered;
    }
 };

Body:
short answer  - all of the code is further above in a previous answer i made. edited, good to go.

$scope.setOperand = function (operandEntered) {
        if ($scope.operator){
            $scope.rightOperand += operandEntered;
        }
        else {
            $scope.leftOperand += operandEntered;
        };
    };


问:
ASP MVC API response to model
Im using an api to obtain some financial information for clients in out system.

The information returned from the API is passed to a model(ReportResponse) and displayed in a view (Report)

within the view i look through the items in the Model using a foreach and display as follows

```<code>  @foreach (var r in Model.JsonReport.ReportDetail.FirstAddress.DataSections.AccountData.AccountDataDetail.AccountDataItem.Select((value, i) => new { i, value }))
    {
        if (Decimal.Parse(r.value.Balances.Current.ToString().Replace("£", "")) > 0)

        {

            <div class="col-md-3">
                <div class="panel panel-primary">
                    <div class="panel-heading">
                        <div class="col-md-10">
                            @r.value.AccountOverview.CompanyName

                        </div>

                        <div class="col-md-2">
                            <button class="btn btn-primary" id="@r.i" onclick="SubmitDebt(@r.i)">Save</button>
                        </div>
                        <div class="clearfix"></div>
                    </div>
                    <div class="panel-body">
                        <div class="row">
                            <div class="col-md-6">
                                Current Balance
                            </div>
                            <div class="col-md-6">
                                @r.value.Balances.Current
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                Default Delinquent
                            </div>
                            <div class="col-md-6">
                                @r.value.Balances.DefaultDelinquent
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                Start
                            </div>
                            <div class="col-md-6">
                                @r.value.Balances.Start
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                Account Number
                            </div>
                            <div class="col-md-6">
                                @r.value.AccountOverview.AccountNumber
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                Account Type
                            </div>
                            <div class="col-md-6">
                                @r.value.AccountOverview.AccountType
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                Company Type
                            </div>
                            <div class="col-md-6">
                                @r.value.AccountOverview.CompanyType
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                Credit Limit
                            </div>
                            <div class="col-md-6">
                                @r.value.AccountOverview.CreditLimit
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                Credit Limit
                            </div>
                            <div class="col-md-6">
                                @r.value.AccountOverview.JointAccount
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        }

    }
</code>```

the information is then reviewed with the client who will be on the phone, and if applicable i then want this information adding to our Debts model.

My question is how do i map objects from the Report view to a debt model?

As you can see i do not have a strongly typed view, and the amount information returned from the API is variable and therefore needs to be dynamic

I would ideally like to be able to add a button to each section of the report that allows the user to press save, at which point i want just that one section on the report to be placed in my debt model and stored in the database

答: This is not going to work. The view is not submitted when you click a button. A form POST only returns fields, like input, select which are in the submitted form. I do not see a form, nor fields in your view. So you can return an id only.</p>

Title: ASP MVC API response to model

Body:
Im using an api to obtain some financial information for clients in out system.

The information returned from the API is passed to a model(ReportResponse) and displayed in a view (Report)

within the view i look through the items in the Model using a foreach and display as follows

  @foreach (var r in Model.JsonReport.ReportDetail.FirstAddress.DataSections.AccountData.AccountDataDetail.AccountDataItem.Select((value, i) => new { i, value }))
    {
        if (Decimal.Parse(r.value.Balances.Current.ToString().Replace("£", "")) > 0)

        {

                            @r.value.AccountOverview.CompanyName

                            <button class="btn btn-primary" id="@r.i" onclick="SubmitDebt(@r.i)">Save</button>

                                Current Balance

                                @r.value.Balances.Current

                                Default Delinquent

                                @r.value.Balances.DefaultDelinquent

                                Start

                                @r.value.Balances.Start

                                Account Number

                                @r.value.AccountOverview.AccountNumber

                                Account Type

                                @r.value.AccountOverview.AccountType

                                Company Type

                                @r.value.AccountOverview.CompanyType

                                Credit Limit

                                @r.value.AccountOverview.CreditLimit

                                Credit Limit

                                @r.value.AccountOverview.JointAccount

        }

    }

the information is then reviewed with the client who will be on the phone, and if applicable i then want this information adding to our Debts model.

My question is how do i map objects from the Report view to a debt model?

As you can see i do not have a strongly typed view, and the amount information returned from the API is variable and therefore needs to be dynamic

I would ideally like to be able to add a button to each section of the report that allows the user to press save, at which point i want just that one section on the report to be placed in my debt model and stored in the database


问:
Refresh/ TImer function for only 1 of 2 feeds -- $q.all() merge
This is a question based off my previous question here.

Essentially, I've used the $q.all() method to resolve multiple http calls. Then I filter and merge the two data sources.

This all works really well. But I want one of my two feeds to refresh every 5 minutes. Normally, I would do this by appending the following timer to the end of my code

```<code>var timer = $scope.intervalFunction = function() {
    $timeout(function() {
       /* function to call $http.get again */
        $scope.intervalFunction();
    }, 300000)
};
timer();
$timeout.cancel(timer);
</code>```

My issue is, since I don't define the http calls as separate functions, and I also "merge" both sources, how do I call one of these sources only, and then update accordingly without making multiple list item copies (which is something that has happened to me in many attempts).

Thank you!

JSFiddle here

答:
"I want one of my two feeds to refresh every 5 minutes". I'm not sure that you can do the trick with one of two $q.all requests. I just can advice you to make another request outside of your $q.all wrapper and start $timeout for it after your getting the result of first $q.all request.

Need to say, that I'm not absolutely sure in this solution because I didn't test it, but hope this will works:

```<code>$q.all(promises)
  .then(function(response) {
    metadata = response.metadataPromise.data;
    metrics = response.metricsPromise.data;
    joinMetadataAndMetrics();
    requestEveryFiveMinutes();
  })
  .catch (error) (function (error) {
    console.log(error);
  });

function requestEveryFiveMinutes() {
  $interval(function() {
    // here you can make the needed http request
    yourRequest()
      .then(function() {
        // handle the response as needed
      })
      .catch(function(err) {
        console.log(err);
      })
  }, 300000);
}
</code>```

And don't forget to inject $interval in your controller

Body:
This is a question based off my previous question here.

Essentially, I've used the $q.all() method to resolve multiple http calls. Then I filter and merge the two data sources.

This all works really well. But I want one of my two feeds to refresh every 5 minutes. Normally, I would do this by appending the following timer to the end of my code

var timer = $scope.intervalFunction = function() {
    $timeout(function() {
       /* function to call $http.get again */
        $scope.intervalFunction();
    }, 300000)
};
timer();
$timeout.cancel(timer);

My issue is, since I don't define the http calls as separate functions, and I also "merge" both sources, how do I call one of these sources only, and then update accordingly without making multiple list item copies (which is something that has happened to me in many attempts).

Thank you!

JSFiddle here

Body:
"I want one of my two feeds to refresh every 5 minutes". I'm not sure that you can do the trick with one of two $q.all requests. I just can advice you to make another request outside of your $q.all wrapper and start $timeout for it after your getting the result of first $q.all request.

Need to say, that I'm not absolutely sure in this solution because I didn't test it, but hope this will works:

$q.all(promises)
  .then(function(response) {
    metadata = response.metadataPromise.data;
    metrics = response.metricsPromise.data;
    joinMetadataAndMetrics();
    requestEveryFiveMinutes();
  })
  .catch (error) (function (error) {
    console.log(error);
  });

function requestEveryFiveMinutes() {
  $interval(function() {
    // here you can make the needed http request
    yourRequest()
      .then(function() {
        // handle the response as needed
      })
      .catch(function(err) {
        console.log(err);
      })
  }, 300000);
}

And don't forget to inject $interval in your controller


问:
Can anyone explain why a section isn't centering on my page?
I'm trying to center a few elements on my page vertically and horizontally, but for some reason, setting the container element to have a margin of auto isn't centering them.  Can anyone explain why?

HTML/CSS

body{
 margin: 0;
 padding: 0;
 background-color: rgb(0, 0, 0);
}

#links{
 margin: auto;
}

.link{
 display: inline-block;
 margin: 0 2%;
 width: 15vw;
 height: 15vw;
 border: 2px solid rgb(100, 100, 0);
 border-radius: 50%;
 background-image: url("line.png");
 background-repeat: no-repeat;
 background-size: contain;
 background-position: center;
 background-color: rgb(0, 0, 50);
}

.link:first-of-type{
 margin-left: 0;
}

.link:last-of-type{
 margin-right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="landingpage">
    <section id="links">
        <div class="link" id="home"></div>
        <div class="link" id="work"></div>
        <div class="link" id="contact"></div>
    </section>
</div></code>```

Pen

答: For horizontal centering make #linksdisplay:inline-block or give it a fixed width. And for vertical centering there is no simple way. Make your parent div position:relative and make #links position:absolute; top: 50%; left: 50%; transform: translate(-50%, -50%).  Using table AND/OR table cell is not always good technique.

Body:
I'm trying to center a few elements on my page vertically and horizontally, but for some reason, setting the container element to have a margin of auto isn't centering them.  Can anyone explain why?

HTML/CSS

body{
 margin: 0;
 padding: 0;
 background-color: rgb(0, 0, 0);
}

#links{
 margin: auto;
}

.link{
 display: inline-block;
 margin: 0 2%;
 width: 15vw;
 height: 15vw;
 border: 2px solid rgb(100, 100, 0);
 border-radius: 50%;
 background-image: url("line.png");
 background-repeat: no-repeat;
 background-size: contain;
 background-position: center;
 background-color: rgb(0, 0, 50);
}

.link:first-of-type{
 margin-left: 0;
}

.link:last-of-type{
 margin-right: 0;
}

Pen


问:
improve mongo query performance
I'm using a node based CMS system called Keystone, which uses MongoDB for a data store, giving fairly liberal control over data and access.  I have a very complex model called Family, which has about 250 fields, a bunch of relationships, and a dozen or so methods.  I have a form on my site which allows the user to enter in the required information to create a new Family record, however the processing time is running long (12s on localhost and over 30s on my Heroku instance).  The issue I'm running into is that Heroku emits an application error for any processes that run over 30s, which means I need to optimize my query.  All processing happens very quickly except one function.  Below is the offending function:

```<code>const Family = keystone.list( 'Family' );

exports.getNextRegistrationNumber = ( req, res, done ) => {

    console.time('get registration number');

    const locals = res.locals;

    Family.model.find()
        .select( 'registrationNumber' )
        .exec()
        .then( families => {

            // get an array of registration numbers
            const registrationNumbers = families.map( family => family.get( 'registrationNumber' ) );

            // get the largest registration number
            locals.newRegistrationNumber = Math.max( ...registrationNumbers ) + 1;

            console.timeEnd('get registration number');

            done();

        }, err => {

            console.timeEnd('get registration number');

            console.log( 'error setting registration number' );

            console.log( err );

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

};

the processing in my .then() happens in milliseconds, however, the Family.model.find() takes way too long to execute.  Any advice on how to speed things up would be greatly appreciated.  There are about 40,000 Family records the query is trying to dig through, and there is already an index on the registrationNumber field.

答:
It makes sense that the then() executes quickly but the find() takes a while; finding the largest value in a set of records is a relatively quick database operation while getting the set could potentially be very time-consuming depending on a number of factors.

If you are simply reading the data and presenting it to the user via REST or some sort of visual interface, you can make use of lean() which will return plain javascript objects. By default, you are returning a mongoose.Document which in your case is unnecessary as there does not appear to be any data manipulation after your read query; you are just getting the data.

More importantly, it appears that all you need is one record: the record with the largest registrationNumber. You should always use findOne() when you are looking for one record in any set of records to maximize performance.

See previous answer detailing using findOne in a node.js implementation, or see mongoDB documentation for general information about this collection method.

Title: improve mongo query performance

Body:
I'm using a node based CMS system called Keystone, which uses MongoDB for a data store, giving fairly liberal control over data and access.  I have a very complex model called Family, which has about 250 fields, a bunch of relationships, and a dozen or so methods.  I have a form on my site which allows the user to enter in the required information to create a new Family record, however the processing time is running long (12s on localhost and over 30s on my Heroku instance).  The issue I'm running into is that Heroku emits an application error for any processes that run over 30s, which means I need to optimize my query.  All processing happens very quickly except one function.  Below is the offending function:

const Family = keystone.list( 'Family' );

exports.getNextRegistrationNumber = ( req, res, done ) => {

    console.time('get registration number');

    const locals = res.locals;

    Family.model.find()
        .select( 'registrationNumber' )
        .exec()
        .then( families => {

            // get an array of registration numbers
            const registrationNumbers = families.map( family => family.get( 'registrationNumber' ) );

            // get the largest registration number
            locals.newRegistrationNumber = Math.max( ...registrationNumbers ) + 1;

            console.timeEnd('get registration number');

            done();

        }, err => {

            console.timeEnd('get registration number');

            console.log( 'error setting registration number' );

            console.log( err );

            done();
        });

};

the processing in my .then() happens in milliseconds, however, the Family.model.find() takes way too long to execute.  Any advice on how to speed things up would be greatly appreciated.  There are about 40,000 Family records the query is trying to dig through, and there is already an index on the registrationNumber field.


问:
Change the version of excel attached file in email using c#
I am trying to send the email with attached excel xlsx file.
I can download the attached excel file on my laptop, and galaxy phone but I can't download it on the iphone.
 So I want to lower the excel version using https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.xlfileformat.aspx.
For this, when I change the code to

```<code> wb.SaveAs("filename.xls", FileFormat: Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel8);
</code>```

It says SaveAs does not have a parameter for FileFormat.
They said they need 2 parameters. (Stream stream, bool validate)

So I have no idea where can I put those fileformat to change the fileformat from xlsx to xls on my code.

```<code> //set DataTable Name of Excel Sheet
  data.TableName = "E_Data";

//Create a New Workbook
using (XLWorkbook wb = new XLWorkbook())
{
//Add the DataTable as Excel Workhseet
wb.Worksheets.Add(data);

using (MemoryStream memoryStream = new MemoryStream())
{
    //Save the Excel Workbook to MemoryStream
    wb.SaveAs(memoryStream);

    //Convert MemoryStream to Byte array
    byte[] bytes = memoryStream.ToArray();
    memoryStream.Close();

     ...

      mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "NSOList.xlsx"));
}
}
</code>```

答:
You are using ClosedXml Libary, ClosedXML doesn't support the older format, hence you can not save your file as xls.
if you can use Microsoft.Office.Interop.Excel namespace (i.e office is installed on server \ pc)  it will be very easy, create your excel file using Interop.Excel and than save it
using SaveAs() method for example: wb.SaveAs(c:\\memoryStream.xls,XlFileFormat.xlOpenXMLWorkbook)

Body:
I am trying to send the email with attached excel xlsx file.
I can download the attached excel file on my laptop, and galaxy phone but I can't download it on the iphone.
 So I want to lower the excel version using https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.xlfileformat.aspx.
For this, when I change the code to

 wb.SaveAs("filename.xls", FileFormat: Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel8);

It says SaveAs does not have a parameter for FileFormat.
They said they need 2 parameters. (Stream stream, bool validate)

So I have no idea where can I put those fileformat to change the fileformat from xlsx to xls on my code.

 //set DataTable Name of Excel Sheet
  data.TableName = "E_Data";

//Create a New Workbook
using (XLWorkbook wb = new XLWorkbook())
{
//Add the DataTable as Excel Workhseet
wb.Worksheets.Add(data);

using (MemoryStream memoryStream = new MemoryStream())
{
    //Save the Excel Workbook to MemoryStream
    wb.SaveAs(memoryStream);

    //Convert MemoryStream to Byte array
    byte[] bytes = memoryStream.ToArray();
    memoryStream.Close();

     ...

      mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "NSOList.xlsx"));
}
}


问:
How do I use BCP to extract a subset of Boost which can be built?
I am trying to use the bcp tool in Boost to extract a subset of headers/libraries to use in my project.

OS: Linux Ubuntu 12.04 LTS x64

Boost version: 1.56.0, downloaded as
source code from boost.org

I want to use a custom namespace as well, which bcp supplied, but the resulting code needs to be built, and this is not as straightforward as it should be.

I would have thought a simple

```<code>./dist/bin/bcp --namespace=myboost build filesystem ../myboost
</code>```

would be enough to produce a set of files that could build the 'filesystem' library, but there seems to be extra problems that just keep cropping up.

I have read as many related posts all over the web that I could find, and yet none have presented a solution that works.

Steps I've followed and the corresponding error messages are detailed below.

After extracting the boost 1.56.0 tarball, I have done the following:

```<code>./bootstrap.sh
./b2 tools/bcp
mkdir ../myboost
./dist/bin/bcp --namespace=myboost build filesystem ../myboost
</code>```

The files copied into ../myboost don't include a bootstrap.sh, b2, bjam or other *.jam files, which seem to be something the 'build' target should be including, right?

Other sources (including stackoverflow posts) have suggested copying these files from the original boost location:

```<code>cp bootstrap.sh boost-build.jam boostcpp.jam ../myboost
cd ../myboost
./bootstrap.sh
</code>```

This then builds b2 and bjam ok.

When running b2, things fall over:

```<code>./b2

/work/approved-osslibs/boost/boost-1.56.0/myboost/tools/build/src/build /project.jam:262: in find-jamfile from module project
error: Unable to load Jamfile.
error: Could not find a Jamfile in directory 'tools/inspect/build'.
error: Attempted to find it with pattern '[Bb]uild.jam [Jj]amfile.v2 [Jj]amfile [Jj]amfile.jam'.
error: Please consult the documentation at 'http://www.boost.org'.
<error backtrace lines snipped>
</code>```

So this implies to me that the 'build' tool relies on 'inspect', so we go back and copy that:

```<code>cd ../boost_1_56_0
./dist/bin/bcp --namespace=myboost inspect ../myboost
cd ../myboost
./b2
</code>```

which results in the error:

```<code>/work/myboost/tools/build/src/build/project.jam:262: in find-jamfile from module project
error: Unable to load Jamfile.
error: Could not find a Jamfile in directory 'libs/wave/tool/build'.
error: Attempted to find it with pattern '[Bb]uild.jam [Jj]amfile.v2 [Jj]amfile [Jj]amfile.jam'.
error: Please consult the documentation at 'http://www.boost.org'.
<error backtrace lines snipped>
</code>```

So that means 'build' also depends on wave...

```<code>cd ../boost_1_56_0
./dist/bin/bcp --namespace=myboost wave ../myboost
cd ../myboost
./b2
</code>```

At which point I encounter this error:

```<code>/work/myboost/tools/build/src/build/targets.jam:397: in find-really
*** argument error
* rule project.is-registered-id ( id )
* called with: (  )
* missing argument id
/work/myboost/tools/build/src/build/project.jam:600:see definition of rule 'project.is-registered-id' being called
<error backtrace lines snipped>
</code>```

I have found this particular error relating to the boost filesystem library referenced in this ticket but that was supposed to have been fixed so I wasn't expecting to see it in Boost 1.56.0 which is the latest release.

What is going on?

Why can't bcp create an executable build system for just one boost library?

Why is build dependent on inspect and wave, which add a LOT more headers to the extracted "myboost" than should be necessary?

Any help on this issue would be appreciated.

答:
I encountered a number of issues when trying to do this today with Boost 1.64 (which I compiled with MSVC 2010 under MS Windows).  Thanks for pointing me in the right direction, BTW.

Start with bootstrap.bat and b2 -j 8 tools\bcp in the original Boost directory.  (Here, as well as below, replace 8 with the number of simultaneous jobs to run.)

When running .\dist\bin\bcp, I found that I had to include tools\build\src and libs\config\checks\architecture on my command line, for later builds to work.

I also had to copy bootstrap.bat, boost-build.jam, and boostcpp.jam to my copied-boost directory.

I don't know why, but I had to rename my original Boost directory (i.e. the one that bcp was run from) or else the build would somehow end up back in there.

After that, changing to my copied-boost directory and running bootstrap.bat allowed me to build my cut-down version of Boost with the top-level namespace changed.

b2 -j 8 toolset=msvc-10.0 threading=multi link=shared address-model=32 variant=debug

b2 -j 8 toolset=msvc-10.0 threading=multi link=shared address-model=32 variant=release

move stage\lib lib32-msvc-10.0

Body:
I am trying to use the bcp tool in Boost to extract a subset of headers/libraries to use in my project.

OS: Linux Ubuntu 12.04 LTS x64

Boost version: 1.56.0, downloaded as
source code from boost.org

I want to use a custom namespace as well, which bcp supplied, but the resulting code needs to be built, and this is not as straightforward as it should be.

I would have thought a simple

./dist/bin/bcp --namespace=myboost build filesystem ../myboost

would be enough to produce a set of files that could build the 'filesystem' library, but there seems to be extra problems that just keep cropping up.

I have read as many related posts all over the web that I could find, and yet none have presented a solution that works.

Steps I've followed and the corresponding error messages are detailed below.

After extracting the boost 1.56.0 tarball, I have done the following:

./bootstrap.sh
./b2 tools/bcp
mkdir ../myboost
./dist/bin/bcp --namespace=myboost build filesystem ../myboost

The files copied into ../myboost don't include a bootstrap.sh, b2, bjam or other *.jam files, which seem to be something the 'build' target should be including, right?

Other sources (including stackoverflow posts) have suggested copying these files from the original boost location:

cp bootstrap.sh boost-build.jam boostcpp.jam ../myboost
cd ../myboost
./bootstrap.sh

This then builds b2 and bjam ok.

When running b2, things fall over:

./b2

/work/approved-osslibs/boost/boost-1.56.0/myboost/tools/build/src/build /project.jam:262: in find-jamfile from module project
error: Unable to load Jamfile.
error: Could not find a Jamfile in directory 'tools/inspect/build'.
error: Attempted to find it with pattern '[Bb]uild.jam [Jj]amfile.v2 [Jj]amfile [Jj]amfile.jam'.
error: Please consult the documentation at 'http://www.boost.org'.
<error backtrace lines snipped>

So this implies to me that the 'build' tool relies on 'inspect', so we go back and copy that:

cd ../boost_1_56_0
./dist/bin/bcp --namespace=myboost inspect ../myboost
cd ../myboost
./b2

which results in the error:

/work/myboost/tools/build/src/build/project.jam:262: in find-jamfile from module project
error: Unable to load Jamfile.
error: Could not find a Jamfile in directory 'libs/wave/tool/build'.
error: Attempted to find it with pattern '[Bb]uild.jam [Jj]amfile.v2 [Jj]amfile [Jj]amfile.jam'.
error: Please consult the documentation at 'http://www.boost.org'.
<error backtrace lines snipped>

So that means 'build' also depends on wave...

cd ../boost_1_56_0
./dist/bin/bcp --namespace=myboost wave ../myboost
cd ../myboost
./b2

At which point I encounter this error:

/work/myboost/tools/build/src/build/targets.jam:397: in find-really
*** argument error
* rule project.is-registered-id ( id )
* called with: (  )
* missing argument id
/work/myboost/tools/build/src/build/project.jam:600:see definition of rule 'project.is-registered-id' being called
<error backtrace lines snipped>

I have found this particular error relating to the boost filesystem library referenced in this ticket but that was supposed to have been fixed so I wasn't expecting to see it in Boost 1.56.0 which is the latest release.

What is going on?

Why can't bcp create an executable build system for just one boost library?

Why is build dependent on inspect and wave, which add a LOT more headers to the extracted "myboost" than should be necessary?

Any help on this issue would be appreciated.


问:
Can I Skin HTML5 Video on the iPhone / iPad?
I've seen lots of tutorials on how to skin html5 video for desktop browsers, but can't find anything relating to skinning the html5 <video> on an iPad / iPhone.

I'm assuming that this is because it can't be done.

Anyone draw a line under this for me?

Thanks!

答: Everything you read about skinning html5 videos is valid for iPad/iPhone. The <video> element is launched in a UIWebView which is rendered by the Webkit engine (Chrome, Safari)


问:
How to automatically change drawables depending on a flavor?
I'm working on a really messy app and first time with flavors. App has like 4,5 flavors all with identical background colors, drawables, etc. Only logo is different.

Now I have to make a new flavor with completely different layout. Background color should be yellow instead of grey and drawable images should be black instead of white. The problem is, I have like 100 different white images. Is there a way I can change them to black automatically? (designer can redraw them or whatever to be black and I can put them in drawable folder of that flavor) Or I would have to programmatically check if new flavor is used then call setDrawable(newBlackImage) on every widget that uses white drawable?  That seems like a very complicated way to do since all drawables are set via XML layout..

The way they've been using flavors was creating resource bool file and then check in code if some key has value true/false then hide/show some things... So I assume I should do something similar with this, or no?

This is what the project structure for one of my flavors looks like:

As you can see, every flavor only has different launcher and login screen icons. Also each has their own arrays, bools and strings resource files. But all of them share same layout resources and drawables with white icons.

答:
I think you're already in the right way. By creating specific flavours for each group of drawable in your gradle file you'll just need to create a drawable folder for the flavours with specific files.

For example, the flavour 'black' will need a drawable folder in which all your black-background images will be stored.

In order to get it working, all resources must exist for all flavours so you won't need to change any part of your code.

You can find a quick guide here:
https://medium.com/@thiagolopessilva/the-handling-multiple-java-source-and-resources-using-flavors-on-gradle-18a4b581285b


问:
summarize weekly average using daily data in R
How to add one column price.wk.average to the data such that price.wk.average is equal to the average price of last week, and also add one column price.mo.average to the data such that it equals to the average price of last month? The price.wk.average will be the same for the entire week. </p>

```<code> Dates    Price   Demand  Price.wk.average   Price.mo.average
 2010-1-1   x        x
 2010-1-2   x        x
 ......
  2015-1-1  x         x
</code>```

答:
(Since I don't have enough points to comment)

I wanted to point out that Eric's answer will not distinguish average weekly price by year. Therefore, if you are interested in unique weeks (Week 1 of 2012 != Week 1 of 2015 ), you will need to do extra work to group by unique weeks.

```<code>df <- data.frame( Dates = c("2010-1-1", "2010-1-2", "2015-01-3"),
                  Price = c(50, 20, 40) )

      Dates Price
1  2010-1-1    50
2  2010-1-2    20
3 2015-01-3    40
</code>```

Just to keep your data frame tidy, I suggest converting dates to POSIX format then sorting the data frame:

```<code>library(lubridate)
df <- df %>%
      mutate(Dates = lubridate::parse_date_time(Dates,"ymd")) %>%
      arrange( Dates )
</code>```

To group by unique weeks:

```<code>df <- df %>%
      group_by( yw = paste( year(Dates), week(Dates)))
</code>```

Then mutate and ungroup.

To group by unique months:

```<code>df <- df %>%
      group_by( ym = paste( year(Dates), month(Dates)))
</code>```

and mutate and ungroup.

Body:
How to add one column price.wk.average to the data such that price.wk.average is equal to the average price of last week, and also add one column price.mo.average to the data such that it equals to the average price of last month? The price.wk.average will be the same for the entire week.

 Dates    Price   Demand  Price.wk.average   Price.mo.average
 2010-1-1   x        x
 2010-1-2   x        x
 ......
  2015-1-1  x         x

Body:
(Since I don't have enough points to comment)

I wanted to point out that Eric's answer will not distinguish average weekly price by year. Therefore, if you are interested in unique weeks (Week 1 of 2012 != Week 1 of 2015 ), you will need to do extra work to group by unique weeks.

df <- data.frame( Dates = c("2010-1-1", "2010-1-2", "2015-01-3"),
                  Price = c(50, 20, 40) )

      Dates Price
1  2010-1-1    50
2  2010-1-2    20
3 2015-01-3    40

Just to keep your data frame tidy, I suggest converting dates to POSIX format then sorting the data frame:

library(lubridate)
df <- df %>%
      mutate(Dates = lubridate::parse_date_time(Dates,"ymd")) %>%
      arrange( Dates )

To group by unique weeks:

df <- df %>%
      group_by( yw = paste( year(Dates), week(Dates)))

Then mutate and ungroup.

To group by unique months:

df <- df %>%
      group_by( ym = paste( year(Dates), month(Dates)))

and mutate and ungroup.


问:
What is the alternative for switch statement in Lua language?
I have this piece of code in C++ and i want to know how can i write some codes that replace switch statement in Lua because i face many problems and i need to use this statement.

```<code>   int choice;
do// loop
{
      cout<<"\n >>> The General Menu <<< \n";
      cout << endl;
    cout<< " press (1) to Add    "<<endl;
    cout<< " press (2) to Save   "<<endl;
    cout<< " press (3) to Quit " << endl;
    cout<< endl;
      cout<< "Enter your choice please (1/2/3): ";
    cin>>choice;

    switch(choice)
    {
        case 1:
            add();
            break;
        case 2:
            save();
            break;

        default:
            cout<<" The program has been terminated "<<endl;
           cout<<" Thank you! \n";
    }
} while (choice != 3);
</code>```

}
The statement has been used inside a do..while loop.

答:
one more version of switcher (without initializing table as variable):</p>

```<code>local case=2;
local result=({[1]="case1", [2]="case2", 3="case3"})[case];
print (result); --> case2
</code>```

Body:
I have this piece of code in C++ and i want to know how can i write some codes that replace switch statement in Lua because i face many problems and i need to use this statement.

   int choice;
do// loop
{
      cout<<"\n >>> The General Menu <<< \n";
      cout << endl;
    cout<< " press (1) to Add    "<<endl;
    cout<< " press (2) to Save   "<<endl;
    cout<< " press (3) to Quit " << endl;
    cout<< endl;
      cout<< "Enter your choice please (1/2/3): ";
    cin>>choice;

    switch(choice)
    {
        case 1:
            add();
            break;
        case 2:
            save();
            break;

        default:
            cout<<" The program has been terminated "<<endl;
           cout<<" Thank you! \n";
    }
} while (choice != 3);

}
The statement has been used inside a do..while loop.

Body:
one more version of switcher (without initializing table as variable):

local case=2;
local result=({[1]="case1", [2]="case2", 3="case3"})[case];
print (result); --> case2


问:
Mongoose SchemaTypes Syntax: Array of ObjectIds
Is this

```<code>blog: [{type: Schema.Types.ObjectId, ref: 'BlogEntry'}]
</code>```

the same as this

```<code>blog: {type: [Schema.Types.ObjectId], ref: 'BlogEntry'}
</code>```

or is the second example incorrect?

答:
Both are correct, but they're not the same. In the first one, the key blog is an array of objects. Each object contains two keys: type and ref where type is a single ObjectId and ref is already define.
In the second one the key blog is no longer an array but a single object. Now, in this object the key type is an array of ObjectId.

Body:
Is this

blog: [{type: Schema.Types.ObjectId, ref: 'BlogEntry'}]

the same as this

blog: {type: [Schema.Types.ObjectId], ref: 'BlogEntry'}

or is the second example incorrect?


问:
Overwriting the default case class constructor (Scala)
If I have a case class:

```<code>case class NonNegativeInt(i: Int)
</code>```

where the field i to be set to 0 if the parameter is negative. So I cannot just use the default constructor provided by the case class. If I define an apply() method in the companion object (or wherever):

```<code>def apply(n: Int) = new NonNegativeInt(Math.max(0, n))
</code>```

Apparently they have the same signature. Is there a practical way/pattern to process the constraints on the fields?

答:
Although I mostly agree with @flavian's answer that you should use another name for your method, what you can do is not make a case class at all. Or rather, implement by hand all that the case class construct gives you:</p>

```<code>class NonNegativeInt private (val i: Int) {
  override def equals(that: Any): Boolean = that.isInstanceOf[NonNegativeInt] && that.asInstanceOf[NonNegativeInt].i == i
  override def hashCode = i.hashCode

  def copy(i: Int = this.i) = NonNegativeInt(i)  //use companion apply method, not private constructor
}

object NonNegativeInt {
  def apply(i: Int) =
    new NonNegativeInt(if (i < 0) 0 else i)

  def unapply(that: NonNegativeInt): Option[Int] = Some(that.i)
}
</code>```

Body:
If I have a case class:

case class NonNegativeInt(i: Int)

where the field i to be set to 0 if the parameter is negative. So I cannot just use the default constructor provided by the case class. If I define an apply() method in the companion object (or wherever):

def apply(n: Int) = new NonNegativeInt(Math.max(0, n))

Apparently they have the same signature. Is there a practical way/pattern to process the constraints on the fields?

Body:
Although I mostly agree with @flavian's answer that you should use another name for your method, what you can do is not make a case class at all. Or rather, implement by hand all that the case class construct gives you:

class NonNegativeInt private (val i: Int) {
  override def equals(that: Any): Boolean = that.isInstanceOf[NonNegativeInt] && that.asInstanceOf[NonNegativeInt].i == i
  override def hashCode = i.hashCode

  def copy(i: Int = this.i) = NonNegativeInt(i)  //use companion apply method, not private constructor
}

object NonNegativeInt {
  def apply(i: Int) =
    new NonNegativeInt(if (i < 0) 0 else i)

  def unapply(that: NonNegativeInt): Option[Int] = Some(that.i)
}


问:
Value type of string? Has no member components. (Struct)
I look at each thread but can't find any solution for my case.
I have a model:

```<code>import Foundation

public struct Destinos: Data {
    public var idDestino : Int?
    public var desDestino : String?

    public func dictionary() -> NSDictionary {

        let dictionary = NSMutableDictionary()

        dictionary.setValue(self.idDestino, forKey: "idDestino")
        dictionary.setValue(self.desDestino, forKey: "desDestino")

        return dictionary
    }
}
</code>```

So I want to change the desDestino "string" to [String] to use later and show in at tableView. For this.I write this line of code in another file.swift:

```<code>var cadena = Destinos()

cadena.desDestino = "HOLA, nada, algo, otra, cosa, mas que eso"
let array = cadena.desDestino.components(separatedBy: ", ") // in this line i get the error: value type of string? has no member components.
</code>```

so... what is the problem?

答:
There's no reason to use NSDictionary here. Just use a native Swift dictionary (with a literal).

```<code>public struct Destinos {
    public let idDestino : Int?
    public let desDestino : String?

    public func toDictionary() -> [String: Any?] {
        return [
            "idDestino": idDestino,
            "desDestino": desDestino
        ]
    }
}
</code>```

As for generating your array, you have two issues:
1. components(seperatedBy:) is misspelt
2. cadena.desDestino is an is a String? (Also known as a Optional<String>) which hasn't been unwrapped. The nicest way to take care of this is to use optional chaining, and then use nil coalescence (??) to make it an empty array in the case cadena.desDestino is nil.

```<code>var cadena = Destinos(
    idDestino: 123,
    desDestino: "HOLA, nada, algo, otra, cosa, mas que eso"
)

let array = cadena.desDestino?.components(separatedBy: ", ") ?? []
</code>```

Body:
I look at each thread but can't find any solution for my case.
I have a model:

import Foundation

public struct Destinos: Data {
    public var idDestino : Int?
    public var desDestino : String?

    public func dictionary() -> NSDictionary {

        let dictionary = NSMutableDictionary()

        dictionary.setValue(self.idDestino, forKey: "idDestino")
        dictionary.setValue(self.desDestino, forKey: "desDestino")

        return dictionary
    }
}

So I want to change the desDestino "string" to [String] to use later and show in at tableView. For this.I write this line of code in another file.swift:

var cadena = Destinos()

cadena.desDestino = "HOLA, nada, algo, otra, cosa, mas que eso"
let array = cadena.desDestino.components(separatedBy: ", ") // in this line i get the error: value type of string? has no member components.

so... what is the problem?

Body:
There's no reason to use NSDictionary here. Just use a native Swift dictionary (with a literal).

public struct Destinos {
    public let idDestino : Int?
    public let desDestino : String?

    public func toDictionary() -> [String: Any?] {
        return [
            "idDestino": idDestino,
            "desDestino": desDestino
        ]
    }
}

As for generating your array, you have two issues:
1. components(seperatedBy:) is misspelt
2. cadena.desDestino is an is a String? (Also known as a Optional<String>) which hasn't been unwrapped. The nicest way to take care of this is to use optional chaining, and then use nil coalescence (??) to make it an empty array in the case cadena.desDestino is nil.

var cadena = Destinos(
    idDestino: 123,
    desDestino: "HOLA, nada, algo, otra, cosa, mas que eso"
)

let array = cadena.desDestino?.components(separatedBy: ", ") ?? []


问:
Debugging Serverless Framework invoke local function
I am trying to  debug sls invoke local.

My setup:

However I keep getting:

```<code>/Users/nikos/.nvm/versions/node/v6.9.1/bin/node --debug-brk=63417 --expose_debug_as=v8debug /Users/nikos/.nvm/versions/node/v6.9.1/bin/serverless invoke local -f createTodo
Debugger listening on [::]:63417

Process finished with exit code 130 (interrupted by signal 2: SIGINT)
</code>```

答:
I've gotten this to work in IntelliJ, so it should work in Webstorm too. You will need the serverless-offline plugin (https://github.com/dherault/serverless-offline)

In your Run Configuration, change your Application parameters to:

offline -s dev

and add the environment variable SLS_DEBUG=*

serverless-offline will start a server that the IntelliJ Node debugger can hook into.

Body:
I am trying to  debug sls invoke local.

My setup:

However I keep getting:

/Users/nikos/.nvm/versions/node/v6.9.1/bin/node --debug-brk=63417 --expose_debug_as=v8debug /Users/nikos/.nvm/versions/node/v6.9.1/bin/serverless invoke local -f createTodo
Debugger listening on [::]:63417

Process finished with exit code 130 (interrupted by signal 2: SIGINT)


问:
Scipy Newton Krylov Expects Square Matrix
I am trying to use scipy.optimize.newton_krylov() to solve a least-squares optimization problem, i.e. finding x such that (Ax - b)**2 = 0. My understanding is that A has to be mxn with m>n, b has to be mx1, and x will be nx1. When I try to run the optimization, I get an error:

```<code>ValueError: expected square matrix, but got shape=(40, 6)
</code>```

Presumably this error concerns the computation of the Jacobian and not my input matrix A? But if so, how can I change the values I am providing to the functions to resolve this problem? Any advice would be appreciated.

The following code reproduces the error:

```<code>import numpy as np
from scipy.optimize import newton_krylov

A = np.random.uniform(0, 1, (40,6))
b = np.arange(40)
x0 = np.ones(6)

def F(x):
    return (A.dot(x) - b)**2

x = newton_krylov(F, np.ones(6))
</code>```

答:
As the docstring of newton_krylov explains, it finds a root of a function F(x).  The function F must accept a one-dimensional array, and return a one-dimensional array of the same size as the input.  If, for example, x has length 3, F(x) must return an array with length 3. In that case, newton_krylov attempts to solve F(x) = [0, 0, 0].

The error that you got is the result of newton_krylov attempting to use the numerically computed Jacobian matrix of F with a function that expects the matrix to be square.  Your function F has a Jacobian matrix with shape (40, 6), because the input has length 6 and the output has length 40.

By itself, newton_krylov is not the right function to use for solving a least-squares problem.  A least-squares problem is a minimization problem, not a root-finding problem.  (A solver such as newton_krylov might be used to implement a minimization algorithm, but I assume you are interested in using an existing solution rather than writing your own.)

You say you want to solve a least-squares problem, but then you say "i.e. finding x such that (Ax - b)**2 = 0."  I assume that was just a bit a sloppiness in your description, because that is not the least-squares problem. The least-squares problem is to find x such that sum((Ax - b)**2) is minimized.  (In general, there won't be an x that makes the sum of squares equal to zero.)

So, assuming you really want to find x such that sum((Ax - b)**2) is minimized, you can use scipy.linalg.lstsq.

For example:

```<code>In [54]: from scipy.linalg import lstsq

In [55]: A = np.random.uniform(0, 1, (40,6))

In [56]: b = np.arange(40)

In [57]: x, res, rank, s = lstsq(A, b)

In [58]: x
Out[58]:
array([  5.07513787,   1.83858547,  18.07818853,   9.28805475,
         6.13019155,  -0.7045539 ])
</code>```

Body:
I am trying to use scipy.optimize.newton_krylov() to solve a least-squares optimization problem, i.e. finding x such that (Ax - b)**2 = 0. My understanding is that A has to be mxn with m>n, b has to be mx1, and x will be nx1. When I try to run the optimization, I get an error:

ValueError: expected square matrix, but got shape=(40, 6)

Presumably this error concerns the computation of the Jacobian and not my input matrix A? But if so, how can I change the values I am providing to the functions to resolve this problem? Any advice would be appreciated.

The following code reproduces the error:

import numpy as np
from scipy.optimize import newton_krylov

A = np.random.uniform(0, 1, (40,6))
b = np.arange(40)
x0 = np.ones(6)

def F(x):
    return (A.dot(x) - b)**2

x = newton_krylov(F, np.ones(6))

Body:
As the docstring of newton_krylov explains, it finds a root of a function F(x).  The function F must accept a one-dimensional array, and return a one-dimensional array of the same size as the input.  If, for example, x has length 3, F(x) must return an array with length 3. In that case, newton_krylov attempts to solve F(x) = [0, 0, 0].

The error that you got is the result of newton_krylov attempting to use the numerically computed Jacobian matrix of F with a function that expects the matrix to be square.  Your function F has a Jacobian matrix with shape (40, 6), because the input has length 6 and the output has length 40.

By itself, newton_krylov is not the right function to use for solving a least-squares problem.  A least-squares problem is a minimization problem, not a root-finding problem.  (A solver such as newton_krylov might be used to implement a minimization algorithm, but I assume you are interested in using an existing solution rather than writing your own.)

You say you want to solve a least-squares problem, but then you say "i.e. finding x such that (Ax - b)**2 = 0."  I assume that was just a bit a sloppiness in your description, because that is not the least-squares problem. The least-squares problem is to find x such that sum((Ax - b)**2) is minimized.  (In general, there won't be an x that makes the sum of squares equal to zero.)

So, assuming you really want to find x such that sum((Ax - b)**2) is minimized, you can use scipy.linalg.lstsq.

For example:

In [54]: from scipy.linalg import lstsq

In [55]: A = np.random.uniform(0, 1, (40,6))

In [56]: b = np.arange(40)

In [57]: x, res, rank, s = lstsq(A, b)

In [58]: x
Out[58]:
array([  5.07513787,   1.83858547,  18.07818853,   9.28805475,
         6.13019155,  -0.7045539 ])


问:
SQL Server script convert xml attributes and text value into table
I have a table testA which contains 4 columns, and column Dv_Data is an xml string.

testA

```<code>ID   X  Y  Dv_Data
---------------------------------------------------------------------------
101  4  5  <U><V N="TTF">1</V><V N="MF">0</V><V N="ResultA">383.501</V></U>
102  4  6  <U><V N="TTF">0</V><V N="MF">1</V><V N="ResultA">383.601</V></U>
</code>```

The question is, how can I achieve this result with a SQL script?

```<code>ID  X  Y  TTF  MF  ResultA
---------------------------
101 4  5  1    0   383.501
102 4  6  0    1   383.601
</code>```

Table testA has hundreds of rows.

Appreciate your valuable input.

答:
You could use XML to derive the column names / values and pivot the results. For example:</p>

```<code>DECLARE @TestA TABLE (ID INT, X INT, Y INT, Dv_Data XML);
INSERT @TestA VALUES
(101, 4, 5, '<U><V N="TTF">1</V><V N="MF">0</V><V N="ResultA">383.501</V></U>'),
(102, 4, 6, '<U><V N="TTF">0</V><V N="MF">1</V><V N="ResultA">383.601</V></U>');

SELECT *
FROM
(
    SELECT T.ID,
           T.X,
           T.Y,
           ColName = A.B.value('@N', 'VARCHAR(MAX)'),
           ColVal = A.B.value('text()[1]', 'VARCHAR(MAX)')
    FROM @TestA AS T
    CROSS APPLY T.Dv_Data.nodes('U/V') AS A(B)
) AS T
PIVOT
(
    MAX(ColVal) FOR ColName IN ([TTF], [MF], [ResultA])
) AS P;
</code>```

Body:
I have a table testA which contains 4 columns, and column Dv_Data is an xml string.

testA

ID   X  Y  Dv_Data
---------------------------------------------------------------------------
101  4  5  <V N="TTF">1</V><V N="MF">0</V><V N="ResultA">383.501</V>
102  4  6  <V N="TTF">0</V><V N="MF">1</V><V N="ResultA">383.601</V>

The question is, how can I achieve this result with a SQL script?

ID  X  Y  TTF  MF  ResultA
---------------------------
101 4  5  1    0   383.501
102 4  6  0    1   383.601

Table testA has hundreds of rows.

Appreciate your valuable input.

Body:
You could use XML to derive the column names / values and pivot the results. For example:

DECLARE @TestA TABLE (ID INT, X INT, Y INT, Dv_Data XML);
INSERT @TestA VALUES
(101, 4, 5, '<U><V N="TTF">1</V><V N="MF">0</V><V N="ResultA">383.501</V></U>'),
(102, 4, 6, '<U><V N="TTF">0</V><V N="MF">1</V><V N="ResultA">383.601</V></U>');

SELECT *
FROM
(
    SELECT T.ID,
           T.X,
           T.Y,
           ColName = A.B.value('@N', 'VARCHAR(MAX)'),
           ColVal = A.B.value('text()[1]', 'VARCHAR(MAX)')
    FROM @TestA AS T
    CROSS APPLY T.Dv_Data.nodes('U/V') AS A(B)
) AS T
PIVOT
(
    MAX(ColVal) FOR ColName IN ([TTF], [MF], [ResultA])
) AS P;