问:
How can I speed up reading multiple files and putting the data into a dataframe?
I have a number of text files, say 50, that I need to read into a massive dataframe. At the moment, I am using the following steps.

Read every file and check what the labels are. The information I need is often contained in the first few lines. The same labels just repeat for the rest of the file, with different types of data listed against them each time.

Create a dataframe with those labels.

Read the file again and fill the dataframe with values.

Concatenate that dataframe with a master dataframe.

This works pretty well for files that are of the 100 KB size - a few minutes, but at 50 MB, it just takes hours, and is not practical.

How can I optimise my code? In particular -

How can I identify what functions are taking the most time, which I need to optimise? Is it the reading of the file? Is it the writing to the dataframe? Where is my program spending time?

Should I consider multithreading or multiprocessing?

Can I improve the algorithm?

Perhaps read the entire file in in one go into a list, rather than line by line,

Parse data in chunks/entire file, rather than line by line,

Assign data to the dataframe in chunks/one go, rather than row by row.

Is there anything else that I can do to make my code execute faster?

Here is an example code. My own code is a little more complex, as the text files are more complex such that I have to use about 10 regular expressions and multiple while loops to read the data in and allocate it to the right location in the right array. To keep the MWE simple, I haven't used repeating labels in the input files for the MWE either, so it would like I'm reading the file twice for no reason. I hope that makes sense!

```<code>import re
import pandas as pd

df = pd.DataFrame()
paths = ["../gitignore/test1.txt", "../gitignore/test2.txt"]
reg_ex = re.compile('^(.+) (.+)\n')
# read all files to determine what indices are available
for path in paths:
    file_obj = open(path, 'r')
    print file_obj.readlines()

['a 1\n', 'b 2\n', 'end']
['c 3\n', 'd 4\n', 'end']

indices = []
for path in paths:
    index = []
    with open(path, 'r') as file_obj:
        line = True
        while line:
            try:
                line = file_obj.readline()
                match = reg_ex.match(line)
                index += match.group(1)
            except AttributeError:
                pass
    indices.append(index)
# read files again and put data into a master dataframe
for path, index in zip(paths, indices):
    subset_df = pd.DataFrame(index=index, columns=["Number"])
    with open(path, 'r') as file_obj:
        line = True
        while line:
            try:
                line = file_obj.readline()
                match = reg_ex.match(line)
                subset_df.loc[[match.group(1)]] = match.group(2)
            except AttributeError:
                pass
    df = pd.concat([df, subset_df]).sort_index()
print df

  Number
a      1
b      2
c      3
d      4
</code>```

My input files:

test1.txt

```<code>a 1
b 2
end
</code>```

test2.txt

```<code>c 3
d 4
end
</code>```

答:
First of all, if you are reading the file in multiple times, it seems like that would be the bottleneck.  Try reading the file into 1 string object and then using cStringIO on it multiple times.

Second, you haven't really shown any reason to build the indices before reading in all the files.  Even if you do, why are you using Pandas for IO?  It seems like you can build it up in regular python data structures (maybe using __slots__) and then put it in the master dataframe.  If you don't need file X index before you read file Y (as you 2nd loop seems to suggest), you just need to loop over the files once.

Third, you can either use simple split/strip on the strings to pull out space separated tokens, or if it's more complicated (there are string quotes and such) use the CSV module from Python's standard library.  Until you show how you actually build up your data, it's hard to suggest a fix related to that.

What you have shown so far can be done fairly quickly with the simple

```<code>for path in paths:
    data = []
    with open(path, 'r') as file_obj:
        for line in file_obj:
            try:
                d1, d2 = line.strip().split()
            except ValueError:
                pass
            data.append(d1, int(d2)))
    index, values = zip(*data)
    subset_df = pd.DataFrame({"Number": pd.Series(values, index=index)})
</code>```

Here's the difference in timings when I run on a virtual machine with the disk space not pre-allocated (the generated files are roughly 24MB in size):

```<code>import pandas as pd
from random import randint
from itertools import combinations
from posix import fsync

outfile = "indexValueInput"

for suffix in ('1', '2'):
    with open(outfile+"_" + suffix, 'w') as f:
        for i, label in enumerate(combinations([chr(i) for i in range(ord('a'), ord('z')+1)], 8)) :
            val = randint(1, 1000000)
            print >>f, "%s %d" % (''.join(label), val)
            if i > 3999999:
                break
        print >>f, "end"
        fsync(f.fileno())

def readWithPandas():
    data = []
    with open(outfile + "_2", 'r') as file_obj:
        for line in file_obj:
            try:
                d1, d2 = str.split(line.strip())
            except ValueError:
                pass
            data.append((d1, int(d2)))
    index, values = zip(*data)
    subset_df = pd.DataFrame({"Numbers": pd.Series(values, index=index)})

def readWithoutPandas():
    data = []
    with open(outfile+"_1", 'r') as file_obj:
        for line in file_obj:
            try:
                d1, d2 = str.split(line.strip())
            except ValueError:
                pass
            data.append((d1, int(d2)))
    index, values = zip(*data)

def time_func(func, *args):
    import time
    print "timing function", str(func.func_name)
    tStart = time.clock()
    func(*args)
    tEnd = time.clock()
    print "%f seconds " % (tEnd - tStart)

time_func(readWithoutPandas)
time_func(readWithPandas)
</code>```

The resulting times are:

```<code>timing function readWithoutPandas
4.616853 seconds
timing function readWithPandas
4.931765 seconds
</code>```

You can try these functions with your index buildup and see what the difference in time would be.  It is almost certain that the slow down comes from multiple disk reads.  And since Pandas will take no time to build up your dataframe from a dictionary, you are better off figuring out how to build up your index in pure Python before passing the data to Pandas.  But do both the data read and the build up of the index in 1 disk read.

I guess one other caveat is that if you print from inside of your code, expect that to take a huge amount of time.  The time it takes to write plain text to a tty dwarves the time it takes to read/write to disk.

Body:
I have a number of text files, say 50, that I need to read into a massive dataframe. At the moment, I am using the following steps.

Read every file and check what the labels are. The information I need is often contained in the first few lines. The same labels just repeat for the rest of the file, with different types of data listed against them each time.

Create a dataframe with those labels.

Read the file again and fill the dataframe with values.

Concatenate that dataframe with a master dataframe.

This works pretty well for files that are of the 100 KB size - a few minutes, but at 50 MB, it just takes hours, and is not practical.

How can I optimise my code? In particular -

How can I identify what functions are taking the most time, which I need to optimise? Is it the reading of the file? Is it the writing to the dataframe? Where is my program spending time?

Should I consider multithreading or multiprocessing?

Can I improve the algorithm?

Perhaps read the entire file in in one go into a list, rather than line by line,

Parse data in chunks/entire file, rather than line by line,

Assign data to the dataframe in chunks/one go, rather than row by row.

Is there anything else that I can do to make my code execute faster?

Here is an example code. My own code is a little more complex, as the text files are more complex such that I have to use about 10 regular expressions and multiple while loops to read the data in and allocate it to the right location in the right array. To keep the MWE simple, I haven't used repeating labels in the input files for the MWE either, so it would like I'm reading the file twice for no reason. I hope that makes sense!

import re
import pandas as pd

df = pd.DataFrame()
paths = ["../gitignore/test1.txt", "../gitignore/test2.txt"]
reg_ex = re.compile('^(.+) (.+)\n')
# read all files to determine what indices are available
for path in paths:
    file_obj = open(path, 'r')
    print file_obj.readlines()

['a 1\n', 'b 2\n', 'end']
['c 3\n', 'd 4\n', 'end']

indices = []
for path in paths:
    index = []
    with open(path, 'r') as file_obj:
        line = True
        while line:
            try:
                line = file_obj.readline()
                match = reg_ex.match(line)
                index += match.group(1)
            except AttributeError:
                pass
    indices.append(index)
# read files again and put data into a master dataframe
for path, index in zip(paths, indices):
    subset_df = pd.DataFrame(index=index, columns=["Number"])
    with open(path, 'r') as file_obj:
        line = True
        while line:
            try:
                line = file_obj.readline()
                match = reg_ex.match(line)
                subset_df.loc[[match.group(1)]] = match.group(2)
            except AttributeError:
                pass
    df = pd.concat([df, subset_df]).sort_index()
print df

  Number
a      1
b      2
c      3
d      4

My input files:

test1.txt

a 1
b 2
end

test2.txt

c 3
d 4
end

Body:
First of all, if you are reading the file in multiple times, it seems like that would be the bottleneck.  Try reading the file into 1 string object and then using cStringIO on it multiple times.

Second, you haven't really shown any reason to build the indices before reading in all the files.  Even if you do, why are you using Pandas for IO?  It seems like you can build it up in regular python data structures (maybe using __slots__) and then put it in the master dataframe.  If you don't need file X index before you read file Y (as you 2nd loop seems to suggest), you just need to loop over the files once.

Third, you can either use simple split/strip on the strings to pull out space separated tokens, or if it's more complicated (there are string quotes and such) use the CSV module from Python's standard library.  Until you show how you actually build up your data, it's hard to suggest a fix related to that.

What you have shown so far can be done fairly quickly with the simple

for path in paths:
    data = []
    with open(path, 'r') as file_obj:
        for line in file_obj:
            try:
                d1, d2 = line.strip().split()
            except ValueError:
                pass
            data.append(d1, int(d2)))
    index, values = zip(*data)
    subset_df = pd.DataFrame({"Number": pd.Series(values, index=index)})

Here's the difference in timings when I run on a virtual machine with the disk space not pre-allocated (the generated files are roughly 24MB in size):

import pandas as pd
from random import randint
from itertools import combinations
from posix import fsync

outfile = "indexValueInput"

for suffix in ('1', '2'):
    with open(outfile+"_" + suffix, 'w') as f:
        for i, label in enumerate(combinations([chr(i) for i in range(ord('a'), ord('z')+1)], 8)) :
            val = randint(1, 1000000)
            print >>f, "%s %d" % (''.join(label), val)
            if i > 3999999:
                break
        print >>f, "end"
        fsync(f.fileno())

def readWithPandas():
    data = []
    with open(outfile + "_2", 'r') as file_obj:
        for line in file_obj:
            try:
                d1, d2 = str.split(line.strip())
            except ValueError:
                pass
            data.append((d1, int(d2)))
    index, values = zip(*data)
    subset_df = pd.DataFrame({"Numbers": pd.Series(values, index=index)})

def readWithoutPandas():
    data = []
    with open(outfile+"_1", 'r') as file_obj:
        for line in file_obj:
            try:
                d1, d2 = str.split(line.strip())
            except ValueError:
                pass
            data.append((d1, int(d2)))
    index, values = zip(*data)

def time_func(func, *args):
    import time
    print "timing function", str(func.func_name)
    tStart = time.clock()
    func(*args)
    tEnd = time.clock()
    print "%f seconds " % (tEnd - tStart)

time_func(readWithoutPandas)
time_func(readWithPandas)

The resulting times are:

timing function readWithoutPandas
4.616853 seconds
timing function readWithPandas
4.931765 seconds

You can try these functions with your index buildup and see what the difference in time would be.  It is almost certain that the slow down comes from multiple disk reads.  And since Pandas will take no time to build up your dataframe from a dictionary, you are better off figuring out how to build up your index in pure Python before passing the data to Pandas.  But do both the data read and the build up of the index in 1 disk read.

I guess one other caveat is that if you print from inside of your code, expect that to take a huge amount of time.  The time it takes to write plain text to a tty dwarves the time it takes to read/write to disk.


来源: stackexchange

问:
How do you access url args in react-router-dom 4 when using Route render prop instead of Route component prop?
I am using react-router-dom v 4.0.0.

In my top-level <App /> component that renders my react router, I have three routes.  The first two work as expected, the third one does not.

```<code>render() {
    const pageMain = (
        <PageMain token={this.state.token} />
    );
    const pageActivity = (
        <PageActivity
            projectActivities={this.state.projectActivities}
            projectActivitiesMap={this.state.projectActivitiesMap} />
    );
    return (<Router>
        <div>
            <Route
                path="/"
                component={PageSplash}
            />
            <Route
                path="/app"
                render={props => pageMain}
            />
            <Route
                path="/activity/:activityId/"
                render={props => pageActivity}
            />
        </div>
    </Router>);
}
</code>```

When I go to www.example.com/, the router directs me to my PageSplash component as expected.

When I go to www.example.com/app, the router directs me to my PageMain component as expected.  Further, in my PageMain component, I have access to this.props.token as expected.

When I go to www.example.com/activity/12345/, the router directs me to my PageActivity component as expected.  In my PageActivity component, I have access to this.props.projectActivities and this.props.projectActivitiesMap as expected.  However, I'd like to be able to access the activityId from the url, which should be 12345 in this case.  In PageActivity, I don't receive this.props.params as I thought, from reading countless pages of documentation.

I started by using simple routes like my first one.  Then I needed to pass data from my top-level component to the /app route, so I begin using the <Route /> render prop instead of the component prop.  This works fine.  Then I needed to pass data and access the url param.  I can access the passed props, but my PageActivity component isn't receiving a params prop.  How do I access the activityId in my PageActivity component?

答:
I figured out how to do this.  I needed to inline my PageActivity component, and add {...props}.  The problematic route looks like this now:

```<code><Route path="/activity/:activityId/" render={props => (
    <PageActivity
        projectActivities={this.state.projectActivities}
        projectActivitiesMap={this.state.projectActivitiesMap}
        {...props}
    />
)} />
</code>```

Also, in react-router-dom 4.0.0, page params are passed in this.props.match.params.

ContentLicense: CC BY-SA 3.0

Body:
I am using react-router-dom v 4.0.0.

In my top-level <App /> component that renders my react router, I have three routes.  The first two work as expected, the third one does not.

render() {
    const pageMain = (
        <PageMain token={this.state.token} />
    );
    const pageActivity = (
        <PageActivity
            projectActivities={this.state.projectActivities}
            projectActivitiesMap={this.state.projectActivitiesMap} />
    );
    return (<Router>

            <Route
                path="/"
                component={PageSplash}
            />
            <Route
                path="/app"
                render={props => pageMain}
            />
            <Route
                path="/activity/:activityId/"
                render={props => pageActivity}
            />

    </Router>);
}

When I go to www.example.com/, the router directs me to my PageSplash component as expected.

When I go to www.example.com/app, the router directs me to my PageMain component as expected.  Further, in my PageMain component, I have access to this.props.token as expected.

When I go to www.example.com/activity/12345/, the router directs me to my PageActivity component as expected.  In my PageActivity component, I have access to this.props.projectActivities and this.props.projectActivitiesMap as expected.  However, I'd like to be able to access the activityId from the url, which should be 12345 in this case.  In PageActivity, I don't receive this.props.params as I thought, from reading countless pages of documentation.

I started by using simple routes like my first one.  Then I needed to pass data from my top-level component to the /app route, so I begin using the <Route /> render prop instead of the component prop.  This works fine.  Then I needed to pass data and access the url param.  I can access the passed props, but my PageActivity component isn't receiving a params prop.  How do I access the activityId in my PageActivity component?

Body:
I figured out how to do this.  I needed to inline my PageActivity component, and add {...props}.  The problematic route looks like this now:

<Route path="/activity/:activityId/" render={props => (
    <PageActivity
        projectActivities={this.state.projectActivities}
        projectActivitiesMap={this.state.projectActivitiesMap}
        {...props}
    />
)} />

Also, in react-router-dom 4.0.0, page params are passed in this.props.match.params.


问:
Put the variables that returned false in their own array
My code prints "zach" into a separate array. My "isNonStopWord" looks to see if any of the words in skoal appear in "zach". If they do it returns false next to these words that appear in both and true next to every word in "zach" that is not in "skoal" all I am trying to do now is to put all of the words that returned false into their own array and I cannot figure out how to do it. If you have an idea please let me know.   </p>

```<code>  package zk;

 import java.util.Arrays;
 public class Class {

 public boolean isNonStopWord(String x, String[] y) {

    if (Arrays.asList(y).contains(x)) {
        return false;
    }
    return true;
}

public static void main(String [] args) {
    Class cs = new Class();

    String zach = ("Amazon offered up more answers Thursday about what"
            + " caused a bunch of websites to fail two days ago. According "
            + "to a postmortem by the company's cloud services business, "
            + "around 9:37 a.m. PT Tuesday an Amazon worker incorrectly"
            + " punched in a command while trying to debug an issue. "
            + "That command shut down a large set of servers at Amazon Web "
            + "Services' Northern Virginia site, causing a domino effect of"
            + " problems. Other services that relied on those S3 cloud"
            + " storage servers were disrupted. Also, removing so much "
            + "server capacity required a full system restart, which then "
            + "took longer than expected, AWS said. The sites affected "
            + "included Quora, Imgur, IFTTT, Giphy and Slack. Amazon was "
            + "able to fix the issue by about 2 p.m. PT.");

    String [] skoal = {"THE", "BE", "TO", "OF", "AND", "A", "IN",
            "THAT", "I", "IT", "ON", "IN", "BUT", "IS", "WITH"};

    zach = zach.replace(",","");
    zach = zach.replace(".","");
    zach = zach.toUpperCase();
    String [] strings = zach.split(" ");

int july = 0;

    for (String s1: strings)
    {
        boolean answer = cs.isNonStopWord(s1,skoal);
        System.out.println((s1) + "  " + (answer));
        if(answer==false){
            july++;
    }
  }

    System.out.println("There are " + july +" " + "non-stop words");
    zach = "...";

 }
</code>```

答:
Your question is not very clear, I sounds like you are asking for a way to print the false and true words separately.

First thing I did is change your last if statement to an if else, and place the System.out.println((s1) + "  " + (answer)); statement within the else part of the if else. Then I put a statement that would add s1 to the ArrayList of false words and placed that statement within the if part of the if else.

Finally, i used a for loop to cycle through the false word and print them followed by "false". Take a look:

```<code>        ArrayList<String> list = new ArrayList<String>(); //Create an ArrayList for the false words

        for (String s1: strings)
        {
            boolean answer = cs.isNonStopWord(s1,skoal);
            if(answer==false){
                july++;
                list.add(s1); //If the word is false, add it to the list
        }else{
            System.out.println((s1) + "  " + (answer)); //If the word is true, print it
        }
      }

        String[] falses = new String[list.size()]; //
        falses = list.toArray(falses);             // Convert the ArrayList to a regular array for processing

        for(int i = 0; i < list.size(); i++){         //
            System.out.println(falses[i] + " false"); // Cycle through the array of false words and print them followed by "false"
        }                                             //

        System.out.println("There are " + july +" " + "non-stop words");
        zach = "...";
        }
</code>```

Body:
My code prints "zach" into a separate array. My "isNonStopWord" looks to see if any of the words in skoal appear in "zach". If they do it returns false next to these words that appear in both and true next to every word in "zach" that is not in "skoal" all I am trying to do now is to put all of the words that returned false into their own array and I cannot figure out how to do it. If you have an idea please let me know.

  package zk;

 import java.util.Arrays;
 public class Class {

 public boolean isNonStopWord(String x, String[] y) {

    if (Arrays.asList(y).contains(x)) {
        return false;
    }
    return true;
}

public static void main(String [] args) {
    Class cs = new Class();

    String zach = ("Amazon offered up more answers Thursday about what"
            + " caused a bunch of websites to fail two days ago. According "
            + "to a postmortem by the company's cloud services business, "
            + "around 9:37 a.m. PT Tuesday an Amazon worker incorrectly"
            + " punched in a command while trying to debug an issue. "
            + "That command shut down a large set of servers at Amazon Web "
            + "Services' Northern Virginia site, causing a domino effect of"
            + " problems. Other services that relied on those S3 cloud"
            + " storage servers were disrupted. Also, removing so much "
            + "server capacity required a full system restart, which then "
            + "took longer than expected, AWS said. The sites affected "
            + "included Quora, Imgur, IFTTT, Giphy and Slack. Amazon was "
            + "able to fix the issue by about 2 p.m. PT.");

    String [] skoal = {"THE", "BE", "TO", "OF", "AND", "A", "IN",
            "THAT", "I", "IT", "ON", "IN", "BUT", "IS", "WITH"};

    zach = zach.replace(",","");
    zach = zach.replace(".","");
    zach = zach.toUpperCase();
    String [] strings = zach.split(" ");

int july = 0;

    for (String s1: strings)
    {
        boolean answer = cs.isNonStopWord(s1,skoal);
        System.out.println((s1) + "  " + (answer));
        if(answer==false){
            july++;
    }
  }

    System.out.println("There are " + july +" " + "non-stop words");
    zach = "...";

 }

Body:
Your question is not very clear, I sounds like you are asking for a way to print the false and true words separately.

First thing I did is change your last if statement to an if else, and place the System.out.println((s1) + "  " + (answer)); statement within the else part of the if else. Then I put a statement that would add s1 to the ArrayList of false words and placed that statement within the if part of the if else.

Finally, i used a for loop to cycle through the false word and print them followed by "false". Take a look:

        ArrayList<String> list = new ArrayList<String>(); //Create an ArrayList for the false words

        for (String s1: strings)
        {
            boolean answer = cs.isNonStopWord(s1,skoal);
            if(answer==false){
                july++;
                list.add(s1); //If the word is false, add it to the list
        }else{
            System.out.println((s1) + "  " + (answer)); //If the word is true, print it
        }
      }

        String[] falses = new String[list.size()]; //
        falses = list.toArray(falses);             // Convert the ArrayList to a regular array for processing

        for(int i = 0; i < list.size(); i++){         //
            System.out.println(falses[i] + " false"); // Cycle through the array of false words and print them followed by "false"
        }                                             //

        System.out.println("There are " + july +" " + "non-stop words");
        zach = "...";
        }


问:
Click to create tag / label random but start from label-default
When I click on my button I am trying to create a bootstrap label. But each time I click it should start off at label-default and work through the switch until it gets to the last one the go back to the beginning

As shown on image below it not starting off at label-default

Question each time I click on the button to create label how can I
  make sure it does not double up and starts from label-default

DEMO

CODEPEN DEMO

SCRIPT

```<code>$(document).on('click', '#category_button', function(e){

    e.preventDefault();

    //if ($("#label-" + category_name).length  == 0) {

        var rand = Math.floor((Math.random() * 5) + 1);

        switch(rand){
          case 1:
            element = 'label-default';
            break;
          case 2:
            element = 'label-primary';
            break;
          case 3:
            element = 'label-success';
            break;
          case 4:
            element = 'label-info';
            break;
          case 5:
            element = 'label-warning';
            break;
        }

        html = '';
        html += '<li id="">';
        html += '<span class="label ' + element + '">';
        html += 'Hello';
        html += '</span>';
        html += '</li>';

        $('.categories ul').append(html);
    //}
});
</code>```

答:
Not sure if I misunderstood your question, but you are using a random to decide which label to add. If you want an ordered sequence, you should not be using random. Code shown below:</p>

```<code>var counter = 0;
$(document).on('click', '#category_button', function(e){
  e.preventDefault();
    switch(counter) {
      case 0:
        element = 'label-default';
        break;
      case 1:
        element = 'label-primary';
        break;
      case 2:
        element = 'label-success';
        break;
      case 3:
        element = 'label-info';
        break;
      case 4:
        element = 'label-warning';
        break;
    }

    counter = (counter + 1) % 5;

    var html = '';
    html += '<li id="">';
    html += '<span class="label ' + element + '">';
    html += 'Hello';
    html += '</span>';
    html += '</li>';

    $('.categories ul').append(html);
  //}
});
</code>```

Body:
When I click on my button I am trying to create a bootstrap label. But each time I click it should start off at label-default and work through the switch until it gets to the last one the go back to the beginning

As shown on image below it not starting off at label-default

Question each time I click on the button to create label how can I
  make sure it does not double up and starts from label-default

DEMO

CODEPEN DEMO

SCRIPT

$(document).on('click', '#category_button', function(e){

    e.preventDefault();

    //if ($("#label-" + category_name).length  == 0) {

        var rand = Math.floor((Math.random() * 5) + 1);

        switch(rand){
          case 1:
            element = 'label-default';
            break;
          case 2:
            element = 'label-primary';
            break;
          case 3:
            element = 'label-success';
            break;
          case 4:
            element = 'label-info';
            break;
          case 5:
            element = 'label-warning';
            break;
        }

        html = '';
        html += '
';
        html += '';
        html += 'Hello';
        html += '';
        html += '
';

        $('.categories ul').append(html);
    //}
});

Body:
Not sure if I misunderstood your question, but you are using a random to decide which label to add. If you want an ordered sequence, you should not be using random. Code shown below:

var counter = 0;
$(document).on('click', '#category_button', function(e){
  e.preventDefault();
    switch(counter) {
      case 0:
        element = 'label-default';
        break;
      case 1:
        element = 'label-primary';
        break;
      case 2:
        element = 'label-success';
        break;
      case 3:
        element = 'label-info';
        break;
      case 4:
        element = 'label-warning';
        break;
    }

    counter = (counter + 1) % 5;

    var html = '';
    html += '<li id="">';
    html += '<span class="label ' + element + '">';
    html += 'Hello';
    html += '</span>';
    html += '</li>';

    $('.categories ul').append(html);
  //}
});


问:
Upload an Excel File using Jquery
I want to upload an Excel file using Jquery through RestEasy Service which consumes multipart/form-data. Whether I want to use Ajax for File upload or simple Jquery/Javascript is more enough. If I want to use only Ajax means, what kind of content-type do I have to post for upload?

This is my HTML & Jquery Code.

```<code><script type="Javascript">
    $(document).ready(function () {
        //var filename = document.getElementById("uploadedFile").value;
        var filename = $("#uploadedFile").val();
        //alert(filename);
        jQuery("#Upload").click(function () {
            $.ajax({
                url: 'service url',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                // enctype: 'multipart/form-data',
                data: {
                    file: filename
                },
                cache: false,
                success: function (data) {
                    alert('success');
                    return false;
                },
                error: function (data, status) {
                    alert("failue");
                    alert(status);
                }
            });
        });
    });
</script>

<input type="file"  name="uploadedFile" id="uploadedFile" size="30" ><br><br>
<input type="button" id="Upload" name="Upload" value="Upload"  style="width:72px;height:23px;">
</code>```

答:
If you are using HTML5, this should be easy.

This is how I did with the file upload

HTML,

```<code><form method="POST" enctype="multipart/form-data"
      action="/file/upload" style="display: none">
      <input type="file" name="file"  multiple="multiple" id="uploadImages">
</form>
</code>```

JS,

```<code>$('#uploadImages').on('change', function (){
            var formData = new FormData();
            for(var i = 0; i < this.files.length; i++){
                formData.append('file', this.files[i]);

                $.ajax({
                    url : '/file/upload',
                    type : 'post',
                    data : formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success : function () {
                        alert("upload successfully")
                    }
                })

            }
        }
        $('form')[0].reset();
    })
</code>```

Title: Upload an Excel File using Jquery

Body:
I want to upload an Excel file using Jquery through RestEasy Service which consumes multipart/form-data. Whether I want to use Ajax for File upload or simple Jquery/Javascript is more enough. If I want to use only Ajax means, what kind of content-type do I have to post for upload?

This is my HTML & Jquery Code.

<input type="file"  name="uploadedFile" id="uploadedFile" size="30" >

<input type="button" id="Upload" name="Upload" value="Upload"  style="width:72px;height:23px;">

Body:
If you are using HTML5, this should be easy.

This is how I did with the file upload

HTML,

<form method="POST" enctype="multipart/form-data"
      action="/file/upload" style="display: none">
      <input type="file" name="file"  multiple="multiple" id="uploadImages">
</form>

JS,

$('#uploadImages').on('change', function (){
            var formData = new FormData();
            for(var i = 0; i < this.files.length; i++){
                formData.append('file', this.files[i]);

                $.ajax({
                    url : '/file/upload',
                    type : 'post',
                    data : formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success : function () {
                        alert("upload successfully")
                    }
                })

            }
        }
        $('form')[0].reset();
    })


问:
How do I change the font size when printing from Eclipse?
Sometimes I'd like to print my code and read it during lunch. In Eclipse I'm using 10pt Helvetica font, but printing at this size is a waste of paper I think. I changed to font size 6pt, and the print was perfect; fully readable and paper saving.

However, coding in 6pt font is very hard and stressing for my eyes, so I cannot keep the setting. Also, changing font size everytime I print is a pain.

Is there a way to keep 10pt for my editor AND have the printer run at 6pt, at the same time?

答:
Using Mars.1 Release (4.5.1) I still see this as a problem. I tried the scaling in the printer dialog as suggested by Allen and Eclipsed, and my Brother printer under Windows used just as much paper, using same page breaks, leaving white space at bottom of each page.

So do an experiment with a small selection before trying this. Your mileage may vary.

I'm almost ashamed to admit it, but, so that I could get colors, and preview before printing, I ended up pasting into Microsoft Word and printing from there.


问:
Convert float number from nonuniform ranges
So I have this, relatively easy, problem and wondering if the solution for it already exists.

I have to convert a value from one range to another. If there was just one range, like this:

```<code> {-30.0, 30.0} -> {25.0, 50.0}
</code>```

that would have been easy.
But I have a set of ranges:

```<code> {-30.0, -20.0} -> {25.0, 30.0}
 {-20.0,   0.0} -> {30.0, 40.0}
 {  0.0,  30.0} -> {40.0, 50.0}
</code>```

One solution is to do a linear search on each access.
Another solution is to make the ranges to have equivalent length so that the input value could be directly mapped.

Does anyone know a better than linear search solution? Or if a container that performs this kind of conversion already exist?

Thanks so much.

答:
I assume that the range can't overlap. (both domain & range)

I suggest sorting the range.

This way, you can query the range using O(log n).

push the range into array / some std collection

using sort http://www.cplusplus.com/reference/algorithm/sort/.

To compare, use only min or only max value of the input range.

query a range using min or max (corresponding as above)

Alternative approach

In some input pattern, this approach can be appropriate :-

Convert this :-

```<code> {-30.0, -20.0} -> {25.0, 30.0}
 {-20.0,   0.0} -> {30.0, 40.0}
 {  0.0,  30.0} -> {40.0, 50.0}
</code>```

into something more uniform :-

```<code>float [] inputRange =  {-30,-20, -10,0 ,10       ,20       ,30};
float [] outputRange = {25 ,30 ,*35*,40,*43.3333*,*43.6667*,50};
//* is a pre-calculated
</code>```

Then you can query using only O(1).

Disadvantage :-

Waste more memory

The input have to be snapped with some not-so-tiny value. (This case = 10)

Body:
So I have this, relatively easy, problem and wondering if the solution for it already exists.

I have to convert a value from one range to another. If there was just one range, like this:

 {-30.0, 30.0} -> {25.0, 50.0}

that would have been easy.
But I have a set of ranges:

 {-30.0, -20.0} -> {25.0, 30.0}
 {-20.0,   0.0} -> {30.0, 40.0}
 {  0.0,  30.0} -> {40.0, 50.0}

One solution is to do a linear search on each access.
Another solution is to make the ranges to have equivalent length so that the input value could be directly mapped.

Does anyone know a better than linear search solution? Or if a container that performs this kind of conversion already exist?

Thanks so much.

Body:
I assume that the range can't overlap. (both domain & range)

I suggest sorting the range.

This way, you can query the range using O(log n).

push the range into array / some std collection

using sort http://www.cplusplus.com/reference/algorithm/sort/.

To compare, use only min or only max value of the input range.

query a range using min or max (corresponding as above)

Alternative approach

In some input pattern, this approach can be appropriate :-

Convert this :-

 {-30.0, -20.0} -> {25.0, 30.0}
 {-20.0,   0.0} -> {30.0, 40.0}
 {  0.0,  30.0} -> {40.0, 50.0}

into something more uniform :-

float [] inputRange =  {-30,-20, -10,0 ,10       ,20       ,30};
float [] outputRange = {25 ,30 ,*35*,40,*43.3333*,*43.6667*,50};
//* is a pre-calculated

Then you can query using only O(1).

Disadvantage :-

Waste more memory

The input have to be snapped with some not-so-tiny value. (This case = 10)


问:
MVC 5 Authorize Attribute Stored Procedure not found
I'm trying to add Role Based Authorization to our webpage but having this usual error;

```<code>Could not find stored procedure 'dbo.aspnet_CheckSchemaVersion'.
</code>```

I found that usual solution is to run aspnet_regsql.exe but I'm told not to do it. Main reason being concerns about the DB state as it would add lots of tables and Stored Procedures to it.

I'm trying to find some other approach to handle this matter but so far nothing I found worked.

I checked our connection string, looks OK. I noticed it didn't have integratedsecurity part, added it. App stopped working.

Tried adding <add key="owin:AutomaticAppStartup" value="true"/> to App.Setting, didn't work either.

What else I can try?

答: You can create a custom authorization attribute by extending the authorize attribute. For more details and step by step tutorial you may refer Custom Roles Based Access Control (RBAC) in ASP.NET MVC</p>

Body:
I'm trying to add Role Based Authorization to our webpage but having this usual error;

Could not find stored procedure 'dbo.aspnet_CheckSchemaVersion'.

I found that usual solution is to run aspnet_regsql.exe but I'm told not to do it. Main reason being concerns about the DB state as it would add lots of tables and Stored Procedures to it.

I'm trying to find some other approach to handle this matter but so far nothing I found worked.

I checked our connection string, looks OK. I noticed it didn't have integratedsecurity part, added it. App stopped working.

Tried adding <add key="owin:AutomaticAppStartup" value="true"/> to App.Setting, didn't work either.

What else I can try?


问:
Ensuring subprocesses are dead on exiting Python program
Is there a way to ensure all created subprocess are dead at exit time of a Python program? By subprocess I mean those created with subprocess.Popen().

If not, should I iterate over all of the issuing kills and then kills -9? anything cleaner?

答:
Find out a solution for linux (without installing prctl):</p>

```<code>def _set_pdeathsig(sig=signal.SIGTERM):
    """help function to ensure once parent process exits, its childrent processes will automatically die
    """
    def callable():
        libc = ctypes.CDLL("libc.so.6")
        return libc.prctl(1, sig)
    return callable

subprocess.Popen(your_command, preexec_fn=_set_pdeathsig(signal.SIGTERM))
</code>```

OwnerDisplayName: J. Pablo Fernández

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Ali A

Body:
Find out a solution for linux (without installing prctl):

def _set_pdeathsig(sig=signal.SIGTERM):
    """help function to ensure once parent process exits, its childrent processes will automatically die
    """
    def callable():
        libc = ctypes.CDLL("libc.so.6")
        return libc.prctl(1, sig)
    return callable

subprocess.Popen(your_command, preexec_fn=_set_pdeathsig(signal.SIGTERM))


问:
How do I stop a MySQL decimal field from being rounded?
I have a table in MySQL with a field that is decimal, length 9, unsigned. I'm using it for prices.

After I insert the data, and query for it, it has all been rounded and the decimal has been removed.

I'm confused as to why.

Troubleshooting tips?

Host: web.com

phpMyAdmin version: 2.11.10.1

MySQL client version: 5.0.95

答:
The rounding is happening because you need to declare the precision in the type declaration</p>

```<code>create table test01 (field01 decimal(9,2));
</code>```

Body:
The rounding is happening because you need to declare the precision in the type declaration

create table test01 (field01 decimal(9,2));


问:
Form transition over image
I am basically trying to recreate the the Directions, Availability and Resident Login section about half way down this website http://www.livewestvillage.com/. I haven't had the chance to learn css all to well so if somebody could show me an example or a site that's good to learn this type of thing from I would appreciate it.

I've just been swamped at work so I don't really get as much time for personal projects like this anymore.

答:
This is the example how to achieve those effect. I already comment the css, hoping that you will learn something.

HTML

```<code><h1>
Hover Me!!
</h1>

<div class="box">

<div class="widget-image">
<img src="http://www.livewestvillage.com/media_library/2014/58c310ba3db6a855.jpg" class="img-responsive">
</div>

<div class="widget-form">
<form>
  <input type="text" name="firstname" placeholder="First Name">
  <input type="text" name="lastname" placeholder="Last Name">
</form>
</div>

</div>
</code>```

CSS

```<code>.box{
    overflow: hidden;
    position: relative;
}

input {
    display: inline-block;
    margin: 0px 6px;
    padding: 10px 10px 10px 15px;
}

.widget-form {
    padding: 43px 0px;
    width: 426px;
    height: 100%;
    background: rgba(0, 0, 0, 0.64);
    transition:all 0.5s ease-out;
    position: absolute;
    top: 250px;
    z-index: 100;
}

//set the position of the widget
.widget-image{
  width: 426px;
}

//when the mouse enter the div will scroll up
.widget-image:hover + .widget-form {
      top: 0;
}

//maintain the div position
.widget-form:hover, .widget-form:focus ,  .widget-form :active {
  top: 0;
}
</code>```

DEMO

Title: Form transition over image

Body:
This is the example how to achieve those effect. I already comment the css, hoping that you will learn something.

HTML

<h1>
Hover Me!!
</h1>

<div class="box">

<div class="widget-image">
<img src="http://www.livewestvillage.com/media_library/2014/58c310ba3db6a855.jpg" class="img-responsive">
</div>

<div class="widget-form">
<form>
  <input type="text" name="firstname" placeholder="First Name">
  <input type="text" name="lastname" placeholder="Last Name">
</form>
</div>

</div>

CSS

.box{
    overflow: hidden;
    position: relative;
}

input {
    display: inline-block;
    margin: 0px 6px;
    padding: 10px 10px 10px 15px;
}

.widget-form {
    padding: 43px 0px;
    width: 426px;
    height: 100%;
    background: rgba(0, 0, 0, 0.64);
    transition:all 0.5s ease-out;
    position: absolute;
    top: 250px;
    z-index: 100;
}

//set the position of the widget
.widget-image{
  width: 426px;
}

//when the mouse enter the div will scroll up
.widget-image:hover + .widget-form {
      top: 0;
}

//maintain the div position
.widget-form:hover, .widget-form:focus ,  .widget-form :active {
  top: 0;
}

DEMO


问:
Randomly Generate a Word from a txt.file (Python)
I have a text file of sentences. I need to randomly read strings and output the string and its line number in an output file. I have written the following code:

```<code>ifile = open("test2.txt", "r")
otfile = open("OUT3.txt", "w")
otfile.write("Randomly Selected String \t\t\t Line Number")

import random

i=0

for lines in ifile.readline():

  line = lines[i]

  words = line.split()
  myword = random.choice(words)

  otfile.write(myword)
  otfile.write(str(i))
  i +=1
  otfile.write("\n")
</code>```

However I am only getting one character and no line number. I have been trying to change the code but I am just creating errors. Any ideas?

(Edit)
Test2.txt has the following sentences:

```<code>Brooklyn is the best place on Earth.
I had chocolate ice cream today.
I ate all the cookies in the cookie jar.
Today was a no good very bad day.
He got his clothes dirty playing outside.
</code>```

答:
try this</p>

```<code>with open('test2.txt') as f:
    lines = f.readlines()
    for line in lines:
        words = line.split(' ')
        myword = random.choice([x for x in words])
        print ">"+str(myword)
</code>```

Body:
I have a text file of sentences. I need to randomly read strings and output the string and its line number in an output file. I have written the following code:

ifile = open("test2.txt", "r")
otfile = open("OUT3.txt", "w")
otfile.write("Randomly Selected String \t\t\t Line Number")

import random

i=0

for lines in ifile.readline():

  line = lines[i]

  words = line.split()
  myword = random.choice(words)

  otfile.write(myword)
  otfile.write(str(i))
  i +=1
  otfile.write("\n")

However I am only getting one character and no line number. I have been trying to change the code but I am just creating errors. Any ideas?

(Edit)
Test2.txt has the following sentences:

Brooklyn is the best place on Earth.
I had chocolate ice cream today.
I ate all the cookies in the cookie jar.
Today was a no good very bad day.
He got his clothes dirty playing outside.

Body:
try this

with open('test2.txt') as f:
    lines = f.readlines()
    for line in lines:
        words = line.split(' ')
        myword = random.choice([x for x in words])
        print ">"+str(myword)


问:
How can I append one list to another where Indices match in Python?
I have two lists :

```<code>List1 = [['ab' , 'bc' ] , ['ef' , 'ij' ]]
List2 = [['pq' , 'rs' ] , ['uv' , 'xy' ]]
</code>```

I want a list that looks like this:

```<code>FinalList = [['ab', 'bc', 'pq', 'rs'], ['ef', 'ij', 'uv', 'xy']]
</code>```

Elements in the first position of List1 must be appended to elements in first position of list 2 , elements in second position of list 1 must be appended to elements in second position of list 2 and so on.

Thanks!

答:
Here's a simple comprehension that will work so long as the two lists are the same size

```<code>a = [ ['ab' , 'bc' ] , ['ef' , 'ij' ] ]
b = [ ['pq' , 'rs' ] , ['uv' , 'xy' ] ]
blended = [[a[ix]+b[ix]] for ix in range(len(a))]
</code>```

Results in

```<code>[['ab', 'bc', 'pq', 'rs']], [['ef', 'ij', 'uv', 'xy']]]
</code>```

Body:
I have two lists :

List1 = [['ab' , 'bc' ] , ['ef' , 'ij' ]]
List2 = [['pq' , 'rs' ] , ['uv' , 'xy' ]]

I want a list that looks like this:

FinalList = [['ab', 'bc', 'pq', 'rs'], ['ef', 'ij', 'uv', 'xy']]

Elements in the first position of List1 must be appended to elements in first position of list 2 , elements in second position of list 1 must be appended to elements in second position of list 2 and so on.

Thanks!

Body:
Here's a simple comprehension that will work so long as the two lists are the same size

a = [ ['ab' , 'bc' ] , ['ef' , 'ij' ] ]
b = [ ['pq' , 'rs' ] , ['uv' , 'xy' ] ]
blended = [[a[ix]+b[ix]] for ix in range(len(a))]

Results in

[['ab', 'bc', 'pq', 'rs']], [['ef', 'ij', 'uv', 'xy']]]


问:
How to modify service url paramer in angularjs
I'm trying to modify the city parameter by searching for a city parameter, but I don't think it's possible to modify an angular service that way. So how would I be able to modify the service parameter in the controller? Any help would be amazing!

HTML:

```<code><section ng-controller="MainController">

    <form action="" class="form-inline well well-sm clearfix" >
  <span class="glyphicon glyphicon-search"></span>
  <input type="text" placeholder="Search..." class="form-control" ng-model="city" />
  <button class="btn btn-warning pull-right" ng-click="search()"><strong>Search</strong></button>
</form>
    <h1>{{fiveDay.city.name}}</h1>
    <div ng-repeat="day in fiveDay.list" class="forecast">
        <div class="day">
            <div class="weekday">
                <p>{{ day.dt*1000 | date}}</p>
                <!-- <p>{{ parseJsonDate(day.dt)}}</p> -->
            </div>
            <div class="weather"><img ng-src="http://openweathermap.org/img/w/{{day.weather[0].icon}}.png"/></div>
            <div class="temp">{{day.weather[0].description}}</div>
            <div class="temp">Max {{ day.main.temp_max }}°</div>
            <div class="temp">Min {{ day.main.temp_min }}°</div>
        </div>
    </div>
</section>
</code>```

JS:

```<code>var app = angular.module('App', []);
app.controller('MainController', ['$scope', 'forecast', function($scope,    forecast) {
forecast.city="orlando";
  forecast.success(function(data) {
        $scope.fiveDay = data;
     });
  }]);
app.factory('forecast', ['$http', function($http) {
var city = "orlando";
var key="a1f2d85f6babd3bf7afd83350bc5f2a6";
  return $http.get('http://api.openweathermap.org/data/2.5/forecast?q='+city+'&APPID='+key+'&units=metric&cnt=5')
    .success(function(data) {
      return data;
    })
    .error(function(err) {
      return err;
    });
}]);
</code>```

答:
增加参数 callback ， 回调：JSON_CALLBACK</p>

```
$http.jsonp("http://api.openweathermap.org/data/2.5/forecast?q='+city+'&APPID='+key+'&units=metric&cnt=5&callback=JSON_CALLBACK").success(function(data){ ... });
```

Body:
I'm trying to modify the city parameter by searching for a city parameter, but I don't think it's possible to modify an angular service that way. So how would I be able to modify the service parameter in the controller? Any help would be amazing!

HTML:

    <form action="" class="form-inline well well-sm clearfix" >

  <input type="text" placeholder="Search..." class="form-control" ng-model="city" />
  <button class="btn btn-warning pull-right" ng-click="search()">Search</button>
</form>

{{fiveDay.city.name}}

{{ day.dt*1000 | date}}

{{day.weather[0].description}}

Max {{ day.main.temp_max }}°

Min {{ day.main.temp_min }}°

JS:

var app = angular.module('App', []);
app.controller('MainController', ['$scope', 'forecast', function($scope,    forecast) {
forecast.city="orlando";
  forecast.success(function(data) {
        $scope.fiveDay = data;
     });
  }]);
app.factory('forecast', ['$http', function($http) {
var city = "orlando";
var key="a1f2d85f6babd3bf7afd83350bc5f2a6";
  return $http.get('http://api.openweathermap.org/data/2.5/forecast?q='+city+'&APPID='+key+'&units=metric&cnt=5')
    .success(function(data) {
      return data;
    })
    .error(function(err) {
      return err;
    });
}]);

Body:
增加参数 callback ， 回调：JSON_CALLBACK

$http.jsonp("http://api.openweathermap.org/data/2.5/forecast?q='+city+'&APPID='+key+'&units=metric&cnt=5&callback=JSON_CALLBACK").success(function(data){ ... });


问:
Fix UILabel position below UITableViewController's UINavigationBar
We are placing a temporary label over our UITableViewController view when we need to show a status message.  The view goes directly beneath the UINavigationBar.  This works well but the statusView scrolls with the table and will disappear as the table scrolls up.  How can you fix the statusView position even as the table scrolls?

Update:

What almost works as inspired by another question is to use the TableViewDelegate method to fix the statusView position:

```<code>override func scrollViewDidScroll(_ scrollView: UIScrollView) {
    var newFrame = statusView.frame
    newFrame.origin.x = 0
    newFrame.origin.y = self.tableView.contentOffset.y + self.navigationController!.navigationBar.bounds.height
    statusView.frame = newFrame
}
</code>```

It places our statusView bar in a fixed position but it's partially underneath the navigation bar.   Seems like we just need to tweak the newFrame.origin.y logic....

Update 2:

Per https://stackoverflow.com/a/40202931/47281 just needed to include the status bar:

```<code>    newFrame.origin.y = self.tableView.contentOffset.y + self.navigationController!.navigationBar.frame.size.height + UIApplication.shared.statusBarFrame.height
</code>```

答:
Per updates above solution was inspired by another question - we used the TableViewDelegate scrollViewDidScroll to fix the position:</p>

```<code>override func scrollViewDidScroll(_ scrollView: UIScrollView) {
    var newFrame = statusView.frame
    newFrame.origin.x = 0
    newFrame.origin.y = self.tableView.contentOffset.y + self.navigationController!.navigationBar.bounds.height
    statusView.frame = newFrame
}
</code>```

Body:
We are placing a temporary label over our UITableViewController view when we need to show a status message.  The view goes directly beneath the UINavigationBar.  This works well but the statusView scrolls with the table and will disappear as the table scrolls up.  How can you fix the statusView position even as the table scrolls?

Update:

What almost works as inspired by another question is to use the TableViewDelegate method to fix the statusView position:

override func scrollViewDidScroll(_ scrollView: UIScrollView) {
    var newFrame = statusView.frame
    newFrame.origin.x = 0
    newFrame.origin.y = self.tableView.contentOffset.y + self.navigationController!.navigationBar.bounds.height
    statusView.frame = newFrame
}

It places our statusView bar in a fixed position but it's partially underneath the navigation bar.   Seems like we just need to tweak the newFrame.origin.y logic....

Update 2:

Per https://stackoverflow.com/a/40202931/47281 just needed to include the status bar:

    newFrame.origin.y = self.tableView.contentOffset.y + self.navigationController!.navigationBar.frame.size.height + UIApplication.shared.statusBarFrame.height

Body:
Per updates above solution was inspired by another question - we used the TableViewDelegate scrollViewDidScroll to fix the position:

override func scrollViewDidScroll(_ scrollView: UIScrollView) {
    var newFrame = statusView.frame
    newFrame.origin.x = 0
    newFrame.origin.y = self.tableView.contentOffset.y + self.navigationController!.navigationBar.bounds.height
    statusView.frame = newFrame
}


问:
How to pass variables from client to Express api
I've completely new to node.js and express.
I've done some calculations with javascript on my client page and I want to send that generated array of numbers to my node.js server app.  When I had to send form data I just used form action to my route. Now I'm totally lost and don't know where to start at. What code should I write in my route and how to pass js variable or array to it from my client app?</p>

答:
Simple Example

app.js

```<code>var express = require('express')
var app = express()

app.set('view engine', 'pug')

app.get('/', function (req, res) {
  res.render('index')
})

app.post('/example_route', function (req, res) {
  res.send({'msg': 'Hello World!'})
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})
</code>```

views/index.pug

```<code>doctype html
html
  head
    title= 'HomePage'
    script(src='https://code.jquery.com/jquery-3.2.1.min.js')
  body
    button(onclick='$.post("http://localhost:3000/example_route", function(data) {alert(data.msg);})') Click me!
</code>```

This homepage includes jquery from cdn and onclick event makes a POST request to your server.

Body:
Simple Example

app.js

var express = require('express')
var app = express()

app.set('view engine', 'pug')

app.get('/', function (req, res) {
  res.render('index')
})

app.post('/example_route', function (req, res) {
  res.send({'msg': 'Hello World!'})
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

views/index.pug

doctype html
html
  head
    title= 'HomePage'
    script(src='https://code.jquery.com/jquery-3.2.1.min.js')
  body
    button(onclick='$.post("http://localhost:3000/example_route", function(data) {alert(data.msg);})') Click me!

This homepage includes jquery from cdn and onclick event makes a POST request to your server.


问:
Single precision big endian float values to Python's float (double precision, big endian)
I need to receive hex encoded single precision big endian float values coming from an Arduino over a serial line (RS-232). How do convert them to Python's float which are big endians with double precision?

The Arduino send something like "8192323E" and in Python I would like to have 0.174387. I found "Convert hex to float" but it seems that all of them don't work for single precision floats.

From the linked page, this looks promising:

```<code>from ctypes import *

def convert(s):
    i = int(s, 16)                   # convert from hex to a Python int
    cp = pointer(c_int(i))           # make this into a c integer
    fp = cast(cp, POINTER(c_float))  # cast the int pointer to a float pointer
    return fp.contents.value         # dereference the pointer, get the float
</code>```

But it still doesn't work with my single precision floats.

In Java (Processing) I've been able to do that:

```<code>float decodeFloat(String inString) {
  byte [] inData = new byte[4];

  inString = inString.substring(2, 10); // discard the leading "f:"
  inData[0] = (byte) unhex(inString.substring(0, 2));
  inData[1] = (byte) unhex(inString.substring(2, 4));
  inData[2] = (byte) unhex(inString.substring(4, 6));
  inData[3] = (byte) unhex(inString.substring(6, 8));

  int intbits = (inData[3] << 24) | ((inData[2] & 0xff) << 16) | ((inData[1] & 0xff) << 8) | (inData[0] & 0xff);
  //unhex(inString.substring(0, 8));
  return Float.intBitsToFloat(intbits);
}
</code>```

For your reference, this is the C code running on the Arduino implementing the hex encoding.

```<code>void serialFloatPrint(float f) {
  byte * b = (byte *) &f;
  Serial.print("f:");
  for(int i=0; i<4; i++) {

    byte b1 = (b[i] >> 4) & 0x0f;
    byte b2 = (b[i] & 0x0f);

    char c1 = (b1 < 10) ? ('0' + b1) : 'A' + b1 - 10;
    char c2 = (b2 < 10) ? ('0' + b2) : 'A' + b2 - 10;

    Serial.print(c1);
    Serial.print(c2);
  }
}
</code>```

Body:
I need to receive hex encoded single precision big endian float values coming from an Arduino over a serial line (RS-232). How do convert them to Python's float which are big endians with double precision?

The Arduino send something like "8192323E" and in Python I would like to have 0.174387. I found "Convert hex to float" but it seems that all of them don't work for single precision floats.

From the linked page, this looks promising:

from ctypes import *

def convert(s):
    i = int(s, 16)                   # convert from hex to a Python int
    cp = pointer(c_int(i))           # make this into a c integer
    fp = cast(cp, POINTER(c_float))  # cast the int pointer to a float pointer
    return fp.contents.value         # dereference the pointer, get the float

But it still doesn't work with my single precision floats.

In Java (Processing) I've been able to do that:

float decodeFloat(String inString) {
  byte [] inData = new byte[4];

  inString = inString.substring(2, 10); // discard the leading "f:"
  inData[0] = (byte) unhex(inString.substring(0, 2));
  inData[1] = (byte) unhex(inString.substring(2, 4));
  inData[2] = (byte) unhex(inString.substring(4, 6));
  inData[3] = (byte) unhex(inString.substring(6, 8));

  int intbits = (inData[3] << 24) | ((inData[2] & 0xff) << 16) | ((inData[1] & 0xff) << 8) | (inData[0] & 0xff);
  //unhex(inString.substring(0, 8));
  return Float.intBitsToFloat(intbits);
}

For your reference, this is the C code running on the Arduino implementing the hex encoding.

void serialFloatPrint(float f) {
  byte * b = (byte *) &f;
  Serial.print("f:");
  for(int i=0; i<4; i++) {

    byte b1 = (b[i] >> 4) & 0x0f;
    byte b2 = (b[i] & 0x0f);

    char c1 = (b1 < 10) ? ('0' + b1) : 'A' + b1 - 10;
    char c2 = (b2 < 10) ? ('0' + b2) : 'A' + b2 - 10;

    Serial.print(c1);
    Serial.print(c2);
  }
}

Body:
Indeed, you need to invert the byte order. Look:

>>> convert('8192323E')
-5.370402375965945e-38
>>> convert('3E329281')
0.17438699305057526


问:
How to clear screen on python 3.6 IDLE?
All I wanted to ask that if i want to clear screen in IDLE what method I can use to clear it without closing it.
For e.g.
I print this statement using:-

```<code>print("Prabal Tiwari")
</code>```

after getting output of this I want to clear the console without closing it.
Just like we use "clear" on ubuntu terminal.

答: I think you can restart it but I don't think there is any way to do it without restarting the console. Hope this helped!</p>

Title: How to clear screen on python 3.6 IDLE?

Body:
All I wanted to ask that if i want to clear screen in IDLE what method I can use to clear it without closing it.
For e.g.
I print this statement using:-

print("Prabal Tiwari")

after getting output of this I want to clear the console without closing it.
Just like we use "clear" on ubuntu terminal.


问:
Which is More Important in iOS: Memory or CPU?
I have been testing several different extensions for viewing animated GIFs in iOS.  Here are my (non-scientific) results:

```<code>Extension           CPU    Memory
Animated-Gif-iOS    6%     26.3 MB  (caches downloaded data)
FLAnimatedImage     5%     32.3 MB
Gifu                0%     174.8 MB
SwiftGif            0%     174.4 MB
YLGIFImage          6%     32.2 MB
iOSDevCenters+GIF   0%     173.7 MB
</code>```

What is the preference for trading memory usage for CPU usage?  Should this decision change if I plan on showing multiple animated GIFs on the screen at the same time?

答:
That depends on what you find most important. Higher RAM will give you better prowess to run multiple things together. Higher processing speed gives you faster results.

Read this guide that explain the difference further.

Body:
I have been testing several different extensions for viewing animated GIFs in iOS.  Here are my (non-scientific) results:

Extension           CPU    Memory
Animated-Gif-iOS    6%     26.3 MB  (caches downloaded data)
FLAnimatedImage     5%     32.3 MB
Gifu                0%     174.8 MB
SwiftGif            0%     174.4 MB
YLGIFImage          6%     32.2 MB
iOSDevCenters+GIF   0%     173.7 MB

What is the preference for trading memory usage for CPU usage?  Should this decision change if I plan on showing multiple animated GIFs on the screen at the same time?


问:
Proving using contradiction technique
I have the following goals:

```<code>  f : bool -> bool
  b : bool
  H1 : f true = true
  H2 : f true = false
  H3 : f false = false
  ============================
   false = true
</code>```

Now using H1 and H2, I want to prove the goal using contradiction. I know about inversion tactic, but I don't think I can apply it here. Any idea on how to proceed from here ?

This is the fully reproducible code where you can get the above goals:

```<code>Theorem bool_fn_applied_thrice :
  forall (f : bool -> bool) (b : bool),
  f (f (f b)) = f b.
Proof.
  intros f b.
  destruct (f b) eqn:H1.
  - destruct (f true) eqn:H2.
    + rewrite -> H2.
      reflexivity.
    + destruct (f false) eqn:H3.
      * reflexivity.
      * destruct b in H1.
        {

        }
</code>```

Also would be interested to know if there is an simpler way of solving the above theorem than the above approach (Just the hints. One another way of approaching is using destruct on b initially which actually proves the theorem after 5 usage of destructs).

答:
There are many ways to proceed, and since this is an exercise from Software Foundations that might be used as homework, I will not give a full answer.

Indeed H1 and H2 contradict each other.

The way I expect you know about at this point is using rewrite. For instance, rewrite H1 in H2. will replace f true with true in H2, yielding H2 : true = false. You can then do either inversion H2 or discriminate.

I'm not sure there's a best way of going about the proof, there are essentially 8 cases to consider and only little room for shortcutting those.

Title: Proving using contradiction technique

Body:
I have the following goals:

  f : bool -> bool
  b : bool
  H1 : f true = true
  H2 : f true = false
  H3 : f false = false
  ============================
   false = true

Now using H1 and H2, I want to prove the goal using contradiction. I know about inversion tactic, but I don't think I can apply it here. Any idea on how to proceed from here ?

This is the fully reproducible code where you can get the above goals:

Theorem bool_fn_applied_thrice :
  forall (f : bool -> bool) (b : bool),
  f (f (f b)) = f b.
Proof.
  intros f b.
  destruct (f b) eqn:H1.
  - destruct (f true) eqn:H2.
    + rewrite -> H2.
      reflexivity.
    + destruct (f false) eqn:H3.
      * reflexivity.
      * destruct b in H1.
        {

        }

Also would be interested to know if there is an simpler way of solving the above theorem than the above approach (Just the hints. One another way of approaching is using destruct on b initially which actually proves the theorem after 5 usage of destructs).


答:
You can use list comprehension the zipped lists.</p>

```<code>[x + y for x, y in zip(List1, List2)]
</code>```

Title: How can I append one list to another where Indices match in Python?

Body:
You can use list comprehension the zipped lists.

[x + y for x, y in zip(List1, List2)]


问:
Cannot create a database on a fresh installed monetdb
I'm new using MonetDB. I've follow this installation guide http://www.monetdb.org/Documentation/Guide/Installation
and I'm facing a problem to just create a database. Here is the error

```<code>monetdb create /tmp/c
monetdb: cannot find a control socket, use -h and/or -p
</code>```

Ruuning the command with option -por -h didn't change anything

```<code>monetdb -p create /tmp/c
monetdb: cannot find a control socket, use -h and/or -p
</code>```

can come one help me ?

答:
Probably, you also can have an issue with the root access. I recommend creating the folder for MonetDB's data farm on your own:
mkdir /tmp/c
monetdbd create /tmp/c
monetdbd start /tmp/c
monetdb create db_name
monetdb release db_name
mclient -u monetdb -d db_name
pass: monetdb</p>

Body:
I'm new using MonetDB. I've follow this installation guide http://www.monetdb.org/Documentation/Guide/Installation
and I'm facing a problem to just create a database. Here is the error

monetdb create /tmp/c
monetdb: cannot find a control socket, use -h and/or -p

Ruuning the command with option -por -h didn't change anything

monetdb -p create /tmp/c
monetdb: cannot find a control socket, use -h and/or -p

can come one help me ?


问:
Restoring files on a version enabled amazon s3 bucket
I am trying to enable versioning and lifecycle policies on my Amazon S3 buckets. I understand that it is possible to enable Versioning first and then apply LifeCycle policy on that bucket. If you see the image below, that will confirm this idea.

I have then uploaded a file several times which created several versions of the same file. I then deleted the file and still able to see several versions. However, if I try to restore a file, I see that the Initiate Restore option is greyed out.

I would like to ask anyone who had any similar issue or let me know what I am doing wrong.

Thanks,

答:
With the new console, you can do it as following.

Click on the Deleted Objects button

You will see your deleted object below, Select it

Click on More -> Undo delete


问:
Methods for implementing contour plotting
I need to implement a contour plotting algorithm (as opposed to just using one). The input is a (continuous) function f: R^2 - > R (the function is defined over the entire domain, not just for certain inputs). The output should be in vector form, i.e. a set of splines or line segments.

I'm looking for recommendations on how to implement this, preferably in the form of (scientific) papers.

I found some references to algorithms developed in the 80s ("Level Tracing Algorithm"). Have there been any development in this area in the past 30 years? What's the standard method(s) used to solve this problem?

The algorithm will be used for real-time visualization, so it needs to be fast while still producing decent results.

(Small, self-contained and well tested C/C++ implementations would be welcomed as well.)

答: See for instance xfarbe.</p>

Body: See for instance xfarbe.


问:
Can I move a kernel thread from one namespace to another?
Our situation is:

First we have a kernel thread (say KS) that starts to run when kernel starts to run;

Then when system is ready, we create another namespace (say NS1) that has a different mntns with LXC.

Our requirement is the KS need to write something in a path that can only seen by NS1. So I'm thinking can I move the KS to the NS1 namespace (at least change the mount namespace)? If yes, how? I have checked the setns() syscall and its kernel source code, but still don't know how to do it (either in user-space or change the KS source code), and even not sure if this is the right way to solve the problem.

My other question is: my understanding is that a kernel task (e.g., kernel threads) aware "namespace" if it is in process context, but my friend thinks that the "namespace" is a user-space concept, all kernel staff knows only about the root namespace. Which one is correct?

答:
No it is not the right way to solve your problem. The whole idea of writing to any namespace from the kernel thread is bad, as explained in detail here: http://www.linuxjournal.com/article/8110. You should do it from the user space, after you enter the required mount name space by using the setns(2) syscall. The setns(2) man page has an example code to do that.

The answer to your other question is your friend is wrong; the name space setup and relevant processing is done inside the kernel, by the kernel, thus the kernel must know everything about all of the name spaces. Each task's struct_task contains nsproxy struct member with all of the relevant pointers to the respective name space data structures -- these are kernel-only data structures. The user space actually does not know anything about this (other than having requested it in the clone()). In case of the mount name space, the user process is handed a mount table: either the same one as that of the parent, or a private copy if a new mount name space has been requested by clone(flags=CLONE_NEWNS). Either way the user process just uses whatever mount table (structures) it was handed, and the kernel manages the name space details without the user being aware of it.


问:
How to replace lite-server with my express server.js for Angular 2?
Well, the question maybe has nothing to do with Angular 2, but...After watching Deborah's PluralSight Getting Started video, I tried to migrate my existing angular 1.x project to angular 2. For the client part, I want to switch to TypeScript and Angular 2, but for server part, I want to keep existing code as much as possible. The first issue I ran into is how to replace lite-server used in Deborah's project with my own server.js, while keeping her browsersync setup. Here is part of her package.json file which uses lite-server with -c parameter:

```<code>"scripts": {
    "build": "tsc -p src/",
    "build:watch": "tsc -p src/ -w",
    "serve": "lite-server -c=bs-config.json",
    "prestart": "npm run build",
    "start": "concurrently \"npm run build:watch\" \"npm run serve\"",
    "lint": "tslint ./src/**/*.ts -t verbose"
},
</code>```

bs-config.json looks like this:

```<code>{
  "server": {
    "baseDir": "src",
    "routes": {
      "/node_modules": "node_modules"
    }
  }
}
</code>```

My question is how to replace lite-server with my server.js which looks like this:

```<code>var express  = require('express');
var app      = express();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var http = require('http');
var path = require('path');

var session = require('express-session');
var route = require('./server/route');

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));

var port = 3000;
app.listen(port);
console.log('App listening on port ' + port);

route.init(app);

app.get('*', function(req, res) {
   res.sendfile(__dirname + '/public/index.html');
});
</code>```

systemjs.config.js

```<code>/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

      // other libraries
      'rxjs': 'npm:rxjs'
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);
</code>```

tsconfig.json

```<code>{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  }
}
</code>```

答:
Update Package.json. Run npm install again.Then npm start.

```<code>"scripts": {

"start": "node server/server.js"
}
</code>```

"server/server.js" is path of  server.js file.

Body:
Well, the question maybe has nothing to do with Angular 2, but...After watching Deborah's PluralSight Getting Started video, I tried to migrate my existing angular 1.x project to angular 2. For the client part, I want to switch to TypeScript and Angular 2, but for server part, I want to keep existing code as much as possible. The first issue I ran into is how to replace lite-server used in Deborah's project with my own server.js, while keeping her browsersync setup. Here is part of her package.json file which uses lite-server with -c parameter:

"scripts": {
    "build": "tsc -p src/",
    "build:watch": "tsc -p src/ -w",
    "serve": "lite-server -c=bs-config.json",
    "prestart": "npm run build",
    "start": "concurrently \"npm run build:watch\" \"npm run serve\"",
    "lint": "tslint ./src/**/*.ts -t verbose"
},

bs-config.json looks like this:

{
  "server": {
    "baseDir": "src",
    "routes": {
      "/node_modules": "node_modules"
    }
  }
}

My question is how to replace lite-server with my server.js which looks like this:

var express  = require('express');
var app      = express();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var http = require('http');
var path = require('path');

var session = require('express-session');
var route = require('./server/route');

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));

var port = 3000;
app.listen(port);
console.log('App listening on port ' + port);

route.init(app);

app.get('*', function(req, res) {
   res.sendfile(__dirname + '/public/index.html');
});

systemjs.config.js

/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

      // other libraries
      'rxjs': 'npm:rxjs'
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  }
}

Body:
Update Package.json. Run npm install again.Then npm start.

"scripts": {

"start": "node server/server.js"
}

"server/server.js" is path of  server.js file.


问:
Node Sequelize Followering/Following Relationship
As the title states, i'm trying to figure out how to do a following/follower relationship in Sequelize. I'm more so trying to implement what i did in Rails into Node.

So heres the Ruby Code

InRelationship Model class file Ruby

```<code>belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
</code>```

In user model class file Ruby

```<code># Relationships
has_many :active_relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy
has_many :following, through: :active_relationships, source: :followed
has_many :followers, through: :passive_relationships, source: :follower
has_many :passive_relationships, class_name: "Relationship", foreign_key: "followed_id", dependent: :destroy
</code>```

Now heres my attempt of translating this code into nodeJS Sequelize
User File - NodeJS Sequelize

```<code> User.hasMany(models.Relationships, {
      as: "active_relatinships",
      foreignKey: "followerId"
    })
 User.hasMany(models.Relationships, {
      as: "passive_relatinships",
      foreignKey: "followingId"
    })
</code>```

Rleationship File NodeJS Sequelize

```<code> Relationships.belongsToMany(models.User,
      {through: "active_relationships", as: "follower"})
 Relationships.belongsToMany(models.User,
      {through: "passive_relationships", as: "followed"})
</code>```

What am i doing wrong? This is the error i get when tryin to include in my Query

Unhandled rejection Error: Relationships (active_relationships) is not associated to User!

Here is my include query

```<code>    include: [
        {model: models.Areas, as: "current_area" },
        {model: models.VisitedAreas},
        {model: models.OnTheWays, include: [
          {model: models.Areas, as: "Area"}]},
        {model: models.Settings},
        {model: models.Pictures},
        {model: models.Relationships, as: "passive_relationships"},
        {model: models.Relationships, as: "active_relationships"}]
</code>```

答:
I have an idea about this question! on my option:
you should use this.

```<code>   User.hasMany(models.Relationships, {foreignKey: "followerId"})
   include: [{model: models.Relationships}]
</code>```

I write a demo about this question:

```<code>   User.hasMany(Money, {foreignKey: "followingId"});
   const result = await dbs.User.findAll({include: [{modedbs.Money}]});
   console.log(JSON.stringify(result));
</code>```

This is my result:

Body:
As the title states, i'm trying to figure out how to do a following/follower relationship in Sequelize. I'm more so trying to implement what i did in Rails into Node.

So heres the Ruby Code

InRelationship Model class file Ruby

belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"

In user model class file Ruby

# Relationships
has_many :active_relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy
has_many :following, through: :active_relationships, source: :followed
has_many :followers, through: :passive_relationships, source: :follower
has_many :passive_relationships, class_name: "Relationship", foreign_key: "followed_id", dependent: :destroy

Now heres my attempt of translating this code into nodeJS Sequelize
User File - NodeJS Sequelize

 User.hasMany(models.Relationships, {
      as: "active_relatinships",
      foreignKey: "followerId"
    })
 User.hasMany(models.Relationships, {
      as: "passive_relatinships",
      foreignKey: "followingId"
    })

Rleationship File NodeJS Sequelize

 Relationships.belongsToMany(models.User,
      {through: "active_relationships", as: "follower"})
 Relationships.belongsToMany(models.User,
      {through: "passive_relationships", as: "followed"})

What am i doing wrong? This is the error i get when tryin to include in my Query

Unhandled rejection Error: Relationships (active_relationships) is not associated to User!

Here is my include query

    include: [
        {model: models.Areas, as: "current_area" },
        {model: models.VisitedAreas},
        {model: models.OnTheWays, include: [
          {model: models.Areas, as: "Area"}]},
        {model: models.Settings},
        {model: models.Pictures},
        {model: models.Relationships, as: "passive_relationships"},
        {model: models.Relationships, as: "active_relationships"}]

Body:
I have an idea about this question! on my option:
you should use this.

   User.hasMany(models.Relationships, {foreignKey: "followerId"})
   include: [{model: models.Relationships}]

I write a demo about this question:

   User.hasMany(Money, {foreignKey: "followingId"});
   const result = await dbs.User.findAll({include: [{modedbs.Money}]});
   console.log(JSON.stringify(result));

This is my result:


问:
The cheapest way to compare two sets of strings
I have to sets of strings

```<code>set 1:

    "hello"
    "world"
    "stackoverflow"

set 2:
    "world"
    "hello"
    "stackoverflow"
</code>```

Before I tried to compare the content, I know exactly that these two sets contain only unique values. So I am not thinking about java Set for unique test.

So in Java, what should be the cheapest way to compare these two sets? By cheapest, I mean memory like.

I know I can do ArrayList.contains() forLoop, is there a better way?

And I was told Java HashSet consumes 5 times more resources than ArrayList when containing same length of contents. Is that true?

UPDATE

I don't have sample for you, since this is just an idea came to my mind.

By two sets of strings, I meant literally set, this set can also be stored in Java ArrayList.

what I want

is to compare these two sets of string to know if they are containing the same contents. of course I know before the actions that they both containing unique contents.

UPDATE

Sorry, this is not a practical problem I ran across with. This is just an idea I am wondering about.

答:
Since your only concern is memory footprint than basic nested loop on arrays (or whatever collections these strings are stored in at the moment) would work perfectly fine and only use fixed amount of extra space (for loop counters).

You can shorten code by using contains too - that function should require fixed amount of memory, but you'd waste some on call stack frame.

Note that this will trade run-time performance of comparison for memory usage. The penalty for time performance is significant, and likely will be easily noticeable for sets of size more 10-20 items. More balanced approach  of comparing the sets is covered for example in What is the fastest way to compare two sets in Java? - memory cost of appropriate data structures is generally less of a concern than run-time cost.

Body:
I have to sets of strings

set 1:

    "hello"
    "world"
    "stackoverflow"

set 2:
    "world"
    "hello"
    "stackoverflow"

Before I tried to compare the content, I know exactly that these two sets contain only unique values. So I am not thinking about java Set for unique test.

So in Java, what should be the cheapest way to compare these two sets? By cheapest, I mean memory like.

I know I can do ArrayList.contains() forLoop, is there a better way?

And I was told Java HashSet consumes 5 times more resources than ArrayList when containing same length of contents. Is that true?

UPDATE

I don't have sample for you, since this is just an idea came to my mind.

By two sets of strings, I meant literally set, this set can also be stored in Java ArrayList.

what I want

is to compare these two sets of string to know if they are containing the same contents. of course I know before the actions that they both containing unique contents.

UPDATE

Sorry, this is not a practical problem I ran across with. This is just an idea I am wondering about.


问:
How to identify the original message that triggers MessageFaultEvent
I'm using BlazeDS to send messages in Flex. Inside the UI component, I defined a producer like  the one below:

```<code>    <mx:Producer id="producer"
    destination="chat"
    fault="faultHandler(event);"/>
</code>```

I was wondering inside faultHandler how I'm able to identify what message causes the error. As it seems there's no way to get the reference to the original message.

This is the code snippet how the message is constructed and sent.

```<code>        private function sendMessage():void {
            var message:AsyncMessage = new AsyncMessage();
            message.body = userName.text + ": " + input.text;
            producer.send(message);
        }
</code>```

Thanks!

答:
Doesn't look like the producer object holds on to a reference of the message object.  You can add this by just extending the producer class and overriding the fault function and dispatching a custom event that contains the message.

some sudo code:

```<code>public class MyProducer extends Producer
{

    public function MyProducer(){
       super()
    }

    override public function fault(errMsg:ErrorMessage, msg:IMessage):void
    {
        var evt:MyMessageEvent = new MyMessageEvent(msg)
        dispatch(evt);
        super(errMsg, msg);
    }

}
</code>```

Then all you need to do is listen for the MyMessageEvent event and get your message.

Body:
I'm using BlazeDS to send messages in Flex. Inside the UI component, I defined a producer like  the one below:

    <mx:Producer id="producer"
    destination="chat"
    fault="faultHandler(event);"/>

I was wondering inside faultHandler how I'm able to identify what message causes the error. As it seems there's no way to get the reference to the original message.

This is the code snippet how the message is constructed and sent.

        private function sendMessage():void {
            var message:AsyncMessage = new AsyncMessage();
            message.body = userName.text + ": " + input.text;
            producer.send(message);
        }

Thanks!

Body:
Doesn't look like the producer object holds on to a reference of the message object.  You can add this by just extending the producer class and overriding the fault function and dispatching a custom event that contains the message.

some sudo code:

public class MyProducer extends Producer
{

    public function MyProducer(){
       super()
    }

    override public function fault(errMsg:ErrorMessage, msg:IMessage):void
    {
        var evt:MyMessageEvent = new MyMessageEvent(msg)
        dispatch(evt);
        super(errMsg, msg);
    }

}

Then all you need to do is listen for the MyMessageEvent event and get your message.


问:
How to sort through list of a list and remove a list if less not least value
Currently, this takes the list of the candidates and sorts it so that the candidates with the lowest score are in the first positions, how would I get it so that it checks each list and if the number in the second field is not equal to the first one it deletes this list?
I am trying to remove all lists that are not the lowest or equal lowest number in candidate [x][1]:

```<code>candidates = [[name, 3, characteristic], [name, 7, characteristic], [name, 3, characteristic]]
</code>```

so the following code should only delete candidates [1]

```<code>from operator import itemgetter

candidates.sort(key=itemgetter(1))

for [x][1] in candidates:
    if candidates[x][1] != candidates[0][1] :
        candidates.remove(candidates[x])
</code>```

Thanks!

答:
The problem with your solution is that you are modifying the candidates list while iterating over the very same list. This causes problems as you probably noticed.

Rather than sorted() you can use min() with a key to determine the item with the least value. This gives better performance - O(n) vs. O(n log n) - which might be important if there is a long list of candidates.

Furthermore, you would be better off determining the minimum value upfront, store it in a variable, and use that in a list comprehension/filter when comparing items. This avoids multiple redundant calls to min() resulting in a more efficient solution:

```<code>from operator import itemgetter

candidates = [['name', 97, 'blah'], ['name', 7, 'candidate'], ['name', 3, 'characteristic'], ['name', 3, 'characteristic']]

min_value = min(candidates, key=itemgetter(1))[1]
candidates = [candidate for candidate in candidates if candidate[1] == min_value]
print(candidates)
# [['name', 3, 'characteristic'], ['name', 3, 'characteristic']]
</code>```

Note that I use a list comprehension here. They are considered more Pythonic, may have better performance, and can easily be changed into generator expressions which can also yield better performance in many situations.

Body:
Currently, this takes the list of the candidates and sorts it so that the candidates with the lowest score are in the first positions, how would I get it so that it checks each list and if the number in the second field is not equal to the first one it deletes this list?
I am trying to remove all lists that are not the lowest or equal lowest number in candidate [x][1]:

candidates = [[name, 3, characteristic], [name, 7, characteristic], [name, 3, characteristic]]

so the following code should only delete candidates [1]

from operator import itemgetter

candidates.sort(key=itemgetter(1))

for [x][1] in candidates:
    if candidates[x][1] != candidates[0][1] :
        candidates.remove(candidates[x])

Thanks!

Body:
The problem with your solution is that you are modifying the candidates list while iterating over the very same list. This causes problems as you probably noticed.

Rather than sorted() you can use min() with a key to determine the item with the least value. This gives better performance - O(n) vs. O(n log n) - which might be important if there is a long list of candidates.

Furthermore, you would be better off determining the minimum value upfront, store it in a variable, and use that in a list comprehension/filter when comparing items. This avoids multiple redundant calls to min() resulting in a more efficient solution:

from operator import itemgetter

candidates = [['name', 97, 'blah'], ['name', 7, 'candidate'], ['name', 3, 'characteristic'], ['name', 3, 'characteristic']]

min_value = min(candidates, key=itemgetter(1))[1]
candidates = [candidate for candidate in candidates if candidate[1] == min_value]
print(candidates)
# [['name', 3, 'characteristic'], ['name', 3, 'characteristic']]

Note that I use a list comprehension here. They are considered more Pythonic, may have better performance, and can easily be changed into generator expressions which can also yield better performance in many situations.


问:
What does the gray exclamation mark means in Xcode 8.3?
I updated the Xcode to 8.3 version today, but I found a new error message, a gray exclamation mark. I do not know what it means, But the program can run normally. Does anyone know what this symbol means?

答:
That error style is not new to Xcode 8.3, but your project may be experiencing new warnings or errors due to changes in Xcode 8.3 which is causing this style to appear.

That style is used to provide you with additional information about a given error or warning. You should see the primary issue somewhere above the grey exclamation mark style. There should also be a disclosure triangle that will let you collapse this additional information.

You need to resolve the primary issue.


问:
PHP mail function doesn't complete sending of e-mail
```<code><?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: yoursite.com';
    $to = 'contact@yoursite.com';
    $subject = 'Customer Inquiry';
    $body = "From: $name\n E-Mail: $email\n Message:\n $message";

    if ($_POST['submit']) {
        if (mail ($to, $subject, $body, $from)) {
            echo '<p>Your message has been sent!</p>';
        } else {
            echo '<p>Something went wrong, go back and try again!</p>';
        }
    }
?>
</code>```

I've tried creating a simple mail form. The form itself is on my index.html page, but it submits to a separate "thank you for your submission" page, thankyou.php, where the above PHP code is embedded.
The code submits perfectly, but never sends an email. How can I fix this?

答:
If you are running this code on a local server (i.e your computer for development purposes) it won't send the email to the recipient. It will create a .txt file in a folder named mailoutput.

In the case if you are using a free hosing service, like 000webhost or hostinger, those service providers disable the mail() function to prevent unintended uses of email spoofing, spamming, etc. I prefer you to contact them to see whether they support this feature.

If you are sure that the service provider supports the mail() function, you can check this PHP manual for further reference,

PHP mail()

To check weather your hosting service support the mail() function, try running this code (remember to change the recipient email address):

```<code><?php
    $to      = 'nobody@example.com';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: webmaster@example.com' . "\r\n" .
        'Reply-To: webmaster@example.com' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
?>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: yoursite.com';
    $to = 'contact@yoursite.com';
    $subject = 'Customer Inquiry';
    $body = "From: $name\n E-Mail: $email\n Message:\n $message";

    if ($_POST['submit']) {
        if (mail ($to, $subject, $body, $from)) {
            echo '
Your message has been sent!
';
        } else {
            echo '
Something went wrong, go back and try again!
';
        }
    }
?>

I've tried creating a simple mail form. The form itself is on my index.html page, but it submits to a separate "thank you for your submission" page, thankyou.php, where the above PHP code is embedded.
The code submits perfectly, but never sends an email. How can I fix this?

Body:
If you are running this code on a local server (i.e your computer for development purposes) it won't send the email to the recipient. It will create a .txt file in a folder named mailoutput.

In the case if you are using a free hosing service, like 000webhost or hostinger, those service providers disable the mail() function to prevent unintended uses of email spoofing, spamming, etc. I prefer you to contact them to see whether they support this feature.

If you are sure that the service provider supports the mail() function, you can check this PHP manual for further reference,

PHP mail()

To check weather your hosting service support the mail() function, try running this code (remember to change the recipient email address):

<?php
    $to      = 'nobody@example.com';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: webmaster@example.com' . "\r\n" .
        'Reply-To: webmaster@example.com' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
?>


问:
Run a command in a shell and keep running the command when you close the session
I am using Putty to connect to a remote server. What I want to know is if there is any way to write my commands and allow them to keep running after I close the session with Putty. The reason for this is that I do not want to keep the computer ON all the time. Is there any way to do this?.

Update with the solution

For my question as it is presented the best solution is use one of the commands provided such as nohup, because you do not have to install any additional software. But if you are in the same problem use screen, install it and use it. It is amazing.

I have selected the answer of Norman Ramsey as favourite because propose several solutions using commands and screen. But please check the other answers specially the one of PEZ, then you get an insight of what screen is able todo.

答: Try using GNU Screen.  It allows you to have several shells open at once.  And you can disconnect from those running shells (i.e. close session with Putty) and they will keep doing their thing.</p>

OwnerDisplayName: Eduardo

LastEditorDisplayName: Eduardo

OwnerDisplayName: Carlos Rendon