问:
PHP Read from socket on windows machine
I am trying to write a "simple" PHP program that should write and read string to/from a socket (telnet on port 23).

Socket Connection is made using pfsockopen (or socket_connect) function and it seems to work properly (verified with wireshark).
The problem is when I try to read from socket using fread or socket_read.
The buffer returned by these two functions is unreadable (no text but special ascii characters).

Consider that php script is running on a Windows XP PC.
Do you know about any limitation in using these libraries on windows PC and telnet protocol?

```<code>    $header1=chr(0xFF).chr(0xFB).chr(0x1F).chr(0xFF).chr(0xFB).chr(0x20).chr(0xFF).chr(0xFB).chr(0x18).chr(0xFF).chr(0xFB).chr(0x27).chr(0xFF).chr(0xFD).chr(0x01).chr(0xFF).chr(0xFB).chr(0x03).chr(0xFF).chr(0xFD).chr(0x03).chr(0xFF).chr(0xFC).chr(0x23).chr(0xFF).chr(0xFC).chr(0x24).chr(0xFF).chr(0xFA).chr(0x1F).chr(0x00).chr(0x50).chr(0x00).chr(0x18).chr(0xFF).chr(0xF0).chr(0xFF).chr(0xFA).chr(0x20).chr(0x00).chr(0x33).chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0x2C).chr(0x33).chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0xFF).chr(0xF0).chr(0xFF).chr(0xFA).chr(0x27).chr(0x00).chr(0xFF).chr(0xF0).chr(0xFF).chr(0xFA).chr(0x18).chr(0x00).chr(0x58).chr(0x54).chr(0x45).chr(0x52).chr(0x4D).chr(0xFF).chr(0xF0);

$fp=pfsockopen("10.129.127.33",23);
fputs($fp,$header1);
sleep(1);
$output=fread($fp,8164);
echo $output;
</code>```

答:
```<code><?php
# Generating output by telneting a router

$username='myusername';
$password='mypassword';
$ip="192.168.0.1";

    $Telnet_Header = chr(0xFF).chr(0xFB).chr(0x1F).chr(0xFF).chr(0xFB).chr(0x20).chr(0xFF).chr(0xFB).chr(0x18).chr(0xFF).chr(0xFB).chr(0x27).chr(0xFF).chr(0xFD).chr(0x01).chr(0xFF).chr(0xFB).chr(0x03).chr(0xFF).chr(0xFD).chr(0x03).chr(0xFF).chr(0xFC).chr(0x23).chr(0xFF).chr(0xFC).chr(0x24).chr(0xFF).chr(0xFA).chr(0x1F).chr(0x00).chr(0x50).chr(0x00).chr(0x18).chr(0xFF).chr(0xF0).chr(0xFF).chr(0xFA).chr(0x20).chr(0x00).chr(0x33).chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0x2C).chr(0x33).chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0xFF).chr(0xF0).chr(0xFF).chr(0xFA).chr(0x27).chr(0x00).chr(0xFF).chr(0xF0).chr(0xFF).chr(0xFA).chr(0x18).chr(0x00).chr(0x58).chr(0x54).chr(0x45).chr(0x52).chr(0x4D).chr(0xFF).chr(0xF0);
$Telnet_Header2 = chr(0xFF).chr(0xFC).chr(0x01).chr(0xFF).chr(0xFC).chr(0x22).chr(0xFF).chr(0xFE).chr(0x05).chr(0xFF).chr(0xFC).chr(0x21);
$Port = 23;
$Conn = fsockopen($ip, $Port);
fputs($Conn,$Telnet_Header);
sleep(1);
fputs($Conn,$Telnet_Header2);
sleep(1);
fputs($Conn,$username."\r");
sleep(5);
fputs($Conn,$password."\r");
sleep(1);
fputs($Conn,$username."\r");
sleep(5);
fputs($Conn,$password."\r");
sleep(5);
fputs($Conn,"en \r");
   sleep(3);
fputs($Conn,"conf t\r");
   sleep(3);
fputs($Conn,"terminal length 0\r");
   sleep(3);
fputs($Conn,"sh run\r");

   $output="";
do
{
    $output.=fread($Conn, 1000);
    $stat=socket_get_status($Conn);
}while($stat["unread_bytes"]);
$output = explode("\n", $output);
for ($i=6;$i<count($output)-1;$i++)
    {
    echo ($output[$i]."\n");
    }

?>
</code>```

Title: PHP Read from socket on windows machine

Body:
I am trying to write a "simple" PHP program that should write and read string to/from a socket (telnet on port 23).

Socket Connection is made using pfsockopen (or socket_connect) function and it seems to work properly (verified with wireshark).
The problem is when I try to read from socket using fread or socket_read.
The buffer returned by these two functions is unreadable (no text but special ascii characters).

Consider that php script is running on a Windows XP PC.
Do you know about any limitation in using these libraries on windows PC and telnet protocol?

    $header1=chr(0xFF).chr(0xFB).chr(0x1F).chr(0xFF).chr(0xFB).chr(0x20).chr(0xFF).chr(0xFB).chr(0x18).chr(0xFF).chr(0xFB).chr(0x27).chr(0xFF).chr(0xFD).chr(0x01).chr(0xFF).chr(0xFB).chr(0x03).chr(0xFF).chr(0xFD).chr(0x03).chr(0xFF).chr(0xFC).chr(0x23).chr(0xFF).chr(0xFC).chr(0x24).chr(0xFF).chr(0xFA).chr(0x1F).chr(0x00).chr(0x50).chr(0x00).chr(0x18).chr(0xFF).chr(0xF0).chr(0xFF).chr(0xFA).chr(0x20).chr(0x00).chr(0x33).chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0x2C).chr(0x33).chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0xFF).chr(0xF0).chr(0xFF).chr(0xFA).chr(0x27).chr(0x00).chr(0xFF).chr(0xF0).chr(0xFF).chr(0xFA).chr(0x18).chr(0x00).chr(0x58).chr(0x54).chr(0x45).chr(0x52).chr(0x4D).chr(0xFF).chr(0xF0);

$fp=pfsockopen("10.129.127.33",23);
fputs($fp,$header1);
sleep(1);
$output=fread($fp,8164);
echo $output;


来源: stackexchange

问:
Angular localization: just switch language, no translation needed
I've been looking at how Angular (not AngularJS) approaches localization, and it seems like it's all centered around having a translation service that will give you the translated text. It seems like a lot more than I actually need. I'm writing a web site that will serve dashboards both in English and Spanish, and all I need is for a service that shows text that we already translated in one language or the other depending on what the user selects. Would I need to still use the same approach, and just skip the translation service part, or doy you guys know of another library that will just take care of switching languages?

I'm new to Angular (I come from a .NET world - where localization is managed a little differently), so any help is appreciated.

Thanks.

答:
You can take a look at ngx-translate.

It's based on classic raw key-value pairs that can be served thorugh translation files or other self implemented loading methods like http calls to a file (if you don't want to serve the translation files with your app). The service usually is initiated with a default language and a fallback language. You can switch languages programmatically, the service will then try to load another input file (or whatever you've implemented to get the translations for a language). Here's an example for initiation and switching the language.

```<code>constructor(private translate: TranslateService) {
    // this language will be used as a fallback when a translation isn't found in the current language
    this.translate.setDefaultLang('en');

     // the lang to use, if the lang isn't available, it will use the current loader to get them
    this.translate.use('en');
}

switchLanguage(language:string) {
    // switch to another language
    this.translate.use(language);
}
</code>```

The translation values can be bound to the frontend in multiple ways, some work so that you don't even have to reload anything when changing the language, it will switch all values automatically, but they are limited in use. Other ways may nee a reload of the components that are currently shown.

Here's an example that works without reloading.

```<code><!-- translation value with the key "hello" in the currently set language -->
<div translate>hello</div>
</code>```

For more information, check their page, it's pretty well documented.

ContentLicense: CC BY-SA 3.0

Body:
You can take a look at ngx-translate.

It's based on classic raw key-value pairs that can be served thorugh translation files or other self implemented loading methods like http calls to a file (if you don't want to serve the translation files with your app). The service usually is initiated with a default language and a fallback language. You can switch languages programmatically, the service will then try to load another input file (or whatever you've implemented to get the translations for a language). Here's an example for initiation and switching the language.

constructor(private translate: TranslateService) {
    // this language will be used as a fallback when a translation isn't found in the current language
    this.translate.setDefaultLang('en');

     // the lang to use, if the lang isn't available, it will use the current loader to get them
    this.translate.use('en');
}

switchLanguage(language:string) {
    // switch to another language
    this.translate.use(language);
}

The translation values can be bound to the frontend in multiple ways, some work so that you don't even have to reload anything when changing the language, it will switch all values automatically, but they are limited in use. Other ways may nee a reload of the components that are currently shown.

Here's an example that works without reloading.

<!-- translation value with the key "hello" in the currently set language -->
<div translate>hello</div>

For more information, check their page, it's pretty well documented.


问:
Multiple data binding using angular2
i have developed dropdown as child component and used that child in a parent component and working fine. Here child component is dropdown and data for dropdown values is displayed from a get method (Service call).

So, I want to use same child component in the same parent component but the values of dropdown will be different, basically it needs to make one more service call.

Could you explain how to handle this scenario like reusing same child components, but it needs to make separate calls and display the dropdown values accordingly.

答:
You can either

Having an Input to pass url to your dropdown to retrieve data

Making dropdown component to have an Input to get list of data from parent, then do your fetching data in parent and pass retrieved data to the drop down component

Title: Multiple data binding using angular2


问:
How to limited EditText for start characters just english alphabet in Android
In my application I want use EditText and I want start characters just English alphabet.

My mean is, First of characters has just English alphabet (a to z).

I write below codes :

```<code>registerUsernameEdtTxt.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    if (charSequence.toString().length() < 2) {
            registerUsernameEdtTxt.setFilters(new InputFilter[]{new InputFilter() {
                public CharSequence filter(CharSequence src, int start,
                                           int end, Spanned dst, int dstart, int dend) {
                    if (src.toString().matches("[a-zA-Z ]+")) {
                        registerUsernameInptLay.setErrorEnabled(false);
                        return src;
                    }
                    registerUsernameInptLay.setError(context.getResources().getString(R.string.insertJustEnglish));
                    return "";
                }
            }});
        }
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
});
</code>```

But not work me! How can I it?

Please help me

答:
Add this class to your project:

```<code>public class EnglishInputFilter implements InputFilter {

    @Override
    public CharSequence filter(CharSequence charSequence, int start, int end, Spanned spanned, int dstart, int dend) {

        StringBuilder newChars = new StringBuilder(charSequence.toString().substring(start, end));

        for (int i = 0; i < newChars.length(); ) {
            if (!Character.isLetter(newChars.charAt(i)))
                newChars.deleteCharAt(i);
            else
                i++;
        }
        return newChars.toString();
    }

}
</code>```

Then do this with your EditText:

```<code>myEditText.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS)
myEditText.setFilters(new InputFilter[]{new EnglishInputFilter()});
</code>```

It also removes no letter characters from pasted strings, if you paste "1A2B" it will really paste "AB"

You can add more filters, for example for limit the total length.

Body:
In my application I want use EditText and I want start characters just English alphabet.

My mean is, First of characters has just English alphabet (a to z).

I write below codes :

registerUsernameEdtTxt.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    if (charSequence.toString().length() < 2) {
            registerUsernameEdtTxt.setFilters(new InputFilter[]{new InputFilter() {
                public CharSequence filter(CharSequence src, int start,
                                           int end, Spanned dst, int dstart, int dend) {
                    if (src.toString().matches("[a-zA-Z ]+")) {
                        registerUsernameInptLay.setErrorEnabled(false);
                        return src;
                    }
                    registerUsernameInptLay.setError(context.getResources().getString(R.string.insertJustEnglish));
                    return "";
                }
            }});
        }
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
});

But not work me! How can I it?

Please help me

Body:
Add this class to your project:

public class EnglishInputFilter implements InputFilter {

    @Override
    public CharSequence filter(CharSequence charSequence, int start, int end, Spanned spanned, int dstart, int dend) {

        StringBuilder newChars = new StringBuilder(charSequence.toString().substring(start, end));

        for (int i = 0; i < newChars.length(); ) {
            if (!Character.isLetter(newChars.charAt(i)))
                newChars.deleteCharAt(i);
            else
                i++;
        }
        return newChars.toString();
    }

}

Then do this with your EditText:

myEditText.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS)
myEditText.setFilters(new InputFilter[]{new EnglishInputFilter()});

It also removes no letter characters from pasted strings, if you paste "1A2B" it will really paste "AB"

You can add more filters, for example for limit the total length.


问:
React Router Dom History
I'm trying to navigate in my react app after some functionality occurs. Normally I would use window.location to do this, however, I was told to avoid page refreshes in a Single Page App such as mine. I'm struggling to get it to navigate away.

I am using react-router-dom and react-dnd. Because of react-dnd the history is not getting passed down the way it normally would.

```<code>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { DragSource } from 'react-dnd'
import ItemTypes from '../ItemTypes'
import { BrowserRouter } from 'react-router-dom'
const style = {
    fontSize: '126px',
    'cursor': 'move',
}

const boxSource = {
    beginDrag(props) {
        return {
            name: props.name,
        }
    },

    endDrag(props, monitor) {
        // const item = monitor.getItem()
        const dropResult = monitor.getDropResult()

        if (dropResult) {
            // window.location.href = 'http://localhost/book/'
            // what do i put here to navigate away
        }
    },
}

class Key extends Component {
    static propTypes = {
        connectDragSource: PropTypes.func.isRequired,
        isDragging: PropTypes.bool.isRequired,
        name: PropTypes.string.isRequired,
    }

    render() {
        const { isDragging, connectDragSource } = this.props
        const { name } = this.props
        const opacity = isDragging ? 0.4 : 1

        return connectDragSource(<div style={{ ...style, opacity }}>{name}</div>)
    }
}

// @DragSource(ItemTypes.BOX, boxSource, (connect, monitor) => ({
//  connectDragSource: connect.dragSource(),
//  isDragging: monitor.isDragging(),
// }))

export default DragSource(ItemTypes.BOX, boxSource, (connect , monitor) => {
    return {
        connectDragSource: connect.dragSource(),
        isDragging: monitor.isDragging(),
    }
})(Key)
</code>```

I've tried to use browserHistory with react-router but BrowserRouter does not take history as a prop by default.

If I have to use window.location just let me know.

答:
Try using push:

```<code>if (dropResult) {
  history.push('/book')
}
</code>```

See this for more detail.

Title: React Router Dom History

Body:
I'm trying to navigate in my react app after some functionality occurs. Normally I would use window.location to do this, however, I was told to avoid page refreshes in a Single Page App such as mine. I'm struggling to get it to navigate away.

I am using react-router-dom and react-dnd. Because of react-dnd the history is not getting passed down the way it normally would.

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { DragSource } from 'react-dnd'
import ItemTypes from '../ItemTypes'
import { BrowserRouter } from 'react-router-dom'
const style = {
    fontSize: '126px',
    'cursor': 'move',
}

const boxSource = {
    beginDrag(props) {
        return {
            name: props.name,
        }
    },

    endDrag(props, monitor) {
        // const item = monitor.getItem()
        const dropResult = monitor.getDropResult()

        if (dropResult) {
            // window.location.href = 'http://localhost/book/'
            // what do i put here to navigate away
        }
    },
}

class Key extends Component {
    static propTypes = {
        connectDragSource: PropTypes.func.isRequired,
        isDragging: PropTypes.bool.isRequired,
        name: PropTypes.string.isRequired,
    }

    render() {
        const { isDragging, connectDragSource } = this.props
        const { name } = this.props
        const opacity = isDragging ? 0.4 : 1

        return connectDragSource(
{name}
)
    }
}

// @DragSource(ItemTypes.BOX, boxSource, (connect, monitor) => ({
//  connectDragSource: connect.dragSource(),
//  isDragging: monitor.isDragging(),
// }))

export default DragSource(ItemTypes.BOX, boxSource, (connect , monitor) => {
    return {
        connectDragSource: connect.dragSource(),
        isDragging: monitor.isDragging(),
    }
})(Key)

I've tried to use browserHistory with react-router but BrowserRouter does not take history as a prop by default.

If I have to use window.location just let me know.

Body:
Try using push:

if (dropResult) {
  history.push('/book')
}

See this for more detail.


问:
Kotlin Null safety warning Unexpected tokens (use ; to seperate expressions on the same line)
I was trying Elvis operator in Kotlin code in my application and received following warning:

```<code>Unexpected tokens (use ; to seperate expressions on the same line)
</code>```

Code:

```<code>    var key: String = "KEY is"
    /* "check" is name of String variable which can be null
    Warning coming on following statement*/
    var str : String = check?key.replace("KEY", "ABDS-ASDSA-DSSS")?:check
</code>```

Any ideas how to resolve this?

答:
I would not understand why you need any null safe operators here. None of your variables are nullable.

You wrote

```<code>check?key.replace("KEY", "ABDS-ASDSA-DSSS")?:check
</code>```

? (after check) is not an operator in Kotlin.

You may have wanted the ternary conditional operator, which is simply replaced by if/else.

Judging from your comment, you seem to want the safe call operator though, which is ?., not ?.

```<code>check?.key?.replace("KEY", "ABDS-ASDSA-DSSS") ?: check
</code>```

There is a difference between the Elvis operator and the safe call operator. The Elvis operator works with an expression while the safe call operator is simply a null-safe property access or method call.

The Elvis operator returns its first operand if it is not null, and returns the second operand otherwise.

The ?. operator returns null if the receiver is null, otherwise, it returns the result of the call.

Body:
I was trying Elvis operator in Kotlin code in my application and received following warning:

Unexpected tokens (use ; to seperate expressions on the same line)

Code:

    var key: String = "KEY is"
    /* "check" is name of String variable which can be null
    Warning coming on following statement*/
    var str : String = check?key.replace("KEY", "ABDS-ASDSA-DSSS")?:check

Any ideas how to resolve this?

Body:
I would not understand why you need any null safe operators here. None of your variables are nullable.

You wrote

check?key.replace("KEY", "ABDS-ASDSA-DSSS")?:check

? (after check) is not an operator in Kotlin.

You may have wanted the ternary conditional operator, which is simply replaced by if/else.

Judging from your comment, you seem to want the safe call operator though, which is ?., not ?.

check?.key?.replace("KEY", "ABDS-ASDSA-DSSS") ?: check

There is a difference between the Elvis operator and the safe call operator. The Elvis operator works with an expression while the safe call operator is simply a null-safe property access or method call.

The Elvis operator returns its first operand if it is not null, and returns the second operand otherwise.

The ?. operator returns null if the receiver is null, otherwise, it returns the result of the call.


问:
Get nodes from a graph condensation
I have an adjacency  matrix adj and a cellarray nodeManes that contains names that will be given to the graph G that will be constructed from adj.

So I use G = digraph(adj,nodeNames); and I get the following graph :

Now, I want to find the strongly connected components in G and do a graph condensation so I use the following:

```<code>C = condensation(G);
p2 = plot(C);
</code>```

and get this results :

So I have 6 strongly connected components, but my problem is that I lost the node names, I want to get something like:

Is that any way to get the nodes names in the result of the condentation?

答:
I think the official documentation can take you to the right point:

Output Arguments

C - Condensation Graph

Condensation graph, returned as a digraph object. C is a directed
  acyclic graph (DAG), and is topologically sorted. The node numbers in
  C correspond to the bin numbers returned by conncomp.

Let's take a loot at conncomp:

conncomp(G) returns the connected components of graph G as bins. The
  bin numbers indicate which component each node in the graph belongs to

Look at the examples... I think that if you use conncomp on your graph before using the condensation function, you will be able to rebuild your node names on your new graph with a little effort.

Title: Get nodes from a graph condensation

Body:
I have an adjacency  matrix adj and a cellarray nodeManes that contains names that will be given to the graph G that will be constructed from adj.

So I use G = digraph(adj,nodeNames); and I get the following graph :

Now, I want to find the strongly connected components in G and do a graph condensation so I use the following:

C = condensation(G);
p2 = plot(C);

and get this results :

So I have 6 strongly connected components, but my problem is that I lost the node names, I want to get something like:

Is that any way to get the nodes names in the result of the condentation?


问:
INSERT INTO error for MYSQL
Hi this is my first time posting. I have searched all over for an answer but can't seem to find one that fixes mine. I am writing mysql code for a project and can't seem to insert data into a database I am creating. The link to the code is here:

http://sqlfiddle.com/#!9/be69b

Below is what I have come up with so far

```<code>CREATE TABLE IF NOT EXISTS `customers` (`CustomerID` INT AUTO_INCREMENT,
`FirstName` VARCHAR(255) NOT NULL,
`LastName` VARCHAR(255) NOT NULL,
`Address` VARCHAR(255) NOT NULL,
`Apt#` VARCHAR(255) NOT NULL,
`City` VARCHAR(50) NOT NULL,
`State` VARCHAR(3) NOT NULL,
`Zip` VARCHAR(9) NOT NULL,
`HomePhone` VARCHAR(11),
`MobilePhone` VARCHAR(11),
`OtherPhone` VARCHAR(11),
PRIMARY KEY(`CustomerID`)
)
ENGINE=INNODB;

INSERT INTO `customers` VALUES
(`1`, `John`, `Doe`, `123 Green St.`, `Apt A.`, `Richmond`, `VA`, `78646`, `18049481616`, ``, ``);
</code>```

It throws out an error saying that Unknown column 1 in field list. I have tried doing this without AUTO_INCREMENT and it doesn't change anything. Can anyone help with this? Thanks for your help!

答:
One of the things that I try and do when debugging sql code is to make sure that special characters and blanks aren't messing with the query.

Using your insert code above, I recreated your table, and this query worked:

```<code>INSERT INTO `customers` VALUES (null,'John', 'Doe', '123 Green St.', 'Apt A.', 'Richmond, VA', '78646', '18049481616', null,null, null)
</code>```

Title: INSERT INTO error for MYSQL

Body:
Hi this is my first time posting. I have searched all over for an answer but can't seem to find one that fixes mine. I am writing mysql code for a project and can't seem to insert data into a database I am creating. The link to the code is here:

http://sqlfiddle.com/#!9/be69b

Below is what I have come up with so far

CREATE TABLE IF NOT EXISTS `customers` (`CustomerID` INT AUTO_INCREMENT,
`FirstName` VARCHAR(255) NOT NULL,
`LastName` VARCHAR(255) NOT NULL,
`Address` VARCHAR(255) NOT NULL,
`Apt#` VARCHAR(255) NOT NULL,
`City` VARCHAR(50) NOT NULL,
`State` VARCHAR(3) NOT NULL,
`Zip` VARCHAR(9) NOT NULL,
`HomePhone` VARCHAR(11),
`MobilePhone` VARCHAR(11),
`OtherPhone` VARCHAR(11),
PRIMARY KEY(`CustomerID`)
)
ENGINE=INNODB;

INSERT INTO `customers` VALUES
(`1`, `John`, `Doe`, `123 Green St.`, `Apt A.`, `Richmond`, `VA`, `78646`, `18049481616`, ``, ``);

It throws out an error saying that Unknown column 1 in field list. I have tried doing this without AUTO_INCREMENT and it doesn't change anything. Can anyone help with this? Thanks for your help!

Body:
One of the things that I try and do when debugging sql code is to make sure that special characters and blanks aren't messing with the query.

Using your insert code above, I recreated your table, and this query worked:

INSERT INTO `customers` VALUES (null,'John', 'Doe', '123 Green St.', 'Apt A.', 'Richmond, VA', '78646', '18049481616', null,null, null)


答:
Two issues:

1) You don't need to insert the ID since it's the field has an AUTO_INCREMENT clause.

2) You're using backticks which indicate column names, not strings.

```<code>INSERT INTO
    `customers`
    (`FirstName`, `LastName`, `Address`, `Apt#`, `City`, `State`, `Zip`, `HomePhone`, `MobilePhone`, `OtherPhone`)
VALUES
    ('John', 'Doe', '123 Green St.', 'Apt A.', 'Richmond', 'VA', '78646', '18049481616', '', '');
</code>```

SQLFiddle: http://sqlfiddle.com/#!9/392ddf

Title: INSERT INTO error for MYSQL

Body:
Two issues:

1) You don't need to insert the ID since it's the field has an AUTO_INCREMENT clause.

2) You're using backticks which indicate column names, not strings.

INSERT INTO
    `customers`
    (`FirstName`, `LastName`, `Address`, `Apt#`, `City`, `State`, `Zip`, `HomePhone`, `MobilePhone`, `OtherPhone`)
VALUES
    ('John', 'Doe', '123 Green St.', 'Apt A.', 'Richmond', 'VA', '78646', '18049481616', '', '');

SQLFiddle: http://sqlfiddle.com/#!9/392ddf


问:
Manipulating object in array changes object outside of array?
I don't understand why this behavior is happening. Lets say I define an object and make an array of 3 of this object. If I modify the objects in the array, it affects all instances of the object? Could someone explain why this is? Also, how do I make an array with independent "Copies" of the object to get the desired behavior? Thanks!

example

```<code>testObject = {"value1":"a","value2":"b"};
objArray = [];
for(i=0; i < 3; i++){
   var newobj = testObject; //make a new testObject
   objArray.push(newobj); //push new object to array
   }
delete objArray[0].value2 // Desired, delete value 2 ONLY from array object 0
objArray[2].value2 //Undefined? Why is value2 missing from object 2
testObject.value2 //Undefined? Why is value2 missing from original object?
</code>```

答:
When creating an Object in JavaScript, you are actually creating a reference to that object. You can store this in a variable and pass it around ... perhaps append it to an array. When you go to do operations on an object reference, it finds the original object that the reference points to and updates it. Thus when you use .push it's not creating a new object but simply pushing the reference to that object. If you update it in one spot it will update it in the other and any others where you have assigned that reference.

Copying an object into a new object is generally called cloning. There are a lot of different ways to clone objects in JavaScript with varying results.

You can use var newobj = { ...testObject } as the other answer suggests. This spread operator essentially copies the properties of testObject and creates a new object (declared with the outer { }). The reference to that new object is then assigned to newobj. You can think of it as doing this:

```<code>var newobj = {
  value1: testObject.value1,
  value2: testObject.value2,
};
</code>```

However, you should keep in mind that this gives you only one level of cloning. That is to say if your object contains other objects then the reference to that object will be assigned as the property rather than a clone of that object. For example: let's say you had:

```<code>var testObject = { obj: { a: "b" } };
var newobj = { ...testObject };
delete testObject.obj.a;
console.log(newobj); // { obj: {} }
</code>```

In order to solve this, you need to do what is called a deep clone which in JavaScript can be done by recursively cloning object properties that are also objects. There are a bunch of ways to do this including libraries like lodash or home-grown functions. One example on SO: What is the most efficient way to deep clone an object in JavaScript?

Finally, if testObject is supposed to be something like an object template or initial state from which other newobj are derived, it might make more sense to use a function:

```<code>function newObjFactory() {
  return {
    value1: "a",
    value2: "b",
  };
}
</code>```

Then you can do var newobj = newObjFactory() and you'll get a new object each time since a new object is created by the function each time it's called and returned.

Body:
I don't understand why this behavior is happening. Lets say I define an object and make an array of 3 of this object. If I modify the objects in the array, it affects all instances of the object? Could someone explain why this is? Also, how do I make an array with independent "Copies" of the object to get the desired behavior? Thanks!

example

testObject = {"value1":"a","value2":"b"};
objArray = [];
for(i=0; i < 3; i++){
   var newobj = testObject; //make a new testObject
   objArray.push(newobj); //push new object to array
   }
delete objArray[0].value2 // Desired, delete value 2 ONLY from array object 0
objArray[2].value2 //Undefined? Why is value2 missing from object 2
testObject.value2 //Undefined? Why is value2 missing from original object?

Body:
When creating an Object in JavaScript, you are actually creating a reference to that object. You can store this in a variable and pass it around ... perhaps append it to an array. When you go to do operations on an object reference, it finds the original object that the reference points to and updates it. Thus when you use .push it's not creating a new object but simply pushing the reference to that object. If you update it in one spot it will update it in the other and any others where you have assigned that reference.

Copying an object into a new object is generally called cloning. There are a lot of different ways to clone objects in JavaScript with varying results.

You can use var newobj = { ...testObject } as the other answer suggests. This spread operator essentially copies the properties of testObject and creates a new object (declared with the outer { }). The reference to that new object is then assigned to newobj. You can think of it as doing this:

var newobj = {
  value1: testObject.value1,
  value2: testObject.value2,
};

However, you should keep in mind that this gives you only one level of cloning. That is to say if your object contains other objects then the reference to that object will be assigned as the property rather than a clone of that object. For example: let's say you had:

var testObject = { obj: { a: "b" } };
var newobj = { ...testObject };
delete testObject.obj.a;
console.log(newobj); // { obj: {} }

In order to solve this, you need to do what is called a deep clone which in JavaScript can be done by recursively cloning object properties that are also objects. There are a bunch of ways to do this including libraries like lodash or home-grown functions. One example on SO: What is the most efficient way to deep clone an object in JavaScript?

Finally, if testObject is supposed to be something like an object template or initial state from which other newobj are derived, it might make more sense to use a function:

function newObjFactory() {
  return {
    value1: "a",
    value2: "b",
  };
}

Then you can do var newobj = newObjFactory() and you'll get a new object each time since a new object is created by the function each time it's called and returned.


问:
how to update 'people/me'
i use

```<code>people.get({resourceName: 'people/me'})
</code>```

get logged-in user's info, but i can't use

```<code>people.updateContact({resourceName: 'people/me', ...})
</code>```

or

```<code>people.updateContact({resourceName: 'people/[meid]', ...})
</code>```

update this info.

error message is :

```<code>{code: 400, message: "Resource name "people/me" is not a valid contact person resource.", status: "INVALID_ARGUMENT"}
</code>```

or

```<code>{code: 400, message: "Resource name "people/[meid]" is not a valid contact person resource.", status: "INVALID_ARGUMENT"}
</code>```

答: There isn't support for updating the people/me resource in the Google People API as the API only supports updating contacts, and people/me represents the person based on your profile / account. There's some info describing how merged people are composed at https://developers.google.com/people/#understanding_merged_person_data. Only contact based people can be updated.

Title: how to update 'people/me'

Body:
i use

people.get({resourceName: 'people/me'})

get logged-in user's info, but i can't use

people.updateContact({resourceName: 'people/me', ...})

or

people.updateContact({resourceName: 'people/[meid]', ...})

update this info.

error message is :

{code: 400, message: "Resource name "people/me" is not a valid contact person resource.", status: "INVALID_ARGUMENT"}

or

{code: 400, message: "Resource name "people/[meid]" is not a valid contact person resource.", status: "INVALID_ARGUMENT"}


问:
How to sort the RDD and get top N elements using scala?
I have RDD of a case class(TopNModel) and want to get top N elements from giving RDD where sort by tx + rx.
In case of two equal (tx + rx) sort by mac.

```<code>case class TopNModel(mac: Long, tx: Int, rx: Int)
</code>```

For example:

```<code>RDD[TopNModel(10L, 200, 100), TopNModel(12L, 100, 100), TopNModel(1L, 200, 400), TopNModel(11L, 100, 200)]
</code>```

sort by tx + rx and mac:

```<code>RDD[TopNModel(1L, 200, 400), TopNModel(10L, 200, 100), TopNModel(11L, 100, 200), TopNModel(12L, 100, 100)]
</code>```

My Question:

How to sort if rx + tx values are the same then sort based on mac?

答:
EDIT: per important comment below, if indeed the requirement is to "get top N" entities based on this order, sortBy is wasteful compared to takeOrdered. Use the second solution ("alternative") with takeOrdered.

You can use the fact that tuples are naturally-ordered from "leftmost" argument to right, and create a tuple with the negative value of tx + rx (so that these are sorted in decending order) and the positive value of mac:

```<code>val result = rdd.sortBy { case TopNModel(mac, tx, rx) => (-(tx + rx), mac) }
</code>```

Alternatively, if you want TopNModel to always be sorted this way (no matter the context), you can make it an Ordered and implement its compare method. Then, sorting by identity will use that compare to get the same result:

```<code>case class TopNModel(mac: Long, tx: Int, rx: Int) extends Ordered[TopNModel] {
  import scala.math.Ordered.orderingToOrdered
  def compare(that: TopNModel): Int = (-(tx + rx), mac) compare (-(that.tx + that.rx), that.mac)
}

val result = rdd.sortBy(identity)
</code>```

Body:
I have RDD of a case class(TopNModel) and want to get top N elements from giving RDD where sort by tx + rx.
In case of two equal (tx + rx) sort by mac.

case class TopNModel(mac: Long, tx: Int, rx: Int)

For example:

RDD[TopNModel(10L, 200, 100), TopNModel(12L, 100, 100), TopNModel(1L, 200, 400), TopNModel(11L, 100, 200)]

sort by tx + rx and mac:

RDD[TopNModel(1L, 200, 400), TopNModel(10L, 200, 100), TopNModel(11L, 100, 200), TopNModel(12L, 100, 100)]

My Question:

How to sort if rx + tx values are the same then sort based on mac?

Body:
EDIT: per important comment below, if indeed the requirement is to "get top N" entities based on this order, sortBy is wasteful compared to takeOrdered. Use the second solution ("alternative") with takeOrdered.

You can use the fact that tuples are naturally-ordered from "leftmost" argument to right, and create a tuple with the negative value of tx + rx (so that these are sorted in decending order) and the positive value of mac:

val result = rdd.sortBy { case TopNModel(mac, tx, rx) => (-(tx + rx), mac) }

Alternatively, if you want TopNModel to always be sorted this way (no matter the context), you can make it an Ordered and implement its compare method. Then, sorting by identity will use that compare to get the same result:

case class TopNModel(mac: Long, tx: Int, rx: Int) extends Ordered[TopNModel] {
  import scala.math.Ordered.orderingToOrdered
  def compare(that: TopNModel): Int = (-(tx + rx), mac) compare (-(that.tx + that.rx), that.mac)
}

val result = rdd.sortBy(identity)


问:
Why I should create separate project for ReactJS?
I want to use React for front end and Express for backend in my new web application.

According to guides I have to create subproject with create-react-app tool in my project directory:

```<code>my-project
|-frontend
| |-package.json
| |-components
| | |-...
| |
| |-...
|
|-backend
| |-api
| | |-...
| |-app.js
| |-...
|
|-package.json
</code>```

While development, I should launch two servers on different ports, for backend and for frontend, and proxy requests to backend throw React server.

This scheme looks very ugly to me. How can I configure backend server to provide the same functionality as react-scripts does, to avoid using a separate server for it

答:
Having to separate folders (for backend and for frontend) will give you a clearer and scalable structure for your project.

In your backend create a package.json file and inside a script section with:

```<code>"scripts": {
  "start": "node index.js"  // the command you use to run your project
}
</code>```

The way you can run both projects in the same script:

Install npm-run-all package

```<code>$ npm install npm-run-all --save-dev
</code>```

Then in your file my-project/package.json you should have something like this:

```<code>"scripts": {
  "start:server": "cd backend && npm start",
  "start:client": "cd frontend && npm start",
  "start": "npm-run-all --parallel start:client start:server"
}
</code>```

Hope it helps!

ContentLicense: CC BY-SA 4.0

Body:
I want to use React for front end and Express for backend in my new web application.

According to guides I have to create subproject with create-react-app tool in my project directory:

my-project
|-frontend
| |-package.json
| |-components
| | |-...
| |
| |-...
|
|-backend
| |-api
| | |-...
| |-app.js
| |-...
|
|-package.json

While development, I should launch two servers on different ports, for backend and for frontend, and proxy requests to backend throw React server.

This scheme looks very ugly to me. How can I configure backend server to provide the same functionality as react-scripts does, to avoid using a separate server for it

Body:
Having to separate folders (for backend and for frontend) will give you a clearer and scalable structure for your project.

In your backend create a package.json file and inside a script section with:

"scripts": {
  "start": "node index.js"  // the command you use to run your project
}

The way you can run both projects in the same script:

Install npm-run-all package

$ npm install npm-run-all --save-dev

Then in your file my-project/package.json you should have something like this:

"scripts": {
  "start:server": "cd backend && npm start",
  "start:client": "cd frontend && npm start",
  "start": "npm-run-all --parallel start:client start:server"
}

Hope it helps!


问:
Nesting
 and
 tags?

Question:

Which of these is the proper way to nest the
 and
 tags, and what is your reasoning behind it?

Choice A:

```<code><article>
    <h1>Some Title</h1>
    <p>Here's some text and whatnot.</p>
    <p>Here's another paragraph filled with other text and other whatnots.</p>
</article>
</code>```

Choice B:

```<code><div class="post">
    <h1>Here's a Really Awesome Title</h1>
    <article>
        <p>Here's a paragraph with text and whatnot.</p>
        <p>And here's another paragraph. I think this one is pretty awesome too.</p>
    </article>
</div>
</code>```

Opinions seem mixed about this, and I'm not 100% which is the correct answer.

答:
Headings are scoped to article elements (and other sectioning elements). The heading should be inside the article to which it applies.

The first element of heading content in an element of sectioning content represents the heading for that section

— http://www.w3.org/TR/html5/sections.html#headings-and-sections

Choice A is better if it is the heading for that article.

Choice B is better if it is the heading for all the articles that follow it.

ContentLicense: CC BY-SA 2.5

Title: Nesting <article> and <h1> tags?

Body:
Question:

Which of these is the proper way to nest the
 and
 tags, and what is your reasoning behind it?

Choice A:

Some Title

Here's some text and whatnot.

Here's another paragraph filled with other text and other whatnots.

Choice B:

Here's a Really Awesome Title

Here's a paragraph with text and whatnot.

And here's another paragraph. I think this one is pretty awesome too.

Opinions seem mixed about this, and I'm not 100% which is the correct answer.


问:
SQL - Create new start and stop datetime and combine rows based on other columns
My issue is pretty similar to this question: Find start and end dates when one field changes

However, I've been unable to adapt the code to my situation. Any help would be greatly appreciated.

I have data which contains an ID, a variable called Type, and two datetime fields (one named Start and the other named Stop). This can be found here: http://sqlfiddle.com/#!6/35f43

Values for columns Start and Stop can run consecutively, and I want to combine those records grouping by ID and Type. The issue I currently have is I need to keep ID and Type separate if the Start and Stop datetimes are not consecutive.

For example, in the data on the SQLFiddle link, ID '3' currently has five records with type A with one record of type B in between.

```<code>ID         Start                                Stop               Type
3      2010-03-12 05:10:02.0000000    2010-03-20 12:00:00.0000000   A
3      2010-03-20 12:00:00.0000000    2010-04-07 09:46:30.0000000   A
3      2010-04-07 09:46:30.0000000    2010-05-01 08:13:42.0000000   B
3      2010-05-01 08:13:42.0000000    2010-07-04 09:30:32.0000000   A
3      2010-07-04 09:30:32.0000000    2010-07-06 11:41:38.0000000   A
3      2010-07-06 11:41:38.0000000    2010-07-09 12:51:30.0000000   A
</code>```

I need this to show as:

```<code>ID         Start                                Stop               Type
3      2010-03-12 05:10:02.0000000    2010-04-07 09:46:30.0000000   A
3      2010-04-07 09:46:30.0000000    2010-05-01 08:13:42.0000000   B
3      2010-05-01 08:13:42.0000000    2010-07-09 12:51:30.0000000   A
</code>```

Any ideas?

答:
This will do it:</p>

```<code>SELECT
    ID
    , Start
    , [Stop]
    , [Type]
FROM
    (
        SELECT
            ID
            , MIN(Start) Start
            , MAX([Stop]) [Stop]
            , [Type]
            , [Region]
        FROM
            (
                SELECT
                    ID
                    , Start
                    , [Stop]
                    , [Type]
                    , SUM([First]) OVER (PARTITION BY ID ORDER BY [Start]) Region
                FROM
                    (
                        SELECT
                            ID
                            , Start
                            , [Stop]
                            , [Type]
                            ,
                                CASE
                                    WHEN LAG([Type], 1, NULL) OVER (PARTITION BY ID ORDER BY [Start]) = [Type]
                                    THEN 0
                                    ELSE 1
                                END [First]
                        FROM YourTable
                    ) Q
            ) Q2
        GROUP BY
            ID
            , [Type]
            , [Region]
    ) Q3
ORDER BY Region
</code>```

Body:
My issue is pretty similar to this question: Find start and end dates when one field changes

However, I've been unable to adapt the code to my situation. Any help would be greatly appreciated.

I have data which contains an ID, a variable called Type, and two datetime fields (one named Start and the other named Stop). This can be found here: http://sqlfiddle.com/#!6/35f43

Values for columns Start and Stop can run consecutively, and I want to combine those records grouping by ID and Type. The issue I currently have is I need to keep ID and Type separate if the Start and Stop datetimes are not consecutive.

For example, in the data on the SQLFiddle link, ID '3' currently has five records with type A with one record of type B in between.

ID         Start                                Stop               Type
3      2010-03-12 05:10:02.0000000    2010-03-20 12:00:00.0000000   A
3      2010-03-20 12:00:00.0000000    2010-04-07 09:46:30.0000000   A
3      2010-04-07 09:46:30.0000000    2010-05-01 08:13:42.0000000   B
3      2010-05-01 08:13:42.0000000    2010-07-04 09:30:32.0000000   A
3      2010-07-04 09:30:32.0000000    2010-07-06 11:41:38.0000000   A
3      2010-07-06 11:41:38.0000000    2010-07-09 12:51:30.0000000   A

I need this to show as:

ID         Start                                Stop               Type
3      2010-03-12 05:10:02.0000000    2010-04-07 09:46:30.0000000   A
3      2010-04-07 09:46:30.0000000    2010-05-01 08:13:42.0000000   B
3      2010-05-01 08:13:42.0000000    2010-07-09 12:51:30.0000000   A

Any ideas?

Body:
This will do it:

SELECT
    ID
    , Start
    , [Stop]
    , [Type]
FROM
    (
        SELECT
            ID
            , MIN(Start) Start
            , MAX([Stop]) [Stop]
            , [Type]
            , [Region]
        FROM
            (
                SELECT
                    ID
                    , Start
                    , [Stop]
                    , [Type]
                    , SUM([First]) OVER (PARTITION BY ID ORDER BY [Start]) Region
                FROM
                    (
                        SELECT
                            ID
                            , Start
                            , [Stop]
                            , [Type]
                            ,
                                CASE
                                    WHEN LAG([Type], 1, NULL) OVER (PARTITION BY ID ORDER BY [Start]) = [Type]
                                    THEN 0
                                    ELSE 1
                                END [First]
                        FROM YourTable
                    ) Q
            ) Q2
        GROUP BY
            ID
            , [Type]
            , [Region]
    ) Q3
ORDER BY Region


问:
phpmyadmin multiple values in one column
I would like to ask you, does it possible to create a column in phpmyadmin where I could insert (import) more than one value in one column. As example I create a table with name mytable then added column1 (with value 1) and now i would like to add column2(with values 3 5 8).

When I try to do that it only show column2 with value 3 in it... It ignores 5 and 8.

答:
The answer to "can I do it" is "yes". However, the answer to "should I do it" is "try to find another way". For example if I have a string like:

```<code>$mystring = "1 2 3 4 5";
</code>```

If I execute a query to insert this into a table column field it will insert it. If this is the only way you can tackle your algorithm then I suggest you insert data values split with / or - so when you retrieve you can explode them and get their values, but I do not suggest doing it this way. Instead, I suggest you to try and find another solution to your problem before you go for this one.

Body:
The answer to "can I do it" is "yes". However, the answer to "should I do it" is "try to find another way". For example if I have a string like:

$mystring = "1 2 3 4 5";

If I execute a query to insert this into a table column field it will insert it. If this is the only way you can tackle your algorithm then I suggest you insert data values split with / or - so when you retrieve you can explode them and get their values, but I do not suggest doing it this way. Instead, I suggest you to try and find another solution to your problem before you go for this one.


问:
Set date from RecordSet
I am looping through a recordset and extracting dates

```<code>Set dtMSDate = rs.Fields(1)
</code>```

However, when I try to run my module, it highlights the above line and gives the error Compile error: Object required"

Is there some special thing I need to do to format/convert/cast the recordset into the date object? I am not too familiar with the syntax of VBA. I tried...

```<code>CDate(rs.Fields(1))
</code>```

But that still highlights "Fields(1))" with the same error.

Thanks for helping a noob out.

答:
It is not an object, thus:</p>

```<code>dtMSDate = rs.Fields(1).Value
</code>```

Title: Set date from RecordSet

Body:
I am looping through a recordset and extracting dates

Set dtMSDate = rs.Fields(1)

However, when I try to run my module, it highlights the above line and gives the error Compile error: Object required"

Is there some special thing I need to do to format/convert/cast the recordset into the date object? I am not too familiar with the syntax of VBA. I tried...

CDate(rs.Fields(1))

But that still highlights "Fields(1))" with the same error.

Thanks for helping a noob out.

Body:
It is not an object, thus:

dtMSDate = rs.Fields(1).Value


问:
how to get the xml representation of the SOAP request message?
I have the WSDL of a SOAP web service and I am consuming it via my MVC application.

From adding the WSDL as a web service to my Visual Studio solution it automatically creates a proxy class for me and it handles all the serialization/destabilization for me which is really awesome for a while. I have been using this proxy class to call/send my SOAP request to the web service (with pure c# code and no XML involves) and I got my response message back and everything is working great.

However, there is a need now for me to find what is the exact xml representation of the SOAP message that I am sending to the web service. How can I get/find/make this?

答:
you can do it like this

```<code>var serxml = new System.Xml.Serialization.XmlSerializer(request.GetType());
var ms = new MemoryStream();
serxml.Serialize(ms, request);
string xml = Encoding.UTF8.GetString(ms.ToArray());
</code>```

where xml is your raw SOAP

Body:
you can do it like this

var serxml = new System.Xml.Serialization.XmlSerializer(request.GetType());
var ms = new MemoryStream();
serxml.Serialize(ms, request);
string xml = Encoding.UTF8.GetString(ms.ToArray());

where xml is your raw SOAP


问:
Difference between accessing bits after initializing multiple-bit registers forwards vs. backwards in Verilog
New Verilog user here. I was doing some exercises and needed to use some logic which made me wonder this. Here is some relevant code:

```<code>reg [7:0] a;
reg [0:7] b;
a[2] = 1'b1;
b[2] = 1'b1;
</code>```

Would 'a' now be 00100000, or 00000100? I'm guessing 'b' would be 00100000, is that correct?

答:
The range [7:0] means the MSB is 7 and the LSB is 0. So a would be 00000100

A few extra lines of code would give you your answer without needing to ask:

```<code>module top;
reg [7:0] a;
reg [0:7] b;
initial begin
  a[2] = 1'b1;
  b[2] = 1'b1;
  $displayb(a,,b);
end
endmodule
</code>```

Body:
New Verilog user here. I was doing some exercises and needed to use some logic which made me wonder this. Here is some relevant code:

reg [7:0] a;
reg [0:7] b;
a[2] = 1'b1;
b[2] = 1'b1;

Would 'a' now be 00100000, or 00000100? I'm guessing 'b' would be 00100000, is that correct?

Body:
The range [7:0] means the MSB is 7 and the LSB is 0. So a would be 00000100

A few extra lines of code would give you your answer without needing to ask:

module top;
reg [7:0] a;
reg [0:7] b;
initial begin
  a[2] = 1'b1;
  b[2] = 1'b1;
  $displayb(a,,b);
end
endmodule


问:
Casting type inside Optional
I have the following:

```<code>class Foo implements Inter {
    void doSomething();
}

Optional<Inter> getPossible() {
    Optional<Foo> possible = ...;
    possible.ifPresent(Foo::doSomething);
    return possible.map(f -> f);
}
</code>```

getPossible needs to return an Optional<Inter> because it's overriding a superclass's implementation.

That map at the end of the method is purely to convert the type. Is there a more elegant option?

答:
One alternative would be to edit the method signature in Foo to become the following:

```<code>class Foo implements Inter {
    Inter doSomething() {
        ...
        return this;
    }
}
</code>```

Now, you can simplify getPossible to the following:

```<code>Optional<Inter> getPossible() {
    Optional<Foo> possible = ...;
    return possible.map(Foo::doSomething);
}
</code>```

Title: Casting type inside Optional

Body:
I have the following:

class Foo implements Inter {
    void doSomething();
}

Optional<Inter> getPossible() {
    Optional<Foo> possible = ...;
    possible.ifPresent(Foo::doSomething);
    return possible.map(f -> f);
}

getPossible needs to return an Optional<Inter> because it's overriding a superclass's implementation.

That map at the end of the method is purely to convert the type. Is there a more elegant option?

Body:
One alternative would be to edit the method signature in Foo to become the following:

class Foo implements Inter {
    Inter doSomething() {
        ...
        return this;
    }
}

Now, you can simplify getPossible to the following:

Optional<Inter> getPossible() {
    Optional<Foo> possible = ...;
    return possible.map(Foo::doSomething);
}


答: Choice A. The chapter headings (which H1 is too) are part of you article.</p>

Title: Nesting <article> and <h1> tags?


问:
Ionic2 serve not working
When i write ionic serve nothing opens. I have tried changing nodejs versions. Reinstalling ionic cordova. Also cleared cache and other ways on internet. Nothing works. Please help. No errors are shown but a window is not opened.

Info:

```<code>C:\Projects\cutePuppyPics>ionic info

cli packages: (C:\Users\Tullo\AppData\Roaming\npm\node_modules)

    @ionic/cli-utils  : 1.19.0
    ionic (Ionic CLI) : 3.19.0

global packages:

    cordova (Cordova CLI) : 7.1.0

local packages:

    @ionic/app-scripts : 3.1.4
    Cordova Platforms  : none
    Ionic Framework    : ionic-angular 3.9.2

System:

    Node : v8.9.1
    npm  : 5.5.1
    OS   : Windows 10

Environment Variables:

    ANDROID_HOME : not set

Misc:

    backend : pro
</code>```

Serve:

```<code>C:\Projects\cutePuppyPics>ionic serve
Starting app-scripts server: --address 0.0.0.0 --port 8100 --livereload-port 35729 --dev-logger-port 53703 --nobrowser -
Ctrl+C to cancel
[20:52:58]  watch started ...
[20:52:58]  build dev started ...
[20:52:58]  clean started ...
[20:52:58]  clean finished in 12 ms
[20:52:58]  copy started ...
[20:52:58]  deeplinks started ...
[20:52:58]  deeplinks finished in 40 ms
[20:52:58]  transpile started ...
[20:53:03]  transpile finished in 5.17 s
[20:53:03]  preprocess started ...
[20:53:04]  preprocess finished in 4 ms
[20:53:04]  webpack started ...
[20:53:04]  copy finished in 5.44 s
[20:53:13]  webpack finished in 9.14 s
[20:53:13]  sass started ...
[20:53:14]  sass finished in 1.68 s
[20:53:14]  postprocess started ...
[20:53:14]  postprocess finished in 16 ms
[20:53:14]  lint started ...
[20:53:14]  build dev finished in 16.32 s
[20:53:14]  watch ready in 16.47 s`enter code here`
[20:53:14]  dev server running: http://localhost:8100/

[OK] Development server running!
     Local: http://localhost:8100
     External: http://192.168.10.8:8100
     DevApp: cutePuppyPics@8100 on LAPTOP-NNU75MUT
</code>```

答: Sometimes the browser doesn't open automatically. Try entering http://localhost:8100 on your browser manually after ionic serve.

Title: Ionic2 serve not working

Body:
When i write ionic serve nothing opens. I have tried changing nodejs versions. Reinstalling ionic cordova. Also cleared cache and other ways on internet. Nothing works. Please help. No errors are shown but a window is not opened.

Info:

C:\Projects\cutePuppyPics>ionic info

cli packages: (C:\Users\Tullo\AppData\Roaming\npm\node_modules)

    @ionic/cli-utils  : 1.19.0
    ionic (Ionic CLI) : 3.19.0

global packages:

    cordova (Cordova CLI) : 7.1.0

local packages:

    @ionic/app-scripts : 3.1.4
    Cordova Platforms  : none
    Ionic Framework    : ionic-angular 3.9.2

System:

    Node : v8.9.1
    npm  : 5.5.1
    OS   : Windows 10

Environment Variables:

    ANDROID_HOME : not set

Misc:

    backend : pro

Serve:

C:\Projects\cutePuppyPics>ionic serve
Starting app-scripts server: --address 0.0.0.0 --port 8100 --livereload-port 35729 --dev-logger-port 53703 --nobrowser -
Ctrl+C to cancel
[20:52:58]  watch started ...
[20:52:58]  build dev started ...
[20:52:58]  clean started ...
[20:52:58]  clean finished in 12 ms
[20:52:58]  copy started ...
[20:52:58]  deeplinks started ...
[20:52:58]  deeplinks finished in 40 ms
[20:52:58]  transpile started ...
[20:53:03]  transpile finished in 5.17 s
[20:53:03]  preprocess started ...
[20:53:04]  preprocess finished in 4 ms
[20:53:04]  webpack started ...
[20:53:04]  copy finished in 5.44 s
[20:53:13]  webpack finished in 9.14 s
[20:53:13]  sass started ...
[20:53:14]  sass finished in 1.68 s
[20:53:14]  postprocess started ...
[20:53:14]  postprocess finished in 16 ms
[20:53:14]  lint started ...
[20:53:14]  build dev finished in 16.32 s
[20:53:14]  watch ready in 16.47 s`enter code here`
[20:53:14]  dev server running: http://localhost:8100/

[OK] Development server running!
     Local: http://localhost:8100
     External: http://192.168.10.8:8100
     DevApp: cutePuppyPics@8100 on LAPTOP-NNU75MUT


问:
Custom attribute in Twilio verb
I was looking into attributes of Dial verb. In Dial verb, we have an attribute hangupOnStar. So if we created a call using dial verb and set attribute hangupOnStar then in the middle of the call the user can hang up the call by pressing star (*) on his phone. And then next verb will get executed in the twiml response.

So my question is can we create our own custom attribute like toHangupPress (some_key)? I searched the web but didn't find any documentation in this regard.

Can we create custom attribute at any place in Programmable Voice of Twilio?

答:
Twilio developer evangelist here.

You cannot create custom properties for TwiML, so it is not possible to hang up with any other keypress when using <Dial>.

If you are doing other things, then you can use <Gather> to take keypresses and react to them, however it's not possible to nest a <Dial> within a <Gather>.

Title: Custom attribute in Twilio verb


问:
VBA Calling a private function inside of a userform
I have a userform defined as "SingleListForm".
I have a private sub named "loadSingleListForm(ID As Double)"
I am attempting to pass a variable into the form and I was implementing it in the fashion that loadSingleListForm would set the form up based on ID, basically re-using one form to show variable data from variable sources in the listbox.

But calling a standard Intersect from  outside the form (Worksheet_SelectionChange) these two options compile but do not work.

```<code>Application.Run "SingleListForm.loadSingleListForm", ID 'ID already declared and assigned
</code>```

This doesn't work either

```<code>Call ActiveWorkbook.UserForm("SingleListForm").loadSingleListForm(ID)
</code>```

Where it says UserForm I have also tried SingleListForm.
Here the runtime error is:

I am trying hard not to use a Global Variable here to pass to the form.
Perhaps I should go to Initialize and try something there.
I am trying to pass the variable to the form and then of course set up the form based on this case and then show the form.  you can't pass with show so you have to find another way to set up.

I just realized I have not called a userform private function from outside of the form before, but I do it with modules all the time.  The first case works in that instance.

Cheers,
-WWC

答: Declare your sub in the form as Public Public Sub loadSingleListForm(ID As Double) and then call it like this SingleListForm.loadSingleListForm ID

Body:
I have a userform defined as "SingleListForm".
I have a private sub named "loadSingleListForm(ID As Double)"
I am attempting to pass a variable into the form and I was implementing it in the fashion that loadSingleListForm would set the form up based on ID, basically re-using one form to show variable data from variable sources in the listbox.

But calling a standard Intersect from  outside the form (Worksheet_SelectionChange) these two options compile but do not work.

Application.Run "SingleListForm.loadSingleListForm", ID 'ID already declared and assigned

This doesn't work either

Call ActiveWorkbook.UserForm("SingleListForm").loadSingleListForm(ID)

Where it says UserForm I have also tried SingleListForm.
Here the runtime error is:

I am trying hard not to use a Global Variable here to pass to the form.
Perhaps I should go to Initialize and try something there.
I am trying to pass the variable to the form and then of course set up the form based on this case and then show the form.  you can't pass with show so you have to find another way to set up.

I just realized I have not called a userform private function from outside of the form before, but I do it with modules all the time.  The first case works in that instance.

Cheers,
-WWC


问:
How does one make a horizontal listbox in .NET
I am working on porting a VB6 application to .NET and one of the desired UI elements is a horizontal listbox. I can't seem to figure out how to replicate this in .NET.

Can this be done with basic winforms?

How would you replicate this?

Sample:

The VB6 code that will replicate the above image:

```<code>Private Sub Form_Load()
    lst_horizontal(1).FontSize = 6
    Dim iMaxChoices As Integer
    iMaxChoices = 10
    For i = 1 To iMaxChoices
        lst_horizontal(1).AddItem (" " + CStr(i))
    Next i
End Sub

Private Sub lst_horizontal_Click(Index As Integer)
    Dim iMaxChoices As Integer
    iMaxChoices = 10

    For i = 0 To iMaxChoices - 1

        If lst_horizontal(1).Selected(i) Then
            Debug.Print ("Item " + CStr(i + 1) + " selected")
        End If

    Next i
</code>```

Weasel words: I can figure out how to replicate this in Silverlight/XAML, but this app can't be done in that fashion.

答: This is supported in Winforms as well.  Set the MultiColumn property to True, the ColumnWidth property to, say, 15.  Producing:

Body:
I am working on porting a VB6 application to .NET and one of the desired UI elements is a horizontal listbox. I can't seem to figure out how to replicate this in .NET.

Can this be done with basic winforms?

How would you replicate this?

Sample:

The VB6 code that will replicate the above image:

Private Sub Form_Load()
    lst_horizontal(1).FontSize = 6
    Dim iMaxChoices As Integer
    iMaxChoices = 10
    For i = 1 To iMaxChoices
        lst_horizontal(1).AddItem (" " + CStr(i))
    Next i
End Sub

Private Sub lst_horizontal_Click(Index As Integer)
    Dim iMaxChoices As Integer
    iMaxChoices = 10

    For i = 0 To iMaxChoices - 1

        If lst_horizontal(1).Selected(i) Then
            Debug.Print ("Item " + CStr(i + 1) + " selected")
        End If

    Next i

Weasel words: I can figure out how to replicate this in Silverlight/XAML, but this app can't be done in that fashion.


问:
How can I edit my code to make it decrypt all encrypted files within a directory and sub directories?
I need to edit this code so that it will decrypt all of the files in a directory that are encrypted, currently it encrypts everything and decrypts 1 at a time. How do I do this? Thanks. I am also running it from terminal, if that affects anything. When it encrypts a file, it renames the file with "(encrypted)" in front of the original name, maybe I can make it search for names with (encrypted) and decrypt them.</p>

```<code>from Crypto.Hash import SHA256
from Crypto.Cipher import AES
import os, random, sys, pkg_resources

#Encryption Function

def encrypt(key, filename):
    chunksize = 256 * 1024
    outFile = os.path.join(os.path.dirname(filename), "(encrypted)"+os.path.basename(filename))
    filesize = str(os.path.getsize(filename)).zfill(16)
    IV = ''

    for i in range(16):
        IV += chr(random.randint(0, 0xFF))

    encryptor = AES.new(key, AES.MODE_CBC, IV)

    with open(filename, "rb") as infile:
        with open(outFile, "wb") as outfile:
            outfile.write(filesize)
            outfile.write(IV)
            while True:
                chunk = infile.read(chunksize)

                if len(chunk) == 0:
                    break

                elif len(chunk) % 16 !=0:
                    chunk += ' ' *  (16 - (len(chunk) % 16))

                outfile.write(encryptor.encrypt(chunk))

def decrypt(key, filename):
    outFile = os.path.join(os.path.dirname(filename), os.path.basename(filename[11:]))
    chunksize = 64 * 1024
    with open(filename, "rb") as infile:
        filesize = infile.read(16)
        IV = infile.read(16)

        decryptor = AES.new(key, AES.MODE_CBC, IV)

        with open(outFile, "wb") as outfile:
            while True:
                chunk = infile.read(chunksize)
                if len(chunk) == 0:
                    break

                outfile.write(decryptor.decrypt(chunk))

            outfile.truncate(int(filesize))

def allfiles():
    allFiles = []
    for root, subfiles, files in os.walk(os.getcwd()):
        for names in files:
            allFiles.append(os.path.join(root, names))

    return allFiles

choice = raw_input("Do you want to (E)ncrypt or (D)ecrypt? ")
password = raw_input("Enter the password: ")

encFiles = allfiles()

if choice == "E" or choice == "e":
    for Tfiles in encFiles:
        if os.path.basename(Tfiles).startswith("(encrypted)"):
            print ("%s is already encrypted" %str(Tfiles))
            pass

        elif Tfiles == os.path.join(os.getcwd(), sys.argv[0]):
            pass
        else:
            encrypt(SHA256.new(password).digest(), str(Tfiles))
            print ("Done encrypting %s" %str(Tfiles))
            os.remove(Tfiles)

elif choice == "D" or choice == "d":
    filename = raw_input("Enter the filename to decrypt: ")
    if not os.path.exists(filename):
        print ("The file does not exist")
        sys.exit(0)
    elif not filename.startswith("(encrypted)"):
        print ("%s is already not encrypted" %filename)
        sys.exit()
    else:
        decrypt(SHA256.new(password).digest(), filename)
        print ("Done decrypting %s" %filename)
        os.remove(filename)

else:
    print ("Please choose a valid command.")
    sys.exit()
</code>```

答:
Change the following</p>

```<code>elif choice == "D" or choice == "d":
    for Tfiles in encFiles:
        filename = raw_input("Enter the filename to decrypt: ")
        if not os.path.exists(filename):
            print ("The file does not exist")
            sys.exit(0)
        elif not filename.startswith("(encrypted)"):
            print ("%s is already not encrypted" %filename)
            sys.exit()
</code>```

Body:
I need to edit this code so that it will decrypt all of the files in a directory that are encrypted, currently it encrypts everything and decrypts 1 at a time. How do I do this? Thanks. I am also running it from terminal, if that affects anything. When it encrypts a file, it renames the file with "(encrypted)" in front of the original name, maybe I can make it search for names with (encrypted) and decrypt them.

from Crypto.Hash import SHA256
from Crypto.Cipher import AES
import os, random, sys, pkg_resources

#Encryption Function

def encrypt(key, filename):
    chunksize = 256 * 1024
    outFile = os.path.join(os.path.dirname(filename), "(encrypted)"+os.path.basename(filename))
    filesize = str(os.path.getsize(filename)).zfill(16)
    IV = ''

    for i in range(16):
        IV += chr(random.randint(0, 0xFF))

    encryptor = AES.new(key, AES.MODE_CBC, IV)

    with open(filename, "rb") as infile:
        with open(outFile, "wb") as outfile:
            outfile.write(filesize)
            outfile.write(IV)
            while True:
                chunk = infile.read(chunksize)

                if len(chunk) == 0:
                    break

                elif len(chunk) % 16 !=0:
                    chunk += ' ' *  (16 - (len(chunk) % 16))

                outfile.write(encryptor.encrypt(chunk))

def decrypt(key, filename):
    outFile = os.path.join(os.path.dirname(filename), os.path.basename(filename[11:]))
    chunksize = 64 * 1024
    with open(filename, "rb") as infile:
        filesize = infile.read(16)
        IV = infile.read(16)

        decryptor = AES.new(key, AES.MODE_CBC, IV)

        with open(outFile, "wb") as outfile:
            while True:
                chunk = infile.read(chunksize)
                if len(chunk) == 0:
                    break

                outfile.write(decryptor.decrypt(chunk))

            outfile.truncate(int(filesize))

def allfiles():
    allFiles = []
    for root, subfiles, files in os.walk(os.getcwd()):
        for names in files:
            allFiles.append(os.path.join(root, names))

    return allFiles

choice = raw_input("Do you want to (E)ncrypt or (D)ecrypt? ")
password = raw_input("Enter the password: ")

encFiles = allfiles()

if choice == "E" or choice == "e":
    for Tfiles in encFiles:
        if os.path.basename(Tfiles).startswith("(encrypted)"):
            print ("%s is already encrypted" %str(Tfiles))
            pass

        elif Tfiles == os.path.join(os.getcwd(), sys.argv[0]):
            pass
        else:
            encrypt(SHA256.new(password).digest(), str(Tfiles))
            print ("Done encrypting %s" %str(Tfiles))
            os.remove(Tfiles)

elif choice == "D" or choice == "d":
    filename = raw_input("Enter the filename to decrypt: ")
    if not os.path.exists(filename):
        print ("The file does not exist")
        sys.exit(0)
    elif not filename.startswith("(encrypted)"):
        print ("%s is already not encrypted" %filename)
        sys.exit()
    else:
        decrypt(SHA256.new(password).digest(), filename)
        print ("Done decrypting %s" %filename)
        os.remove(filename)

else:
    print ("Please choose a valid command.")
    sys.exit()

Body:
Change the following

elif choice == "D" or choice == "d":
    for Tfiles in encFiles:
        filename = raw_input("Enter the filename to decrypt: ")
        if not os.path.exists(filename):
            print ("The file does not exist")
            sys.exit(0)
        elif not filename.startswith("(encrypted)"):
            print ("%s is already not encrypted" %filename)
            sys.exit()


问:
How to get Months between two dates
I'm trying to get All the months between two dates.

for e.g if the user posted an article on 21-10-2012 and today date is 5-12-2017. Now i want to get all the month and Year between this period like shown below

```<code>10-2012
11-2012
01-2013
02-2014
03-2015
04-2015
05-2015
06-2015
07-2015 // and so on
.......
.......
.......
12-2017 // Till Today Date
</code>```

Till Now i was only able to calculate the difference.

```<code>$article_date= date("d-m-Y", $article['date']);
$year = date("Y");
$month = date("m");
$day = date("d");
$date1 = new DateTime($article_date);
$date2 = new DateTime("$day-$month-$year");

$diff = $date1->diff($date2);

echo (($diff->format('%y') * 12) + $diff->format('%m')) . " full months difference";
</code>```

How can i get all the months?

答:
Use this code</p>

```<code>$start    = new DateTime('2012-10-21');
$start->modify('first day of this month');
$end      = new DateTime('2017-12-05');
$end->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period   = new DatePeriod($start, $interval, $end);

foreach ($period as $dt) {
    echo $dt->format("m-Y") . "<br>\n";
}
</code>```

Title: How to get Months between two dates

Body:
I'm trying to get All the months between two dates.

for e.g if the user posted an article on 21-10-2012 and today date is 5-12-2017. Now i want to get all the month and Year between this period like shown below

10-2012
11-2012
01-2013
02-2014
03-2015
04-2015
05-2015
06-2015
07-2015 // and so on
.......
.......
.......
12-2017 // Till Today Date

Till Now i was only able to calculate the difference.

$article_date= date("d-m-Y", $article['date']);
$year = date("Y");
$month = date("m");
$day = date("d");
$date1 = new DateTime($article_date);
$date2 = new DateTime("$day-$month-$year");

$diff = $date1->diff($date2);

echo (($diff->format('%y') * 12) + $diff->format('%m')) . " full months difference";

How can i get all the months?

Body:
Use this code

$start    = new DateTime('2012-10-21');
$start->modify('first day of this month');
$end      = new DateTime('2017-12-05');
$end->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period   = new DatePeriod($start, $interval, $end);

foreach ($period as $dt) {
    echo $dt->format("m-Y") . "<br>\n";
}


问:
Staged roll out and beta testers on Android
For our Android app, we have a number of beta testers signed up via an opt-in link through Google Play. If I do a staged production roll out at 10%, will that include my beta testers or will they just have to be the lucky 10% to get it?

Is there a way that I can publish a version of the app both to beta testers and to 10% as staged roll out at the same time through Google Play?

Basically I want to release to a few specific users (beta testers) as well as to a % of the rest of users, before going to prod at 100%.

答:
Beta testers are implicitly included in a staged rollout. Otherwise, the beta release would be lagging behind the production release, and that really shouldn't happen.

My own empirical observations confirm this: I've done several staged rollouts, and beta testers have always been among the first to receive the update.

Of course it's also possible to release to beta first, and then promote the APK to production with a staged rollout.


问:
A strange behavior of the multiprocessing when queue is added into the apply_async func?
I want to put the generated result of the func in pool.apply_async() method into a queue, everything seems very well but the error confused me a lot.

My purpose is try to make multiple asynchronized producers(maybe not correct here) and multiple consumers.

Here is my toy example:

```<code>from multiprocessing import Pool
import multiprocessing
from threading import Thread

from six.moves import xrange
pool = Pool(processes=2, maxtasksperchild=1000)

# resp_queue = multiprocessing.Queue(1000)
manager = multiprocessing.Manager()
resp_queue = manager.Queue()

rang = 10000

def fetch_page(url):
    resp_queue.put(url)

def parse_response():
    url = resp_queue.get()
    print(url)

r_threads = []

def start_processing():
    for i in range(2):
        r_threads.append(Thread(target=parse_response))
        print("start %s thread.." % i)
        r_threads[-1].start()

urls = map(lambda x: "this is url %s" % x, xrange(rang))
for i in xrange(rang):
    pool.apply_async(fetch_page, (urls[i],))

start_processing()

pool.close()
pool.join()
</code>```

The error reads that:

```<code>> Process PoolWorker-1: Process PoolWorker-2: Traceback (most recent
> call last): Traceback (most recent call last):   File
> "/usr/lib/python2.7/multiprocessing/process.py", line 258, in
> _bootstrap   File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
>     self.run()
>     self.run()   File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run   File
> "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
>     self._target(*self._args, **self._kwargs)
>     self._target(*self._args, **self._kwargs)   File "/usr/lib/python2.7/multiprocessing/pool.py", line 102, in worker
> File "/usr/lib/python2.7/multiprocessing/pool.py", line 102, in worker
>     task = get()
>     task = get()   File "/usr/lib/python2.7/multiprocessing/queues.py", line 376, in get
> File "/usr/lib/python2.7/multiprocessing/queues.py", line 376, in get
>     return recv()
>     return recv() AttributeError: 'module' object has no attribute 'fetch_page' AttributeError: 'module' object has no attribute
> 'fetch_page' start 0 thread.. start 1 thread..
</code>```

I have read this answer but found it very strange, and this answer doesn't work on my Ubuntu machine.

Any suggestions are highly appreciated. Thanks very much.

答:
Have a look at the code below. Changes I made to your version:

I'm using map instead of apply as it gets an iterable and splits work between workers nicely.

I've added a while loop to your parse_resp function (now get_url) so each thread will get values from queue to exhaustion.

Pool instantiation & calling is after __name__ == '__main__' which is a windows hack needed for Python multiprocessing (as much as I know, might be wrong I'm on Ubuntu).

from multiprocessing import Pool
    import multiprocessing
    from threading import Thread

```<code>manager = multiprocessing.Manager()
url_queue = manager.Queue()

rang = 10000

def put_url(url):
    url_queue.put(url)

def get_url(thread_id):
    while not url_queue.empty():
        print('Thread {0} got url {1}'.format(str(thread_id), url_queue.get()))

r_threads = []

def start_threading():
    for i in range(2):
        r_threads.append(Thread(target=get_url, args=(i,)))
        print("start %s thread.." % i)
        r_threads[-1].start()
    for i in r_threads:
        i.join()

urls = ["url %s" % x for x in range(rang)]

if __name__ == '__main__':
    pool = Pool(processes=2, maxtasksperchild=1000)
    pool.map_async(put_url, urls)
    start_threading()
    pool.close()
    pool.join()
</code>```

Prints:

start 0 thread..

   start 1 thread..

   Thread 0 got url 0

   Thread 0 got url 1

   Thread 1 got url 2

   Thread 0 got url 3

   Thread 0 got url 4

   Thread 1 got url 5

   Thread 0 got url 6

Body:
I want to put the generated result of the func in pool.apply_async() method into a queue, everything seems very well but the error confused me a lot.

My purpose is try to make multiple asynchronized producers(maybe not correct here) and multiple consumers.

Here is my toy example:

from multiprocessing import Pool
import multiprocessing
from threading import Thread

from six.moves import xrange
pool = Pool(processes=2, maxtasksperchild=1000)

# resp_queue = multiprocessing.Queue(1000)
manager = multiprocessing.Manager()
resp_queue = manager.Queue()

rang = 10000

def fetch_page(url):
    resp_queue.put(url)

def parse_response():
    url = resp_queue.get()
    print(url)

r_threads = []

def start_processing():
    for i in range(2):
        r_threads.append(Thread(target=parse_response))
        print("start %s thread.." % i)
        r_threads[-1].start()

urls = map(lambda x: "this is url %s" % x, xrange(rang))
for i in xrange(rang):
    pool.apply_async(fetch_page, (urls[i],))

start_processing()

pool.close()
pool.join()

The error reads that:

> Process PoolWorker-1: Process PoolWorker-2: Traceback (most recent
> call last): Traceback (most recent call last):   File
> "/usr/lib/python2.7/multiprocessing/process.py", line 258, in
> _bootstrap   File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
>     self.run()
>     self.run()   File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run   File
> "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
>     self._target(*self._args, **self._kwargs)
>     self._target(*self._args, **self._kwargs)   File "/usr/lib/python2.7/multiprocessing/pool.py", line 102, in worker
> File "/usr/lib/python2.7/multiprocessing/pool.py", line 102, in worker
>     task = get()
>     task = get()   File "/usr/lib/python2.7/multiprocessing/queues.py", line 376, in get
> File "/usr/lib/python2.7/multiprocessing/queues.py", line 376, in get
>     return recv()
>     return recv() AttributeError: 'module' object has no attribute 'fetch_page' AttributeError: 'module' object has no attribute
> 'fetch_page' start 0 thread.. start 1 thread..

I have read this answer but found it very strange, and this answer doesn't work on my Ubuntu machine.

Any suggestions are highly appreciated. Thanks very much.

Body:
Have a look at the code below. Changes I made to your version:

I'm using map instead of apply as it gets an iterable and splits work between workers nicely.

I've added a while loop to your parse_resp function (now get_url) so each thread will get values from queue to exhaustion.

Pool instantiation & calling is after __name__ == '__main__' which is a windows hack needed for Python multiprocessing (as much as I know, might be wrong I'm on Ubuntu).

from multiprocessing import Pool
    import multiprocessing
    from threading import Thread

manager = multiprocessing.Manager()
url_queue = manager.Queue()

rang = 10000

def put_url(url):
    url_queue.put(url)

def get_url(thread_id):
    while not url_queue.empty():
        print('Thread {0} got url {1}'.format(str(thread_id), url_queue.get()))

r_threads = []

def start_threading():
    for i in range(2):
        r_threads.append(Thread(target=get_url, args=(i,)))
        print("start %s thread.." % i)
        r_threads[-1].start()
    for i in r_threads:
        i.join()

urls = ["url %s" % x for x in range(rang)]

if __name__ == '__main__':
    pool = Pool(processes=2, maxtasksperchild=1000)
    pool.map_async(put_url, urls)
    start_threading()
    pool.close()
    pool.join()

Prints:

start 0 thread..

   start 1 thread..

   Thread 0 got url 0

   Thread 0 got url 1

   Thread 1 got url 2

   Thread 0 got url 3

   Thread 0 got url 4

   Thread 1 got url 5

   Thread 0 got url 6


问:
Datagridview checkboxcolumn validation
In a DatagridView I have databound checkboxcolumns. But if I check or uncheck multiple checkboxes, not all changes are saved. (It doesn't trigger the property Set method on all, maybe on every 2nd). However if I after each checkbox-click, click on another cell (column) before the next checkbox, then all actions will trigger the Set methods.  So it seems the cell validation does not work on a per-cell basis, but on a per column basis (For the checkboxcolumn).  So how do you solve this?

答:
It is not really clear what you have tried and what doesn't work. I assume you have a Winform application and use a SqlDataSource to bind a SQL-Server table to your grid. There is a boolean(bit) field in your database, hence the grid automatically generates a DataGridViewCheckBoxColumn. You are trying to save all changes that the user has made when he clicks a save-button.

Are all of these guesses correct?

All you have to do is to update your dataset/datatable with the dataadapter.

```<code>Private Sub BtnSaveChanges_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSaveChanges.Click
    Me.FooTableAdapter.Update(DataSet1.Foo)
End Sub
</code>```

MSD-Example: http://msdn.microsoft.com/en-use/library/fbk67b6z.aspx

If changes should be saved directly to the database, you can handle the CurrentItemChanged-event of the BindingSource.

```<code>Private Sub FooBindingSource_CurrentItemChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles FooBindingSource.CurrentItemChanged
     Dim thisDataRow As DataRow = DirectCast(DirectCast(sender, BindingSource).Current, DataRowView).Row
     If thisDataRow.RowState = DataRowState.Modified Then
         Me.FooTableAdapter.Update(thisDataRow)
     End If
End Sub
</code>```

Title: Datagridview checkboxcolumn validation

Body:
It is not really clear what you have tried and what doesn't work. I assume you have a Winform application and use a SqlDataSource to bind a SQL-Server table to your grid. There is a boolean(bit) field in your database, hence the grid automatically generates a DataGridViewCheckBoxColumn. You are trying to save all changes that the user has made when he clicks a save-button.

Are all of these guesses correct?

All you have to do is to update your dataset/datatable with the dataadapter.

Private Sub BtnSaveChanges_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSaveChanges.Click
    Me.FooTableAdapter.Update(DataSet1.Foo)
End Sub

MSD-Example: http://msdn.microsoft.com/en-use/library/fbk67b6z.aspx

If changes should be saved directly to the database, you can handle the CurrentItemChanged-event of the BindingSource.

Private Sub FooBindingSource_CurrentItemChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles FooBindingSource.CurrentItemChanged
     Dim thisDataRow As DataRow = DirectCast(DirectCast(sender, BindingSource).Current, DataRowView).Row
     If thisDataRow.RowState = DataRowState.Modified Then
         Me.FooTableAdapter.Update(thisDataRow)
     End If
End Sub


问:
ggplot geom_errorbarh error (wants discrete when entered as continuous, but wants continuous when entered as discrete)
I am working on creating a forest plot for a meta analysis using ggplot2.
Here is what an earlier version/incomplete graph looked like.

My problem is now that I'm going to back to work on it some more, everything works except I cant get the error bars with geom_errorbarh.

Data:   Here is a data file from dput on my dropbox. For the life of me, I can't figure out how to get it to paste direct on here in a way that would copy-and-paste into R without having problems. Anyway, if you just save that file (q.df) and run df.forest <- dget("your-path/q.df"), you'll have a usable df. (Note: this is parsed down from the full df that I'm working with to only include the variables needed for this particular plot, but if something doesn't make sense, just let me know and I'll try to clarify.)

So this much works and produces the graph I want, except the error bars.

```<code>ggplot(df.forest, aes(y=ID, x=g,  shape = iv.domain, size = plot.weight))+
 geom_point(aes(size = iv.domain))+
 scale_shape_manual(name = "IV Domain",
                 values = c(15, 16, 17, 5),
                 labels = c("Abstraction", "Social", "Temporal",
 "Summary\neffects"))+
 ylab("Refrence")+
 scale_x_continuous(limits=c(-1.5,2.5), name='Effect size (g)')+
 geom_vline(xintercept=0, color='dark grey', linetype='dotted')+
 facet_grid(dv.level~., scales= 'free', space='free')+
 theme_bw()+
 theme(panel.grid.major=element_blank(),
    panel.grid.minor=element_blank(),
    panel.border=element_blank(),
    axis.line=element_line(),
    text=element_text(family='Times'),
    plot.caption=element_text(hjust = 0, vjust = -7),
    plot.margin = unit(c(.25,.25,.75,.25), "cm"))+
 guides(size = FALSE) +
 scale_size_discrete(range = c(1.5,4.5))
</code>```

But if I add: + geom_errorbarh(aes(xmin=gLL, xmax=gUL),height=.3), (where gLL and gUL are numeric values representing the 95% CI lower/upper limits), it gives me an error:

Error: Continuous value supplied to discrete scale.

However, if I enter factorized versions of gLL and gUL: + geom_errorbarh(aes(xmin=gLL.f, xmax=gUL.f),height=.3), it give me the opposite error:

Error: Discrete value supplied to continuous scale.

I've searched high and low, and can't seem to find where anyone has had problems with a function saying something is supposed to be discrete when you enter it as continuous, but saying something is supposed to be continuous when you enter it as discrete.

Moreover, I don't have a clue why it worked yesterday, yet won't work today. I've restarted R/cleared my environment, and gone back through my whole script line by line to make sure nothing leading up to this error was off, but I can't find anything. I've tried adding the aes() from geom_errorbarh to the ggplot(aes()) instead, but that doesn't change anything either. And again, if I run these lines without geom_errorbarh, it makes the exact graph I want minus the error bars, so the error is definitely in that line.

Any help at all would be greatly appreciated!

Cheers!

Edit: Thanks to @eipi10 I figured it out. I had overlooked where I had changed what my size aes() variable was  (and didn't think about it since it ran just fine until you added in the geom_errorbarh line). That also explains why it was making me use scale_size_discrete which wasn't making sense, but it worked, so I went with it. Anyway, once I deleted the aes() within geom_point(), and changed scale_size_discrete to scale_size, it worked!! Thank you! -AE

答: This is occurring because you have two size mappings, size = plot.weight in the main ggplot call and size=iv.domain in geom_point. The first is continuous and the second is discrete. You can have one or the other, but not both, and the scale_size_*** call has to match the type of variable (continuous or discrete) that you map to size.

Body:
I am working on creating a forest plot for a meta analysis using ggplot2.
Here is what an earlier version/incomplete graph looked like.

My problem is now that I'm going to back to work on it some more, everything works except I cant get the error bars with geom_errorbarh.

Data:   Here is a data file from dput on my dropbox. For the life of me, I can't figure out how to get it to paste direct on here in a way that would copy-and-paste into R without having problems. Anyway, if you just save that file (q.df) and run df.forest <- dget("your-path/q.df"), you'll have a usable df. (Note: this is parsed down from the full df that I'm working with to only include the variables needed for this particular plot, but if something doesn't make sense, just let me know and I'll try to clarify.)

So this much works and produces the graph I want, except the error bars.

ggplot(df.forest, aes(y=ID, x=g,  shape = iv.domain, size = plot.weight))+
 geom_point(aes(size = iv.domain))+
 scale_shape_manual(name = "IV Domain",
                 values = c(15, 16, 17, 5),
                 labels = c("Abstraction", "Social", "Temporal",
 "Summary\neffects"))+
 ylab("Refrence")+
 scale_x_continuous(limits=c(-1.5,2.5), name='Effect size (g)')+
 geom_vline(xintercept=0, color='dark grey', linetype='dotted')+
 facet_grid(dv.level~., scales= 'free', space='free')+
 theme_bw()+
 theme(panel.grid.major=element_blank(),
    panel.grid.minor=element_blank(),
    panel.border=element_blank(),
    axis.line=element_line(),
    text=element_text(family='Times'),
    plot.caption=element_text(hjust = 0, vjust = -7),
    plot.margin = unit(c(.25,.25,.75,.25), "cm"))+
 guides(size = FALSE) +
 scale_size_discrete(range = c(1.5,4.5))

But if I add: + geom_errorbarh(aes(xmin=gLL, xmax=gUL),height=.3), (where gLL and gUL are numeric values representing the 95% CI lower/upper limits), it gives me an error:

Error: Continuous value supplied to discrete scale.

However, if I enter factorized versions of gLL and gUL: + geom_errorbarh(aes(xmin=gLL.f, xmax=gUL.f),height=.3), it give me the opposite error:

Error: Discrete value supplied to continuous scale.

I've searched high and low, and can't seem to find where anyone has had problems with a function saying something is supposed to be discrete when you enter it as continuous, but saying something is supposed to be continuous when you enter it as discrete.

Moreover, I don't have a clue why it worked yesterday, yet won't work today. I've restarted R/cleared my environment, and gone back through my whole script line by line to make sure nothing leading up to this error was off, but I can't find anything. I've tried adding the aes() from geom_errorbarh to the ggplot(aes()) instead, but that doesn't change anything either. And again, if I run these lines without geom_errorbarh, it makes the exact graph I want minus the error bars, so the error is definitely in that line.

Any help at all would be greatly appreciated!

Cheers!

Edit: Thanks to @eipi10 I figured it out. I had overlooked where I had changed what my size aes() variable was  (and didn't think about it since it ran just fine until you added in the geom_errorbarh line). That also explains why it was making me use scale_size_discrete which wasn't making sense, but it worked, so I went with it. Anyway, once I deleted the aes() within geom_point(), and changed scale_size_discrete to scale_size, it worked!! Thank you! -AE


答:
You can, but don't

Technically a single database field can store multiple values by storing them in a comma-separated string, or a JSON-encoded string. Many newer versions of MySql also support storing complex objects in a Json Datatype, which can hold just about anything. However, it is usually a bad idea to do this, and goes against the intent of a relational database.

Instead consider creating a separate column for each value.

Better, store optional values in another table.

Rather than attempting to define a single column to store varying data, create a new table, which references the rows on the first table. Below is an example of a Many-to-One data relationship which would solve your problem.

```<code>table a
-------
id, name, column1
1,  'A',  1
2,  'B',  5

table b
-------
id, a_id, column2
81, 1,    3
82, 1,    5
83, 1,    8
94, 2,    1
95, 2,    2
96, 2,    3
97, 2,    4
98, 2,    5
</code>```

By joining these two table, you have a similar result set which is both much more flexible, and sortable/searchable/filterable.

```<code>SELECT a.id, a.name, a.column1, b.column2
FROM a
LEFT JOIN b ON a.id = b.a_id
</code>```

Title: phpmyadmin multiple values in one column

Body:
I would like to ask you, does it possible to create a column in phpmyadmin where I could insert (import) more than one value in one column. As example I create a table with name mytable then added column1 (with value 1) and now i would like to add column2(with values 3 5 8).

When I try to do that it only show column2 with value 3 in it... It ignores 5 and 8.

Body:
You can, but don't

Technically a single database field can store multiple values by storing them in a comma-separated string, or a JSON-encoded string. Many newer versions of MySql also support storing complex objects in a Json Datatype, which can hold just about anything. However, it is usually a bad idea to do this, and goes against the intent of a relational database.

Instead consider creating a separate column for each value.

Better, store optional values in another table.

Rather than attempting to define a single column to store varying data, create a new table, which references the rows on the first table. Below is an example of a Many-to-One data relationship which would solve your problem.

table a
-------
id, name, column1
1,  'A',  1
2,  'B',  5

table b
-------
id, a_id, column2
81, 1,    3
82, 1,    5
83, 1,    8
94, 2,    1
95, 2,    2
96, 2,    3
97, 2,    4
98, 2,    5

By joining these two table, you have a similar result set which is both much more flexible, and sortable/searchable/filterable.

SELECT a.id, a.name, a.column1, b.column2
FROM a
LEFT JOIN b ON a.id = b.a_id


问:
Website Messed Up Only If Accessed In Past
So my website: ropinranch.com

looks FINE on any browser (so far) if you haven't accessed the page in the past. But for any of my previous users, it looks messed up when they load it.

We've all cleared all of our cookies, and emptied our cache. I even edited a new image on the page to see if that would change and it DID.

I cannot think any other way the page would be keeping memory of it.
One of my testers said that if they had the page bookmarked in the past of it working fine, that when clicking on the bookmark it loads fine still -- but typing in a URL fails.

Any other ideas on what I'm missing here?

Update: I realized what happened -- but I'm unsure how to fix.
https://ropinranch.com WORKS
but
www.ropinranch.com does not. I know theres a setting in my c-pannel to change this but I don't know what it's called

答:
This helped me temporarily:

By Varun: If you are just testing, could you try passing a timestamp or random number in the URL ( manually , just for testing ) and check. Eg : http://ropinranch.com?f=141414542343 (each time with a diff number )

But What I did was I had to go through the server and reroute all traffic to my SSL site rather than things of www. or http://