问:
Why does a container running a console app simply exits after starting
I want to run a simple dotnet core console app in a container interactively. I am not able to do that and the container simply starts and then exits immediately without fully running the program.

All that the console app has is the followng three statements.

```<code>Console.WriteLine("Hello World!");
var readText = Console.ReadLine(); // Wait for me to enter some text
Console.WriteLine(readText);
</code>```

The last two lines make it interactive.

When I run the container, it prints the Hello World! But then it immediately exits, without waiting for me enter some text. Why? what am I missing?

I was able to run a dotnet core web app in the container in a similar manner, and I am able to map the ports outside and within the container to successfully browse the web app. But when it comes to console app, I am stumped.

I guess there could be something very simple that I am missing. Driving me nuts

The steps to reproduce as described below.

Launch Vs2019 and create a new .net core console project.

Add a couple of statements to make it interactive.

Add Docker support to the created project. Right click the project, Add -> select Container Orchestrator Support

Now visual studio creates a set of files and changes the csproj file as well.

In a powershell navigate to folder having the solution file. Run the command "docker-compose up"

Once the images are built, and containers are up and running, we can see start to see the problem.

We can see here Hello-World!. But it does not wait for me to type something. Type docker ps -a and see a container that is exited. When I try to start that using docker start -i or docker start -a, the container starts but exits immediately. What should I do to make the container run so that i can type something for my app running in it read? You can see in the docker desktop as well. Even if I start them(using the start button available with the docker desktop UI against each container), it simply stops again.

I had run web apps in containers. With proper port mapping, a web app running inside of a container can be accessed from outside. I had created a dotnet core web app in similar lines described above, modified the docker-compose file to include port mapping(shown below) and when I do docker-compose up, the app is up and running. But with a console app, the container simply exits.

答:
By default, you don't have an interactive TTY when the container is started with docker-compose up.

You need to add that to your service:

```<code>stdin_open: true
tty: true
</code>```

Body:
I want to run a simple dotnet core console app in a container interactively. I am not able to do that and the container simply starts and then exits immediately without fully running the program.

All that the console app has is the followng three statements.

Console.WriteLine("Hello World!");
var readText = Console.ReadLine(); // Wait for me to enter some text
Console.WriteLine(readText);

The last two lines make it interactive.

When I run the container, it prints the Hello World! But then it immediately exits, without waiting for me enter some text. Why? what am I missing?

I was able to run a dotnet core web app in the container in a similar manner, and I am able to map the ports outside and within the container to successfully browse the web app. But when it comes to console app, I am stumped.

I guess there could be something very simple that I am missing. Driving me nuts

The steps to reproduce as described below.

Launch Vs2019 and create a new .net core console project.

Add a couple of statements to make it interactive.

Add Docker support to the created project. Right click the project, Add -> select Container Orchestrator Support

Now visual studio creates a set of files and changes the csproj file as well.

In a powershell navigate to folder having the solution file. Run the command "docker-compose up"

Once the images are built, and containers are up and running, we can see start to see the problem.

We can see here Hello-World!. But it does not wait for me to type something. Type docker ps -a and see a container that is exited. When I try to start that using docker start -i or docker start -a, the container starts but exits immediately. What should I do to make the container run so that i can type something for my app running in it read? You can see in the docker desktop as well. Even if I start them(using the start button available with the docker desktop UI against each container), it simply stops again.

I had run web apps in containers. With proper port mapping, a web app running inside of a container can be accessed from outside. I had created a dotnet core web app in similar lines described above, modified the docker-compose file to include port mapping(shown below) and when I do docker-compose up, the app is up and running. But with a console app, the container simply exits.

Body:
By default, you don't have an interactive TTY when the container is started with docker-compose up.

You need to add that to your service:

stdin_open: true
tty: true


来源: stackexchange

问:
Use kafka-avro-console-producer without autoregister the schema
I'm trying to use kafka-avro-console-producer 5.4.0-ccs without to autoregister the schema. I tried with:

--producer-property auto.register.schemas=false

and

--property auto.register.schemas=false

But it's registering the schema anyway. The property seems correct: https://github.com/confluentinc/schema-registry/blob/a0a04628687a72ac6d01869d881a60fbde4177e7/avro-serializer/src/main/java/io/confluent/kafka/serializers/AbstractKafkaAvroSerDeConfig.java#L54

答: it seems the property is auto.register for the CLI instead of auto.register.schemas. I found it in the code but it may change in next versions since and it isn't documented.

ContentLicense: CC BY-SA 4.0


问:
How to strip non-numeric characters in column (WHERE clause) using MySQL 5.5
I have a column registration_number with arbitrarily formatted values. These could be:

```<code>390
39B
C39(B)
39
39BC
3911
</code>```

I need all rows that match 39. Result should be:

```<code>39B
C39(B)
39
39BC
</code>```

Can I do a regexp on the WHERE column?

答:
You can use:

```<code>where registration_number regexp '(^|[^0-9])39([^0-9]|$)'
</code>```

Here is a db<>fiddle.

Body:
I have a column registration_number with arbitrarily formatted values. These could be:

390
39B
C39(B)
39
39BC
3911

I need all rows that match 39. Result should be:

39B
C39(B)
39
39BC

Can I do a regexp on the WHERE column?

Body:
You can use:

where registration_number regexp '(^|[^0-9])39([^0-9]|$)'

Here is a db<>fiddle.


问:
Map NumPy Values
Let's say I have a NumPy array:

```<code>x = np.array([[0, 5],
              [1, 6],
              [4, 3],
              [2, 4],
              [3, 2]])
</code>```

and a "look-up" array that tells me how to map one integer (first column) to another (second column):

```<code>lookup = np.array([[0, 50],
                   [1, 16],
                   [2, 47],
</code>```

So, 0 -> 50, 1 -> 16, and 2 -> 47. Notice that integers [3, 4, 5, 6] is not in the lookup and therefore do not need to be changed. A simple way to do this is:

```<code>for i in range(lookup.shape[0]):
    num = lookup[i, 0]
    x[x == num] = lookup[i, 1]
</code>```

And the expected output should be:

```<code>np.array([[50, 5],
          [16, 6],
          [4, 3],
          [47, 4],
          [3, 47]])
</code>```

For a big 2D array x and a much larger lookup, is there a more efficient way to do this in a vectorized way in NumPy?

答:
My approach for the case where x does not contain negative or big integers:

```<code>a = np.arange(x.max()+1)

a[lookup[:,0]] = lookup[:,1]

x = a[x]
</code>```

Title: Map NumPy Values

Body:
Let's say I have a NumPy array:

x = np.array([[0, 5],
              [1, 6],
              [4, 3],
              [2, 4],
              [3, 2]])

and a "look-up" array that tells me how to map one integer (first column) to another (second column):

lookup = np.array([[0, 50],
                   [1, 16],
                   [2, 47],

So, 0 -> 50, 1 -> 16, and 2 -> 47. Notice that integers [3, 4, 5, 6] is not in the lookup and therefore do not need to be changed. A simple way to do this is:

for i in range(lookup.shape[0]):
    num = lookup[i, 0]
    x[x == num] = lookup[i, 1]

And the expected output should be:

np.array([[50, 5],
          [16, 6],
          [4, 3],
          [47, 4],
          [3, 47]])

For a big 2D array x and a much larger lookup, is there a more efficient way to do this in a vectorized way in NumPy?

Body:
My approach for the case where x does not contain negative or big integers:

a = np.arange(x.max()+1)

a[lookup[:,0]] = lookup[:,1]

x = a[x]


问:
Performance of operator| vs operators+
Is there any major difference between | and + that would affect a code's performance in the long run? or are both O(1)? the code i am working with is something like this:

```<code>uint64_t dostuff(uint64_t a,uint64_t b){
        // the max values of the inputs are 2^32 - 1

        // lots of stuff involving boolean operators
        // that have no way of being substituted by
        // arithmetic operators

        return (a << 32) + b;
        //or
        return (a << 32) | b;
}
</code>```

the code will be used many times, so i want to speed it up as much as possible.

答:
Both are a single instruction. As for electronic propagation times, no idea which one is faster.

You can test for speed yourself, I guess, but seeing as the difference will probably be linear (if detectable at all), and affected by noisy factors, it may be a bit difficult.

ContentLicense: CC BY-SA 3.0

Title: Performance of operator| vs operators+

Body:
Is there any major difference between | and + that would affect a code's performance in the long run? or are both O(1)? the code i am working with is something like this:

uint64_t dostuff(uint64_t a,uint64_t b){
        // the max values of the inputs are 2^32 - 1

        // lots of stuff involving boolean operators
        // that have no way of being substituted by
        // arithmetic operators

        return (a << 32) + b;
        //or
        return (a << 32) | b;
}

the code will be used many times, so i want to speed it up as much as possible.


问:
How to fix canvas size in Mapbox GL?
I'm using Mapbox GL to show a map and crop a fixed size image from the center of it. It works great for a particular resolution I designed it (1920x1080) but when I started to make the page responsive where the map styles width and height changes, the canvas size also started to change!

So, when I crop the image the size should be always different because 300px on a 900px canvas it's not the same map area as 300px on a 2000px canvas. The canvas size even changes drastically if I change the device type from Desktop to Mobile in Chrome.

Is there any way to make the canvas DOM size fixed while scaling the entire map with CSS attributes as it's done on a normal canvas? I tried doing trackResize: false and the canvas DOM size stays fixed but the map is not scaled to fit the container neither.

答:
Im working with angular 9 and this worked for me this way:
ngAfterViewInit() {
    setTimeout(() => this.buildMap(), 2000);
  }

Title: How to fix canvas size in Mapbox GL?


问:
React useEffect hook is not working with rails
I am using the react hooks but in that useEffect is not working. As in the console start and end are not printing. Also I am using react in rails project.

```<code>import PropTypes from 'prop-types';
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';

const DetailInterview = () => {
  const [participants, setparticipants] = useState([])
  const [interviews, setinterviews] = useState([])

  async function fetchParticipantsList() {
    fetch('/api/v1/participants').
      then((response) => response.json()).
      then((participants) => setparticipants({ participants }));
  };

  async function fetchInterviewsList() {
    const { match: { params: { id } } } = this.props;
    fetch(`/api/v1/interviews/${id}`).
      then((response) => response.json()).
      then((interviews) => setinterviews({ interviews }));

    console.log("sa",interviews)
  };

  useEffect(() => {
    console.log('start')
    fetchParticipantsList();
    fetchInterviewsList();
    console.log('end')
  });

  const interviewslist = JSON.stringify(interviews)

  console.log('interviewlist: ',interviewslist)

  return (
    <div>
      <h3>All participants</h3>
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Title</th>
            <th>Description</th>
            <th>Is Published</th>
          </tr>
        </thead>
        <tbody>
          {
            interviewslist.map((interview) => {
              return (
                <tr key={interview.id}>
                  <td>{interview.id}</td>
                  <td>{interview.interview_id}</td>
                  <td>
                    {/* <Link to={`/posts/${post.id}`}> */}
                    {interview.participant_id}
                    {/* </Link> */}
                  </td>
                  <td>{interview.created_at}</td>
                  <td>'Yes No'</td>
                </tr>
              )
            })
          }
        </tbody>
      </table>
    </div>
  );
}

export default DetailInterview;
</code>```

Can anybody please help me why this is not working. Because of which I think it is showing
this error:

Uncaught TypeError: interviewslist.map is not a function.

Also this console is printing twice: console.log('interviewlist: ',interviewslist)

答:
You should use interviews not interviewList. You actually stringify interviews to interviewList. So interviewList is basically a string not an array. So Please use interviews.map</p>

```<code>{
      interviews? interviews.map((interview) => {
          return (
            <tr key={interview.id}>
              <td>{interview.id}</td>
              <td>{interview.interview_id}</td>
              <td>
                {/* <Link to={`/posts/${post.id}`}> */}
                {interview.participant_id}
                {/* </Link> */}
              </td>
              <td>{interview.created_at}</td>
              <td>'Yes No'</td>
            </tr>
          )
        }) : null
}
</code>```

Body:
I am using the react hooks but in that useEffect is not working. As in the console start and end are not printing. Also I am using react in rails project.

import PropTypes from 'prop-types';
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';

const DetailInterview = () => {
  const [participants, setparticipants] = useState([])
  const [interviews, setinterviews] = useState([])

  async function fetchParticipantsList() {
    fetch('/api/v1/participants').
      then((response) => response.json()).
      then((participants) => setparticipants({ participants }));
  };

  async function fetchInterviewsList() {
    const { match: { params: { id } } } = this.props;
    fetch(`/api/v1/interviews/${id}`).
      then((response) => response.json()).
      then((interviews) => setinterviews({ interviews }));

    console.log("sa",interviews)
  };

  useEffect(() => {
    console.log('start')
    fetchParticipantsList();
    fetchInterviewsList();
    console.log('end')
  });

  const interviewslist = JSON.stringify(interviews)

  console.log('interviewlist: ',interviewslist)

  return (

All participants

            ID
            Title
            Description
            Is Published

          {
            interviewslist.map((interview) => {
              return (

                  {interview.id}
                  {interview.interview_id}

                    {/* <Link to={`/posts/${post.id}`}> */}
                    {interview.participant_id}
                    {/* </Link> */}

                  {interview.created_at}
                  'Yes No'

              )
            })
          }

  );
}

export default DetailInterview;

Can anybody please help me why this is not working. Because of which I think it is showing
this error:

Uncaught TypeError: interviewslist.map is not a function.

Also this console is printing twice: console.log('interviewlist: ',interviewslist)

Body:
You should use interviews not interviewList. You actually stringify interviews to interviewList. So interviewList is basically a string not an array. So Please use interviews.map

{
      interviews? interviews.map((interview) => {
          return (
            <tr key={interview.id}>
              <td>{interview.id}</td>
              <td>{interview.interview_id}</td>
              <td>
                {/* <Link to={`/posts/${post.id}`}> */}
                {interview.participant_id}
                {/* </Link> */}
              </td>
              <td>{interview.created_at}</td>
              <td>'Yes No'</td>
            </tr>
          )
        }) : null
}


问:
printing array not working
hello everyone i am printing array from the database in the following format

```<code>Array ( [0] => 14
        [task_id] => 14
        [1] => 123
        [user_id] => 123
        [2] => 456
        [employee_id] => 456
        [3] => 2
        [service_id] => 2
        [4] => 2:00 AM
        [starttime] => 2:00 AM
        [5] => 4:00 AM
        [endtime] => 4:00 AM
        [6] => se a
        [servicename] => se a
        [7] => ddsdsd
        [servicedescription] => ddsdsd
        [8] => dsd
        [employeename] => dsd
        [9] => pictures/noimage.gif
        [employeepicture] => pictures/noimage.gif
        [10] => pictures/noimage.gif
        [pic_path] => pictures/noimage.gif )
</code>```

It is the result of

```<code>$rd = $this->executeQuery();
$recordsArray = array();
while (($row = mysqli_fetch_array($rd)) ){
$recordsArray[] = $row;
</code>```

problem is how can i pick the single record from it like this

```<code>echo $row[$task_id]; // not working
</code>```

Thanks

答:
```<code>echo $row['task_id'];
</code>```

maybe it's a syntax error?

Title: printing array not working

Body:
hello everyone i am printing array from the database in the following format

Array ( [0] => 14
        [task_id] => 14
        [1] => 123
        [user_id] => 123
        [2] => 456
        [employee_id] => 456
        [3] => 2
        [service_id] => 2
        [4] => 2:00 AM
        [starttime] => 2:00 AM
        [5] => 4:00 AM
        [endtime] => 4:00 AM
        [6] => se a
        [servicename] => se a
        [7] => ddsdsd
        [servicedescription] => ddsdsd
        [8] => dsd
        [employeename] => dsd
        [9] => pictures/noimage.gif
        [employeepicture] => pictures/noimage.gif
        [10] => pictures/noimage.gif
        [pic_path] => pictures/noimage.gif )

It is the result of

$rd = $this->executeQuery();
$recordsArray = array();
while (($row = mysqli_fetch_array($rd)) ){
$recordsArray[] = $row;

problem is how can i pick the single record from it like this

echo $row[$task_id]; // not working

Thanks

Body:
echo $row['task_id'];

maybe it's a syntax error?


问:
How to change axis tick label spacing on python graph?
I have the following formula:

```<code>import matplotlib.pyplot as plt
import mplleaflet
import pandas as pd
import numpy as np

ax = plt.gca()
datamax.plot(kind='line',x='Date',y='Data_Value',color='red',ax=ax)
datamin.plot(kind='line',x='Date',y='Data_Value', color='blue',ax=ax)
plt.ylabel("Temperature (degrees C)",color='navy')
plt.xlabel("Date",color='navy')
plt.title('Record high and low temperatures by day (2005-2014)', alpha=1.0,color='brown')
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15),
          fancybox=False,labels=['Record high','Record low'])
#ax.set_xticks(ax.get_xticks()[::2])
plt.show()
</code>```

However, I want to change the spacing of the tick labels so that either all of the tick labels are on the X-axis (they are currently too crammed and overlapping!).

Another possibility would be to display only each year on the X-axis (2005-2014, thus with 10 axis labels).

My output currently looks like this:

The dataframe datamax looks like this:

```<code>  Date           ID Element  Data_Value
0     2005-01-01  USW00094889    TMAX         156
1     2005-01-02  USW00094889    TMAX         139
2     2005-01-03  USW00094889    TMAX         133
3     2005-01-04  USW00094889    TMAX          39
4     2005-01-05  USW00094889    TMAX          33
5     2005-01-06  USW00094889    TMAX           0
6     2005-01-07  USW00094889    TMAX           6
7     2005-01-08  USW00094889    TMAX          17
8     2005-01-09  USW00094889    TMAX          28
9     2005-01-10  USW00094889    TMAX          44
10    2005-01-11  USW00094889    TMAX          44
11    2005-01-12  USW00094889    TMAX         139
12    2005-01-13  USW00094889    TMAX         161
13    2005-01-14  USW00094889    TMAX         150
14    2005-01-15  USW00094889    TMAX         -33
15    2005-01-16  USW00094889    TMAX         -33
16    2005-01-17  USW00094889    TMAX         -50
17    2005-01-18  USW00094889    TMAX         -33
18    2005-01-19  USW00094889    TMAX          11
19    2005-01-20  USW00094889    TMAX          11
20    2005-01-21  USW00094889    TMAX         -39
21    2005-01-22  USW00094889    TMAX         -72
22    2005-01-23  USW00094889    TMAX         -44
23    2005-01-24  USW00094889    TMAX          11
24    2005-01-25  USW00094889    TMAX          28
25    2005-01-26  USW00094889    TMAX          28
26    2005-01-27  USW00094889    TMAX           6
27    2005-01-28  USW00094889    TMAX         -11
28    2005-01-29  USW00094889    TMAX          17
29    2005-01-30  USW00094889    TMAX          28
...          ...          ...     ...         ...
3603  2014-11-13  USW00094889    TMAX          39
3604  2014-11-14  USW00094889    TMAX          33
3605  2014-11-15  USW00094889    TMAX          28
3606  2014-11-16  USW00094889    TMAX          28
3607  2014-11-17  USW00094889    TMAX          17
3608  2014-11-18  USW00094889    TMAX          11
3609  2014-11-19  USW00094889    TMAX          11
3610  2014-11-20  USW00094889    TMAX           6
3611  2014-11-21  USW00094889    TMAX         -10
3612  2014-11-22  USW00094889    TMAX         106
3613  2014-11-23  USW00094889    TMAX         156
3614  2014-11-24  USW00094889    TMAX         172
3615  2014-11-25  USW00094889    TMAX         172
3616  2014-11-26  USW00094889    TMAX          28
3617  2014-11-27  USW00094889    TMAX          39
3618  2014-11-28  USW00094889    TMAX          22
3619  2014-11-29  USW00094889    TMAX         117
3620  2014-11-30  USW00094889    TMAX         178
3621  2014-12-01  USW00094889    TMAX         172
3622  2014-12-02  USW00094889    TMAX          33
3623  2014-12-03  USW00094889    TMAX          61
3624  2014-12-04  USW00094889    TMAX          50
3625  2014-12-05  USW00094889    TMAX          50
3626  2014-12-06  USW00094889    TMAX          67
3627  2014-12-07  USW00094889    TMAX          67
3628  2014-12-08  USW00094889    TMAX          72
3629  2014-12-09  USW00094889    TMAX          56
3630  2014-12-10  USW00094889    TMAX          50
3631  2014-12-11  USW00094889    TMAX          61
3632  2014-12-12  USW00094889    TMAX          50

[3631 rows x 4 columns]
</code>```

And the dataframe datamin like this:

```<code>     Date           ID Element  Data_Value
0     2005-01-01  USC00200032    TMIN         -56
1     2005-01-02  USC00200032    TMIN         -56
2     2005-01-03  USC00200032    TMIN           0
3     2005-01-04  USC00200032    TMIN         -39
4     2005-01-05  USC00200032    TMIN         -94
5     2005-01-06  USC00200032    TMIN        -106
6     2005-01-07  USC00200032    TMIN        -111
7     2005-01-08  USC00200032    TMIN        -100
8     2005-01-09  USC00200032    TMIN         -67
9     2005-01-10  USC00200032    TMIN         -56
10    2005-01-11  USC00200032    TMIN         -22
11    2005-01-12  USC00200032    TMIN         -17
12    2005-01-13  USC00200032    TMIN         -83
13    2005-01-14  USC00200032    TMIN        -128
14    2005-01-15  USC00200032    TMIN        -144
15    2005-01-16  USC00200032    TMIN        -150
16    2005-01-17  USC00200032    TMIN        -189
17    2005-01-18  USC00200032    TMIN        -217
18    2005-01-19  USC00200228    TMIN        -300
19    2005-01-20  USC00200032    TMIN        -156
20    2005-01-21  USC00200032    TMIN        -178
21    2005-01-22  USC00200032    TMIN        -178
22    2005-01-23  USC00200032    TMIN        -250
23    2005-01-24  USC00200032    TMIN        -267
24    2005-01-25  USC00200032    TMIN        -228
25    2005-01-26  USC00200032    TMIN        -206
26    2005-01-27  USC00200032    TMIN        -239
27    2005-01-28  USC00200032    TMIN        -250
28    2005-01-29  USC00200032    TMIN        -222
29    2005-01-30  USC00200228    TMIN        -217
...          ...          ...     ...         ...
3603  2014-11-13  USC00200032    TMIN         -71
3604  2014-11-14  USC00200032    TMIN         -78
3605  2014-11-15  USC00200032    TMIN         -94
3606  2014-11-16  USC00200032    TMIN         -72
3607  2014-11-17  USC00200032    TMIN        -106
3608  2014-11-18  USC00200032    TMIN        -144
3609  2014-11-19  USC00200032    TMIN        -128
3610  2014-11-20  USC00200032    TMIN        -122
3611  2014-11-21  USC00200032    TMIN        -182
3612  2014-11-22  USC00200032    TMIN        -172
3613  2014-11-23  USC00200032    TMIN        -100
3614  2014-11-24  USC00200032    TMIN          -5
3615  2014-11-25  USC00200032    TMIN         -33
3616  2014-11-26  USC00200032    TMIN         -67
3617  2014-11-27  USC00200032    TMIN         -82
3618  2014-11-28  USC00200032    TMIN        -133
3619  2014-11-29  USC00200032    TMIN        -106
3620  2014-11-30  USC00200032    TMIN         -56
3621  2014-12-01  USC00200032    TMIN         -88
3622  2014-12-02  USC00200032    TMIN         -99
3623  2014-12-03  USC00200032    TMIN         -71
3624  2014-12-04  USC00200032    TMIN         -77
3625  2014-12-05  USC00200032    TMIN         -61
3626  2014-12-06  USC00200032    TMIN         -50
3627  2014-12-07  USC00200032    TMIN         -78
3628  2014-12-08  USC00200032    TMIN         -78
3629  2014-12-09  USC00200032    TMIN         -39
3630  2014-12-10  USC00200032    TMIN         -72
3631  2014-12-11  USC00200032    TMIN         -88
3632  2014-12-12  USC00200032    TMIN         -78

[3631 rows x 4 columns]
</code>```

答:
Few options to solve your issue including those you mentioned:

```<code>x = np.arange(0, 10,0.555)
y = np.sin(x)
plt.xticks(x, x)
plt.plot(x,y)
</code>```

1) display only a fraction of each xtick (for instance only year in your case)

```<code>plt.figure()
plt.plot(x,y)
short_xticks = [f'{i:.1f}' for i in x]
plt.xticks(x, short_xticks)
</code>```

2) make a wider figure (display all the ticks labels)

```<code>fig, ax = plt.subplots(figsize=(15,5))
plt.xticks(x)
plt.plot(x,y)
</code>```

3) rotate the xticks by 90 degrees

```<code>plt.figure()
plt.xticks(x, rotation=90)
plt.plot(x,y)
</code>```

4) take one every n xtick (here n=2)

```<code>plt.figure()
plt.xticks(x[::2])
plt.plot(x,y)
</code>```

plt.show()

Body:
I have the following formula:

import matplotlib.pyplot as plt
import mplleaflet
import pandas as pd
import numpy as np

ax = plt.gca()
datamax.plot(kind='line',x='Date',y='Data_Value',color='red',ax=ax)
datamin.plot(kind='line',x='Date',y='Data_Value', color='blue',ax=ax)
plt.ylabel("Temperature (degrees C)",color='navy')
plt.xlabel("Date",color='navy')
plt.title('Record high and low temperatures by day (2005-2014)', alpha=1.0,color='brown')
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15),
          fancybox=False,labels=['Record high','Record low'])
#ax.set_xticks(ax.get_xticks()[::2])
plt.show()

However, I want to change the spacing of the tick labels so that either all of the tick labels are on the X-axis (they are currently too crammed and overlapping!).

Another possibility would be to display only each year on the X-axis (2005-2014, thus with 10 axis labels).

My output currently looks like this:

The dataframe datamax looks like this:

  Date           ID Element  Data_Value
0     2005-01-01  USW00094889    TMAX         156
1     2005-01-02  USW00094889    TMAX         139
2     2005-01-03  USW00094889    TMAX         133
3     2005-01-04  USW00094889    TMAX          39
4     2005-01-05  USW00094889    TMAX          33
5     2005-01-06  USW00094889    TMAX           0
6     2005-01-07  USW00094889    TMAX           6
7     2005-01-08  USW00094889    TMAX          17
8     2005-01-09  USW00094889    TMAX          28
9     2005-01-10  USW00094889    TMAX          44
10    2005-01-11  USW00094889    TMAX          44
11    2005-01-12  USW00094889    TMAX         139
12    2005-01-13  USW00094889    TMAX         161
13    2005-01-14  USW00094889    TMAX         150
14    2005-01-15  USW00094889    TMAX         -33
15    2005-01-16  USW00094889    TMAX         -33
16    2005-01-17  USW00094889    TMAX         -50
17    2005-01-18  USW00094889    TMAX         -33
18    2005-01-19  USW00094889    TMAX          11
19    2005-01-20  USW00094889    TMAX          11
20    2005-01-21  USW00094889    TMAX         -39
21    2005-01-22  USW00094889    TMAX         -72
22    2005-01-23  USW00094889    TMAX         -44
23    2005-01-24  USW00094889    TMAX          11
24    2005-01-25  USW00094889    TMAX          28
25    2005-01-26  USW00094889    TMAX          28
26    2005-01-27  USW00094889    TMAX           6
27    2005-01-28  USW00094889    TMAX         -11
28    2005-01-29  USW00094889    TMAX          17
29    2005-01-30  USW00094889    TMAX          28
...          ...          ...     ...         ...
3603  2014-11-13  USW00094889    TMAX          39
3604  2014-11-14  USW00094889    TMAX          33
3605  2014-11-15  USW00094889    TMAX          28
3606  2014-11-16  USW00094889    TMAX          28
3607  2014-11-17  USW00094889    TMAX          17
3608  2014-11-18  USW00094889    TMAX          11
3609  2014-11-19  USW00094889    TMAX          11
3610  2014-11-20  USW00094889    TMAX           6
3611  2014-11-21  USW00094889    TMAX         -10
3612  2014-11-22  USW00094889    TMAX         106
3613  2014-11-23  USW00094889    TMAX         156
3614  2014-11-24  USW00094889    TMAX         172
3615  2014-11-25  USW00094889    TMAX         172
3616  2014-11-26  USW00094889    TMAX          28
3617  2014-11-27  USW00094889    TMAX          39
3618  2014-11-28  USW00094889    TMAX          22
3619  2014-11-29  USW00094889    TMAX         117
3620  2014-11-30  USW00094889    TMAX         178
3621  2014-12-01  USW00094889    TMAX         172
3622  2014-12-02  USW00094889    TMAX          33
3623  2014-12-03  USW00094889    TMAX          61
3624  2014-12-04  USW00094889    TMAX          50
3625  2014-12-05  USW00094889    TMAX          50
3626  2014-12-06  USW00094889    TMAX          67
3627  2014-12-07  USW00094889    TMAX          67
3628  2014-12-08  USW00094889    TMAX          72
3629  2014-12-09  USW00094889    TMAX          56
3630  2014-12-10  USW00094889    TMAX          50
3631  2014-12-11  USW00094889    TMAX          61
3632  2014-12-12  USW00094889    TMAX          50

[3631 rows x 4 columns]

And the dataframe datamin like this:

     Date           ID Element  Data_Value
0     2005-01-01  USC00200032    TMIN         -56
1     2005-01-02  USC00200032    TMIN         -56
2     2005-01-03  USC00200032    TMIN           0
3     2005-01-04  USC00200032    TMIN         -39
4     2005-01-05  USC00200032    TMIN         -94
5     2005-01-06  USC00200032    TMIN        -106
6     2005-01-07  USC00200032    TMIN        -111
7     2005-01-08  USC00200032    TMIN        -100
8     2005-01-09  USC00200032    TMIN         -67
9     2005-01-10  USC00200032    TMIN         -56
10    2005-01-11  USC00200032    TMIN         -22
11    2005-01-12  USC00200032    TMIN         -17
12    2005-01-13  USC00200032    TMIN         -83
13    2005-01-14  USC00200032    TMIN        -128
14    2005-01-15  USC00200032    TMIN        -144
15    2005-01-16  USC00200032    TMIN        -150
16    2005-01-17  USC00200032    TMIN        -189
17    2005-01-18  USC00200032    TMIN        -217
18    2005-01-19  USC00200228    TMIN        -300
19    2005-01-20  USC00200032    TMIN        -156
20    2005-01-21  USC00200032    TMIN        -178
21    2005-01-22  USC00200032    TMIN        -178
22    2005-01-23  USC00200032    TMIN        -250
23    2005-01-24  USC00200032    TMIN        -267
24    2005-01-25  USC00200032    TMIN        -228
25    2005-01-26  USC00200032    TMIN        -206
26    2005-01-27  USC00200032    TMIN        -239
27    2005-01-28  USC00200032    TMIN        -250
28    2005-01-29  USC00200032    TMIN        -222
29    2005-01-30  USC00200228    TMIN        -217
...          ...          ...     ...         ...
3603  2014-11-13  USC00200032    TMIN         -71
3604  2014-11-14  USC00200032    TMIN         -78
3605  2014-11-15  USC00200032    TMIN         -94
3606  2014-11-16  USC00200032    TMIN         -72
3607  2014-11-17  USC00200032    TMIN        -106
3608  2014-11-18  USC00200032    TMIN        -144
3609  2014-11-19  USC00200032    TMIN        -128
3610  2014-11-20  USC00200032    TMIN        -122
3611  2014-11-21  USC00200032    TMIN        -182
3612  2014-11-22  USC00200032    TMIN        -172
3613  2014-11-23  USC00200032    TMIN        -100
3614  2014-11-24  USC00200032    TMIN          -5
3615  2014-11-25  USC00200032    TMIN         -33
3616  2014-11-26  USC00200032    TMIN         -67
3617  2014-11-27  USC00200032    TMIN         -82
3618  2014-11-28  USC00200032    TMIN        -133
3619  2014-11-29  USC00200032    TMIN        -106
3620  2014-11-30  USC00200032    TMIN         -56
3621  2014-12-01  USC00200032    TMIN         -88
3622  2014-12-02  USC00200032    TMIN         -99
3623  2014-12-03  USC00200032    TMIN         -71
3624  2014-12-04  USC00200032    TMIN         -77
3625  2014-12-05  USC00200032    TMIN         -61
3626  2014-12-06  USC00200032    TMIN         -50
3627  2014-12-07  USC00200032    TMIN         -78
3628  2014-12-08  USC00200032    TMIN         -78
3629  2014-12-09  USC00200032    TMIN         -39
3630  2014-12-10  USC00200032    TMIN         -72
3631  2014-12-11  USC00200032    TMIN         -88
3632  2014-12-12  USC00200032    TMIN         -78

[3631 rows x 4 columns]

Body:
Few options to solve your issue including those you mentioned:

x = np.arange(0, 10,0.555)
y = np.sin(x)
plt.xticks(x, x)
plt.plot(x,y)

1) display only a fraction of each xtick (for instance only year in your case)

plt.figure()
plt.plot(x,y)
short_xticks = [f'{i:.1f}' for i in x]
plt.xticks(x, short_xticks)

2) make a wider figure (display all the ticks labels)

fig, ax = plt.subplots(figsize=(15,5))
plt.xticks(x)
plt.plot(x,y)

3) rotate the xticks by 90 degrees

plt.figure()
plt.xticks(x, rotation=90)
plt.plot(x,y)

4) take one every n xtick (here n=2)

plt.figure()
plt.xticks(x[::2])
plt.plot(x,y)

plt.show()


问:
"ignoring potentially dangerous server-supplied filename" in pscp
I want to copy some file from a remote Linux system to my Windows PC using pscp (from PuTTY). I wrote a small script that should copy all .png files in a directory on my server:

```<code>pscp -unsafe root@169.60.147.[redacted]:/root/pytorch-CycleGAN-and-pix2pix/results/summer2winter_yosemite_cyclegan/test_latest/images/*.png C:\files\tests\images
</code>```

I'm using the -unsafe option because whenever I run this command, I get this output:

```<code>ignoring potentially dangerous server-supplied filename '2011-05-29 10:20:21_rec_A.png'
ignoring potentially dangerous server-supplied filename '2011-07-06 16:55:20_real_B.png'
..
ignoring potentially dangerous server-supplied filename '2011-08-30 23:13:10_real_A.png'
pscp: wildcard '*.png' matched no files
</code>```

However, when I use the -unsafe option the command will still output those same results. Here is some documentation on pscp that I read over thoroughly, to no avail. Anyone have any ideas?

答:
-unsafe won't help with this.

The problem is that your file names contain colons. Colons are not allowed in Windows file names.

Body:
I want to copy some file from a remote Linux system to my Windows PC using pscp (from PuTTY). I wrote a small script that should copy all .png files in a directory on my server:

pscp -unsafe root@169.60.147.[redacted]:/root/pytorch-CycleGAN-and-pix2pix/results/summer2winter_yosemite_cyclegan/test_latest/images/*.png C:\files\tests\images

I'm using the -unsafe option because whenever I run this command, I get this output:

ignoring potentially dangerous server-supplied filename '2011-05-29 10:20:21_rec_A.png'
ignoring potentially dangerous server-supplied filename '2011-07-06 16:55:20_real_B.png'
..
ignoring potentially dangerous server-supplied filename '2011-08-30 23:13:10_real_A.png'
pscp: wildcard '*.png' matched no files

However, when I use the -unsafe option the command will still output those same results. Here is some documentation on pscp that I read over thoroughly, to no avail. Anyone have any ideas?


问:
How to debug Rust in Intellij idea?
I have searched for rust debugging and found guides for vs code only. My question is how to configure intellij rust for debugging?</p>

答:
Old question, but great news! https://blog.jetbrains.com/clion/2020/05/whats-new-in-intellij-rust/
Now it's VERY easy to debug Rust in IntelliJ, just download mentioned plugin and the rest is done before first usage.</p>

Title: How to debug Rust in Intellij idea?


问:
Bootstrap collapse not collapsing element
I just implement the code of collapse from w3schools (light code than the bootstrap website .. I've tried this one also) and the collapse element isn't displayed

I'm using angular 9, bootstrap 4 and I've installed JQuery

here is the code :

```<code><p>
    <button class="btn btn-info m-3" type="button">Add Invoice</button>
    <button class="btn btn-primary m-3" type="button" data-toggle="collapse" data-target="#searchBloc">
         Search
    </button>
</p>
<div class="collapse" id="searchBloc">
    <div class="card card-body">
           Search Form
    </div>
</div>
</code>```

i've add the jquery cdn in my index.html :

```<code><script src="https://code.jquery.com/jquery-3.5.1.min.js"
         integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
         crossorigin="anonymous">
</script>
</code>```

答:
The simplest answer is that you have to wrap all the content in same div.

All the content includes

1) The content which you are going to click

2) the content you want to display when button click

They both have to be wrap in same div

You have to include the bootstrap js also in order to make it work!

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

    <button class="btn btn-info m-3" type="button">Add Invoice</button>
    <button class="btn btn-primary m-3" type="button" data-toggle="collapse" data-target="#searchBloc">
      Search
    </button>

      Search Form

```

Body:
I just implement the code of collapse from w3schools (light code than the bootstrap website .. I've tried this one also) and the collapse element isn't displayed

I'm using angular 9, bootstrap 4 and I've installed JQuery

here is the code :

    <button class="btn btn-info m-3" type="button">Add Invoice</button>
    <button class="btn btn-primary m-3" type="button" data-toggle="collapse" data-target="#searchBloc">
         Search
    </button>

           Search Form

i've add the jquery cdn in my index.html :

Body:
The simplest answer is that you have to wrap all the content in same div.

All the content includes

1) The content which you are going to click

2) the content you want to display when button click

They both have to be wrap in same div

You have to include the bootstrap js also in order to make it work!

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous">
</script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous">
</script>

<div>
  <p>
    <button class="btn btn-info m-3" type="button">Add Invoice</button>
    <button class="btn btn-primary m-3" type="button" data-toggle="collapse" data-target="#searchBloc">
      Search
    </button>
  </p>
  <div class="collapse" id="searchBloc">
    <div class="card card-body">
      Search Form
    </div>
  </div>
</div>


问:
How can I make two components communicate in React?
I have just started using React and I am struggling to figure out how to make 2 components communicate between each other to exchange data. For example, I am trying to build a calculator which has component buttons with their values and component input field which is supposed to display the value of the buttons. I think I can figure out how to write the code, but I am strugging to understand, how to make them know about each other?
Thank you!</p>

答:
You can do that via 2 ways

1 - props to communicate between them

```<code>class Calculator extends React.Component {
    this.state ={
    num1:1,
    num2:2
    }
  render() {
    return <Sum num1={this.state.num1} num2={this.state.num2}>;
  }
}

const sum =(props)=>{
    return (
      <div>
     {props.num1+props.num2}
      </div>
    );
}
</code>```

2 - You can use any State management solution for react (but only if its a complex app)

Body:
You can do that via 2 ways

1 - props to communicate between them

class Calculator extends React.Component {
    this.state ={
    num1:1,
    num2:2
    }
  render() {
    return <Sum num1={this.state.num1} num2={this.state.num2}>;
  }
}

const sum =(props)=>{
    return (
      <div>
     {props.num1+props.num2}
      </div>
    );
}

2 - You can use any State management solution for react (but only if its a complex app)


问:
How to change outliers to some other colors in a scatter plot
If I have a scatter plot like this

I was wondering is there any way to change the obvious outliers, like the three on the top, to some other colors in the same plot?

答:
ImportanceOfBeingErnest has a great answer. Here's a one-liner I use if I have an array corresponding to enum categories for the data points (especially useful when visualizing data pre divided into classes).

```<code>import numpy as np
import matplotlib.pyplot as plt

num = 1000
x= np.random.rand(1,100)
y= np.random.rand(1,100)*2

# Creating a simple data point classification criteria, classes in this case will be 0, 1 and 2
classes = np.round(y)

# Passing in the classes for the "c" argument is super convinient
plt.scatter(x,y, c=classes,cmap=plt.cm.Set1)
plt.show()
</code>```

Corresponding scatter plot that divides the graph into 3 colored regions:

Body:
ImportanceOfBeingErnest has a great answer. Here's a one-liner I use if I have an array corresponding to enum categories for the data points (especially useful when visualizing data pre divided into classes).

import numpy as np
import matplotlib.pyplot as plt

num = 1000
x= np.random.rand(1,100)
y= np.random.rand(1,100)*2

# Creating a simple data point classification criteria, classes in this case will be 0, 1 and 2
classes = np.round(y)

# Passing in the classes for the "c" argument is super convinient
plt.scatter(x,y, c=classes,cmap=plt.cm.Set1)
plt.show()

Corresponding scatter plot that divides the graph into 3 colored regions:


问:
Fastest way to whitelist list of words by another set keeping words order
I have list of words like words = ['a', 'spam', 'an', 'eggs', 'the', 'foo', 'and', 'bar'].

And I want to exclude some words (stop-words) defined in another list or set stop_words = ['a', 'an', 'the', 'and'].

What is the fastest way to do that and also keeping the order of original list? I tried to use set() or even SortedSet(). But it still doesn't help, words are still different from original order.

r1 = set(words) - set(stop_words)
r2 = SortedSet(words) - SortedSet(stop_words)
```

<p>Tried iterating one by one, but not sure if it will be quick enough on big lists.</p>

<pre class="lang-py prettyprint-override"><code>r3 = [w for w in words if w not in stop_words]
</code>```

答:
You can use a set for stop_words and then walk though the original list:

```<code>stop_words = set(stop_words)
result = [w for w in words if w not in stop_words]
</code>```

Body:
I have list of words like words = ['a', 'spam', 'an', 'eggs', 'the', 'foo', 'and', 'bar'].

And I want to exclude some words (stop-words) defined in another list or set stop_words = ['a', 'an', 'the', 'and'].

What is the fastest way to do that and also keeping the order of original list? I tried to use set() or even SortedSet(). But it still doesn't help, words are still different from original order.

r1 = set(words) - set(stop_words)
r2 = SortedSet(words) - SortedSet(stop_words)

Tried iterating one by one, but not sure if it will be quick enough on big lists.

r3 = [w for w in words if w not in stop_words]

Body:
You can use a set for stop_words and then walk though the original list:

stop_words = set(stop_words)
result = [w for w in words if w not in stop_words]


问:
How to make content available for premium React Native
on my react-native app I would like to have premium content for people who paid a subscription.

My issue is how I make the content to display as unavailable(if you are not premium ) and the same as the other content if you are premium. Basically I would like the premium content to be displayed with a "lock overlay" on it for non-premium users.

However, I do not know how I set this conditional. It is a matter of state? If yes where should be positioned this state considering that is unidirectional?

Just to be clear I will have premium and non premium content

答:
I had the same trouble in a project, i was should show a screen if user was supervisor, and show another screen if wasn't supervisor.

I used react-dynamic-import, basically i split my main project in 3 parts:

Employee's Screen - The screen with access and components if user wasn't supervisor.

Supervisor's Screen - The screen with access and components if user was supervisor.

Default screen - The screen that would appear regardless of whether the user is a supervisor or not, and pull with react-dynamic-import your must screen, if user was supervisor i pull Supervisor's Screen, if wasn't supervisor, pull Employee's Screen

You can save a hash in cookie session and read this cookie in JS and validate with REST API, and the return of REST API is the path where are the component Premium, like that:

// getting hash from cookie
const userHash = document.cookie.replace(/^.*;?user-hash=([^;]+);?.*$/, '$1');

// generate api LINK with
const apiLink = `/API/V1.0/checkuser?hash=${encodeURI(hash)}`;

/* getting value where are path is premium or isn't premium, in my case i'am using Ajax Request and my API returns a JSON like :
{"path": "pathWhereAreComponentPremium"}
*/
const pathComponent = (await $.get(apiLink)).path;

const loader = () => import(pathComponent);

// Load component dynamically
var Component = ReactDynamicImport({loader});

// ...

```

<p>In <code>Component</code> are the component if user are or aren't premium.</p>

<p><strong>Edit 1:</strong>
Forgive my english, i'am brazilian, and i'm learning.</p>

<p><strong>Edit 2:</strong></p>

<p>If you want just render a component by conditional analises, you can do this:</p>

<pre class="lang-js prettyprint-override"><code>const App = (props) => {

    const [isPremium, setPremium] = React.useState(false);

    const handleButtonPremium = () => (setPremium(!isPremium));

    return (<>
        <div>
            T-Shirt
            {isPremium ? <button>Get</button> : <button>Buy $1.5</button>}
        </div>
        <button onClick={handleButtonPremium}>
            {isPremium ? "Cancel Premium assign" : "Get Premium assign"}
        </button>
    </>)
}
</code>```

See more here

Body:
I had the same trouble in a project, i was should show a screen if user was supervisor, and show another screen if wasn't supervisor.

I used react-dynamic-import, basically i split my main project in 3 parts:

Employee's Screen - The screen with access and components if user wasn't supervisor.

Supervisor's Screen - The screen with access and components if user was supervisor.

Default screen - The screen that would appear regardless of whether the user is a supervisor or not, and pull with react-dynamic-import your must screen, if user was supervisor i pull Supervisor's Screen, if wasn't supervisor, pull Employee's Screen

You can save a hash in cookie session and read this cookie in JS and validate with REST API, and the return of REST API is the path where are the component Premium, like that:

// getting hash from cookie
const userHash = document.cookie.replace(/^.*;?user-hash=([^;]+);?.*$/, '$1');

// generate api LINK with
const apiLink = `/API/V1.0/checkuser?hash=${encodeURI(hash)}`;

/* getting value where are path is premium or isn't premium, in my case i'am using Ajax Request and my API returns a JSON like :
{"path": "pathWhereAreComponentPremium"}
*/
const pathComponent = (await $.get(apiLink)).path;

const loader = () => import(pathComponent);

// Load component dynamically
var Component = ReactDynamicImport({loader});

// ...

In Component are the component if user are or aren't premium.

Edit 1:
Forgive my english, i'am brazilian, and i'm learning.

Edit 2:

If you want just render a component by conditional analises, you can do this:

const App = (props) => {

    const [isPremium, setPremium] = React.useState(false);

    const handleButtonPremium = () => (setPremium(!isPremium));

    return (<>
        <div>
            T-Shirt
            {isPremium ? <button>Get</button> : <button>Buy $1.5</button>}
        </div>
        <button onClick={handleButtonPremium}>
            {isPremium ? "Cancel Premium assign" : "Get Premium assign"}
        </button>
    </>)
}

See more here


问:
how xdp ebpf change checksum tcphdr after update dest port
how xdp ebpf change checksum tcphdr after update dest port ?

// Check tcp header size
struct tcphdr *tcph = data + nh_off;
nh_off += sizeof(struct tcphdr);
if (data + nh_off > data_end) {
    return XDP_PASS;
}
tcph->dest = bpf_ntohs(5555);
// ... i'm trying change checksum of tcphdr, it's not work for me.
tcph->check = 0;
tcph->check = checksum((unsigned short *)tcph, sizeof(struct tcphdr));

return XDP_TX;
```

<p>this is the function code with which i am trying to change the checksum of a tcp packet</p>

<pre class="lang-c prettyprint-override"><code>static inline unsigned short checksum(unsigned short *buf, int bufsz) {
    unsigned long sum = 0;

    while (bufsz > 1) {
        sum += *buf;
        buf++;
        bufsz -= 2;
    }

    if (bufsz == 1) {
        sum += *(unsigned char *)buf;
    }

    sum = (sum & 0xffff) + (sum >> 16);
    sum = (sum & 0xffff) + (sum >> 16);

    return ~sum;
}
</code>```

I load an xdp program for the lo interface, and I want to proxy the packet to port 5555 in the same network interface.

答:
Unless you're working with hardware offload, you probably want to use the relevant BPF helper bpf_l4_csum_replace() (or alternatively bpf_csum_diff()).

```<code> * int bpf_l4_csum_replace(struct sk_buff *skb, u32 offset, u64 from, u64 to, u64 flags)
 *  Description
 *      Recompute the layer 4 (e.g. TCP, UDP or ICMP) checksum for the
 *      packet associated to *skb*. Computation is incremental, so the
 *      helper must know the former value of the header field that was
 *      modified (*from*), the new value of this field (*to*), and the
 *      number of bytes (2 or 4) for this field, stored on the lowest
 *      four bits of *flags*. Alternatively, it is possible to store
 *      the difference between the previous and the new values of the
 *      header field in *to*, by setting *from* and the four lowest
 *      bits of *flags* to 0. For both methods, *offset* indicates the
 *      location of the IP checksum within the packet. In addition to
 *      the size of the field, *flags* can be added (bitwise OR) actual
 *      flags. With **BPF_F_MARK_MANGLED_0**, a null checksum is left
 *      untouched (unless **BPF_F_MARK_ENFORCE** is added as well), and
 *      for updates resulting in a null checksum the value is set to
 *      **CSUM_MANGLED_0** instead. Flag **BPF_F_PSEUDO_HDR** indicates
 *      the checksum is to be computed against a pseudo-header.
 *
 *      This helper works in combination with **bpf_csum_diff**\ (),
 *      which does not update the checksum in-place, but offers more
 *      flexibility and can handle sizes larger than 2 or 4 for the
 *      checksum to update.
 *
 *      A call to this helper is susceptible to change the underlying
 *      packet buffer. Therefore, at load time, all checks on pointers
 *      previously done by the verifier are invalidated and must be
 *      performed again, if the helper is used in combination with
 *      direct packet access.
 *  Return
 *      0 on success, or a negative error in case of failure.
</code>```

The kernel samples or Cilium display some example usage.

If you cannot use it, there is an eBPF implementation from Netronome available here that might help you.

Body:
how xdp ebpf change checksum tcphdr after update dest port ?

// Check tcp header size
struct tcphdr *tcph = data + nh_off;
nh_off += sizeof(struct tcphdr);
if (data + nh_off > data_end) {
    return XDP_PASS;
}
tcph->dest = bpf_ntohs(5555);
// ... i'm trying change checksum of tcphdr, it's not work for me.
tcph->check = 0;
tcph->check = checksum((unsigned short *)tcph, sizeof(struct tcphdr));

return XDP_TX;

this is the function code with which i am trying to change the checksum of a tcp packet

static inline unsigned short checksum(unsigned short *buf, int bufsz) {
    unsigned long sum = 0;

    while (bufsz > 1) {
        sum += *buf;
        buf++;
        bufsz -= 2;
    }

    if (bufsz == 1) {
        sum += *(unsigned char *)buf;
    }

    sum = (sum & 0xffff) + (sum >> 16);
    sum = (sum & 0xffff) + (sum >> 16);

    return ~sum;
}

I load an xdp program for the lo interface, and I want to proxy the packet to port 5555 in the same network interface.

Body:
Unless you're working with hardware offload, you probably want to use the relevant BPF helper bpf_l4_csum_replace() (or alternatively bpf_csum_diff()).

 * int bpf_l4_csum_replace(struct sk_buff *skb, u32 offset, u64 from, u64 to, u64 flags)
 *  Description
 *      Recompute the layer 4 (e.g. TCP, UDP or ICMP) checksum for the
 *      packet associated to *skb*. Computation is incremental, so the
 *      helper must know the former value of the header field that was
 *      modified (*from*), the new value of this field (*to*), and the
 *      number of bytes (2 or 4) for this field, stored on the lowest
 *      four bits of *flags*. Alternatively, it is possible to store
 *      the difference between the previous and the new values of the
 *      header field in *to*, by setting *from* and the four lowest
 *      bits of *flags* to 0. For both methods, *offset* indicates the
 *      location of the IP checksum within the packet. In addition to
 *      the size of the field, *flags* can be added (bitwise OR) actual
 *      flags. With **BPF_F_MARK_MANGLED_0**, a null checksum is left
 *      untouched (unless **BPF_F_MARK_ENFORCE** is added as well), and
 *      for updates resulting in a null checksum the value is set to
 *      **CSUM_MANGLED_0** instead. Flag **BPF_F_PSEUDO_HDR** indicates
 *      the checksum is to be computed against a pseudo-header.
 *
 *      This helper works in combination with **bpf_csum_diff**\ (),
 *      which does not update the checksum in-place, but offers more
 *      flexibility and can handle sizes larger than 2 or 4 for the
 *      checksum to update.
 *
 *      A call to this helper is susceptible to change the underlying
 *      packet buffer. Therefore, at load time, all checks on pointers
 *      previously done by the verifier are invalidated and must be
 *      performed again, if the helper is used in combination with
 *      direct packet access.
 *  Return
 *      0 on success, or a negative error in case of failure.

The kernel samples or Cilium display some example usage.

If you cannot use it, there is an eBPF implementation from Netronome available here that might help you.


问:
Object cannot be cast from DBNull to other types : Data Binding
I am getting this error when dynamically binding my controls onto the dataSource.
(Most answers respond to when using parameters : like this one Object cannot be cast from DBNull to other types ).
Can we expand for when binding controls?</p>

答:
Just tried the extensions of the "DataBindings.Add" method: therefore this code:

```<code>            this.chkDispensed.DataBindings.Add("Checked", DT_items, "dispensedItem_bol");
            this.chkDirectionsAuto.DataBindings.Add("Checked", DT_items, "directionsAuto_bol");
</code>```

.. Changes to

```<code>            bool myDefBool = false;
            this.chkDispensed.DataBindings.Add("Checked", DT_items, "dispensedItem_bol", true, DataSourceUpdateMode.OnPropertyChanged, myDefBool);
            this.chkDirectionsAuto.DataBindings.Add("Checked", DT_items, "directionsAuto_bol", true, DataSourceUpdateMode.OnPropertyChanged, myDefBool);
</code>```

This takes care of the NULL values from the database. I suppose it MUST be done for ALL controls, any type. Thank you.

Body:
Just tried the extensions of the "DataBindings.Add" method: therefore this code:

            this.chkDispensed.DataBindings.Add("Checked", DT_items, "dispensedItem_bol");
            this.chkDirectionsAuto.DataBindings.Add("Checked", DT_items, "directionsAuto_bol");

.. Changes to

            bool myDefBool = false;
            this.chkDispensed.DataBindings.Add("Checked", DT_items, "dispensedItem_bol", true, DataSourceUpdateMode.OnPropertyChanged, myDefBool);
            this.chkDirectionsAuto.DataBindings.Add("Checked", DT_items, "directionsAuto_bol", true, DataSourceUpdateMode.OnPropertyChanged, myDefBool);

This takes care of the NULL values from the database. I suppose it MUST be done for ALL controls, any type. Thank you.


问:
is there a way to pass a variable in the byte string b''?
I am trying to pass a variable in the b'' but it always converts the name of the variable in byte.

```<code>    string = 'this is a string'
    print(string)
    string = b'string'
    print(string)

Result:

    this is a string
    b'string'

</code>```

but the result which i want is
b'this is a string'

答:
b'string' is the literal word "string" as bytes, not a variable substitution. You need to encode your variable as bytes separately.

string = 'this is a string'
print(string)
as_bytes = bytes(string, 'utf8')
print(as_bytes)
b'this is a string'
```

Body:
I am trying to pass a variable in the b'' but it always converts the name of the variable in byte.

    string = 'this is a string'
    print(string)
    string = b'string'
    print(string)

Result:

    this is a string
    b'string'

but the result which i want is
b'this is a string'


答:
No performance difference on any modern computer.

The two operators have different meaning though. If the bit is already set, | will do nothing, but + will clear the bit and all the following non-zero bits and set the next zero bit to 1.

Title: Performance of operator| vs operators+

Body:
Is there any major difference between | and + that would affect a code's performance in the long run? or are both O(1)? the code i am working with is something like this:

uint64_t dostuff(uint64_t a,uint64_t b){
        // the max values of the inputs are 2^32 - 1

        // lots of stuff involving boolean operators
        // that have no way of being substituted by
        // arithmetic operators

        return (a << 32) + b;
        //or
        return (a << 32) | b;
}

the code will be used many times, so i want to speed it up as much as possible.


问:
how to give dynamic path to fo:external graphic xsl
The value I am getting for sp_sign(given below) I want to use it as src for fo:external graphic . I tried many things still no luck please help.

```<code>    <xsl:for-each select="//**sp_sign**">
    <xsl:value-of select="**@value**" />
</code>```

//

```<code><xsl:variable name="src" select="//sp_sign" />
<fo:external-graphic baseline-shift="super" **src="${src}"** content-height="80px" content-width="80px"/>
</fo:block>
</code>```

Thanks in advance
Regards,
Manik Vashisht

答:
Just add the variable between braces!

<xsl:variable name="logo" select="LOGO"/>
<fo:block>
  <fo:external-graphic src="{$logo}" />
</fo:block>
```

<p>The result will be:</p>

<pre class="lang-xml prettyprint-override"><code><fo:external-graphic src="https://ibb.co/kqSQ9z3"/>
</code>```

Body:
The value I am getting for sp_sign(given below) I want to use it as src for fo:external graphic . I tried many things still no luck please help.

    <xsl:for-each select="//**sp_sign**">
    <xsl:value-of select="**@value**" />

//

<xsl:variable name="src" select="//sp_sign" />
<fo:external-graphic baseline-shift="super" **src="${src}"** content-height="80px" content-width="80px"/>
</fo:block>

Thanks in advance
Regards,
Manik Vashisht

Body:
Just add the variable between braces!

<xsl:variable name="logo" select="LOGO"/>
<fo:block>
  <fo:external-graphic src="{$logo}" />
</fo:block>

The result will be:

<fo:external-graphic src="https://ibb.co/kqSQ9z3"/>


问:
Sudoku Backtracking with Solution Counter
Background

I've implemented a sudoku-solver algorithm (backtracking) that looks like this:

```<code>//Backtracking-Algorithm
public static boolean solver(int[][] board) {
    for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 9; j++) {
            if (board[i][j] == 0) {
                for (int n = 1; n < 10; n++) {
                    if (checkRow(board, i, n) && checkColumn(board, j, n) && checkBox(board, i, j, n)) {
                        board[i][j] = n;
                        if (!solver(board)) {
                            board[i][j] = 0;
                        } else {
                            return true;
                        }
                    }
                }
                return false;
            }
        }
    }
    return true;
}
</code>```

This solution is working fine (it can solve sudokus).

What I try to achieve

I now want to achieve that the algorithm tells me, whether there is only one solution or more solutions.

What I've tried

I tried to achieve my goal, by changing the return type to an int and count the possible solutions (stops at 2, because if there are two solutions, I can say there are "multiple" solutions). So basically, I just want to know whether there is no, one, or many solution(s):

```<code>// Backtracking-Algorithm
public int solver(int[][] board, int count) { //Starts with count = 0
  if (count < 2) {
    for (int i = 0; i < GRID_SIZE; i++) {
      for (int j = 0; j < GRID_SIZE; j++) {
        /*
         * Only empty fields will be changed
         */
        if (board[i][j] == EMPTY) {
          /*
           * Try all numbers between 1 and 9
           */
          for (int n = 1; n <= GRID_SIZE; n++) {
            /*
             * Is number n safe?
             */
            if (checkRow(board, i, n) && checkColumn(board, j, n) && checkBox(board, i, j, n)) {
              board[i][j] = n;
              if (solver(board, count) > count) {
                count++;
              } else {
                board[i][j] = 0;
              }
            }
          }
          return count;
        }
      }
    }
    return count + 1;
  }
  return count;
}
</code>```

The problem is that count always goes to "1" and then the algorithm stops.

Question

What changes in the code are necessary to make it work?

答:
The issue with your code is that it stops after it finds the first solution - more specifically, your code will never change an assigned value to a cell unless it is wrong. This is standard backtracking that you've implemented. What you need to do is, once you find one solution, you need to force your code to use other values and see if it also returns a valid solution.

Let's say this is the last row of your sudoku (where you're missing the last value), and your count is currently 0 (i.e. no solution so far):

```<code>| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 0 |
</code>```

Your code will try all values from 1-9 for that last cell, and once it finds out that 9 is the correct value, it will fill it in and make a recursive call.

On the recursive call, your code will not find any empty values so it will increment count by 1  (so count is now 1) and return, specifically this line: return count + 1;Because you're not making any further recursive calls at this point, the incremented count will be passed up the recursive stack and and you'll end up with a value of 1.

What you need to do is, once you've found one solution, you need to backtrack again and force increment one of the values. Your last line in the solution you found looks like this:

```<code>| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
</code>```

You cannot increment the last cell because it's already at 9, so you set it to 0 / EMPTY and go to the previous value. The previous value is 8, which can be incremented to 9, so you do that and then solve that board:

```<code>| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | 0 |
</code>```

Maybe this doesn't return a solution, so you go back one more (setting the second last cell to 0 and increment the previous cell:

```<code>| 1 | 2 | 3 | 4 | 5 | 6 | 8 | 0 | 0 |
</code>```

Now see if this gives you a solution. And so on...

TLDR: once you find a solution, you need to feed it back to your code with tighter constraints (i.e. force increment one of the valid values and see if it still gives you another solution).

Body:
Background

I've implemented a sudoku-solver algorithm (backtracking) that looks like this:

//Backtracking-Algorithm
public static boolean solver(int[][] board) {
    for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 9; j++) {
            if (board[i][j] == 0) {
                for (int n = 1; n < 10; n++) {
                    if (checkRow(board, i, n) && checkColumn(board, j, n) && checkBox(board, i, j, n)) {
                        board[i][j] = n;
                        if (!solver(board)) {
                            board[i][j] = 0;
                        } else {
                            return true;
                        }
                    }
                }
                return false;
            }
        }
    }
    return true;
}

This solution is working fine (it can solve sudokus).

What I try to achieve

I now want to achieve that the algorithm tells me, whether there is only one solution or more solutions.

What I've tried

I tried to achieve my goal, by changing the return type to an int and count the possible solutions (stops at 2, because if there are two solutions, I can say there are "multiple" solutions). So basically, I just want to know whether there is no, one, or many solution(s):

// Backtracking-Algorithm
public int solver(int[][] board, int count) { //Starts with count = 0
  if (count < 2) {
    for (int i = 0; i < GRID_SIZE; i++) {
      for (int j = 0; j < GRID_SIZE; j++) {
        /*
         * Only empty fields will be changed
         */
        if (board[i][j] == EMPTY) {
          /*
           * Try all numbers between 1 and 9
           */
          for (int n = 1; n <= GRID_SIZE; n++) {
            /*
             * Is number n safe?
             */
            if (checkRow(board, i, n) && checkColumn(board, j, n) && checkBox(board, i, j, n)) {
              board[i][j] = n;
              if (solver(board, count) > count) {
                count++;
              } else {
                board[i][j] = 0;
              }
            }
          }
          return count;
        }
      }
    }
    return count + 1;
  }
  return count;
}

The problem is that count always goes to "1" and then the algorithm stops.

Question

What changes in the code are necessary to make it work?

Body:
The issue with your code is that it stops after it finds the first solution - more specifically, your code will never change an assigned value to a cell unless it is wrong. This is standard backtracking that you've implemented. What you need to do is, once you find one solution, you need to force your code to use other values and see if it also returns a valid solution.

Let's say this is the last row of your sudoku (where you're missing the last value), and your count is currently 0 (i.e. no solution so far):

| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 0 |

Your code will try all values from 1-9 for that last cell, and once it finds out that 9 is the correct value, it will fill it in and make a recursive call.

On the recursive call, your code will not find any empty values so it will increment count by 1  (so count is now 1) and return, specifically this line: return count + 1;Because you're not making any further recursive calls at this point, the incremented count will be passed up the recursive stack and and you'll end up with a value of 1.

What you need to do is, once you've found one solution, you need to backtrack again and force increment one of the values. Your last line in the solution you found looks like this:

| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |

You cannot increment the last cell because it's already at 9, so you set it to 0 / EMPTY and go to the previous value. The previous value is 8, which can be incremented to 9, so you do that and then solve that board:

| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | 0 |

Maybe this doesn't return a solution, so you go back one more (setting the second last cell to 0 and increment the previous cell:

| 1 | 2 | 3 | 4 | 5 | 6 | 8 | 0 | 0 |

Now see if this gives you a solution. And so on...

TLDR: once you find a solution, you need to feed it back to your code with tighter constraints (i.e. force increment one of the valid values and see if it still gives you another solution).


问:
TypeScript error when I perform addition to a number and pass as a prop?
I have a heading component which takes a level as a prop:

In Heading.tsx

```<code>type Props = {
  level?: 1 | 2 | 3 | 4 | 5 | 6;
  children: string;
};
</code>```

My other component needs to add a number to a prop it's given, and make that the level:

In MyComponent.tsx:

```<code>type Props = {
  componentLevel: 1 | 2 | 3;
};

const MyComponent = ({ componentLevel }) => (
  <Heading level={componentLevel + 1}>My Component Heading text</Heading>
)
</code>```

Logically I can see that Heading will always get the props that it needs, however TypeScript gives me an error:

TS2322: Type 'number' is not assignable to type '1 | 2 | 3 | 4 | 5 | 6'.

答:
Other people's code is good answer, I just want to add some more detail:
When you use union like this : level?: 1 | 2 | 3 | 4 | 5 | 6; and then pass level={componentLevel + 1} as props of Heading component, TS only can understand componentLevel + 1 as number because you did not mention that it is one value on the union level?: 1 | 2 | 3 | 4 | 5 | 6;.

Body:
I have a heading component which takes a level as a prop:

In Heading.tsx

type Props = {
  level?: 1 | 2 | 3 | 4 | 5 | 6;
  children: string;
};

My other component needs to add a number to a prop it's given, and make that the level:

In MyComponent.tsx:

type Props = {
  componentLevel: 1 | 2 | 3;
};

const MyComponent = ({ componentLevel }) => (
  <Heading level={componentLevel + 1}>My Component Heading text</Heading>
)

Logically I can see that Heading will always get the props that it needs, however TypeScript gives me an error:

TS2322: Type 'number' is not assignable to type '1 | 2 | 3 | 4 | 5 | 6'.


问:
Required String parameter 'token' is not present
I'm using spring boot and thymeleaf in my application, I'm trying implement 'token CSRF' in Controller and thymeleaf file to reset password and protect by CSRF:

my controller:

```<code>@Controller
@RequestMapping("/sdsc0004")
public class SdsPasswordRegController {

private static final Logger LOGGER = LoggerFactory.getLogger(SdsPasswordRegController.class);

@Autowired
private CustomerService customerService;

@ModelAttribute("customer")
public SdsPasswordRegForm passwordReset() {
  return new SdsPasswordRegForm();
}

@GetMapping
public String getUpdatePassword(HttpServletRequest request, HttpServletResponse response,
@RequestParam("token") String token, Model model) {

   Customer checkTokenUser = customerService.findByConfirmationTokenCSRF(token);
   // No token found in DB
    if(checkTokenUser == null) {
      // modelAndView.addObject("invalidToken", "Oops!  This is an invalid confirmation link.");
      LOGGER.info("invalid Token");
      model.addAttribute("invalidToken", "can not verify token !!");
    }
    else {
       model.addAttribute("confirmationToken", checkTokenUser.getConfirmationToken());
      LOGGER.info("invalid Token", checkTokenUser.getConfirmationToken());
    }

    LOGGER.info("Loading submit form successfully");
    model.addAttribute("customer", customer);

    return "sdsc0004";
  }

  @PostMapping
  public String setUpdatePassword(@ModelAttribute("customer") @Validated SdsPasswordRegForm customer,
BindingResult result, Model model, @RequestParam Map requestParams) {

 Customer customerDTO = new Customer();
 // boolean resetOrUpdatePassword = customerService.save(customer.getNewPassword());

 if (result.hasErrors()) {
  LOGGER.info("Submit form: confirm submit password success !!");
    return "sdsc0004";
  }
  else {
    // customer.setSdsUserMgmtDto(customerDTO.setIsLocked(false));
    customerDTO.setIsLocked(true);
    customerDTO.setConfirmationToken(UUID.randomUUID().toString());

    System.out.println();
    System.out.println("token generate automatic: " + customerDTO.getConfirmationToken());

    // customerService.save(customer.getNewPassword());

    return "redirect:/sdsc0005";
   }
  }
 }
</code>```

my HTML:

```<code><div th:if="${invalidToken}" class="alert alert-danger" role="alert" th:text=${invalidToken}></div>

    <form th:if="!${invalidToken}" th:action="@{/sdsc0004}" th:object="${customer}" method="post">
      <input type="hidden" name="token" th:value=${confirmationToken}  >

        <div style="margin-top: 2em">
            <div class="row">
                <div class="col-xs-2 col-sm-2 col-lg-3"></div>
                </div>
                <div class="row">
                    <div class="col-xs-2 col-sm-2 col-lg-3"></div>
                        <div class="row">
                            <div class="col-xs-2 col-sm-2 col-lg-3"></div>
                                <div class="col-xs-8 col-sm-8 col-lg-5" style="background: #f2f2f2;">
                                <p>
                                <input type="password" style="width: 100%;" name="newPassword" th:value="*{newPassword}" placeholder="New password" />
                                <div class="text-danger" th:if="${#fields.hasErrors('newPassword')}" th:errors="*{newPassword}"></div>
                                </p>
                                </div>
                            <div class="col-xs-2 col-sm-2 col-lg-3"></div>
                            </div>
                            <div class="row">
                                <div class="col-xs-2 col-sm-2 col-lg-3"></div>
                                <div class="col-xs-8 col-sm-8 col-lg-5" style="background: #f2f2f2;">
                                <p>
                                    <input type="password" style="width: 100%;" name="confirmNewPassword" th:value="*{confirmNewPassword}" placeholder="Confirm new password" />
                                    <div class="text-danger" th:if="${#fields.hasErrors('confirmNewPassword')}" th:errors="*{confirmNewPassword}"></div>
                                </p>
                            </div>
                                <div class="col-xs-2 col-sm-2 col-lg-3"></div>
                            </div>

                <div class="row">
                    <div class="col-xs-2 col-sm-2 col-lg-3"></div>
                        <div class="col-xs-8 col-sm-8 col-lg-5" style="background: #f2f2f2;">
                            <button type="submit" class="logoff-btn" style="width: 100%; padding: 3%; margin: 0">Reset</button>
                        </div>
                    </div>
                </div>
    </form>
</code>```

When I build and it happen an error following as:

```<code>There was an unexpected error (type=Bad Request, status=400).
Required String parameter 'token' is not present
org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'token' is not present
        at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:204)
        at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:114)
        at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
        at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167)
</code>```

How to fix the problem

答: I think that there is a problem with your business logic. You send the "token" with "post" method in thymeleaf, but requires "token" param in "@GetMapping".</p>

Body:
I'm using spring boot and thymeleaf in my application, I'm trying implement 'token CSRF' in Controller and thymeleaf file to reset password and protect by CSRF:

my controller:

@Controller
@RequestMapping("/sdsc0004")
public class SdsPasswordRegController {

private static final Logger LOGGER = LoggerFactory.getLogger(SdsPasswordRegController.class);

@Autowired
private CustomerService customerService;

@ModelAttribute("customer")
public SdsPasswordRegForm passwordReset() {
  return new SdsPasswordRegForm();
}

@GetMapping
public String getUpdatePassword(HttpServletRequest request, HttpServletResponse response,
@RequestParam("token") String token, Model model) {

   Customer checkTokenUser = customerService.findByConfirmationTokenCSRF(token);
   // No token found in DB
    if(checkTokenUser == null) {
      // modelAndView.addObject("invalidToken", "Oops!  This is an invalid confirmation link.");
      LOGGER.info("invalid Token");
      model.addAttribute("invalidToken", "can not verify token !!");
    }
    else {
       model.addAttribute("confirmationToken", checkTokenUser.getConfirmationToken());
      LOGGER.info("invalid Token", checkTokenUser.getConfirmationToken());
    }

    LOGGER.info("Loading submit form successfully");
    model.addAttribute("customer", customer);

    return "sdsc0004";
  }

  @PostMapping
  public String setUpdatePassword(@ModelAttribute("customer") @Validated SdsPasswordRegForm customer,
BindingResult result, Model model, @RequestParam Map requestParams) {

 Customer customerDTO = new Customer();
 // boolean resetOrUpdatePassword = customerService.save(customer.getNewPassword());

 if (result.hasErrors()) {
  LOGGER.info("Submit form: confirm submit password success !!");
    return "sdsc0004";
  }
  else {
    // customer.setSdsUserMgmtDto(customerDTO.setIsLocked(false));
    customerDTO.setIsLocked(true);
    customerDTO.setConfirmationToken(UUID.randomUUID().toString());

    System.out.println();
    System.out.println("token generate automatic: " + customerDTO.getConfirmationToken());

    // customerService.save(customer.getNewPassword());

    return "redirect:/sdsc0005";
   }
  }
 }

my HTML:

    <form th:if="!${invalidToken}" th:action="@{/sdsc0004}" th:object="${customer}" method="post">
      <input type="hidden" name="token" th:value=${confirmationToken}  >

                                <input type="password" style="width: 100%;" name="newPassword" th:value="*{newPassword}" placeholder="New password" />

                                    <input type="password" style="width: 100%;" name="confirmNewPassword" th:value="*{confirmNewPassword}" placeholder="Confirm new password" />

                            <button type="submit" class="logoff-btn" style="width: 100%; padding: 3%; margin: 0">Reset</button>

    </form>

When I build and it happen an error following as:

There was an unexpected error (type=Bad Request, status=400).
Required String parameter 'token' is not present
org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'token' is not present
        at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:204)
        at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:114)
        at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
        at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167)

How to fix the problem


问:
Opening a file path in Excel 2016
I am trying to write a VBA to open up a file path to a direct folder. What is wrong with how I am doing it? Is this the right way to do it?

I have searched and used examples from here, but get an error (see below)

```<code>Sub OpenFolder()
    Dim FolderPath As String

    FolderPath = "C:\Users\myname\Desktop\AdaptiveThreatProtection\"

    Call Shell("explorer.exe """ & FolderPath & "", vbNormalFocus)

End Sub

</code>```

答:
```<code>Sub OpenFolder()

    Dim MyFolder As String
    MyFolder = "C:\Users\myname\Desktop\AdaptiveThreatProtection"
    ThisWorkbook.FollowHyperlink MyFolder

End Sub
</code>```

Using ThisWorkbook ended up working for me. It opens the exact file path.

Title: Opening a file path in Excel 2016

Body:
I am trying to write a VBA to open up a file path to a direct folder. What is wrong with how I am doing it? Is this the right way to do it?

I have searched and used examples from here, but get an error (see below)

Sub OpenFolder()
    Dim FolderPath As String

    FolderPath = "C:\Users\myname\Desktop\AdaptiveThreatProtection\"

    Call Shell("explorer.exe """ & FolderPath & "", vbNormalFocus)

End Sub

Body:
Sub OpenFolder()

    Dim MyFolder As String
    MyFolder = "C:\Users\myname\Desktop\AdaptiveThreatProtection"
    ThisWorkbook.FollowHyperlink MyFolder

End Sub

Using ThisWorkbook ended up working for me. It opens the exact file path.


问:
Laravel google verification
Google asks me to verify my website by clicking link www.domain.com/dummy_text.html, but whenever i click this link I get NotFoundHttpException error. How can I reach files in public folder and avoid this error?

Thanks!

答:
First of all you need to go to Google Search Console create an instance of the site to be verified.
After doing that, you do the following.

1) Upload the downloaded Google verification File to your public directory.

2) Assuming the Google Verification file's name is "google97ce02dabcfc3bb5.html",
Edit your site's .htaccess file with the following configuration.

```<code>#Start of Google Analytics verification for Laravel
RewriteCond $1 !^(index\.php|public|robots|google97ce02dabcfc3bb5\.html)

RewriteRule ^([0-9A-Za-z-:._/\x7f-\xff]*)$ /public/index.php/$1 [L]
#End of Google Analytics Verification for Laravel
</code>```

Title: Laravel google verification

Body:
First of all you need to go to Google Search Console create an instance of the site to be verified.
After doing that, you do the following.

1) Upload the downloaded Google verification File to your public directory.

2) Assuming the Google Verification file's name is "google97ce02dabcfc3bb5.html",
Edit your site's .htaccess file with the following configuration.

#Start of Google Analytics verification for Laravel
RewriteCond $1 !^(index\.php|public|robots|google97ce02dabcfc3bb5\.html)

RewriteRule ^([0-9A-Za-z-:._/\x7f-\xff]*)$ /public/index.php/$1 [L]
#End of Google Analytics Verification for Laravel


问:
Performance of operator| vs operators+
Is there any major difference between | and + that would affect a code's performance in the long run? or are both O(1)? the code i am working with is something like this:

```<code>uint64_t dostuff(uint64_t a,uint64_t b){
        // the max values of the inputs are 2^32 - 1

        // lots of stuff involving boolean operators
        // that have no way of being substituted by
        // arithmetic operators

        return (a << 32) + b;
        //or
        return (a << 32) | b;
}
</code>```

the code will be used many times, so i want to speed it up as much as possible.

答:
The best answer here is not trying to predict which one is better but benchmark it or check the assembly code. I would guess that both will be optimized to the same instruction and in any case the number of CPU cycles taken by both could be equal.

But I strongly suggest you to check ASM and benchmark both solutions.

Title: Performance of operator| vs operators+


问:
How to create a list like this [1,1,1,1,1,2,2]?
I have looked all over and know how to make lists like this:
[1,1,1,1,1,1]

and like this:
[1,2,3,4,5]

But can't figure out how to make a list like this:
[1,1,1,1,1,2,2].

I've tried this:

```<code>flagpriority = [[1 for i in range(len(res)-2)]]
</code>```

and then played with putting 2,2 in there but it turns it into 2 lists or just gives me 1,1.

Body:
I have looked all over and know how to make lists like this:
[1,1,1,1,1,1]

and like this:
[1,2,3,4,5]

But can't figure out how to make a list like this:
[1,1,1,1,1,2,2].

I've tried this:

flagpriority = [[1 for i in range(len(res)-2)]]

and then played with putting 2,2 in there but it turns it into 2 lists or just gives me 1,1.

Body: flagpriority = [1] * (len(res)-2) + [2] * 2


问:
Python3 how to combine 2 text files line by line conditionally
I have two ascii tables in text files containing information about stars, one of which with the headers

| ID | TIME | MAGNITUDE | ERROR |

and the other has the headers

| ID | CLASS |

and I want to add the CLASS column to the first text file. The main problem here is that the first text file has got many rows for each star (I.E. Star 3_6588 has got 20 entries in table a for different times) whereas the second text file has only one entry for each ID (as Star 3_6588 is always a Class I).

What I need to do is to add the |CLASS| column to the first table where every instance of a specific ID has the required class. The text file has over 14  million rows in it which is why I can't just do this manually.

答: Sounds like you should use the csv module to read the ID|CLASS file into a dictionary, then iterate over the first file line-by-line, lookup CLASS using the ID value, and output the resulting "row" to a new file.</p>


问:
React-pdf submit multiple values
I am trying to create a form where you input some values in this case, name and surname and then you generate a pdf.
I am using https://react-pdf.org/advanced#on-the-fly-rendering to aid with the task. However, I have only managed to submit one value. Code extract below:

```<code><BlobProvider
          document={MyDoc({
            value: this.state.value,
          },{
            value1: this.state.value1,
          })}
        >
          {({ url }) => (
            <a href={url} target="_blank">
              Print
            </a>
          )}
        </BlobProvider>
</code>```

I have tried multiple options in introducing the second value it appears as undefined when console.log, so it doesn't work let alone a much larger form.
This is the full extent of the code https://codesandbox.io/s/strange-ramanujan-847ph?file=/src/App.js

Apologies, I didn't manage to make it work in codesandbox, but it does work in my code editor.

答:
Managed to make it work and yes you can introdue as many values as possible

```<code> <BlobProvider
          document={MyDoc({
            value: this.state.value,
            surname: this.state.surname,
**more values here**
          })}
        >
          {({ url }) => (
            <a href={url} target="_blank">
              Print
            </a>
          )}
        </BlobProvider>
</code>```

The full extent of the code below:

```<code>import React from "react";
import { BlobProvider, Document, Page, Text, View } from "@react-pdf/renderer";

const MyDoc = ({ value, surname }) => (
  <Document>
    <Page wrap>
      <Text>Section #1</Text>

      <View style={{ flexDirection: "row", margin: "2", color: "blue" }}>
        <Text style={{ padding: 10 }}>Name : </Text>
        <Text style={{ padding: 10 }}>{value}</Text>
        {console.log("name", value)}
      </View>

      <View style={{ flexDirection: "row", margin: "2", color: "blue" }}>
        <Text style={{ padding: 10 }}>Surname : </Text>
        <Text style={{ padding: 10 }}>{surname}</Text>
        {console.log("surname", surname)}
      </View>
    </Page>
  </Document>
);

class App extends React.Component {
  state = { value: "", surname: "" };

  render() {
    return (
      <div >
        <div>Pdf Generator</div>
        <form>
          <div >
            <div >
              <label>name</label>
              <input

                value={this.state.value}
                type="text"
                onChange={(e) => this.setState({ value: e.target.value })}
                placeholder="name"
              />
            </div>

            <div>
              <label>surname</label>
              <input
                value={this.state.surname}
                type="text"
                onChange={(e) => this.setState({ surname: e.target.value })}
                placeholder="surname"
              />
            </div>
          </div>
        </form>

        <BlobProvider
          document={MyDoc({
            value: this.state.value,
            surname: this.state.surname,
          })}
        >
          {({ url }) => (
            <a href={url} target="_blank">
              Print
            </a>
          )}
        </BlobProvider>
      </div>
    );
  }
}

export default App;
</code>```

Title: React-pdf submit multiple values

Body:
I am trying to create a form where you input some values in this case, name and surname and then you generate a pdf.
I am using https://react-pdf.org/advanced#on-the-fly-rendering to aid with the task. However, I have only managed to submit one value. Code extract below:

<BlobProvider
          document={MyDoc({
            value: this.state.value,
          },{
            value1: this.state.value1,
          })}
        >
          {({ url }) => (

              Print

          )}
        </BlobProvider>

I have tried multiple options in introducing the second value it appears as undefined when console.log, so it doesn't work let alone a much larger form.
This is the full extent of the code https://codesandbox.io/s/strange-ramanujan-847ph?file=/src/App.js

Apologies, I didn't manage to make it work in codesandbox, but it does work in my code editor.

Body:
Managed to make it work and yes you can introdue as many values as possible

 <BlobProvider
          document={MyDoc({
            value: this.state.value,
            surname: this.state.surname,
**more values here**
          })}
        >
          {({ url }) => (
            <a href={url} target="_blank">
              Print
            </a>
          )}
        </BlobProvider>

The full extent of the code below:

import React from "react";
import { BlobProvider, Document, Page, Text, View } from "@react-pdf/renderer";

const MyDoc = ({ value, surname }) => (
  <Document>
    <Page wrap>
      <Text>Section #1</Text>

      <View style={{ flexDirection: "row", margin: "2", color: "blue" }}>
        <Text style={{ padding: 10 }}>Name : </Text>
        <Text style={{ padding: 10 }}>{value}</Text>
        {console.log("name", value)}
      </View>

      <View style={{ flexDirection: "row", margin: "2", color: "blue" }}>
        <Text style={{ padding: 10 }}>Surname : </Text>
        <Text style={{ padding: 10 }}>{surname}</Text>
        {console.log("surname", surname)}
      </View>
    </Page>
  </Document>
);

class App extends React.Component {
  state = { value: "", surname: "" };

  render() {
    return (
      <div >
        <div>Pdf Generator</div>
        <form>
          <div >
            <div >
              <label>name</label>
              <input

                value={this.state.value}
                type="text"
                onChange={(e) => this.setState({ value: e.target.value })}
                placeholder="name"
              />
            </div>

            <div>
              <label>surname</label>
              <input
                value={this.state.surname}
                type="text"
                onChange={(e) => this.setState({ surname: e.target.value })}
                placeholder="surname"
              />
            </div>
          </div>
        </form>

        <BlobProvider
          document={MyDoc({
            value: this.state.value,
            surname: this.state.surname,
          })}
        >
          {({ url }) => (
            <a href={url} target="_blank">
              Print
            </a>
          )}
        </BlobProvider>
      </div>
    );
  }
}

export default App;


问:
What influences the speed of code?
The way to see how fast your code is going, is performance profiling. There are tools for it and such, but I wonder what the factors are for code speed.

For instance, I've been told that image-editting software will use bitwise operations instead of integer variables to calculate their stuff, simply because it's faster.

So that must mean working with integers and other primitive types takes a few more steps to calculate compared to binairy.

There must be other stuff, but I don't have enough experience with how an OS connects to your hardware and the internal workings of many coding languages to know what.

So I'm asking here: do you know what influences the speed of code?

Not necessarily the speed of programs.

答:
On 2009 hardware, as in real estate, there are just three things to keep in mind when thinking about the speed of code: memory, memory, memory.  (I include cache and locality.)

Reduce allocations.  Reduce writes.  Reduce reads.

After that you're usually in the noise, and it's harder to state categorical results.  (For example, it used to be true that computations done in a floating-point unit were almost always slower than similar computations done in an integer unit.  That's not true any more.)

If you can keep multiple integer units and a floating-point unit busy at once, that's a plus.

OwnerDisplayName: Vordreller

ContentLicense: CC BY-SA 2.5

Title: What influences the speed of code?

LastEditorDisplayName: Vordreller

OwnerDisplayName: Norman Ramsey


问:
React Redux,Updation of particular item in state
The below Reducer supposed to update quantity of particular object in state when I dispatch {"id": 14, 'quantity':3} or {"id": 14, 'quantity':2}.

```<code>
const initialState={ items = [ {"id": 14, 'quantity':1},{"id": 15,'quantity':1},{"id": 25,'quantity':1}] }

const cart =(state=initialState,action)=>{
    switch(action.type){
        case 'UPDATECART':{

             //need updating code here

                 }
        default: return state
    }
}

export default cart
</code>```

How can I update particular object in state's array, keeping other values unaltered ?

The updation function increment quantity of existing object by 1 and id will be permanent.

Proposed work flow

```<code> CURRENT STATE : items = [ {"id": 14, 'quantity':1},{"id": 15,'quantity':1},{"id": 25,'quantity':1}]
    INCOMING OBJECT : {"id": 15,'quantity':2}
    EXPECTED RESULTANT STATE : items = [ {"id": 14, 'quantity':1},{"id": 15,'quantity':3},{"id": 25,'quantity':1}]
</code>```

答:
You should replace the item in the array and return new state reference, try the following code</p>

```<code>const initialState = {
  items: [
    { id: 14, quantity: 1 },
    { id: 15, quantity: 1 },
    { id: 25, quantity: 1 }
  ]
};

const cart = (state = initialState, action) => {
  switch (action.type) {
    case "UPDATECART": {
      const index = state.items.findIndex(
        item => item.id === action.payload.id
      );
      if (index >= 0) {
        state.items[index] = {
          id: action.payload.id,
          quantity: action.payload.quantity
        };
      } else {
        // add to array if not exist
        state.items.push({
          id: action.payload.id,
          quantity: action.payload.quantity
        });
      }
      return {
        items: [...state.items] // creating new array
      };
    }
    default:
      return state;
  }
};

export default cart;

</code>```

Body:
The below Reducer supposed to update quantity of particular object in state when I dispatch {"id": 14, 'quantity':3} or {"id": 14, 'quantity':2}.

const initialState={ items = [ {"id": 14, 'quantity':1},{"id": 15,'quantity':1},{"id": 25,'quantity':1}] }

const cart =(state=initialState,action)=>{
    switch(action.type){
        case 'UPDATECART':{

             //need updating code here

                 }
        default: return state
    }
}

export default cart

How can I update particular object in state's array, keeping other values unaltered ?

The updation function increment quantity of existing object by 1 and id will be permanent.

Proposed work flow

 CURRENT STATE : items = [ {"id": 14, 'quantity':1},{"id": 15,'quantity':1},{"id": 25,'quantity':1}]
    INCOMING OBJECT : {"id": 15,'quantity':2}
    EXPECTED RESULTANT STATE : items = [ {"id": 14, 'quantity':1},{"id": 15,'quantity':3},{"id": 25,'quantity':1}]

Body:
You should replace the item in the array and return new state reference, try the following code

const initialState = {
  items: [
    { id: 14, quantity: 1 },
    { id: 15, quantity: 1 },
    { id: 25, quantity: 1 }
  ]
};

const cart = (state = initialState, action) => {
  switch (action.type) {
    case "UPDATECART": {
      const index = state.items.findIndex(
        item => item.id === action.payload.id
      );
      if (index >= 0) {
        state.items[index] = {
          id: action.payload.id,
          quantity: action.payload.quantity
        };
      } else {
        // add to array if not exist
        state.items.push({
          id: action.payload.id,
          quantity: action.payload.quantity
        });
      }
      return {
        items: [...state.items] // creating new array
      };
    }
    default:
      return state;
  }
};

export default cart;