问:
React Js Updating a value inside a array with onChange to a child component
I have a list with opening_hours that I map inside my render function. I map them to a child component. I want to change the value of each object inside my parent state when the child component state is changed. Only problem is that my values don't change in the child component nor the parent state. I have passed the onChange method to each child component, but the problem lies in my onChange function in the parent state.

I have tried to pass the onChange to my child component and update the state with [e.target.name] : e.target.value. But that didn't work. So I tried to copy the arrayList and update the state based on the index of the mapped arrayList. That also didn't work.

```<code>    handleOnChange =  (index) => {
        let newData = [...this.state.opening_hours];
        this.setState(
            newData.map((barbershop, j) => {
                if (j === index) {
                    return barbershop;
                    console.log(barbershop)
                }
            return {
                newData,
            };
        }));
        console.log(newData)
    };

    render() {
        return (
            <>
                <div className="container mb-2">
                    <h4>Opening hours </h4>
                    <Form>
                        {this.state.opening_hours.map((barbershop, index) => (
                            <Day
                                key={barbershop.id}
                                day={barbershop.day}
                                open_time={barbershop.open_time}
                                close_time={barbershop.close_time}
                                index = {index}
                                onChange={() => this.handleOnChange(index)}/>
                        ))}
                    </Form>

                    <Button onClick={this.handleSubmit} variant="primary" type="submit">
                        Update opening hours
                    </Button>
                </div>
            </>
        );
    }
}
</code>```

My child component looks like this

```<code>class Day extends Component {

    constructor(props) {
        super(props);
        this.state = {
            day: this.props.day,
            open_time: this.props.open_time,
            close_time: this.props.close_time,
        };
        console.log(this.state)
    }

    handleChange = () => {
        this.props.onChange(this.props.index)
    }

    render() {
        return (
                <Form.Group as={Row}>
                <Form.Label column sm="3">
                    {ENUM[this.state.day]}
                </Form.Label>
                <Col sm="3">
                    <Form.Control
                        name="open_time"
                        value={this.state.open_time}
                        onChange={this.handleChange}
                        type="time"
                        min="08:00"
                        max="24:00"/>
                </Col>
                <Col sm="3">
                    <Form.Control
                        name="close_time"
                        value={this.state.close_time}
                        onChange={this.handleChange}
                        type="time"
                        min="08:00"
                        max="24:00"/>
                </Col>
            </Form.Group>
        );
    }
}

</code>```

EDIT:

答:
So I have done some investigation, I believe the problem is that you are not returning data back to the consumer.

Here is what I think, the solution is:

```<code>import React, { Component, useState, useEffect } from "react";

class UI extends Component {
  handleOnChange = ({ index, ...newHours }) => {
    // update array item
    const opening_hours = this.state.opening_hours.map((item, i) => {
      const newData = i === index ? newHours : {};

      return {
        ...item,
        ...newData
      };
    });

    // update item in opening_hours => state
    this.setState({ opening_hours });
  };

  render() {
    return (
      <div className="container mb-2">
        <h4>Opening hours</h4>

        <Form>
          {this.state.opening_hours.map(({ id, ...barbershop }, index) => (
            <Day
              key={id}
              {...barbershop}
              {...{ index }}
              onChange={this.handleOnChange}
            />
          ))}
        </Form>

        <Button onClick={this.handleSubmit} variant="primary" type="submit">
          Update opening hours
        </Button>
      </div>
    );
  }
}

const Day = ({ day, onChange, index, ...props }) => {
  const [open_time, setOpenTime] = useState(props.open_time);
  const [close_time, setCloseTime] = useState(props.close_time);

  useEffect(() => {
    onChange({ index, open_time, close_time });
  }, [open_time, close_time, onChange, index]);

  const sharedProps = {
    type: "time",
    min: "08:00",
    max: "24:00"
  };

  return (
    <Form.Group as={Row}>
      <Form.Label column sm="3">
        {ENUM[day]}
      </Form.Label>

      <Col sm="3">
        <Form.Control
          {...sharedProps}
          name="open_time"
          value={open_time}
          onChange={({ target }) => setOpenTime(target.value)}
        />
      </Col>

      <Col sm="3">
        <Form.Control
          {...sharedProps}
          name="close_time"
          value={close_time}
          onChange={({ target }) => setCloseTime(target.value)}
        />
      </Col>
    </Form.Group>
  );
};
</code>```

Body:
I have a list with opening_hours that I map inside my render function. I map them to a child component. I want to change the value of each object inside my parent state when the child component state is changed. Only problem is that my values don't change in the child component nor the parent state. I have passed the onChange method to each child component, but the problem lies in my onChange function in the parent state.

I have tried to pass the onChange to my child component and update the state with [e.target.name] : e.target.value. But that didn't work. So I tried to copy the arrayList and update the state based on the index of the mapped arrayList. That also didn't work.

    handleOnChange =  (index) => {
        let newData = [...this.state.opening_hours];
        this.setState(
            newData.map((barbershop, j) => {
                if (j === index) {
                    return barbershop;
                    console.log(barbershop)
                }
            return {
                newData,
            };
        }));
        console.log(newData)
    };

    render() {
        return (
            <>

Opening hours

                    <Form>
                        {this.state.opening_hours.map((barbershop, index) => (
                            <Day
                                key={barbershop.id}
                                day={barbershop.day}
                                open_time={barbershop.open_time}
                                close_time={barbershop.close_time}
                                index = {index}
                                onChange={() => this.handleOnChange(index)}/>
                        ))}
                    </Form>

                    <Button onClick={this.handleSubmit} variant="primary" type="submit">
                        Update opening hours
                    </Button>

            </>
        );
    }
}

My child component looks like this

class Day extends Component {

    constructor(props) {
        super(props);
        this.state = {
            day: this.props.day,
            open_time: this.props.open_time,
            close_time: this.props.close_time,
        };
        console.log(this.state)
    }

    handleChange = () => {
        this.props.onChange(this.props.index)
    }

    render() {
        return (
                <Form.Group as={Row}>
                <Form.Label column sm="3">
                    {ENUM[this.state.day]}
                </Form.Label>
                <Col sm="3">
                    <Form.Control
                        name="open_time"
                        value={this.state.open_time}
                        onChange={this.handleChange}
                        type="time"
                        min="08:00"
                        max="24:00"/>
                </Col>
                <Col sm="3">
                    <Form.Control
                        name="close_time"
                        value={this.state.close_time}
                        onChange={this.handleChange}
                        type="time"
                        min="08:00"
                        max="24:00"/>
                </Col>
            </Form.Group>
        );
    }
}

EDIT:

Body:
So I have done some investigation, I believe the problem is that you are not returning data back to the consumer.

Here is what I think, the solution is:

import React, { Component, useState, useEffect } from "react";

class UI extends Component {
  handleOnChange = ({ index, ...newHours }) => {
    // update array item
    const opening_hours = this.state.opening_hours.map((item, i) => {
      const newData = i === index ? newHours : {};

      return {
        ...item,
        ...newData
      };
    });

    // update item in opening_hours => state
    this.setState({ opening_hours });
  };

  render() {
    return (
      <div className="container mb-2">
        <h4>Opening hours</h4>

        <Form>
          {this.state.opening_hours.map(({ id, ...barbershop }, index) => (
            <Day
              key={id}
              {...barbershop}
              {...{ index }}
              onChange={this.handleOnChange}
            />
          ))}
        </Form>

        <Button onClick={this.handleSubmit} variant="primary" type="submit">
          Update opening hours
        </Button>
      </div>
    );
  }
}

const Day = ({ day, onChange, index, ...props }) => {
  const [open_time, setOpenTime] = useState(props.open_time);
  const [close_time, setCloseTime] = useState(props.close_time);

  useEffect(() => {
    onChange({ index, open_time, close_time });
  }, [open_time, close_time, onChange, index]);

  const sharedProps = {
    type: "time",
    min: "08:00",
    max: "24:00"
  };

  return (
    <Form.Group as={Row}>
      <Form.Label column sm="3">
        {ENUM[day]}
      </Form.Label>

      <Col sm="3">
        <Form.Control
          {...sharedProps}
          name="open_time"
          value={open_time}
          onChange={({ target }) => setOpenTime(target.value)}
        />
      </Col>

      <Col sm="3">
        <Form.Control
          {...sharedProps}
          name="close_time"
          value={close_time}
          onChange={({ target }) => setCloseTime(target.value)}
        />
      </Col>
    </Form.Group>
  );
};


来源: stackexchange

问:
Find out how the height of a button was set
My code (full version):

        <form class="form-group">
          <form>
            <input type="text" class="form-control w-100 pr-0 mr-0" id="quick-add-task-control-text-area" placeholder="Task name">
          </form>
        </form>

        <button type="button" class="btn btn-secondary w-100 h-100 ml-0" id="schedule-button">Schedule</button>

    <button type="button" class="btn btn-primary btn-sm" id="add-task-modal-save">Save changes</button>

        Priority

      <select class="custom-select" id="inputGroupSelectPriority">
        <option selected>Choose...</option>
        <option value="Low">Low</option>
        <option value="Medium">Medium</option>
        <option value="High">High</option>
      </select>

```

After opening my modal on the navbar ("+" icon), I wanted the height of my input-group to be the same height as my "save changes" button on the left. After inspecting its styles (of the 'save button' I could not understand how it's height was calculated. I did not find any em or rem, or any reference to the parent element like the bootstrap class "h-100". So I had to do it using the height property and pixels, which I know is a terrible way of doing it.
So my question is, how do I set the height of my input-group element in the proper responsive-friendly way?

(For the modal footer I didn't set a container and a row and columns as I did in the modal body, is that terrible?)

答:
In projects using Bootstrap, any element with d-flex is a flexbox container, making the immediate child elements flex items.

Flexbox can drastically change the height of items when flex-direction equals row, which is the default. The items will naturally take up the height of the flexbox container.

Applying a fixed height to items might help but in this circumstance it might just be easier to add a wrapper div around elements like <select> and <button> that are being effected in this way by a flexbox container. That way the wrapper you added can have its height changed by the flexbox container, but the <select> inside keeps its natural height.

Awesome resource about how flexbox works.

ContentLicense: CC BY-SA 4.0

Body:
My code (full version):

        <form class="form-group">
          <form>
            <input type="text" class="form-control w-100 pr-0 mr-0" id="quick-add-task-control-text-area" placeholder="Task name">
          </form>
        </form>

        <button type="button" class="btn btn-secondary w-100 h-100 ml-0" id="schedule-button">Schedule</button>

    <button type="button" class="btn btn-primary btn-sm" id="add-task-modal-save">Save changes</button>

        Priority

      <select class="custom-select" id="inputGroupSelectPriority">
        <option selected>Choose...</option>
        <option value="Low">Low</option>
        <option value="Medium">Medium</option>
        <option value="High">High</option>
      </select>

After opening my modal on the navbar ("+" icon), I wanted the height of my input-group to be the same height as my "save changes" button on the left. After inspecting its styles (of the 'save button' I could not understand how it's height was calculated. I did not find any em or rem, or any reference to the parent element like the bootstrap class "h-100". So I had to do it using the height property and pixels, which I know is a terrible way of doing it.
So my question is, how do I set the height of my input-group element in the proper responsive-friendly way?

(For the modal footer I didn't set a container and a row and columns as I did in the modal body, is that terrible?)


问:
loopback event stream causing race condition
My overall goal is to watch my database for any changes and automatically broadcast those changes to any user connected to my website.
The problem that I am seeing is that I have an action triggering a post request to my database and then the event stream is triggered at the same time because the model that I am watching has changed. Which results in the initial action fulfilling and the action triggered by the event stream is being interrupted before it is fulfilled.

this is the first action that is triggered to create a new blog post entry in my database

export const topicSubmit = (date, newTopic, newTopicBody, memberId, name) => {
    return {
        type: 'TOPIC_SUBMIT',
        payload: axios({
            method: 'post',
            url: `/api/blogPosts`,
            data: {
                "blogTitle": newTopic,
                "blogBody": newTopicBody,
                "date": date,
                "upVotes": 0,
                "numComments": 0,
                "voteNames": [],
                "memberId": memberId,
                "steamNameId": name
            }
        })
            .then(response => {
                return response.data
            })
            .catch(err => err)
    }
}

// this is the boot script that creates the change stream

var es = require('event-stream');
module.exports = function (app) {
    console.log('realtime boot script')
    var BlogPost = app.models.BlogPost;
    BlogPost.createChangeStream(function (err, changes) {
        changes.pipe(es.stringify()).pipe(process.stdout);
    });
}

// this is the event listener on my front end that will dispatch all
// changes made in my database to my front end

componentDidMount() {
        const { dispatch } = this.props;
          let urlToChangeStream = '/api/blogPosts/change-stream?_format=event-stream';
          let src = new EventSource(urlToChangeStream);
          src.addEventListener('data', function (msg) {
              let data = JSON.parse(msg.data);
          dispatch(liveChangeBlogs(data))
          });
```

I am expecting that the 'TOPIC_SUBMIT' action should return fulfilled before the 'liveChangeBlogs' action is dispatched by the event listener
Here is the documentation that I found on loopback event stream https://loopback.io/doc/en/lb3/Realtime-server-sent-events.html

答:
I ended up solving this issue using Redux Thunk, adding a setTimeout and a closure to my componentDidMount. The topicSubmit action and the boot script did not change. Not sure if the setTimeout is the proper way to go, but it was the only way I could think of to get around the race case.</p>

```<code> componentDidMount() {
        const { dispatch } = this.props;
        const newBlog = this.handleNewBlog;
        let urlToChangeStream = '/api/blogPosts/change-stream?_format=event-stream';
        let src = new EventSource(urlToChangeStream);
        src.addEventListener('data', function (msg) {
            newBlog(msg)
        });

        const newThread = this.handleNewThread;
        let urlToChangeStream2 = '/api/threads/change-stream?_format=event-stream';
        let src2 = new EventSource(urlToChangeStream2);
        src2.addEventListener('data', function (msg) {
            newThread(msg)
        });
        dispatch(getBlogs());
    }

  handleNewBlog(msg) {
        const { dispatch } = this.props;
        let data = JSON.parse(msg.data);
        if(data.data == undefined) {
            setTimeout(() => {
                dispatch(getBlogs());
            }, 1000);
        } else {
            setTimeout(() => {
                dispatch(liveChangeBlogs(data));
            }, 1000);
        }
    }

 handleNewThread(msg) {
        const { dispatch, viewingThreadId } = this.props;
        let data2 = JSON.parse(msg.data);
        console.log('data2: ', data2)
        if (data2.type == 'remove') {
            return dispatch(getThreadsById(viewingThreadId))
        }
        let id = data2.data.blogPostId
        setTimeout(() => {
            if (viewingThreadId === id) {
                dispatch(getThreadsById(id));
            } else {
                return
            }
        }, 1000);
    }
</code>```

Body:
My overall goal is to watch my database for any changes and automatically broadcast those changes to any user connected to my website.
The problem that I am seeing is that I have an action triggering a post request to my database and then the event stream is triggered at the same time because the model that I am watching has changed. Which results in the initial action fulfilling and the action triggered by the event stream is being interrupted before it is fulfilled.

this is the first action that is triggered to create a new blog post entry in my database

export const topicSubmit = (date, newTopic, newTopicBody, memberId, name) => {
    return {
        type: 'TOPIC_SUBMIT',
        payload: axios({
            method: 'post',
            url: `/api/blogPosts`,
            data: {
                "blogTitle": newTopic,
                "blogBody": newTopicBody,
                "date": date,
                "upVotes": 0,
                "numComments": 0,
                "voteNames": [],
                "memberId": memberId,
                "steamNameId": name
            }
        })
            .then(response => {
                return response.data
            })
            .catch(err => err)
    }
}

// this is the boot script that creates the change stream

var es = require('event-stream');
module.exports = function (app) {
    console.log('realtime boot script')
    var BlogPost = app.models.BlogPost;
    BlogPost.createChangeStream(function (err, changes) {
        changes.pipe(es.stringify()).pipe(process.stdout);
    });
}

// this is the event listener on my front end that will dispatch all
// changes made in my database to my front end

componentDidMount() {
        const { dispatch } = this.props;
          let urlToChangeStream = '/api/blogPosts/change-stream?_format=event-stream';
          let src = new EventSource(urlToChangeStream);
          src.addEventListener('data', function (msg) {
              let data = JSON.parse(msg.data);
          dispatch(liveChangeBlogs(data))
          });

I am expecting that the 'TOPIC_SUBMIT' action should return fulfilled before the 'liveChangeBlogs' action is dispatched by the event listener
Here is the documentation that I found on loopback event stream https://loopback.io/doc/en/lb3/Realtime-server-sent-events.html

Body:
I ended up solving this issue using Redux Thunk, adding a setTimeout and a closure to my componentDidMount. The topicSubmit action and the boot script did not change. Not sure if the setTimeout is the proper way to go, but it was the only way I could think of to get around the race case.

 componentDidMount() {
        const { dispatch } = this.props;
        const newBlog = this.handleNewBlog;
        let urlToChangeStream = '/api/blogPosts/change-stream?_format=event-stream';
        let src = new EventSource(urlToChangeStream);
        src.addEventListener('data', function (msg) {
            newBlog(msg)
        });

        const newThread = this.handleNewThread;
        let urlToChangeStream2 = '/api/threads/change-stream?_format=event-stream';
        let src2 = new EventSource(urlToChangeStream2);
        src2.addEventListener('data', function (msg) {
            newThread(msg)
        });
        dispatch(getBlogs());
    }

  handleNewBlog(msg) {
        const { dispatch } = this.props;
        let data = JSON.parse(msg.data);
        if(data.data == undefined) {
            setTimeout(() => {
                dispatch(getBlogs());
            }, 1000);
        } else {
            setTimeout(() => {
                dispatch(liveChangeBlogs(data));
            }, 1000);
        }
    }

 handleNewThread(msg) {
        const { dispatch, viewingThreadId } = this.props;
        let data2 = JSON.parse(msg.data);
        console.log('data2: ', data2)
        if (data2.type == 'remove') {
            return dispatch(getThreadsById(viewingThreadId))
        }
        let id = data2.data.blogPostId
        setTimeout(() => {
            if (viewingThreadId === id) {
                dispatch(getThreadsById(id));
            } else {
                return
            }
        }, 1000);
    }


问:
Pushing a local Docker image to a private repository with a self-signed certificate
I'm trying to push an image, say foo/bar, from my local Docker registry to a registry running on OpenShift 3.11 (actually Minishift v1.33.0+ba29431).

The registry is at 192.168.64.3:2376 and it expects HTTPS connections. It uses a self-signed certificate.

First I copy the tag for the new image:

```<code>docker tag foo/bar 192.168.64.3:2376/app/foo/bar
</code>```

This succeeds. Then I try pushing:

```<code>$ docker push 192.168.64.3:2376/app/foo/bar
The push refers to repository [192.168.64.3:2376/app/foo/bar]
Get https://192.168.64.3:2376/v2/: x509: certificate signed by unknown authority
</code>```

or, when Docker is configured to allow use of unsafe registries in 192.168.64.0/24, it talks HTTP to the server instead of disabling certificate verification:

```<code>$ docker push 192.168.64.3:2376/app/foo/bar
The push refers to repository [192.168.64.3:2376/app/foo/bar]
Get http://192.168.64.3:2376/v2/: EOF
</code>```

The documentation says that for an unsafe registry, it should "First, try using HTTPS. If HTTPS is available but the certificate is invalid, ignore the error about the certificate. If HTTPS is not available, fall back to HTTP." So I would not expect to see an EOF error.

I also cannot try to tell Docker to use the Minishift certs, because it suddenly loses the ability to talk to the local Docker daemon (it should use a Unix domain socket, not tcp://localhost:2376):

```<code>$ export DOCKER_TLS_VERIFY="1"
$ export DOCKER_CERT_PATH="/Users/rzg/.minishift/certs"
$ docker push 192.168.64.3:2376/app/foo/bar
Cannot connect to the Docker daemon at tcp://localhost:2376. Is the docker daemon running?
</code>```

This is the version of Docker I'm using:

```<code>Client: Docker Engine - Community
 Version:           18.09.2
 API version:       1.39
 Go version:        go1.10.8
 Git commit:        6247962
 Built:             Sun Feb 10 04:12:39 2019
 OS/Arch:           darwin/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          18.09.2
  API version:      1.39 (minimum version 1.12)
  Go version:       go1.10.6
  Git commit:       6247962
  Built:            Sun Feb 10 04:13:06 2019
  OS/Arch:          linux/amd64
  Experimental:     false
</code>```

答:
Those two environment variables you mention are for the docker command-line tool to talk to the Docker daemon.  You don't normally need to set them.  (Also note that port 2376 is the conventional port for the Docker API HTTP-over-TLS, though nothing stops you from using it for a registry instead.)

You're trying to configure the Docker daemon to talk to a remote registry that you trust.  The dockerd reference says about secure registries:

A secure registry uses TLS and a copy of its CA certificate is placed on the Docker host at /etc/docker/certs.d/myregistry:5000/ca.crt.

So in your setup, you need to find the CA certificate for your registry, and put it in /etc/docker/certs.d/192.168.64.3:2376/ca.crt, and then restart the Docker daemon.

This is also described in the OpenShift OKD documentation under Securing and Exposing the Registry (see "Manually Securing the Registry", and in particular its steps 12 and 13).

Body:
I'm trying to push an image, say foo/bar, from my local Docker registry to a registry running on OpenShift 3.11 (actually Minishift v1.33.0+ba29431).

The registry is at 192.168.64.3:2376 and it expects HTTPS connections. It uses a self-signed certificate.

First I copy the tag for the new image:

docker tag foo/bar 192.168.64.3:2376/app/foo/bar

This succeeds. Then I try pushing:

$ docker push 192.168.64.3:2376/app/foo/bar
The push refers to repository [192.168.64.3:2376/app/foo/bar]
Get https://192.168.64.3:2376/v2/: x509: certificate signed by unknown authority

or, when Docker is configured to allow use of unsafe registries in 192.168.64.0/24, it talks HTTP to the server instead of disabling certificate verification:

$ docker push 192.168.64.3:2376/app/foo/bar
The push refers to repository [192.168.64.3:2376/app/foo/bar]
Get http://192.168.64.3:2376/v2/: EOF

The documentation says that for an unsafe registry, it should "First, try using HTTPS. If HTTPS is available but the certificate is invalid, ignore the error about the certificate. If HTTPS is not available, fall back to HTTP." So I would not expect to see an EOF error.

I also cannot try to tell Docker to use the Minishift certs, because it suddenly loses the ability to talk to the local Docker daemon (it should use a Unix domain socket, not tcp://localhost:2376):

$ export DOCKER_TLS_VERIFY="1"
$ export DOCKER_CERT_PATH="/Users/rzg/.minishift/certs"
$ docker push 192.168.64.3:2376/app/foo/bar
Cannot connect to the Docker daemon at tcp://localhost:2376. Is the docker daemon running?

This is the version of Docker I'm using:

Client: Docker Engine - Community
 Version:           18.09.2
 API version:       1.39
 Go version:        go1.10.8
 Git commit:        6247962
 Built:             Sun Feb 10 04:12:39 2019
 OS/Arch:           darwin/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          18.09.2
  API version:      1.39 (minimum version 1.12)
  Go version:       go1.10.6
  Git commit:       6247962
  Built:            Sun Feb 10 04:13:06 2019
  OS/Arch:          linux/amd64
  Experimental:     false


问:
Syntax issue with using Multer in Node.js
i've been using this tutorial :

https://medium.com/@mahesh_joshi/reactjs-nodejs-upload-image-how-to-upload-image-using-reactjs-and-nodejs-multer-918dc66d304c

To upload a file from React client side to Node.js server side.
I'm havng an issue with the POST route given in the tutorial,
VS Code shows a syntax error when pasting it. Can anyone re-arrange it?
This is the route :

```<code>router.post("/upload", {
upload(req, res, (err) => {
  console.log("Request ---", req.body);
  console.log("Request file ---", req.file);//Here you get file.
  /*Now do where ever you want to do*/
  if(!err)
     return res.send(200).end();
});
};);
</code>```

答:
It should be like this</p>

```<code>router.post('/upload', function (req, res) {
    upload(req, res, function (err) {
        console.log("Request ---", req.body);
        console.log("Request file ---", req.file);//Here you get file.
        /*Now do where ever you want to do*/
        if(!err) {
            return res.send(200).end();
        }
    })
})
</code>```

Body:
i've been using this tutorial :

https://medium.com/@mahesh_joshi/reactjs-nodejs-upload-image-how-to-upload-image-using-reactjs-and-nodejs-multer-918dc66d304c

To upload a file from React client side to Node.js server side.
I'm havng an issue with the POST route given in the tutorial,
VS Code shows a syntax error when pasting it. Can anyone re-arrange it?
This is the route :

router.post("/upload", {
upload(req, res, (err) => {
  console.log("Request ---", req.body);
  console.log("Request file ---", req.file);//Here you get file.
  /*Now do where ever you want to do*/
  if(!err)
     return res.send(200).end();
});
};);

Body:
It should be like this

router.post('/upload', function (req, res) {
    upload(req, res, function (err) {
        console.log("Request ---", req.body);
        console.log("Request file ---", req.file);//Here you get file.
        /*Now do where ever you want to do*/
        if(!err) {
            return res.send(200).end();
        }
    })
})


问:
How do I interpolate a variable as a key in a JavaScript object?
How can I use the value of the variable a as a key to lookup a property? I want to be able to say: b["whatever"] and have this return 20:

```<code>var a = "whatever";
var b = {a : 20};     // Want this to assign b.whatever
alert(b["whatever"]); // so that this shows 20, not `undefined`
</code>```

I am asking if it's possible during the creation of b, to have it contain "whatever":20 instead of a:20 where "whatever" is itself in a variable. Maybe an eval could be used?

答:
```<code>var a = "whatever";
var b = {};
b[a] = 20;
alert(b["whatever"]); // shows 20
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How can I use the value of the variable a as a key to lookup a property? I want to be able to say: b["whatever"] and have this return 20:

var a = "whatever";
var b = {a : 20};     // Want this to assign b.whatever
alert(b["whatever"]); // so that this shows 20, not `undefined`

I am asking if it's possible during the creation of b, to have it contain "whatever":20 instead of a:20 where "whatever" is itself in a variable. Maybe an eval could be used?


问:
Dynamically Updating Formulas From Another Google Spreadsheet
I have two google spreadsheets, a master copy and a child copy. When I update the formulas in the master copy, I want it to update the formulas in the child copy too. I intend to create many copies of the child copy and don't want to update the formulas in each one every time something small has to change.

I've tried using IMPORTRANGE(), and it only gives me the values, not the formulas. So I thought to create my own script to get this done. I'm using the following code to attempt this:

```<code>function REMOTEDATA(inKey, inRange) {

  var outData;
  var ss = SpreadsheetApp.openById(inKey);

  if (ss) {
     outData = ss.getRange(inRange).getFormulas();
  }

  return outData;
}

//My manifest is the following:
{
  "oauthScopes": [
    "https://www.googleapis.com/auth/spreadsheets"
  ],
  "timeZone": "America/Denver",
  "dependencies": {
  },
  "exceptionLogging": "STACKDRIVER"
}
</code>```

I'm very new to oAuth and I don't understand how to get this to work. When I attempt this it gives me the following:

"You do not have permission to call SpreadsheetApp.openById. Required permissions: https://www.googleapis.com/auth/spreadsheets (line 4)."

Can anyone tell me what I need to add to get this to work? If there's an easier way, I'm all ears.

EDIT:
After reading Ruben's comment below, I changed the way I was doing it to having a button on the sheet itself run the function. It fixed the first problem, but now I'm running into another problem. I can't copy all the data directly from one sheet to another. I'm trying to get formulas, values, and formatting. If I just use getFormulas() and setFormulas() with the ranges, it gets rid of all the values that aren't formulas, and it doesn't change the formatting. I've been trying to use copyTo() but it tells me I can't do this between spreadsheets. My current code is:

```<code>function REMOTEDATA() {

  var MASTERKEY = "key";
  var UPDATERANGES = ["A1:B200", "C7:C200", "D1:H200", "J1:L200", "N1:S200", "U1:X200", "z1:ac200", "AE1:AH200", "AJ1:AL200"];

  var ss = SpreadsheetApp.openById(MASTERKEY);
  var cur_ss = SpreadsheetApp.getActiveSpreadsheet();

  UPDATERANGES.forEach(function(range) {

    data = ss.getRange(range).copyTo(cur_ss.getRange(range));

  });
}
</code>```

My head is starting to hurt looking at the different methods for the Ranges Class. I can't see any methods to do this, but I feel like I'm missing something. Any other ideas?

EDIT 3:
Okay. I figured out a workaround. Basically what I did was copy the entire sheet from one spreadsheet to the other using the sheet.copyTo() function. Then after that I used the range.copyTo() to get what I wanted. Then I deleted the copied sheet using sheet.deleteSheet()

答:
Custom functions run anonymously so they can't call services that require authorization, like openById.

Instead of using a custom function to execute your script use another method like a custom menu, assign the script to an image, etc. or just run it from the script editor.

NOTE: You will have to modify your script a bit or use a another function to pass the required arguments.

Body:
I have two google spreadsheets, a master copy and a child copy. When I update the formulas in the master copy, I want it to update the formulas in the child copy too. I intend to create many copies of the child copy and don't want to update the formulas in each one every time something small has to change.

I've tried using IMPORTRANGE(), and it only gives me the values, not the formulas. So I thought to create my own script to get this done. I'm using the following code to attempt this:

function REMOTEDATA(inKey, inRange) {

  var outData;
  var ss = SpreadsheetApp.openById(inKey);

  if (ss) {
     outData = ss.getRange(inRange).getFormulas();
  }

  return outData;
}

//My manifest is the following:
{
  "oauthScopes": [
    "https://www.googleapis.com/auth/spreadsheets"
  ],
  "timeZone": "America/Denver",
  "dependencies": {
  },
  "exceptionLogging": "STACKDRIVER"
}

I'm very new to oAuth and I don't understand how to get this to work. When I attempt this it gives me the following:

"You do not have permission to call SpreadsheetApp.openById. Required permissions: https://www.googleapis.com/auth/spreadsheets (line 4)."

Can anyone tell me what I need to add to get this to work? If there's an easier way, I'm all ears.

EDIT:
After reading Ruben's comment below, I changed the way I was doing it to having a button on the sheet itself run the function. It fixed the first problem, but now I'm running into another problem. I can't copy all the data directly from one sheet to another. I'm trying to get formulas, values, and formatting. If I just use getFormulas() and setFormulas() with the ranges, it gets rid of all the values that aren't formulas, and it doesn't change the formatting. I've been trying to use copyTo() but it tells me I can't do this between spreadsheets. My current code is:

function REMOTEDATA() {

  var MASTERKEY = "key";
  var UPDATERANGES = ["A1:B200", "C7:C200", "D1:H200", "J1:L200", "N1:S200", "U1:X200", "z1:ac200", "AE1:AH200", "AJ1:AL200"];

  var ss = SpreadsheetApp.openById(MASTERKEY);
  var cur_ss = SpreadsheetApp.getActiveSpreadsheet();

  UPDATERANGES.forEach(function(range) {

    data = ss.getRange(range).copyTo(cur_ss.getRange(range));

  });
}

My head is starting to hurt looking at the different methods for the Ranges Class. I can't see any methods to do this, but I feel like I'm missing something. Any other ideas?

EDIT 3:
Okay. I figured out a workaround. Basically what I did was copy the entire sheet from one spreadsheet to the other using the sheet.copyTo() function. Then after that I used the range.copyTo() to get what I wanted. Then I deleted the copied sheet using sheet.deleteSheet()


问:
Unmarshaling json rawdata from redash in golang
I got a response from redash as follows:

```<code>{'PP_DOM': '{"DEFAULT":100}',....................., 'Myst':'["a","b","c","d"]',
</code>```

I want to unmarshal "myst" key's value as a list in golang.I am newbie here.

答:
You can unmarshall into map[string]interface{} if you have an unknown data structure to explore it. you then may later want to define a struct which maps to the data properly. So to get started, use something like this:

    var jsonData = []byte(`{"PP_DOM": {"DEFAULT":100},"Myst":["a","b","c","d"]}`)
    var data map[string]interface{}
    err := json.Unmarshal(jsonData, &data)
    if err != nil {
        fmt.Println("json: error decoding", err)
    }
    fmt.Printf("Myst:%+v", data["Myst"])
```

https://play.golang.org/p/V5GBtLH6oLs

Your json doesn't appear to be valid, better to post what you have tried instead, which should at least involve valid json.

You should take a look at the docs for the json pkg, in particular the examples.

Body:
I got a response from redash as follows:

{'PP_DOM': '{"DEFAULT":100}',....................., 'Myst':'["a","b","c","d"]',

I want to unmarshal "myst" key's value as a list in golang.I am newbie here.

Body:
You can unmarshall into map[string]interface{} if you have an unknown data structure to explore it. you then may later want to define a struct which maps to the data properly. So to get started, use something like this:

    var jsonData = []byte(`{"PP_DOM": {"DEFAULT":100},"Myst":["a","b","c","d"]}`)
    var data map[string]interface{}
    err := json.Unmarshal(jsonData, &data)
    if err != nil {
        fmt.Println("json: error decoding", err)
    }
    fmt.Printf("Myst:%+v", data["Myst"])

https://play.golang.org/p/V5GBtLH6oLs

Your json doesn't appear to be valid, better to post what you have tried instead, which should at least involve valid json.

You should take a look at the docs for the json pkg, in particular the examples.


问:
How to filter duplicate types from tuple C++
How does one filter duplicate types from a tuple?

For example:

```<code>using Tuple = std::tuple<int, double, int, double, std::string, std::string>
using FilteredTuple = without_duplicates<Tuple>;
</code>```

In which without_duplicates is implemented in such a way that it generates the following FilteredTuple type:

```<code>std::tuple<int, double, std::string>
</code>```

答:
If you have access to Boost, then this can be done directly using boost::mp11::mp_unique<your_tuple_type>.

For example:

```<code>{
  using not_unique = std::tuple<int, int, char, std::string, double, int>;
  using filtered = boost::mp11::mp_unique<not_unique>;
  static_assert(std::is_same_v<std::tuple<int, char, std::string, double>, filtered>);
}
{
  using already_unique = std::tuple<int, char, std::string, double>;
  using filtered = boost::mp11::mp_unique<already_unique>;
  static_assert(std::is_same_v<std::tuple<int, char, std::string, double>, filtered>);
}
</code>```

Live example

Body:
How does one filter duplicate types from a tuple?

For example:

using Tuple = std::tuple<int, double, int, double, std::string, std::string>
using FilteredTuple = without_duplicates<Tuple>;

In which without_duplicates is implemented in such a way that it generates the following FilteredTuple type:

std::tuple<int, double, std::string>

Body:
If you have access to Boost, then this can be done directly using boost::mp11::mp_unique<your_tuple_type>.

For example:

{
  using not_unique = std::tuple<int, int, char, std::string, double, int>;
  using filtered = boost::mp11::mp_unique<not_unique>;
  static_assert(std::is_same_v<std::tuple<int, char, std::string, double>, filtered>);
}
{
  using already_unique = std::tuple<int, char, std::string, double>;
  using filtered = boost::mp11::mp_unique<already_unique>;
  static_assert(std::is_same_v<std::tuple<int, char, std::string, double>, filtered>);
}

Live example


问:
How do I create an NSFetchedPropertyDescription programmatically?
I have a pre-existing NSManagedObjectModel that I created with the Xcode GUI.  I want to create a sorted fetched property, which Xcode 3.2's GUI doesn't support.  I do all of this before creating my NSPersistentStoreCoordinator because I know you can't modify a NSManagedObjectModel after an object graph manager has started using it.  I created the NSFetchedPropertyDescription thusly:

```<code>NSManagedObjectModel *managedObjectModel = ... // fetch from my mainBundle

NSEntityDescription *fetchedPropertyEntityDescription = [entitiesByName objectForKey:@"MyEntity"];

NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
[fetchRequest setEntity:fetchedPropertyEntityDescription];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"myPredicateProperty == $FETCH_SOURCE"]];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"mySortProperty" ascending:YES]]];

NSFetchedPropertyDescription *fetchedPropertyDescription = [[[NSFetchedPropertyDescription alloc] init] autorelease];
[fetchedPropertyDescription setFetchRequest:fetchRequest];
[fetchedPropertyDescription setName:@"myFetchedProperty"];

NSEntityDescription *entityDescription = [entitiesByName objectForKey:@"MyFetchSourceEntity"];

[entityDescription setProperties:[[entityDescription properties] arrayByAddingObject:fetchedPropertyDescription]];
</code>```

When I call

```<code>[fetchedPropertyDescription setFetchRequest:fetchRequest];
</code>```

I get the following exception:

```<code>NSInvalidArgumentException: Can't use fetch request with fetched property description (entity model mismatch).
</code>```

答:
You can't alter a managed object model once it has been used to create an object graph i.e. after there is context or a store that uses it. The model defines the properties and relationships of all the objects in the graph. If you change it on the fly the graph turns into gibberish.

This applies to fetched properties as well. From the NSFetchProperyDescription docs:

Fetched Property descriptions are
  editable until they are used by an
  object graph manager. This allows you
  to create or modify them dynamically.
  However, once a description is used
  (when the managed object model to
  which it belongs is associated with a
  persistent store coordinator), it must
  not (indeed cannot) be changed. This
  is enforced at runtime: any attempt to
  mutate a model or any of its subjects
  after the model is associated with a
  persistent store coordinator causes an
  exception to be thrown. If you need to
  modify a model that is in use, create
  a copy, modify the copy, and then
  discard the objects with the old
  model.

Body:
I have a pre-existing NSManagedObjectModel that I created with the Xcode GUI.  I want to create a sorted fetched property, which Xcode 3.2's GUI doesn't support.  I do all of this before creating my NSPersistentStoreCoordinator because I know you can't modify a NSManagedObjectModel after an object graph manager has started using it.  I created the NSFetchedPropertyDescription thusly:

NSManagedObjectModel *managedObjectModel = ... // fetch from my mainBundle

NSEntityDescription *fetchedPropertyEntityDescription = [entitiesByName objectForKey:@"MyEntity"];

NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
[fetchRequest setEntity:fetchedPropertyEntityDescription];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"myPredicateProperty == $FETCH_SOURCE"]];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"mySortProperty" ascending:YES]]];

NSFetchedPropertyDescription *fetchedPropertyDescription = [[[NSFetchedPropertyDescription alloc] init] autorelease];
[fetchedPropertyDescription setFetchRequest:fetchRequest];
[fetchedPropertyDescription setName:@"myFetchedProperty"];

NSEntityDescription *entityDescription = [entitiesByName objectForKey:@"MyFetchSourceEntity"];

[entityDescription setProperties:[[entityDescription properties] arrayByAddingObject:fetchedPropertyDescription]];

When I call

[fetchedPropertyDescription setFetchRequest:fetchRequest];

I get the following exception:

NSInvalidArgumentException: Can't use fetch request with fetched property description (entity model mismatch).


问:
Sum of two queries
My table looks like this:

I made two queries:

```<code>SELECT COUNT(column_1) AS result_1 FROM table WHERE column_1= 5;
SELECT COUNT(column_2) AS result_2 FROM table WHERE column_2 = 5;
</code>```

The first query gives me result_1 = 2, and the second result_2 = 3

I need to make a query that will give me the sum of these two (2+3=5).
I always get two results or just one of them.

答:
Each of these expressions:

```<code>column_1 = 5
</code>```

and

```<code>column_2 = 5
</code>```

evaluates to 0 or 1 (false or true).

So you can use them like this:

```<code>SELECT SUM(column_1 = 5) + SUM(column_2 = 5) AS result FROM table
</code>```

See the demo.

Result:

```<code>| result |
| ------ |
| 5      |
</code>```

Title: Sum of two queries

Body:
My table looks like this:

I made two queries:

SELECT COUNT(column_1) AS result_1 FROM table WHERE column_1= 5;
SELECT COUNT(column_2) AS result_2 FROM table WHERE column_2 = 5;

The first query gives me result_1 = 2, and the second result_2 = 3

I need to make a query that will give me the sum of these two (2+3=5).
I always get two results or just one of them.

Body:
Each of these expressions:

column_1 = 5

and

column_2 = 5

evaluates to 0 or 1 (false or true).

So you can use them like this:

SELECT SUM(column_1 = 5) + SUM(column_2 = 5) AS result FROM table

See the demo.

Result:

| result |
| ------ |
| 5      |


问:
Error:(29, 34) Type mismatch: inferred type is String? but Editable! was expected
```<code>package com.example.acer.test

import android.content.Context
import android.content.SharedPreferences
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private var sharedP: SharedPreferences? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btn_add.setOnClickListener {
            sharedP = getSharedPreferences("addData", Context.MODE_PRIVATE)
            var myEditor = sharedP?.edit()
            myEditor?.putString("product_name" , et_productname.text.toString())
            myEditor?.commit()
            Toast.makeText(this@MainActivity, "The product is saved" , Toast.LENGTH_SHORT).show()

        }
        btn_get.setOnClickListener {
            et_getproduct.text = sharedP?.getString("product_name","null")
        }

    }
}
</code>```

I need to read a string from Shared preferences in Kotlin but it is showing the following error : Error:(29, 34) Type mismatch: inferred type is String? but Editable! was expected

答:
You can create an extension method like this:

```<code>fun String.toEditable(): Editable = Editable.Factory.getInstance().newEditable(this)
</code>```

and then change your code like this:

```<code>btn_get.setOnClickListener {
            et_getproduct.text = sharedP?.getString("product_name","null").toEditable()
        }
</code>```

This is what I used and it works great

Body:
package com.example.acer.test

import android.content.Context
import android.content.SharedPreferences
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private var sharedP: SharedPreferences? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btn_add.setOnClickListener {
            sharedP = getSharedPreferences("addData", Context.MODE_PRIVATE)
            var myEditor = sharedP?.edit()
            myEditor?.putString("product_name" , et_productname.text.toString())
            myEditor?.commit()
            Toast.makeText(this@MainActivity, "The product is saved" , Toast.LENGTH_SHORT).show()

        }
        btn_get.setOnClickListener {
            et_getproduct.text = sharedP?.getString("product_name","null")
        }

    }
}

I need to read a string from Shared preferences in Kotlin but it is showing the following error : Error:(29, 34) Type mismatch: inferred type is String? but Editable! was expected

Body:
You can create an extension method like this:

fun String.toEditable(): Editable = Editable.Factory.getInstance().newEditable(this)

and then change your code like this:

btn_get.setOnClickListener {
            et_getproduct.text = sharedP?.getString("product_name","null").toEditable()
        }

This is what I used and it works great


问:
Java -> Context, Expression expected?
I'm trying to learn and make an Android app via Java and Android Studio. My extent of Java is a few hours of youtube studying and a basic college course two years ago. I do know how to code however. I'm proficient with Python.

I wish to use this bluetooth library (https://github.com/akexorcist/Android-BluetoothSPPLibrary) so that I can communicate simply between a phone and a bluetooth enabled ESP32 microcontroller.

In my project I created a button which I'll use for testing this library.

```<code>*snip*
        //my button
        Button btn = findViewById(R.id.myBtn); //use R.id for the button id
        btn.setOnClickListener(new View.OnClickListener() { //button listener
            @Override
            public void onClick(View v) {
                //add whatever code here
                Log.e("my app", "log msg test"); //outputs to logcat window
                BluetoothSPP bt = new BluetoothSPP(Context);

                if(!bt.isBluetoothAvailable()) {
                    Log.e("my app", "bluetooth is not available");
                } else {
                    Log.e("my app", "bluetooth is available");
                }

            }
*snip*
</code>```

I'm stuck on:

```<code>BluetoothSPP bt = new BluetoothSPP(Context);
</code>```

Context gives me an error saying expression expected. I looked up what Context is in Java and understand why that would be a thing. However, I have no idea how to implement it, let alone, the proper context here.

答:
If it is for activity

```<code>BluetoothSPP bt = new BluetoothSPP(MainActivity.this);
or
BluetoothSPP bt = new BluetoothSPP(this);
or
BluetoothSPP bt = new BluetoothSPP(getApplicationContext());
</code>```

If it for fragment

```<code>BluetoothSPP bt = new BluetoothSPP(getActivty());
</code>```

Title: Java -> Context, Expression expected?

Body:
I'm trying to learn and make an Android app via Java and Android Studio. My extent of Java is a few hours of youtube studying and a basic college course two years ago. I do know how to code however. I'm proficient with Python.

I wish to use this bluetooth library (https://github.com/akexorcist/Android-BluetoothSPPLibrary) so that I can communicate simply between a phone and a bluetooth enabled ESP32 microcontroller.

In my project I created a button which I'll use for testing this library.

*snip*
        //my button
        Button btn = findViewById(R.id.myBtn); //use R.id for the button id
        btn.setOnClickListener(new View.OnClickListener() { //button listener
            @Override
            public void onClick(View v) {
                //add whatever code here
                Log.e("my app", "log msg test"); //outputs to logcat window
                BluetoothSPP bt = new BluetoothSPP(Context);

                if(!bt.isBluetoothAvailable()) {
                    Log.e("my app", "bluetooth is not available");
                } else {
                    Log.e("my app", "bluetooth is available");
                }

            }
*snip*

I'm stuck on:

BluetoothSPP bt = new BluetoothSPP(Context);

Context gives me an error saying expression expected. I looked up what Context is in Java and understand why that would be a thing. However, I have no idea how to implement it, let alone, the proper context here.

Body:
If it is for activity

BluetoothSPP bt = new BluetoothSPP(MainActivity.this);
or
BluetoothSPP bt = new BluetoothSPP(this);
or
BluetoothSPP bt = new BluetoothSPP(getApplicationContext());

If it for fragment

BluetoothSPP bt = new BluetoothSPP(getActivty());


问:
Subquery in knex.js or direct postgresql queries in knex.js using raw or any alternative ways
I'm currently working in a express.js project and using knex for database migration and queries .i'm having trouble in writing the queries to get exact result which i got in postgresql (dbeaver). Below given the query which i need to convert to knex query(from a table ).Actually wants to get the count of column based on the different values of a column(applications)

```<code>select count(job_id) as total_applicants ,

(select count(job_id) from applications as APPL join
recruiter_positions as POS on POS.position_id=APPL.job_id
where APPL.state='qualified' and POS.creator_id='e5f604be-e773-490b-
a525-fad3b95fd941') as qlCount,
(select count(job_id) from applications as APPL join
recruiter_positions as POS on POS.position_id=APPL.job_id
where APPL.state='backup' and POS.creator_id='e5f604be-e773-490b-a525-
fad3b95fd941') as bckCount,
(select count(job_id) from applications as APPL join
recruiter_positions as POS on POS.position_id=APPL.job_id
where APPL.state='interview' and POS.creator_id='e5f604be-e773-490b-
a525-fad3b95fd941') as intrCount,
(select count(job_id) from applications as APPL join
recruiter_positions as POS on POS.position_id=APPL.job_id
where APPL.state='offer' and POS.creator_id='e5f604be-e773-490b-a525-
fad3b95fd941') as offrCount,
(select count(job_id) from applications as APPL join
recruiter_positions as POS on POS.position_id=APPL.job_id
where APPL.state='screening' and POS.creator_id='e5f604be-e773-490b-
a525-fad3b95fd941') as screenCount,
(select count(job_id) from applications as APPL join
recruiter_positions as POS on POS.position_id=APPL.job_id
where APPL.state='rejected' and POS.creator_id='e5f604be-e773-490b-
a525-fad3b95fd941') as rejectedCount

from applications as APPL join recruiter_positions as POS on
POS.position_id=APPL.job_id
where APPL.state notnull and POS.creator_id='e5f604be-e773-490b-a525-
fad3b95fd941'
</code>```

答:
Without converting the entire thing for you, here's how subqueries work in Knex.

Each query returns an instance of the Knex query builder, which we alias with .as. So it's pretty easy to build them up gradually:

```<code>const subquery1 = knex("foos").count("*").as("foocount");
const subquery2 = knex("bars").count("*").as("barcount");
knex.select(subquery1, subquery2).then(console.log);
</code>```

Body:
I'm currently working in a express.js project and using knex for database migration and queries .i'm having trouble in writing the queries to get exact result which i got in postgresql (dbeaver). Below given the query which i need to convert to knex query(from a table ).Actually wants to get the count of column based on the different values of a column(applications)

select count(job_id) as total_applicants ,

(select count(job_id) from applications as APPL join
recruiter_positions as POS on POS.position_id=APPL.job_id
where APPL.state='qualified' and POS.creator_id='e5f604be-e773-490b-
a525-fad3b95fd941') as qlCount,
(select count(job_id) from applications as APPL join
recruiter_positions as POS on POS.position_id=APPL.job_id
where APPL.state='backup' and POS.creator_id='e5f604be-e773-490b-a525-
fad3b95fd941') as bckCount,
(select count(job_id) from applications as APPL join
recruiter_positions as POS on POS.position_id=APPL.job_id
where APPL.state='interview' and POS.creator_id='e5f604be-e773-490b-
a525-fad3b95fd941') as intrCount,
(select count(job_id) from applications as APPL join
recruiter_positions as POS on POS.position_id=APPL.job_id
where APPL.state='offer' and POS.creator_id='e5f604be-e773-490b-a525-
fad3b95fd941') as offrCount,
(select count(job_id) from applications as APPL join
recruiter_positions as POS on POS.position_id=APPL.job_id
where APPL.state='screening' and POS.creator_id='e5f604be-e773-490b-
a525-fad3b95fd941') as screenCount,
(select count(job_id) from applications as APPL join
recruiter_positions as POS on POS.position_id=APPL.job_id
where APPL.state='rejected' and POS.creator_id='e5f604be-e773-490b-
a525-fad3b95fd941') as rejectedCount

from applications as APPL join recruiter_positions as POS on
POS.position_id=APPL.job_id
where APPL.state notnull and POS.creator_id='e5f604be-e773-490b-a525-
fad3b95fd941'

Body:
Without converting the entire thing for you, here's how subqueries work in Knex.

Each query returns an instance of the Knex query builder, which we alias with .as. So it's pretty easy to build them up gradually:

const subquery1 = knex("foos").count("*").as("foocount");
const subquery2 = knex("bars").count("*").as("barcount");
knex.select(subquery1, subquery2).then(console.log);


问:
What happens to a Startup IPI sent to an Active AP that is not in a Wait-for-SIPI state
In a previous Stackoverflow answer Margaret Bloom says:

Waking the APs

This is achieved by inssuing a INIT-SIPI-SIPI (ISS) sequence to the all the APs.

The BSP that will send the ISS sequence using as destination the
  shorthand All excluding self, thereby targeting all the APs.

A SIPI (Startup Inter Processor Interrupt) is ignored by all the CPUs
  that are waked by the time they receive it, thus the second SIPI is
  ignored if the first one suffices to wake up the target processors. It
  is advised by Intel for compatibility reason.

I've been doing multi processing code for years and my observation of hardware has been that on some processors it seems different than stated. I'm pretty sure I've observed Application Processors (AP) have their Instruction Pointer modified upon receipt of Startup IPI even when it was active (not in a Wait-for-Startup-IPI).

Is there any Intel documentation that states what an AP will do upon a receipt of a Startup IPI when not in a Wait-for-Startup-IPI state, or documents the behaviour as undefined? I can't seem to find a definitive answer in the Intel Software Documentation Manuals or the supplementary Intel document Minimal Boot Loader for Intel® Architecture.

Generally I write the initialization code to initialize and start an AP by assuming that the AP may get a SIPI and have its Instruction Pointer reset while in an active state (not in a Wait-for-Startup-IPI state).

I'm trying to determine the accuracy of Margaret Bloom's statement that a second Startup IPI will be ignored by an AP that has been previously awoken.

答:
I consider my statement correct, up to bugs.

I don't claim that buggy hardware should be ignored but that their impact must first evaluated.

I'd like the remind the reader that while I have an opinionated position on the matter, I wanted this answer to be as neutral as possible.

To full fill this purpose I tried to provide sources for my statements.

While I do trust other users experiences I cannot base my belief on memories alone (for they cannot be verified)1 and I'm looking forward for someone to correct my quoted statement with proofs.

I understand this is an unpopular view, I hope it just won't pass as totally wrong.

First of all, as usual with computers it all boils down to standards. While Intel documents the MP behaviour of their CPUs in the manuals, there went a step further and made a proper MultiProcessor specification.

The importance of this specification is its role in the industry, this is not how Intel's CPUs work, this is, as far as i known, the only x86 SMP industry reference.

AMD and Cyrix pushed the OpenPIC specification but quoting Wikipedia:

No x86 motherboard was released with OpenPIC however.[3] After the OpenPIC's failure in the x86 market, AMD licensed the Intel APIC Architecture for its AMD Athlon and later processors.

In the Appendix B4 of the MP-specification is present the line

If the
  target processor is in the halted state immediately after RESET or INIT, a STARTUP IPI causes it
  to leave that state and start executing. The effect is to set CS:IP to VV00:0000h.

As noted in the comment I've parsed the if as a stronger *iif.

Unfortunately, the quoted sentence, as stated, is only a sufficient condition. So it cannot be used to deduce the behaviour of a SIPI on a running CPU.

However I personally believe this is a mistake, the intent of the authors of the specification is to use the SIPI to wake up a CPU in the wait-for-SIPI state.

The SIPI was specifically introduced with the advent of integrated APICs, along with a revision of the INIT IPI, to manage the booting of the APs.

The SIPI has no effect on the BSP (which never enters the wait-for-SIPI state according to Intel's manuals) and it's clear that is should have no affect on a running CPU.

The usefulness of the SIPI, besides being non-maskeable and not requiring the LAPIC to be enabled, is that is avoid running from the reset vector and the need for the warm boot flag for APs.

It makes no sense, from a design perspective, to let SIPI act on running CPUs. CPUs are always restarted with an INIT IPI as the first IPI.

So, I'm confident in parsing the quoted statement as colloquial English with the tacit agreement that it is also a necessary condition.

I believe this sets the official behaviour of SIPI on a woke-up CPU, namely to ignore them.

Fact 1: There is a industry-standard MP specification followed by all major x86 manufacturers, though being ambiguous, it's intent is to set the behaviour of SIPIs.

Page 98 of the Pentium Spec Update seems to confirm that, at least for the Pentium (an presumably for later Intel generations, which may include AMDs since they have bought a license for the LAPIC from Intel):

If an INIT IPI is then sent to the halted upgrade component, it will be latched and kept pending until a
  STARTUP IPI is received. From the time the STARTUP IPI is received the CPU will respond to further INIT IPls
  but will ignore any STARTUP IPls. It will not respond to future STARTUP IPls until a RESET assertion or an
  INIT assertion (INIT Pin or INIT IPI) happens again.

The 75-, 90, and 100-MHz Pentium processors, when used as a primary processor, will never respond to a
  STARTUP IPI at any time. It will ignore the STARTUP IPI with no effects.

To shutdown the processors the operating system should only use the INIT IPI, STARTUP IPls should never be
  used once the processors are running.

This doesn't settle the question if there are CPUs where subsequent IPIs are not ignored.

While this question is still to be addressed, we have, by now, turned it into the question "Are there buggy CPUs that ... ?".

This is an huge leap-forward because we can now see how existing OSes deal with it.

I won't discuss Windows, while I recognise this is a big absence I'm not in the mood of digging into Windows binaries right now.

I may do it later.

Linux

Linux sends two SIPIs and I don't see any feedback in this loop.  The code is in smpboot.c where we clearly see that num_starts is set to 2.

I won't discuss the difference between the LAPIC and the 82489DX APIC, particularly that the latter didn't have SIPI2.

We can however see how Linux follow the Intel's algorithm and it is not worried by the second SIPI.

In the loop, executed num_starts time, a SIPI is sent to the target AP.

In the comments has been pointed out that the trampoline is idempotent and that Linux as a synchronisation mechanism.

That doesn't match with my experience, of course Linux synchronises code between CPUs but that's done later in the boot after the AP is running.

In fact the trampoline the first C code the AP executes is  start_secondary and it doesn't seem idempotent (set_cpu_online is called later in the body, if that counts).

Finally, if the programmers wanted to prevent a double SIPI they'd put the synchronisation logic as early as possible to avoid dealing with complex situations later.

The trampoline goes as far as dealing with SME and vulnerabilities fixes, why would one want to do that before dealing with the SIPI-SIPI issue?

It makes no sense to me to have such a critical check so late.

Free BSD

I wanted to include a BSD OS because BSD code is known to be very clean and robust.

I was able to found a GitHub (unofficial) repository with the Free BSD source and while I'm less confident with that code I've found the routine that starts an AP in mp_x86.c.

Free BSD also uses the Intel's algorithm.
To my amusement, the source also explains why there is the need for a second SIPI: the P5 processor (The P54C Pentium family?) did ignore the first SIPI due to a bug:

/*

       * next we do a STARTUP IPI: the previous INIT IPI might still be

       * latched, (P5 bug) this 1st STARTUP would then terminate

       * immediately, and the previously started INIT IPI would continue. OR

       * the previous INIT IPI has already run. and this STARTUP IPI will

       * run. OR the previous INIT IPI was ignored. and this STARTUP IPI

       * will run.

       */

I was unable to find the source for this statement, the only clue I have is the errata AP11 of the Pentium Specification Update found on an old android (i.e. Linux) kernel.

Today Linux seems to have dropped the support for those old buggy LAPICs.

Considering the detailed comments I don't see the need to check for the idempotency of the code up to an hypothetical check.

The BSD code is clearly written with the commented assumptions in mind.

Fact 2: Two mainstream OSes don't consider SIPI bugs occurring often enough to be worth handling.

While searching the Internet I've found a commit in the gem5 simulator with the title X86: Only recognize the first startup IPI after INIT or reset.

Apparently, they got it wrong at first and then fixed it.

Next step is trying to find some online documentation.

I first searched in Google Patents and while a lot of interesting results pop up (including how the APIC IDs are assigned), regarding SIPIs I only found this text in the patent Method and apparatus for initiating execution of an application processor in a clustered multiprocessor system:

STARTUP IPIs do not cause any change of State in the target processor (except for the change to the instruction pointer), and can be issued only one time after RESET or after an INIT IPI reception or pin assertion.

Wikipedia lists VIA as the only other x86 manufacturer still present..

I tried looking for VIA manuals, but it seems they are not public?

About the past manufacturers, I was unable to find if any ever produced MP CPUs at all. E.g. Cyrix 6x86MX didn't have an APIC at all, so they may have been put in a MP system only by an external APIC (which couldn't support SIPIs).

Next step would be to look at all of the AMD and Intel errata and see if there's something about the SIPIs.

However, errata are bugs and so the question turns into a search for a proof of non-existence (i.e. do bugged LAPICs exist?) which is hard to find (simply because bugs are hard to find and there are many micro-architectures).

My understanding is that the first integrated APIC (an LAPIC as known today) shipped with the P54C, I've consulting the errata but found nothing regarding the handling of SIPIs.

However understanding the errata in their full consequences is not trivial.

I've then moved to the Pentium Pro Errata (which is the next uarch, the P6) and found an incorrect handling of the SIPIs though not exactly what we are looking for:

3AP.  INIT_IPI After STARTUP_IPI-STARTUP_IPI Sequence May Cause

AP to Execute at 0h**

  PROBLEM: The MP Specification states that to wake up an application processor (AP), the interprocessor
  interrupt sequence INIT_IPI, STARTUP_IPI, STARTUP_IPI should be sent to that processor. On the Pentium
  Pro processor, an INIT_IPI, STARTUP_IPI sequence will also work. However, if the INIT_IPI, STARTUP_IPI,
  STARTUP_IPI sequence is sent to an AP, an internal race condition may occur in the APIC logic which leaves
  the processor in an incorrect state. Operation will be correct in this state, but if another INIT_IPI is sent to the
  processor, the processor will not stop execution as expected, and will instead begin execution at linear address
  0h. In order for the race condition to cause this incorrect state, the system’s core to bus clock ratio must be 5:2
  or greater.

IMPLICATION: If a system is using a core to bus clock ratio of 5:2 or greater, and the sequence INIT_IPI,
  STARTUP_IPI, STARTUP_IPI is generated on the APIC bus to wake up an AP, and then at some later time
  another INIT_IPI is sent to the processor, that processor may attempt to execute at linear address 0h, and will
  execute random opcodes. Some operating systems do generate this sequence when attempting to shut the
  system down, and in a multiprocessor system, may hang after taking the processors offline. The effect seen will
  be that the OS may not restart the system if ‘shutdown and restart’ or the equivalent is selected upon exiting the
  operating system. If an operating system gives the user the capability to take an AP offline using an INIT_IPI
  (Intel has not identified any operating systems which currently have this capability), this option should not be
  used.

WORKAROUND: BIOS code should execute a single STARTUP_IPI to wake up an application processor.
  Operating systems, however, will issue an INIT_IPI, STARTUP_IPI, STARTUP_IPI sequence, as recommended
  in the MP specification. It is possible that BIOS code may contain a workaround for this erratum in systems with
  C0 or subsequent steppings of Pentium Pro processor silicon. No workaround is available for the B0 stepping of
  the Pentium Pro processor.

STATUS: For the steppings affected see the Summary Table of Changes at the beginning of this section.

This AP3 erratum is interesting because:

It confirms that an INIT-SIPI sequence is enough to startup an AP. This was evident from the MP specification and from the Free BSD code.

It may lead to a behaviour similar to a restart. The bug will make an INIT IPI (after the INIT-SIPI-SIPI sequence) restart the AP at 0h (linear, presumably after the initialisation).

 If the BIOS uses the INIT-SIPI-SIPI to use the APs and later the OS attempts to use that sequence again, the first INIT will start the AP.

 However, this won't lead to a predictable behaviour unless the LAPIC is left in a corrupted state where any SIPI will be accepted.

Funny enough, in the same errata there is even a bug causing "the opposite behaviour": 8AP. APs Do Not Respond to a STARTUP_IPI After an INIT# or INIT_IPI
in Low Power Mode

I've also checked the Pentium II, Pentium II Xeon, Pentium III, Pentium 4 errata and found nothing new about SIPIs.

To my understanding, the first AMD processor capable of SMP was the Athlon MP based on the Palomino uarch.

I've checked the revision guide for the Athlon MP and found nothing, checked the revisions in this list and found nothing.

Unfortunately I have little experience with non AMD non Intel x86 CPUs. I was unable to find which secondary manufactures included an LAPIC.

Fact 3: Official documentation from non AMD/Intel manufacturers is hard to find and errata are not easily searchable. No errata contains a bug related to the acceptance of the SIPI on a running processor but numerous LAPIC bugs are present making plausible the existence of such bugs.

Final step would be a hardware test.

While this test cannot rule out the presence of other behaviour, at least is documented (crappy) code.

Documented code is good because it can be used to repeat an experiment by other researchers, it can be scrutinised for bugs and constitute a proof.

In short, it is scientific.

I have never seen a CPU where subsequent SIPIs restarted it but this doesn't matter because it suffices to have a single buggy CPU to confirm the presence of the bug.

I'm too young, too poor and too human to have conducted an extensive, bug-free, analysis of all the MP CPUs.

So, instead, I made a test and run it.

Fact 4: Whiskey lake, Haswell, Kaby lake and Ivy Bridge all ignore subsequent SIPIs.

Other people are welcome to test on AMD's and older CPUs.

Again this doesn't constitute a proof but it's important to frame the state of the matter correctly.

The more data we have the more accurate knowledge of the bug we get.

The test consist in bootstrapping the APs and making them increment a counter and enter an infinite loop (either with jmp $ or with hlt, the result is the same).

Meanwhile the BSP will send a SIPI each n seconds, where n is at least 2  (but it may be more due to the very imprecise timing mechanism), and print the counter.

If the counter stays at k-1, where k is the number of APs, then the secondary SIPI are ignored.

There are some technical details to address.

First, the bootloader is legacy (not UEFI) and I didn't want to read another sector so I wanted it to fit in 512 bytes and so I shared the booting sequence between the BSP and the APs.

Second, some code must be executed only by the BSP but before entering in protected mode (e.g. video mode setting) so I used a flag (init) instead of checking the BSP flag in the IA32_APIC_BASE_MSR register (which is done later to diverge the APs from the BSP).

Third, I've took some shortcuts. The SIPI bootups the CPU at 8000h so I put a far jump there to 0000h:7c00h. The timing is done with the port 80h trick and it is very imprecise but should suffice. The GDT uses the null entry.  The counter is printed a few lines below the top to avoid being cropped by some monitor.

If the loop is modified to include the INIT IPI, the counter is incremented regularly.

Please note that this code is without support.

```<code>BITS 16
ORG 7c00h

%define IA32_APIC_BASE_MSR 1bh
%define SVR_REG 0f0h
%define ICRL_REG 0300h
%define ICRH_REG 0310h

xor ax, ax
mov ds, ax
mov ss, ax
xor sp, sp      ;This stack ought be enough

cmp BYTE [init], 0
je _get_pm

;Make the trampoline at 8000h
mov BYTE [8000h], 0eah
mov WORD [8001h], 7c00h
mov WORD [8003h], 0000h

mov ax, 0b800h
mov es, ax
mov ax, 0003h
int 10h
mov WORD [es:0000], 0941h

mov BYTE [init], 0

_get_pm:
;Mask interrupts
mov al, 0ffh
out 21h, al
out 0a1h, al

;THIS PART TO BE TESTED
;
;CAN BE REPLACED WITH A cli, SIPIs ARE NOT MASKEABLE
;THE cli REMOVES THE NEED FOR MASKING THE INTERRUPTS AND
;CAN BE PLACED ANYWHERE BEFORE ENTERING PM (BUT LEAVE xor ax, ax
;AS THE FIRST INSTRUCTION)

;Flush pending ones (See Michael Petch's comments)
sti
mov cx, 15
loop $

lgdt [GDT]
mov eax, cr0
or al, 1
mov cr0, eax
sti

mov ax, 10h
mov es, ax
mov ds, ax
mov ss, ax
jmp 08h:DWORD __START32__

__START32__:
 BITS 32

 mov ecx, IA32_APIC_BASE_MSR
 rdmsr
 or ax, (1<<11)          ;ENABLE LAPIC
 mov ecx, IA32_APIC_BASE_MSR
 wrmsr

 mov ebx, eax
 and ebx, 0ffff_f000h    ;APIC BASE

 or DWORD [ebx+SVR_REG], 100h

 test ax, 100h
 jnz __BSP__

__AP__:
 lock inc BYTE [counter]

 jmp $            ;Don't use HLT just in case

__BSP__:
 xor edx, edx
 mov DWORD [ebx+ICRH_REG], edx
 mov DWORD [ebx+ICRL_REG], 000c4500h        ;INIT

 mov ecx, 10_000
.wait1:
 in al, 80h
 dec ecx
jnz .wait1

.SIPI_loop:
 movzx eax, BYTE [counter]
 mov ecx, 100
 div ecx
 add ax, 0930h
 mov WORD [0b8000h + 80*2*5], ax

 mov eax, edx
 xor edx, edx
 mov ecx, 10
 div ecx
 add ax, 0930h
 mov WORD [0b8000h + 80*2*5 + 2], ax

 mov eax, edx
 xor edx, edx
 add ax, 0930h
 mov WORD [0b8000h + 80*2*5 + 4], ax

 xor edx, edx
 mov DWORD [ebx+ICRH_REG], edx
 mov DWORD [ebx+ICRL_REG], 000c4608h        ;SIPI at 8000h

 mov ecx, 2_000_000
.wait2:
 in al, 80h
 dec ecx
jnz .wait2

jmp .SIPI_loop

GDT dw 17h
    dd GDT
    dw 0

    dd 0000ffffh, 00cf9a00h
    dd 0000ffffh, 00cf9200h

counter db 0
init db 1

TIMES 510-($-$$) db 0
dw 0aa55h
</code>```

Conclusions

No definitive conclusion can be draw, the matter is still open.

The reader has been presented with a list of facts.

The intended behaviour is to ignore subsequent SIPIs, the need for two SIPI is due to a "P5 bug".

Linux and Free BSD don't seem to mind about buggy SIPI handling.

Other manufacturers seems to provide no documentation on their LAPICs if they produce any on their own.

Recent Intel's hardware ignore subsequent SIPIs.

1With due respect to all people involved and without attacking anyone credibility. I do believe there are buggy CPUs out there but there are also buggy software and buggy memories.  As I don't trust my own old memories I think I'm still within the bounds of a respectful conversation to ask others to no trust their vague ones.

2 Possibly because MP in those days was done with regular CPUs packed together and asserting their INIT# with an external chip (the APIC) was the only way to start them up (along with setting a warm reset vector).  However in those years I was too young to have a computer.

According to my testing, SIPIs are ignored when not in a wait-for-SIPI state.
I've tested a Whiskey-lake 8565U, of course real-hardware test doesn't constitute a proof.

I'm confident that all the Intel's processors since the Pentium 4 also have the same behaviour but this is just my view.

In this answer I solely want to present the result of a test. Everyone will draw their own conclusions.

Body:
I consider my statement correct, up to bugs.

I don't claim that buggy hardware should be ignored but that their impact must first evaluated.

I'd like the remind the reader that while I have an opinionated position on the matter, I wanted this answer to be as neutral as possible.

To full fill this purpose I tried to provide sources for my statements.

While I do trust other users experiences I cannot base my belief on memories alone (for they cannot be verified)1 and I'm looking forward for someone to correct my quoted statement with proofs.

I understand this is an unpopular view, I hope it just won't pass as totally wrong.

First of all, as usual with computers it all boils down to standards. While Intel documents the MP behaviour of their CPUs in the manuals, there went a step further and made a proper MultiProcessor specification.

The importance of this specification is its role in the industry, this is not how Intel's CPUs work, this is, as far as i known, the only x86 SMP industry reference.

AMD and Cyrix pushed the OpenPIC specification but quoting Wikipedia:

No x86 motherboard was released with OpenPIC however.[3] After the OpenPIC's failure in the x86 market, AMD licensed the Intel APIC Architecture for its AMD Athlon and later processors.

In the Appendix B4 of the MP-specification is present the line

If the
  target processor is in the halted state immediately after RESET or INIT, a STARTUP IPI causes it
  to leave that state and start executing. The effect is to set CS:IP to VV00:0000h.

As noted in the comment I've parsed the if as a stronger *iif.

Unfortunately, the quoted sentence, as stated, is only a sufficient condition. So it cannot be used to deduce the behaviour of a SIPI on a running CPU.

However I personally believe this is a mistake, the intent of the authors of the specification is to use the SIPI to wake up a CPU in the wait-for-SIPI state.

The SIPI was specifically introduced with the advent of integrated APICs, along with a revision of the INIT IPI, to manage the booting of the APs.

The SIPI has no effect on the BSP (which never enters the wait-for-SIPI state according to Intel's manuals) and it's clear that is should have no affect on a running CPU.

The usefulness of the SIPI, besides being non-maskeable and not requiring the LAPIC to be enabled, is that is avoid running from the reset vector and the need for the warm boot flag for APs.

It makes no sense, from a design perspective, to let SIPI act on running CPUs. CPUs are always restarted with an INIT IPI as the first IPI.

So, I'm confident in parsing the quoted statement as colloquial English with the tacit agreement that it is also a necessary condition.

I believe this sets the official behaviour of SIPI on a woke-up CPU, namely to ignore them.

Fact 1: There is a industry-standard MP specification followed by all major x86 manufacturers, though being ambiguous, it's intent is to set the behaviour of SIPIs.

Page 98 of the Pentium Spec Update seems to confirm that, at least for the Pentium (an presumably for later Intel generations, which may include AMDs since they have bought a license for the LAPIC from Intel):

If an INIT IPI is then sent to the halted upgrade component, it will be latched and kept pending until a
  STARTUP IPI is received. From the time the STARTUP IPI is received the CPU will respond to further INIT IPls
  but will ignore any STARTUP IPls. It will not respond to future STARTUP IPls until a RESET assertion or an
  INIT assertion (INIT Pin or INIT IPI) happens again.

The 75-, 90, and 100-MHz Pentium processors, when used as a primary processor, will never respond to a
  STARTUP IPI at any time. It will ignore the STARTUP IPI with no effects.

To shutdown the processors the operating system should only use the INIT IPI, STARTUP IPls should never be
  used once the processors are running.

This doesn't settle the question if there are CPUs where subsequent IPIs are not ignored.

While this question is still to be addressed, we have, by now, turned it into the question "Are there buggy CPUs that ... ?".

This is an huge leap-forward because we can now see how existing OSes deal with it.

I won't discuss Windows, while I recognise this is a big absence I'm not in the mood of digging into Windows binaries right now.

I may do it later.

Linux

Linux sends two SIPIs and I don't see any feedback in this loop.  The code is in smpboot.c where we clearly see that num_starts is set to 2.

I won't discuss the difference between the LAPIC and the 82489DX APIC, particularly that the latter didn't have SIPI2.

We can however see how Linux follow the Intel's algorithm and it is not worried by the second SIPI.

In the loop, executed num_starts time, a SIPI is sent to the target AP.

In the comments has been pointed out that the trampoline is idempotent and that Linux as a synchronisation mechanism.

That doesn't match with my experience, of course Linux synchronises code between CPUs but that's done later in the boot after the AP is running.

In fact the trampoline the first C code the AP executes is  start_secondary and it doesn't seem idempotent (set_cpu_online is called later in the body, if that counts).

Finally, if the programmers wanted to prevent a double SIPI they'd put the synchronisation logic as early as possible to avoid dealing with complex situations later.

The trampoline goes as far as dealing with SME and vulnerabilities fixes, why would one want to do that before dealing with the SIPI-SIPI issue?

It makes no sense to me to have such a critical check so late.

Free BSD

I wanted to include a BSD OS because BSD code is known to be very clean and robust.

I was able to found a GitHub (unofficial) repository with the Free BSD source and while I'm less confident with that code I've found the routine that starts an AP in mp_x86.c.

Free BSD also uses the Intel's algorithm.
To my amusement, the source also explains why there is the need for a second SIPI: the P5 processor (The P54C Pentium family?) did ignore the first SIPI due to a bug:

/*

       * next we do a STARTUP IPI: the previous INIT IPI might still be

       * latched, (P5 bug) this 1st STARTUP would then terminate

       * immediately, and the previously started INIT IPI would continue. OR

       * the previous INIT IPI has already run. and this STARTUP IPI will

       * run. OR the previous INIT IPI was ignored. and this STARTUP IPI

       * will run.

       */

I was unable to find the source for this statement, the only clue I have is the errata AP11 of the Pentium Specification Update found on an old android (i.e. Linux) kernel.

Today Linux seems to have dropped the support for those old buggy LAPICs.

Considering the detailed comments I don't see the need to check for the idempotency of the code up to an hypothetical check.

The BSD code is clearly written with the commented assumptions in mind.

Fact 2: Two mainstream OSes don't consider SIPI bugs occurring often enough to be worth handling.

While searching the Internet I've found a commit in the gem5 simulator with the title X86: Only recognize the first startup IPI after INIT or reset.

Apparently, they got it wrong at first and then fixed it.

Next step is trying to find some online documentation.

I first searched in Google Patents and while a lot of interesting results pop up (including how the APIC IDs are assigned), regarding SIPIs I only found this text in the patent Method and apparatus for initiating execution of an application processor in a clustered multiprocessor system:

STARTUP IPIs do not cause any change of State in the target processor (except for the change to the instruction pointer), and can be issued only one time after RESET or after an INIT IPI reception or pin assertion.

Wikipedia lists VIA as the only other x86 manufacturer still present..

I tried looking for VIA manuals, but it seems they are not public?

About the past manufacturers, I was unable to find if any ever produced MP CPUs at all. E.g. Cyrix 6x86MX didn't have an APIC at all, so they may have been put in a MP system only by an external APIC (which couldn't support SIPIs).

Next step would be to look at all of the AMD and Intel errata and see if there's something about the SIPIs.

However, errata are bugs and so the question turns into a search for a proof of non-existence (i.e. do bugged LAPICs exist?) which is hard to find (simply because bugs are hard to find and there are many micro-architectures).

My understanding is that the first integrated APIC (an LAPIC as known today) shipped with the P54C, I've consulting the errata but found nothing regarding the handling of SIPIs.

However understanding the errata in their full consequences is not trivial.

I've then moved to the Pentium Pro Errata (which is the next uarch, the P6) and found an incorrect handling of the SIPIs though not exactly what we are looking for:

3AP.  INIT_IPI After STARTUP_IPI-STARTUP_IPI Sequence May Cause

AP to Execute at 0h**

  PROBLEM: The MP Specification states that to wake up an application processor (AP), the interprocessor
  interrupt sequence INIT_IPI, STARTUP_IPI, STARTUP_IPI should be sent to that processor. On the Pentium
  Pro processor, an INIT_IPI, STARTUP_IPI sequence will also work. However, if the INIT_IPI, STARTUP_IPI,
  STARTUP_IPI sequence is sent to an AP, an internal race condition may occur in the APIC logic which leaves
  the processor in an incorrect state. Operation will be correct in this state, but if another INIT_IPI is sent to the
  processor, the processor will not stop execution as expected, and will instead begin execution at linear address
  0h. In order for the race condition to cause this incorrect state, the system’s core to bus clock ratio must be 5:2
  or greater.

IMPLICATION: If a system is using a core to bus clock ratio of 5:2 or greater, and the sequence INIT_IPI,
  STARTUP_IPI, STARTUP_IPI is generated on the APIC bus to wake up an AP, and then at some later time
  another INIT_IPI is sent to the processor, that processor may attempt to execute at linear address 0h, and will
  execute random opcodes. Some operating systems do generate this sequence when attempting to shut the
  system down, and in a multiprocessor system, may hang after taking the processors offline. The effect seen will
  be that the OS may not restart the system if ‘shutdown and restart’ or the equivalent is selected upon exiting the
  operating system. If an operating system gives the user the capability to take an AP offline using an INIT_IPI
  (Intel has not identified any operating systems which currently have this capability), this option should not be
  used.

WORKAROUND: BIOS code should execute a single STARTUP_IPI to wake up an application processor.
  Operating systems, however, will issue an INIT_IPI, STARTUP_IPI, STARTUP_IPI sequence, as recommended
  in the MP specification. It is possible that BIOS code may contain a workaround for this erratum in systems with
  C0 or subsequent steppings of Pentium Pro processor silicon. No workaround is available for the B0 stepping of
  the Pentium Pro processor.

STATUS: For the steppings affected see the Summary Table of Changes at the beginning of this section.

This AP3 erratum is interesting because:

It confirms that an INIT-SIPI sequence is enough to startup an AP. This was evident from the MP specification and from the Free BSD code.

It may lead to a behaviour similar to a restart. The bug will make an INIT IPI (after the INIT-SIPI-SIPI sequence) restart the AP at 0h (linear, presumably after the initialisation).

 If the BIOS uses the INIT-SIPI-SIPI to use the APs and later the OS attempts to use that sequence again, the first INIT will start the AP.

 However, this won't lead to a predictable behaviour unless the LAPIC is left in a corrupted state where any SIPI will be accepted.

Funny enough, in the same errata there is even a bug causing "the opposite behaviour": 8AP. APs Do Not Respond to a STARTUP_IPI After an INIT# or INIT_IPI
in Low Power Mode

I've also checked the Pentium II, Pentium II Xeon, Pentium III, Pentium 4 errata and found nothing new about SIPIs.

To my understanding, the first AMD processor capable of SMP was the Athlon MP based on the Palomino uarch.

I've checked the revision guide for the Athlon MP and found nothing, checked the revisions in this list and found nothing.

Unfortunately I have little experience with non AMD non Intel x86 CPUs. I was unable to find which secondary manufactures included an LAPIC.

Fact 3: Official documentation from non AMD/Intel manufacturers is hard to find and errata are not easily searchable. No errata contains a bug related to the acceptance of the SIPI on a running processor but numerous LAPIC bugs are present making plausible the existence of such bugs.

Final step would be a hardware test.

While this test cannot rule out the presence of other behaviour, at least is documented (crappy) code.

Documented code is good because it can be used to repeat an experiment by other researchers, it can be scrutinised for bugs and constitute a proof.

In short, it is scientific.

I have never seen a CPU where subsequent SIPIs restarted it but this doesn't matter because it suffices to have a single buggy CPU to confirm the presence of the bug.

I'm too young, too poor and too human to have conducted an extensive, bug-free, analysis of all the MP CPUs.

So, instead, I made a test and run it.

Fact 4: Whiskey lake, Haswell, Kaby lake and Ivy Bridge all ignore subsequent SIPIs.

Other people are welcome to test on AMD's and older CPUs.

Again this doesn't constitute a proof but it's important to frame the state of the matter correctly.

The more data we have the more accurate knowledge of the bug we get.

The test consist in bootstrapping the APs and making them increment a counter and enter an infinite loop (either with jmp $ or with hlt, the result is the same).

Meanwhile the BSP will send a SIPI each n seconds, where n is at least 2  (but it may be more due to the very imprecise timing mechanism), and print the counter.

If the counter stays at k-1, where k is the number of APs, then the secondary SIPI are ignored.

There are some technical details to address.

First, the bootloader is legacy (not UEFI) and I didn't want to read another sector so I wanted it to fit in 512 bytes and so I shared the booting sequence between the BSP and the APs.

Second, some code must be executed only by the BSP but before entering in protected mode (e.g. video mode setting) so I used a flag (init) instead of checking the BSP flag in the IA32_APIC_BASE_MSR register (which is done later to diverge the APs from the BSP).

Third, I've took some shortcuts. The SIPI bootups the CPU at 8000h so I put a far jump there to 0000h:7c00h. The timing is done with the port 80h trick and it is very imprecise but should suffice. The GDT uses the null entry.  The counter is printed a few lines below the top to avoid being cropped by some monitor.

If the loop is modified to include the INIT IPI, the counter is incremented regularly.

Please note that this code is without support.

BITS 16
ORG 7c00h

%define IA32_APIC_BASE_MSR 1bh
%define SVR_REG 0f0h
%define ICRL_REG 0300h
%define ICRH_REG 0310h

xor ax, ax
mov ds, ax
mov ss, ax
xor sp, sp      ;This stack ought be enough

cmp BYTE [init], 0
je _get_pm

;Make the trampoline at 8000h
mov BYTE [8000h], 0eah
mov WORD [8001h], 7c00h
mov WORD [8003h], 0000h

mov ax, 0b800h
mov es, ax
mov ax, 0003h
int 10h
mov WORD [es:0000], 0941h

mov BYTE [init], 0

_get_pm:
;Mask interrupts
mov al, 0ffh
out 21h, al
out 0a1h, al

;THIS PART TO BE TESTED
;
;CAN BE REPLACED WITH A cli, SIPIs ARE NOT MASKEABLE
;THE cli REMOVES THE NEED FOR MASKING THE INTERRUPTS AND
;CAN BE PLACED ANYWHERE BEFORE ENTERING PM (BUT LEAVE xor ax, ax
;AS THE FIRST INSTRUCTION)

;Flush pending ones (See Michael Petch's comments)
sti
mov cx, 15
loop $

lgdt [GDT]
mov eax, cr0
or al, 1
mov cr0, eax
sti

mov ax, 10h
mov es, ax
mov ds, ax
mov ss, ax
jmp 08h:DWORD __START32__

__START32__:
 BITS 32

 mov ecx, IA32_APIC_BASE_MSR
 rdmsr
 or ax, (1<<11)          ;ENABLE LAPIC
 mov ecx, IA32_APIC_BASE_MSR
 wrmsr

 mov ebx, eax
 and ebx, 0ffff_f000h    ;APIC BASE

 or DWORD [ebx+SVR_REG], 100h

 test ax, 100h
 jnz __BSP__

__AP__:
 lock inc BYTE [counter]

 jmp $            ;Don't use HLT just in case

__BSP__:
 xor edx, edx
 mov DWORD [ebx+ICRH_REG], edx
 mov DWORD [ebx+ICRL_REG], 000c4500h        ;INIT

 mov ecx, 10_000
.wait1:
 in al, 80h
 dec ecx
jnz .wait1

.SIPI_loop:
 movzx eax, BYTE [counter]
 mov ecx, 100
 div ecx
 add ax, 0930h
 mov WORD [0b8000h + 80*2*5], ax

 mov eax, edx
 xor edx, edx
 mov ecx, 10
 div ecx
 add ax, 0930h
 mov WORD [0b8000h + 80*2*5 + 2], ax

 mov eax, edx
 xor edx, edx
 add ax, 0930h
 mov WORD [0b8000h + 80*2*5 + 4], ax

 xor edx, edx
 mov DWORD [ebx+ICRH_REG], edx
 mov DWORD [ebx+ICRL_REG], 000c4608h        ;SIPI at 8000h

 mov ecx, 2_000_000
.wait2:
 in al, 80h
 dec ecx
jnz .wait2

jmp .SIPI_loop

GDT dw 17h
    dd GDT
    dw 0

    dd 0000ffffh, 00cf9a00h
    dd 0000ffffh, 00cf9200h

counter db 0
init db 1

TIMES 510-($-$$) db 0
dw 0aa55h

Conclusions

No definitive conclusion can be draw, the matter is still open.

The reader has been presented with a list of facts.

The intended behaviour is to ignore subsequent SIPIs, the need for two SIPI is due to a "P5 bug".

Linux and Free BSD don't seem to mind about buggy SIPI handling.

Other manufacturers seems to provide no documentation on their LAPICs if they produce any on their own.

Recent Intel's hardware ignore subsequent SIPIs.

1With due respect to all people involved and without attacking anyone credibility. I do believe there are buggy CPUs out there but there are also buggy software and buggy memories.  As I don't trust my own old memories I think I'm still within the bounds of a respectful conversation to ask others to no trust their vague ones.

2 Possibly because MP in those days was done with regular CPUs packed together and asserting their INIT# with an external chip (the APIC) was the only way to start them up (along with setting a warm reset vector).  However in those years I was too young to have a computer.

According to my testing, SIPIs are ignored when not in a wait-for-SIPI state.
I've tested a Whiskey-lake 8565U, of course real-hardware test doesn't constitute a proof.

I'm confident that all the Intel's processors since the Pentium 4 also have the same behaviour but this is just my view.

In this answer I solely want to present the result of a test. Everyone will draw their own conclusions.