问:
mqtt client does not receive message in case of thread and rest-api
I have a python script, which based on flask and mqtt. The use case is to receive a request via rest-api then to create a new thread which publishes some messages on mosquitto mqtt and expects a response (see subscribe). My problem is that I don't receive any messages. I think it has something to do with the thread, because without the thread it's working very fine..
Do you know what can be the problem?

Thank you in anticipation!

here the code:

```<code>from flask import Flask, Response
import paho.mqtt.client as mqtt
from threading import Thread
import threading

app = Flask(__name__)
lock = threading.Lock()

def on_connect(client, userdata, flags, rc):  # The callback for when the client connects to the broker
    print("Connected with result code {0}".format(str(rc)))  # Print result of connection attempt
    client.subscribe("/mytopic")

def on_message(client, userdata, msg):  # The callback for when a PUBLISH message is received from the server.
    print(msg.topic)

client = mqtt.Client(client_id=client_name, clean_session=True)
client.on_connect = on_connect  # Define callback function for successful connection
client.on_message = on_message  # Define callback function for receipt of a message
client.username_pw_set(mqtt_user, mqtt_password)
client.loop_start()
client.connect(mqtt_host)

def test(param1, param2):
   lock.acquire()
   try:

      ret = client.publish("/mytopic", "")
      while True:
            check the response from mqtt => but i don't get the response anymore
            ....
            break
    finally:
        lock.release()
    return result

@app.route('/test/check', methods=['POST'])
def check():
    global sessionId
    sessionId = sessionId + 1
    t = Thread(target=test, args=(sessionId,None))
    t.start()
    return {'id': sessionId, 'eta': 0}

if __name__ == '__main__':
    app.run(debug=True)
</code>```

答:
There are a couple of problems with this.

Both the client.connect() and the client.subscribe() calls need iterations of the client network loop to run in order to complete properly.

The network loop needs to run at least once every keep alive period the time after the connection has been made in order to stop the broker disconnecting the client as dead. This means if there is a delay between starting the code and the first REST request then the client will be disconnected.

Better to use the client.start_loop() function to run MQTT client network loop continuously in the background on it's own.

You should also remove the call to client.subscribe() that is outside the on_connect() callback.

EDIT:
As hashed out in the comments/chat the following works. It looks like running the flask app in debug mode does some strange things and creates multiple MQTT clients over and over again with the same client id. This leads to the broker constantly kicking the old ones off so messages never get delivered.

```<code>from flask import Flask, Response
import paho.mqtt.client as mqtt
import time
from threading import Thread
import threading

app = Flask(__name__)
lock = threading.Lock()
sessionId=0
cont=True

def on_connect(client, userdata, flags, rc): # The callback for when the client connects to the broker
print("Connected with result code {0}".format(str(rc))) # Print result of connection attempt
client.subscribe("mytopic")

def on_message(client, userdata, msg): # The callback for when a PUBLISH message is received from the server.
global cont
print(msg.topic)
cont=False

client = mqtt.Client(client_id="foo", clean_session=True)
client.on_connect = on_connect # Define callback function for successful connection
client.on_message = on_message # Define callback function for receipt of a message
#client.username_pw_set(mqtt_user, mqtt_password)
client.connect("localhost", port=1884)
client.loop_start()

def test(param1, param2):
lock.acquire()
try:
ret = client.publish("mytopic", "foo")
while cont:
time.sleep(5)
print("loop")
finally:
lock.release()

result = "foo"

return result

@app.route('/test/check', methods=['POST'])
def check():
global sessionId
sessionId = sessionId + 1
t = Thread(target=test, args=(sessionId,None))
t.start()
return {'id': sessionId, 'eta': 0}

if __name__ == '__main__':
print("started")
app.run()
</code>```

Body:
I have a python script, which based on flask and mqtt. The use case is to receive a request via rest-api then to create a new thread which publishes some messages on mosquitto mqtt and expects a response (see subscribe). My problem is that I don't receive any messages. I think it has something to do with the thread, because without the thread it's working very fine..
Do you know what can be the problem?

Thank you in anticipation!

here the code:

from flask import Flask, Response
import paho.mqtt.client as mqtt
from threading import Thread
import threading

app = Flask(__name__)
lock = threading.Lock()

def on_connect(client, userdata, flags, rc):  # The callback for when the client connects to the broker
    print("Connected with result code {0}".format(str(rc)))  # Print result of connection attempt
    client.subscribe("/mytopic")

def on_message(client, userdata, msg):  # The callback for when a PUBLISH message is received from the server.
    print(msg.topic)

client = mqtt.Client(client_id=client_name, clean_session=True)
client.on_connect = on_connect  # Define callback function for successful connection
client.on_message = on_message  # Define callback function for receipt of a message
client.username_pw_set(mqtt_user, mqtt_password)
client.loop_start()
client.connect(mqtt_host)

def test(param1, param2):
   lock.acquire()
   try:

      ret = client.publish("/mytopic", "")
      while True:
            check the response from mqtt => but i don't get the response anymore
            ....
            break
    finally:
        lock.release()
    return result

@app.route('/test/check', methods=['POST'])
def check():
    global sessionId
    sessionId = sessionId + 1
    t = Thread(target=test, args=(sessionId,None))
    t.start()
    return {'id': sessionId, 'eta': 0}

if __name__ == '__main__':
    app.run(debug=True)

Body:
There are a couple of problems with this.

Both the client.connect() and the client.subscribe() calls need iterations of the client network loop to run in order to complete properly.

The network loop needs to run at least once every keep alive period the time after the connection has been made in order to stop the broker disconnecting the client as dead. This means if there is a delay between starting the code and the first REST request then the client will be disconnected.

Better to use the client.start_loop() function to run MQTT client network loop continuously in the background on it's own.

You should also remove the call to client.subscribe() that is outside the on_connect() callback.

EDIT:
As hashed out in the comments/chat the following works. It looks like running the flask app in debug mode does some strange things and creates multiple MQTT clients over and over again with the same client id. This leads to the broker constantly kicking the old ones off so messages never get delivered.

from flask import Flask, Response
import paho.mqtt.client as mqtt
import time
from threading import Thread
import threading

app = Flask(__name__)
lock = threading.Lock()
sessionId=0
cont=True

def on_connect(client, userdata, flags, rc): # The callback for when the client connects to the broker
print("Connected with result code {0}".format(str(rc))) # Print result of connection attempt
client.subscribe("mytopic")

def on_message(client, userdata, msg): # The callback for when a PUBLISH message is received from the server.
global cont
print(msg.topic)
cont=False

client = mqtt.Client(client_id="foo", clean_session=True)
client.on_connect = on_connect # Define callback function for successful connection
client.on_message = on_message # Define callback function for receipt of a message
#client.username_pw_set(mqtt_user, mqtt_password)
client.connect("localhost", port=1884)
client.loop_start()

def test(param1, param2):
lock.acquire()
try:
ret = client.publish("mytopic", "foo")
while cont:
time.sleep(5)
print("loop")
finally:
lock.release()

result = "foo"

return result

@app.route('/test/check', methods=['POST'])
def check():
global sessionId
sessionId = sessionId + 1
t = Thread(target=test, args=(sessionId,None))
t.start()
return {'id': sessionId, 'eta': 0}

if __name__ == '__main__':
print("started")
app.run()


来源: stackexchange

问:
Error in method to visualize missing values
I am trying to visualize missing values (NA) in a data.frame containing the Hepatitis dataset and using the package VIM. I am trying to do that by using the function spineMiss:

```<code>spineMiss(hepatitis[, c("PRONOSTICO", "PROTIME")])
</code>```

But I get the following error:

Error in createPlot(main, sub, xlab, ylab, labels): (list) object
  cannot be coerced to type 'double'

This the str of the dataframe:

If I use the function like this:

```<code>a <- hepatitis$PRONOSTICO
b <- hepatitis$PROTIME
spineMiss(c(a,b))
</code>```

I do not get any error, but the result does not make much sense. What I am doing wrong?

答:
I got the conclusion that the error was related with the structure of the data.frame itself. It was not created by me with R code but read from a file. After the reading I have done some preprocessing (type conversion, etc). The str(hepatitis) shows that the original specification of the attributes of the data.frame are still stored in it. I do not understand completely how that makes spineMiss malfunction but certainly that is the root of the problem.

I have solved it by creating a new data.frame and copying all the data of the previous one (the read from a file and preprocessed) in it:

```<code>aux <- data.frame(matrix(ncol = 20, nrow = 0))
colnames(aux) <- atributos
for(i in 1:nrow(hepatitis)){
  aux[i,] = hepatitis[i,]
}
spineMiss(aux[, c("PRONOSTICO", "PROTIME")])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to visualize missing values (NA) in a data.frame containing the Hepatitis dataset and using the package VIM. I am trying to do that by using the function spineMiss:

spineMiss(hepatitis[, c("PRONOSTICO", "PROTIME")])

But I get the following error:

Error in createPlot(main, sub, xlab, ylab, labels): (list) object
  cannot be coerced to type 'double'

This the str of the dataframe:

If I use the function like this:

a <- hepatitis$PRONOSTICO
b <- hepatitis$PROTIME
spineMiss(c(a,b))

I do not get any error, but the result does not make much sense. What I am doing wrong?

Body:
I got the conclusion that the error was related with the structure of the data.frame itself. It was not created by me with R code but read from a file. After the reading I have done some preprocessing (type conversion, etc). The str(hepatitis) shows that the original specification of the attributes of the data.frame are still stored in it. I do not understand completely how that makes spineMiss malfunction but certainly that is the root of the problem.

I have solved it by creating a new data.frame and copying all the data of the previous one (the read from a file and preprocessed) in it:

aux <- data.frame(matrix(ncol = 20, nrow = 0))
colnames(aux) <- atributos
for(i in 1:nrow(hepatitis)){
  aux[i,] = hepatitis[i,]
}
spineMiss(aux[, c("PRONOSTICO", "PROTIME")])


问:
Pagination in nodejs with mysql
In my project I need to query the db with pagination and provide user the functionality to query based on current search result. Something like limit, I am not able to find anything to use with nodejs. My backend is mysql and I am writing a rest api.</p>

答:
I taked the solution of @Benito and I tried to make it more clear</p>

```<code>var numPerPage = 20;
var skip = (page-1) * numPerPage;
var limit = skip + ',' + numPerPage; // Here we compute the LIMIT parameter for MySQL query
sql.query('SELECT count(*) as numRows FROM users',function (err, rows, fields) {
    if(err) {
        console.log("error: ", err);
        result(err, null);
    }else{
        var numRows = rows[0].numRows;
        var numPages = Math.ceil(numRows / numPerPage);
        sql.query('SELECT * FROM users LIMIT ' + limit,function (err, rows, fields) {
            if(err) {
                console.log("error: ", err);
                result(err, null);
            }else{
                console.log(rows)
                result(null, rows,numPages);
            }
        });
    }
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Pagination in nodejs with mysql

Body:
I taked the solution of @Benito and I tried to make it more clear

var numPerPage = 20;
var skip = (page-1) * numPerPage;
var limit = skip + ',' + numPerPage; // Here we compute the LIMIT parameter for MySQL query
sql.query('SELECT count(*) as numRows FROM users',function (err, rows, fields) {
    if(err) {
        console.log("error: ", err);
        result(err, null);
    }else{
        var numRows = rows[0].numRows;
        var numPages = Math.ceil(numRows / numPerPage);
        sql.query('SELECT * FROM users LIMIT ' + limit,function (err, rows, fields) {
            if(err) {
                console.log("error: ", err);
                result(err, null);
            }else{
                console.log(rows)
                result(null, rows,numPages);
            }
        });
    }
});


问:
Visual C# If text box equals 1 open form 1 if text box equals 2 open form 2
Im creating a login page for my work at school but im a bit stuck, i need it so that if the student is logins in it shows the student form anf if a teacher logins in it shows the teacher form.</p>

```<code>        private void btnSignIn_Click(object sender, EventArgs e)
    {
        if (txtUser.Text == "Student" & txtPass.Text == "GPSC1" || txtUser.Text == "Staff" & txtPass.Text == "GPSC2")

            MessageBox.Show("Success");

        else
            MessageBox.Show("Error");

        if (txtUser.Text == "Student" & txtPass.Text == "GPSC1")
            this.Hide();
        StudentForm studentForm = new StudentForm();
        studentForm.ShowDialog();
        this.Close();

        if (txtUser.Text == "Staff" & txtPass.Text == "GPSC2")
            this.Hide();
        TeacherForm teacherForm = new TeacherForm();
        teacherForm.ShowDialog();
        this.Close();

    }
</code>```

答:
You should add braces to create a new scope, so you can execute more than one statement within an if statement.

For example:

```<code>private void btnSignIn_Click(object sender, EventArgs e)
{
    if (txtUser.Text == "Student" && txtPass.Text == "GPSC1")
    //                            ^^  use &&   (& suits better for bitwise)
    {
        MessageBox.Show("Success");
        this.Hide();
        StudentForm studentForm = new StudentForm();
        studentForm.ShowDialog();
        this.Close();
    }
    else
        if(txtUser.Text == "Staff" && txtPass.Text == "GPSC2")
        {
            MessageBox.Show("Success");
            this.Hide();
            TeacherForm teacherForm = new TeacherForm();
            teacherForm.ShowDialog();
            this.Close();
        }
        else
            MessageBox.Show("Error");
}
</code>```

Body:
Im creating a login page for my work at school but im a bit stuck, i need it so that if the student is logins in it shows the student form anf if a teacher logins in it shows the teacher form.

        private void btnSignIn_Click(object sender, EventArgs e)
    {
        if (txtUser.Text == "Student" & txtPass.Text == "GPSC1" || txtUser.Text == "Staff" & txtPass.Text == "GPSC2")

            MessageBox.Show("Success");

        else
            MessageBox.Show("Error");

        if (txtUser.Text == "Student" & txtPass.Text == "GPSC1")
            this.Hide();
        StudentForm studentForm = new StudentForm();
        studentForm.ShowDialog();
        this.Close();

        if (txtUser.Text == "Staff" & txtPass.Text == "GPSC2")
            this.Hide();
        TeacherForm teacherForm = new TeacherForm();
        teacherForm.ShowDialog();
        this.Close();

    }

Body:
You should add braces to create a new scope, so you can execute more than one statement within an if statement.

For example:

private void btnSignIn_Click(object sender, EventArgs e)
{
    if (txtUser.Text == "Student" && txtPass.Text == "GPSC1")
    //                            ^^  use &&   (& suits better for bitwise)
    {
        MessageBox.Show("Success");
        this.Hide();
        StudentForm studentForm = new StudentForm();
        studentForm.ShowDialog();
        this.Close();
    }
    else
        if(txtUser.Text == "Staff" && txtPass.Text == "GPSC2")
        {
            MessageBox.Show("Success");
            this.Hide();
            TeacherForm teacherForm = new TeacherForm();
            teacherForm.ShowDialog();
            this.Close();
        }
        else
            MessageBox.Show("Error");
}


问:
Thread-safe uniform random number generator
I have some parallel Fortran90 code in which each thread needs to generate the same sequence of random numbers.

I have a random number generator that seems to be thread-unsafe, since, for a given seed, I'm completely unable to repeat the same results each time I run the program.

I surfed unsuccessfully (almost) the entire web looking for some code of a thread-safe RNG. Could anyone provide me with (the link to) the code of one?

Thanks in advance!

答:
The alternatives seem to be:

Use a synchronisation object (such as
a mutex) on the generator's seed
value. This will unfortunately
serialise your code on accesses to
generator

Use thread-local storage in the
generator so each thread gets its own
seed - this may cause statstical
problems for your app

If your platform supports a suitable
atomic operation, use that on the
seed (it probably won't, however)

Not a very encouraging list, I know. And to add to it, I have no idea how to implement any of them in FORTRAN!

OwnerDisplayName: Bellman

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Eric P

OwnerDisplayName: anon


问:
Showing a list of software with LGPL during boot
I remember seeing a list of software components with LGPL licenses during the start up of Linux root file system built with Yocto Project. I can't seem to figure out what enables this, even after going through the Mega Manual. </p>

```<code>NOTICE: This file system contains the following GPLv3 packages:
        autoconf
        bash-dev
        bash
        binutils
        cifs-utils
        cpio
        cpp-symlinks
        cpp
        dosfstools
        elfutils
        g++-symlinks
        g++
        gawk-dev
        gawk
        gcc-symlinks
        gcc
        gdb
        gdbc6x
        gdbserver
        gettext-dev
        gettext
        gzip
        libbfd
        libcairo-dbg
        libcairo-perf-utils
        libdw1
        libelf1
        libgdbm-compat4
        libgdbm-dev
        libgdbm4
        libgettextlib
        libgettextsrc
        libgmp-dev
        libgmp10
        libgmpxx4
        libidn11
        libmpc3
        libmpfr4
        libreadline-dev
        libreadline7
        libunistring2
        m4-dev
        m4
        make
        nettle-dev
        nettle
        parted
        python3-pycairo-dev
        python3-pycairo
        which
If you do not wish to distribute GPLv3 components please remove
the above packages prior to distribution.  This can be done using
the opkg remove command.  i.e.:
    opkg remove <package>
Where <package> is the name printed in the list above

NOTE: If the package is a dependency of another package you
      will be notified of the dependent packages.  You should
      use the --force-removal-of-dependent-packages option to
      also remove the dependent packages as well
</code>```

答: Found my answer - it's from arago-gpl-notice from meta-arago. It only displays GPLv3 also.</p>

Body:
I remember seeing a list of software components with LGPL licenses during the start up of Linux root file system built with Yocto Project. I can't seem to figure out what enables this, even after going through the Mega Manual.

NOTICE: This file system contains the following GPLv3 packages:
        autoconf
        bash-dev
        bash
        binutils
        cifs-utils
        cpio
        cpp-symlinks
        cpp
        dosfstools
        elfutils
        g++-symlinks
        g++
        gawk-dev
        gawk
        gcc-symlinks
        gcc
        gdb
        gdbc6x
        gdbserver
        gettext-dev
        gettext
        gzip
        libbfd
        libcairo-dbg
        libcairo-perf-utils
        libdw1
        libelf1
        libgdbm-compat4
        libgdbm-dev
        libgdbm4
        libgettextlib
        libgettextsrc
        libgmp-dev
        libgmp10
        libgmpxx4
        libidn11
        libmpc3
        libmpfr4
        libreadline-dev
        libreadline7
        libunistring2
        m4-dev
        m4
        make
        nettle-dev
        nettle
        parted
        python3-pycairo-dev
        python3-pycairo
        which
If you do not wish to distribute GPLv3 components please remove
the above packages prior to distribution.  This can be done using
the opkg remove command.  i.e.:
    opkg remove <package>
Where <package> is the name printed in the list above

NOTE: If the package is a dependency of another package you
      will be notified of the dependent packages.  You should
      use the --force-removal-of-dependent-packages option to
      also remove the dependent packages as well


问:
Hide Open Program With CMD
Hello I would like to know if someone can help me I would like to know how to open a program and this is hidden (not shown in the taskbar) I was testing the following but it did not work Anyone have any other ideas?

Start /b "Título" "word.exe"

答:
If you are simply trying to start a program from the command prompt you must first locate the file path of the executable

Example:

Assuming word.exe lives in the below directory, cd will change your working directory in the command prompt

```<code>cd C:\Program Files\Microsoft Office\root\Office16
</code>```

Then start the program with

```<code>start /B WINWORD.exe
</code>```

Or as stated in the comments you could just type its registered name:

```<code>start winword
start /min winword
</code>```

/min will not hide it, it will just minimize to the task bar.

Title: Hide Open Program With CMD

Body:
If you are simply trying to start a program from the command prompt you must first locate the file path of the executable

Example:

Assuming word.exe lives in the below directory, cd will change your working directory in the command prompt

cd C:\Program Files\Microsoft Office\root\Office16

Then start the program with

start /B WINWORD.exe

Or as stated in the comments you could just type its registered name:

start winword
start /min winword

/min will not hide it, it will just minimize to the task bar.


问:
Yii2 kartik select2 widget showing values too issue
I have created a yii2 kartik select2 widget to select multiple car models like below

```<code><?= Select2::widget([
        'name' => 'drp-make',
        'data' => Car::getCarMakesEnglish(),
        'value' => explode(",",$model->drp_make),
        'options' => [
          'id'=>'drp-make',
          'placeholder' => 'All Makes',
          'multiple' => true
        ]
      ]); ?>
</code>```

And the function to get data for the select2 like

```<code> public static function getCarMakesEnglish(){
            $out=array();
        $makes=CarMakes::find()->select(['id','make_eng'])->all();
        foreach ($makes as $make) {
            array_push($out,array($make['id'] => $make['make_eng']));
        }
        return $out;
    }
</code>```

Its working perfect.But a issue is there.please see the below picture

Its showing values too not only the names.I want to show only the make names.How to do that

答:
Because you are pushing an array to every index of the $out

```<code>array_push($out,array($make['id'] => $make['make_eng']))
</code>```

you should use yii\helpers\ArrayHelper::map() instead that do this for you. Change your function getCarMakesEnglish() to the following

```<code>public static function getCarMakesEnglish()
{
    $makes = CarMakes::find()->select(['id', 'make_eng'])->all();
    return \yii\helpers\ArrayHelper::map($makes,'id','make_eng');
}
</code>```

Body:
I have created a yii2 kartik select2 widget to select multiple car models like below

<?= Select2::widget([
        'name' => 'drp-make',
        'data' => Car::getCarMakesEnglish(),
        'value' => explode(",",$model->drp_make),
        'options' => [
          'id'=>'drp-make',
          'placeholder' => 'All Makes',
          'multiple' => true
        ]
      ]); ?>

And the function to get data for the select2 like

 public static function getCarMakesEnglish(){
            $out=array();
        $makes=CarMakes::find()->select(['id','make_eng'])->all();
        foreach ($makes as $make) {
            array_push($out,array($make['id'] => $make['make_eng']));
        }
        return $out;
    }

Its working perfect.But a issue is there.please see the below picture

Its showing values too not only the names.I want to show only the make names.How to do that

Body:
Because you are pushing an array to every index of the $out

array_push($out,array($make['id'] => $make['make_eng']))

you should use yii\helpers\ArrayHelper::map() instead that do this for you. Change your function getCarMakesEnglish() to the following

public static function getCarMakesEnglish()
{
    $makes = CarMakes::find()->select(['id', 'make_eng'])->all();
    return \yii\helpers\ArrayHelper::map($makes,'id','make_eng');
}


问:
How can I use `console.log` or `console.error` in a vue template?
I have a vue component with

```<code> <form @keydown="console.error($event.target.name);">
</code>```

gives

app.js:47961 [Vue warn]: Property or method "console" is not defined
on the instance but referenced during render.

window.console doesn't work either

What is the proper way to use console and window in a template to debug?

答: You can use this.console instead console or wrap call to console in a method, i am using eslint config with rule 'no-console': 'off'

Body:
I have a vue component with

 <form @keydown="console.error($event.target.name);">

gives

app.js:47961 [Vue warn]: Property or method "console" is not defined
on the instance but referenced during render.

window.console doesn't work either

What is the proper way to use console and window in a template to debug?


问:
ReactJS: How to display selected value from dropdown in input fields?
I am trying to do following:

The user can select a calculation from the dropdown menu. The selected numbers(from calculation) appear in the input fields and the user can change the calculation. The modified calculation is displayed after pressing the "Add" button. Also the modified calculation should shown in red color in the dropdown menu.

I managed to get the calculation right, but the selected numbers doesn't appear in the input fields. What I have to do to update the values to the input fields?

Here is my code:

```<code>import React from 'react';

export default class Lisatehtava1 extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            num1: 0,
            num2: 0,
            total: 0,
            results: [],
        }
    }

    handleChange = (e) => {
        const { name, value } = e.target;
        this.setState({
            [name]: value
        })
    }

    add = () => {

        const { num1, num2 } = this.state;

        this.setState({
            total: (parseInt(num1) + parseInt(num2))

        }, () => {

            let result = { num1: this.state.num1, num2: this.state.num2, total: this.state.total };

            const t = [...this.state.results, result];

            this.setState({ results: t }, () => {
                this.setState({ num1: "" }, () => {
                    this.setState({ num2: "" });

                });
            });
        })
    }

    render() {

        let dropdown = this.state.results.map((item, id) => {
            return <option key={id}>{item.num1} + {item.num2} = {item.total}</option>
        });

        return (
            <div>
                <div>
                    <label>Numero 1</label>
                    <input type="text" name="num1" onChange={this.handleChange} />
                </div>
                <div>
                    <label>Numero 2</label>
                    <input type="text" name="num2" onChange={this.handleChange} />
                </div>
                <button onClick={this.add}>Add</button>
                <div><select onChange={this.handleChange}>{dropdown}</select></div>
            </div>
        );
    }
}
</code>```

答:
There are a few things you have to change.

1.In the input tag you must include a value attibute

```<code><input type="text" name="num1" onChange={this.handleChange} value={this.state.num1} />
</code>```

similar to 2nd input tag

2.You can use split on the value from the select tag event.

```<code><select onChange={(e)=>{
                      this.setState({
                        num1:e.target.value.split(" ")[0],
                         num2:e.target.value.split(" ")[2]
                      })
                }}>{dropdown}</select>
</code>```

You can check out live example https://stackblitz.com/edit/react-fm8wd4

Body:
I am trying to do following:

The user can select a calculation from the dropdown menu. The selected numbers(from calculation) appear in the input fields and the user can change the calculation. The modified calculation is displayed after pressing the "Add" button. Also the modified calculation should shown in red color in the dropdown menu.

I managed to get the calculation right, but the selected numbers doesn't appear in the input fields. What I have to do to update the values to the input fields?

Here is my code:

import React from 'react';

export default class Lisatehtava1 extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            num1: 0,
            num2: 0,
            total: 0,
            results: [],
        }
    }

    handleChange = (e) => {
        const { name, value } = e.target;
        this.setState({
            [name]: value
        })
    }

    add = () => {

        const { num1, num2 } = this.state;

        this.setState({
            total: (parseInt(num1) + parseInt(num2))

        }, () => {

            let result = { num1: this.state.num1, num2: this.state.num2, total: this.state.total };

            const t = [...this.state.results, result];

            this.setState({ results: t }, () => {
                this.setState({ num1: "" }, () => {
                    this.setState({ num2: "" });

                });
            });
        })
    }

    render() {

        let dropdown = this.state.results.map((item, id) => {
            return <option key={id}>{item.num1} + {item.num2} = {item.total}</option>
        });

        return (

                    Numero 1
                    <input type="text" name="num1" onChange={this.handleChange} />

                    Numero 2
                    <input type="text" name="num2" onChange={this.handleChange} />

                <button onClick={this.add}>Add</button>

<select onChange={this.handleChange}>{dropdown}</select>

        );
    }
}

Body:
There are a few things you have to change.

1.In the input tag you must include a value attibute

<input type="text" name="num1" onChange={this.handleChange} value={this.state.num1} />

similar to 2nd input tag

2.You can use split on the value from the select tag event.

<select onChange={(e)=>{
                      this.setState({
                        num1:e.target.value.split(" ")[0],
                         num2:e.target.value.split(" ")[2]
                      })
                }}>{dropdown}</select>

You can check out live example https://stackblitz.com/edit/react-fm8wd4


问:
Uncaught ReferenceError: writeIn is not defined at change (<anonymous>:5:4) at <anonymous>:7:1
I try to write a function to change the color of a text, but the error occurs. I winder how to fix this.

```<code>function change() {
var colour = prompt("What's your favourite colour?");
a = colour.value
id = document.querySelector('.tab ');
id.style.backgoundColor = writeIn(a) ;
}
change();
console.log(a);
</code>```

I edited the code as below, the error went, but still the value is undifined and no change occurs in the text.

```<code>var changing = function change() {
var cls = document.querySelector('.tab ');
var colour = prompt("What's your favourite colour?");
var a = colour.value;
cls.style.backgoundColor = a ;
alert(a);
}
changing();
console.log(a);
</code>```

答:
I think you want some thing like below code:

let favouriteColor;

function change() {
  favouriteColor = prompt("What's your favourite colour?");
  cls = document.querySelector('.tab ');
  cls.style.backgroundColor = favouriteColor;
  alert(favouriteColor);
}
change();
console.log(favouriteColor);
```

Body:
I try to write a function to change the color of a text, but the error occurs. I winder how to fix this.

function change() {
var colour = prompt("What's your favourite colour?");
a = colour.value
id = document.querySelector('.tab ');
id.style.backgoundColor = writeIn(a) ;
}
change();
console.log(a);

I edited the code as below, the error went, but still the value is undifined and no change occurs in the text.

var changing = function change() {
var cls = document.querySelector('.tab ');
var colour = prompt("What's your favourite colour?");
var a = colour.value;
cls.style.backgoundColor = a ;
alert(a);
}
changing();
console.log(a);


问:
Add BCC to Woocoomerce transactional email sent through Sendinblue
We are currently using Sendinblue as mail marketing provider and did set it up on our Wordpress/Woocommerce shop to handle marketing and transactional emails now.

Before that, we used to send some transactional woocommerce transactional email, such as order_completed in bcc to one of our own email addresses. This is necessary for certain internal processes.

Hence Sendinblue has taken over, this function isn't being triggered, or more like is triggered but doesn't get processed through Sendinblue anymore.

Although, I found an API call that could actually do exactly that: https://developers.sendinblue.com/reference#sendtransacemail

```<code><?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.sendinblue.com/v3/smtp/email",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\"bcc\":[{\"email\":\"something@domain.com\"}]}",
  CURLOPT_HTTPHEADER => array(
    "accept: application/json",
    "content-type: application/json"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
</code>```

As well as this: https://apidocs.sendinblue.com/tutorial-sending-transactional-email/

Though, I'm absolutely unsure where to add this in order to trigger BCC through Sendinblue.

Would be amazing, if someone could point me in the right direction.

Kind Regards
Chris

答:
you don't have to use the API calls to be able to use Sendinblue for Email. What you should do is just making Sendinblue as your Email Server by entering your Sendinblue server details as your Wordpress default SMTP server. You can use the following code to do so.

If you do the above your website will function normally and all triggers will work just fine, the only thing if that your website will use Sendinblue as it's Email Server and all the sent emails will be logged to your  Sendinblue account.

How to get your Sendinblue SMTP account working:
https://help.sendinblue.com/hc/en-us/articles/209463245--How-can-I-get-my-SendinBlue-SMTP-account-activated-

Very simple article to help you with configuring your SMTP:
https://help.dreamhost.com/hc/en-us/articles/215526937-Configuring-the-WP-Mail-SMTP-plugin

Good luck!

Body:
We are currently using Sendinblue as mail marketing provider and did set it up on our Wordpress/Woocommerce shop to handle marketing and transactional emails now.

Before that, we used to send some transactional woocommerce transactional email, such as order_completed in bcc to one of our own email addresses. This is necessary for certain internal processes.

Hence Sendinblue has taken over, this function isn't being triggered, or more like is triggered but doesn't get processed through Sendinblue anymore.

Although, I found an API call that could actually do exactly that: https://developers.sendinblue.com/reference#sendtransacemail

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.sendinblue.com/v3/smtp/email",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\"bcc\":[{\"email\":\"something@domain.com\"}]}",
  CURLOPT_HTTPHEADER => array(
    "accept: application/json",
    "content-type: application/json"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

As well as this: https://apidocs.sendinblue.com/tutorial-sending-transactional-email/

Though, I'm absolutely unsure where to add this in order to trigger BCC through Sendinblue.

Would be amazing, if someone could point me in the right direction.

Kind Regards
Chris


问:
The most Pythonic way of checking if a value in a dictionary is defined/has zero length
Say I have a dictionary, and I want to check if a key is mapped to a nonempty value.  One way of doing this would be the len function:

```<code>mydict = {"key" : "value", "emptykey" : ""}
print "True" if len(mydict["key"]) > 0 else "False"  # prints true
print "True" if len(mydict["emptykey"]) > 0 else "False"  # prints false
</code>```

However, one can rely on the semantics of Python and how if an object is defined it evaluates to true and leave out the len call:

```<code>mydict = {"key" : "value", "emptykey" : ""}
print "True" if mydict["key"] else "False"  # prints true
print "True" if mydict["emptykey"] else "False"  # prints false
</code>```

However, I'm not sure which is more Pythonic.  The first feels "explicit is better than implicit", however the second feels "simple is better than complex".

I also wonder if the leaving out the len call could bite me as the dict I'm working with doesn't necessarily contain strings, but could contain other len-able types (lists, sets, etc).  OTOH, in the former (with the len call) if None gets stored as a value the code will blow up, whereas the non-len version will work as expected (will eval to false).

Which version is safer and more Pythonic?

Edit: clarifying assumptions: I know the key is in the dictionary, and I know values will be len-able.  I also cannot avoid having zero-length values enter the dictionary.

Edit #2: It seems like people are missing the point of my question.  I'm not trying to determine the most Pythonic/safest way of checking if a key is present in a dictionary, I'm trying to check if a value has zero length or not

答:
Since I came here to know whether we can check the dictionary key is present or not for those the answer is:

```<code>if mydict.get(key,0):
    ---
</code>```

and for the length of the key > 0, the answer is already provided by @Ethan Furman

```<code>if mydict[key]:
    ---
</code>```

Body:
Say I have a dictionary, and I want to check if a key is mapped to a nonempty value.  One way of doing this would be the len function:

mydict = {"key" : "value", "emptykey" : ""}
print "True" if len(mydict["key"]) > 0 else "False"  # prints true
print "True" if len(mydict["emptykey"]) > 0 else "False"  # prints false

However, one can rely on the semantics of Python and how if an object is defined it evaluates to true and leave out the len call:

mydict = {"key" : "value", "emptykey" : ""}
print "True" if mydict["key"] else "False"  # prints true
print "True" if mydict["emptykey"] else "False"  # prints false

However, I'm not sure which is more Pythonic.  The first feels "explicit is better than implicit", however the second feels "simple is better than complex".

I also wonder if the leaving out the len call could bite me as the dict I'm working with doesn't necessarily contain strings, but could contain other len-able types (lists, sets, etc).  OTOH, in the former (with the len call) if None gets stored as a value the code will blow up, whereas the non-len version will work as expected (will eval to false).

Which version is safer and more Pythonic?

Edit: clarifying assumptions: I know the key is in the dictionary, and I know values will be len-able.  I also cannot avoid having zero-length values enter the dictionary.

Edit #2: It seems like people are missing the point of my question.  I'm not trying to determine the most Pythonic/safest way of checking if a key is present in a dictionary, I'm trying to check if a value has zero length or not

Body:
Since I came here to know whether we can check the dictionary key is present or not for those the answer is:

if mydict.get(key,0):
    ---

and for the length of the key > 0, the answer is already provided by @Ethan Furman

if mydict[key]:
    ---


问:
Recursive including template files fails compilation
I am trying to use a simple template class to decode different types. I am getting this error

```<code>Decoder.h:16: error: non-const lvalue reference to type 'CheckDecoder::NormalType' cannot bind to a value of unrelated type 'CheckDecoder::NestedType'
        CheckDecoder::decode(m_value, istr);
                             ^~~~~~~
</code>```

Actually its a part of big project but I am sharing a simple project to show this specific problem. Please help to resolve this issue, also provide some reference to read more about this template issue.

These are the four files in the project

main.cpp

```<code>#include <iostream>
#include <NormalType.h>
#include <NestedType.h>
#include <Decoder.h>

using namespace std;
using namespace CheckDecoder;
int main()
{
    Decoder<NormalType> d_normal;
    d_normal.decode(std::cin);

    Decoder<NestedType> d_nested;
    d_nested.decode(std::cin);
    return 0;
}
</code>```

Decoder.h

```<code>#ifndef DECODER_H
#define DECODER_H

#include <iostream>

namespace CheckDecoder {

template<typename T>
class Decoder
{
public:
    void decode(std::istream& istr)
    {
        // some complex code
        CheckDecoder::decode(m_value, istr);
    }

    T m_value;
};

}
#endif // DECODER_H

</code>```

NormalType.h

```<code>#ifndef NORMALTYPE_H
#define NORMALTYPE_H

#include <iostream>

namespace CheckDecoder {

class NormalType
{

};

void decode(NormalType& t, std::istream& istr)
{
    // do something
}
}
#endif // NORMALTYPE_H

</code>```

NestedType.h

```<code>#ifndef NESTEDTYPE_H
#define NESTEDTYPE_H

#include <Decoder.h>

namespace CheckDecoder {

class NestedType
{

private:
    Decoder<int> m_value;
};

void decode(NestedType& t, std::istream& istr)
{
    // do something
}
}

#endif // NESTEDTYPE_H

</code>```

答:
The way your includes are ordered, in main.cpp first CheckDecoder::decode(NormalType) is declared, then CheckDecoder::decode is used by Decoder, and finally CheckDecoder::decode(NestedType) is declared. At the point of definition in Decoder, only the first declaration is visible; the second doesn't participate in overload resolution. It could have been found by argument-dependent lookup, but the way you call it - with a qualified name - suppresses that.

One possible workaround is to move the call to a scope where other things named decode don't get in the way, and then use an unqualified name to allow argument-dependent lookup to do its thing. Something like this:

```<code>struct DecoderHelper {
  template <typename T>
  static void DoDecode(T& value, std::istream& istr) {
    decode(value, istr);
  }
};

template<typename T>
class Decoder
{
public:
    void decode(std::istream& istr)
    {
        // some complex code
        DecoderHelper::DoDecode<T>(m_value, istr);
    }

    T m_value;
};
</code>```

Body:
I am trying to use a simple template class to decode different types. I am getting this error

Decoder.h:16: error: non-const lvalue reference to type 'CheckDecoder::NormalType' cannot bind to a value of unrelated type 'CheckDecoder::NestedType'
        CheckDecoder::decode(m_value, istr);
                             ^~~~~~~

Actually its a part of big project but I am sharing a simple project to show this specific problem. Please help to resolve this issue, also provide some reference to read more about this template issue.

These are the four files in the project

main.cpp

#include <iostream>
#include <NormalType.h>
#include <NestedType.h>
#include <Decoder.h>

using namespace std;
using namespace CheckDecoder;
int main()
{
    Decoder<NormalType> d_normal;
    d_normal.decode(std::cin);

    Decoder<NestedType> d_nested;
    d_nested.decode(std::cin);
    return 0;
}

Decoder.h

#ifndef DECODER_H
#define DECODER_H

#include <iostream>

namespace CheckDecoder {

template<typename T>
class Decoder
{
public:
    void decode(std::istream& istr)
    {
        // some complex code
        CheckDecoder::decode(m_value, istr);
    }

    T m_value;
};

}
#endif // DECODER_H

NormalType.h

#ifndef NORMALTYPE_H
#define NORMALTYPE_H

#include <iostream>

namespace CheckDecoder {

class NormalType
{

};

void decode(NormalType& t, std::istream& istr)
{
    // do something
}
}
#endif // NORMALTYPE_H

NestedType.h

#ifndef NESTEDTYPE_H
#define NESTEDTYPE_H

#include <Decoder.h>

namespace CheckDecoder {

class NestedType
{

private:
    Decoder<int> m_value;
};

void decode(NestedType& t, std::istream& istr)
{
    // do something
}
}

#endif // NESTEDTYPE_H

Body:
The way your includes are ordered, in main.cpp first CheckDecoder::decode(NormalType) is declared, then CheckDecoder::decode is used by Decoder, and finally CheckDecoder::decode(NestedType) is declared. At the point of definition in Decoder, only the first declaration is visible; the second doesn't participate in overload resolution. It could have been found by argument-dependent lookup, but the way you call it - with a qualified name - suppresses that.

One possible workaround is to move the call to a scope where other things named decode don't get in the way, and then use an unqualified name to allow argument-dependent lookup to do its thing. Something like this:

struct DecoderHelper {
  template <typename T>
  static void DoDecode(T& value, std::istream& istr) {
    decode(value, istr);
  }
};

template<typename T>
class Decoder
{
public:
    void decode(std::istream& istr)
    {
        // some complex code
        DecoderHelper::DoDecode<T>(m_value, istr);
    }

    T m_value;
};


问:
What Does This Script Do?
I'm reviewing the tutorial "Advanced Auto-Dependency Generation" and found a script with this:

```<code> %.P : %.c
   ....; [ -s $@ ] || rm -f $@
</code>```

What does that part of the target do?  I know I've seen this syntax:
[...]||... before in bash scripts, but I can't recall how it works exactly...

Thanks in advance!!

答: If the preceding command fails (i.e. [), the following command is executed (rm). Failure is a non-zero return code.

Title: What Does This Script Do?

Body:
I'm reviewing the tutorial "Advanced Auto-Dependency Generation" and found a script with this:

 %.P : %.c
   ....; [ -s $@ ] || rm -f $@

What does that part of the target do?  I know I've seen this syntax:
[...]||... before in bash scripts, but I can't recall how it works exactly...

Thanks in advance!!


问:
Seemingly Random Delay in queries
This is a follow up to this issue I posted a while ago.

I have the following code:

```<code>SET work_mem = '16MB';
SELECT      s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset
FROM        rm_o_resource_usage_instance_splits_new s
INNER JOIN  rm_o_resource_usage r ON s.usage_id = r.id
INNER JOIN  scheduledactivities sa ON s.activity_index = sa.activity_index AND r.schedule_id = sa.solution_id and s.solution = sa.solution_id
WHERE       r.schedule_id = 10
ORDER BY    r.resource_id, s.start_date
</code>```

When I run EXPLAIN (ANALYZE, BUFFERS) I get the following:

```<code>Sort  (cost=3724.02..3724.29 rows=105 width=89) (actual time=245.802..247.573 rows=22302 loops=1)
  Sort Key: r.resource_id, s.start_date
  Sort Method: quicksort  Memory: 6692kB
  Buffers: shared hit=198702 read=5993 written=612
  ->  Nested Loop  (cost=703.76..3720.50 rows=105 width=89) (actual time=1.898..164.741 rows=22302 loops=1)
        Buffers: shared hit=198702 read=5993 written=612
        ->  Hash Join  (cost=703.34..3558.54 rows=105 width=101) (actual time=1.815..11.259 rows=22302 loops=1)
              Hash Cond: (s.usage_id = r.id)
              Buffers: shared hit=3 read=397 written=2
              ->  Bitmap Heap Scan on rm_o_resource_usage_instance_splits_new s  (cost=690.61..3486.58 rows=22477 width=69) (actual time=1.782..5.820 rows=22302 loops=1)
                    Recheck Cond: (solution = 10)
                    Heap Blocks: exact=319
                    Buffers: shared hit=2 read=396 written=2
                    ->  Bitmap Index Scan on rm_o_resource_usage_instance_splits_new_solution_idx  (cost=0.00..685.00 rows=22477 width=0) (actual time=1.609..1.609 rows=22302 loops=1)
                          Index Cond: (solution = 10)
                          Buffers: shared hit=2 read=77
              ->  Hash  (cost=12.66..12.66 rows=5 width=48) (actual time=0.023..0.023 rows=1 loops=1)
                    Buckets: 1024  Batches: 1  Memory Usage: 9kB
                    Buffers: shared hit=1 read=1
                    ->  Bitmap Heap Scan on rm_o_resource_usage r  (cost=4.19..12.66 rows=5 width=48) (actual time=0.020..0.020 rows=1 loops=1)
                          Recheck Cond: (schedule_id = 10)
                          Heap Blocks: exact=1
                          Buffers: shared hit=1 read=1
                          ->  Bitmap Index Scan on rm_o_resource_usage_sched  (cost=0.00..4.19 rows=5 width=0) (actual time=0.017..0.017 rows=1 loops=1)
                                Index Cond: (schedule_id = 10)
                                Buffers: shared read=1
        ->  Index Scan using scheduledactivities_activity_index_idx on scheduledactivities sa  (cost=0.42..1.53 rows=1 width=16) (actual time=0.004..0.007 rows=1 loops=22302)
              Index Cond: (activity_index = s.activity_index)
              Filter: (solution_id = 10)
              Rows Removed by Filter: 5
              Buffers: shared hit=198699 read=5596 written=610
Planning time: 7.070 ms
Execution time: 248.691 ms
</code>```

Every time I run EXPLAIN, I get roughly the same results. The Execution Time is always between 170ms and 250ms, which, to me is perfectly fine. However, when this query is run through a C++ project (using PQexec(conn, query) where conn is a dedicated connection, and query is the above query), the time it takes seems to vary widely. In general, the query is very quick, and you don't notice a delay. The problem is, that on occasion, this query will take 2 to 3 minutes to complete.

If I open the pgadmin, and have a look at the "server activity" for the database, there's about 30 or so connections, mostly sitting at "idle". The above query's connection is marked as "active", and will stay as "active" for several minutes.

I am at a loss of why it randomly takes several minutes to complete the same query, with no change in data in the DB either. I have tried increasing the work_mem which didn't make any difference (nor did I really expect it to). Any help or suggestions would be greatly appreciated.

There isn't any more specific tags, but I'm currently using Postgres 10.11, but it's also been an issue on other versions of 10.x. System is a Xeon quad-core @ 3.4Ghz, with SSD and 24GB of memory.

Per jjanes's suggestion, I put in the auto_explain. Eventually go this output:

```<code>duration: 128057.373 ms
plan:
Query Text: SET work_mem = '32MB';SELECT        s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset FROM     rm_o_resource_usage_instance_splits_new s INNER JOIN    rm_o_resource_usage r ON s.usage_id = r.id INNER JOIN  scheduledactivities sa ON s.activity_index = sa.activity_index AND r.schedule_id = sa.solution_id and s.solution = sa.solution_id WHERE      r.schedule_id = 12642 ORDER BY   r.resource_id, s.start_date
Sort  (cost=14.36..14.37 rows=1 width=98) (actual time=128042.083..128043.287 rows=21899 loops=1)
  Output: s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset
  Sort Key: r.resource_id, s.start_date
  Sort Method: quicksort  Memory: 6585kB
  Buffers: shared hit=21198435 read=388 dirtied=119
  ->  Nested Loop  (cost=0.85..14.35 rows=1 width=98) (actual time=4.995..127958.935 rows=21899 loops=1)
        Output: s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset
        Join Filter: (s.activity_index = sa.activity_index)
        Rows Removed by Join Filter: 705476285
        Buffers: shared hit=21198435 read=388 dirtied=119
        ->  Nested Loop  (cost=0.42..9.74 rows=1 width=110) (actual time=0.091..227.705 rows=21899 loops=1)
              Output: s.start_date, s.end_date, s.resources, s.activity_index, s.solution, r.resource_id, r.schedule_id
              Inner Unique: true
              Join Filter: (s.usage_id = r.id)
              Buffers: shared hit=22102 read=388 dirtied=119
              ->  Index Scan using rm_o_resource_usage_instance_splits_new_solution_idx on public.rm_o_resource_usage_instance_splits_new s  (cost=0.42..8.44 rows=1 width=69) (actual time=0.082..17.418 rows=21899 loops=1)
                    Output: s.start_time, s.end_time, s.resources, s.activity_index, s.usage_id, s.start_date, s.end_date, s.solution
                    Index Cond: (s.solution = 12642)
                    Buffers: shared hit=203 read=388 dirtied=119
              ->  Seq Scan on public.rm_o_resource_usage r  (cost=0.00..1.29 rows=1 width=57) (actual time=0.002..0.002 rows=1 loops=21899)
                    Output: r.id, r.schedule_id, r.resource_id
                    Filter: (r.schedule_id = 12642)
                    Rows Removed by Filter: 26
                    Buffers: shared hit=21899
        ->  Index Scan using scheduled_activities_idx on public.scheduledactivities sa  (cost=0.42..4.60 rows=1 width=16) (actual time=0.006..4.612 rows=32216 loops=21899)
              Output: sa.usedresourceset, sa.activity_index, sa.solution_id
              Index Cond: (sa.solution_id = 12642)
              Buffers: shared hit=21176333",,,,,,,,,""
</code>```

EDIT: Full definitions of the tables are below:

```<code>CREATE TABLE public.rm_o_resource_usage_instance_splits_new
(
    start_time integer NOT NULL,
    end_time integer NOT NULL,
    resources jsonb NOT NULL,
    activity_index integer NOT NULL,
    usage_id bigint NOT NULL,
    start_date text COLLATE pg_catalog."default" NOT NULL,
    end_date text COLLATE pg_catalog."default" NOT NULL,
    solution bigint NOT NULL,
    CONSTRAINT rm_o_resource_usage_instance_splits_new_pkey PRIMARY KEY (start_time, activity_index, usage_id),
    CONSTRAINT rm_o_resource_usage_instance_splits_new_solution_fkey FOREIGN KEY (solution)
        REFERENCES public.rm_o_schedule_stats (id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE,
    CONSTRAINT rm_o_resource_usage_instance_splits_new_usage_id_fkey FOREIGN KEY (usage_id)
        REFERENCES public.rm_o_resource_usage (id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

CREATE INDEX rm_o_resource_usage_instance_splits_new_activity_idx
    ON public.rm_o_resource_usage_instance_splits_new USING btree
    (activity_index ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX rm_o_resource_usage_instance_splits_new_solution_idx
    ON public.rm_o_resource_usage_instance_splits_new USING btree
    (solution ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX rm_o_resource_usage_instance_splits_new_usage_idx
    ON public.rm_o_resource_usage_instance_splits_new USING btree
    (usage_id ASC NULLS LAST)
    TABLESPACE pg_default;
</code>```

```<code>CREATE TABLE public.rm_o_resource_usage
(
    id bigint NOT NULL DEFAULT nextval('rm_o_resource_usage_id_seq'::regclass),
    schedule_id bigint NOT NULL,
    resource_id text COLLATE pg_catalog."default" NOT NULL,
    CONSTRAINT rm_o_resource_usage_pkey PRIMARY KEY (id),
    CONSTRAINT rm_o_resource_usage_schedule_id_fkey FOREIGN KEY (schedule_id)
        REFERENCES public.rm_o_schedule_stats (id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

CREATE INDEX rm_o_resource_usage_idx
    ON public.rm_o_resource_usage USING btree
    (id ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX rm_o_resource_usage_sched
    ON public.rm_o_resource_usage USING btree
    (schedule_id ASC NULLS LAST)
    TABLESPACE pg_default;
</code>```

```<code>CREATE TABLE public.scheduledactivities
(
    id bigint NOT NULL DEFAULT nextval('scheduledactivities_id_seq'::regclass),
    solution_id bigint NOT NULL,
    activity_id text COLLATE pg_catalog."default" NOT NULL,
    sequence_index integer,
    startminute integer,
    finishminute integer,
    issue text COLLATE pg_catalog."default",
    activity_index integer NOT NULL,
    is_objective boolean NOT NULL,
    usedresourceset integer DEFAULT '-1'::integer,
    start timestamp without time zone,
    finish timestamp without time zone,
    is_ore boolean,
    is_ignored boolean,
    CONSTRAINT scheduled_activities_pkey PRIMARY KEY (id),
    CONSTRAINT scheduledactivities_solution_id_fkey FOREIGN KEY (solution_id)
        REFERENCES public.rm_o_schedule_stats (id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

CREATE INDEX scheduled_activities_activity_id_idx
    ON public.scheduledactivities USING btree
    (activity_id COLLATE pg_catalog."default" ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX scheduled_activities_id_idx
    ON public.scheduledactivities USING btree
    (id ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX scheduled_activities_idx
    ON public.scheduledactivities USING btree
    (solution_id ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX scheduledactivities_activity_index_idx
    ON public.scheduledactivities USING btree
    (activity_index ASC NULLS LAST)
    TABLESPACE pg_default;
</code>```

EDIT: Additional output from auto_explain after adding index on scheduledactivities (solution_id, activity_index)

```<code>  Output: s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset
  Sort Key: r.resource_id, s.start_date
  Sort Method: quicksort  Memory: 6283kB
  Buffers: shared hit=20159117 read=375 dirtied=190
  ->  Nested Loop  (cost=0.85..10.76 rows=1 width=100) (actual time=5.518..122489.627 rows=20761 loops=1)
        Output: s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset
        Join Filter: (s.activity_index = sa.activity_index)
        Rows Removed by Join Filter: 668815615
        Buffers: shared hit=20159117 read=375 dirtied=190
        ->  Nested Loop  (cost=0.42..5.80 rows=1 width=112) (actual time=0.057..217.563 rows=20761 loops=1)
              Output: s.start_date, s.end_date, s.resources, s.activity_index, s.solution, r.resource_id, r.schedule_id
              Inner Unique: true
              Join Filter: (s.usage_id = r.id)
              Buffers: shared hit=20947 read=375 dirtied=190
              ->  Index Scan using rm_o_resource_usage_instance_splits_new_solution_idx on public.rm_o_resource_usage_instance_splits_new s  (cost=0.42..4.44 rows=1 width=69) (actual time=0.049..17.622 rows=20761 loops=1)
                    Output: s.start_time, s.end_time, s.resources, s.activity_index, s.usage_id, s.start_date, s.end_date, s.solution
                    Index Cond: (s.solution = 12644)
                    Buffers: shared hit=186 read=375 dirtied=190
              ->  Seq Scan on public.rm_o_resource_usage r  (cost=0.00..1.35 rows=1 width=59) (actual time=0.002..0.002 rows=1 loops=20761)
                    Output: r.id, r.schedule_id, r.resource_id
                    Filter: (r.schedule_id = 12644)
                    Rows Removed by Filter: 22
                    Buffers: shared hit=20761
        ->  Index Scan using scheduled_activities_idx on public.scheduledactivities sa  (cost=0.42..4.94 rows=1 width=16) (actual time=0.007..4.654 rows=32216 loops=20761)
              Output: sa.usedresourceset, sa.activity_index, sa.solution_id
              Index Cond: (sa.solution_id = 12644)
              Buffers: shared hit=20138170",,,,,,,,,""
</code>```

The easiest way to reproduce the issue is to add more values to the three tables. I didn't delete any, only did a few thousand INSERTs.

答:
```<code>->  Index Scan using .. s  (cost=0.42..8.44 rows=1 width=69) (actual time=0.082..17.418 rows=21899 loops=1)
                    Index Cond: (s.solution = 12642)
</code>```

The planner thinks it will find 1 row, and instead finds 21899. That error can pretty clearly lead to bad plans.  And a single equality condition should be estimated quite accurately, so I'd say the statistics on your table are way off.  It could be that the autovac launcher is tuned poorly so it doesn't run often enough, or it could be that select parts of your data change very rapidly (did you just insert 21899 rows with s.solution = 12642 immediately before running the query?) and so the stats can't be kept accurate enough.

```<code>  ->  Nested Loop ...
        Join Filter: (s.activity_index = sa.activity_index)
        Rows Removed by Join Filter: 705476285
        ->  ...
        ->  Index Scan using scheduled_activities_idx on public.scheduledactivities sa  (cost=0.42..4.60 rows=1 width=16) (actual time=0.006..4.612 rows=32216 loops=21899)
              Output: sa.usedresourceset, sa.activity_index, sa.solution_id
              Index Cond: (sa.solution_id = 12642)
</code>```

If you can't get it to use the Hash Join, you can at least reduce the harm of the Nested Loop by building an index on scheduledactivities (solution_id, activity_index).  That way the activity_index criterion could be part of the Index Condition, rather than being a Join Filter.  You could probably then drop the index exclusively on solution_id, as there is little point in maintaining both indexes.

Title: Seemingly Random Delay in queries

Body:
This is a follow up to this issue I posted a while ago.

I have the following code:

SET work_mem = '16MB';
SELECT      s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset
FROM        rm_o_resource_usage_instance_splits_new s
INNER JOIN  rm_o_resource_usage r ON s.usage_id = r.id
INNER JOIN  scheduledactivities sa ON s.activity_index = sa.activity_index AND r.schedule_id = sa.solution_id and s.solution = sa.solution_id
WHERE       r.schedule_id = 10
ORDER BY    r.resource_id, s.start_date

When I run EXPLAIN (ANALYZE, BUFFERS) I get the following:

Sort  (cost=3724.02..3724.29 rows=105 width=89) (actual time=245.802..247.573 rows=22302 loops=1)
  Sort Key: r.resource_id, s.start_date
  Sort Method: quicksort  Memory: 6692kB
  Buffers: shared hit=198702 read=5993 written=612
  ->  Nested Loop  (cost=703.76..3720.50 rows=105 width=89) (actual time=1.898..164.741 rows=22302 loops=1)
        Buffers: shared hit=198702 read=5993 written=612
        ->  Hash Join  (cost=703.34..3558.54 rows=105 width=101) (actual time=1.815..11.259 rows=22302 loops=1)
              Hash Cond: (s.usage_id = r.id)
              Buffers: shared hit=3 read=397 written=2
              ->  Bitmap Heap Scan on rm_o_resource_usage_instance_splits_new s  (cost=690.61..3486.58 rows=22477 width=69) (actual time=1.782..5.820 rows=22302 loops=1)
                    Recheck Cond: (solution = 10)
                    Heap Blocks: exact=319
                    Buffers: shared hit=2 read=396 written=2
                    ->  Bitmap Index Scan on rm_o_resource_usage_instance_splits_new_solution_idx  (cost=0.00..685.00 rows=22477 width=0) (actual time=1.609..1.609 rows=22302 loops=1)
                          Index Cond: (solution = 10)
                          Buffers: shared hit=2 read=77
              ->  Hash  (cost=12.66..12.66 rows=5 width=48) (actual time=0.023..0.023 rows=1 loops=1)
                    Buckets: 1024  Batches: 1  Memory Usage: 9kB
                    Buffers: shared hit=1 read=1
                    ->  Bitmap Heap Scan on rm_o_resource_usage r  (cost=4.19..12.66 rows=5 width=48) (actual time=0.020..0.020 rows=1 loops=1)
                          Recheck Cond: (schedule_id = 10)
                          Heap Blocks: exact=1
                          Buffers: shared hit=1 read=1
                          ->  Bitmap Index Scan on rm_o_resource_usage_sched  (cost=0.00..4.19 rows=5 width=0) (actual time=0.017..0.017 rows=1 loops=1)
                                Index Cond: (schedule_id = 10)
                                Buffers: shared read=1
        ->  Index Scan using scheduledactivities_activity_index_idx on scheduledactivities sa  (cost=0.42..1.53 rows=1 width=16) (actual time=0.004..0.007 rows=1 loops=22302)
              Index Cond: (activity_index = s.activity_index)
              Filter: (solution_id = 10)
              Rows Removed by Filter: 5
              Buffers: shared hit=198699 read=5596 written=610
Planning time: 7.070 ms
Execution time: 248.691 ms

Every time I run EXPLAIN, I get roughly the same results. The Execution Time is always between 170ms and 250ms, which, to me is perfectly fine. However, when this query is run through a C++ project (using PQexec(conn, query) where conn is a dedicated connection, and query is the above query), the time it takes seems to vary widely. In general, the query is very quick, and you don't notice a delay. The problem is, that on occasion, this query will take 2 to 3 minutes to complete.

If I open the pgadmin, and have a look at the "server activity" for the database, there's about 30 or so connections, mostly sitting at "idle". The above query's connection is marked as "active", and will stay as "active" for several minutes.

I am at a loss of why it randomly takes several minutes to complete the same query, with no change in data in the DB either. I have tried increasing the work_mem which didn't make any difference (nor did I really expect it to). Any help or suggestions would be greatly appreciated.

There isn't any more specific tags, but I'm currently using Postgres 10.11, but it's also been an issue on other versions of 10.x. System is a Xeon quad-core @ 3.4Ghz, with SSD and 24GB of memory.

Per jjanes's suggestion, I put in the auto_explain. Eventually go this output:

duration: 128057.373 ms
plan:
Query Text: SET work_mem = '32MB';SELECT        s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset FROM     rm_o_resource_usage_instance_splits_new s INNER JOIN    rm_o_resource_usage r ON s.usage_id = r.id INNER JOIN  scheduledactivities sa ON s.activity_index = sa.activity_index AND r.schedule_id = sa.solution_id and s.solution = sa.solution_id WHERE      r.schedule_id = 12642 ORDER BY   r.resource_id, s.start_date
Sort  (cost=14.36..14.37 rows=1 width=98) (actual time=128042.083..128043.287 rows=21899 loops=1)
  Output: s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset
  Sort Key: r.resource_id, s.start_date
  Sort Method: quicksort  Memory: 6585kB
  Buffers: shared hit=21198435 read=388 dirtied=119
  ->  Nested Loop  (cost=0.85..14.35 rows=1 width=98) (actual time=4.995..127958.935 rows=21899 loops=1)
        Output: s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset
        Join Filter: (s.activity_index = sa.activity_index)
        Rows Removed by Join Filter: 705476285
        Buffers: shared hit=21198435 read=388 dirtied=119
        ->  Nested Loop  (cost=0.42..9.74 rows=1 width=110) (actual time=0.091..227.705 rows=21899 loops=1)
              Output: s.start_date, s.end_date, s.resources, s.activity_index, s.solution, r.resource_id, r.schedule_id
              Inner Unique: true
              Join Filter: (s.usage_id = r.id)
              Buffers: shared hit=22102 read=388 dirtied=119
              ->  Index Scan using rm_o_resource_usage_instance_splits_new_solution_idx on public.rm_o_resource_usage_instance_splits_new s  (cost=0.42..8.44 rows=1 width=69) (actual time=0.082..17.418 rows=21899 loops=1)
                    Output: s.start_time, s.end_time, s.resources, s.activity_index, s.usage_id, s.start_date, s.end_date, s.solution
                    Index Cond: (s.solution = 12642)
                    Buffers: shared hit=203 read=388 dirtied=119
              ->  Seq Scan on public.rm_o_resource_usage r  (cost=0.00..1.29 rows=1 width=57) (actual time=0.002..0.002 rows=1 loops=21899)
                    Output: r.id, r.schedule_id, r.resource_id
                    Filter: (r.schedule_id = 12642)
                    Rows Removed by Filter: 26
                    Buffers: shared hit=21899
        ->  Index Scan using scheduled_activities_idx on public.scheduledactivities sa  (cost=0.42..4.60 rows=1 width=16) (actual time=0.006..4.612 rows=32216 loops=21899)
              Output: sa.usedresourceset, sa.activity_index, sa.solution_id
              Index Cond: (sa.solution_id = 12642)
              Buffers: shared hit=21176333",,,,,,,,,""

EDIT: Full definitions of the tables are below:

CREATE TABLE public.rm_o_resource_usage_instance_splits_new
(
    start_time integer NOT NULL,
    end_time integer NOT NULL,
    resources jsonb NOT NULL,
    activity_index integer NOT NULL,
    usage_id bigint NOT NULL,
    start_date text COLLATE pg_catalog."default" NOT NULL,
    end_date text COLLATE pg_catalog."default" NOT NULL,
    solution bigint NOT NULL,
    CONSTRAINT rm_o_resource_usage_instance_splits_new_pkey PRIMARY KEY (start_time, activity_index, usage_id),
    CONSTRAINT rm_o_resource_usage_instance_splits_new_solution_fkey FOREIGN KEY (solution)
        REFERENCES public.rm_o_schedule_stats (id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE,
    CONSTRAINT rm_o_resource_usage_instance_splits_new_usage_id_fkey FOREIGN KEY (usage_id)
        REFERENCES public.rm_o_resource_usage (id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

CREATE INDEX rm_o_resource_usage_instance_splits_new_activity_idx
    ON public.rm_o_resource_usage_instance_splits_new USING btree
    (activity_index ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX rm_o_resource_usage_instance_splits_new_solution_idx
    ON public.rm_o_resource_usage_instance_splits_new USING btree
    (solution ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX rm_o_resource_usage_instance_splits_new_usage_idx
    ON public.rm_o_resource_usage_instance_splits_new USING btree
    (usage_id ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE TABLE public.rm_o_resource_usage
(
    id bigint NOT NULL DEFAULT nextval('rm_o_resource_usage_id_seq'::regclass),
    schedule_id bigint NOT NULL,
    resource_id text COLLATE pg_catalog."default" NOT NULL,
    CONSTRAINT rm_o_resource_usage_pkey PRIMARY KEY (id),
    CONSTRAINT rm_o_resource_usage_schedule_id_fkey FOREIGN KEY (schedule_id)
        REFERENCES public.rm_o_schedule_stats (id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

CREATE INDEX rm_o_resource_usage_idx
    ON public.rm_o_resource_usage USING btree
    (id ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX rm_o_resource_usage_sched
    ON public.rm_o_resource_usage USING btree
    (schedule_id ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE TABLE public.scheduledactivities
(
    id bigint NOT NULL DEFAULT nextval('scheduledactivities_id_seq'::regclass),
    solution_id bigint NOT NULL,
    activity_id text COLLATE pg_catalog."default" NOT NULL,
    sequence_index integer,
    startminute integer,
    finishminute integer,
    issue text COLLATE pg_catalog."default",
    activity_index integer NOT NULL,
    is_objective boolean NOT NULL,
    usedresourceset integer DEFAULT '-1'::integer,
    start timestamp without time zone,
    finish timestamp without time zone,
    is_ore boolean,
    is_ignored boolean,
    CONSTRAINT scheduled_activities_pkey PRIMARY KEY (id),
    CONSTRAINT scheduledactivities_solution_id_fkey FOREIGN KEY (solution_id)
        REFERENCES public.rm_o_schedule_stats (id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

CREATE INDEX scheduled_activities_activity_id_idx
    ON public.scheduledactivities USING btree
    (activity_id COLLATE pg_catalog."default" ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX scheduled_activities_id_idx
    ON public.scheduledactivities USING btree
    (id ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX scheduled_activities_idx
    ON public.scheduledactivities USING btree
    (solution_id ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX scheduledactivities_activity_index_idx
    ON public.scheduledactivities USING btree
    (activity_index ASC NULLS LAST)
    TABLESPACE pg_default;

EDIT: Additional output from auto_explain after adding index on scheduledactivities (solution_id, activity_index)

  Output: s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset
  Sort Key: r.resource_id, s.start_date
  Sort Method: quicksort  Memory: 6283kB
  Buffers: shared hit=20159117 read=375 dirtied=190
  ->  Nested Loop  (cost=0.85..10.76 rows=1 width=100) (actual time=5.518..122489.627 rows=20761 loops=1)
        Output: s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset
        Join Filter: (s.activity_index = sa.activity_index)
        Rows Removed by Join Filter: 668815615
        Buffers: shared hit=20159117 read=375 dirtied=190
        ->  Nested Loop  (cost=0.42..5.80 rows=1 width=112) (actual time=0.057..217.563 rows=20761 loops=1)
              Output: s.start_date, s.end_date, s.resources, s.activity_index, s.solution, r.resource_id, r.schedule_id
              Inner Unique: true
              Join Filter: (s.usage_id = r.id)
              Buffers: shared hit=20947 read=375 dirtied=190
              ->  Index Scan using rm_o_resource_usage_instance_splits_new_solution_idx on public.rm_o_resource_usage_instance_splits_new s  (cost=0.42..4.44 rows=1 width=69) (actual time=0.049..17.622 rows=20761 loops=1)
                    Output: s.start_time, s.end_time, s.resources, s.activity_index, s.usage_id, s.start_date, s.end_date, s.solution
                    Index Cond: (s.solution = 12644)
                    Buffers: shared hit=186 read=375 dirtied=190
              ->  Seq Scan on public.rm_o_resource_usage r  (cost=0.00..1.35 rows=1 width=59) (actual time=0.002..0.002 rows=1 loops=20761)
                    Output: r.id, r.schedule_id, r.resource_id
                    Filter: (r.schedule_id = 12644)
                    Rows Removed by Filter: 22
                    Buffers: shared hit=20761
        ->  Index Scan using scheduled_activities_idx on public.scheduledactivities sa  (cost=0.42..4.94 rows=1 width=16) (actual time=0.007..4.654 rows=32216 loops=20761)
              Output: sa.usedresourceset, sa.activity_index, sa.solution_id
              Index Cond: (sa.solution_id = 12644)
              Buffers: shared hit=20138170",,,,,,,,,""

The easiest way to reproduce the issue is to add more values to the three tables. I didn't delete any, only did a few thousand INSERTs.

Body:
->  Index Scan using .. s  (cost=0.42..8.44 rows=1 width=69) (actual time=0.082..17.418 rows=21899 loops=1)
                    Index Cond: (s.solution = 12642)

The planner thinks it will find 1 row, and instead finds 21899. That error can pretty clearly lead to bad plans.  And a single equality condition should be estimated quite accurately, so I'd say the statistics on your table are way off.  It could be that the autovac launcher is tuned poorly so it doesn't run often enough, or it could be that select parts of your data change very rapidly (did you just insert 21899 rows with s.solution = 12642 immediately before running the query?) and so the stats can't be kept accurate enough.

  ->  Nested Loop ...
        Join Filter: (s.activity_index = sa.activity_index)
        Rows Removed by Join Filter: 705476285
        ->  ...
        ->  Index Scan using scheduled_activities_idx on public.scheduledactivities sa  (cost=0.42..4.60 rows=1 width=16) (actual time=0.006..4.612 rows=32216 loops=21899)
              Output: sa.usedresourceset, sa.activity_index, sa.solution_id
              Index Cond: (sa.solution_id = 12642)

If you can't get it to use the Hash Join, you can at least reduce the harm of the Nested Loop by building an index on scheduledactivities (solution_id, activity_index).  That way the activity_index criterion could be part of the Index Condition, rather than being a Join Filter.  You could probably then drop the index exclusively on solution_id, as there is little point in maintaining both indexes.


问:
Timeout interval in Javascript: How to end timeout
How can I implement into the TimerBreed function the ability to end the repeated autobreed function

e.g. when whichFrog == "second" make the first and third autoBreed loop end so that only the second autoBreed loop is being carried out.

```<code>function autoBreed(x, value1, value2, value3){
    population[x] = population[x] + 1;
    setTimeout(autoBreed, 1000, x, value1, value2, value3);
    document.getElementById(value1.toString()).innerHTML = "+1 PER SECOND";
    document.getElementById(value2.toString()).innerHTML = "<b>" + value3.toString() + "</b> Population: " + population[x];
}
</code>```

```<code>function timerBreed(buttonVar, whichFrog){
    if (whichFrog == "first"){
        autoBreed(0, "autoParaOne", "valueFrogPopOne", "First");
    } else if (whichFrog == "second"){
        autoBreed(1, "autoParaTwo", "valueFrogPopTwo", "Second");
    } else if (whichFrog == "third"){
        autoBreed(2, "autoParaThree", "valueFrogPopThree", "Third");
    }
}
</code>```

答:
If you declare the setTimeout id in the outer scope or make it a global variable, you will be able to clear the timer from either of the functions.

```<code>let timer;
function autoBreed(x, value1, value2, value3){
    population[x] = population[x] + 1;
    timer = setTimeout(autoBreed, 1000, x, value1, value2, value3);
    document.getElementById(value1.toString()).innerHTML = "+1 PER SECOND";
    document.getElementById(value2.toString()).innerHTML = "<b>" + value3.toString() + "</b> Population: " + population[x];
}

function timerBreed(buttonVar, whichFrog){
    if (whichFrog == "first"){
        autoBreed(0, "autoParaOne", "valueFrogPopOne", "First");
    } else if (whichFrog == "second"){
        //autoBreed(1, "autoParaTwo", "valueFrogPopTwo", "Second");
        clearTimeout(timer);
    } else if (whichFrog == "third"){
        autoBreed(2, "autoParaThree", "valueFrogPopThree", "Third");
    }
}
</code>```

Body:
How can I implement into the TimerBreed function the ability to end the repeated autobreed function

e.g. when whichFrog == "second" make the first and third autoBreed loop end so that only the second autoBreed loop is being carried out.

function autoBreed(x, value1, value2, value3){
    population[x] = population[x] + 1;
    setTimeout(autoBreed, 1000, x, value1, value2, value3);
    document.getElementById(value1.toString()).innerHTML = "+1 PER SECOND";
    document.getElementById(value2.toString()).innerHTML = "" + value3.toString() + " Population: " + population[x];
}

function timerBreed(buttonVar, whichFrog){
    if (whichFrog == "first"){
        autoBreed(0, "autoParaOne", "valueFrogPopOne", "First");
    } else if (whichFrog == "second"){
        autoBreed(1, "autoParaTwo", "valueFrogPopTwo", "Second");
    } else if (whichFrog == "third"){
        autoBreed(2, "autoParaThree", "valueFrogPopThree", "Third");
    }
}

Body:
If you declare the setTimeout id in the outer scope or make it a global variable, you will be able to clear the timer from either of the functions.

let timer;
function autoBreed(x, value1, value2, value3){
    population[x] = population[x] + 1;
    timer = setTimeout(autoBreed, 1000, x, value1, value2, value3);
    document.getElementById(value1.toString()).innerHTML = "+1 PER SECOND";
    document.getElementById(value2.toString()).innerHTML = "<b>" + value3.toString() + "</b> Population: " + population[x];
}

function timerBreed(buttonVar, whichFrog){
    if (whichFrog == "first"){
        autoBreed(0, "autoParaOne", "valueFrogPopOne", "First");
    } else if (whichFrog == "second"){
        //autoBreed(1, "autoParaTwo", "valueFrogPopTwo", "Second");
        clearTimeout(timer);
    } else if (whichFrog == "third"){
        autoBreed(2, "autoParaThree", "valueFrogPopThree", "Third");
    }
}


问:
WordPress "Loading mixed (insecure) display content on a secure page"
I'm pretty new to web development. I developed this website using WordPress.
It works fine and it has a SSL certificate as well.

On the homepage, I can see the secure icon (lock icon) in the URL box but when I navigate to the about us page, I get the following error message in the console and I don't get to see the secure icon in the URL box

```<code>Loading mixed (insecure) display content “http://52.76.129.235/wp-content/uploads/2020/01/uam-footer.jpg” on a secure page
</code>```

I tried to debug the error. These are the things I did:

Used a plugin called Better Search Replace to replace http to https

Manually changed all values that had http in database to https

Added define('FORCE_SSL_ADMIN', true); to wp-config.php in WordPress root folder

Can anyone tell me how to fix this error? I tried to locate the URL given in the error message, but I didn't find it.

答:
Sure, it is super easy just you need to follow some steps.

Install and Activate the Really Simple SSL plugin.

After activation, a notice will appear at the top with a button saying Go Ahead, Activate SSL, click on the button to do so.

Now, go to Settings > SSL and enable the WordPress 301 redirect in the toggle.

That's it for simple. You can also buy the Really Simple SSL Pro if you need additional configuration.

Don't hesitate to contact me for further response. I hope the method worked for you.

Body:
I'm pretty new to web development. I developed this website using WordPress.
It works fine and it has a SSL certificate as well.

On the homepage, I can see the secure icon (lock icon) in the URL box but when I navigate to the about us page, I get the following error message in the console and I don't get to see the secure icon in the URL box

Loading mixed (insecure) display content “http://52.76.129.235/wp-content/uploads/2020/01/uam-footer.jpg” on a secure page

I tried to debug the error. These are the things I did:

Used a plugin called Better Search Replace to replace http to https

Manually changed all values that had http in database to https

Added define('FORCE_SSL_ADMIN', true); to wp-config.php in WordPress root folder

Can anyone tell me how to fix this error? I tried to locate the URL given in the error message, but I didn't find it.


问:
Wordpress Product Attribute custom permalink
I want to change product attribute base url permalink.

For example : www.mystore.com/color/blue
and my desired url is : www.mystore.com/blue

Please help..

Thanks a lot

答:
First, you need to check the option "Enable Archives?" to enable the attribute to be viewable on the front end as an archive page. Then to change the URL you can edit the slug.

The final URL is as the following:
www.mystore.com/{attribute_slug}/{term_slug}

Thanks


问:
TypeError when I use Typescript with VueJS
I try to start using typescript with VueJS but I encounter a TypeError problem.

In my App.vue, I have a array of Gallery class as a class property.
In the created hook, I call a webservice to fill this array.
Once I fill it, when I log it, I have Objects and not Gallery instances. And if I try to call a function on a Gallery instance, it fails.
I think the problem is more a TS problem than a Vue problem.

I can't understand why I have actually an array of Object when I say everywhere I need an array of Gallery.

If anyone has a idea to help me, I'm more than interrested.

Thanks for reading. I paste you all my code below.

Have a nice day ;)

Dimitri

App.vue

```<code><template>
    <div>
        <CvGallery v-for="(gallery, i) in galleries" gallery="gallery" :key="i"></CvGallery>
    </div>
</template>

<script lang="ts">
    import { Component, Vue } from 'vue-property-decorator';
    import CvGallery from "@/components/CvGallery.vue";
    import Gallery from "@/models/Gallery";
    import axios from "@/axios/axios-creatiview"

    @Component({
        components: {
            CvGallery
        },
    })
    export default class App extends Vue {
        private galleries: Gallery[] = [];

        created() {
            axios.get('').then(response => {
                console.log(response.data);
                response.data.forEach((galleryJson: {id: number; name: string; description: string}) => {
                    const gallery = new Gallery(galleryJson.id, galleryJson.name, galleryJson.description);
                    this.galleries.push(gallery);
                    console.log(typeof gallery);
                });
            });
        }
    }
</script>

<style>
</style>
</code>```

Gallery.ts

```<code>export default class Gallery{
    private readonly id: number;
    private readonly name: string;
    private readonly description: string;

    constructor(id: number, name: string, description: string) {
        this.id = id;
        this.name = name;
        this.description = description;
    }

    getId(){
        return this.id;
    }

    getName(){
        return this.name;
    }

    getDescription(){
        return this.description;
    }
}
</code>```

CvGallery.vue

```<code><template>
    <div class="gallery">
        <p>Gallery</p>
        <p>{{ gallery.getDescription() }}</p>
    </div>
</template>

<script lang="ts">
    import {Component, Vue, Prop} from 'vue-property-decorator'
    import Gallery from "@/models/Gallery";
    @Component
    export default class CvGallery extends Vue{
        @Prop() private gallery!: Gallery;
    }
</script>

<style scoped>
    .gallery{
        background-color: #222222;
        color: #DDDDDD;
    }
</style>
</code>```

log

```<code>16:16:42,658 [HMR] Waiting for update signal from WDS... log.js:24
16:16:42,771
(3) […]

0: Object { id: 1, name: "DisneyWorld", description: "First trip to DisneyWorld Florida!" }

1: Object { id: 2, name: "Europapark", description: "The best German park" }

2: Object { id: 3, name: "Disneyland Paris", description: "A lot of walkthrough attractions" }

length: 3

<prototype>: Array []
App.vue:23
16:16:42,772 object 3 App.vue:27
16:16:42,774 [Vue warn]: Error in render: "TypeError: _vm.gallery.getDescription is not a function"

found in

---> <CvGallery> at src/components/CvGallery.vue
       <App> at src/App.vue
         <Root> vue.runtime.esm.js:619
16:16:42,774 TypeError: "_vm.gallery.getDescription is not a function"
    render CvGallery.vue:7
    VueJS 20
vue.runtime.esm.js:1888
16:16:42,775 [Vue warn]: Error in render: "TypeError: _vm.gallery.getDescription is not a function"

found in

---> <CvGallery> at src/components/CvGallery.vue
       <App> at src/App.vue
         <Root> vue.runtime.esm.js:619
16:16:42,775 TypeError: "_vm.gallery.getDescription is not a function"
    render CvGallery.vue:7
    VueJS 20
vue.runtime.esm.js:1888
16:16:42,776 [Vue warn]: Error in render: "TypeError: _vm.gallery.getDescription is not a function"

found in

---> <CvGallery> at src/components/CvGallery.vue
       <App> at src/App.vue
         <Root> vue.runtime.esm.js:619
16:16:42,776 TypeError: "_vm.gallery.getDescription is not a function"
    render CvGallery.vue:7
    VueJS 20
vue.runtime.esm.js:1888

</code>```

答:
This is not TypeScript problem because the error occurs at runtime, it would be the same in JavaScript.

vm.gallery.getDescription is not a function error means that gallery is defined, otherwise it would be Cannot read property 'getDescription' of undefined. It also means that gallery is not an instance of Gallery, otherwise there would be getDescription method.

Since there are no mistakes in created hook, the problem can be narrowed down to how gallery is passed to the component; it's a string value:

```<code><CvGallery v-for="(gallery, i) in galleries" gallery="gallery" :key="i"></CvGallery>
</code>```

Instead, it should be bound:

```<code><CvGallery v-for="(gallery, i) in galleries" :gallery="gallery" :key="i"></CvGallery>
</code>```

Body:
I try to start using typescript with VueJS but I encounter a TypeError problem.

In my App.vue, I have a array of Gallery class as a class property.
In the created hook, I call a webservice to fill this array.
Once I fill it, when I log it, I have Objects and not Gallery instances. And if I try to call a function on a Gallery instance, it fails.
I think the problem is more a TS problem than a Vue problem.

I can't understand why I have actually an array of Object when I say everywhere I need an array of Gallery.

If anyone has a idea to help me, I'm more than interrested.

Thanks for reading. I paste you all my code below.

Have a nice day ;)

Dimitri

App.vue

<template>

        <CvGallery v-for="(gallery, i) in galleries" gallery="gallery" :key="i"></CvGallery>

</template>

Gallery.ts

export default class Gallery{
    private readonly id: number;
    private readonly name: string;
    private readonly description: string;

    constructor(id: number, name: string, description: string) {
        this.id = id;
        this.name = name;
        this.description = description;
    }

    getId(){
        return this.id;
    }

    getName(){
        return this.name;
    }

    getDescription(){
        return this.description;
    }
}

CvGallery.vue

<template>

Gallery

{{ gallery.getDescription() }}

</template>

log

16:16:42,658 [HMR] Waiting for update signal from WDS... log.js:24
16:16:42,771
(3) […]

0: Object { id: 1, name: "DisneyWorld", description: "First trip to DisneyWorld Florida!" }

1: Object { id: 2, name: "Europapark", description: "The best German park" }

2: Object { id: 3, name: "Disneyland Paris", description: "A lot of walkthrough attractions" }

length: 3

<prototype>: Array []
App.vue:23
16:16:42,772 object 3 App.vue:27
16:16:42,774 [Vue warn]: Error in render: "TypeError: _vm.gallery.getDescription is not a function"

found in

---> <CvGallery> at src/components/CvGallery.vue
       <App> at src/App.vue
         <Root> vue.runtime.esm.js:619
16:16:42,774 TypeError: "_vm.gallery.getDescription is not a function"
    render CvGallery.vue:7
    VueJS 20
vue.runtime.esm.js:1888
16:16:42,775 [Vue warn]: Error in render: "TypeError: _vm.gallery.getDescription is not a function"

found in

---> <CvGallery> at src/components/CvGallery.vue
       <App> at src/App.vue
         <Root> vue.runtime.esm.js:619
16:16:42,775 TypeError: "_vm.gallery.getDescription is not a function"
    render CvGallery.vue:7
    VueJS 20
vue.runtime.esm.js:1888
16:16:42,776 [Vue warn]: Error in render: "TypeError: _vm.gallery.getDescription is not a function"

found in

---> <CvGallery> at src/components/CvGallery.vue
       <App> at src/App.vue
         <Root> vue.runtime.esm.js:619
16:16:42,776 TypeError: "_vm.gallery.getDescription is not a function"
    render CvGallery.vue:7
    VueJS 20
vue.runtime.esm.js:1888

Body:
This is not TypeScript problem because the error occurs at runtime, it would be the same in JavaScript.

vm.gallery.getDescription is not a function error means that gallery is defined, otherwise it would be Cannot read property 'getDescription' of undefined. It also means that gallery is not an instance of Gallery, otherwise there would be getDescription method.

Since there are no mistakes in created hook, the problem can be narrowed down to how gallery is passed to the component; it's a string value:

<CvGallery v-for="(gallery, i) in galleries" gallery="gallery" :key="i"></CvGallery>

Instead, it should be bound:

<CvGallery v-for="(gallery, i) in galleries" :gallery="gallery" :key="i"></CvGallery>


问:
Electron application shows black screen while running on windows 7 operating system
I am totally new to electron projects. I am facing issue is black screen shows on windows 7(64bit, 2GB ram). But runs perfectly in windows 8, windows 7(64bit, 4GB ram), windows 10 systems . Anyone give solution for this issue.

Used electron version:

```<code>"devDependencies":
{
"electron": "^6.0.10"
}
</code>```

Used Windows 7 system specification:

```<code>Details:
Windows 7 Professional
Ram : 2.00 GB
Processor : Intel(R)Core(TM)i5 CPU M540 @2.53GHz 2.53GHz
system type : 64-bit Operating sysytem
</code>```

答:
Have you installed .NET 4.7.1 or later on the Windows 7 machine?

https://github.com/electron/electron/issues/19569

Body:
I am totally new to electron projects. I am facing issue is black screen shows on windows 7(64bit, 2GB ram). But runs perfectly in windows 8, windows 7(64bit, 4GB ram), windows 10 systems . Anyone give solution for this issue.

Used electron version:

"devDependencies":
{
"electron": "^6.0.10"
}

Used Windows 7 system specification:

Details:
Windows 7 Professional
Ram : 2.00 GB
Processor : Intel(R)Core(TM)i5 CPU M540 @2.53GHz 2.53GHz
system type : 64-bit Operating sysytem


问:
Azure Service Bus Queue - Operation is not valid due to the current state of the object
I am using Azure Service Bus Queues in one of my .net core application to receive the messages from the Queue in the FIFO order. Once received the message from the Queue, then I have processed the business logic with each message. Once processed the business logic with each message then I am trying to delete the message from Queue with following line of code:

```<code>await _messageReceiver.CompleteAsync(message.SystemProperties.LockToken);
</code>```

But for the few messages, I am unable to delete the messages from Queue. Because lock on the message expired even though I configured the “Lock Duration” 3 minutes on Service Bus Queue.

I am getting the following error while deleting/completing the message from Service Bus Queue:

Exception Type: System.InvalidOperationException

Exception Message: Operation is not valid due to the current state of the object.

These are properties I configured on the Azure Service Bus Queue:

```<code>Max Delivery Count =1
Lock Duration=3 minutes
</code>```

答:
There are a few reasons why you are not able to delete the messages in Azure Service Bus Queue.

Challenge with Lock Duration

The first challenge is Time, specifically lock duration for every message once they have been retrieved. The problem is that the messages must be displayed in the UI and then provide time for the customer to choose the messages to be resubmitted or deleted. The solution would be to ask the customer to increase the lock duration, but this is not possible due to several reasons. Firstly, increasing lock duration might not be possible due to customer integration, so we cannot depend on that.

Read more on this blog post on how to overcome the challenge.

Body:
I am using Azure Service Bus Queues in one of my .net core application to receive the messages from the Queue in the FIFO order. Once received the message from the Queue, then I have processed the business logic with each message. Once processed the business logic with each message then I am trying to delete the message from Queue with following line of code:

await _messageReceiver.CompleteAsync(message.SystemProperties.LockToken);

But for the few messages, I am unable to delete the messages from Queue. Because lock on the message expired even though I configured the “Lock Duration” 3 minutes on Service Bus Queue.

I am getting the following error while deleting/completing the message from Service Bus Queue:

Exception Type: System.InvalidOperationException

Exception Message: Operation is not valid due to the current state of the object.

These are properties I configured on the Azure Service Bus Queue:

Max Delivery Count =1
Lock Duration=3 minutes


问:
Auto increment MySQL decimal number problems
I am building an application that will have one table of clients that has an autoincrement id INT field. Then I have an HTML "case" form where the user will have to chose a client from the dropdown, then add some info about "case" that will go into another table.

That means that the client will have an id of 1,2,3 and so on. And I would like that the case adds one decimal number on id number of the client chosen from dropdown. So for Client number two + 1: 2.1, 2.2 and so on. Client number 3, 3.1, 3.2 etc.

What is the best way to add that case filed to SQL? I see if I chose Decimal for a case id field I'm getting number 3.4 as 3.400 because I have chosen decimal 4,3 (MySQL) for testing. I Need to have such decimals because the number of cases can go to hundreds, I can not trim that. I'm struggling with the type of MySQL fields and how to approach this problem.
I'd appreciate some guidance.

The only thing I can think of is to pass the value of a client and then do id + "." + 1, and store it as decimal 1,1 (MySQL), will that auto autoincrement to 1.2 and so on?

答:
Don't do it. This is the best piece of advise I can give to you.

You are trying to use what was called "Inteligent Codes" back in the 80s.

They went out of fashion for a good reason. Very expensive to develop, non-mantainable, limited ranges, you-name-it. Stay away from them and use normal foreign keys instead. They give you all the flexibility you'll need when the application grows.