问:
Rust: Reading and writing CSV performance
I am trying to get an indicative measure of the maximum speed with which I can read and write a 'large' CSV file using Rust.

I have a test CSV file containing 100 million identical rows:

SomeLongStringForTesting1, SomeLongStringForTesting2

The size of this file on disk is 4.84GB.

I have written (mostly copied!) the following code which uses the csv: 1.1.3 crate:

```<code>use std::error::Error;

fn main() {
    read_and_write("C:/Dev/100MillionRows.csv", "C:/Dev/100MillionRowsCopy.csv").unwrap();
}

fn read_and_write(in_file_path: &str, out_file_path: &str) -> Result<(), Box<Error>> {
    let mut rdr = csv::ReaderBuilder::new()
        .has_headers(false)
        .from_path(in_file_path)?;

    let mut wtr = csv::WriterBuilder::new()
        .from_path(out_file_path)?;

    for result in rdr.records() {
        let record = result?;
        wtr.write_record(record.iter())?;
    }

    wtr.flush()?;

    Ok(())
}
</code>```

Building in 'release mode' and then running with the following command:

powershell -Command "Measure-Command {.\target\release\csv-performance.exe}" yields 72.79 seconds, 71.01 seconds, 70.77 seconds for three runs.

Speaking approximately, I'm seeing 10GB (combined read and write) of IO in 70 seconds, which corresponds to 142MB/S. This is approximately what Windows is reporting for disk usage in Task Manager.

This feels like it might be slow, for the following reasons:

winsat disk -drive c yields:

```<code>Windows System Assessment Tool
> Running: Feature Enumeration ''
> Run Time 00:00:00.00
> Running: Storage Assessment '-drive c -ran -read'
> Run Time 00:00:01.31
> Running: Storage Assessment '-drive c -seq -read'
> Run Time 00:00:05.36
> Running: Storage Assessment '-drive c -seq -write'
> Run Time 00:00:03.17
> Running: Storage Assessment '-drive c -flush -seq'
> Run Time 00:00:00.80
> Running: Storage Assessment '-drive c -flush -ran'
> Run Time 00:00:00.73
> Dshow Video Encode Time                      0.00000 s
> Dshow Video Decode Time                      0.00000 s
> Media Foundation Decode Time                 0.00000 s
> Disk  Random 16.0 Read                       541.88 MB/s       8.3
> Disk  Sequential 64.0 Read                   1523.74 MB/s      8.8
> Disk  Sequential 64.0 Write                  805.49 MB/s       8.3
> Average Read Time with Sequential Writes     0.219 ms          8.6
> Latency: 95th Percentile                     1.178 ms          8.2
> Latency: Maximum                             7.760 ms          8.2
> Average Read Time with Random Writes         0.199 ms          8.9
</code>```

which suggests my disk (a pretty decent SSD) is capable of much more.

If I just copy the file:

powershell -Command "Measure-Command {Copy-Item "C:/Dev/100MillionRows.csv" -Destination "C:/Dev/100MillionRowsCopy.csv"}"

it takes 9.97 seconds, 13.85 seconds, 10.90 seconds for three runs. Taking the average at 11.57 seconds, I'm seeing approximately 860 MB/S of IO. This is more in the ballpark of the limitations of my disk.

Clearly when reading the CSV in my code I'm doing more work than a simple copy, but I was surprised that it would be ~6 times slower than the copy.

Would appreciate any thoughts on why this is the case and how to improve the performance of my Rust code? I'm very new to Rust so there's quite possibly something noddy there! I'm aware of the performance section of the docs https://docs.rs/csv/1.0.0/csv/tutorial/index.html#performance, but these seem to be performance improvements on the order of 50%, not several hundred percent.

Update 1

Without modifying the code some further testing shows that the rate isn't consistent as I vary the size of the strings in the rows for 100 million rows:

A,B : 18 MB/S

SomeLongStringForTesting1, SomeLongStringForTesting2 : 142 MB/S

AAAA...(A repeated 300 times),BBBB...(B repeated 300 times): 279 MB/S

I'll have a go at implementing the documented improvements to see what difference it makes, and might also try profiling - any recommendations for tooling appreciated otherwise I'll just have Google.

答:
You can get a pretty substantial improvement by following the performance tips in the tutorial you linked. In particular, the key is really to amortize allocations and avoid a UTF-8 check, both of which are happening in your code. Namely, your code allocates a new record in memory for each row in the CSV file. It also checks each field for valid UTF-8. Both of these have costs, but they do provide a fairly simple API that is decently fast as it is.

Additionally, one tip that isn't mentioned in the tutorial is to use csv::Writer::write_byte_record when possible instead of csv::Writer::write_record. The latter is more flexible, but the former constrains the input a bit more such that it can implement writes more efficiently in common scenarios.

Overall, making these changes is pretty easy:

```<code>use std::error::Error;

fn main() {
    read_and_write("rows.csv", "rows-copy.csv").unwrap();
}

fn read_and_write(
    in_file_path: &str,
    out_file_path: &str,
) -> Result<(), Box<dyn Error>> {
    let mut rdr = csv::ReaderBuilder::new()
        .has_headers(false)
        .from_path(in_file_path)?;
    let mut wtr = csv::WriterBuilder::new()
        .from_path(out_file_path)?;

    let mut record = csv::ByteRecord::new();
    while rdr.read_byte_record(&mut record)? {
        wtr.write_byte_record(&record)?;
    }
    wtr.flush()?;

    Ok(())
}
</code>```

Here is the timing for your code on my Linux system:

```<code>$ time ./target/release/csvsoperf

real    21.518
user    19.315
sys     2.189
maxmem  6 MB
faults  0
</code>```

And here is the timing for my updated code:

```<code>$ time ./target/release/csvsoperf

real    12.057
user    9.924
sys     2.125
maxmem  6 MB
faults  0
</code>```

Profiling the faster code, about 56% of the time is being spent in csv::Reader::read_byte_record, while about 29% of the time is being spent in csv::Writer::write_byte_record. This seems about right to me, and suggests your program isn't really doing anything that is additionally sub-optimal. There are no real bottlenecks outside of csv itself to optimize for.

Clearly when reading the CSV in my code I'm doing more work than a simple copy, but I was surprised that it would be ~6 times slower than the copy.

It's easy to be surprised when using pathological or very constrained inputs. Your example CSV data is very simple, and indeed, there are (obviously) much faster ways to parse and write data if it follows that format. But a CSV parser doesn't know that and must be able to handle the full format, which includes dealing with escaping and quoting. The csv parser has had a lot of optimization work done to it, and should generally be one of the faster CSV parsers in existence. So the more appropriate comparison here should be another CSV parser. It's not surprise that a dumb copy of the data is going to be substantially faster than a parser that is doing non-trivial work on the input.

Body:
I am trying to get an indicative measure of the maximum speed with which I can read and write a 'large' CSV file using Rust.

I have a test CSV file containing 100 million identical rows:

SomeLongStringForTesting1, SomeLongStringForTesting2

The size of this file on disk is 4.84GB.

I have written (mostly copied!) the following code which uses the csv: 1.1.3 crate:

use std::error::Error;

fn main() {
    read_and_write("C:/Dev/100MillionRows.csv", "C:/Dev/100MillionRowsCopy.csv").unwrap();
}

fn read_and_write(in_file_path: &str, out_file_path: &str) -> Result<(), Box<Error>> {
    let mut rdr = csv::ReaderBuilder::new()
        .has_headers(false)
        .from_path(in_file_path)?;

    let mut wtr = csv::WriterBuilder::new()
        .from_path(out_file_path)?;

    for result in rdr.records() {
        let record = result?;
        wtr.write_record(record.iter())?;
    }

    wtr.flush()?;

    Ok(())
}

Building in 'release mode' and then running with the following command:

powershell -Command "Measure-Command {.\target\release\csv-performance.exe}" yields 72.79 seconds, 71.01 seconds, 70.77 seconds for three runs.

Speaking approximately, I'm seeing 10GB (combined read and write) of IO in 70 seconds, which corresponds to 142MB/S. This is approximately what Windows is reporting for disk usage in Task Manager.

This feels like it might be slow, for the following reasons:

winsat disk -drive c yields:

Windows System Assessment Tool
> Running: Feature Enumeration ''
> Run Time 00:00:00.00
> Running: Storage Assessment '-drive c -ran -read'
> Run Time 00:00:01.31
> Running: Storage Assessment '-drive c -seq -read'
> Run Time 00:00:05.36
> Running: Storage Assessment '-drive c -seq -write'
> Run Time 00:00:03.17
> Running: Storage Assessment '-drive c -flush -seq'
> Run Time 00:00:00.80
> Running: Storage Assessment '-drive c -flush -ran'
> Run Time 00:00:00.73
> Dshow Video Encode Time                      0.00000 s
> Dshow Video Decode Time                      0.00000 s
> Media Foundation Decode Time                 0.00000 s
> Disk  Random 16.0 Read                       541.88 MB/s       8.3
> Disk  Sequential 64.0 Read                   1523.74 MB/s      8.8
> Disk  Sequential 64.0 Write                  805.49 MB/s       8.3
> Average Read Time with Sequential Writes     0.219 ms          8.6
> Latency: 95th Percentile                     1.178 ms          8.2
> Latency: Maximum                             7.760 ms          8.2
> Average Read Time with Random Writes         0.199 ms          8.9

which suggests my disk (a pretty decent SSD) is capable of much more.

If I just copy the file:

powershell -Command "Measure-Command {Copy-Item "C:/Dev/100MillionRows.csv" -Destination "C:/Dev/100MillionRowsCopy.csv"}"

it takes 9.97 seconds, 13.85 seconds, 10.90 seconds for three runs. Taking the average at 11.57 seconds, I'm seeing approximately 860 MB/S of IO. This is more in the ballpark of the limitations of my disk.

Clearly when reading the CSV in my code I'm doing more work than a simple copy, but I was surprised that it would be ~6 times slower than the copy.

Would appreciate any thoughts on why this is the case and how to improve the performance of my Rust code? I'm very new to Rust so there's quite possibly something noddy there! I'm aware of the performance section of the docs https://docs.rs/csv/1.0.0/csv/tutorial/index.html#performance, but these seem to be performance improvements on the order of 50%, not several hundred percent.

Update 1

Without modifying the code some further testing shows that the rate isn't consistent as I vary the size of the strings in the rows for 100 million rows:

A,B : 18 MB/S

SomeLongStringForTesting1, SomeLongStringForTesting2 : 142 MB/S

AAAA...(A repeated 300 times),BBBB...(B repeated 300 times): 279 MB/S

I'll have a go at implementing the documented improvements to see what difference it makes, and might also try profiling - any recommendations for tooling appreciated otherwise I'll just have Google.

Body:
You can get a pretty substantial improvement by following the performance tips in the tutorial you linked. In particular, the key is really to amortize allocations and avoid a UTF-8 check, both of which are happening in your code. Namely, your code allocates a new record in memory for each row in the CSV file. It also checks each field for valid UTF-8. Both of these have costs, but they do provide a fairly simple API that is decently fast as it is.

Additionally, one tip that isn't mentioned in the tutorial is to use csv::Writer::write_byte_record when possible instead of csv::Writer::write_record. The latter is more flexible, but the former constrains the input a bit more such that it can implement writes more efficiently in common scenarios.

Overall, making these changes is pretty easy:

use std::error::Error;

fn main() {
    read_and_write("rows.csv", "rows-copy.csv").unwrap();
}

fn read_and_write(
    in_file_path: &str,
    out_file_path: &str,
) -> Result<(), Box<dyn Error>> {
    let mut rdr = csv::ReaderBuilder::new()
        .has_headers(false)
        .from_path(in_file_path)?;
    let mut wtr = csv::WriterBuilder::new()
        .from_path(out_file_path)?;

    let mut record = csv::ByteRecord::new();
    while rdr.read_byte_record(&mut record)? {
        wtr.write_byte_record(&record)?;
    }
    wtr.flush()?;

    Ok(())
}

Here is the timing for your code on my Linux system:

$ time ./target/release/csvsoperf

real    21.518
user    19.315
sys     2.189
maxmem  6 MB
faults  0

And here is the timing for my updated code:

$ time ./target/release/csvsoperf

real    12.057
user    9.924
sys     2.125
maxmem  6 MB
faults  0

Profiling the faster code, about 56% of the time is being spent in csv::Reader::read_byte_record, while about 29% of the time is being spent in csv::Writer::write_byte_record. This seems about right to me, and suggests your program isn't really doing anything that is additionally sub-optimal. There are no real bottlenecks outside of csv itself to optimize for.

Clearly when reading the CSV in my code I'm doing more work than a simple copy, but I was surprised that it would be ~6 times slower than the copy.

It's easy to be surprised when using pathological or very constrained inputs. Your example CSV data is very simple, and indeed, there are (obviously) much faster ways to parse and write data if it follows that format. But a CSV parser doesn't know that and must be able to handle the full format, which includes dealing with escaping and quoting. The csv parser has had a lot of optimization work done to it, and should generally be one of the faster CSV parsers in existence. So the more appropriate comparison here should be another CSV parser. It's not surprise that a dumb copy of the data is going to be substantially faster than a parser that is doing non-trivial work on the input.


来源: stackexchange

问:
Why HTTP was designed to be a pull protocol?
I was watching many presentations about Html 5 WebSockets , where server can initialize connection with client and push the data without the request from the client.

We don't need Polling etc.

And , I am curious , why Http was designed as a "pull" and not full duplex protocol in the first place ? What where the reasons behind that kind of decision ?

答: Because when http was first designed it was meant to be used to retrieve documents from a server. And the easiest way to do is when the client asks the server for a document and gets it delivered as response (or an error in case it does not exist). When you have push protocol that means the server would need to keep client connections around for potentially a long time creating more resource management problems - remember we are talking about early 1990s here.</p>

ContentLicense: CC BY-SA 3.0


问:
overiding class attributes but not methods in the child class
I have this problem, for example I define a Vehicle class as such.

```<code>class Vehicle():
    speed = 0
    def __init__(self):
        pass
    def get_speed(self):
        return Vehicle.speed
</code>```

I have a class attribute speed which I will override in the Bike child class

```<code>class Bike(Vehicle):
   speed = 20
</code>```

if I instantiate a new object of type Bike I get this

```<code>>>> a = Bike()
>>> a.get_speed()
0
</code>```

How do I make it to get without having to override parent class methods.

```<code>>>> a.get_speed()
20
</code>```

I do have a solution but I don't know if it is a good programming practice or not, because instance variables should be unique to that instance, so now I am very much confused.

```<code>class Vehicle():
   def __init__(self):
      self.speed = 0

   def get_speed(self):
      return self.speed

class Bike(Vehicle):
   def __init__(self):
      self.speed = 20
</code>```

should I re-declare it as an instance variable so that if I override self.speed = 20 in the constructor then I get

```<code>>>> a = Bike()
>>> a.get_speed()
20
</code>```

Any help would be much appreciated, thanks a lot in advance.

答:
If an attribute cannot be found in an object's __dict__, i.e. when it is not an instance attribute, Python will look for that attribute in the class next.

That's why you can simply do:

```<code>>>> class Vehicle:
...     speed = 0
...     def get_speed(self):
...         return self.speed
...
>>> class Bike(Vehicle):
...     speed = 20
...
>>> a = Bike()
>>> a.get_speed()
20
</code>```

Additionally, I would get rid of that get_speed method. Writing getters and setters is not idiomatic Python. Simply use a.speed.

If you want to protect the attribute against being set, consider using properties.

ContentLicense: CC BY-SA 4.0

Body:
I have this problem, for example I define a Vehicle class as such.

class Vehicle():
    speed = 0
    def __init__(self):
        pass
    def get_speed(self):
        return Vehicle.speed

I have a class attribute speed which I will override in the Bike child class

class Bike(Vehicle):
   speed = 20

if I instantiate a new object of type Bike I get this

>>> a = Bike()
>>> a.get_speed()
0

How do I make it to get without having to override parent class methods.

>>> a.get_speed()
20

I do have a solution but I don't know if it is a good programming practice or not, because instance variables should be unique to that instance, so now I am very much confused.

class Vehicle():
   def __init__(self):
      self.speed = 0

   def get_speed(self):
      return self.speed

class Bike(Vehicle):
   def __init__(self):
      self.speed = 20

should I re-declare it as an instance variable so that if I override self.speed = 20 in the constructor then I get

>>> a = Bike()
>>> a.get_speed()
20

Any help would be much appreciated, thanks a lot in advance.

Body:
If an attribute cannot be found in an object's __dict__, i.e. when it is not an instance attribute, Python will look for that attribute in the class next.

That's why you can simply do:

>>> class Vehicle:
...     speed = 0
...     def get_speed(self):
...         return self.speed
...
>>> class Bike(Vehicle):
...     speed = 20
...
>>> a = Bike()
>>> a.get_speed()
20

Additionally, I would get rid of that get_speed method. Writing getters and setters is not idiomatic Python. Simply use a.speed.

If you want to protect the attribute against being set, consider using properties.


问:
Reading several datasets
I need to read 8 datasets:

```<code>df01, df02, df03, df04, df05, df06, df07, df08
</code>```

This is my current approach:

```<code>#Set up file paths

filepath_2_df01= "folderX/df01.csv"
filepath_2_df02= "folderX//df02.csv"
filepath_2_df03= "folderX//df03.csv"
filepath_2_df04= "folderX//df04.csv"

filepath_2_df05= "folderY/df05.csv"
filepath_2_df06= "folderY/df06.csv"
filepath_2_df07= "folderY/df07.csv"
filepath_2_df08= "folderY/df08.csv"

#Read files

df01= pd.read_csv(filepath_2_df01)
df02= pd.read_csv(filepath_2_df02)
df03= pd.read_csv(filepath_2_df03)
df04= pd.read_csv(filepath_2_df04)

df05= pd.read_csv(filepath_2_df05)
df06= pd.read_csv(filepath_2_df06)
df07= pd.read_csv(filepath_2_df07)
df08= pd.read_csv(filepath_2_df08)
</code>```

Is there a more concise way of doing that?

答:
You can use glob for this:

```<code>import glob

dfs = []
for file in glob.glob('folderX/*.csv'):
    dfs.append(pd.read_csv(file))

for df in dfs:
    print(df)
</code>```

Title: Reading several datasets

Body:
I need to read 8 datasets:

df01, df02, df03, df04, df05, df06, df07, df08

This is my current approach:

#Set up file paths

filepath_2_df01= "folderX/df01.csv"
filepath_2_df02= "folderX//df02.csv"
filepath_2_df03= "folderX//df03.csv"
filepath_2_df04= "folderX//df04.csv"

filepath_2_df05= "folderY/df05.csv"
filepath_2_df06= "folderY/df06.csv"
filepath_2_df07= "folderY/df07.csv"
filepath_2_df08= "folderY/df08.csv"

#Read files

df01= pd.read_csv(filepath_2_df01)
df02= pd.read_csv(filepath_2_df02)
df03= pd.read_csv(filepath_2_df03)
df04= pd.read_csv(filepath_2_df04)

df05= pd.read_csv(filepath_2_df05)
df06= pd.read_csv(filepath_2_df06)
df07= pd.read_csv(filepath_2_df07)
df08= pd.read_csv(filepath_2_df08)

Is there a more concise way of doing that?

Body:
You can use glob for this:

import glob

dfs = []
for file in glob.glob('folderX/*.csv'):
    dfs.append(pd.read_csv(file))

for df in dfs:
    print(df)


问:
Copying a text from UILabel in iPhone
I have a situation where i want to copy the text from UILabel as a default cut/copy menu which appears in iPhone.I know that i can use a UITextField for enabling this menu but the key pad pops up and when i make the editing to return no,the keypad is not showing up and the default copy/cut menu is also not showing up.

I tried to use UITextView and unchecked the diting property in the properties of the UITextView,but it didn't gave me a proper solution.Because when the font exceeds the UITextView's height. It goes to the next line and it cannot be aligned properly in a view which i have now.

I came across this post "Show iPhone cut copy paste menu on UILabel" in stack overflow itself which says the same functionality which I need.

I downloaded the source code from git but I got 23 errors.

How can  implement this ?

答:
This github project is compiled fine and I have tested it it's working

 UILabel copy using menu

Title: Copying a text from UILabel in iPhone


问:
Cannot set headers after they are sent to the client - Sendgrid
I have a question. I am trying to program a backend which gets an request from client site and the server response is an email. Also I want to save the data in an DB. Basically I have a form on the client site and I just want to save the data and send the data via email to the user. The strange thing is, it is working, but I am getting also this answer:

»Cannot set headers after they are sent to the client«

Could someone give me maybe a hint why it is like this?

```<code>const Briefing = require("../models/briefing");
const sgMail = require("@sendgrid/mail");
sgMail.setApiKey(process.env.EMAIL_API_KEY);

exports.briefing = (req, res) => {
  const {
    gender,
    age,
    income,
  } = req.body;

  let newBriefing = new Briefing({
    gender,
    age,
    income,
  });

  newBriefing.save((err, success) => {
    if (err) {
      console.log("ERROR CREATING BRIEFING", err);
      return res.status(400).json({
        error: err,
      });
    }
    res.json({
      message: "Briefing successfull created",
    });
  });

  const emailData = {
    to: process.env.EMAIL_TO,
    from: process.env.EMAIL_FROM,
    subject: `Briefing`,
    text: "Eine Aufstellung des erstellten Briefings",
    html: `
        <h1>Das Briefing</h1>
        <p>Vielen dank, dass du dir die Zeit genommen hast dieses Briefing zu erstellen.</p>
        <p>Hier vorab die Daten:</p>
        <p>${gender}</p>
        <p>${age}</p>
        <p>${income}</p>
        <p>desweiteren befindet sich im anhang eine PDF</p>
      `,
  };

  sgMail
    .send(emailData)
    .then((send) => {
      console.log("SIGNUP EMAIL SEND", send);
      return res.json({
        message: `Email has been sent to social@moritzwright.com follow the instruction to activate your account.`,
      });
    })
    .catch((err) => {
      console.log("EMAIL SENDING ERROR", err);
      console.error(err.response.body);
    });
};

</code>```

答:
I have fixed the problem in taking the process of sending the email after the if statement, like this:</p>

```<code>const Briefing = require("../models/briefing");
const sgMail = require("@sendgrid/mail");
sgMail.setApiKey(process.env.EMAIL_API_KEY);

exports.briefing = (req, res) => {
  const {
    gender,
    age,
    income,
  });

  newBriefing.save((err, success) => {
    if (err) {
      console.log("ERROR CREATING BRIEFING", err);
      return res.status(400).json({
        error: err,
      });
    }
    const emailData = {
      to: process.env.EMAIL_TO,
      from: process.env.EMAIL_FROM,
      subject: `Briefing`,
      text: "Eine Aufstellung des erstellten Briefings",
      html: `
            <h1>Das Briefing</h1>
            <p>Vielen dank, dass du dir die Zeit genommen hast dieses Briefing zu erstellen.</p>
            <p>Hier vorab die Daten:</p>
            <p>${gender}</p>
            <p>${age}</p>
            <p>${income}</p>
            <p>desweiteren befindet sich im anhang eine PDF</p>
          `,
    };

    sgMail
      .send(emailData)
      .then((send) => {
        console.log("SIGNUP EMAIL SEND", send);
        return res.json({
          message: `Email has been sent to social@moritzwright.com follow the instruction to activate your account.`,
        });
      })
      .catch((err) => {
        console.log("EMAIL SENDING ERROR", err);
        console.error(err.response.body);
      });
  });
};

</code>```

Body:
I have a question. I am trying to program a backend which gets an request from client site and the server response is an email. Also I want to save the data in an DB. Basically I have a form on the client site and I just want to save the data and send the data via email to the user. The strange thing is, it is working, but I am getting also this answer:

»Cannot set headers after they are sent to the client«

Could someone give me maybe a hint why it is like this?

const Briefing = require("../models/briefing");
const sgMail = require("@sendgrid/mail");
sgMail.setApiKey(process.env.EMAIL_API_KEY);

exports.briefing = (req, res) => {
  const {
    gender,
    age,
    income,
  } = req.body;

  let newBriefing = new Briefing({
    gender,
    age,
    income,
  });

  newBriefing.save((err, success) => {
    if (err) {
      console.log("ERROR CREATING BRIEFING", err);
      return res.status(400).json({
        error: err,
      });
    }
    res.json({
      message: "Briefing successfull created",
    });
  });

  const emailData = {
    to: process.env.EMAIL_TO,
    from: process.env.EMAIL_FROM,
    subject: `Briefing`,
    text: "Eine Aufstellung des erstellten Briefings",
    html: `

Das Briefing

Vielen dank, dass du dir die Zeit genommen hast dieses Briefing zu erstellen.

Hier vorab die Daten:

${gender}

${age}

${income}

desweiteren befindet sich im anhang eine PDF

      `,
  };

  sgMail
    .send(emailData)
    .then((send) => {
      console.log("SIGNUP EMAIL SEND", send);
      return res.json({
        message: `Email has been sent to social@moritzwright.com follow the instruction to activate your account.`,
      });
    })
    .catch((err) => {
      console.log("EMAIL SENDING ERROR", err);
      console.error(err.response.body);
    });
};

Body:
I have fixed the problem in taking the process of sending the email after the if statement, like this:

const Briefing = require("../models/briefing");
const sgMail = require("@sendgrid/mail");
sgMail.setApiKey(process.env.EMAIL_API_KEY);

exports.briefing = (req, res) => {
  const {
    gender,
    age,
    income,
  });

  newBriefing.save((err, success) => {
    if (err) {
      console.log("ERROR CREATING BRIEFING", err);
      return res.status(400).json({
        error: err,
      });
    }
    const emailData = {
      to: process.env.EMAIL_TO,
      from: process.env.EMAIL_FROM,
      subject: `Briefing`,
      text: "Eine Aufstellung des erstellten Briefings",
      html: `
            <h1>Das Briefing</h1>
            <p>Vielen dank, dass du dir die Zeit genommen hast dieses Briefing zu erstellen.</p>
            <p>Hier vorab die Daten:</p>
            <p>${gender}</p>
            <p>${age}</p>
            <p>${income}</p>
            <p>desweiteren befindet sich im anhang eine PDF</p>
          `,
    };

    sgMail
      .send(emailData)
      .then((send) => {
        console.log("SIGNUP EMAIL SEND", send);
        return res.json({
          message: `Email has been sent to social@moritzwright.com follow the instruction to activate your account.`,
        });
      })
      .catch((err) => {
        console.log("EMAIL SENDING ERROR", err);
        console.error(err.response.body);
      });
  });
};


问:
How to store $_POST data into session variable if the form name=an array?
I want to store the session data into a session variable so that it can be used in another php page other than the action="addbill.php" in form.But the problem is i want to store the array name[] into the session variable but shows error.

```<code><form action="addbill.php" method="POST">
     <div id="dynamicInput">
     <br><input type="text" name="name[]">
     </div>
     <input type="button" value="Add another text input" onClick="addInput('dynamicInput');">
     <input type="submit"/>
</form>
</code>```

```<code><?php
 session_start();
 $_SESSION['addedmem']= $_POST['name'];
 var_dump($_SESSION['addedmem']);
?>
</code>```

```<code><script>
                var counter = 1;
                var limit = 4;
                function addInput(divName){
                     if (counter == limit)  {
                          alert("You have reached the limit of adding " + counter + " inputs");
                     }
                     else {
                          var newdiv = document.createElement('div');
                          newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
                          document.getElementById(divName).appendChild(newdiv);
                          counter++;
                     }
                }
</script>
</code>```

Output Error:Undefined index: name

"ANY HELP IS WELCOMED"

答:
Just change your form input name to be a standard variable, not an array:</p>

```<code><form action="addbill.php" method="POST">
     <div id="dynamicInput">
     <br><input type="text" name="name">
     </div>
     <input type="button" value="Add another text input" onClick="addInput('dynamicInput');">
     <input type="submit"/>
</form>
</code>```

Body:
I want to store the session data into a session variable so that it can be used in another php page other than the action="addbill.php" in form.But the problem is i want to store the array name[] into the session variable but shows error.

<form action="addbill.php" method="POST">

<input type="text" name="name[]">

     <input type="button" value="Add another text input" onClick="addInput('dynamicInput');">
     <input type="submit"/>
</form>

<?php
 session_start();
 $_SESSION['addedmem']= $_POST['name'];
 var_dump($_SESSION['addedmem']);
?>

Output Error:Undefined index: name

"ANY HELP IS WELCOMED"

Body:
Just change your form input name to be a standard variable, not an array:

<form action="addbill.php" method="POST">
     <div id="dynamicInput">
     <br><input type="text" name="name">
     </div>
     <input type="button" value="Add another text input" onClick="addInput('dynamicInput');">
     <input type="submit"/>
</form>


问:
Allure Report To Contain Multiple Test Projects
I'm looking to user Allure to report for my multiple test suites, what I would like to know is am I able to have multiple test projects under one allure instance.

My project is currently made up of:

2 UI projects

2 API projects

I currently have UI tests (cypress.io) for both projects and I'm working on building out the test framework for both API projects.

Can I organise allure so that I can navigate to one instance for all 4 test frameworks or will I have to have an allure instance for each of the test frameworks (resulting in 4 allure homepages).

答:
You can use Allure Docker Service, now provides support for multiple projects:
https://github.com/fescobar/allure-docker-service#MULTIPLE-PROJECTS---REMOTE-REPORTS</p>


问:
Reducer: getting information about value changes at the store
I don't understand how to get an updated value from the reducer store. For example, I have a React component. In this component after some actions, for example, after a few clicks on a button, I call the action from my reducer actions script like this.props.PostSomethingToServer(). Then the action sends some data to the node express server. The server makes some changes with data and then sends a response to the client store reducer. How can I get the updated data from the reducer store? I need to call another function in this React component with updated values.
By the way, I use  mapStateToProps and export default connect() in the React component. As I know, mapStateToProps and export default connect() help to get data from the store before render(). But I still don't understand how to get updated data from the store after some actions.
A couple of code:
React component:

```<code>ChangeArrayData(){
let something = [];
// filling this array and modifying values
//then I call the action
this.props.postSomethingToServer(something);//something will be changed by server logic and will be returned with updated data by a response.
//then I wanna export the data to .excel, for example
this.ExportToExcel(); // here I have to get updated data from the reducer, but I don't have any information about changes in the reducer.
}
</code>```

Reducer action:

```<code>export const postSomethingToServer= rankedElements => dispatch => {
    axios
      .post("/api/postData", elements)
      .then(response => {
        dispatch({
          type: POST_SOMETHING_SUCCESSFUL,
          status : "success",
          payload:  response.data
        });
//... etc.
</code>```

Reducer:

```<code>const initialState = {
    something: {},
    status: "",
    error : ""
};

export default function(state = initialState, action) {
  switch (action.type) {
    case POST_SOMETHING:
      return {
        ...state,
        status: action.status,
      }
    case POST_SOMETHING_SUCCESSFUL:
      return {
        ...state,
        status: action.status,
        something: action.payload
      }
    case GET_ERRORS:
      return {
        ...state,
        status: action.status,
        error: action.error
      }
    default:
      return state;
  }
}
</code>```

答:
After you dispatch the action, your reducer state something should have the data you expect. Given that you have mapped the data in your mapStateToProps function you can access it via props.

ChangeArrayData() {
  let something = [];
  this.props.postSomethingToServer(something);
  this.ExportToExcel();
  console.log(this.props.somethingReducerState);
}

const mapStateToProps = (state) => ({
  somethingReducerState: state.yourReducerName.something,
});
```

Body:
I don't understand how to get an updated value from the reducer store. For example, I have a React component. In this component after some actions, for example, after a few clicks on a button, I call the action from my reducer actions script like this.props.PostSomethingToServer(). Then the action sends some data to the node express server. The server makes some changes with data and then sends a response to the client store reducer. How can I get the updated data from the reducer store? I need to call another function in this React component with updated values.
By the way, I use  mapStateToProps and export default connect() in the React component. As I know, mapStateToProps and export default connect() help to get data from the store before render(). But I still don't understand how to get updated data from the store after some actions.
A couple of code:
React component:

ChangeArrayData(){
let something = [];
// filling this array and modifying values
//then I call the action
this.props.postSomethingToServer(something);//something will be changed by server logic and will be returned with updated data by a response.
//then I wanna export the data to .excel, for example
this.ExportToExcel(); // here I have to get updated data from the reducer, but I don't have any information about changes in the reducer.
}

Reducer action:

export const postSomethingToServer= rankedElements => dispatch => {
    axios
      .post("/api/postData", elements)
      .then(response => {
        dispatch({
          type: POST_SOMETHING_SUCCESSFUL,
          status : "success",
          payload:  response.data
        });
//... etc.

Reducer:

const initialState = {
    something: {},
    status: "",
    error : ""
};

export default function(state = initialState, action) {
  switch (action.type) {
    case POST_SOMETHING:
      return {
        ...state,
        status: action.status,
      }
    case POST_SOMETHING_SUCCESSFUL:
      return {
        ...state,
        status: action.status,
        something: action.payload
      }
    case GET_ERRORS:
      return {
        ...state,
        status: action.status,
        error: action.error
      }
    default:
      return state;
  }
}


问:
Vue.js list not updating despite array change via assignment
I'm new to vue.js but I'm trying to display a list of options from an underlying array. However, when the underlying array is changed the list does not update/re-render. I am assigning the new array directly to the vue instance data value (not using splice or assigning via index) and in the console if I try and print out the underlying data (vm.clarifyings) that is updated, it is just the re-rendering that is not working. Even using vm.clarifyings.push(object) does not update the view in the browser.

 Vue instance code:

```<code>var vm = new Vue({
    delimiters: ['$[', '$]'], //change delimiters to allow django integration
    el: '#vue_app',
    data: {
        title: init_info.title, //page title
        active: 'presentations',
        navClass: 'nav-item nav-link', //necessary for navbar rendering
        features: features,
        question: '',
        response: '',
        feature_id: init_info.opening,
        last_feature: '',
        clarif_id: '',
        clarifyings: [],
        show_clarifying: false,
    },
</code>```

Relevant method update:

```<code>fetch(url)
  .then(response => response.json())
  .then(function (data) {
      // Type out question and response
      typeWriter(data.question, 'question');
      typeWriter(data.answer, 'response');
      // Save selected option and disable previous selected option
      option_disable(vm.last_feature);
      vm.last_feature = option_ref;
      // Show clarifying questions
      vm.clarifyings = data.clarifyings;
      if (vm.clarifyings.length){
          vm.show_clarifying = true;
      }
      else {
          vm.show_clarifying = false;
      }
  }
</code>```

All of this executes normally it is simply the re-rendering that isn't working. If I specify the array when I initialize the Vue instance it renders properly it simply does not update.

HTML code:

```<code><select class="selectpicker" data-live-search="true" v-model="clarif_id">
        <option v-for="question in clarifyings">$[question.id$] - $[question.name$]</option>
    </select>
</code>```

答:
The problem appeared to be a result of interference with bootstrap-selectpicker, it was fixed by using nextTick functionality in vue like so:</p>

```<code> if (feature_asked) {
            vm.clarifyings = data.clarifyings;
            if (vm.clarifyings.length) {
              vm.show_clarifying = true;
              vm.$nextTick(function () {
                $("#clarifying_qs").selectpicker("refresh");
              });
</code>```

Body:
I'm new to vue.js but I'm trying to display a list of options from an underlying array. However, when the underlying array is changed the list does not update/re-render. I am assigning the new array directly to the vue instance data value (not using splice or assigning via index) and in the console if I try and print out the underlying data (vm.clarifyings) that is updated, it is just the re-rendering that is not working. Even using vm.clarifyings.push(object) does not update the view in the browser.

 Vue instance code:

var vm = new Vue({
    delimiters: ['$[', '$]'], //change delimiters to allow django integration
    el: '#vue_app',
    data: {
        title: init_info.title, //page title
        active: 'presentations',
        navClass: 'nav-item nav-link', //necessary for navbar rendering
        features: features,
        question: '',
        response: '',
        feature_id: init_info.opening,
        last_feature: '',
        clarif_id: '',
        clarifyings: [],
        show_clarifying: false,
    },

Relevant method update:

fetch(url)
  .then(response => response.json())
  .then(function (data) {
      // Type out question and response
      typeWriter(data.question, 'question');
      typeWriter(data.answer, 'response');
      // Save selected option and disable previous selected option
      option_disable(vm.last_feature);
      vm.last_feature = option_ref;
      // Show clarifying questions
      vm.clarifyings = data.clarifyings;
      if (vm.clarifyings.length){
          vm.show_clarifying = true;
      }
      else {
          vm.show_clarifying = false;
      }
  }

All of this executes normally it is simply the re-rendering that isn't working. If I specify the array when I initialize the Vue instance it renders properly it simply does not update.

HTML code:

<select class="selectpicker" data-live-search="true" v-model="clarif_id">
        <option v-for="question in clarifyings">$[question.id$] - $[question.name$]</option>
    </select>

Body:
The problem appeared to be a result of interference with bootstrap-selectpicker, it was fixed by using nextTick functionality in vue like so:

 if (feature_asked) {
            vm.clarifyings = data.clarifyings;
            if (vm.clarifyings.length) {
              vm.show_clarifying = true;
              vm.$nextTick(function () {
                $("#clarifying_qs").selectpicker("refresh");
              });


问:
Making git auto-commit
I'd like to use git to record all the changes to a file.

Is there a way I can turn git 'commit' on to automatically happen every time a file is updated - so there is a new commit for every change to a file?

Ideally I'd like my users to not even know that git is running behind the scenes. A user could then potentially "undo" changes to a file - and this could be achieved by pulling a previous version out of git.

答:
For Windows

According to this article about autocommit, you shou create .bat file with content:

```<code>git add -u
git commit -m "your commit message"
git push origin master
</code>```

and execute with Task Scheduler. If you don't know how to do step-by-step, refer that article.

OwnerDisplayName: git-noob

ContentLicense: CC BY-SA 2.5

Title: Making git auto-commit

Body:
For Windows

According to this article about autocommit, you shou create .bat file with content:

git add -u
git commit -m "your commit message"
git push origin master

and execute with Task Scheduler. If you don't know how to do step-by-step, refer that article.


问:
Building an arc (an array of segments) at three points
I have the coordinates of three points. I want to build an arc on them

An arc (non-ideal) consists of segments (let 10 segments).

I need having the coordinates of three points to get an array of arc segments at these points

How can I do this?

答:
A way, definitely no the shortest way, could be the following.
You have 3 point, thus you can write the circonference equation(x2+y2+ax+by+c=0) (for three points pass only a circonference). This is a matter of solving a system of 3 equations in three unknowns. Now given the 2 outermost points,(x1,y1) and (x2,y2), you can calculate the cord length with Pitagora theorem:

cord = √(y2-y1)2+(x2-x1)2

Now use the theorem of the cord to find the angle in the center that I call alpha  thus:

```<code>sin(alpha/2) = cord/2*radius
</code>```

Having the circonference equation is easy to calculate the radius.
Now that you have alpha you can split the angle in 20 parts. For example if alpha is 160 you get Beta=8

Now you can do:

```<code>P0 x1,y1
P1 cos(180-8),sin(180-8)
P2 cos(180-16),sin(180-16)
.
.
.
</code>```

and so on until to 160 in my example.
But Attention!  Those above are relative coordinates, relative to the center of the circonference. Called the center (c1,c2) the coordinates will be:

```<code>P0 x1,y1
P1 c1+cos(180-8),c2+sen(180-8)
P2 c1+cos(180-16),c2+sin(180-16)
.
.
.
</code>```

Body:
A way, definitely no the shortest way, could be the following.
You have 3 point, thus you can write the circonference equation(x2+y2+ax+by+c=0) (for three points pass only a circonference). This is a matter of solving a system of 3 equations in three unknowns. Now given the 2 outermost points,(x1,y1) and (x2,y2), you can calculate the cord length with Pitagora theorem:

cord = √(y2-y1)2+(x2-x1)2

Now use the theorem of the cord to find the angle in the center that I call alpha  thus:

sin(alpha/2) = cord/2*radius

Having the circonference equation is easy to calculate the radius.
Now that you have alpha you can split the angle in 20 parts. For example if alpha is 160 you get Beta=8

Now you can do:

P0 x1,y1
P1 cos(180-8),sin(180-8)
P2 cos(180-16),sin(180-16)
.
.
.

and so on until to 160 in my example.
But Attention!  Those above are relative coordinates, relative to the center of the circonference. Called the center (c1,c2) the coordinates will be:

P0 x1,y1
P1 c1+cos(180-8),c2+sen(180-8)
P2 c1+cos(180-16),c2+sin(180-16)
.
.
.


问:
How to add javascript to joomla module?
Hi I have problem with adding javascript into a joomla module..I've found some solution, but it's not working..

```<code>$document = &JFactory::getDocument();
$document->addScript("/career.js");
</code>```

These two lines I have in my module, but the script isn't in rendered site..
The file is in root of my web (for test purposes only).

Thanks for your help

答:
You could also use the joomla php module
http://www.fijiwebdesign.com/products/joomla-php-module.html
or maybe you found a module that better fits your needs at:
http://extensions.joomla.org/extensions/edition/custom-code-in-modules</p>

Title: How to add javascript to joomla module?

Body:
Hi I have problem with adding javascript into a joomla module..I've found some solution, but it's not working..

$document = &JFactory::getDocument();
$document->addScript("/career.js");

These two lines I have in my module, but the script isn't in rendered site..
The file is in root of my web (for test purposes only).

Thanks for your help


问:
How to link multiple GUIs in netbeans
I am new to this GUI stuff on NetBeans, so could someone please explain how to link multiple GUIs into one? This I should mention is in a java format.</p>

答:
If you want to open another gui from a specific gui, you should give an event to a button.

For example, if you want to open anothergui from maingui, you can create an event for a button which says anothergui is new anothergui, then you can set visibility true for anothergui.

Title: How to link multiple GUIs in netbeans


问:
Handling null in ReactJS
I have table, filling from Web - Api.

When I am deleting department, linked to some user. Department object getting null. And I have crash of my react app with such error: TypeError: Cannot read property 'name' of null

I've tried ternary like that, but it didn't help

```<code>(typeof user !=='undefined' && typeof user.department.name !=='undefined') ? user.department.name : ''
</code>```

  refreshList()
    {
       fetch("https://localhost:5001/api/users")
       .then(response=> response.json())
       .then(data=> {
        this.setState({users:data});
       });
    }

render(){
        const {users, userid, username, userfullname, department} = this.state;
        return(

           {users.map(user=>

               {user.id}
               {user.userName}
               {user.fullName}
               {user.department.name}	  <---- here i am getting crash when department is null

               ....
               )```

答:
Please correct your ternary as follows...

```<code>{user.department ? user.department.name : ''}
</code>```

Here, it only checks for user.department.name if and only if user.department is NOT null.

Title: Handling null in ReactJS

Body:
I have table, filling from Web - Api.

When I am deleting department, linked to some user. Department object getting null. And I have crash of my react app with such error: TypeError: Cannot read property 'name' of null

I've tried ternary like that, but it didn't help

(typeof user !=='undefined' && typeof user.department.name !=='undefined') ? user.department.name : ''

  refreshList()
    {
       fetch("https://localhost:5001/api/users")
       .then(response=> response.json())
       .then(data=> {
        this.setState({users:data});
       });
    }

render(){
        const {users, userid, username, userfullname, department} = this.state;
        return(

           {users.map(user=>

               {user.id}
               {user.userName}
               {user.fullName}
               {user.department.name}	  <---- here i am getting crash when department is null

               ....
               )

Body:
Please correct your ternary as follows...

{user.department ? user.department.name : ''}

Here, it only checks for user.department.name if and only if user.department is NOT null.


问:
Powershell 7 - Parallel While Loops
I'm running PowerShell 7 and since workflows are no longer supported, I'm running into an issue with parallel while loops. Keeping the example below simple, I just need to run both while's in parallel in the same script but need to ensure that the sleep command works as well within the while loop.

I can't figure a good way of doing this with foreach-object and doing background jobs with while loops - the sleep command never activates driving up CPU. Should be simple but not finding much out there. Again, below is just a simple example of what I need to run.

```<code>while ($true)
{
    write-host "Doing first task"
    Start-Sleep 2
}

while ($true)
{
    write-host "Doing second task"
    Start-Sleep 2
}
</code>```

答:
I couldn't pass an array of scriptblocks to foreach-object, so here's a start-threadjob version, which is similar.

I think you mean to have a semicolon before start-sleep to start a new statement.

```<code>start-threadjob { while ($true) {
  write-host Doing first task; Start-Sleep 2 } }
start-threadjob { while ($true) {
  write-host Doing second task; Start-Sleep 2 } }
get-job | receive-job -wait -autoremovejob

Doing first task
Doing second task
Doing first task
Doing second task
Doing first task
Doing second task
# ...
</code>```

Ah, here's a way.  And the output order varies randomly.

The two tasks could also be scripts, but not functions.

```<code>1,2 | foreach-object -parallel {
  switch ($_) {
    1 { while ($true) { write-host Doing first task; Start-Sleep 2 } }
    2 { while ($true) { write-host Doing second task; Start-Sleep 2 } }
  }
}

Doing first task
Doing second task
Doing second task
Doing first task
Doing second task
Doing first task
# ...
</code>```

Title: Powershell 7 - Parallel While Loops

Body:
I'm running PowerShell 7 and since workflows are no longer supported, I'm running into an issue with parallel while loops. Keeping the example below simple, I just need to run both while's in parallel in the same script but need to ensure that the sleep command works as well within the while loop.

I can't figure a good way of doing this with foreach-object and doing background jobs with while loops - the sleep command never activates driving up CPU. Should be simple but not finding much out there. Again, below is just a simple example of what I need to run.

while ($true)
{
    write-host "Doing first task"
    Start-Sleep 2
}

while ($true)
{
    write-host "Doing second task"
    Start-Sleep 2
}

Body:
I couldn't pass an array of scriptblocks to foreach-object, so here's a start-threadjob version, which is similar.

I think you mean to have a semicolon before start-sleep to start a new statement.

start-threadjob { while ($true) {
  write-host Doing first task; Start-Sleep 2 } }
start-threadjob { while ($true) {
  write-host Doing second task; Start-Sleep 2 } }
get-job | receive-job -wait -autoremovejob

Doing first task
Doing second task
Doing first task
Doing second task
Doing first task
Doing second task
# ...

Ah, here's a way.  And the output order varies randomly.

The two tasks could also be scripts, but not functions.

1,2 | foreach-object -parallel {
  switch ($_) {
    1 { while ($true) { write-host Doing first task; Start-Sleep 2 } }
    2 { while ($true) { write-host Doing second task; Start-Sleep 2 } }
  }
}

Doing first task
Doing second task
Doing second task
Doing first task
Doing second task
Doing first task
# ...


问:
How do you put an onclick on a js button
I have some js created buttons from GeeksforGeeks, but I don't know how to put on click on the buttons. I can create a button using the code I found online, but there was no explanation on how to make that button have on click function</p>

答:
<!DOCTYPE html>

        <button id="btnDemo">On-click Demo</button>

```

<p>java script Code : </p>

<pre class="lang-js prettyprint-override"><code>var btn = document.getElementById('btnDemo');
btn.onClick = function(){
  alert('button is clicked..');
}
</code>```

Jquery Code :

```<code>var btn = $('#btnDemo');
btn.click(function(){
  alert('button is clicked..');
});
</code>```

Body:
<!DOCTYPE html>
<html>
    <body>
        <button id="btnDemo">On-click Demo</button>
    </body>
</html>

java script Code :

var btn = document.getElementById('btnDemo');
btn.onClick = function(){
  alert('button is clicked..');
}

Jquery Code :

var btn = $('#btnDemo');
btn.click(function(){
  alert('button is clicked..');
});


问:
React Functional Component, Redux and Loading Data
I am currently trying to pick up functional react and am having a tough time figuring out the appropriate way to load data from an API on page load. I am using react, redux and thunks. I have modified the project that i created from this course. My code currently looks like this

store.js

```<code>import {createStore, applyMiddleware, compose} from "redux";
import rootReducer from "./reducers";
import reduxImmutableStateInvariant from 'redux-immutable-state-invariant';
import thunk from "redux-thunk";

export default function configureStoreDev(initialState){

    const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; // add support for redux dev tools

    return createStore(
        rootReducer,
        initialState,
        composeEnhancers(applyMiddleware(thunk, reduxImmutableStateInvariant()))
    );
}
</code>```

authorApi.js

```<code>import { handleResponse, handleError } from "./apiUtils";
const baseUrl = process.env.API_URL + "/authors/";

export function getAuthors() {
  return fetch(baseUrl)
    .then(handleResponse)
    .catch(handleError);
}
</code>```

authorActions.js

```<code>import * as actionTypes from "./actionTypes";
import * as authorApi from "../../api/authorApi";
import {apiCallError, beginApiCall} from "./apiStatusAction";

export function loadAuthorsSuccess(authors){
    return {type: actionTypes.LOAD_AUTHORS_SUCCESS, authors: authors};
}

export function loadAuthors(){
    return function(dispatch){

        // invoke loader
        dispatch(beginApiCall());

        return authorApi.getAuthors().then(response => {
            dispatch(loadAuthorsSuccess(response.authors));
        }).catch(error => {
            dispatch(apiCallError());
            throw error;
        })
    }
}
</code>```

authorReducer.js

```<code>import * as actionTypes from "../actions/actionTypes";
import initialState from "./initialState";

export default function authorReducer(state = initialState.authors, action){
    switch(action.type){
        case actionTypes.LOAD_AUTHORS_SUCCESS:
            return action.authors;
        default:
            return state;
    }
}
</code>```

AuthorsPage.js

```<code>import React, {useState, useEffect} from 'react';
import {connect} from 'react-redux';
import AuthorsList from "./AuthorsList";
import Spinner from "../common/Spinner";

import {loadAuthors} from "../../redux/actions/authorActions";
import {loadCourses} from "../../redux/actions/courseActions";

function AuthorsPage({loadAuthors, deleteAuthor, loadCourses, ...props}) {
    const [authors, setAuthors] = useState([...props.authors]);
    const [courses, setCourses] = useState([...props.courses]);
    const [loading, setLoading] = useState(props.loading);
    const [redirectToAddAuthorPage, setRedirectToAddAuthorPage] = useState(false);

    useEffect(() => {
        loadAuthors().catch(error => {
            console.log("Loading authors failed: " + error);
        });
        loadCourses().catch(error => {
            console.log("Loading courses failed: " + error);
        });
    }, []);

    useEffect(() => {
        if(authors !== props.authors && props.authors.length > 0){
            setAuthors([...props.authors]);
        }
    }, [props.authors]);

    useEffect(() => {
        setLoading(props.loading)
    }, [props.loading]);

    return (
        <>
            <h2>Authors</h2>
            {loading === true ? <Spinner/> : (
                <>
                    <button
                        style={{ marginBottom: 20 }}
                        className="btn btn-primary add-course"
                        onClick={() => setRedirectToAddAuthorPage(true )}
                    >
                        Add Author
                    </button>
                    <AuthorsList authors={authors}  />
                </>
            )}

        </>
    );
}

function mapStateToProps(state){
    return {
        authors: state.authors,
        courses: state.courses,
        loading: state.apiCallsInProgress > 0

    }
}
const mapDispatchToProps = {
    loadAuthors: loadAuthors,
    loadCourses: loadCourses
}

export default connect(mapStateToProps, mapDispatchToProps)(AuthorsPage);
</code>```

The part that i am having trouble with is getting the state for the authors list to set appropriately. I tried setting it after the call to loadAuthors() but am not getting the authors list returned in the .then() of that call.

The next option was to listen for the author props to change with useEffect but this doesn't seem to be the most efficient or correct way of loading the data that i need on the initial load.

I cant seem to find any articles or tutorials detailing the appropriate method to accomplish this from a functional component perspective and would appreciate any guidance or pointers in the right direction.

答:
The next option was to listen for the author props to change with
  useEffect but this doesn't seem to be the most efficient or correct
  way of loading the data that i need on the initial load.

You could render props.authors directly without assigning it to useState

Example

const thunk = ReduxThunk.default;

const { connect, Provider } = ReactRedux;
const { bindActionCreators, combineReducers, createStore, applyMiddleware } = Redux;
window.redux = Redux;

const initialState = {
  authors: []
};

const getAuthors = () => Promise.resolve(Array(10).fill(0).map((pr, index) => ({id: index, name: `Author ${index + 1}`})))

const loadAuthorsSuccess = (authors) => {
    return {type: 'LOAD_AUTHORS_SUCCESS', authors};
}

const loadAuthors = () => {

    return function(dispatch) {

        return getAuthors().then(authors => {
            dispatch(loadAuthorsSuccess(authors));
        })
    }
}

const authorReducer = (state = initialState.authors, action) => {

  switch(action.type) {
    case 'LOAD_AUTHORS_SUCCESS':
      return action.authors;
    default:
      return state;
  }
}

const reducer = combineReducers({
authors: authorReducer})
const store = createStore(
  reducer,
  initialState,
  applyMiddleware(thunk)
);

const { useState, useEffect } = React;

function mapStateToProps({authors}) {

  return {
      authors
  }
}
const mapDispatchToProps = {
  loadAuthors
}

const _AuthorsPage = ({loadAuthors, authors}) => {

  useEffect(() => {
    loadAuthors()
      .catch(error => {
        console.log("Loading authors failed: " + error);
      });
  }, [])

  return

    {authors.map(({id, name}) =>
{name}
)}

}

const AuthorsPage = connect(mapStateToProps, mapDispatchToProps)(_AuthorsPage)

const App = () => {

  return

    <AuthorsPage/>

}

ReactDOM.render(
    <Provider store={store}>
      <App />
    </Provider>,
    document.getElementById('root')
  );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/redux@4.0.5/dist/redux.js"></script>
<script src="https://unpkg.com/react-redux@latest/dist/react-redux.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux-thunk/2.3.0/redux-thunk.js"></script>
<div id="root"></div></code>```

Body:
I am currently trying to pick up functional react and am having a tough time figuring out the appropriate way to load data from an API on page load. I am using react, redux and thunks. I have modified the project that i created from this course. My code currently looks like this

store.js

import {createStore, applyMiddleware, compose} from "redux";
import rootReducer from "./reducers";
import reduxImmutableStateInvariant from 'redux-immutable-state-invariant';
import thunk from "redux-thunk";

export default function configureStoreDev(initialState){

    const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; // add support for redux dev tools

    return createStore(
        rootReducer,
        initialState,
        composeEnhancers(applyMiddleware(thunk, reduxImmutableStateInvariant()))
    );
}

authorApi.js

import { handleResponse, handleError } from "./apiUtils";
const baseUrl = process.env.API_URL + "/authors/";

export function getAuthors() {
  return fetch(baseUrl)
    .then(handleResponse)
    .catch(handleError);
}

authorActions.js

import * as actionTypes from "./actionTypes";
import * as authorApi from "../../api/authorApi";
import {apiCallError, beginApiCall} from "./apiStatusAction";

export function loadAuthorsSuccess(authors){
    return {type: actionTypes.LOAD_AUTHORS_SUCCESS, authors: authors};
}

export function loadAuthors(){
    return function(dispatch){

        // invoke loader
        dispatch(beginApiCall());

        return authorApi.getAuthors().then(response => {
            dispatch(loadAuthorsSuccess(response.authors));
        }).catch(error => {
            dispatch(apiCallError());
            throw error;
        })
    }
}

authorReducer.js

import * as actionTypes from "../actions/actionTypes";
import initialState from "./initialState";

export default function authorReducer(state = initialState.authors, action){
    switch(action.type){
        case actionTypes.LOAD_AUTHORS_SUCCESS:
            return action.authors;
        default:
            return state;
    }
}

AuthorsPage.js

import React, {useState, useEffect} from 'react';
import {connect} from 'react-redux';
import AuthorsList from "./AuthorsList";
import Spinner from "../common/Spinner";

import {loadAuthors} from "../../redux/actions/authorActions";
import {loadCourses} from "../../redux/actions/courseActions";

function AuthorsPage({loadAuthors, deleteAuthor, loadCourses, ...props}) {
    const [authors, setAuthors] = useState([...props.authors]);
    const [courses, setCourses] = useState([...props.courses]);
    const [loading, setLoading] = useState(props.loading);
    const [redirectToAddAuthorPage, setRedirectToAddAuthorPage] = useState(false);

    useEffect(() => {
        loadAuthors().catch(error => {
            console.log("Loading authors failed: " + error);
        });
        loadCourses().catch(error => {
            console.log("Loading courses failed: " + error);
        });
    }, []);

    useEffect(() => {
        if(authors !== props.authors && props.authors.length > 0){
            setAuthors([...props.authors]);
        }
    }, [props.authors]);

    useEffect(() => {
        setLoading(props.loading)
    }, [props.loading]);

    return (
        <>

Authors

            {loading === true ? <Spinner/> : (
                <>
                    <button
                        style={{ marginBottom: 20 }}
                        className="btn btn-primary add-course"
                        onClick={() => setRedirectToAddAuthorPage(true )}
                    >
                        Add Author
                    </button>
                    <AuthorsList authors={authors}  />
                </>
            )}

        </>
    );
}

function mapStateToProps(state){
    return {
        authors: state.authors,
        courses: state.courses,
        loading: state.apiCallsInProgress > 0

    }
}
const mapDispatchToProps = {
    loadAuthors: loadAuthors,
    loadCourses: loadCourses
}

export default connect(mapStateToProps, mapDispatchToProps)(AuthorsPage);

The part that i am having trouble with is getting the state for the authors list to set appropriately. I tried setting it after the call to loadAuthors() but am not getting the authors list returned in the .then() of that call.

The next option was to listen for the author props to change with useEffect but this doesn't seem to be the most efficient or correct way of loading the data that i need on the initial load.

I cant seem to find any articles or tutorials detailing the appropriate method to accomplish this from a functional component perspective and would appreciate any guidance or pointers in the right direction.

Body:
The next option was to listen for the author props to change with
  useEffect but this doesn't seem to be the most efficient or correct
  way of loading the data that i need on the initial load.

You could render props.authors directly without assigning it to useState

Example

const thunk = ReduxThunk.default;

const { connect, Provider } = ReactRedux;
const { bindActionCreators, combineReducers, createStore, applyMiddleware } = Redux;
window.redux = Redux;

const initialState = {
  authors: []
};

const getAuthors = () => Promise.resolve(Array(10).fill(0).map((pr, index) => ({id: index, name: `Author ${index + 1}`})))

const loadAuthorsSuccess = (authors) => {
    return {type: 'LOAD_AUTHORS_SUCCESS', authors};
}

const loadAuthors = () => {

    return function(dispatch) {

        return getAuthors().then(authors => {
            dispatch(loadAuthorsSuccess(authors));
        })
    }
}

const authorReducer = (state = initialState.authors, action) => {

  switch(action.type) {
    case 'LOAD_AUTHORS_SUCCESS':
      return action.authors;
    default:
      return state;
  }
}

const reducer = combineReducers({
authors: authorReducer})
const store = createStore(
  reducer,
  initialState,
  applyMiddleware(thunk)
);

const { useState, useEffect } = React;

function mapStateToProps({authors}) {

  return {
      authors
  }
}
const mapDispatchToProps = {
  loadAuthors
}

const _AuthorsPage = ({loadAuthors, authors}) => {

  useEffect(() => {
    loadAuthors()
      .catch(error => {
        console.log("Loading authors failed: " + error);
      });
  }, [])

  return <div>
    {authors.map(({id, name}) => <div key={id}>{name}</div>)}
  </div>
}

const AuthorsPage = connect(mapStateToProps, mapDispatchToProps)(_AuthorsPage)

const App = () => {

  return <div>
    <AuthorsPage/>
  </div>
}

ReactDOM.render(
    <Provider store={store}>
      <App />
    </Provider>,
    document.getElementById('root')
  );

<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/redux@4.0.5/dist/redux.js"></script>
<script src="https://unpkg.com/react-redux@latest/dist/react-redux.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux-thunk/2.3.0/redux-thunk.js"></script>
<div id="root"></div>


问:
Deep copying of elements in a List (Of Class)
Good evening.

I'm trying to do a deep copy of some of the elements of a list, and I'm finding it extremely hard to do. There's a lot of new concepts I'm trying so bear with me if some of the following code seems weird...

I have the following lists:

```<code>accountList as List(Of Account)
accountsInArea as New List(Of Account)
result as New List(Of Account)
</code>```

Where each element's type is a Class defined by myself:

```<code>Public Class Account

Enum AddingType
    income
    expenditure
End Enum
Enum AreaType
    high
    mid
    low
End Enum

Property Area() As AreaType
Property Group() As String
Property AccountNumber() As Integer
Property AccountDescription() As String
Property IncomeExpenditure() As AddingType
Public Property MonthlyValues As New Dictionary(Of Integer, Decimal)
End Class
</code>```

I need to find certain items of accountList and copy the values to a new list: accountsInArea. For now, I have used the following method:

```<code>accountsInArea = accountList.FindAll(Function(acc) acc.Area = area)
</code>```

However, this produces a copy of the reference to those items the Lambda Expression produces (doesn't it?). If I understood correctly while surfing around SO and MSDN, what I need is a deep copy of the elements.

I'd like accountsInArea to have a copy of all the items .FindAll produced, including (especially) those in the MonthlyValuesDictionary.

I have tried:

```<code>accountsInArea = accountList.Select(accountList.FindAll(Function(acc) acc.Area = area))
</code>```

Also:

```<code>For Each account In accountList.FindAll(Function(acc) acc.Area = area)
    accountsInArea.Add(account)
Next
</code>```

And lastly adding to the Class:

```<code>Implements ICloneable

Public Function Clone() As Object Implements System.ICloneable.Clone
    Return Me.MemberwiseClone
End Function
</code>```

And using inside the method:

```<code>accountsInArea = accountList.FindAll(Function(acc) acc.Area = area)
    result = accountsInArea.Select(Function(acc) acc.Clone()).Cast(Of Account).ToList
</code>```

Help would be GREATLY appreciated.

答:
just implement ICloneable in your Class, and

```<code>Dim accountsInArea As List(Of Account) = accountList.Where(Function(x) x.Area = Account.AreaType.high).Select(Function(y) y.clone).Cast(Of Account)().ToList
</code>```

here full code in your ex

```<code>Sub AccountListProg
    Dim accountList As New List(Of Account) From {New Account With {.Area = Account.AreaType.high, .AccountNumber = 1}, _
                                                   New Account With {.Area = Account.AreaType.high, .AccountNumber = 2}, _
                                                   New Account With {.Area = Account.AreaType.low, .AccountNumber = 3}, _
                                                   New Account With {.Area = Account.AreaType.mid, .AccountNumber = 4}}

    Dim accountsInArea As List(Of Account) = accountList.Where(Function(x) x.Area = Account.AreaType.high).Select(Function(y) y.clone).Cast(Of Account)().ToList
End Sub

Public Class Account
    Implements ICloneable
    Public Function Clone() As Object Implements ICloneable.Clone
        Return New Account With {.AccountDescription = AccountDescription, _
                             .AccountNumber = AccountNumber, _
                             .Area = Area, _
                             .Group = Group, _
                             .IncomeExpenditure = AddingType.income, _
                             .MonthlyValues = MonthlyValues}
    End Function
    Enum AddingType
        income
        expenditure
    End Enum
    Enum AreaType
        high
        mid
        low
    End Enum

    Property Area() As AreaType
    Property Group() As String
    Property AccountNumber() As Integer
    Property AccountDescription() As String
    Property IncomeExpenditure() As AddingType
    Public Property MonthlyValues As New Dictionary(Of Integer, Decimal)
End Class
</code>```

Body:
Good evening.

I'm trying to do a deep copy of some of the elements of a list, and I'm finding it extremely hard to do. There's a lot of new concepts I'm trying so bear with me if some of the following code seems weird...

I have the following lists:

accountList as List(Of Account)
accountsInArea as New List(Of Account)
result as New List(Of Account)

Where each element's type is a Class defined by myself:

Public Class Account

Enum AddingType
    income
    expenditure
End Enum
Enum AreaType
    high
    mid
    low
End Enum

Property Area() As AreaType
Property Group() As String
Property AccountNumber() As Integer
Property AccountDescription() As String
Property IncomeExpenditure() As AddingType
Public Property MonthlyValues As New Dictionary(Of Integer, Decimal)
End Class

I need to find certain items of accountList and copy the values to a new list: accountsInArea. For now, I have used the following method:

accountsInArea = accountList.FindAll(Function(acc) acc.Area = area)

However, this produces a copy of the reference to those items the Lambda Expression produces (doesn't it?). If I understood correctly while surfing around SO and MSDN, what I need is a deep copy of the elements.

I'd like accountsInArea to have a copy of all the items .FindAll produced, including (especially) those in the MonthlyValuesDictionary.

I have tried:

accountsInArea = accountList.Select(accountList.FindAll(Function(acc) acc.Area = area))

Also:

For Each account In accountList.FindAll(Function(acc) acc.Area = area)
    accountsInArea.Add(account)
Next

And lastly adding to the Class:

Implements ICloneable

Public Function Clone() As Object Implements System.ICloneable.Clone
    Return Me.MemberwiseClone
End Function

And using inside the method:

accountsInArea = accountList.FindAll(Function(acc) acc.Area = area)
    result = accountsInArea.Select(Function(acc) acc.Clone()).Cast(Of Account).ToList

Help would be GREATLY appreciated.

Body:
just implement ICloneable in your Class, and

Dim accountsInArea As List(Of Account) = accountList.Where(Function(x) x.Area = Account.AreaType.high).Select(Function(y) y.clone).Cast(Of Account)().ToList

here full code in your ex

Sub AccountListProg
    Dim accountList As New List(Of Account) From {New Account With {.Area = Account.AreaType.high, .AccountNumber = 1}, _
                                                   New Account With {.Area = Account.AreaType.high, .AccountNumber = 2}, _
                                                   New Account With {.Area = Account.AreaType.low, .AccountNumber = 3}, _
                                                   New Account With {.Area = Account.AreaType.mid, .AccountNumber = 4}}

    Dim accountsInArea As List(Of Account) = accountList.Where(Function(x) x.Area = Account.AreaType.high).Select(Function(y) y.clone).Cast(Of Account)().ToList
End Sub

Public Class Account
    Implements ICloneable
    Public Function Clone() As Object Implements ICloneable.Clone
        Return New Account With {.AccountDescription = AccountDescription, _
                             .AccountNumber = AccountNumber, _
                             .Area = Area, _
                             .Group = Group, _
                             .IncomeExpenditure = AddingType.income, _
                             .MonthlyValues = MonthlyValues}
    End Function
    Enum AddingType
        income
        expenditure
    End Enum
    Enum AreaType
        high
        mid
        low
    End Enum

    Property Area() As AreaType
    Property Group() As String
    Property AccountNumber() As Integer
    Property AccountDescription() As String
    Property IncomeExpenditure() As AddingType
    Public Property MonthlyValues As New Dictionary(Of Integer, Decimal)
End Class


问:
How to convert a type result into a string in python?
I have a code line

```<code>emp_id=1
tp = type(emp_id)
print(tp)
print(type(tp))
strg = str(tp)
print(strg)
print(type(strg))
</code>```

The result is  as below

```<code><class 'int'>
<class 'type'>
<class 'int'>
<class 'str'>
</code>```

**What i need is i want to store  in a string.

How to do it? **

答:
The function type(x) returns the class of which the object x is an instance. All classes in python have the property __name__ which returns the actual name (as a string) of that class.

```<code>x = 1
tp = type(x).__name__
print(tp)
</code>```

This will print:  int

Body:
I have a code line

emp_id=1
tp = type(emp_id)
print(tp)
print(type(tp))
strg = str(tp)
print(strg)
print(type(strg))

The result is  as below

<class 'int'>
<class 'type'>
<class 'int'>
<class 'str'>

**What i need is i want to store  in a string.

How to do it? **

Body:
The function type(x) returns the class of which the object x is an instance. All classes in python have the property __name__ which returns the actual name (as a string) of that class.

x = 1
tp = type(x).__name__
print(tp)

This will print:  int


问:
Extract Delimited Data in a string input
I am trying to convert a string which is delimited by a ";"
Here are the possible inputs that i have

```<code>Possibility 1: <String>1;2;3;4;5;6;7;8;9;10;11</String>
Possibility 2: <String>1;2;3;4;5</String>
Possibility 3: <String>1;2;3;4;5;6;7;8;9</String>
Possibility 4: <String>1;2;3;4</String>
Possibility 5: <String>1;2;3;4;5;;;;;10;11</String>
</code>```

Few points concerning the logic

Would like to have the above delimited strings mapped to individual
   fields like shown below.

Not concerned about the values in position 6
   and 7 and hence they are not seen in any of the outputs

Towards the
   end of the output is an element with name "combined" which is a
   concatenation of values received in string delimited by an "_"

Order of concatenation though is slightly different which is mentioned here
   1_2_3_4_5_8_11_9_10

If a value is not present in input string then it remains blank like 1__3_4_5__11__10

Output that i would like to see for each of above mentioned possibilities is

```<code>Possibility 1:

<A>1</A>
<B>2</B>
<C>3</C>
<D>4</D>
<E>5</E>
<F>8</F>
<G>9</G>
<H>10</H>
<I>11</I>
<Combined>1_2_3_4_5_8_11_9_10</Combined>

Possibility 2:
<A>1</A>
<B>2</B>
<C>3</C>
<D>4</D>
<E>5</E>
<F></F>
<G></G>
<H></H>
<I></I>
<Combined>1_2_3_4_5____</Combined>

Possibility 3:
<A>1</A>
<B>2</B>
<C>3</C>
<D>4</D>
<E>5</E>
<F>8</F>
<G>9</G>
<H></H>
<I></I>
<Combined>1_2_3_4_5_8__9_</Combined>

Possibility 4:
<A>1</A>
<B>2</B>
<C>3</C>
<D>4</D>
<E></E>
<F></F>
<G></G>
<H></H>
<I>11</I>
<Combined>1_2_3_4_____</Combined>

Possibility 5:
<A>1</A>
<B>2</B>
<C>3</C>
<D>4</D>
<E>5</E>
<F></F>
<G></G>
<H>10</H>
<I>11</I>
<Combined>1_2_3_4_5__11__10</Combined>
</code>```

I am able to get the desired output if i assume that string is of fixed length with 11 delimited sets and this i was able to achieve by using substring before and after functions
However for possibilities like 2 3 4 provider is not always sending the empty delimiters and then my xsl doesnt seem to work.

Any help in this context please?

答:
If you are using Xalan, then this should work for you:</p>

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:str="http://exslt.org/strings"
extension-element-prefixes="str">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
    <xsl:variable name="tokens" select="str:split(String, ';')" />
    <root>
        <A>
            <xsl:value-of select="$tokens[1]"/>
        </A>
        <B>
            <xsl:value-of select="$tokens[2]"/>
        </B>
        <C>
            <xsl:value-of select="$tokens[3]"/>
        </C>
        <D>
            <xsl:value-of select="$tokens[4]"/>
        </D>
        <E>
            <xsl:value-of select="$tokens[5]"/>
        </E>
        <F>
            <xsl:value-of select="$tokens[8]"/>
        </F>
        <G>
            <xsl:value-of select="$tokens[9]"/>
        </G>
        <H>
            <xsl:value-of select="$tokens[10]"/>
        </H>
        <I>
            <xsl:value-of select="$tokens[11]"/>
        </I>
        <Combined>
            <xsl:value-of select="$tokens[1]"/>
            <xsl:text>_</xsl:text>
            <xsl:value-of select="$tokens[2]"/>
            <xsl:text>_</xsl:text>
            <xsl:value-of select="$tokens[3]"/>
            <xsl:text>_</xsl:text>
            <xsl:value-of select="$tokens[4]"/>
            <xsl:text>_</xsl:text>
            <xsl:value-of select="$tokens[5]"/>
            <xsl:text>_</xsl:text>
            <xsl:value-of select="$tokens[8]"/>
            <xsl:text>_</xsl:text>
            <xsl:value-of select="$tokens[11]"/>
            <xsl:text>_</xsl:text>
            <xsl:value-of select="$tokens[9]"/>
            <xsl:text>_</xsl:text>
            <xsl:value-of select="$tokens[10]"/>
        </Combined>
    </root>
</xsl:template>

</xsl:stylesheet>
</code>```

Body:
I am trying to convert a string which is delimited by a ";"
Here are the possible inputs that i have

Possibility 1: <String>1;2;3;4;5;6;7;8;9;10;11</String>
Possibility 2: <String>1;2;3;4;5</String>
Possibility 3: <String>1;2;3;4;5;6;7;8;9</String>
Possibility 4: <String>1;2;3;4</String>
Possibility 5: <String>1;2;3;4;5;;;;;10;11</String>

Few points concerning the logic

Would like to have the above delimited strings mapped to individual
   fields like shown below.

Not concerned about the values in position 6
   and 7 and hence they are not seen in any of the outputs

Towards the
   end of the output is an element with name "combined" which is a
   concatenation of values received in string delimited by an "_"

Order of concatenation though is slightly different which is mentioned here
   1_2_3_4_5_8_11_9_10

If a value is not present in input string then it remains blank like 1__3_4_5__11__10

Output that i would like to see for each of above mentioned possibilities is

Possibility 1:

1
2
<C>3</C>
<D>4</D>
<E>5</E>
<F>8</F>
<G>9</G>
<H>10</H>
11
<Combined>1_2_3_4_5_8_11_9_10</Combined>

Possibility 2:
1
2
<C>3</C>
<D>4</D>
<E>5</E>
<F></F>
<G></G>
<H></H>

<Combined>1_2_3_4_5____</Combined>

Possibility 3:
1
2
<C>3</C>
<D>4</D>
<E>5</E>
<F>8</F>
<G>9</G>
<H></H>

<Combined>1_2_3_4_5_8__9_</Combined>

Possibility 4:
1
2
<C>3</C>
<D>4</D>
<E></E>
<F></F>
<G></G>
<H></H>
11
<Combined>1_2_3_4_____</Combined>

Possibility 5:
1
2
<C>3</C>
<D>4</D>
<E>5</E>
<F></F>
<G></G>
<H>10</H>
11
<Combined>1_2_3_4_5__11__10</Combined>

I am able to get the desired output if i assume that string is of fixed length with 11 delimited sets and this i was able to achieve by using substring before and after functions
However for possibilities like 2 3 4 provider is not always sending the empty delimiters and then my xsl doesnt seem to work.

Any help in this context please?

Body:
If you are using Xalan, then this should work for you:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:str="http://exslt.org/strings"
extension-element-prefixes="str">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
    <xsl:variable name="tokens" select="str:split(String, ';')" />
    <root>
        <A>
            <xsl:value-of select="$tokens[1]"/>
        </A>
        <B>
            <xsl:value-of select="$tokens[2]"/>
        </B>
        <C>
            <xsl:value-of select="$tokens[3]"/>
        </C>
        <D>
            <xsl:value-of select="$tokens[4]"/>
        </D>
        <E>
            <xsl:value-of select="$tokens[5]"/>
        </E>
        <F>
            <xsl:value-of select="$tokens[8]"/>
        </F>
        <G>
            <xsl:value-of select="$tokens[9]"/>
        </G>
        <H>
            <xsl:value-of select="$tokens[10]"/>
        </H>
        <I>
            <xsl:value-of select="$tokens[11]"/>
        </I>
        <Combined>
            <xsl:value-of select="$tokens[1]"/>
            <xsl:text>_</xsl:text>
            <xsl:value-of select="$tokens[2]"/>
            <xsl:text>_</xsl:text>
            <xsl:value-of select="$tokens[3]"/>
            <xsl:text>_</xsl:text>
            <xsl:value-of select="$tokens[4]"/>
            <xsl:text>_</xsl:text>
            <xsl:value-of select="$tokens[5]"/>
            <xsl:text>_</xsl:text>
            <xsl:value-of select="$tokens[8]"/>
            <xsl:text>_</xsl:text>
            <xsl:value-of select="$tokens[11]"/>
            <xsl:text>_</xsl:text>
            <xsl:value-of select="$tokens[9]"/>
            <xsl:text>_</xsl:text>
            <xsl:value-of select="$tokens[10]"/>
        </Combined>
    </root>
</xsl:template>

</xsl:stylesheet>


问:
Connection String to Connect to .MDF
I've created a new project in VS2008, and added a .MDF file to the project.  This is the first time I've tried to use the MDF files and .SQLEXPRESS databases (I've always used extenal Oracle servers in the past).

I'm trying to document everything as I go, but I can't figure out what credentials are being used to connect to the .MDF file.  Is there an easy way to find out?

答:
For a local DB and no SQLEXPRESS server:</p>

```<code>"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=""|DataDirectory|\MyDB.mdf"";Integrated Security=True;Connect Timeout=30"
</code>```

Title: Connection String to Connect to .MDF

Body:
For a local DB and no SQLEXPRESS server:

"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=""|DataDirectory|\MyDB.mdf"";Integrated Security=True;Connect Timeout=30"


问:
Why is the Array undefined?
When I alert my array "markerArray" outside the geocoder-function it says it's undefined.

Can't figure out why? Is there a way to get the values from the array outside the function?

```<code>var markerArray = new Array();
for(var i in opts.markers)
{
    address = opts.markers[i].address;
    //alert(opts.markers[i].icon);
    var geocoder = new google.maps.Geocoder();

    geocoder.geocode({ address: address }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK && results.length) {
            if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    position: results[0].geometry.location,
                    map: map
                });
            }
        }
        markerArray[i] = marker;

    });

}
alert(markerArray[0].position);
</code>```

答:
I suspect it's not markerArray that it's complaining about, but markerArray[0] that's undefined.

You're calling an asynchronous API using functions you create in a loop. Those functions are closures. They each have an enduring reference to the i variable, not a copy of the value as it was when the function was defined. So all of the functions use the last i value from the loop, because none of them runs until the loop is over. So if the last value i has in the loop is 5, say, then all of the functions will use 5.

Also, you're then doing your alert too soon, before any of the callbacks has a chance to run. You'll need to do whatever final processing you need to do in one of the callbacks (you can use a counter to know when they've all happened).

You can fix both the markerArray problem and the premature alert like this:

```<code>var markerArray = new Array();
var callcounter = 0;
for(var i in opts.markers)
{
    address = opts.markers[i].address;
    //alert(opts.markers[i].icon);
    var geocoder = new google.maps.Geocoder();

    ++callcounter;
    geocoder.geocode({ address: address }, buildCallback(i));

}

function buildCallback(index) {
    return function(results, status) {
        if (status == google.maps.GeocoderStatus.OK && results.length) {
            if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    position: results[0].geometry.location,
                    map: map
                });
            }
        }
        markerArray[index] = marker;
        if (--callcounter === 0) {
            // This was the last outstanding call
            alert(markerArray[0]); // Always assuming there was a `0` in `opts.markers`
        }
    };
}
</code>```

Now, the callbacks are closures over the index argument you pass into the buildCallback function, instead of the i variable in your main loop. We do the alert when we're done with all the callbacks, which we know because of the callcounter (see note below if your "race condition" radar is going off).

All of this is because of the way closures work. They're not complicated (in fact, I wrote a blog post about them called Closures are not complicated), but there are some things you need to firmly understand to "get" why they do what they do.

Separately: You're using for..in to loop through opts.markers, which I suspect is an array. If it is, then that code has issues you need to solve. for..in is not for looping through the indexes of an array, it's for looping through the property names of an object. More here. You either need to add some checks to your for..in loop, or just use a boring old-fashioned for loop.

Re the counter: To anyone used to multi-threaded programming, my simple "increment it when scheduling, decrement it when processing" logic looks like it sets up a race condition (what if the first one gets called back before the second one is scheduled?). But it's not a race condition in JavaScript on browsers, because JavaScript on browsers is single-threaded (or if you use web workers, kind of cooperatively multi-threaded). There is no pre-emptive multi-threading here. None of the callbacks will ever be called until they have all been scheduled.

Off-topic: Although var markerArray = new Array(); works just fine, I'd recommend var markerArray = []; instead. It's shorter; for various reasons the implementation can optimize it a bit more (not that it really matters); and there's no possibility that someone has shadowed the Array symbol. Similarly, any time you want just a blank object, use {} instead of new Object().

Title: Why is the Array undefined?

Body:
When I alert my array "markerArray" outside the geocoder-function it says it's undefined.

Can't figure out why? Is there a way to get the values from the array outside the function?

var markerArray = new Array();
for(var i in opts.markers)
{
    address = opts.markers[i].address;
    //alert(opts.markers[i].icon);
    var geocoder = new google.maps.Geocoder();

    geocoder.geocode({ address: address }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK && results.length) {
            if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    position: results[0].geometry.location,
                    map: map
                });
            }
        }
        markerArray[i] = marker;

    });

}
alert(markerArray[0].position);

Body:
I suspect it's not markerArray that it's complaining about, but markerArray[0] that's undefined.

You're calling an asynchronous API using functions you create in a loop. Those functions are closures. They each have an enduring reference to the i variable, not a copy of the value as it was when the function was defined. So all of the functions use the last i value from the loop, because none of them runs until the loop is over. So if the last value i has in the loop is 5, say, then all of the functions will use 5.

Also, you're then doing your alert too soon, before any of the callbacks has a chance to run. You'll need to do whatever final processing you need to do in one of the callbacks (you can use a counter to know when they've all happened).

You can fix both the markerArray problem and the premature alert like this:

var markerArray = new Array();
var callcounter = 0;
for(var i in opts.markers)
{
    address = opts.markers[i].address;
    //alert(opts.markers[i].icon);
    var geocoder = new google.maps.Geocoder();

    ++callcounter;
    geocoder.geocode({ address: address }, buildCallback(i));

}

function buildCallback(index) {
    return function(results, status) {
        if (status == google.maps.GeocoderStatus.OK && results.length) {
            if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    position: results[0].geometry.location,
                    map: map
                });
            }
        }
        markerArray[index] = marker;
        if (--callcounter === 0) {
            // This was the last outstanding call
            alert(markerArray[0]); // Always assuming there was a `0` in `opts.markers`
        }
    };
}

Now, the callbacks are closures over the index argument you pass into the buildCallback function, instead of the i variable in your main loop. We do the alert when we're done with all the callbacks, which we know because of the callcounter (see note below if your "race condition" radar is going off).

All of this is because of the way closures work. They're not complicated (in fact, I wrote a blog post about them called Closures are not complicated), but there are some things you need to firmly understand to "get" why they do what they do.

Separately: You're using for..in to loop through opts.markers, which I suspect is an array. If it is, then that code has issues you need to solve. for..in is not for looping through the indexes of an array, it's for looping through the property names of an object. More here. You either need to add some checks to your for..in loop, or just use a boring old-fashioned for loop.

Re the counter: To anyone used to multi-threaded programming, my simple "increment it when scheduling, decrement it when processing" logic looks like it sets up a race condition (what if the first one gets called back before the second one is scheduled?). But it's not a race condition in JavaScript on browsers, because JavaScript on browsers is single-threaded (or if you use web workers, kind of cooperatively multi-threaded). There is no pre-emptive multi-threading here. None of the callbacks will ever be called until they have all been scheduled.

Off-topic: Although var markerArray = new Array(); works just fine, I'd recommend var markerArray = []; instead. It's shorter; for various reasons the implementation can optimize it a bit more (not that it really matters); and there's no possibility that someone has shadowed the Array symbol. Similarly, any time you want just a blank object, use {} instead of new Object().


问:
Overlay three curves in the same y axis
I want to overlay three curves of the normal distribution with three different sigma values. I have done this:

```<code>curve(dnorm(x, mean(x), sd(x)), col = 2, lwd = 2)
par(new = TRUE)
curve(dnorm(x, mean(x), sd(x)/2), col = 3, lwd = 2)
par(new = TRUE)
curve(dnorm(x, mean(x), sd(x)*2), col = 4, lwd = 2)
</code>```

And the result is
But I want to use only one y axis scale, so the three plots are one under the other and not on the same y scale. Also I want to expand the range of the x axis, to be from -3 to 3 for example

答:
Open a blank graphics device first by setting plot parameter type = "n". Then add = TRUE the 3 curves.

```<code>plot(c(0, 1), c(0, 3), type = "n", xlab = "", ylab = "")
curve(dnorm(x, mean(x), sd(x)), col = 2, lwd = 2, add = TRUE)
curve(dnorm(x, mean(x), sd(x)/2), col = 3, lwd = 2, add = TRUE)
curve(dnorm(x, mean(x), sd(x)*2), col = 4, lwd = 2, add = TRUE)
</code>```

Title: Overlay three curves in the same y axis

Body:
I want to overlay three curves of the normal distribution with three different sigma values. I have done this:

curve(dnorm(x, mean(x), sd(x)), col = 2, lwd = 2)
par(new = TRUE)
curve(dnorm(x, mean(x), sd(x)/2), col = 3, lwd = 2)
par(new = TRUE)
curve(dnorm(x, mean(x), sd(x)*2), col = 4, lwd = 2)

And the result is
But I want to use only one y axis scale, so the three plots are one under the other and not on the same y scale. Also I want to expand the range of the x axis, to be from -3 to 3 for example

Body:
Open a blank graphics device first by setting plot parameter type = "n". Then add = TRUE the 3 curves.

plot(c(0, 1), c(0, 3), type = "n", xlab = "", ylab = "")
curve(dnorm(x, mean(x), sd(x)), col = 2, lwd = 2, add = TRUE)
curve(dnorm(x, mean(x), sd(x)/2), col = 3, lwd = 2, add = TRUE)
curve(dnorm(x, mean(x), sd(x)*2), col = 4, lwd = 2, add = TRUE)


问:
python check if values after the path's are same
I want to write a program in python, that checks if the values after a string are exactly same.

Contents of list.txt

```<code>random/directory/file.txt 0 1 a
random/directory/file1.txt 0 1 a
random/directory/file2.txt 0 1 a
</code>```

first one is str1, second one is str2, third one is str3.

note: these strings dont have the numbers and a letter in them, just the path to file.

I tried it with endswith(), but that did not work as i want.

答:
If you really just want to compare the strings after the first whitespace it is as simple as: </p>

```<code>str1 = "random/directory/file.txt 0 1 a"
str2 = "random/directory/file1.txt 0 1 a"
str3 = "random/directory/file2.txt 0 1 a"

print( str1.split(" ", 1)[1] == str2.split(" ", 1)[1] == str3.split(" ", 1)[1])
OUT: True

str3 = "random/directory/file2.txt 0 1 n"

print( str1.split(" ", 1)[1] == str2.split(" ", 1)[1] == str3.split(" ", 1)[1])
OUT: False
</code>```

Body:
I want to write a program in python, that checks if the values after a string are exactly same.

Contents of list.txt

random/directory/file.txt 0 1 a
random/directory/file1.txt 0 1 a
random/directory/file2.txt 0 1 a

first one is str1, second one is str2, third one is str3.

note: these strings dont have the numbers and a letter in them, just the path to file.

I tried it with endswith(), but that did not work as i want.

Body:
If you really just want to compare the strings after the first whitespace it is as simple as:

str1 = "random/directory/file.txt 0 1 a"
str2 = "random/directory/file1.txt 0 1 a"
str3 = "random/directory/file2.txt 0 1 a"

print( str1.split(" ", 1)[1] == str2.split(" ", 1)[1] == str3.split(" ", 1)[1])
OUT: True

str3 = "random/directory/file2.txt 0 1 n"

print( str1.split(" ", 1)[1] == str2.split(" ", 1)[1] == str3.split(" ", 1)[1])
OUT: False


问:
how to get detailed errors from firebase cloud messeging?
I'm trying to send a message using APN over firebase and get the following message:

```<code>{"code":"messaging/third-party-auth-error","message":"Auth error from APNS or Web Push Service"}
</code>```

How can I get the APNS error listed here: https://firebase.google.com/docs/reference/fcm/rest/v1/ApnsError? I'm using the firebase-admin npm package.

答:
Try to check your bundle identifiers in XCode and Firebase - it could be the simplest problem.

Follow this one answer to find the issue

Feel free to ask anything :3

Body:
I'm trying to send a message using APN over firebase and get the following message:

{"code":"messaging/third-party-auth-error","message":"Auth error from APNS or Web Push Service"}

How can I get the APNS error listed here: https://firebase.google.com/docs/reference/fcm/rest/v1/ApnsError? I'm using the firebase-admin npm package.