问:
Deadlock when using fork, exec and pipes in a parallel environment
I am spawning a child process using fork and exec. Using two pipes to provide input and receive output from that process.

It works just fine most of the time but when I use something like openmp to test how it performs in concurrent environments it hangs in the read syscall, or waitpid sometimes.

When I straceed the child process I found that it is also blocked on the read syscall. Which is weird because I only wait on reading in the parent process after I've provided all of my input and closed the write end of the pipe.

I tried to create an MVCE but it is sort of long. I don't know how to make it any shorter. I removed most of the error checking code for the sake of simplicity.

Note that there are no globals in my code. And I'm not trying to read/write from the same file descriptors in multiple threads.

I can't think of what could go wrong. So hopefully you guys can spot what I'm doing wrong.

There goes:

```<code>#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <limits.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>

size_t
min(size_t first, size_t second)
{
    if(first < second)
    {
        return first;
    }

    return second;
}

struct RDI_Buffer
{
    char* data;
    size_t size;
};

typedef struct RDI_Buffer RDI_Buffer;

RDI_Buffer
rdi_buffer_init()
{
    RDI_Buffer b = {0};
    return b;
}

RDI_Buffer
rdi_buffer_new(size_t size)
{
    RDI_Buffer b;

    b.data = malloc(size);
    b.size = size;
    return b;
}

void
rdi_buffer_free(RDI_Buffer b)
{
    if(!b.data)
    {
        return;
    }

    free(b.data);
}

RDI_Buffer
rdi_buffer_resize(RDI_Buffer b, size_t new_size)
{
    if(!b.data)
    {
        return rdi_buffer_new(new_size);
    }

    char* new_data = realloc(b.data, new_size);

    if(new_data)
    {
        b.size = new_size;
        b.data = new_data;
        return b;
    }

    RDI_Buffer output = rdi_buffer_new(new_size);
    memcpy(output.data, b.data, output.size);
    rdi_buffer_free(b);
    return output;
}

RDI_Buffer
rdi_buffer_null_terminate(RDI_Buffer b)
{
    b = rdi_buffer_resize(b, b.size + 1);
    b.data[b.size - 1] = '\0';
    return b;
}

static RDI_Buffer
rw_from_fd(int w_fd, int r_fd, RDI_Buffer input)
{
    const size_t CHUNK_SIZE = 4096;

    assert(input.size <= CHUNK_SIZE);

    write(w_fd, input.data, input.size);
    close(w_fd);

    RDI_Buffer output = rdi_buffer_new(CHUNK_SIZE);

    read(r_fd, output.data, CHUNK_SIZE);

    close(r_fd);
    return output;
}

int main()
{
#pragma omp parallel for
    for(size_t i = 0; i < 100; i++)
    {
        char* thing =
                "Hello this is a sort of long text so that we can test how "
                "well this works. It should go with cat and be printed.";

        RDI_Buffer input_buffer;
        input_buffer.data = thing;
        input_buffer.size = strlen(thing);

        int main_to_sub[2];
        int sub_to_main[2];

        pipe(main_to_sub);
        pipe(sub_to_main);

        int pid = fork();

        if(pid == 0)
        {
            dup2(main_to_sub[0], STDIN_FILENO);
            dup2(sub_to_main[1], STDOUT_FILENO);

            close(main_to_sub[1]);
            close(main_to_sub[0]);
            close(sub_to_main[1]);
            close(sub_to_main[0]);

            char* argv[] = {"cat", NULL};

            execvp("cat", argv);
            exit(1);
        }

        close(main_to_sub[0]);
        close(sub_to_main[1]);

        RDI_Buffer output =
                rw_from_fd(main_to_sub[1], sub_to_main[0], input_buffer);

        int *status = NULL;
        waitpid(pid, status, 0);

        if(status)
        {
            printf("%d\n", *status);
        }

        output = rdi_buffer_null_terminate(output);

        if(strcmp(output.data, thing) == 0)
        {
            printf("good\n");
        }
        else
        {
            printf("bad\n");
        }

        rdi_buffer_free(output);
    }
}
</code>```

Make sure you compile and link with -fopenmp. Like so: gcc main.c -fopenmp

答:
When your main is hung, type lsof in a separate session.   I think you will see something like:

```<code>....
cat       5323                 steve  txt       REG              252,0    52080    6553613 /bin/cat
cat       5323                 steve  mem       REG              252,0  1868984   17302005 /lib/x86_64-linux-gnu/libc-2.23.so
cat       5323                 steve  mem       REG              252,0   162632   17301981 /lib/x86_64-linux-gnu/ld-2.23.so
cat       5323                 steve  mem       REG              252,0  1668976   12849924 /usr/lib/locale/locale-archive
cat       5323                 steve    0r     FIFO               0,10      0t0      32079 pipe
cat       5323                 steve    1w     FIFO               0,10      0t0      32080 pipe
cat       5323                 steve    2u      CHR              136,0      0t0          3 /dev/pts/0
cat       5323                 steve    3r     FIFO               0,10      0t0      32889 pipe
cat       5323                 steve    4w     FIFO               0,10      0t0      32889 pipe
cat       5323                 steve    6r     FIFO               0,10      0t0      32890 pipe
cat       5323                 steve    7r     FIFO               0,10      0t0      34359 pipe
cat       5323                 steve    8w     FIFO               0,10      0t0      32890 pipe
cat       5323                 steve   10r     FIFO               0,10      0t0      22504 pipe
cat       5323                 steve   15w     FIFO               0,10      0t0      22504 pipe
cat       5323                 steve   16r     FIFO               0,10      0t0      22505 pipe
cat       5323                 steve   31w     FIFO               0,10      0t0      22505 pipe
cat       5323                 steve   35r     FIFO               0,10      0t0      17257 pipe
cat       5323                 steve   47r     FIFO               0,10      0t0      31304 pipe
cat       5323                 steve   49r     FIFO               0,10      0t0      30264 pipe
</code>```

which raises the question, where are all those pipes coming from?   Your main loop is no longer a single loop, it is a set of unsynchronized parallel loops.  Look at the boilerplate below:

```<code>void *tdispatch(void *p) {
      int to[2], from[2];
      pipe(to);
      pipe(from);
      if (fork() == 0) {
          ...
      } else {
          ...
          pthread_exit(0);
     }
}
...
for (int i = 0; i < NCPU; i++) {
    pthread_create(..., tdispatch, ...);
}
for (int i = 0; i < NCPU; i++) {
    pthread_join(...);
}
</code>```

Multiple instances of tdispatch can interleave the pipe(to), pipe(from), and fork() calls; thus fds are leaking into these fork'ed processes.   I say leaking because the forked'd process has no idea that they are there.

A pipe continues to respond to read() system calls while it either has buffered data or there is at least one write file descriptor open to it.

Suppose process 5 has its normal two ends of two pipes open, pointing to pipe#10, and pipe#11; and process 6 has pipe#12 and pipe#13.  But, owing to the leaking above, processes 5 also has the write end of pipe#12, and process 6 has the write end of pipe#10.   Process's 5 and 6 will never exit because they are keeping each others read-pipe's open.

The solution is pretty much what people in the earlier bit were saying: threads and forks are a tricky combination.   You would have to serialize your pipe,fork,initial-close bits in order to make it work.

Body:
I am spawning a child process using fork and exec. Using two pipes to provide input and receive output from that process.

It works just fine most of the time but when I use something like openmp to test how it performs in concurrent environments it hangs in the read syscall, or waitpid sometimes.

When I straceed the child process I found that it is also blocked on the read syscall. Which is weird because I only wait on reading in the parent process after I've provided all of my input and closed the write end of the pipe.

I tried to create an MVCE but it is sort of long. I don't know how to make it any shorter. I removed most of the error checking code for the sake of simplicity.

Note that there are no globals in my code. And I'm not trying to read/write from the same file descriptors in multiple threads.

I can't think of what could go wrong. So hopefully you guys can spot what I'm doing wrong.

There goes:

#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <limits.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>

size_t
min(size_t first, size_t second)
{
    if(first < second)
    {
        return first;
    }

    return second;
}

struct RDI_Buffer
{
    char* data;
    size_t size;
};

typedef struct RDI_Buffer RDI_Buffer;

RDI_Buffer
rdi_buffer_init()
{
    RDI_Buffer b = {0};
    return b;
}

RDI_Buffer
rdi_buffer_new(size_t size)
{
    RDI_Buffer b;

    b.data = malloc(size);
    b.size = size;
    return b;
}

void
rdi_buffer_free(RDI_Buffer b)
{
    if(!b.data)
    {
        return;
    }

    free(b.data);
}

RDI_Buffer
rdi_buffer_resize(RDI_Buffer b, size_t new_size)
{
    if(!b.data)
    {
        return rdi_buffer_new(new_size);
    }

    char* new_data = realloc(b.data, new_size);

    if(new_data)
    {
        b.size = new_size;
        b.data = new_data;
        return b;
    }

    RDI_Buffer output = rdi_buffer_new(new_size);
    memcpy(output.data, b.data, output.size);
    rdi_buffer_free(b);
    return output;
}

RDI_Buffer
rdi_buffer_null_terminate(RDI_Buffer b)
{
    b = rdi_buffer_resize(b, b.size + 1);
    b.data[b.size - 1] = '\0';
    return b;
}

static RDI_Buffer
rw_from_fd(int w_fd, int r_fd, RDI_Buffer input)
{
    const size_t CHUNK_SIZE = 4096;

    assert(input.size <= CHUNK_SIZE);

    write(w_fd, input.data, input.size);
    close(w_fd);

    RDI_Buffer output = rdi_buffer_new(CHUNK_SIZE);

    read(r_fd, output.data, CHUNK_SIZE);

    close(r_fd);
    return output;
}

int main()
{
#pragma omp parallel for
    for(size_t i = 0; i < 100; i++)
    {
        char* thing =
                "Hello this is a sort of long text so that we can test how "
                "well this works. It should go with cat and be printed.";

        RDI_Buffer input_buffer;
        input_buffer.data = thing;
        input_buffer.size = strlen(thing);

        int main_to_sub[2];
        int sub_to_main[2];

        pipe(main_to_sub);
        pipe(sub_to_main);

        int pid = fork();

        if(pid == 0)
        {
            dup2(main_to_sub[0], STDIN_FILENO);
            dup2(sub_to_main[1], STDOUT_FILENO);

            close(main_to_sub[1]);
            close(main_to_sub[0]);
            close(sub_to_main[1]);
            close(sub_to_main[0]);

            char* argv[] = {"cat", NULL};

            execvp("cat", argv);
            exit(1);
        }

        close(main_to_sub[0]);
        close(sub_to_main[1]);

        RDI_Buffer output =
                rw_from_fd(main_to_sub[1], sub_to_main[0], input_buffer);

        int *status = NULL;
        waitpid(pid, status, 0);

        if(status)
        {
            printf("%d\n", *status);
        }

        output = rdi_buffer_null_terminate(output);

        if(strcmp(output.data, thing) == 0)
        {
            printf("good\n");
        }
        else
        {
            printf("bad\n");
        }

        rdi_buffer_free(output);
    }
}

Make sure you compile and link with -fopenmp. Like so: gcc main.c -fopenmp

Body:
When your main is hung, type lsof in a separate session.   I think you will see something like:

....
cat       5323                 steve  txt       REG              252,0    52080    6553613 /bin/cat
cat       5323                 steve  mem       REG              252,0  1868984   17302005 /lib/x86_64-linux-gnu/libc-2.23.so
cat       5323                 steve  mem       REG              252,0   162632   17301981 /lib/x86_64-linux-gnu/ld-2.23.so
cat       5323                 steve  mem       REG              252,0  1668976   12849924 /usr/lib/locale/locale-archive
cat       5323                 steve    0r     FIFO               0,10      0t0      32079 pipe
cat       5323                 steve    1w     FIFO               0,10      0t0      32080 pipe
cat       5323                 steve    2u      CHR              136,0      0t0          3 /dev/pts/0
cat       5323                 steve    3r     FIFO               0,10      0t0      32889 pipe
cat       5323                 steve    4w     FIFO               0,10      0t0      32889 pipe
cat       5323                 steve    6r     FIFO               0,10      0t0      32890 pipe
cat       5323                 steve    7r     FIFO               0,10      0t0      34359 pipe
cat       5323                 steve    8w     FIFO               0,10      0t0      32890 pipe
cat       5323                 steve   10r     FIFO               0,10      0t0      22504 pipe
cat       5323                 steve   15w     FIFO               0,10      0t0      22504 pipe
cat       5323                 steve   16r     FIFO               0,10      0t0      22505 pipe
cat       5323                 steve   31w     FIFO               0,10      0t0      22505 pipe
cat       5323                 steve   35r     FIFO               0,10      0t0      17257 pipe
cat       5323                 steve   47r     FIFO               0,10      0t0      31304 pipe
cat       5323                 steve   49r     FIFO               0,10      0t0      30264 pipe

which raises the question, where are all those pipes coming from?   Your main loop is no longer a single loop, it is a set of unsynchronized parallel loops.  Look at the boilerplate below:

void *tdispatch(void *p) {
      int to[2], from[2];
      pipe(to);
      pipe(from);
      if (fork() == 0) {
          ...
      } else {
          ...
          pthread_exit(0);
     }
}
...
for (int i = 0; i < NCPU; i++) {
    pthread_create(..., tdispatch, ...);
}
for (int i = 0; i < NCPU; i++) {
    pthread_join(...);
}

Multiple instances of tdispatch can interleave the pipe(to), pipe(from), and fork() calls; thus fds are leaking into these fork'ed processes.   I say leaking because the forked'd process has no idea that they are there.

A pipe continues to respond to read() system calls while it either has buffered data or there is at least one write file descriptor open to it.

Suppose process 5 has its normal two ends of two pipes open, pointing to pipe#10, and pipe#11; and process 6 has pipe#12 and pipe#13.  But, owing to the leaking above, processes 5 also has the write end of pipe#12, and process 6 has the write end of pipe#10.   Process's 5 and 6 will never exit because they are keeping each others read-pipe's open.

The solution is pretty much what people in the earlier bit were saying: threads and forks are a tricky combination.   You would have to serialize your pipe,fork,initial-close bits in order to make it work.


来源: stackexchange

问:
Why does this React/Mobx observer component not rerender when its observable props change?
I have a React component which renders a table of data from its props. The data is wrapped in MobX's observable(). From time to time, an asynchronous operation (AJAX call) adds a new row to the data source, which should cause a new table row to render. This is not the case.

A minimal example of the component in question is below:

```<code>@observer
class MyDashboard extends React.Component {
    render() {
        return (
            <Table
                columns={this.props.columns}
                dataSource={this.props.model.contentTypes}
            />
        );
    }

    @action.bound
    private onThingHappened = async () => {
        const thing = await asyncThing();
        runInAction('onThingHappened', () => {
            this.props.model.contentTypes.push(thing);
        });
    }
}
</code>```

The prop model is an observable object. model.contentTypes is an array of objects. The table renders correctly on the first draw; it's subsequent re-renders which are problematic.

The bound action onThingHappened works as expected if the await is removed. To put it differently - model changes which occur before the first await trigger re-renders as expected.

The runInAction does not seem to noticably change anything.

However, if I draw model.contentTypes in the component itself - rather than simply passing it down to a child component (
 in this case), the entire thing works as expected. For example:

```<code>    return (
        <React.Fragment>
            <div style={{display: 'none'}}>{this.props.model.contentTypes.length}</div>
            <Table
                columns={this.props.columns}
                dataSource={this.props.model.contentTypes}
            />
        </React.Fragment>
    )
</code>```

In this render function, dereferencing the model.contentTypes array seems to be enough to trigger the re-render in onThingHappened, even after an await.

答:
I don't use mobx but after some research:

wrapping
 in observer() should work ... if
 render uses the value directly, it can fail if passed to (unwrapped) subcomponent;

'Mobx traces access' then probably it's enough to force mobx to react by 'unnecessary' access.

Try sth like:

```<code>render() {
  const amount = this.props.model.contentTypes.length;
  if( !amount ) return null; // to avoid 'amount unused, no unused ...'

  return (
    <Table
      columns={this.props.columns}
      dataSource={this.props.model.contentTypes}
    />
  );
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a React component which renders a table of data from its props. The data is wrapped in MobX's observable(). From time to time, an asynchronous operation (AJAX call) adds a new row to the data source, which should cause a new table row to render. This is not the case.

A minimal example of the component in question is below:

@observer
class MyDashboard extends React.Component {
    render() {
        return (

        );
    }

    @action.bound
    private onThingHappened = async () => {
        const thing = await asyncThing();
        runInAction('onThingHappened', () => {
            this.props.model.contentTypes.push(thing);
        });
    }
}

The prop model is an observable object. model.contentTypes is an array of objects. The table renders correctly on the first draw; it's subsequent re-renders which are problematic.

The bound action onThingHappened works as expected if the await is removed. To put it differently - model changes which occur before the first await trigger re-renders as expected.

The runInAction does not seem to noticably change anything.

However, if I draw model.contentTypes in the component itself - rather than simply passing it down to a child component (
 in this case), the entire thing works as expected. For example:

    return (
        <React.Fragment>

{this.props.model.contentTypes.length}

        </React.Fragment>
    )

In this render function, dereferencing the model.contentTypes array seems to be enough to trigger the re-render in onThingHappened, even after an await.

Body:
I don't use mobx but after some research:

wrapping <Table/> in observer() should work ... if <Table/> render uses the value directly, it can fail if passed to (unwrapped) subcomponent;

'Mobx traces access' then probably it's enough to force mobx to react by 'unnecessary' access.

Try sth like:

render() {
  const amount = this.props.model.contentTypes.length;
  if( !amount ) return null; // to avoid 'amount unused, no unused ...'

  return (
    <Table
      columns={this.props.columns}
      dataSource={this.props.model.contentTypes}
    />
  );
}


问:
What tools do you use to develop C++ applications on Linux?
I develop C++ applications in a Linux environment.  The tools I use every day include Eclipse with the CDT plugin, gdb and valgrind.

What tools do other people use?  Is there anything out there for Linux that rivals the slickness of Microsoft Visual Studio?

答:
GCC

GHC

Vim

Cmake

cscope

GDB

Valgrind

strace

git

Is there really anything else you could possibly need?

OwnerDisplayName: Clayton

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: greyfade


问:
How would I write a function which uses multiple if statements, where each statement would modify the word one after the other?
I'm trying to write a function which would modify a tagged word depending on the tags present in the word, so basically a lemmatizer, but for words in Swedish.

For example if the word was tagged with A it would remove ending X from the word, and if the word also was tagged with B it would remove ending Y from the word etc. In total there are seven different endings that might be present in the word depending on the tag combinations and which I in that case want to remove.

What I've tried so far is to use several if statements after one another which would modify the word if it was tagged with one tag combination and then check if it was tagged with another tag combination and then modify it based on that and so on.

```<code>if tag1 == 'A':
    word = word.rstrip('x')
if tag2 == 'B' and tag3 == 'C' and tag4 == 'D':
    word = word.rstrip('y')
if tag3 == 'B' and tag4 == 'D':
    word = word.rstrip('z')
</code>```

I'm having problems with understanding how I should phrase the if statements so that they would each check for a tag combination, modify the word if the statement is true and then pass the modified word along to the next statement. How would I do this?

EDIT: As Prune said, I know that I could just add if statements with all the possible tag combinations, but I wanted to see if there is a more elegant solution than to do that.

答:
From your description, it seems that you know how to beat this to death with brute force, but you'd like something more elegant.  You might consider a structure of tags and associated removals, such as

```<code>rules = [ ['A',   'x'],
          ['BCD'. 'y'],
          ['B',   'z'],
          ...
        ]
</code>```

Then iterate through your list of removal rules, applying each as appropriate, something like

```<code>for rule in rules:
    rule_tags = rule[0]
    # Check to see that all rule tags are in the input tags ... left to you to code
    if <your code here>:
        word = word.rstrip(rule[1])   # strip letter included in that rule
</code>```

Does that get you moving toward a solution?

Body:
I'm trying to write a function which would modify a tagged word depending on the tags present in the word, so basically a lemmatizer, but for words in Swedish.

For example if the word was tagged with A it would remove ending X from the word, and if the word also was tagged with B it would remove ending Y from the word etc. In total there are seven different endings that might be present in the word depending on the tag combinations and which I in that case want to remove.

What I've tried so far is to use several if statements after one another which would modify the word if it was tagged with one tag combination and then check if it was tagged with another tag combination and then modify it based on that and so on.

if tag1 == 'A':
    word = word.rstrip('x')
if tag2 == 'B' and tag3 == 'C' and tag4 == 'D':
    word = word.rstrip('y')
if tag3 == 'B' and tag4 == 'D':
    word = word.rstrip('z')

I'm having problems with understanding how I should phrase the if statements so that they would each check for a tag combination, modify the word if the statement is true and then pass the modified word along to the next statement. How would I do this?

EDIT: As Prune said, I know that I could just add if statements with all the possible tag combinations, but I wanted to see if there is a more elegant solution than to do that.

Body:
From your description, it seems that you know how to beat this to death with brute force, but you'd like something more elegant.  You might consider a structure of tags and associated removals, such as

rules = [ ['A',   'x'],
          ['BCD'. 'y'],
          ['B',   'z'],
          ...
        ]

Then iterate through your list of removal rules, applying each as appropriate, something like

for rule in rules:
    rule_tags = rule[0]
    # Check to see that all rule tags are in the input tags ... left to you to code
    if <your code here>:
        word = word.rstrip(rule[1])   # strip letter included in that rule

Does that get you moving toward a solution?


问:
Subset list of dataframes by column name
So I have a list of dataframes df_list=[df1,df2,df3] and a list of column headers I am interested in. col_list=['Fire','Water','Wind','Hail']

I want to loop through each dataframe df_list, and create a new dataframe with only the columns in col_list.The issue is if one of the elements in col_list is not in the df I still want it to make the dataframe however simply without that column.

What I tried doing is,

```<code>for data_frame in df_list:
   try:
       data_frame=data_frame[['Fire','Water','Wind','Hail']]
   except:
        continue
</code>```

However, this does not give the result I am looking for.

答:
You should use a list comprehension:

```<code>[data_frame[['Fire','Water','Wind','Hail']] for data_frame in df_list]
</code>```

If some data_frames do not have all the columns you can use reindex instead:

```<code>[data_frame.reindex(columns=['Fire','Water','Wind','Hail']) for data_frame in df_list]
</code>```

Inside the for loop:

```<code>data_frame=data_frame[['Fire','Water','Wind','Hail']]
</code>```

is overwriting the data_frame variable BUT not updating the i-th item of df_list.

This is equivalent to the following code:

```<code>In [11]: a = [1, 2, 3]

In [12]: for i in a:
    ...:     i = i + 1
    ...:

In [13]: a
Out[13]: [1, 2, 3]
</code>```

Body:
So I have a list of dataframes df_list=[df1,df2,df3] and a list of column headers I am interested in. col_list=['Fire','Water','Wind','Hail']

I want to loop through each dataframe df_list, and create a new dataframe with only the columns in col_list.The issue is if one of the elements in col_list is not in the df I still want it to make the dataframe however simply without that column.

What I tried doing is,

for data_frame in df_list:
   try:
       data_frame=data_frame[['Fire','Water','Wind','Hail']]
   except:
        continue

However, this does not give the result I am looking for.

Body:
You should use a list comprehension:

[data_frame[['Fire','Water','Wind','Hail']] for data_frame in df_list]

If some data_frames do not have all the columns you can use reindex instead:

[data_frame.reindex(columns=['Fire','Water','Wind','Hail']) for data_frame in df_list]

Inside the for loop:

data_frame=data_frame[['Fire','Water','Wind','Hail']]

is overwriting the data_frame variable BUT not updating the i-th item of df_list.

This is equivalent to the following code:

In [11]: a = [1, 2, 3]

In [12]: for i in a:
    ...:     i = i + 1
    ...:

In [13]: a
Out[13]: [1, 2, 3]


问:
This is part of a code to auto-fill a web-page in google chrome (using console), What programming language is it?
I'm trying to understand this code to auto-fill a webpage, what is the language?</p>

```<code>$('body').append('<script>' +
'function autoFill() {' +
'   $("input[data-colorid=\'81\']").prop("checked", true);' +
'   $("input[data-colorid=\'81\']").trigger("click");' +
'  $("input[name=\'GoldenCard\']").filter(\':first\').prop("checked", true);' +
'  $("input[name=\'GoldenCard\']").filter(\':first\').trigger("click");' +

'   $("#featuresNextStep").trigger("click");' +

'   $("input[name=firstName]").val("some name").trigger("change");' +

'   $("#directiveProvince").val("5").trigger("change");' +
'   $("#directiveCity").val("227").trigger("change");' +
'   $("#LoginButton").trigger("click");'
</code>```

答:
It's jQuery.

$ is an alias for jQuery, and after $ follows the element selecting query.

Example:
$("#LoginButton") is the same like getElementById("LoginButton").

Example 2:
$("#LoginButton").trigger("click"); triggers a click event on the login button element in the DOM.

Body:
I'm trying to understand this code to auto-fill a webpage, what is the language?

$('body').append('


答:
This works. The reason that your pseudo-legend disappears is that you only have it for the first frame. What I did here is adding the data for all the 5 years (that's why I have rep) and making sure that frame is included in both plots.

legend.plot <- plot_ly() %>%
  add_markers(x = rep(1,15),
              y = rep(seq_len(length(unique(data$c))),5),
              size = rep(sort(unique(data$c)),5),
              showlegend = F,
              color = I("black"),
              frame = ~data$e,
              marker = list(sizeref=0.1, sizemode="area")) %>%
  layout(
    annotations = list(
      list(x = 1.2,
           y = 0.4,
           text = "Size by: c",
           showarrow = F,
           xref='paper',
           yref='paper')),
    xaxis = list(
      zeroline=F,
      showline=F,
      showticklabels=F,
      showgrid=F),
    yaxis=list(
      side = "right",
      range = c(0,10),
      showgrid=F,
      zeroline=F,
      tickmode = "array",
      tickvals = seq_len(length(unique(data$c))),
      ticktext = c("low","mid","high")))
```

Title: Combining static and animated plotly objects using subplot

Body:
Given the following data.frame

data <- structure(list(
  a = c(3.022210021321, 3.31806778755904, 3.34379454984061, 3.47242836124846, 3.55604033866356, 1.11199792191451, 1.24063173332236, 1.31781202016707, 1.30494863902628, 1.3692655447302, 1.07983946906255, 1.2084732804704, 1.40142399758216, 1.60723809583472, 1.64582823925707),
  b = c(2.64027979608152, 2.79483009168741, 2.90522315997732, 3.08185206924119, 2.86106593266136, 0.653204566863006, 0.697361794178973, 0.67528318052099, 0.653204566863006, 0.697361794178973, 2.06623584097395, 2.28702197755379, 2.48572950047564, 2.72859425071346, 2.77275147802942),
  c = c(2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L),
  d = c(1.16264425026133, 1.16264425026133, 1.16264425026133, 1.16264425026133, 1.16264425026133, 1.48373054411498, 1.48373054411498, 1.48373054411498, 1.48373054411498, 1.48373054411498, 3.35362520562369, 3.35362520562369, 3.35362520562369, 3.35362520562369, 3.35362520562369),
  e = c(2015L, 2016L, 2017L, 2018L, 2019L, 2015L, 2016L, 2017L, 2018L, 2019L, 2015L, 2016L, 2017L, 2018L, 2019L),
  f = c("X", "X", "X", "X", "X", "Y", "Y", "Y", "Y", "Y", "Z", "Z", "Z", "Z", "Z"),
  h = structure(c(2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L), .Label = c("low", "mid", "high"), class = c("ordered", "factor"))),
  row.names = c(NA, -15L),
  class = "data.frame")

and the following code snippet

library(plotly)
p <- data %>% plot_ly(
  x = ~a,
  y = ~b,
  size = ~c,
  sizes = c(100, 850),
  color = ~d,
  colors = "YlOrRd",
  alpha = 0.365,
  frame = ~e,
  text = ~paste0("Info: ", f),
  hoverinfo = "text",
  type = 'scatter',
  mode = 'markers') %>%
  add_text(textfont = list(size = 10, color = "black"), textposition = "top", text=~f, showlegend = F)

legend.plot <- plot_ly() %>%
  add_markers(x = 1,
              y = seq_len(length(unique(data$c))),
              size = sort(unique(data$c)),
              showlegend = F,
              color = I("black"),
              marker = list(sizeref=0.1, sizemode="area")) %>%
  layout(
    annotations = list(
      list(x = 1.2,
           y = 0.4,
           text = "Size by: c",
           showarrow = F,
           xref='paper',
           yref='paper')),
    xaxis = list(
      zeroline=F,
      showline=F,
      showticklabels=F,
      showgrid=F),
    yaxis=list(
      side = "right",
      range = c(0,10),
      showgrid=F,
      zeroline=F,
      tickmode = "array",
      tickvals = seq_len(length(unique(data$c))),
      ticktext = c("low","mid","high")))

subplot(p, legend.plot, widths = c(0.85, 0.15), titleX=TRUE, titleY=TRUE) %>%
  config(displayModeBar = F) %>%
  colorbar(title = "Color by: d", x = 0.9, y = 1)

I manage to almost get a plotly plot that I want (ignoring the warnings along the way for now).

I am, however, unable to figure out, how to make the legend for size to stay during the animation. It appears in the initial stage, before the play button is hit, but as soon as I press play, it goes away.

So the static plot data points are disappearing from the subplot when I run the animation. Any hints?


问:
C# laziness question
What's the common approach to design applications, which strongly rely on lazy evaluation in C# (LINQ, IEnumerable, IQueryable, ...)?

Right now I usually attempt to make every query as lazy as possible, using yield return and LINQ queries, but in runtime this could usually lead to "too lazy" behavior, when every query gets builts from it's beginning obviously resulting in severe visual performance degradation.

What I usually do means putting ToList() projection operators somewhere to cache the data, but I suspect this approach might be incorrect.

What's the appropriate / common ways to design this sort of applications from the very beginning?

答:
I find it useful to classify each IEnumerable into one of three categories.

fast ones - e.g. lists and arrays

slow ones - e.g. database queries or heavy calculations

non-deterministic ones - e.g. list.Select(x => new { ... })

For category 1, I tend keep the concrete type when appropriate, arrays or IList etc.
For category 3, those are best to keep local within a method, to avoid hard-to find bugs.
Then we have category 2, and as always when optimizing performance, measure first to find the bottlenecks.

ContentLicense: CC BY-SA 3.0

Title: C# laziness question


问:
How to select the top 3 values from a group based on date and exclude duplicate value?
If I three columns and 1 column has ID, 1 column has value and 1 column has date.  Example, ID column has ID1, ID2, ID3.  The value for each ID has a numeric value, say 1,2,3,4,5 for each ID.

How do I only get 3 results for each ID based on the most recent date descending.
I am using Sybase SQL.   Is there any way I can write this?

I tried to use Row_number() and rank() but I don't get to use either of those functions with my SQL tool.

```<code>ID  value   Date
1   3   20190511
1   1   20190503
1   5   20190401
2   2   20190520
2   1   20190514
2   4   20190503
3   1   20190516
3   5   20190415
3   3   20190402
</code>```

答:
One method uses a correlated subquery with in:

```<code>select t.*
from t
where t.date in (select top (3) t2.date
                 from t t2
                 where t2.id = t.id
                 order by t2.date desc
                );
</code>```

Note that this assumes that the dates are unique.

Body:
If I three columns and 1 column has ID, 1 column has value and 1 column has date.  Example, ID column has ID1, ID2, ID3.  The value for each ID has a numeric value, say 1,2,3,4,5 for each ID.

How do I only get 3 results for each ID based on the most recent date descending.
I am using Sybase SQL.   Is there any way I can write this?

I tried to use Row_number() and rank() but I don't get to use either of those functions with my SQL tool.

ID  value   Date
1   3   20190511
1   1   20190503
1   5   20190401
2   2   20190520
2   1   20190514
2   4   20190503
3   1   20190516
3   5   20190415
3   3   20190402

Body:
One method uses a correlated subquery with in:

select t.*
from t
where t.date in (select top (3) t2.date
                 from t t2
                 where t2.id = t.id
                 order by t2.date desc
                );

Note that this assumes that the dates are unique.


问:
nmake - how to force echo command to output the tab character?
How to force echo command to output a tab character in MS nmake makefile?
Verbatim tabs inserted right into a string after echo command are removed by nmake and don't show up in the output file.</p>

```<code>all :
    @echo I WANT TO OUTPUT THE <TAB> CHARACTER HERE! > output.txt
</code>```

答:
I had the same need. I used the answer using the quotes around the character and just took it one step further.

{tab} means pressing the keyboard tab key in the text editor.

SET tab="{tab}"

SET tab=%tab:~1,1%

The second line extracts the middle character from the quoted string.

Now you can use the %tab% variable with ECHO and, I suspect, anywhere else it's needed.

ECHO %tab%This text is indented, preceded by a tab.

I suspect this technique could be used with other problem characters as well.

Body:
How to force echo command to output a tab character in MS nmake makefile?
Verbatim tabs inserted right into a string after echo command are removed by nmake and don't show up in the output file.

all :
    @echo I WANT TO OUTPUT THE <TAB> CHARACTER HERE! > output.txt


问:
Typescript generic array is being cast to any[]?
I'm trying to write some generic array utility functions, but when I try calling one from another, the compiler seems to cast the generic to any[] and gives me this error:

```<code>Type 'any[]' is not assignable to type 'T'.
</code>```

My code:

```<code>type UnwrapArray<T extends any[]> = T extends (infer G)[] ? G : never;

function removeFromArray<T extends any[]>(
  array: T,
  value: UnwrapArray<T>
) {
  return array.filter(other => other !== value);
}

function toggleArrayValue<T extends any[]>(array: T, value: UnwrapArray<T>): T {
  if(array.includes(value)) {
    return removeFromArray<T>(array, value);
  } else {
    return [...array, value];
  }
}
</code>```

The specific lines giving me trouble are these:

```<code>return removeFromArray<T>(array, value);
</code>```

And

```<code>return [...array, value];
</code>```

I've found I can add as T to a bunch of stuff and it will compile successfully, but it seems like the compiler should figure this out on its own.

答:
You assume T extends any[] will mean T is an array, and any new array will be assignable to T. This is not true.

Consider the following:

```<code>const myArr = Object.assign([1, 2, 3], {
    extraProp : 1
})

toggleArrayValue(myArr, 1).extraProp // ts says this should be here where is my extraProp
</code>```

extends any[] is the lower bound on what T can be, but it can be anything that inherits array (or a tuple but that is another can of worms of why this can't work)

I am not sure at least from your sample code why you need T to be an array. You can express what you are trying to do without this:

```<code>function removeFromArray<T>(
    array: T[],
    value: T
) {
    return array.filter(other => other !== value);
}

function toggleArrayValue<T>(array: T[], value: T): T[] {
    if (array.includes(value)) {
        return removeFromArray<T>(array, value);
    } else {
        return [...array, value];
    }
}
</code>```

Maybe your actual code is more complex, if so post that (maybe in a different question) and we can see if we can find a better solution than an unsafe type assertion.

Body:
I'm trying to write some generic array utility functions, but when I try calling one from another, the compiler seems to cast the generic to any[] and gives me this error:

Type 'any[]' is not assignable to type 'T'.

My code:

type UnwrapArray<T extends any[]> = T extends (infer G)[] ? G : never;

function removeFromArray<T extends any[]>(
  array: T,
  value: UnwrapArray<T>
) {
  return array.filter(other => other !== value);
}

function toggleArrayValue<T extends any[]>(array: T, value: UnwrapArray<T>): T {
  if(array.includes(value)) {
    return removeFromArray<T>(array, value);
  } else {
    return [...array, value];
  }
}

The specific lines giving me trouble are these:

return removeFromArray<T>(array, value);

And

return [...array, value];

I've found I can add as T to a bunch of stuff and it will compile successfully, but it seems like the compiler should figure this out on its own.

Body:
You assume T extends any[] will mean T is an array, and any new array will be assignable to T. This is not true.

Consider the following:

const myArr = Object.assign([1, 2, 3], {
    extraProp : 1
})

toggleArrayValue(myArr, 1).extraProp // ts says this should be here where is my extraProp

extends any[] is the lower bound on what T can be, but it can be anything that inherits array (or a tuple but that is another can of worms of why this can't work)

I am not sure at least from your sample code why you need T to be an array. You can express what you are trying to do without this:

function removeFromArray<T>(
    array: T[],
    value: T
) {
    return array.filter(other => other !== value);
}

function toggleArrayValue<T>(array: T[], value: T): T[] {
    if (array.includes(value)) {
        return removeFromArray<T>(array, value);
    } else {
        return [...array, value];
    }
}

Maybe your actual code is more complex, if so post that (maybe in a different question) and we can see if we can find a better solution than an unsafe type assertion.


问:
PHP Problem with array_count_values
I need to get one time occurence on my array, with my code I get only first result here is my example code:

```<code>$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
for ($i=0; $i<count($arr); $i++)
{
    if($arrs[$arr[$i]]==1)
    {
        //do something...in this example i expect to receive b c and d
    }
}
</code>```

Thanks in advance

ciao h

答:
You just need to retrieve any value which only occurs once in the array, right? Try this:

```<code>$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);

foreach ($arrs as $uniqueValue => $count)
{
  if($value == 1) {
    echo $uniqueValue;
  }
}
</code>```

array_count_values returns an associative array where the key is the value found and its value is the number of times it occurs in the original array. This loop simply iterates over each unique value found in your array (i.e. the keys from array_count_values) and checks if it was only found once (i.e. that key has a value of 1). If it does, it echos out the value. Of course, you probably want to do something a bit more complex with the value, but this works as a placeholder.

Title: PHP Problem with array_count_values

Body:
I need to get one time occurence on my array, with my code I get only first result here is my example code:

$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
for ($i=0; $i<count($arr); $i++)
{
    if($arrs[$arr[$i]]==1)
    {
        //do something...in this example i expect to receive b c and d
    }
}

Thanks in advance

ciao h

Body:
You just need to retrieve any value which only occurs once in the array, right? Try this:

$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);

foreach ($arrs as $uniqueValue => $count)
{
  if($value == 1) {
    echo $uniqueValue;
  }
}

array_count_values returns an associative array where the key is the value found and its value is the number of times it occurs in the original array. This loop simply iterates over each unique value found in your array (i.e. the keys from array_count_values) and checks if it was only found once (i.e. that key has a value of 1). If it does, it echos out the value. Of course, you probably want to do something a bit more complex with the value, but this works as a placeholder.


问:
Azure DevOps Git Repository - not including all files in Changes
Made a new Azure DevOps Git repository. Moved over files from local TFVC repo. It is not including all the files - there is no .gitignore file.  Why is this?  In screenshot below it is not including Tfs2017Build.Lib.

In addition the folder mentioned, is also not including dependent DLLs.  Why is this?  I can see why typically don't want to have DLLs in repo but in this case we do.

thanks

答:
found the global file here that has those excluded:
"C:\Users{username}\Documents\gitignore_global.txt"</p>


问:
If cell in a range has value "x" copy and paste a range of cells into a different sheet
I am not a programmer by trade but I am trying to automate a small portion of a report I use every day out of curiosity and self interest. Basically, we receive and manually enter contact information (name, e-mail, phone number, etc.) and mark select groups that a person is interested in joining. We then copy and paste that contact information entered into a different sheet for each group.

I want to have a macro that checks the specific columns for each interest group for a "x" and if it finds that value copy and paste the contact information collected to the specific interest groups worksheet. People are able to select multiple interest groups and their contact information is added to each separate interest group spreadsheet.

Report columns look as follows:

```<code>Group 1 Group 2 Group 3 Name Organization Phone E-mail  Notes

Row Contact Information looks similar to:
  x  x John ABC Inc. 000-000-0000 john.smith@fake.com  Call me ASAP!
</code>```

The macro checks the column I have marked interest in Group 1 in and if it finds "x" then it copies the full range to the Group 1 worksheet.

I want it to be able to check multiple columns (i.e. Group 1, 2, 3) for "x" and then copy and paste the information to the right of those columns to the appropriate sheet for the group. If they have interest in multiple groups, their contact info should be copied to each specific worksheet.\

Do I need to have separate counters for each group worksheet and is there a way to write a if then statement that checks for x in each of the columns and then runs the appropriate code to copy and paste into that group?

```<code>Sub Update()

    Dim c As Range
    Dim j As Integer
    Dim Source As Worksheet
    Dim Target1 As Worksheet
    Dim Target2 As Worksheet
    Dim Target3 As Worksheet

    Set Source = ActiveWorkbook.Worksheets("Interest Group Tracking")
    Set Target1 = ActiveWorkbook.Worksheets("Group 1")

    j = 1   'Start copying to row 1 in target sheet
    For Each c In Source.Range("A1:A1000") 'not sure if there is a way to not set a limit for the range
        If c = "x" Then
            Source.Rows(c.Row).Copy Target1.Rows(j + 1)
            j = j + 1
            End If
    Next c

End Sub
</code>```

No errors besides the occasional syntax but don't really know how to structure the loop for checking for each group. I am continuing to research and test things I find and will update if I need to.

答:
Another way of doing it.</p>

```<code>Option Explicit

Sub CopyData()

Dim srcWB As Workbook
Dim srcWS As Worksheet
Dim destWS As Worksheet
Dim CopyRange As Variant

Dim i As Long, j As Long
Dim srcLRow As Long, destLRow As Long
Dim LCol As Long

Set srcWB = ActiveWorkbook
Set srcWS = srcWB.ActiveSheet

srcLRow = srcWS.Cells(srcWS.Rows.Count, "A").End(xlUp).Row
'loop through column 1 to 3
For i = 1 To 3
    For j = 2 To srcLRow
        'loop through rows

            If srcWS.Cells(j, i).value = "x" Then
                Set destWS = srcWB.Sheets("Sheet" & i)
                destLRow = destWS.Cells(destWS.Rows.Count, "A").End(xlUp).Row
                LCol = srcWS.Cells(j, srcWS.Columns.Count).End(xlToLeft).Column 'if you need to grab last used column

                ' Copy data
                Set CopyRange = srcWS.Range(Cells(j, 1), Cells(j, LCol))
                    CopyRange.Copy
                ' paste data from one sht to another
                destWS.Cells(destLRow + 1, 1).PasteSpecial Paste:=xlPasteAll, Transpose:=False
                Application.CutCopyMode = False
            End If
    Next j
Next i
MsgBox "Process completed!", vbInformation
End Sub
</code>```

Body:
I am not a programmer by trade but I am trying to automate a small portion of a report I use every day out of curiosity and self interest. Basically, we receive and manually enter contact information (name, e-mail, phone number, etc.) and mark select groups that a person is interested in joining. We then copy and paste that contact information entered into a different sheet for each group.

I want to have a macro that checks the specific columns for each interest group for a "x" and if it finds that value copy and paste the contact information collected to the specific interest groups worksheet. People are able to select multiple interest groups and their contact information is added to each separate interest group spreadsheet.

Report columns look as follows:

Group 1 Group 2 Group 3 Name Organization Phone E-mail  Notes

Row Contact Information looks similar to:
  x  x John ABC Inc. 000-000-0000 john.smith@fake.com  Call me ASAP!

The macro checks the column I have marked interest in Group 1 in and if it finds "x" then it copies the full range to the Group 1 worksheet.

I want it to be able to check multiple columns (i.e. Group 1, 2, 3) for "x" and then copy and paste the information to the right of those columns to the appropriate sheet for the group. If they have interest in multiple groups, their contact info should be copied to each specific worksheet.\

Do I need to have separate counters for each group worksheet and is there a way to write a if then statement that checks for x in each of the columns and then runs the appropriate code to copy and paste into that group?

Sub Update()

    Dim c As Range
    Dim j As Integer
    Dim Source As Worksheet
    Dim Target1 As Worksheet
    Dim Target2 As Worksheet
    Dim Target3 As Worksheet

    Set Source = ActiveWorkbook.Worksheets("Interest Group Tracking")
    Set Target1 = ActiveWorkbook.Worksheets("Group 1")

    j = 1   'Start copying to row 1 in target sheet
    For Each c In Source.Range("A1:A1000") 'not sure if there is a way to not set a limit for the range
        If c = "x" Then
            Source.Rows(c.Row).Copy Target1.Rows(j + 1)
            j = j + 1
            End If
    Next c

End Sub

No errors besides the occasional syntax but don't really know how to structure the loop for checking for each group. I am continuing to research and test things I find and will update if I need to.

Body:
Another way of doing it.

Option Explicit

Sub CopyData()

Dim srcWB As Workbook
Dim srcWS As Worksheet
Dim destWS As Worksheet
Dim CopyRange As Variant

Dim i As Long, j As Long
Dim srcLRow As Long, destLRow As Long
Dim LCol As Long

Set srcWB = ActiveWorkbook
Set srcWS = srcWB.ActiveSheet

srcLRow = srcWS.Cells(srcWS.Rows.Count, "A").End(xlUp).Row
'loop through column 1 to 3
For i = 1 To 3
    For j = 2 To srcLRow
        'loop through rows

            If srcWS.Cells(j, i).value = "x" Then
                Set destWS = srcWB.Sheets("Sheet" & i)
                destLRow = destWS.Cells(destWS.Rows.Count, "A").End(xlUp).Row
                LCol = srcWS.Cells(j, srcWS.Columns.Count).End(xlToLeft).Column 'if you need to grab last used column

                ' Copy data
                Set CopyRange = srcWS.Range(Cells(j, 1), Cells(j, LCol))
                    CopyRange.Copy
                ' paste data from one sht to another
                destWS.Cells(destLRow + 1, 1).PasteSpecial Paste:=xlPasteAll, Transpose:=False
                Application.CutCopyMode = False
            End If
    Next j
Next i
MsgBox "Process completed!", vbInformation
End Sub


问:
How to keep a value throughout a recursive function (kdtree problem)
I programming Kdtrees with Python 3 and I have an issue with the function that is aimed to determined whether the node put in the arguments is in the Kdtree.

I use a recursive function but it returns None even when the point is present.

#I put the init to show you how the kdnode is made

class KdNode:

def __init__(self, point, dim, left_child, right_child):
   self.point = point;
   self.dim = dim;
   self.left_child = left_child;
   self.right_child = right_child;

def KdTree_present(kdnode,point_to_test):
    if kdnode == None:
        return
    else:

        KdTree_present(kdnode.left_child, point_to_test)
        KdTree_present(kdnode.right_child, point_to_test)
        if kdnode.point == point_to_test:

            return True

#Kdnode_example = [(150, 300), 1, [(200, 250), 0, None, None], [(325, 400), 0, None, None]]
```

Even the output of KdTree_present has to be True, it is always None.

答:
What type is point? Remember that if you compare objects you will always get false unless they're in the same space of memory (they're pointing to the same object), refer to this question Compare object instances for equality by their attributes in Python

For == to work you would have to override the function __eq__ in point. Either create that function or change your condition to something like if knode.point.x == point_to_test.x and knode.point.y == point_to_test.y

Edit:

To add to your comment, there's indeed a problem with the recursion, it will go through all the children until it returns False since there's no more children, or return True if it founds it, whatever is faster, what you should do is this:

```<code>def KdTree_present(kdnode,point_to_test):
    if kdnode == None:
        return False
    if kdnode.point == point_to_test:
        return True
    return KdTree_present(kdnode.left_child, point_to_test) or KdTree_present(kdnode.right_child, point_to_test)
</code>```

Body:
I programming Kdtrees with Python 3 and I have an issue with the function that is aimed to determined whether the node put in the arguments is in the Kdtree.

I use a recursive function but it returns None even when the point is present.

#I put the init to show you how the kdnode is made

class KdNode:

def __init__(self, point, dim, left_child, right_child):
   self.point = point;
   self.dim = dim;
   self.left_child = left_child;
   self.right_child = right_child;

def KdTree_present(kdnode,point_to_test):
    if kdnode == None:
        return
    else:

        KdTree_present(kdnode.left_child, point_to_test)
        KdTree_present(kdnode.right_child, point_to_test)
        if kdnode.point == point_to_test:

            return True

#Kdnode_example = [(150, 300), 1, [(200, 250), 0, None, None], [(325, 400), 0, None, None]]

Even the output of KdTree_present has to be True, it is always None.

Body:
What type is point? Remember that if you compare objects you will always get false unless they're in the same space of memory (they're pointing to the same object), refer to this question Compare object instances for equality by their attributes in Python

For == to work you would have to override the function __eq__ in point. Either create that function or change your condition to something like if knode.point.x == point_to_test.x and knode.point.y == point_to_test.y

Edit:

To add to your comment, there's indeed a problem with the recursion, it will go through all the children until it returns False since there's no more children, or return True if it founds it, whatever is faster, what you should do is this:

def KdTree_present(kdnode,point_to_test):
    if kdnode == None:
        return False
    if kdnode.point == point_to_test:
        return True
    return KdTree_present(kdnode.left_child, point_to_test) or KdTree_present(kdnode.right_child, point_to_test)


问:
Fabric asks for password even though I can SSH using credential
I'm having an odd problem while deploying a Django site using Fabric. I've configured two servers to use key files for login. I can SSH into both without a password. I can run fab on one correctly,

```<code>$ fab live pull
[mysite.com] Executing task 'pull'
[mysite.com] run: test -d proj
[mysite.com] run: test -d proj/.git
[mysite.com] run: git pull origin master
...
</code>```

while the other server asks for a password:

```<code>$ fab staging pull
[dev.mysite.com] Executing task 'pull'
[dev.mysite.com] run: test -d proj
[dev.mysite.com] Login password:
</code>```

The fabfile is set up pretty explicitly

```<code>def staging():
    env.hosts = ['dev.mysite.com']
    env.user = 'bamboo'
    env.key_filename = '~/.ssh/id_dsa_bamboo'
</code>```

And running ssh directly from the command line works

```<code>$ ssh bamboo@dev.mysite.com -i ~/.ssh/id_dsa_bamboo
Last login: Wed Apr 11 06:24:28 2012 from xxx.xxx.xx.xx
[bamboo@dev ~]$
</code>```

I also tried setting env.use_ssh_config = True and running with ~/.ssh/config set to

```<code>Host dev.mysite.com
    User bamboo
    IdentityFile ~/.ssh/id_dsa_bamboo
    ForwardAgent yes
</code>```

Any ideas what could be going on? Thanks for the help.

答:
In my case, I was unable to see anything helpful in the log files. I was able to connect, however, after first connecting to the server using ssh and enabling ssh-agent forwarding:

ssh -A <user>@<host>

Then I ran fab and was connected without being asked for a password as expected.

Body:
I'm having an odd problem while deploying a Django site using Fabric. I've configured two servers to use key files for login. I can SSH into both without a password. I can run fab on one correctly,

$ fab live pull
[mysite.com] Executing task 'pull'
[mysite.com] run: test -d proj
[mysite.com] run: test -d proj/.git
[mysite.com] run: git pull origin master
...

while the other server asks for a password:

$ fab staging pull
[dev.mysite.com] Executing task 'pull'
[dev.mysite.com] run: test -d proj
[dev.mysite.com] Login password:

The fabfile is set up pretty explicitly

def staging():
    env.hosts = ['dev.mysite.com']
    env.user = 'bamboo'
    env.key_filename = '~/.ssh/id_dsa_bamboo'

And running ssh directly from the command line works

$ ssh bamboo@dev.mysite.com -i ~/.ssh/id_dsa_bamboo
Last login: Wed Apr 11 06:24:28 2012 from xxx.xxx.xx.xx
[bamboo@dev ~]$

I also tried setting env.use_ssh_config = True and running with ~/.ssh/config set to

Host dev.mysite.com
    User bamboo
    IdentityFile ~/.ssh/id_dsa_bamboo
    ForwardAgent yes

Any ideas what could be going on? Thanks for the help.


问:
How to fix 'UnicodeDecodeError:'?
I'm trying to create a chatbot and whenever I try running my code I get this,

line 107, in
    for row in f:
  File "/Users/usr/anaconda3/lib/python3.6/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xf8 in position 102: ordinal not in range(128)

I was going to try to add,

```<code>import sys
reload(sys)
sys.setdefaultencoding("utf-8")
</code>```

However I was told that setdefaultencoding is not safe to use, so I never got around to trying this.

Below is my code,

```<code>import sqlite3
import json
from datetime import datetime

timeframe = '2015-01'
sql_transaction = []

connection = sqlite3.connect('/Users/usr/Desktop/fileName/RC_{}'.format(timeframe))
c = connection.cursor()

def create_table():
    c.execute("""CREATE TABLE IF NOT EXISTS parent_reply
    (parent_id TEXT PRIMARY KEY, comment_id TEXT UNIQUE, parent TEXT,
     comment TEXT, subreddit TEXT, unix INT, score INT)""")

def format_data(data):
    data = data.replace("\n", " newlinechar ").replace("\r", " newlinechar ").replace('"', "'")
    return data

def find_existing_score(pid):
    try:
        sql = "SELECT score FROM parent_reply WHERE parent_id = '{}' LIMIT 1".format(pid)
        c.execute(sql)
        result = c.fetchon()
        if result != None:
            return result[0]
        else:
            return False
    except Exception as e:
        # print("find_parent", e)
        return False

if __name__ == "__main__":
    create_table()
    row_counter = 0
    paired_rows = 0

    with open("/Users/usr/Desktop/fileName/RC_{}".format(timeframe), buffering=1000) as f:
        for row in f:
            row_counter += 1
            row = json.loads(row)
            parent_id = row['parent_id']
            body = format_data(row['body'])
            created_utc = row['created_utc']
            score = row['score']
            subreddit = row['subreddit']
            comment_id = row['name']
            parent_data = find_parent(parent_id)

            if score >= 2:
                if acceptable(body):
                    existing_comment_score = find_existing_score(parent_id)
                    if existing_comment_score:
                        if score > existing_comment_score:
                            sql_insert_replace_comment(comment_id, parent_id, parent_data, body, subreddit, created_utc, score)

                    else:
                        if parent_data:
                            sql_insert_has_parent(comment_id, parent_id, parent_data, body, subreddit, created_utc, score)
                            paired_rows += 1
                        else:
                            sql_insert_no_parent(comment_id, parent_id, body, subreddit, created_utc, score)
            if row_counter % 100000 == 0:
                print("Total rows read: {}, Paired rows: {}, Time: {}".format(row_counter, paired_rows, str(datetime.now())))
</code>```

The RC_2015-01 is extracted from a zip file named RC_2015-01.bz2. I'm not sure if this is an issue.

答:
I solved it!

```<code>timeframe = '2015-01'
sql_transaction = []

connection = sqlite3.connect('/Users/usr/Desktop/fileName/RC_{}.db'.format(timeframe))
c = connection.cursor()
</code>```

The issue was that it would create a database that wasn't a database and would have the same name as the file it was trying to decode. By adding .db the file becomes a database and gets a different name.

Title: How to fix 'UnicodeDecodeError:'?

Body:
I'm trying to create a chatbot and whenever I try running my code I get this,

line 107, in
    for row in f:
  File "/Users/usr/anaconda3/lib/python3.6/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xf8 in position 102: ordinal not in range(128)

I was going to try to add,

import sys
reload(sys)
sys.setdefaultencoding("utf-8")

However I was told that setdefaultencoding is not safe to use, so I never got around to trying this.

Below is my code,

import sqlite3
import json
from datetime import datetime

timeframe = '2015-01'
sql_transaction = []

connection = sqlite3.connect('/Users/usr/Desktop/fileName/RC_{}'.format(timeframe))
c = connection.cursor()

def create_table():
    c.execute("""CREATE TABLE IF NOT EXISTS parent_reply
    (parent_id TEXT PRIMARY KEY, comment_id TEXT UNIQUE, parent TEXT,
     comment TEXT, subreddit TEXT, unix INT, score INT)""")

def format_data(data):
    data = data.replace("\n", " newlinechar ").replace("\r", " newlinechar ").replace('"', "'")
    return data

def find_existing_score(pid):
    try:
        sql = "SELECT score FROM parent_reply WHERE parent_id = '{}' LIMIT 1".format(pid)
        c.execute(sql)
        result = c.fetchon()
        if result != None:
            return result[0]
        else:
            return False
    except Exception as e:
        # print("find_parent", e)
        return False

if __name__ == "__main__":
    create_table()
    row_counter = 0
    paired_rows = 0

    with open("/Users/usr/Desktop/fileName/RC_{}".format(timeframe), buffering=1000) as f:
        for row in f:
            row_counter += 1
            row = json.loads(row)
            parent_id = row['parent_id']
            body = format_data(row['body'])
            created_utc = row['created_utc']
            score = row['score']
            subreddit = row['subreddit']
            comment_id = row['name']
            parent_data = find_parent(parent_id)

            if score >= 2:
                if acceptable(body):
                    existing_comment_score = find_existing_score(parent_id)
                    if existing_comment_score:
                        if score > existing_comment_score:
                            sql_insert_replace_comment(comment_id, parent_id, parent_data, body, subreddit, created_utc, score)

                    else:
                        if parent_data:
                            sql_insert_has_parent(comment_id, parent_id, parent_data, body, subreddit, created_utc, score)
                            paired_rows += 1
                        else:
                            sql_insert_no_parent(comment_id, parent_id, body, subreddit, created_utc, score)
            if row_counter % 100000 == 0:
                print("Total rows read: {}, Paired rows: {}, Time: {}".format(row_counter, paired_rows, str(datetime.now())))

The RC_2015-01 is extracted from a zip file named RC_2015-01.bz2. I'm not sure if this is an issue.

Body:
I solved it!

timeframe = '2015-01'
sql_transaction = []

connection = sqlite3.connect('/Users/usr/Desktop/fileName/RC_{}.db'.format(timeframe))
c = connection.cursor()

The issue was that it would create a database that wasn't a database and would have the same name as the file it was trying to decode. By adding .db the file becomes a database and gets a different name.


问:
Extracting Files between two dates which has been saved with dates
I have saved all the daily sales reports in a common folder. each file is named with the corresponding date. eg: 01-01-2019-Sales.csv, 02-01-2019-Sales.csv, etc. all the files are saved in the "C:\Desktop\Sales" folder path. now i want to extract &  combine all the files which are between 05-01-2019 to 04-02-2019.

I know I can extract all the files with pandas using the below code

```<code>import pandas as pd
import glob
import os

file_path = r'C:\Desktop\Sales'
all_files = glob.glob(os.path.join(file_path,'*.csv'))
df = pd.concat([pd.read_csv(f) for f in all_files], sort=False)
</code>```

But, my question is how can i extract files between 2 given specific dates using pandas/python. (using the file names which has been saved with the date) eg ; extract only the files between 05-01-2019 to 04-02-2019.

答:
The dates could be compared lexically with a change to yyyy-mm-dd.</p>

```<code>L = [ '01-01-2019-Sales.csv', '02-01-2019-Sales.csv']
>>> start = '2018-12-01'
>>> end = '2019-02-01'

>>> for file in L:
    m, d, yr = file.split('-')[:3]
    date = '-'.join([yr, m, d])
    if start <= date <= end:
        print(file)

01-01-2019-Sales.csv
02-01-2019-Sales.csv
</code>```

Body:
I have saved all the daily sales reports in a common folder. each file is named with the corresponding date. eg: 01-01-2019-Sales.csv, 02-01-2019-Sales.csv, etc. all the files are saved in the "C:\Desktop\Sales" folder path. now i want to extract &  combine all the files which are between 05-01-2019 to 04-02-2019.

I know I can extract all the files with pandas using the below code

import pandas as pd
import glob
import os

file_path = r'C:\Desktop\Sales'
all_files = glob.glob(os.path.join(file_path,'*.csv'))
df = pd.concat([pd.read_csv(f) for f in all_files], sort=False)

But, my question is how can i extract files between 2 given specific dates using pandas/python. (using the file names which has been saved with the date) eg ; extract only the files between 05-01-2019 to 04-02-2019.

Body:
The dates could be compared lexically with a change to yyyy-mm-dd.

L = [ '01-01-2019-Sales.csv', '02-01-2019-Sales.csv']
>>> start = '2018-12-01'
>>> end = '2019-02-01'

>>> for file in L:
    m, d, yr = file.split('-')[:3]
    date = '-'.join([yr, m, d])
    if start <= date <= end:
        print(file)

01-01-2019-Sales.csv
02-01-2019-Sales.csv


问:
How to access model in constants.php in Codeigniter?
I want to access a function on application/config/constants.php, which is written in one of my CodeIgniter model. Is it possible to do it?</p>

答:
There is no reason to change a constant with a model function or any function for that matter. Constants are meant to be static and strict definitions. Like application paths, version numbers, .etc.

They are similar to a variable except that they can never be changed.

If you wish to have a variable that is a superglobal but needs to be dynamic in some respect you can create a /application/core/MY_Controller.php

```<code>class MY_Controller extends CI_Controller {

     public $someglobalvar;

     public function __construct() {
          parent::__construct();
          $this->load->model('somemodel');
          $this->someglobalvar = $this->somemodel->get_var();
     }

}
</code>```

and have your controllers extend it instead of CI_Controller

(application/controllers/Some_controller.php)

```<code>class Some_controller extends MY_Controller {

     public function index() {

          var_dump($this->someglobalvar);

     }

}
</code>```

Body:
There is no reason to change a constant with a model function or any function for that matter. Constants are meant to be static and strict definitions. Like application paths, version numbers, .etc.

They are similar to a variable except that they can never be changed.

If you wish to have a variable that is a superglobal but needs to be dynamic in some respect you can create a /application/core/MY_Controller.php

class MY_Controller extends CI_Controller {

     public $someglobalvar;

     public function __construct() {
          parent::__construct();
          $this->load->model('somemodel');
          $this->someglobalvar = $this->somemodel->get_var();
     }

}

and have your controllers extend it instead of CI_Controller

(application/controllers/Some_controller.php)

class Some_controller extends MY_Controller {

     public function index() {

          var_dump($this->someglobalvar);

     }

}


问:
Evaluating DNNClassifier for multi-label classification
I am using tensorflow DNNClassifier for multi label classification, which uses accuracy as it uses its metric. I am evaluating the model using sklearn f1 metric, which is showing quite low score. Also score from sklearn accuracy is low. Is my implementation wrong somewhere?

DNN classifier

```<code>embedding_feats = hub.text_embedding_column(key='text',
                         module_spec='https://tfhub.dev/google/universal-sentence-encoder/2',
                         trainable=False)

dnn = tf.estimator.DNNClassifier(
          hidden_units=[512, 128],
          feature_columns=[embedding_feats],
          n_classes=11,
          activation_fn=tf.nn.relu,
          dropout=0.1,
          optimizer=tf.train.AdagradOptimizer(learning_rate=0.005))
</code>```

DNN classifier Train Output. Val acc is 0.40

```<code>Training for step = 8000
Train Time (s): 52.573952436447144
Eval Metrics (Train): {'accuracy': 0.44695774, 'average_loss': 1.516403, 'loss': 193.58235, 'global_step': 8200}
Eval Metrics (Validation): {'accuracy': 0.40303582, 'average_loss': 1.6520736, 'loss': 209.30502, 'global_step': 8200}
</code>```

Sklearn F1 score

```<code>f1_score(y_test,predictions_test,labels=le.classes_,average='weighted')
0.1066998393248964
</code>```

Sklearn Accuracy score

```<code>accuracy_score(y_test, predictions_test)
0.11804138735062664
</code>```

答:
One possible reason for this could be that you are not converting your predictions to whole number i.e. 0 or 1. Your neural network is generating an output in terms of probability of a record being of class 1. If you directly take this probabilities and evaluate it with your y_test, they will not match because 0.98 is not equal to 1.

Round predictions_test to the nearest whole number i.e. <0.5 will be 0 and >0.5 will be 1 and check accuracy.

Body:
I am using tensorflow DNNClassifier for multi label classification, which uses accuracy as it uses its metric. I am evaluating the model using sklearn f1 metric, which is showing quite low score. Also score from sklearn accuracy is low. Is my implementation wrong somewhere?

DNN classifier

embedding_feats = hub.text_embedding_column(key='text',
                         module_spec='https://tfhub.dev/google/universal-sentence-encoder/2',
                         trainable=False)

dnn = tf.estimator.DNNClassifier(
          hidden_units=[512, 128],
          feature_columns=[embedding_feats],
          n_classes=11,
          activation_fn=tf.nn.relu,
          dropout=0.1,
          optimizer=tf.train.AdagradOptimizer(learning_rate=0.005))

DNN classifier Train Output. Val acc is 0.40

Training for step = 8000
Train Time (s): 52.573952436447144
Eval Metrics (Train): {'accuracy': 0.44695774, 'average_loss': 1.516403, 'loss': 193.58235, 'global_step': 8200}
Eval Metrics (Validation): {'accuracy': 0.40303582, 'average_loss': 1.6520736, 'loss': 209.30502, 'global_step': 8200}

Sklearn F1 score

f1_score(y_test,predictions_test,labels=le.classes_,average='weighted')
0.1066998393248964

Sklearn Accuracy score

accuracy_score(y_test, predictions_test)
0.11804138735062664


问:
Why passing by reference works using only pointers declared in the argument list of this C program?
This is Program 3.7 from Robert Wood's "C Programming for Scientists and Engineers". In the code below, the pointers are not declared and initialized in the body of main(), but directly in the argument list of read_data() function.

Normally, when writing code, I first declare 3 pointers (int *int_ptr, float *float_ptr, char *char_ptr) and then assign the addresses of the a, b and c to them. But in the program below, "address of" operators are passed when calling read_data(&a, &b, c); through the argument list of void read_data(int *int_ptr, float *float_ptr, char *char_ptr){...}, where we have "contents of" operators, which seems inconsistent, but works.
Also, fscanf(stdin,"%d %f %s", int_ptr, float_ptr, char_ptr); stores the data supplied by the user in the address of the pointers, whereas I think thought that they should be written in the contents of the variables a, b and c like that:

```<code>fscanf(stdin,"%d %f %s", int_*ptr, *float_ptr, *char_ptr);
</code>```

But I am wrong.

Otherwise the program works, but if I had to write it this way, I will not be able to. So, I want you to help me understand and maybe provide alternative solution.

```<code>/* Program 3.7- Use of functions for input and output of data */
#include <stdio.h>

int main(void) {
  int a;
  float b;
  char c[11];

  /* function prototype */
  void read_data(int *, float *, char *);
  void write_data(int, float, char[]);

  /*call the function*/
  read_data(&a, &b, c);
  write_data(a, b, c);

  return (0);
}

/*Function: read_data - reads an int, float and char string*/
void read_data(int *int_ptr, float *float_ptr, char *char_ptr) {
  fprintf(stdout, " Supply an integer, a float and a string (max. 10 chars):");
  fscanf(stdin, "%d %f %s", int_ptr, float_ptr, char_ptr);
  return;
}

/* Function: write_data - displays an int, float and char string*/
void write_data(int i, float j, char k[]) {
  fprintf(stdout, " The supplied data is: %d %f %s\n", i, j, k);
  return;
}
</code>```

答:
It's not inconsistent, you are just inferring the wrong attributes to the function.

Note the difference between:

A function declaration:

```<code>void read_data(int *int_ptr, float *float_ptr, char *char_ptr){...}
</code>```

And a function call

```<code>read_data(int_ptr, float_ptr, char_ptr);
</code>```

But in the program below, "address of" operators are passed when calling read_data(&a, &b, c); through the argument list of void read_data(int *int_ptr, float *float_ptr, char *char_ptr){...}, where we have "contents of" operators, which seems inconsistent, but works

Your inference on what this function's argument list represents is what is causing your confusion. The function does not take "contents of" pointers, but rather pointers themselves. And since the "address of" operator returns a pointer, it is perfectly fine to call the function using read_data(&a, &b, c)

Body:
This is Program 3.7 from Robert Wood's "C Programming for Scientists and Engineers". In the code below, the pointers are not declared and initialized in the body of main(), but directly in the argument list of read_data() function.

Normally, when writing code, I first declare 3 pointers (int *int_ptr, float *float_ptr, char *char_ptr) and then assign the addresses of the a, b and c to them. But in the program below, "address of" operators are passed when calling read_data(&a, &b, c); through the argument list of void read_data(int *int_ptr, float *float_ptr, char *char_ptr){...}, where we have "contents of" operators, which seems inconsistent, but works.
Also, fscanf(stdin,"%d %f %s", int_ptr, float_ptr, char_ptr); stores the data supplied by the user in the address of the pointers, whereas I think thought that they should be written in the contents of the variables a, b and c like that:

fscanf(stdin,"%d %f %s", int_*ptr, *float_ptr, *char_ptr);

But I am wrong.

Otherwise the program works, but if I had to write it this way, I will not be able to. So, I want you to help me understand and maybe provide alternative solution.

/* Program 3.7- Use of functions for input and output of data */
#include <stdio.h>

int main(void) {
  int a;
  float b;
  char c[11];

  /* function prototype */
  void read_data(int *, float *, char *);
  void write_data(int, float, char[]);

  /*call the function*/
  read_data(&a, &b, c);
  write_data(a, b, c);

  return (0);
}

/*Function: read_data - reads an int, float and char string*/
void read_data(int *int_ptr, float *float_ptr, char *char_ptr) {
  fprintf(stdout, " Supply an integer, a float and a string (max. 10 chars):");
  fscanf(stdin, "%d %f %s", int_ptr, float_ptr, char_ptr);
  return;
}

/* Function: write_data - displays an int, float and char string*/
void write_data(int i, float j, char k[]) {
  fprintf(stdout, " The supplied data is: %d %f %s\n", i, j, k);
  return;
}

Body:
It's not inconsistent, you are just inferring the wrong attributes to the function.

Note the difference between:

A function declaration:

void read_data(int *int_ptr, float *float_ptr, char *char_ptr){...}

And a function call

read_data(int_ptr, float_ptr, char_ptr);

But in the program below, "address of" operators are passed when calling read_data(&a, &b, c); through the argument list of void read_data(int *int_ptr, float *float_ptr, char *char_ptr){...}, where we have "contents of" operators, which seems inconsistent, but works

Your inference on what this function's argument list represents is what is causing your confusion. The function does not take "contents of" pointers, but rather pointers themselves. And since the "address of" operator returns a pointer, it is perfectly fine to call the function using read_data(&a, &b, c)


问:
ReactJS: Return value when item is clicked (multi step form)
I am fairly new to ReactJS. For a small project I am building, I have created a component which returns a value when a card item is clicked. The goal is to build a multi step form.

So far it works as expected but I am pretty sure I am not following best practices.

Especially the 3 event listeners seems to be to repetitive.

Does someone more experienced has suggestions on how to improve the code? Many thanks for your support. :)

```<code>  import React from 'react';
  import PropTypes from 'prop-types';
  import { withStyles } from '@material-ui/core/styles';
  import Grid from '@material-ui/core/Grid';
  import Paper from '@material-ui/core/Paper';

  // Styles for grid items/cards
  const styles = theme => ({
    root: {
      flexGrow: 1,
    },
    paper: {
      height: 250,
      width: 200,
      margin: 20,
    },
  });

  // COMPONENT
  export class Form1 extends React.Component {
    state = {
      spacing: '0',
      step: 1,
      optionStep1: ''
    };

  // METHODS
  // Proceed to next step
  nextStep = () => {
    const { step } = this.state;
    this.setState( {
      step: step + 1
    });
  }

  // Previus step
  prevStep = () => {
    const { step } = this.state;
    this.setState( {
      step: step - 1
    });
  }

  // Change Option of Step 1
  constructor(props) {
    super(props);
    this.state = {
      optionStep1: ''
    };

    // This binding is necessary to make `this` work in the callback
    this.handleClick1 = this.handleClick1.bind(this);
    this.handleClick2 = this.handleClick2.bind(this);
    this.handleClick3 = this.handleClick3.bind(this);
  }

  // Eventlisteners
  handleClick1() {
    this.setState(state => ({
      optionStep1: 'option 1 picked'
    })
    );
    console.log('option 1 picked');
  }

  handleClick2() {
    this.setState(state => ({
      optionStep1: 'option 2 picked'
    })
    );
    console.log('option 2 picked');
  }

  handleClick3() {
    this.setState(state => ({
      optionStep1: 'option 3 picked'
    })
    );
    console.log('option 3 picked');
  }

  // RENDER
    render() {
      const { classes } = this.props;
      const { spacing } = this.state;

      return (
        <Grid container className={classes.root} spacing={16}>
          <Grid item xs={12}>
            <Grid container className={classes.demo} justify="center" spacing={Number(spacing)}>
                <Grid onClick={this.handleClick1}>
                  <Paper className={classes.paper} />
                </Grid>
                <Grid onClick={this.handleClick2}>
                  <Paper className={classes.paper} />
                </Grid>
                <Grid onClick={this.handleClick3}>
                  <Paper className={classes.paper} />
                </Grid>
            </Grid>
          </Grid>
        </Grid>
      );
    }
  }

  Form1.propTypes = {
    classes: PropTypes.object.isRequired,
  };

  export default withStyles(styles)(Form1);
</code>```

答:
I would create only one handleClick function that would take an argument:

```<code>handleClick(option) {
  this.setState({
    optionStep1: `option ${option} picked`,
  });

  console.log(`option ${option} picked`);
}
</code>```

And then you can call this generic function for each of your option elements:

```<code><Grid onClick={() => this.handleClick(1)}>
  <Paper className={classes.paper} />
</Grid>
</code>```

Body:
I am fairly new to ReactJS. For a small project I am building, I have created a component which returns a value when a card item is clicked. The goal is to build a multi step form.

So far it works as expected but I am pretty sure I am not following best practices.

Especially the 3 event listeners seems to be to repetitive.

Does someone more experienced has suggestions on how to improve the code? Many thanks for your support. :)

  import React from 'react';
  import PropTypes from 'prop-types';
  import { withStyles } from '@material-ui/core/styles';
  import Grid from '@material-ui/core/Grid';
  import Paper from '@material-ui/core/Paper';

  // Styles for grid items/cards
  const styles = theme => ({
    root: {
      flexGrow: 1,
    },
    paper: {
      height: 250,
      width: 200,
      margin: 20,
    },
  });

  // COMPONENT
  export class Form1 extends React.Component {
    state = {
      spacing: '0',
      step: 1,
      optionStep1: ''
    };

  // METHODS
  // Proceed to next step
  nextStep = () => {
    const { step } = this.state;
    this.setState( {
      step: step + 1
    });
  }

  // Previus step
  prevStep = () => {
    const { step } = this.state;
    this.setState( {
      step: step - 1
    });
  }

  // Change Option of Step 1
  constructor(props) {
    super(props);
    this.state = {
      optionStep1: ''
    };

    // This binding is necessary to make `this` work in the callback
    this.handleClick1 = this.handleClick1.bind(this);
    this.handleClick2 = this.handleClick2.bind(this);
    this.handleClick3 = this.handleClick3.bind(this);
  }

  // Eventlisteners
  handleClick1() {
    this.setState(state => ({
      optionStep1: 'option 1 picked'
    })
    );
    console.log('option 1 picked');
  }

  handleClick2() {
    this.setState(state => ({
      optionStep1: 'option 2 picked'
    })
    );
    console.log('option 2 picked');
  }

  handleClick3() {
    this.setState(state => ({
      optionStep1: 'option 3 picked'
    })
    );
    console.log('option 3 picked');
  }

  // RENDER
    render() {
      const { classes } = this.props;
      const { spacing } = this.state;

      return (
        <Grid container className={classes.root} spacing={16}>
          <Grid item xs={12}>
            <Grid container className={classes.demo} justify="center" spacing={Number(spacing)}>
                <Grid onClick={this.handleClick1}>
                  <Paper className={classes.paper} />
                </Grid>
                <Grid onClick={this.handleClick2}>
                  <Paper className={classes.paper} />
                </Grid>
                <Grid onClick={this.handleClick3}>
                  <Paper className={classes.paper} />
                </Grid>
            </Grid>
          </Grid>
        </Grid>
      );
    }
  }

  Form1.propTypes = {
    classes: PropTypes.object.isRequired,
  };

  export default withStyles(styles)(Form1);

Body:
I would create only one handleClick function that would take an argument:

handleClick(option) {
  this.setState({
    optionStep1: `option ${option} picked`,
  });

  console.log(`option ${option} picked`);
}

And then you can call this generic function for each of your option elements:

<Grid onClick={() => this.handleClick(1)}>
  <Paper className={classes.paper} />
</Grid>


问:
Exclude directory while using tar
I use the following command to create a tar.gz

```<code>tar -pczf domain.com.tar.gz  /var/www/domain.com/public_html/www/
</code>```

The tar.gz file contain the following folders

```<code>var-->www-->domain.com-->public_html-->www-->then the content of www
</code>```

I want the tar.gz file to contain only the content of www without any folder.I tried to use -C but i get

Cowardly refusing to create an empty archive error

```<code>tar -pczf domain.com.tar.gz -C  /var/www/domain.com/public_html/www/
</code>```

Edit 1
I added the . but then the exclude no longer work and all files have a ./ in their filename

Filename become like .\file.txt in archive

```<code>tar -pczf domain.com.tar.gz -C  /var/www/domain.com/public_html/www/ . --exclude='/var/www/domain.com/public_html/www/tmp/*'
</code>```

Real example

```<code>tar --exclude='tmp/cookies/*' --exclude='tmp/logs/*' -pczf filterbypass.me.tar.gz -C /var/www/filterbypass.me/public_html/www .
</code>```

I want tar,gz to contain only my files in www , not folders + not ./ in filename

答:
After reading all this good answers for different versions and having solved the problem for myself, I think there are very small details that are very important, and rare to GNU/Linux general use, that aren't stressed enough and deserves more than comments.

So I'm not going to try to answer the question for every case, but instead, try to register where to look when things doesn't work.

IT IS VERY IMPORTANT TO NOTICE:

THE ORDER OF THE OPTIONS MATTER: it is not the same put the --exclude before than after the file option and directories to backup. This is unexpected at least to me, because in my experience, in GNU/Linux commands, usually the order of the options doesn't matter.

Different tar versions expects this options in different order: for instance, @Andrew's answer indicates that in GNU tar v 1.26 and 1.28 the excludes comes last, whereas in my case, with GNU tar 1.29, it's the other way.

THE TRAILING SLASHES MATTER: at least in GNU tar 1.29, it shouldn't be any.

In my case, for GNU tar 1.29 on Debian stretch, the command that worked was

```<code>tar --exclude="/home/user/.config/chromium" --exclude="/home/user/.cache" -cf file.tar  /dir1/ /home/ /dir3/
</code>```

The quotes didn't matter, it worked with or without them.

I hope this will be useful to someone.

Title: Exclude directory while using tar

Body:
I use the following command to create a tar.gz

tar -pczf domain.com.tar.gz  /var/www/domain.com/public_html/www/

The tar.gz file contain the following folders

var-->www-->domain.com-->public_html-->www-->then the content of www

I want the tar.gz file to contain only the content of www without any folder.I tried to use -C but i get

Cowardly refusing to create an empty archive error

tar -pczf domain.com.tar.gz -C  /var/www/domain.com/public_html/www/

Edit 1
I added the . but then the exclude no longer work and all files have a ./ in their filename

Filename become like .\file.txt in archive

tar -pczf domain.com.tar.gz -C  /var/www/domain.com/public_html/www/ . --exclude='/var/www/domain.com/public_html/www/tmp/*'

Real example

tar --exclude='tmp/cookies/*' --exclude='tmp/logs/*' -pczf filterbypass.me.tar.gz -C /var/www/filterbypass.me/public_html/www .

I want tar,gz to contain only my files in www , not folders + not ./ in filename

Body:
After reading all this good answers for different versions and having solved the problem for myself, I think there are very small details that are very important, and rare to GNU/Linux general use, that aren't stressed enough and deserves more than comments.

So I'm not going to try to answer the question for every case, but instead, try to register where to look when things doesn't work.

IT IS VERY IMPORTANT TO NOTICE:

THE ORDER OF THE OPTIONS MATTER: it is not the same put the --exclude before than after the file option and directories to backup. This is unexpected at least to me, because in my experience, in GNU/Linux commands, usually the order of the options doesn't matter.

Different tar versions expects this options in different order: for instance, @Andrew's answer indicates that in GNU tar v 1.26 and 1.28 the excludes comes last, whereas in my case, with GNU tar 1.29, it's the other way.

THE TRAILING SLASHES MATTER: at least in GNU tar 1.29, it shouldn't be any.

In my case, for GNU tar 1.29 on Debian stretch, the command that worked was

tar --exclude="/home/user/.config/chromium" --exclude="/home/user/.cache" -cf file.tar  /dir1/ /home/ /dir3/

The quotes didn't matter, it worked with or without them.

I hope this will be useful to someone.


问:
to replace using find word in array from text file
I have problem that str_replace can't replace the second to last word... first word is working then second up to last is not work in array.. I tried enter the message "ducker apple banana chicken" in "chat.php?message=" then become like this:

output:

"***er apple banana chicken"

badwords.txt:

```<code>duck;
apple;
banana;
chicken;
water;
</code>```

chat.php

```<code>$censoredfilter = file("badwords.txt");
$censoredfilter = implode("\n", $censoredfilter);
$censoredfilter = explode(";", $censoredfilter);

$message = $_GET['message'];

for($i = 0; $i<sizeof($censoredfilter);$i++)
{
    $message = str_replace($censoredfilter[$i], "***", $message);
}
</code>```

答:
str_replace(array('things', 'go', 'here'), '', $text)

should replace anything value in the array found in the text with nothing

```<code>$censoredfilter = file("badwords.txt");
$censoredfilter = implode("\n", $censoredfilter);
$censoredfilter = explode(";", $censoredfilter);

str_replace($censoredfilter, '***', $_GET['message']);
</code>```

Body:
I have problem that str_replace can't replace the second to last word... first word is working then second up to last is not work in array.. I tried enter the message "ducker apple banana chicken" in "chat.php?message=" then become like this:

output:

"***er apple banana chicken"

badwords.txt:

duck;
apple;
banana;
chicken;
water;

chat.php

$censoredfilter = file("badwords.txt");
$censoredfilter = implode("\n", $censoredfilter);
$censoredfilter = explode(";", $censoredfilter);

$message = $_GET['message'];

for($i = 0; $i<sizeof($censoredfilter);$i++)
{
    $message = str_replace($censoredfilter[$i], "***", $message);
}

Body:
str_replace(array('things', 'go', 'here'), '', $text)

should replace anything value in the array found in the text with nothing

$censoredfilter = file("badwords.txt");
$censoredfilter = implode("\n", $censoredfilter);
$censoredfilter = explode(";", $censoredfilter);

str_replace($censoredfilter, '***', $_GET['message']);


问:
Dynamic flask URL variable is not being passed to the view function
I'm trying to pass a dynamic variable from a route in Flask into my view function. It seem's like a standard feature. But the code is displaying some odd behavior.

Here's the function:

@bp.route('/<id>/update', methods=('GET', 'POST'))
@login_required
def update(id):
    return id
```

<p>Here's the output on the http://localhost:5000/1/update page:</p>

```id
```

As you can see I expected the value of "1" to print, but instead the name of the parameter was printed... I have no idea why this is happening and would really appreciate some help.

Thanks!

(Edit: This is code from the tutorial)

答:
The solution was a bug in the @login_required decorator from a different module. If anyone has this same error, here is what my code was...

```<code>def login_required(view):
@functools.wraps(view)
def wrapped_view(**kwargs):
    if g.user is None:
        return redirect(url_for('auth.login'))
    return view(*kwargs)
return wrapped_view
</code>```

"kwargs" was missing a star, so python treated it as "args" instead of "kwargs"...

Body:
I'm trying to pass a dynamic variable from a route in Flask into my view function. It seem's like a standard feature. But the code is displaying some odd behavior.

Here's the function:

@bp.route('/<id>/update', methods=('GET', 'POST'))
@login_required
def update(id):
    return id

Here's the output on the http://localhost:5000/1/update page:

id

As you can see I expected the value of "1" to print, but instead the name of the parameter was printed... I have no idea why this is happening and would really appreciate some help.

Thanks!

(Edit: This is code from the tutorial)

Body:
The solution was a bug in the @login_required decorator from a different module. If anyone has this same error, here is what my code was...

def login_required(view):
@functools.wraps(view)
def wrapped_view(**kwargs):
    if g.user is None:
        return redirect(url_for('auth.login'))
    return view(*kwargs)
return wrapped_view

"kwargs" was missing a star, so python treated it as "args" instead of "kwargs"...