问:
Always get previous state in React app
In relation to my previous question, I'm doing this to store the right state:

```<code>if (value === 'checkpoint')
{
  if (checked1)
  {
    this.setState({checked1 : false})
    localStorage.setObject('checked1', false)
  }
  else
  {
    this.setState({checked1 : true})
    localStorage.setObject('checked1', true)
  }
}
</code>```

Now I have multiple checkboxes (let's say I have four). One for ALL checkboxes, and the other 3 for categories. I want my app to detect when the three category checkboxes are checked, and check the ALL checkbox automatically. When any of the category checkboxes are unchecked, the ALL checkbox will uncheck itself.

I tried this code:

```<code>  if (checked1 && checked2 && checked3) {
    this.setState({checkedAll: true})
  } else {
    this.setState({checkedAll: false})
  }
</code>```

But the other 3 checkbox (checked1, checked2, checked3) will always get a previous state.

How do I get the right state so that my checkedAll functions correctly?

答:
If you use this.setState({new state}, //perform some action}), whatever action is being performed will receive the most current value of state.

Copy and paste this component and view the console to see it is receiving the correct state

```<code>import React, { Component } from 'react'

class Menu extends Component {
  state = {
    checkAll: false,
    check1: false,
    check2: false,
    check3: false
  }

  handleChange = () => {
    const all = (this.salmon.checked && this.tuna.checked && this.snapper.checked)
    if (all) {
      this.setState({
        checkAll: true,
        check1: this.salmon.checked,
        check2: this.tuna.checked,
        check3: this.snapper.checked
      }, () => {
        this.all.checked = true
        console.log('Most current state', JSON.stringify(this.state))
      })
    } else {
      this.setState({
        checkAll: false,
        check1: this.salmon.checked,
        check2: this.tuna.checked,
        check3: this.snapper.checked
      }, () => {
        this.all.checked = false
        console.log('Most current state', JSON.stringify(this.state))
      })
    }
  }

  handleAll = () => {
    this.setState({
      checkAll: true,
      check1: true,
      check2: true,
      check3: true
    }, () => {
      this.salmon.checked = true
      this.tuna.checked = true
      this.snapper.checked = true
      console.log('Most current state', JSON.stringify(this.state))
    })
  }

  render() {
    return (
      <div>
        <h1>Select Options</h1>
        <form>
          <span>
            Select All:
            <input
              onChange={this.handleAll}
              type="checkbox"
              value={this.state.checkAll}
              ref={all => this.all = all}
            />
          </span>
          <ul>
            <li>
              <input
                onChange={this.handleChange}
                type="checkbox"
                value={this.state.check1}
                ref={salmon => this.salmon = salmon}
              />
              Salmon
            </li>
            <li>
              <input
                onChange={this.handleChange}
                type="checkbox"
                value={this.state.check2}
                ref={tuna => this.tuna = tuna}
              />
              Tuna
            </li>
            <li>
              <input
                onChange={this.handleChange}
                type="checkbox"
                value={this.state.check3}
                ref={snapper => this.snapper = snapper}
              />
              Snapper
            </li>
          </ul>
        </form>
      </div>
    )
  }
}

export default Menu
</code>```

Title: Always get previous state in React app

Body:
In relation to my previous question, I'm doing this to store the right state:

if (value === 'checkpoint')
{
  if (checked1)
  {
    this.setState({checked1 : false})
    localStorage.setObject('checked1', false)
  }
  else
  {
    this.setState({checked1 : true})
    localStorage.setObject('checked1', true)
  }
}

Now I have multiple checkboxes (let's say I have four). One for ALL checkboxes, and the other 3 for categories. I want my app to detect when the three category checkboxes are checked, and check the ALL checkbox automatically. When any of the category checkboxes are unchecked, the ALL checkbox will uncheck itself.

I tried this code:

  if (checked1 && checked2 && checked3) {
    this.setState({checkedAll: true})
  } else {
    this.setState({checkedAll: false})
  }

But the other 3 checkbox (checked1, checked2, checked3) will always get a previous state.

How do I get the right state so that my checkedAll functions correctly?

Body:
If you use this.setState({new state}, //perform some action}), whatever action is being performed will receive the most current value of state.

Copy and paste this component and view the console to see it is receiving the correct state

import React, { Component } from 'react'

class Menu extends Component {
  state = {
    checkAll: false,
    check1: false,
    check2: false,
    check3: false
  }

  handleChange = () => {
    const all = (this.salmon.checked && this.tuna.checked && this.snapper.checked)
    if (all) {
      this.setState({
        checkAll: true,
        check1: this.salmon.checked,
        check2: this.tuna.checked,
        check3: this.snapper.checked
      }, () => {
        this.all.checked = true
        console.log('Most current state', JSON.stringify(this.state))
      })
    } else {
      this.setState({
        checkAll: false,
        check1: this.salmon.checked,
        check2: this.tuna.checked,
        check3: this.snapper.checked
      }, () => {
        this.all.checked = false
        console.log('Most current state', JSON.stringify(this.state))
      })
    }
  }

  handleAll = () => {
    this.setState({
      checkAll: true,
      check1: true,
      check2: true,
      check3: true
    }, () => {
      this.salmon.checked = true
      this.tuna.checked = true
      this.snapper.checked = true
      console.log('Most current state', JSON.stringify(this.state))
    })
  }

  render() {
    return (
      <div>
        <h1>Select Options</h1>
        <form>
          <span>
            Select All:
            <input
              onChange={this.handleAll}
              type="checkbox"
              value={this.state.checkAll}
              ref={all => this.all = all}
            />
          </span>
          <ul>
            <li>
              <input
                onChange={this.handleChange}
                type="checkbox"
                value={this.state.check1}
                ref={salmon => this.salmon = salmon}
              />
              Salmon
            </li>
            <li>
              <input
                onChange={this.handleChange}
                type="checkbox"
                value={this.state.check2}
                ref={tuna => this.tuna = tuna}
              />
              Tuna
            </li>
            <li>
              <input
                onChange={this.handleChange}
                type="checkbox"
                value={this.state.check3}
                ref={snapper => this.snapper = snapper}
              />
              Snapper
            </li>
          </ul>
        </form>
      </div>
    )
  }
}

export default Menu


来源: stackexchange

问:
Is there standard way to get numerical consistency in Julia
```<code>└─╼ julia
 Version 0.6.0 (2017-06-19 13:05 UTC)
 julia> 1.0 + 0.1 - 1.0 - 0.1 == 0
  false
 julia> 1.0 + 0.1 - 1.0 - 0.1
  8.326672684688674e-17
</code>```

i understand that decimals like 0.1 cannot be represented exactly in binary based point without some additional effort e.g.

```<code>julia> 1//10
 1//10
julia> 1 + 1//10
 11//10
julia> 1 + 1//10 - 1
 1//10
julia> 1 + 1//10 - 1 - 1//10
 0//1
julia> 1 + 1//10 - 1 - 1//10 == 0
 true
</code>```

or going purely symbolic.

there are several rounding options:
    julia> Round
    RoundDown            RoundNearest          RoundNearestTiesUp    RoundUp
    RoundFromZero        RoundNearestTiesAway  RoundToZero     RoundingMode

Without launching into a protracted discussion of numerical stability, does Julia have a recommended style?

thx

答:
This really isn't a question about Julia. This will show up in any language using IEEE floating point arithmetic, since Julia just uses the standard. So the standard rules apply.

Don't expect floating point calculations to be exact. Instead, test floating point sameness using isapprox (or \approx for ≈) with a tolerance set appropriately.

If you need true decimals, you should use rationals like in that example you have.

Another helpful thing may be DecFP.jl which uses IEEE decimal arithmetic and thus is more precise in this kind of example.

If you need to be more precise, use higher precision. BigFloats have their purpose.

ContentLicense: CC BY-SA 3.0

Body:
└─╼ julia
 Version 0.6.0 (2017-06-19 13:05 UTC)
 julia> 1.0 + 0.1 - 1.0 - 0.1 == 0
  false
 julia> 1.0 + 0.1 - 1.0 - 0.1
  8.326672684688674e-17

i understand that decimals like 0.1 cannot be represented exactly in binary based point without some additional effort e.g.

julia> 1//10
 1//10
julia> 1 + 1//10
 11//10
julia> 1 + 1//10 - 1
 1//10
julia> 1 + 1//10 - 1 - 1//10
 0//1
julia> 1 + 1//10 - 1 - 1//10 == 0
 true

or going purely symbolic.

there are several rounding options:
    julia> Round
    RoundDown            RoundNearest          RoundNearestTiesUp    RoundUp
    RoundFromZero        RoundNearestTiesAway  RoundToZero     RoundingMode

Without launching into a protracted discussion of numerical stability, does Julia have a recommended style?

thx


问:
MySql Client's Credentials Packet
How should the client's credentials packet look when communicating with a MySql server?

I am working on using a microcontroller to communicate with a MySql server on AWS.

Once I open a TCP socket to the server I receive the server's greeting packet. However, I am having trouble with the client's credentials packet.

When I send the packet I created in the code below, I do not receive a response from the server.

As a side note, I do receive the error "Got packets out of order" when I set the packet sequence number to 0 instead of 1. Any ideas?

Server's greeting:

```<code>4e0000000a352e362e33372d6c6f67006a3300005871507a363d6e3400ffff0802007fc01500000000000000000000542d2364524c65392d752659006d7973716c5f6e61746976655f70617373776f726400
</code>```

Server's Error message:

```<code>21000001ff8404233038533031476f74207061636b657473206f7574206f66206f72646572

char buf[76];
memset(buf, 0, sizeof(buf));
buf[0] = 0x4C;
buf[1] = 0x00;
buf[2] = 0x00;
buf[3] = 0x01;
buf[4] = 0x08 | 0x04;
buf[5] = 0x80 | 0x02 | 0x01;
buf[6] = 0x00;
buf[7] = 0x00;
buf[8] = 0xB8;
buf[9] = 0x0B;
buf[10] = 0x00;
buf[11] = 0x00;
buf[12] = 0x35;
char username[] = "username";
size_t usernameLength = sizeof(username);
strncpy(&buf[36],username,usernameLength-1);
buf[48] = 0x00;
char password[] = "password";
size_t passwordLength = sizeof(password);
unsigned char hash[SHA_DIGEST_LENGTH];
SHA1(password, passwordLength-1, hash);
buf[49] = 0x14;
memcpy(&buf[50],&hash[0],20);
strncpy(&buf[70],"dbname",sizeof("dbname")-1);
buf[75] = 0x00;
</code>```

答:
I understand that this was not an appropriate place to ask the question I had. However, after posting, I did find a very helpful repository on Github here: https://github.com/ChuckBell/MySQL_Connector_Arduino
The repository contains all of the source code necessary to write a client which connects to a MySQL database. Most importantly, it shows the proper way to hash the password. </p>

<p>I hope this helps other people since there is very little documentation of MySQL provided by Oracle unless you license the software, regular clients don't provide source code, and observing packet traffic provides limited insight into how the handshake process works. </p>

Title: MySql Client's Credentials Packet

Body:
How should the client's credentials packet look when communicating with a MySql server?

I am working on using a microcontroller to communicate with a MySql server on AWS.

Once I open a TCP socket to the server I receive the server's greeting packet. However, I am having trouble with the client's credentials packet.

When I send the packet I created in the code below, I do not receive a response from the server.

As a side note, I do receive the error "Got packets out of order" when I set the packet sequence number to 0 instead of 1. Any ideas?

Server's greeting:

4e0000000a352e362e33372d6c6f67006a3300005871507a363d6e3400ffff0802007fc01500000000000000000000542d2364524c65392d752659006d7973716c5f6e61746976655f70617373776f726400

Server's Error message:

21000001ff8404233038533031476f74207061636b657473206f7574206f66206f72646572

char buf[76];
memset(buf, 0, sizeof(buf));
buf[0] = 0x4C;
buf[1] = 0x00;
buf[2] = 0x00;
buf[3] = 0x01;
buf[4] = 0x08 | 0x04;
buf[5] = 0x80 | 0x02 | 0x01;
buf[6] = 0x00;
buf[7] = 0x00;
buf[8] = 0xB8;
buf[9] = 0x0B;
buf[10] = 0x00;
buf[11] = 0x00;
buf[12] = 0x35;
char username[] = "username";
size_t usernameLength = sizeof(username);
strncpy(&buf[36],username,usernameLength-1);
buf[48] = 0x00;
char password[] = "password";
size_t passwordLength = sizeof(password);
unsigned char hash[SHA_DIGEST_LENGTH];
SHA1(password, passwordLength-1, hash);
buf[49] = 0x14;
memcpy(&buf[50],&hash[0],20);
strncpy(&buf[70],"dbname",sizeof("dbname")-1);
buf[75] = 0x00;

Body:
I understand that this was not an appropriate place to ask the question I had. However, after posting, I did find a very helpful repository on Github here: https://github.com/ChuckBell/MySQL_Connector_Arduino
The repository contains all of the source code necessary to write a client which connects to a MySQL database. Most importantly, it shows the proper way to hash the password.

I hope this helps other people since there is very little documentation of MySQL provided by Oracle unless you license the software, regular clients don't provide source code, and observing packet traffic provides limited insight into how the handshake process works.


问:
Check if Xml Node has an Attribute
How do I check if a node has particular attribute or not.

What I did is:

```<code>string referenceFileName = xmlFileName;
XmlTextReader textReader = new XmlTextReader(referenceFileName);

while (textReader.Read())
{
  XmlNodeType nType = textReader.NodeType;

  // if node type is an element
  if (nType == XmlNodeType.Element)
  {
    if (textReader.Name.Equals("Control"))
    {
      if (textReader.AttributeCount >= 1)
      {
        String val = string.Empty;
        val = textReader.GetAttribute("Visible");
        if (!(val == null || val.Equals(string.Empty)))
        {

        }
      }
    }
  }
</code>```

Is there any function to check that a given attribute is present or not?

答:
If anyone is not using a reader and just an XmlDocument try XmlAttributeCollection/XmlAttribute</p>

```<code>XmlDocument doc = new XmlDocument();
try{
doc.Load(_indexFile);
    foreach(XmlNode node in doc.DocumentElement.ChildNodes){
        XmlAttributeCollection attrs = node.Attributes;
        foreach(XmlAttribute attr in attrs){
            Console.WriteLine(node.InnerText + ": " + attr.Name + " - " + attr.Value);
            if(attr.Name == "my-amazing-attribute")
            {
                //Do something with attribute
            }
        }
    }
}
} catch (Exception ex) {
    //Do something with ex
}
</code>```

Title: Check if Xml Node has an Attribute

Body:
How do I check if a node has particular attribute or not.

What I did is:

string referenceFileName = xmlFileName;
XmlTextReader textReader = new XmlTextReader(referenceFileName);

while (textReader.Read())
{
  XmlNodeType nType = textReader.NodeType;

  // if node type is an element
  if (nType == XmlNodeType.Element)
  {
    if (textReader.Name.Equals("Control"))
    {
      if (textReader.AttributeCount >= 1)
      {
        String val = string.Empty;
        val = textReader.GetAttribute("Visible");
        if (!(val == null || val.Equals(string.Empty)))
        {

        }
      }
    }
  }

Is there any function to check that a given attribute is present or not?

Body:
If anyone is not using a reader and just an XmlDocument try XmlAttributeCollection/XmlAttribute

XmlDocument doc = new XmlDocument();
try{
doc.Load(_indexFile);
    foreach(XmlNode node in doc.DocumentElement.ChildNodes){
        XmlAttributeCollection attrs = node.Attributes;
        foreach(XmlAttribute attr in attrs){
            Console.WriteLine(node.InnerText + ": " + attr.Name + " - " + attr.Value);
            if(attr.Name == "my-amazing-attribute")
            {
                //Do something with attribute
            }
        }
    }
}
} catch (Exception ex) {
    //Do something with ex
}


问:
SELECT WHERE Statement
I am trying to select the a value from the database such as

```<code> $stmt = $pdo->query('SELECT acc_id FROM account_info WHERE acc_id = (the most recent value entered ');
</code>```

i tried :

```<code>$stmt = $pdo->query('SELECT acc_id FROM account_info WHERE acc_id = "26" ');
</code>```

and it was successful. However whenever I try something like  :

```<code>$stmt = $pdo->query('SELECT acc_id FROM account_info WHERE acc_id = :acc_id');
</code>```

or

```<code>$stmt = $pdo->query('SELECT acc_id FROM account_info WHERE acc_id = $acc_id ');
</code>```

i get the following error :

```<code>core.js:1350 ERROR SyntaxError: Unexpected token S in JSON at position 0
at JSON.parse (<anonymous>)
</code>```

my TS code :

```<code>load()
{
this.http.get('http://localhost:10080/ionic/patients.php')
  .map(res => res.json())
  .subscribe(data =>
  {
     this.items = data;
  });
 }

  viewEntry(param)
{
 this.navCtrl.push('AccInfoPage',param);
}
</code>```

and this is my HTML:

```<code><ion-item *ngFor="let item of items">
<h2>{{ item.acc_id }} </h2>
<button ion-button color="primary" item-right (click)="viewEntry({ account: item })">View</button>
 </ion-item>
</code>```

What am I doing wrong ? How can I fix it ??
 Thank you in advance!

答: SELECT acc_id FROM account_info ORDER BY acc_id DESC LIMIT 1

Title: SELECT WHERE Statement

Body:
I am trying to select the a value from the database such as

 $stmt = $pdo->query('SELECT acc_id FROM account_info WHERE acc_id = (the most recent value entered ');

i tried :

$stmt = $pdo->query('SELECT acc_id FROM account_info WHERE acc_id = "26" ');

and it was successful. However whenever I try something like  :

$stmt = $pdo->query('SELECT acc_id FROM account_info WHERE acc_id = :acc_id');

or

$stmt = $pdo->query('SELECT acc_id FROM account_info WHERE acc_id = $acc_id ');

i get the following error :

core.js:1350 ERROR SyntaxError: Unexpected token S in JSON at position 0
at JSON.parse (<anonymous>)

my TS code :

load()
{
this.http.get('http://localhost:10080/ionic/patients.php')
  .map(res => res.json())
  .subscribe(data =>
  {
     this.items = data;
  });
 }

  viewEntry(param)
{
 this.navCtrl.push('AccInfoPage',param);
}

and this is my HTML:

<ion-item *ngFor="let item of items">

{{ item.acc_id }}

<button ion-button color="primary" item-right (click)="viewEntry({ account: item })">View</button>
 </ion-item>

What am I doing wrong ? How can I fix it ??
 Thank you in advance!


问:
Why is arrange() ignoring values? (Not used with group by)
My question concerns using the arrange function from the dplyr package, I saw some posts on it but all of them involved issues with group by and arrange, and just arrange seems to be causing me the problem. It is only sorting some columns of my data correctly.

I don't know if you'll be able to reproduce my problem with out the data, so here is a link to it. It's the file called outcome of care measures.csv, a data frame of hospitals and other health related variables. I wrote a function best that is supposed to return the hospital with the lowest 30 day mortality rating in given input state for a given of 3 health conditions.

I read the data and assign names for when I want to read the relevant columns like this;

```<code>best<-function(ST, outcome){
  library(dyplr)
  data<-read.csv("outcome-of-care-measures.csv", na.strings = "Not available", stringsAsFactors = FALSE)
  outcomes<-c("heart attack"=11, "heart failure"=17, "pneumonia"=23)
</code>```

And then I have 3 if branches that  each finds the hospital with the lowest mortality rate of the input health condition. My first branch functions just fine, and I can't tell it apart from the one that dosen't function. The branch below returns data whose output column is incorrectly sorted.

```<code>  if (outcome=="pneumonia"){
    rel_data<-data[, c(2,7,outcomes["pneumonia"])]
    names(rel_data)<-c("hospital", "state", "outcome")
    sorted<- arrange(rel_data, state, outcome, hospital)
    state_sorted<-subset(sorted, state==ST)
    print(state_sorted$hospital[1])}}
</code>```

When I call best("MD", "pneumonia") it returns the 10th ranked hospital, not the first. It looks like indicies 1-9 were cut off the top of this column and were pasted at the bottom of the column. Any idea what might be going wrong? If I type in "heart attack" in place of "pneumonia", the column seems to be sorted just fine and I get the correct output. I'm 100% sure the only difference is "pneumonia" instead of "heart attack".

答:
Here's a function that does what you're after, using the tidyverse package ecosystem.

```<code>getBestHospital <- function(data, state, outcome) {

  # column numbers for health conditions
  outcomes <- c("heart attack" = 11, "heart failure" = 17, "pneumonia" = 23)

  # get name of column to sort by
  sortCol <- colnames(data)[outcomes[outcome]]

  # return top-ranked hospital for given state and outcome
  data %>%
    dplyr::filter(State == state) %>%
    dplyr::arrange_(paste0("`", sortCol, "`")) %>%
    .$`Hospital Name` %>%
    head(1)

}
</code>```

And here's how to call it:

```<code>library(tidyverse)

d <- readr::read_csv("~/../Downloads/outcome-of-care-measures.csv", na = "Not Available")

getBestHospital(d, "MD", "pneumonia")
</code>```

Note that using na = "Not Available" solves the issues of having non-numeric data in the outcome columns.

Some sample output:

```<code>> getBestHospital(d, "MD", "pneumonia")
[1] "GREATER BALTIMORE MEDICAL CENTER"
> getBestHospital(d, "CA", "heart attack")
[1] "GLENDALE ADVENTIST MEDICAL CENTER"
> getBestHospital(d, "FL", "heart failure")
[1] "FLORIDA HOSPITAL HEARTLAND MEDICAL CENTER"
</code>```

Body:
My question concerns using the arrange function from the dplyr package, I saw some posts on it but all of them involved issues with group by and arrange, and just arrange seems to be causing me the problem. It is only sorting some columns of my data correctly.

I don't know if you'll be able to reproduce my problem with out the data, so here is a link to it. It's the file called outcome of care measures.csv, a data frame of hospitals and other health related variables. I wrote a function best that is supposed to return the hospital with the lowest 30 day mortality rating in given input state for a given of 3 health conditions.

I read the data and assign names for when I want to read the relevant columns like this;

best<-function(ST, outcome){
  library(dyplr)
  data<-read.csv("outcome-of-care-measures.csv", na.strings = "Not available", stringsAsFactors = FALSE)
  outcomes<-c("heart attack"=11, "heart failure"=17, "pneumonia"=23)

And then I have 3 if branches that  each finds the hospital with the lowest mortality rate of the input health condition. My first branch functions just fine, and I can't tell it apart from the one that dosen't function. The branch below returns data whose output column is incorrectly sorted.

  if (outcome=="pneumonia"){
    rel_data<-data[, c(2,7,outcomes["pneumonia"])]
    names(rel_data)<-c("hospital", "state", "outcome")
    sorted<- arrange(rel_data, state, outcome, hospital)
    state_sorted<-subset(sorted, state==ST)
    print(state_sorted$hospital[1])}}

When I call best("MD", "pneumonia") it returns the 10th ranked hospital, not the first. It looks like indicies 1-9 were cut off the top of this column and were pasted at the bottom of the column. Any idea what might be going wrong? If I type in "heart attack" in place of "pneumonia", the column seems to be sorted just fine and I get the correct output. I'm 100% sure the only difference is "pneumonia" instead of "heart attack".

Body:
Here's a function that does what you're after, using the tidyverse package ecosystem.

getBestHospital <- function(data, state, outcome) {

  # column numbers for health conditions
  outcomes <- c("heart attack" = 11, "heart failure" = 17, "pneumonia" = 23)

  # get name of column to sort by
  sortCol <- colnames(data)[outcomes[outcome]]

  # return top-ranked hospital for given state and outcome
  data %>%
    dplyr::filter(State == state) %>%
    dplyr::arrange_(paste0("`", sortCol, "`")) %>%
    .$`Hospital Name` %>%
    head(1)

}

And here's how to call it:

library(tidyverse)

d <- readr::read_csv("~/../Downloads/outcome-of-care-measures.csv", na = "Not Available")

getBestHospital(d, "MD", "pneumonia")

Note that using na = "Not Available" solves the issues of having non-numeric data in the outcome columns.

Some sample output:

> getBestHospital(d, "MD", "pneumonia")
[1] "GREATER BALTIMORE MEDICAL CENTER"
> getBestHospital(d, "CA", "heart attack")
[1] "GLENDALE ADVENTIST MEDICAL CENTER"
> getBestHospital(d, "FL", "heart failure")
[1] "FLORIDA HOSPITAL HEARTLAND MEDICAL CENTER"


问:
How to add 2 buttons in Panel to collapse/expand all groups in a grid in ExtJs?
I have a panel and inside of it I have a grid, so my question is how to have 2 buttons to collapse/expand all groups in a grid? I'm still new to ExtJs.

Here's the code that I'm using. It works just fine.

```<code>var store = Ext.create('Ext.data.Store', {
fields: ['name', 'seniority', 'department'],
groupField: 'department',
data: [
    { name: 'Michael Scott', seniority: 7, department: 'Management' },
    { name: 'Dwight Schrute', seniority: 2, department: 'Sales' },
    { name: 'Jim Halpert', seniority: 3, department: 'Sales' },
    { name: 'Kevin Malone', seniority: 4, department: 'Accounting' },
    { name: 'Angela Martin', seniority: 5, department: 'Accounting' }
]
});

Ext.create('Ext.grid.Panel', {
title: 'Employees',
store: store,
columns: [
    { text: 'Name', dataIndex: 'name', flex: 1 },
    { text: 'Seniority', dataIndex: 'seniority', flex: 1 }
],
features: [{ftype:'grouping'}],
renderTo: Ext.getBody()
});
</code>```

Maybe using dockedItem in the Panel will be the way I want it.

答:
For buttons, I guess you would use a toolbar on your grid:</p>

```<code>tbar:[{
    iconCls:'x-fa fa-plus-square',
    handler:function(btn) {
        btn.up('grid').getView().findFeature("grouping").expandAll();
    }
},{
    iconCls:'x-fa fa-minus-square',
    handler:function(btn) {
        btn.up('grid').getView().findFeature("grouping").collapseAll();
    }
}]
</code>```

Body:
I have a panel and inside of it I have a grid, so my question is how to have 2 buttons to collapse/expand all groups in a grid? I'm still new to ExtJs.

Here's the code that I'm using. It works just fine.

var store = Ext.create('Ext.data.Store', {
fields: ['name', 'seniority', 'department'],
groupField: 'department',
data: [
    { name: 'Michael Scott', seniority: 7, department: 'Management' },
    { name: 'Dwight Schrute', seniority: 2, department: 'Sales' },
    { name: 'Jim Halpert', seniority: 3, department: 'Sales' },
    { name: 'Kevin Malone', seniority: 4, department: 'Accounting' },
    { name: 'Angela Martin', seniority: 5, department: 'Accounting' }
]
});

Ext.create('Ext.grid.Panel', {
title: 'Employees',
store: store,
columns: [
    { text: 'Name', dataIndex: 'name', flex: 1 },
    { text: 'Seniority', dataIndex: 'seniority', flex: 1 }
],
features: [{ftype:'grouping'}],
renderTo: Ext.getBody()
});

Maybe using dockedItem in the Panel will be the way I want it.

Body:
For buttons, I guess you would use a toolbar on your grid:

tbar:[{
    iconCls:'x-fa fa-plus-square',
    handler:function(btn) {
        btn.up('grid').getView().findFeature("grouping").expandAll();
    }
},{
    iconCls:'x-fa fa-minus-square',
    handler:function(btn) {
        btn.up('grid').getView().findFeature("grouping").collapseAll();
    }
}]


问:
ngFor group by key and display key for each group
I need to sort out the best way to get my object grouped and then loop those groups in my template.

The data is not sent to me grouped so in my component, I add a key to each array in the object:

```<code>ngOnInit(): void {
    this.getEmailsService.emailsAPI().subscribe(
        data => {
            let firstChar: string
            this.results = data
            this.emails = this.results
            this.emails.forEach(element => {
                firstChar = element.sender_email.charAt(0);
                element.key = firstChar
                console.log(element)
            });
        }
    );
}
</code>```

the resulting dictionary looks like this:

```<code>created: "2017-10-07T01:42:25.110747Z"
email_domain: "domain.com"
has_user_viewed: false
key: "j"
pk: "wGR"
sender_email:"someone@domain.com"
sender_name: null
</code>```

then in my template I have:

```<code><div class="col-sm-6 mb-3" *ngFor="let email of emails | filter : searchText">
</code>```

what would be the best way to handle grouping this by the key value and then also displaying the "master" 'key' for each group? so that you had something like:

```<code>key
->result
->result
->result
key
->result
->result
->result
</code>```

答:
You should keep your Array of objects standard as all the same model in an array without keys. Then if you want to group your array by a specific field this is a handy array transformation that can be passed a field and group the entire array by whatever selector you choose:

```<code>transformArray(array: Array<any>, field) {
    if (array) {
      const groupedObj = array.reduce((prev, cur) => {
        if (!prev[cur[field]]) {
          prev[cur[field]] = [cur];
        } else {
          prev[cur[field]].push(cur);
        }
        return prev;
      }, {});
      return Object.keys(groupedObj).map(key => ({ key, value: groupedObj[key] }));
    }
    return [];
  }
</code>```

This will group your array into objects with a 'key' of whatever you passed into the method and then a nested array called 'value' which has all the objects related to your grouping field.

Body:
I need to sort out the best way to get my object grouped and then loop those groups in my template.

The data is not sent to me grouped so in my component, I add a key to each array in the object:

ngOnInit(): void {
    this.getEmailsService.emailsAPI().subscribe(
        data => {
            let firstChar: string
            this.results = data
            this.emails = this.results
            this.emails.forEach(element => {
                firstChar = element.sender_email.charAt(0);
                element.key = firstChar
                console.log(element)
            });
        }
    );
}

the resulting dictionary looks like this:

created: "2017-10-07T01:42:25.110747Z"
email_domain: "domain.com"
has_user_viewed: false
key: "j"
pk: "wGR"
sender_email:"someone@domain.com"
sender_name: null

then in my template I have:

what would be the best way to handle grouping this by the key value and then also displaying the "master" 'key' for each group? so that you had something like:

key
->result
->result
->result
key
->result
->result
->result

Body:
You should keep your Array of objects standard as all the same model in an array without keys. Then if you want to group your array by a specific field this is a handy array transformation that can be passed a field and group the entire array by whatever selector you choose:

transformArray(array: Array<any>, field) {
    if (array) {
      const groupedObj = array.reduce((prev, cur) => {
        if (!prev[cur[field]]) {
          prev[cur[field]] = [cur];
        } else {
          prev[cur[field]].push(cur);
        }
        return prev;
      }, {});
      return Object.keys(groupedObj).map(key => ({ key, value: groupedObj[key] }));
    }
    return [];
  }

This will group your array into objects with a 'key' of whatever you passed into the method and then a nested array called 'value' which has all the objects related to your grouping field.


问:
How is CIL used to make network / http requests?
I can see a list of CIL instructions here:

https://en.wikipedia.org/wiki/List_of_CIL_instructions

My understanding is that CIL is run in the CLR. However, I can't see how any of these instructions can be used to make a http request (which is obviously possible in the CLR).

None of the codes seem to be about getting outside information.

What am I missing?

答:
Neither does it have instructions for creating files. You have a point in observing that with plain CIL, some tasks simply cannot be done. Opening sockets, writing to disk, drawing on the screen etc. are tasks that can neither be done by a single CIL instruction, nor decomposed fully into these instructions.

x86 assembly code has no instructions to play a sound using the PC Speaker, but it obviously can be done using it (not a complete example):

```<code>mov al, 0x36
out 0x43, al
mov ax, 11931
out 0x40, al
mov al, ah
out 0x40, al
</code>```

Here, the out can be used to write a value to a CPU-specific port. This is a way to communicate with the "outside world". In this case, the CPU runs and interprets the code as best as it can, and it simply understands what the port numbers mean. It may communicate with a serial port, or simply change some voltage somewhere, but at this point, we meet the hardware, so there are no "instructions" here anymore, just electricity.

CIL doesn't have an out opcode, because that would be very unsafe and unverifiable. Instead (this is probably what you are asking for), it has code implementation attributes for methods to specify where to look for the implementation of a particular method.

ImplAttr ::= …
  | cil
  | native
  | runtime

These attributes are mutually exclusive; they specify the type of code the method contains.

cil specifies that the method body consists of cil code. Unless the method is declared abstract, the body of the method shall be provided if cil is used.

native specifies that a method was implemented using native code, tied to a specific processor for
  which it was generated. native methods shall not have a body but instead refer to a native method that
  declares the body. Typically, the PInvoke functionality of the CLI is used to refer to a native method.

runtime specifies that the implementation of the method is automatically provided by the runtime and is primarily used for the methods of delegates.
  (ECMA-335)

Method marked with cil shall have the body consisting of CIL opcodes, native shall indicate that the body is in native instructions located somewhere, and runtime leaves the task of executing the method to the runtime. The call opcode is used to call these methods, as usual.

An example of such a method:

```<code>.method assembly hidebysig static pinvokeimpl("kernel32.dll" autochar lasterr winapi bestfit:off)
    bool  DeleteFile(string path) cil managed preservesig
{
}
</code>```

For some reason, ildasm displays cil managed which is in direct conflict with pinvokeimpl according to ECMA-335. It should be native unmanaged, and I am not sure why ildasm shows this instead.

The mechanisms of calling external methods are P/Invoke, QCall, and FCall. Good information about them can be found here. This is the only legit way defined for a CIL code to interact with the system or runtime.

Body:
Neither does it have instructions for creating files. You have a point in observing that with plain CIL, some tasks simply cannot be done. Opening sockets, writing to disk, drawing on the screen etc. are tasks that can neither be done by a single CIL instruction, nor decomposed fully into these instructions.

x86 assembly code has no instructions to play a sound using the PC Speaker, but it obviously can be done using it (not a complete example):

mov al, 0x36
out 0x43, al
mov ax, 11931
out 0x40, al
mov al, ah
out 0x40, al

Here, the out can be used to write a value to a CPU-specific port. This is a way to communicate with the "outside world". In this case, the CPU runs and interprets the code as best as it can, and it simply understands what the port numbers mean. It may communicate with a serial port, or simply change some voltage somewhere, but at this point, we meet the hardware, so there are no "instructions" here anymore, just electricity.

CIL doesn't have an out opcode, because that would be very unsafe and unverifiable. Instead (this is probably what you are asking for), it has code implementation attributes for methods to specify where to look for the implementation of a particular method.

ImplAttr ::= …
  | cil
  | native
  | runtime

These attributes are mutually exclusive; they specify the type of code the method contains.

cil specifies that the method body consists of cil code. Unless the method is declared abstract, the body of the method shall be provided if cil is used.

native specifies that a method was implemented using native code, tied to a specific processor for
  which it was generated. native methods shall not have a body but instead refer to a native method that
  declares the body. Typically, the PInvoke functionality of the CLI is used to refer to a native method.

runtime specifies that the implementation of the method is automatically provided by the runtime and is primarily used for the methods of delegates.
  (ECMA-335)

Method marked with cil shall have the body consisting of CIL opcodes, native shall indicate that the body is in native instructions located somewhere, and runtime leaves the task of executing the method to the runtime. The call opcode is used to call these methods, as usual.

An example of such a method:

.method assembly hidebysig static pinvokeimpl("kernel32.dll" autochar lasterr winapi bestfit:off)
    bool  DeleteFile(string path) cil managed preservesig
{
}

For some reason, ildasm displays cil managed which is in direct conflict with pinvokeimpl according to ECMA-335. It should be native unmanaged, and I am not sure why ildasm shows this instead.

The mechanisms of calling external methods are P/Invoke, QCall, and FCall. Good information about them can be found here. This is the only legit way defined for a CIL code to interact with the system or runtime.


问:
how does a browser will pick the client Locale value.?
How a browser will get the client machine locale value. I am curious about internal process of how an browser picks up the Operating System locale value of the client machine. (i.e for the Browser/any app that is running on the client OS, which variable value does these apps/browser will fetch and send as the request header info?)</p>

答:
Fascinating question.

Firefox has shown how it gets this according to different Operating Systems here : https://dxr.mozilla.org/mozilla-esr45/source/intl/locale/nsLocaleService.cpp?q=nslocaleservice&redirect_type=direct#69

From that I have created a list for you

Windos XP : GetSystemDefaultLCID()

If QT library is available QLocale::system().name().toUtf8()

Fallback is C++ getenv("LANG") very raw

Mac uses this CFLocaleRef cflocale = CFLocaleCopyCurrent(); see here for more info How to get the locale of the current user in OSX using C++

Also, Androids Chromium browser which was built in c++ makes a call to Java.LocaleUtils which uses Java's Locale.getDefault()

```<code>std::string GetDefaultLocaleString() {
  JNIEnv* env = base::android::AttachCurrentThread();
  ScopedJavaLocalRef<jstring> locale =
      Java_LocaleUtils_getDefaultLocaleString(env);
  return ConvertJavaStringToUTF8(locale);
}
</code>```

https://docs.oracle.com/javase/7/docs/api/java/util/Locale.html#getDefault()

Body:
Fascinating question.

Firefox has shown how it gets this according to different Operating Systems here : https://dxr.mozilla.org/mozilla-esr45/source/intl/locale/nsLocaleService.cpp?q=nslocaleservice&redirect_type=direct#69

From that I have created a list for you

Windos XP : GetSystemDefaultLCID()

If QT library is available QLocale::system().name().toUtf8()

Fallback is C++ getenv("LANG") very raw

Mac uses this CFLocaleRef cflocale = CFLocaleCopyCurrent(); see here for more info How to get the locale of the current user in OSX using C++

Also, Androids Chromium browser which was built in c++ makes a call to Java.LocaleUtils which uses Java's Locale.getDefault()

std::string GetDefaultLocaleString() {
  JNIEnv* env = base::android::AttachCurrentThread();
  ScopedJavaLocalRef<jstring> locale =
      Java_LocaleUtils_getDefaultLocaleString(env);
  return ConvertJavaStringToUTF8(locale);
}

https://docs.oracle.com/javase/7/docs/api/java/util/Locale.html#getDefault()


问:
Best ways to teach a beginner to program?
Original Question

I am currently engaged in teaching my brother to program.  He is a total beginner, but very smart. (And he actually wants to learn).  I've noticed that some of our sessions have gotten bogged down in minor details, and I don't feel I've been very organized. (But the answers to this post have helped a lot.)

What can I do better to teach him effectively?  Is there a logical order that I can use to run through concept by concept?  Are there complexities I should avoid till later?

The language we are working with is Python, but advice in any language is welcome.

How to Help

If you have good ones please add the following in your answer:

Beginner Exercises and Project Ideas

Resources for teaching beginners

Screencasts / blog posts / free e-books

Print books that are good for beginners

Please describe the resource with a link to it so I can take a look.  I want everyone to know that I have definitely been using some of these ideas.  Your submissions will be aggregated in this post.

Online Resources for teaching beginners:

A Gentle Introduction to Programming Using Python

How to Think Like a Computer Scientist

Alice: a 3d program for beginners

Scratch (A system to develop programming skills)

How To Design Programs

Structure and Interpretation of Computer Programs

Learn To Program

Robert Read's How To Be a Programmer

Microsoft XNA

Spawning the Next Generation of Hackers

COMP1917 Higher Computing lectures by Richard Buckland (requires iTunes)

Dive into Python

Python Wikibook

Project Euler - sample problems (mostly mathematical)

pygame - an easy python library for creating games

Invent Your Own Computer Games With Python

Foundations of Programming for a next step beyond basics.

Squeak by Example

Snake Wrangling For Kids (It's not just for kids!)

Recommended Print Books for teaching beginners

Accelerated C++

Python Programming for the Absolute Beginner

Code by Charles Petzold

Python Programming: An Introduction to Computer Science 2nd Edition

答: One I used with my kids is CEEBot. It's not python, but it teaches C / Java style programming in a fun, robot-programming kind of game. It is aimed at 10-15 year olds, but it is a really good one.</p>

LastEditorDisplayName: epatel

OwnerDisplayName: GrizzlyGuru

ContentLicense: CC BY-SA 2.5


问:
How to limit Phusion Passenger memory usage?
Is there a way to limit the amount of memory Phusion Passenger uses when serving up your app?

My host comes by and kills the process after I get a bunch of traffic and so I end up serving up blank pages. Is there anything I can do to say "hey don't use any more than 100Mb and only spawn 3 processes no matter how overloaded the site is"

答:
There is no way to limit the memory usage explicitly (say use <= 100MiB).

But what you can do is limit the number of processes by setting PassengerMaxPoolSize.
Set that and then see how is the memory usage (that depends on the apps you are running).

Also, using Ruby Enterprise Edition may help.

LastEditorDisplayName: John Topley

OwnerDisplayName: piku


问:
Epub page break if element effected move elements to new page together as one
In writing a epub file and i have images that are directly related to certain text i have tried putting them in a div as a block and floating but once in the reader the text moves to a new line i want to make sure if the text is moved to a new page the image follows it as if one element.</p>

```<code><div id="img_graphics2" class="center">
    <img id="graphics2" src="../images/graphics2.jpg" alt="graphics2"/>
    <p class="imgtxt">Above: Is a storage container</p>
</div>

img_graphics2 {
   display: block;
   float:left;
   width: 76%;
   margin-left: 12%;
   margin-right: 12%;:
}
</code>```

答:
Just needed to add css attribute "page-break-inside:avoid" to containing div </p>

```<code><div id="img_graphics2" class="imgtxtdiv">
  <img id="graphics2" src="../images/graphics2.jpg" alt="graphics2"/>
  <p class="imgtxt">Above: Is a storage container</p>
</div>

img_graphics2 {
   display: block;
   float:left;
   width: 76%;
   margin-left: 12%;
   margin-right: 12%;:
}
.imgtxtdiv {
    page-break-inside:avoid
}
</code>```

Body:
In writing a epub file and i have images that are directly related to certain text i have tried putting them in a div as a block and floating but once in the reader the text moves to a new line i want to make sure if the text is moved to a new page the image follows it as if one element.

Above: Is a storage container

img_graphics2 {
   display: block;
   float:left;
   width: 76%;
   margin-left: 12%;
   margin-right: 12%;:
}

Body:
Just needed to add css attribute "page-break-inside:avoid" to containing div

<div id="img_graphics2" class="imgtxtdiv">
  <img id="graphics2" src="../images/graphics2.jpg" alt="graphics2"/>
  <p class="imgtxt">Above: Is a storage container</p>
</div>

img_graphics2 {
   display: block;
   float:left;
   width: 76%;
   margin-left: 12%;
   margin-right: 12%;:
}
.imgtxtdiv {
    page-break-inside:avoid
}


问:
Default selection and reroute on changing selection for <select> in React-Redux
So I am having a few problems with this, but first let me outline what I am trying to do.

When the user first logs in , it takes them to /home which has a list of projects. Clicking on one of the projects will take them to /project/84 if 84 is the number of that project. When they are routed to that URL there is a <select> with a list of projects (that were also listed on /home).

This is what should happen:

1) The <select> should have a value equal to the name of the project selected. For example, if project 84 is called Project 84, it should already be displayed in the <select> even if there are 20 other other projects before and after it.

2) When the user selects a new <option> in <select>, it should automatically send a GET to the server to retrieve the information of the project they selected.

So here is what I have so far:

```<code>import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';

class SelectProject extends Component {

    getProject() {
        // console.log('Working');
        this.setState({
            value: event.target.value
        });
    }

    renderCurrentProjectName() {
        const { project_list } = this.props;

        if (!Project_list) {
            return <div>Loading...</div>;
        }

        return _(this.props.Project_list)
            .filter(c => c.project_id == this.props.Project_id)
            .map('project')
            .value();
    }

    renderProjectSelect() {
        return _.map(this.props.project_list, s => {
            return (
                <option key={s.project_id}>{s.project}</option>
            );
        });
    }

    render() {

        return (
            <div className='panel panel-default'>
                <div className='panel-heading'>
                    <h4><strong>{this.renderCurrentProjectName()}</strong></h4>
                </div>

                <div className='panel-body'>
                    <select className='form-control' onChange={this.getProject()} value={this.renderCurrentProjectName()}>
                        {this.renderProjectSelect()}
                    </select>
                </div>
            </div>
        );
    }
}

function mapStateToProps(state) {
    return {
        project_id: state.documents.project_id,
        project_list: state.documents.project_list
    }
}

export default connect(mapStateToProps, null)(SelectProject);
</code>```

This just generates 1000 errors saying: Cannot update during an existing state transition (such as within 'render' or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to 'componentWillMount'.

This is caused by the this.setState({ value: even.target.value }) so when I remove it I just get: Warning: Failed form propType: You provided a 'value' prop to a form field without an 'onChange' handler. This will render a read-only field. If the field should be mutable use 'defaultValue'. Otherwise, set either 'onChange' or 'readOnly'. Check the render method of 'SelectProduct'.

This does accomplish 1) though by selecting the name of the project in the <select>; however, you can't select anything else (haven't even gotten as sending the GET).

defaultValue doesn't seem to do anything, at least it doesn't select the correct <option>.

Also have done the following which resulted in the same errors and behavior (i.e. it selects the correct <option>, but won't let you select anything else):

```<code>...
class SelectProject extends Component {

    constructor(props) {
        super(props);

        this.state = {
            value: this.renderCurrentProductName()
        };
    }

    getProject() {
        // console.log('Working');
        this.setState({
            value: event.target.value
        });
    }

                ...
                    <select className='form-control' onChange={this.getProject()} value={this.state.value}>
                        {this.renderProjectSelect()}
                    </select>
                ...
</code>```

These are some of the SO questions I have been referencing.

OnChange event using React JS for drop down

ReactJS: Select with default value from props without onChange event?

答:
Can you say why you are calling the functions in the on change?
Can you try passing the event to the function:</p>

```<code>class SelectProject extends Component {

constructor(props) {
    super(props);

    this.state = {
        value: this.renderCurrentProductName()
    };
}

getProject(event) {
    // console.log('Working');
    this.setState({
        value: event.target.value
    });
}

            ...
                <select className='form-control' onChange={this.getProject} value={this.state.value}>
                    {this.renderProjectSelect}
                </select>
            ...
</code>```

Body:
So I am having a few problems with this, but first let me outline what I am trying to do.

When the user first logs in , it takes them to /home which has a list of projects. Clicking on one of the projects will take them to /project/84 if 84 is the number of that project. When they are routed to that URL there is a <select> with a list of projects (that were also listed on /home).

This is what should happen:

1) The <select> should have a value equal to the name of the project selected. For example, if project 84 is called Project 84, it should already be displayed in the <select> even if there are 20 other other projects before and after it.

2) When the user selects a new <option> in <select>, it should automatically send a GET to the server to retrieve the information of the project they selected.

So here is what I have so far:

import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';

class SelectProject extends Component {

    getProject() {
        // console.log('Working');
        this.setState({
            value: event.target.value
        });
    }

    renderCurrentProjectName() {
        const { project_list } = this.props;

        if (!Project_list) {
            return
Loading...
;
        }

        return _(this.props.Project_list)
            .filter(c => c.project_id == this.props.Project_id)
            .map('project')
            .value();
    }

    renderProjectSelect() {
        return _.map(this.props.project_list, s => {
            return (
                <option key={s.project_id}>{s.project}</option>
            );
        });
    }

    render() {

        return (

{this.renderCurrentProjectName()}

                    <select className='form-control' onChange={this.getProject()} value={this.renderCurrentProjectName()}>
                        {this.renderProjectSelect()}
                    </select>

        );
    }
}

function mapStateToProps(state) {
    return {
        project_id: state.documents.project_id,
        project_list: state.documents.project_list
    }
}

export default connect(mapStateToProps, null)(SelectProject);

This just generates 1000 errors saying: Cannot update during an existing state transition (such as within 'render' or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to 'componentWillMount'.

This is caused by the this.setState({ value: even.target.value }) so when I remove it I just get: Warning: Failed form propType: You provided a 'value' prop to a form field without an 'onChange' handler. This will render a read-only field. If the field should be mutable use 'defaultValue'. Otherwise, set either 'onChange' or 'readOnly'. Check the render method of 'SelectProduct'.

This does accomplish 1) though by selecting the name of the project in the <select>; however, you can't select anything else (haven't even gotten as sending the GET).

defaultValue doesn't seem to do anything, at least it doesn't select the correct <option>.

Also have done the following which resulted in the same errors and behavior (i.e. it selects the correct <option>, but won't let you select anything else):

...
class SelectProject extends Component {

    constructor(props) {
        super(props);

        this.state = {
            value: this.renderCurrentProductName()
        };
    }

    getProject() {
        // console.log('Working');
        this.setState({
            value: event.target.value
        });
    }

                ...
                    <select className='form-control' onChange={this.getProject()} value={this.state.value}>
                        {this.renderProjectSelect()}
                    </select>
                ...

These are some of the SO questions I have been referencing.

OnChange event using React JS for drop down

ReactJS: Select with default value from props without onChange event?

Body:
Can you say why you are calling the functions in the on change?
Can you try passing the event to the function:

class SelectProject extends Component {

constructor(props) {
    super(props);

    this.state = {
        value: this.renderCurrentProductName()
    };
}

getProject(event) {
    // console.log('Working');
    this.setState({
        value: event.target.value
    });
}

            ...
                <select className='form-control' onChange={this.getProject} value={this.state.value}>
                    {this.renderProjectSelect}
                </select>
            ...


问:
Python, Pandas, inverted expanding window
Lets consider the following Series:

```<code>s=pd.Series(data=[100, 110, 120, 150, 110, 90, 80, 70, 90, 95])
</code>```

I iterate over each item and perform the following operation:

```<code>for i in range(len(s)):
    m=max(s[i]-s[i:])
</code>```

Basically comparing each item with all items that follow, and retrieving the max.

I can do that with:

```<code>r=[]
for i in range(len(s)):
    m=max(s[i]-s[i:])
    r.append(m)

result=pd.Series(r)
</code>```

But I had the feeling that this would be something that a rolling window could do? I am trying to make my code a bit cleaner and was just starting reading and exploring about the rolling function, but i cannot yet but my finger on it. This idea seems like a inverted expanding function (i.e. it takes less and less data as it goes down the data)?

If someone has ideas about how to reformat the code using rolling / expanding windows, please let me know.

答:
Reverse the initial series using [::-1], take the cumulative min value, then reverse again.  Subtract the resulting series from s.

```<code>>>> s.sub(s[::-1].cummin()[::-1])

0    30
1    40
2    50
3    80
4    40
5    20
6    10
7     0
8     0
9     0
dtype: int64
</code>```

If the index is monotonically increasing, one can be more explicit:

```<code>s.sub(s.sort_index(ascending=False).cummin().sort_index())
</code>```

Body:
Lets consider the following Series:

s=pd.Series(data=[100, 110, 120, 150, 110, 90, 80, 70, 90, 95])

I iterate over each item and perform the following operation:

for i in range(len(s)):
    m=max(s[i]-s[i:])

Basically comparing each item with all items that follow, and retrieving the max.

I can do that with:

r=[]
for i in range(len(s)):
    m=max(s[i]-s[i:])
    r.append(m)

result=pd.Series(r)

But I had the feeling that this would be something that a rolling window could do? I am trying to make my code a bit cleaner and was just starting reading and exploring about the rolling function, but i cannot yet but my finger on it. This idea seems like a inverted expanding function (i.e. it takes less and less data as it goes down the data)?

If someone has ideas about how to reformat the code using rolling / expanding windows, please let me know.

Body:
Reverse the initial series using [::-1], take the cumulative min value, then reverse again.  Subtract the resulting series from s.

>>> s.sub(s[::-1].cummin()[::-1])

0    30
1    40
2    50
3    80
4    40
5    20
6    10
7     0
8     0
9     0
dtype: int64

If the index is monotonically increasing, one can be more explicit:

s.sub(s.sort_index(ascending=False).cummin().sort_index())


问:
Looking to pinpoint the what's wrong in my SQL query
(THIS IS NOT A DUPLICATE.  READ CAREFULLY!)
I have two tables:

ZIPCodes- contains all the zipcodes of the USA with latitude and longitude.

usersearch_answers- has a zipcode column with the zipcodes where users live.

I want to have two variables: zipcode that the user can specify, and a distance in miles that a user can also specify.

The results should return anyone within the radius of the zipcode that the user specified.

Now, the query below works as expected only when there's at least one person in the users table with the zipcode that was specified.

Nothing returns if the zipcode that entered is not contained in the table, even if there are nearby zipcodes.

Can someone please pinpoint for me in this code where the problem is?  What do I need to do in order to get the rest of the zipcodes working? Any help is greatly appreciated.  Thanks in advance.

```<code>$data_query = mysqli_query($conn, "
SELECT ZIPCodes.zipcode, usersearch_answers.username,
       (3959 * acos(cos(radians(ZIPCodes.latitude)) *
       cos(radians(center.latitude)) *
       cos(radians(ZIPCodes.longitude ) -
       radians(center.longitude)) +
       sin(radians(ZIPCodes.latitude)) *
       sin(radians(center.latitude)))) AS distance
FROM
(
    (
        SELECT usersearch_answers.username,
            usersearch_answers.zipcode,
            ZIPCodes.latitude,
            ZIPCodes.longitude
        FROM
        (
            usersearch_answers JOIN ZIPCodes ON usersearch_answers.zipcode = ZIPCodes.zipcode
        )
        WHERE (ZIPCodes.zipcode='33133')
    ) center, ZIPCodes
) INNER JOIN usersearch_answers ON ZIPCodes.zipcode = usersearch_answers.zipcode
WHERE (usersearch_answers.username <> '$userLoggedIn')
HAVING (distance < 5000)
ORDER BY distance");
</code>```

答:
Your issue is this line:

```<code>usersearch_answers JOIN ZIPCodes ON usersearch_answers.zipcode = ZIPCodes.zipcode
</code>```

The keyword JOIN by itself (no LEFT or RIGHT) implies that this is an INNER JOIN.  So in order for there to be a record returned then it has to include zip AND the user.

If you want it to return even if there is no user then change that line to:

```<code>usersearch_answers RIGHT JOIN ZIPCodes ON usersearch_answers.zipcode = ZIPCodes.zipcode
</code>```

Full query:

```<code>$data_query = mysqli_query($conn, "
SELECT ZIPCodes.zipcode, usersearch_answers.username,
       (3959 * acos(cos(radians(ZIPCodes.latitude)) *
       cos(radians(center.latitude)) *
       cos(radians(ZIPCodes.longitude ) -
       radians(center.longitude)) +
       sin(radians(ZIPCodes.latitude)) *
       sin(radians(center.latitude)))) AS distance
FROM
(
    (
        SELECT usersearch_answers.username,
            ZIPCodes.zipcode,
            ZIPCodes.latitude,
            ZIPCodes.longitude
        FROM
        (
            usersearch_answers RIGHT JOIN ZIPCodes ON usersearch_answers.zipcode = ZIPCodes.zipcode
        )
        WHERE (ZIPCodes.zipcode='33133')
    ) center, ZIPCodes
) INNER JOIN usersearch_answers ON ZIPCodes.zipcode = usersearch_answers.zipcode
WHERE (usersearch_answers.username <> '$userLoggedIn')
HAVING (distance < 5000)
ORDER BY distance");
</code>```

Body:
(THIS IS NOT A DUPLICATE.  READ CAREFULLY!)
I have two tables:

ZIPCodes- contains all the zipcodes of the USA with latitude and longitude.

usersearch_answers- has a zipcode column with the zipcodes where users live.

I want to have two variables: zipcode that the user can specify, and a distance in miles that a user can also specify.

The results should return anyone within the radius of the zipcode that the user specified.

Now, the query below works as expected only when there's at least one person in the users table with the zipcode that was specified.

Nothing returns if the zipcode that entered is not contained in the table, even if there are nearby zipcodes.

Can someone please pinpoint for me in this code where the problem is?  What do I need to do in order to get the rest of the zipcodes working? Any help is greatly appreciated.  Thanks in advance.

$data_query = mysqli_query($conn, "
SELECT ZIPCodes.zipcode, usersearch_answers.username,
       (3959 * acos(cos(radians(ZIPCodes.latitude)) *
       cos(radians(center.latitude)) *
       cos(radians(ZIPCodes.longitude ) -
       radians(center.longitude)) +
       sin(radians(ZIPCodes.latitude)) *
       sin(radians(center.latitude)))) AS distance
FROM
(
    (
        SELECT usersearch_answers.username,
            usersearch_answers.zipcode,
            ZIPCodes.latitude,
            ZIPCodes.longitude
        FROM
        (
            usersearch_answers JOIN ZIPCodes ON usersearch_answers.zipcode = ZIPCodes.zipcode
        )
        WHERE (ZIPCodes.zipcode='33133')
    ) center, ZIPCodes
) INNER JOIN usersearch_answers ON ZIPCodes.zipcode = usersearch_answers.zipcode
WHERE (usersearch_answers.username <> '$userLoggedIn')
HAVING (distance < 5000)
ORDER BY distance");

Body:
Your issue is this line:

usersearch_answers JOIN ZIPCodes ON usersearch_answers.zipcode = ZIPCodes.zipcode

The keyword JOIN by itself (no LEFT or RIGHT) implies that this is an INNER JOIN.  So in order for there to be a record returned then it has to include zip AND the user.

If you want it to return even if there is no user then change that line to:

usersearch_answers RIGHT JOIN ZIPCodes ON usersearch_answers.zipcode = ZIPCodes.zipcode

Full query:

$data_query = mysqli_query($conn, "
SELECT ZIPCodes.zipcode, usersearch_answers.username,
       (3959 * acos(cos(radians(ZIPCodes.latitude)) *
       cos(radians(center.latitude)) *
       cos(radians(ZIPCodes.longitude ) -
       radians(center.longitude)) +
       sin(radians(ZIPCodes.latitude)) *
       sin(radians(center.latitude)))) AS distance
FROM
(
    (
        SELECT usersearch_answers.username,
            ZIPCodes.zipcode,
            ZIPCodes.latitude,
            ZIPCodes.longitude
        FROM
        (
            usersearch_answers RIGHT JOIN ZIPCodes ON usersearch_answers.zipcode = ZIPCodes.zipcode
        )
        WHERE (ZIPCodes.zipcode='33133')
    ) center, ZIPCodes
) INNER JOIN usersearch_answers ON ZIPCodes.zipcode = usersearch_answers.zipcode
WHERE (usersearch_answers.username <> '$userLoggedIn')
HAVING (distance < 5000)
ORDER BY distance");


问:
Get inventory list from PayPal Buy Now Button
I would like to integrate a PayPal Button into my website which has an inventory configured via PayPal. So far so good. But as soon as every item has been sold the button should switch to an "SOLD OUT" info. Is it possible to get the inventory amount via the PayPal API? And if yes....how?

Any ideas or experiences?

Thanks

答:
Yes, you can track your inventory with PayPal button. Check the link below for the steps.

https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/step_2/


问:
ASP.NET Identity 2 with Google login... Logout doesn't work
I want to be able to logout the currently logged in user, especially in the use case of current user closes browser, opens a new browser, heads to the login page.

Here is what I've been trying...

```<code>private ActionResult DoLogout()/// check this out https://dzone.com/articles/catching-systemwebowin-cookie the sytem.web cookie monster
{
    var AuthenticationManager = HttpContext.GetOwinContext().Authentication;
    AuthenticationManager.SignOut();
    AuthenticationManager.SignOut( DefaultAuthenticationTypes.ApplicationCookie );
    Session.Abandon();

    var user = UserManager.FindByName( User.Identity.Name );

    if (user != null)
    {
        UserManager.UpdateSecurityStamp( user.Id ); // remove the old cookie so it can't be reused to re-log in - EWB
    }

     AuthenticationManager.SignOut();

    ClearCookies();

    Request.GetOwinContext().Authentication.SignOut( DefaultAuthenticationTypes.ApplicationCookie );// https://stackoverflow.com/questions/28999318/owin-authentication-signout-doesnt-seem-to-remove-the-cookie - stralos s answer
                                                                                // https://stackoverflow.com/questions/43675904/asp-net-identity-2-logging-out-other-sessions-using-security-stamp-after-pa

    AuthenticationManager.SignOut( DefaultAuthenticationTypes.ApplicationCookie );

    return Redirect("https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=https://"+ Url.Action( "Index", "Home", new { target = "_blank" } ) ); //https://stackoverflow.com/questions/27515518/asp-net-identity-external-login-wont-log-out - f belihocine answer

  }
</code>```

but when I log back in this code gets called

```<code>var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

if (loginInfo == null)
{
    return RedirectToAction("LogOut");    // <--- here
}
</code>```

Because the user is in a broken state, because I think ASP.net is logged out, but Google is still logged in....

Any help is appreciated

答: You need to call Google API to get this done , please see this for more information ASP.net identity - external login - won't log out</p>

Body:
I want to be able to logout the currently logged in user, especially in the use case of current user closes browser, opens a new browser, heads to the login page.

Here is what I've been trying...

private ActionResult DoLogout()/// check this out https://dzone.com/articles/catching-systemwebowin-cookie the sytem.web cookie monster
{
    var AuthenticationManager = HttpContext.GetOwinContext().Authentication;
    AuthenticationManager.SignOut();
    AuthenticationManager.SignOut( DefaultAuthenticationTypes.ApplicationCookie );
    Session.Abandon();

    var user = UserManager.FindByName( User.Identity.Name );

    if (user != null)
    {
        UserManager.UpdateSecurityStamp( user.Id ); // remove the old cookie so it can't be reused to re-log in - EWB
    }

     AuthenticationManager.SignOut();

    ClearCookies();

    Request.GetOwinContext().Authentication.SignOut( DefaultAuthenticationTypes.ApplicationCookie );// https://stackoverflow.com/questions/28999318/owin-authentication-signout-doesnt-seem-to-remove-the-cookie - stralos s answer
                                                                                // https://stackoverflow.com/questions/43675904/asp-net-identity-2-logging-out-other-sessions-using-security-stamp-after-pa

    AuthenticationManager.SignOut( DefaultAuthenticationTypes.ApplicationCookie );

    return Redirect("https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=https://"+ Url.Action( "Index", "Home", new { target = "_blank" } ) ); //https://stackoverflow.com/questions/27515518/asp-net-identity-external-login-wont-log-out - f belihocine answer

  }

but when I log back in this code gets called

var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

if (loginInfo == null)
{
    return RedirectToAction("LogOut");    // <--- here
}

Because the user is in a broken state, because I think ASP.net is logged out, but Google is still logged in....

Any help is appreciated


问:
get all tuples with maximum second value
How to fix the number of occurrence in a list of tuples and return an item with max value.

```<code>        given = [('a',2),('b',3),('c',5),('a',3),('c',5)]

        expected = [('c',5),('a',3),('b',3)]
</code>```

How do you do this without doing anything to complex.

答:
Here is one way:

```<code>given = [('a',2),('b',3),('c',5),('a',3),('c',5)]
expected = dict(sorted(given)).items()
</code>```

Explanation

sorted(...)

When you sort the list, all the items with a low value (second element) are moved to the front of the list.

dict(...)

When you convert the sorted list to a dict, the lower values are replaced by the higher values which are closer to the end of the list.

Body:
How to fix the number of occurrence in a list of tuples and return an item with max value.

        given = [('a',2),('b',3),('c',5),('a',3),('c',5)]

        expected = [('c',5),('a',3),('b',3)]

How do you do this without doing anything to complex.

Body:
Here is one way:

given = [('a',2),('b',3),('c',5),('a',3),('c',5)]
expected = dict(sorted(given)).items()

Explanation

sorted(...)

When you sort the list, all the items with a low value (second element) are moved to the front of the list.

dict(...)

When you convert the sorted list to a dict, the lower values are replaced by the higher values which are closer to the end of the list.


问:
Unsafe connection after changing rules in .htaccess
I'm trying to set rules to change the URL from page contact.php to contact but the website now show unsafe connection in the main page but not on other pages.

This is the rule i used:

```<code>RewriteRule ^contact(.[A-Za-z0-9-]+)/?$ contact.php?=$1
</code>```

While i still haven't set this clean URL yet, it's strange the website isn't using a secure connection anymore.

The link is here. Even if i clear the rule it is still unsecure and even if you write https:// in the URL, after navigating through other pages and back to the main page again it is not secure anymore.

Can you give me insight from this?

答:
This may not be answering you question directly, but when I need to change a url i use javascript. You can try...

```<code>var obj = { Title: 'Contact Us', Url: '/contact'};
history.pushState(obj, obj.Title, obj.Url);
</code>```

This would allow the browser to see the page as intended from the server and just show the url.

Body:
I'm trying to set rules to change the URL from page contact.php to contact but the website now show unsafe connection in the main page but not on other pages.

This is the rule i used:

RewriteRule ^contact(.[A-Za-z0-9-]+)/?$ contact.php?=$1

While i still haven't set this clean URL yet, it's strange the website isn't using a secure connection anymore.

The link is here. Even if i clear the rule it is still unsecure and even if you write https:// in the URL, after navigating through other pages and back to the main page again it is not secure anymore.

Can you give me insight from this?

Body:
This may not be answering you question directly, but when I need to change a url i use javascript. You can try...

var obj = { Title: 'Contact Us', Url: '/contact'};
history.pushState(obj, obj.Title, obj.Url);

This would allow the browser to see the page as intended from the server and just show the url.


问:
Is there standard way to get numerical consistency in Julia
```<code>└─╼ julia
 Version 0.6.0 (2017-06-19 13:05 UTC)
 julia> 1.0 + 0.1 - 1.0 - 0.1 == 0
  false
 julia> 1.0 + 0.1 - 1.0 - 0.1
  8.326672684688674e-17
</code>```

i understand that decimals like 0.1 cannot be represented exactly in binary based point without some additional effort e.g.

```<code>julia> 1//10
 1//10
julia> 1 + 1//10
 11//10
julia> 1 + 1//10 - 1
 1//10
julia> 1 + 1//10 - 1 - 1//10
 0//1
julia> 1 + 1//10 - 1 - 1//10 == 0
 true
</code>```

or going purely symbolic.

there are several rounding options:
    julia> Round
    RoundDown            RoundNearest          RoundNearestTiesUp    RoundUp
    RoundFromZero        RoundNearestTiesAway  RoundToZero     RoundingMode

Without launching into a protracted discussion of numerical stability, does Julia have a recommended style?

thx

答:
Also there is sum_kbn which may be all you need for your application:

```<code>julia> sum([1.0, 0.1, - 1.0, - 0.1])
8.326672684688674e-17

julia> sum_kbn([1.0, 0.1, - 1.0, - 0.1])
0.0

help?> sum_kbn
search: sum_kbn cumsum_kbn

  sum_kbn(A)

  Returns the sum of all elements of A, using the Kahan-Babuska-Neumaier compensated summation algorithm for additional accuracy.
</code>```

Body:
└─╼ julia
 Version 0.6.0 (2017-06-19 13:05 UTC)
 julia> 1.0 + 0.1 - 1.0 - 0.1 == 0
  false
 julia> 1.0 + 0.1 - 1.0 - 0.1
  8.326672684688674e-17

i understand that decimals like 0.1 cannot be represented exactly in binary based point without some additional effort e.g.

julia> 1//10
 1//10
julia> 1 + 1//10
 11//10
julia> 1 + 1//10 - 1
 1//10
julia> 1 + 1//10 - 1 - 1//10
 0//1
julia> 1 + 1//10 - 1 - 1//10 == 0
 true

or going purely symbolic.

there are several rounding options:
    julia> Round
    RoundDown            RoundNearest          RoundNearestTiesUp    RoundUp
    RoundFromZero        RoundNearestTiesAway  RoundToZero     RoundingMode

Without launching into a protracted discussion of numerical stability, does Julia have a recommended style?

thx

Body:
Also there is sum_kbn which may be all you need for your application:

julia> sum([1.0, 0.1, - 1.0, - 0.1])
8.326672684688674e-17

julia> sum_kbn([1.0, 0.1, - 1.0, - 0.1])
0.0

help?> sum_kbn
search: sum_kbn cumsum_kbn

  sum_kbn(A)

  Returns the sum of all elements of A, using the Kahan-Babuska-Neumaier compensated summation algorithm for additional accuracy.


问:
Reject String If Contains Any Non-Alpha Numeric Character
I am writing a program and want the program to not loop and request another search pattern if the search pattern (word) contains any non alpha numeric characters.

I have setup a Boolean word to false and an if statement to change the Boolean to true if the word contains letters or numbers. Then another if statement to allow the program to execute if the Boolean is true.

My logic must be off because it is still executing through the search pattern if I simply enter "/". The search pattern cannot contain any non alpha numeric characters to include spaces. I am trying to use Regex to solve this problem.

Sample problematic output:

```<code>Please enter a search pattern: /
Line number 1
this.a 2test/austin
            ^

Line number 8
ra charity Charityis 4 times a day/a.a-A
                                  ^
</code>```

Here is my applicable code:

```<code>while (again) {

   boolean found = false;
   System.out.printf("%n%s", "Please enter a search pattern: ", "%n");
   String wordToSearch = input.next();

   if (wordToSearch.equals("EINPUT")) {
      System.out.printf("%s", "Bye!");
      System.exit(0);
   }

   Pattern p = Pattern.compile("\\W*");
   Matcher m = p.matcher(wordToSearch);

   if (m.find())
      found = true;

   String data;
   int lineCount = 1;

   if (found = true) {
      try (FileInputStream fis =
                 new FileInputStream(this.inputPath.getPath())) {
         File file1 = this.inputPath;
         byte[] buffer2 = new byte[fis.available()];
         fis.read(buffer2);
         data = new String(buffer2);
         Scanner in = new Scanner(data).useDelimiter("\\\\|[^a-zA-z0-9]+");
         while (in.hasNextLine()) {

            String line = in.nextLine();

            Pattern pattern = Pattern.compile("\\b" + wordToSearch + "\\b");
            Matcher matcher = pattern.matcher(line);

            if (matcher.find()) {
               System.out.println("Line number " + lineCount);
               String stringToFile = f.findWords(line, wordToSearch);
               System.out.println();
            }
            lineCount++;
         }
      }
   }
}
</code>```

答:
Create a separate method to call the String you are searching through:

```<code>public boolean isAlphanumeric(String str)
{
    char[] charArray = str.toCharArray();
    for(char c:charArray)
    {
        if (!Character.isLetterOrDigit(c))
            return false;
    }
    return true;
}
</code>```

Then, add the following if statement to the above code prior to the second try statement.

```<code>if (isAlphanumeric(wordToSearch) == true)
</code>```

Body:
I am writing a program and want the program to not loop and request another search pattern if the search pattern (word) contains any non alpha numeric characters.

I have setup a Boolean word to false and an if statement to change the Boolean to true if the word contains letters or numbers. Then another if statement to allow the program to execute if the Boolean is true.

My logic must be off because it is still executing through the search pattern if I simply enter "/". The search pattern cannot contain any non alpha numeric characters to include spaces. I am trying to use Regex to solve this problem.

Sample problematic output:

Please enter a search pattern: /
Line number 1
this.a 2test/austin
            ^

Line number 8
ra charity Charityis 4 times a day/a.a-A
                                  ^

Here is my applicable code:

while (again) {

   boolean found = false;
   System.out.printf("%n%s", "Please enter a search pattern: ", "%n");
   String wordToSearch = input.next();

   if (wordToSearch.equals("EINPUT")) {
      System.out.printf("%s", "Bye!");
      System.exit(0);
   }

   Pattern p = Pattern.compile("\\W*");
   Matcher m = p.matcher(wordToSearch);

   if (m.find())
      found = true;

   String data;
   int lineCount = 1;

   if (found = true) {
      try (FileInputStream fis =
                 new FileInputStream(this.inputPath.getPath())) {
         File file1 = this.inputPath;
         byte[] buffer2 = new byte[fis.available()];
         fis.read(buffer2);
         data = new String(buffer2);
         Scanner in = new Scanner(data).useDelimiter("\\\\|[^a-zA-z0-9]+");
         while (in.hasNextLine()) {

            String line = in.nextLine();

            Pattern pattern = Pattern.compile("\\b" + wordToSearch + "\\b");
            Matcher matcher = pattern.matcher(line);

            if (matcher.find()) {
               System.out.println("Line number " + lineCount);
               String stringToFile = f.findWords(line, wordToSearch);
               System.out.println();
            }
            lineCount++;
         }
      }
   }
}

Body:
Create a separate method to call the String you are searching through:

public boolean isAlphanumeric(String str)
{
    char[] charArray = str.toCharArray();
    for(char c:charArray)
    {
        if (!Character.isLetterOrDigit(c))
            return false;
    }
    return true;
}

Then, add the following if statement to the above code prior to the second try statement.

if (isAlphanumeric(wordToSearch) == true)


问:
Are variable types permanent in Statically Typed Languages?
My understanding is that variable types are "checked" before run-time for statically typed languages.

I take this to mean that a var of type int can't ever be type string? Does this mean variable type can't change (within the same scope) throughout the program (in a statically typed language)?

Somebody mentioned "variable shadowing" but I'm pretty sure that only applies in different scopes.

```<code>var i = 'hi';
function foo() {
    var i = 1;
}
</code>```

My understanding of var shadowing is that i in the global scope is a different variable than i in the foo function scope and therefore their types are permanent and unrelated (in a static language, which JS is not). Is that right?

答:
Somebody mentioned "variable shadowing" but I'm pretty sure that only applies in different scopes.

It depends on your definition of "scope",  Rust, for example, allows the kind of shadowing that you're talking about, even within a single block:

```<code>fn main() {
    let a: str = "hello";
    let a: i32 = 3;
}
</code>```

It could be argued that the declaration of a shadow variable implicitly ends the scope of the previous variable.  But to quote from the Rust book:

Note that shadowing a name does not alter or destroy the value it was bound to, and the value will continue to exist until it goes out of scope, even if it is no longer accessible by any means.

Body:
My understanding is that variable types are "checked" before run-time for statically typed languages.

I take this to mean that a var of type int can't ever be type string? Does this mean variable type can't change (within the same scope) throughout the program (in a statically typed language)?

Somebody mentioned "variable shadowing" but I'm pretty sure that only applies in different scopes.

var i = 'hi';
function foo() {
    var i = 1;
}

My understanding of var shadowing is that i in the global scope is a different variable than i in the foo function scope and therefore their types are permanent and unrelated (in a static language, which JS is not). Is that right?

Body:
Somebody mentioned "variable shadowing" but I'm pretty sure that only applies in different scopes.

It depends on your definition of "scope",  Rust, for example, allows the kind of shadowing that you're talking about, even within a single block:

fn main() {
    let a: str = "hello";
    let a: i32 = 3;
}

It could be argued that the declaration of a shadow variable implicitly ends the scope of the previous variable.  But to quote from the Rust book:

Note that shadowing a name does not alter or destroy the value it was bound to, and the value will continue to exist until it goes out of scope, even if it is no longer accessible by any means.


问:
Save an std::vector<int> to file
I noticed, that when using:

```<code>std::vector<int> v(100000);
...
std::ofstream outfile("outfile.dat", std::ios::out | std::ofstream::binary);
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(outfile));
outfile.close();
</code>```

my std::vector<int> is not serialized as raw bytes data (4 bytes per int) but as string, i.e. the string representation of each integer is saved to disk, which I don't want.

How to save a std::vector<int> as binary data?

(Note: I'd like to learn it with standard C++03, before learning new methods for it).

答:
std::ostream_iterator writes values to the stream using its operator<<. Elements are written as if you used outfile << value for each member of the vector, which means converting values to text.

So, what you want to do instead is define a class that serializes itself to the stream in a binary representation, eg:

```<code>std::copy(v.begin(), v.end(), std::ostream_iterator<BinaryInt>(outfile));
                                                    ^^^^^^^^^
</code>```

Now you have to define the BinaryInt type so that it can be constructed by an int value but serialize itself via operator<< appropriately:

```<code>struct BinaryInt
{
    int value;
    BinaryValue(int v): value(v) {}
    friend std::ostream& operator<<(std::ostream& str, BinaryInt const& bi)
    {
        // convert bi.value into a binary representation.
        // Note C++ does not define a specific size for int.
        // Nor does it define an endianess.
        // Nor does it define a specific representation.
        // So to be cross platform/OS/compiler you will need to define these
        // and convert the integer into this representation.
        //
        // return str.write(<data>, <size>);
        //
        // If this is just a test the following would work
        // but is extremely brittle for the long term.

        return str.write(reinterpret_cast<const char*>(&bi.value), sizeof(bi.value));
    }
};
</code>```

Title: Save an std::vector<int> to file

Body:
I noticed, that when using:

std::vector<int> v(100000);
...
std::ofstream outfile("outfile.dat", std::ios::out | std::ofstream::binary);
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(outfile));
outfile.close();

my std::vector<int> is not serialized as raw bytes data (4 bytes per int) but as string, i.e. the string representation of each integer is saved to disk, which I don't want.

How to save a std::vector<int> as binary data?

(Note: I'd like to learn it with standard C++03, before learning new methods for it).

Body:
std::ostream_iterator writes values to the stream using its operator<<. Elements are written as if you used outfile << value for each member of the vector, which means converting values to text.

So, what you want to do instead is define a class that serializes itself to the stream in a binary representation, eg:

std::copy(v.begin(), v.end(), std::ostream_iterator<BinaryInt>(outfile));
                                                    ^^^^^^^^^

Now you have to define the BinaryInt type so that it can be constructed by an int value but serialize itself via operator<< appropriately:

struct BinaryInt
{
    int value;
    BinaryValue(int v): value(v) {}
    friend std::ostream& operator<<(std::ostream& str, BinaryInt const& bi)
    {
        // convert bi.value into a binary representation.
        // Note C++ does not define a specific size for int.
        // Nor does it define an endianess.
        // Nor does it define a specific representation.
        // So to be cross platform/OS/compiler you will need to define these
        // and convert the integer into this representation.
        //
        // return str.write(<data>, <size>);
        //
        // If this is just a test the following would work
        // but is extremely brittle for the long term.

        return str.write(reinterpret_cast<const char*>(&bi.value), sizeof(bi.value));
    }
};


问:
How do I set transaction isolation level in Laravel 5.5?
In laravel 5.5 with MySQL I use \Illuminate\Support\Facades\DB to create transactions this way:

```<code>DB::transaction(function() {
    ...
});
</code>```

What is the isolation level for such transaction and is there a way to set it explicitly?

答:
The default in SqlLite is

```<code>'BEGIN IMMEDIATE TRANSACTION';
</code>```

The default in MySQL is

```<code>'SET TRANSACTION ISOLATION LEVEL READ COMMITTED';
</code>```

You can set it yourself by doing something like this

```<code>$pdo = DB::connection()->getPdo();
$pdo->exec('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
</code>```

Body:
In laravel 5.5 with MySQL I use \Illuminate\Support\Facades\DB to create transactions this way:

DB::transaction(function() {
    ...
});

What is the isolation level for such transaction and is there a way to set it explicitly?

Body:
The default in SqlLite is

'BEGIN IMMEDIATE TRANSACTION';

The default in MySQL is

'SET TRANSACTION ISOLATION LEVEL READ COMMITTED';

You can set it yourself by doing something like this

$pdo = DB::connection()->getPdo();
$pdo->exec('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');


问:
Skype for Business shell commands from code

I've developed an application that manages Skype For Business users configurations.

One of the operations I need to run should set Skype user's registrar pool, using this command:

```<code>Move-CsUser -Identity [UserName] -Target [RegistrarPool] -Confirm:$false
</code>```

Now when I run the command from the command line – it works great.

But, unlike the other Skype shell commands I use within my application,
when I run that command using my c# code I get this terrible error:

```<code>Move-CsUser : Unable to cast COM object of type 'System.__ComObject' to interface type \r\n
'Microsoft.Rtc.Interop.User.ICsUserManagement'. This operation failed because the QueryInterface call on the COM \r\n
component for the interface with IID '{D5ADD966-BDC3-4A8F-BFE8-6A59A9F74CB2}' failed due to the following error: Class \r\n
not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).\r\nAt line:1 char:1\r\n+
Move-CsUser -Identity 'testuser' -Target 'XXX' -Confirm: ...\r\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
\r\n    +
CategoryInfo          : InvalidOperation: (CN=Agent Develo...DC=il,DC=tleumi:OCSADUser) [Move-CsUser], InvalidCa \r\n   stException\r\n
+ FullyQualifiedErrorId : MoveError,Microsoft.Rtc.Management.AD.Cmdlets.MoveOcsUserCmdlet\r\n \r\n"
</code>```

I'm apparently terrible at overcoming COM object's errors, despite my best attempts to solve it.

Can anyone give me a hand?

How can I make it work?

答:
yeah its a pain have this every time I do a lync coding project.
Right click on your project name go to properties.
 you need to set the platform target to x64 not any cpu </p>

Body:
I've developed an application that manages Skype For Business users configurations.

One of the operations I need to run should set Skype user's registrar pool, using this command:

Move-CsUser -Identity [UserName] -Target [RegistrarPool] -Confirm:$false

Now when I run the command from the command line – it works great.

But, unlike the other Skype shell commands I use within my application,
when I run that command using my c# code I get this terrible error:

Move-CsUser : Unable to cast COM object of type 'System.__ComObject' to interface type \r\n
'Microsoft.Rtc.Interop.User.ICsUserManagement'. This operation failed because the QueryInterface call on the COM \r\n
component for the interface with IID '{D5ADD966-BDC3-4A8F-BFE8-6A59A9F74CB2}' failed due to the following error: Class \r\n
not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).\r\nAt line:1 char:1\r\n+
Move-CsUser -Identity 'testuser' -Target 'XXX' -Confirm: ...\r\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
\r\n    +
CategoryInfo          : InvalidOperation: (CN=Agent Develo...DC=il,DC=tleumi:OCSADUser) [Move-CsUser], InvalidCa \r\n   stException\r\n
+ FullyQualifiedErrorId : MoveError,Microsoft.Rtc.Management.AD.Cmdlets.MoveOcsUserCmdlet\r\n \r\n"

I'm apparently terrible at overcoming COM object's errors, despite my best attempts to solve it.

Can anyone give me a hand?

How can I make it work?


问:
Error R10 (Boot timeout) on heroku, works in <5 sec using npm start and heroku locally
I'm trying to run a node.js app on heroku, it runs fine using npm start and using heroku locally, but does not run when hosted on heroku. I have looked through all the solutions i could find, the remote mongodb database works fine when run using npm start, my port is set up correctly, have restarted heroku and dynamos a bunch of times, and I have a procfile with the following:

```<code>web node index.js
</code>```

The following is the console messages I get:

```<code>Starting process with command `node index.js`
Warning: connect.session() MemoryStore is not
designed for a production environment, as it will leak
memory, and will not scale past a single process.
Application ready to serve requests.
Environment: production
app[web.1]: (node:4) DeprecationWarning: `open()` is deprecated in
mongoose >= 4.11.0,
use `openUri()` instead, or set the `useMongoClient` option if using
`connect()`
or `createConnection()`. See
http://mongoosejs.com/docs/connections.html#use-mongo-client
Db.prototype.authenticate method will no longer be available in the
next major
release 3.x as MongoDB 3.6 will only allow auth against users in the
admin db
and will no longer allow multiple credentials on a socket. Please
authenticate using MongoClient.connect with auth credentials.
DB Connection Open...
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within
60 seconds of launch
Stopping process with SIGKILL
Process exited with status 137
</code>```

This is my package.json:

```<code>{
  "name": "shop",
  "version": "0.1.0",
  "description": "eCommerce Site",
  "author": "Slav Bugryn",
  "main": "index.js",
  "scripts": {
    "test": "grunt test",
    "build": "grunt build",
    "all": "npm run build && npm run test",
    "start": "node server.js"
  },
  "dependencies": {
    "connect-flash": "^0.1.1",
    "construx": "^1.0.0",
    "construx-copier": "^1.0.0",
    "construx-dustjs": "^1.1.0",
    "construx-less": "^1.0.0",
    "dust-makara-helpers": "^4.2.0",
    "dustjs-helpers": "^1.7.3",
    "eslint": "^4.12.1",
    "express": "^4.12.2",
    "express-messages": "^1.0.1",
    "kraken-js": "^2.0.0",
    "makara": "^2.0.3",
    "mongodb": "^2.2.33",
    "mongoose": "^4.13.6",
    "requirejs": "^2.3.5"
  },
  "devDependencies": {
    "grunt": "^1.0.1",
    "grunt-cli": "^1.2.0",
    "grunt-config-dir": "^0.3.2",
    "grunt-contrib-clean": "^1.1.0",
    "grunt-contrib-less": "^1.4.1",
    "grunt-contrib-requirejs": "^1.0.0",
    "grunt-copy-to": "0.0.12",
    "grunt-dustjs": "^1.4.0",
    "grunt-eslint": "^20.1.0",
    "grunt-makara-amdify": "^1.0.1",
    "grunt-mocha-cli": "^3.0.0",
    "mocha": "^4.0.1",
    "supertest": "^3.0.0"
  },
  "directories": {
    "lib": "lib",
    "test": "test"
  },
  "keywords": [],
  "license": "ISC"
}
</code>```

Any advice would be greatly appreciated, thanks in advance.

答: Figured it out! I sent the Procfile to the wrong place (had to go to server.js, which i found out by looking in package.json and finds start under scripts), after fixing that I got another error (same as here, where i also got the fix: Got a internal server error after I deploy my node js project to the host) which i fixed by running grunt build (had to use --force too).</p>

Body:
I'm trying to run a node.js app on heroku, it runs fine using npm start and using heroku locally, but does not run when hosted on heroku. I have looked through all the solutions i could find, the remote mongodb database works fine when run using npm start, my port is set up correctly, have restarted heroku and dynamos a bunch of times, and I have a procfile with the following:

web node index.js

The following is the console messages I get:

Starting process with command `node index.js`
Warning: connect.session() MemoryStore is not
designed for a production environment, as it will leak
memory, and will not scale past a single process.
Application ready to serve requests.
Environment: production
app[web.1]: (node:4) DeprecationWarning: `open()` is deprecated in
mongoose >= 4.11.0,
use `openUri()` instead, or set the `useMongoClient` option if using
`connect()`
or `createConnection()`. See
http://mongoosejs.com/docs/connections.html#use-mongo-client
Db.prototype.authenticate method will no longer be available in the
next major
release 3.x as MongoDB 3.6 will only allow auth against users in the
admin db
and will no longer allow multiple credentials on a socket. Please
authenticate using MongoClient.connect with auth credentials.
DB Connection Open...
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within
60 seconds of launch
Stopping process with SIGKILL
Process exited with status 137

This is my package.json:

{
  "name": "shop",
  "version": "0.1.0",
  "description": "eCommerce Site",
  "author": "Slav Bugryn",
  "main": "index.js",
  "scripts": {
    "test": "grunt test",
    "build": "grunt build",
    "all": "npm run build && npm run test",
    "start": "node server.js"
  },
  "dependencies": {
    "connect-flash": "^0.1.1",
    "construx": "^1.0.0",
    "construx-copier": "^1.0.0",
    "construx-dustjs": "^1.1.0",
    "construx-less": "^1.0.0",
    "dust-makara-helpers": "^4.2.0",
    "dustjs-helpers": "^1.7.3",
    "eslint": "^4.12.1",
    "express": "^4.12.2",
    "express-messages": "^1.0.1",
    "kraken-js": "^2.0.0",
    "makara": "^2.0.3",
    "mongodb": "^2.2.33",
    "mongoose": "^4.13.6",
    "requirejs": "^2.3.5"
  },
  "devDependencies": {
    "grunt": "^1.0.1",
    "grunt-cli": "^1.2.0",
    "grunt-config-dir": "^0.3.2",
    "grunt-contrib-clean": "^1.1.0",
    "grunt-contrib-less": "^1.4.1",
    "grunt-contrib-requirejs": "^1.0.0",
    "grunt-copy-to": "0.0.12",
    "grunt-dustjs": "^1.4.0",
    "grunt-eslint": "^20.1.0",
    "grunt-makara-amdify": "^1.0.1",
    "grunt-mocha-cli": "^3.0.0",
    "mocha": "^4.0.1",
    "supertest": "^3.0.0"
  },
  "directories": {
    "lib": "lib",
    "test": "test"
  },
  "keywords": [],
  "license": "ISC"
}

Any advice would be greatly appreciated, thanks in advance.