问:
VSCODE & GitHub Desktop pre-commit hook: npx: command not found
I am starting a new repo, thinking I should use the most recent Huksy v6 which is installed from LintStaged using their setup guide:

```<code>npx mrm lint-staged

// package.json updated with:
"husky": ">=6",
"lint-staged": ">=10",
</code>```

This adds necessary packages and adds the husky files including the precommit files:

```<code>#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx lint-staged
</code>```

When i run my commit in the terminal it works fine.  However, if I try to run my commit in GitHub Desktop or VSCode (which I know some teammates do), it results in an error for both:

npx: command not found.  husky - pre-commit hook exited with code 127 (error)

I have npx installed:

```<code>npx -v
// 6.14.10
</code>```

If I try to install in globall, such as described in other StackOverflow suggestions, it returns a warning about existing location (with & with out sudo):

ERR! EEXIST: file already exists, symlink '../lib/node_modules/npx/index.js' -> '/Users/plucks/.nvm/versions/node/v14.15.4/bin/npx'
npm ERR! File exists: /Users/plucks/.nvm/versions/node/v14.15.4/bin/npx
npm ERR! Remove the existing file and try again, or run npm
npm ERR! with --force to overwrite files recklessly.

Is there anything I can do so the programs like VSCode & GitHub Desktop can run?

答:
For husky>=6: update your .husky/pre-commit file to contain this:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

npx lint-staged
```

This will find and expose the current node path and therefore npx path that you are using, which has been configured with Node Version Manager nvm

Body:
I am starting a new repo, thinking I should use the most recent Huksy v6 which is installed from LintStaged using their setup guide:

npx mrm lint-staged

// package.json updated with:
"husky": ">=6",
"lint-staged": ">=10",

This adds necessary packages and adds the husky files including the precommit files:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx lint-staged

When i run my commit in the terminal it works fine.  However, if I try to run my commit in GitHub Desktop or VSCode (which I know some teammates do), it results in an error for both:

npx: command not found.  husky - pre-commit hook exited with code 127 (error)

I have npx installed:

npx -v
// 6.14.10

If I try to install in globall, such as described in other StackOverflow suggestions, it returns a warning about existing location (with & with out sudo):

ERR! EEXIST: file already exists, symlink '../lib/node_modules/npx/index.js' -> '/Users/plucks/.nvm/versions/node/v14.15.4/bin/npx'
npm ERR! File exists: /Users/plucks/.nvm/versions/node/v14.15.4/bin/npx
npm ERR! Remove the existing file and try again, or run npm
npm ERR! with --force to overwrite files recklessly.

Is there anything I can do so the programs like VSCode & GitHub Desktop can run?

Body:
For husky>=6: update your .husky/pre-commit file to contain this:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

npx lint-staged

This will find and expose the current node path and therefore npx path that you are using, which has been configured with Node Version Manager nvm


来源: stackexchange

问:
How to debug connection problem for SchemaSpy with MySQL (using password: NO)?
I have a no-login variant of mysql running on my machine. So I just type mysql for getting a mysql client shell.

No when I am trying to let SchemaSpy connect to mysql it fails:

```<code># try with my user:
java -jar schemaSpy_5.0.0.jar -t mysql -dp /home/bodo/bin/mysql_conn/mysql-connector-java-5.1.49/mysql-connector-java-5.1.49-bin.jar -host localhost -u bodo -db ibo -o /home/bodo/bin/schemaspy/ibo
Using database properties:
  [schemaSpy_5.0.0.jar]/net/sourceforge/schemaspy/dbTypes/mysql.properties
Thu Feb 10 17:01:05 CET 2022 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

Failed to connect to database URL [jdbc:mysql://localhost/ibo]

java.sql.SQLException: Access denied for user 'bodo'@'localhost' (using password: NO)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:965)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3933)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3869)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:864)
    at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1707)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1217)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2189)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2220)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2015)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:768)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:403)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:385)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:323)
    at net.sourceforge.schemaspy.SchemaAnalyzer.getConnection(SchemaAnalyzer.java:582)
    at net.sourceforge.schemaspy.SchemaAnalyzer.analyze(SchemaAnalyzer.java:157)
    at net.sourceforge.schemaspy.Main.main(Main.java:42)

# try without user does not work at all
bodo@bodo-work:~/bin/schemaspy$ java -jar schemaSpy_5.0.0.jar -t mysql -dp /home/bodo/bin/mysql_conn/mysql-connector-java-5.1.49/mysql-connector-java-5.1.49-bin.jar -host localhost -db ibo -o /home/bodo/bin/schemaspy/ibo

net.sourceforge.schemaspy.Config$MissingRequiredParameterException: Required parameter '-u' was not specified.
</code>```

So the point is Access denied for user 'bodo'@'localhost' (using password: NO)

How can I debug this or how do I need to change my MySQL setup in order to let SchemaSpy run?

答:
I have solved the connection problem by granting the user in question access to the database and by using a password.

When you have this situation:

```<code>mysql -u bodo
ERROR 1045 (28000): Access denied for user 'bodo'@'localhost' (using password: NO)
</code>```

and you have no anonymous user

this can help:

ALTER USER 'bodo'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_pssw';

GRANT ALL PRIVILEGES ON *.* TO 'bodo'@'localhost' WITH GRANT OPTION;

Do not forget to FLUSH PRIVILEGES;.

Then you should be able to use:

```<code>mysql -u bodo -p ibo -h localhost
Enter password:
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 22
Server version: 8.0.28-0ubuntu0.20.04.3 (Ubuntu)

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>
</code>```

References

AskUbuntu, SO1, SO2, Docs.

ContentLicense: CC BY-SA 4.0

Body:
I have a no-login variant of mysql running on my machine. So I just type mysql for getting a mysql client shell.

No when I am trying to let SchemaSpy connect to mysql it fails:

# try with my user:
java -jar schemaSpy_5.0.0.jar -t mysql -dp /home/bodo/bin/mysql_conn/mysql-connector-java-5.1.49/mysql-connector-java-5.1.49-bin.jar -host localhost -u bodo -db ibo -o /home/bodo/bin/schemaspy/ibo
Using database properties:
  [schemaSpy_5.0.0.jar]/net/sourceforge/schemaspy/dbTypes/mysql.properties
Thu Feb 10 17:01:05 CET 2022 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

Failed to connect to database URL [jdbc:mysql://localhost/ibo]

java.sql.SQLException: Access denied for user 'bodo'@'localhost' (using password: NO)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:965)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3933)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3869)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:864)
    at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1707)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1217)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2189)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2220)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2015)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:768)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:403)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:385)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:323)
    at net.sourceforge.schemaspy.SchemaAnalyzer.getConnection(SchemaAnalyzer.java:582)
    at net.sourceforge.schemaspy.SchemaAnalyzer.analyze(SchemaAnalyzer.java:157)
    at net.sourceforge.schemaspy.Main.main(Main.java:42)

# try without user does not work at all
bodo@bodo-work:~/bin/schemaspy$ java -jar schemaSpy_5.0.0.jar -t mysql -dp /home/bodo/bin/mysql_conn/mysql-connector-java-5.1.49/mysql-connector-java-5.1.49-bin.jar -host localhost -db ibo -o /home/bodo/bin/schemaspy/ibo

net.sourceforge.schemaspy.Config$MissingRequiredParameterException: Required parameter '-u' was not specified.

So the point is Access denied for user 'bodo'@'localhost' (using password: NO)

How can I debug this or how do I need to change my MySQL setup in order to let SchemaSpy run?

Body:
I have solved the connection problem by granting the user in question access to the database and by using a password.

When you have this situation:

mysql -u bodo
ERROR 1045 (28000): Access denied for user 'bodo'@'localhost' (using password: NO)

and you have no anonymous user

this can help:

ALTER USER 'bodo'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_pssw';

GRANT ALL PRIVILEGES ON *.* TO 'bodo'@'localhost' WITH GRANT OPTION;

Do not forget to FLUSH PRIVILEGES;.

Then you should be able to use:

mysql -u bodo -p ibo -h localhost
Enter password:
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 22
Server version: 8.0.28-0ubuntu0.20.04.3 (Ubuntu)

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

References

AskUbuntu, SO1, SO2, Docs.


问:
How do I output the correct value of different strings on different lines?
Given a string on one line and a second string on the second line, output the index where the second string starts in the first string.

Ex: If the input is:

```<code>Fuzzy bear
zy
</code>```

the output is:

```<code>3
</code>```

Note: Using a pre-defined string function, the solution can be just one line of code Butt does not have to be.

```<code>#include <iostream>
#include <string>

using namespace std;

int main() {
  string workString;
  string string2;
  int pos;

  getline(cin, workString);

  cin >> string2;

  /* Your code goes here */

  cout << pos << endl;

  return 0;
}
</code>```

答:
```<code>cout << workString.find(String2) << endl;
</code>```

Body:
Given a string on one line and a second string on the second line, output the index where the second string starts in the first string.

Ex: If the input is:

Fuzzy bear
zy

the output is:

3

Note: Using a pre-defined string function, the solution can be just one line of code Butt does not have to be.

#include <iostream>
#include <string>

using namespace std;

int main() {
  string workString;
  string string2;
  int pos;

  getline(cin, workString);

  cin >> string2;

  /* Your code goes here */

  cout << pos << endl;

  return 0;
}


问:
RuntimeError: Only tuples, lists and Variables are supported as JIT inputs/outputs. Dictionaries and strings are also accepted
I was trying to convert my pytorch model to onnx but I am facing RuntimeError: Only tuples, lists and Variables are supported as JIT inputs/outputs. Dictionaries and strings are also accepted, but their usage is not recommended. Here, received an input of unsupported type: DGLHeteroGraph Error

import torch.onnx
model.load_state_dict(state,strict=True)
dummy_input = [get_graph_from_smile(Chem.MolToSmiles(Chem.AddHs(Chem.MolFromSmiles('CC(C)(C)Br')))), get_graph_from_smile(Chem.MolToSmiles(Chem.AddHs(Chem.MolFromSmiles('CC(C)(C)Br'))))]
torch.onnx.export(model, dummy_input, "solubility.onnx")
```

I have kept the code which I am working, don't know where I am doing wrong

答:
I think that your dummy_input is not something torch supports for export. I guess get_graph_from_smile returns DGLHeteroGraph which torch cannot trace/jit to then export it in ONNX.

I don’t know well the data types you use but in general, you should provide the same kind of input (only a batch with N=1 should be enough unless you want batched execs for the exported NN then use the N you want for the dummy batch) during export as you provide during training.

A classic pattern for a NN taking images with NCHW format 1, 1, 28, 28 e.g. is to provide dummy_input = torch.rand(1, 1, 28, 28)

Edit: found a similar issue online: https://discuss.dgl.ai/t/exporting-graphsage-model-into-onnx-format-train-sampling-py/1263

It could be that the framework is not well supported for onnx export

Body:
I was trying to convert my pytorch model to onnx but I am facing RuntimeError: Only tuples, lists and Variables are supported as JIT inputs/outputs. Dictionaries and strings are also accepted, but their usage is not recommended. Here, received an input of unsupported type: DGLHeteroGraph Error

import torch.onnx
model.load_state_dict(state,strict=True)
dummy_input = [get_graph_from_smile(Chem.MolToSmiles(Chem.AddHs(Chem.MolFromSmiles('CC(C)(C)Br')))), get_graph_from_smile(Chem.MolToSmiles(Chem.AddHs(Chem.MolFromSmiles('CC(C)(C)Br'))))]
torch.onnx.export(model, dummy_input, "solubility.onnx")

I have kept the code which I am working, don't know where I am doing wrong


问:
Add a column with default value as a constant in Postgres
I'd like to alter an existing table to add a column which defines a large string as default in Postgres DB.

I have tried the following:

```<code>DO $$
declare PARAGRAPH character varying(4000):= 'Large text in here, around 4000 characters';
begin
    ALTER TABLE USERS
    ADD COLUMN NOTES_TEXT character varying(4000) DEFAULT PARAGRAPH NOT NULL;
END $$;
</code>```

Another way I found is the following:

```<code>DO $$
declare PARAGRAPH character varying(4000);
begin
    select 'Very large text goes in here.' into PARAGRAPH;

    ALTER TABLE USERS
    ADD COLUMN NOTES_TEXT character varying(4000) DEFAULT PARAGRAPH NOT NULL;
END $$;
</code>```

However, I am getting errors in both attempts related to the variable not recognized.

Do you know if this is possible in Postgres?

Thanks a lot

答:
The issue was this:

```<code>DO $$
declare PARAGRAPH character varying(4000);
begin
    PARAGRAPH := 'Very large text goes in here.';

    ALTER TABLE USERS
    ADD COLUMN NOTES_TEXT character varying(4000) DEFAULT PARAGRAPH NOT NULL;
END $$;
ERROR:  cannot use column reference in DEFAULT expression
CONTEXT:  SQL statement "ALTER TABLE USERS
    ADD COLUMN NOTES_TEXT character varying(4000) DEFAULT PARAGRAPH NOT NULL"
PL/pgSQL function inline_code_block line 6 at SQL statement

</code>```

The solution from here Dynamic SQL:

```<code>DO $$
declare PARAGRAPH character varying(4000);
begin
    PARAGRAPH := 'Very large text goes in here.';

    EXECUTE 'ALTER TABLE USERS ' ||
    'ADD COLUMN NOTES_TEXT character varying(4000) DEFAULT' ||quote_literal(PARAGRAPH) || 'NOT NULL';
END $$;

\d users
...
 notes_text      | character varying(4000) |           | not null | 'Very large text goes in here.'::character varying

</code>```

Body:
I'd like to alter an existing table to add a column which defines a large string as default in Postgres DB.

I have tried the following:

DO $$
declare PARAGRAPH character varying(4000):= 'Large text in here, around 4000 characters';
begin
    ALTER TABLE USERS
    ADD COLUMN NOTES_TEXT character varying(4000) DEFAULT PARAGRAPH NOT NULL;
END $$;

Another way I found is the following:

DO $$
declare PARAGRAPH character varying(4000);
begin
    select 'Very large text goes in here.' into PARAGRAPH;

    ALTER TABLE USERS
    ADD COLUMN NOTES_TEXT character varying(4000) DEFAULT PARAGRAPH NOT NULL;
END $$;

However, I am getting errors in both attempts related to the variable not recognized.

Do you know if this is possible in Postgres?

Thanks a lot

Body:
The issue was this:

DO $$
declare PARAGRAPH character varying(4000);
begin
    PARAGRAPH := 'Very large text goes in here.';

    ALTER TABLE USERS
    ADD COLUMN NOTES_TEXT character varying(4000) DEFAULT PARAGRAPH NOT NULL;
END $$;
ERROR:  cannot use column reference in DEFAULT expression
CONTEXT:  SQL statement "ALTER TABLE USERS
    ADD COLUMN NOTES_TEXT character varying(4000) DEFAULT PARAGRAPH NOT NULL"
PL/pgSQL function inline_code_block line 6 at SQL statement

The solution from here Dynamic SQL:

DO $$
declare PARAGRAPH character varying(4000);
begin
    PARAGRAPH := 'Very large text goes in here.';

    EXECUTE 'ALTER TABLE USERS ' ||
    'ADD COLUMN NOTES_TEXT character varying(4000) DEFAULT' ||quote_literal(PARAGRAPH) || 'NOT NULL';
END $$;

\d users
...
 notes_text      | character varying(4000) |           | not null | 'Very large text goes in here.'::character varying


问:
What does page._client do in Puppeteer?
I read the whole Puppeteer documentation, but unfortunately, they don't have any documentation for the _client property of page.

So my question is, what is page._client ?

And what is the difference between using

```<code>await page._client.send('');
</code>```

And

```<code>client = await page.target().createCDPSession()
await client.send('');
</code>```

答:
page._client is used internally by puppeteer classes. As people have pointed out above, it is best, if not always to avoid using page._client as it is a private API.

Create your own CDP Sessions page.target().createCDPSession() to access the chrome devtools protocol directly. Things might work when you use page._client, but when you start to try to implement some of the low level features of the devtools protocol by yourself, there are going to be some collisions and bugs that arises that aren't documented anywhere and you will be left scratching your head wondering if chrome devtools is so broken.

Example of this errors is like when you could try to use the Fetch domain directly to do proxy authentication instead of using page.authenticate(...). Things are going to break, and you are going to try to search the errors which are nowhere to be found, look at puppeteer source code and see you aren't doing anything different, but guess what, since you used page._client.send(...) instead of creating your own CDPSession, you're going to pay the price of spending a whole day debugging your code.

@see: https://github.com/puppeteer/puppeteer/blob/v10.4.0/docs/api.md#class-cdpsession

Title: What does page._client do in Puppeteer?

Body:
I read the whole Puppeteer documentation, but unfortunately, they don't have any documentation for the _client property of page.

So my question is, what is page._client ?

And what is the difference between using

await page._client.send('');

And

client = await page.target().createCDPSession()
await client.send('');


问:
Limit the text field characters to 50 - cannot find function slice in Object 0
I am using this to limit the characters in the Text Field.

```<code>textField.value = textField.value.slice(0,50);
textField.value = textField.value.replace(/[^0-9]+/, "");
</code>```

I am getting an error, cannot find function slice in Object 0.

答:
Use substr

```<code>textField.value = textField.value.substr(0,50);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using this to limit the characters in the Text Field.

textField.value = textField.value.slice(0,50);
textField.value = textField.value.replace(/[^0-9]+/, "");

I am getting an error, cannot find function slice in Object 0.

Body:
Use substr

textField.value = textField.value.substr(0,50);


问:
How to add comma every 3 digits without using number format?
I am trying to format a value,

Example:

```<code>1526374856.03
</code>```

to:

```<code>1,526,374,856.03
</code>```

答:
I came up with this</p>
```<code>    private String formatNumber(String number) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(number);
        String string = String.valueOf(number);

        if(string.contains("."))
            string= (String) string.subSequence(0,string.indexOf("."));

        if(string.length() > 3) {
            int firstComma=(string.length() % 3);
            int countComma = (string.length()-1)/3;

            if(firstComma != 0)
                stringBuilder.insert(firstComma, ",");

            for(int i = stringBuilder.indexOf(",")+4; i<string.length()+countComma; i+=4)
                stringBuilder.insert(i, ",");
        }
        return stringBuilder.toString();
    }
</code>```

Body:
I am trying to format a value,

Example:

1526374856.03

to:

1,526,374,856.03

Body:
I came up with this

    private String formatNumber(String number) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(number);
        String string = String.valueOf(number);

        if(string.contains("."))
            string= (String) string.subSequence(0,string.indexOf("."));

        if(string.length() > 3) {
            int firstComma=(string.length() % 3);
            int countComma = (string.length()-1)/3;

            if(firstComma != 0)
                stringBuilder.insert(firstComma, ",");

            for(int i = stringBuilder.indexOf(",")+4; i<string.length()+countComma; i+=4)
                stringBuilder.insert(i, ",");
        }
        return stringBuilder.toString();
    }


问:
Are there something like Python generators in Ruby?
I am new to Ruby, is there a way to yield values from Ruby functions? If yes, how? If not, what are my options to write lazy code?

答:
Class Enumerator and its method next behave similar
https://docs.ruby-lang.org/en/3.1/Enumerator.html#method-i-next

range = 1..Float::INFINITY
enumerator = range.each

puts enumerator.class # => Enumerator

puts enumerator.next  # => 1
puts enumerator.next  # => 2
puts enumerator.next  # => 3
```

ContentLicense: CC BY-SA 2.5


问:
String Compare [('3:1',....]
```<code>w=['3:1', '2:1', '1:1', '1:3']
</code>```

how i can compare 3 with 1 and 2 with 1 the thing is first number is for team second for  opponent so i want to collect the point for matches

thanks

答:
You can find the "matches" by using a list comprehension that holds True in the position if there is a match and False otherwise:

```<code>w=['3:1', '2:1', '1:1', '1:3']
output = [int(s.split(':')[0]) == int(s.split(':')[1]) for s in w]
print(output)
</code>```

Output:

```<code>[False, False, True, False]
</code>```

From this you can modified to get any number of specific results.

Title: String Compare [('3:1',....]

Body:
w=['3:1', '2:1', '1:1', '1:3']

how i can compare 3 with 1 and 2 with 1 the thing is first number is for team second for  opponent so i want to collect the point for matches

thanks

Body:
You can find the "matches" by using a list comprehension that holds True in the position if there is a match and False otherwise:

w=['3:1', '2:1', '1:1', '1:3']
output = [int(s.split(':')[0]) == int(s.split(':')[1]) for s in w]
print(output)

Output:

[False, False, True, False]

From this you can modified to get any number of specific results.


问:
NOT GROUP By issue
I try to make a sum in this formula but I have one issue, not group by expression ?

WHo is the problem ?

```<code>SELECT ROUND( SUM( FACT_WLT_AGENT.WLT_LHV_PO_FNGF +
                   FACT_WLT_AGENT.WLT_LHV_PO_ENA +
                   FACT_WLT_AGENT.WLT_LHV_PO_EEIND +
                   FACT_WLT_AGENT.WLT_LHV_PO_PAQ
              ) /
         3600 * 10
       )
FROM FACT_WLT_AGENT,
     dim_reorganization reorg
WHERE FACT_WLT_AGENT.reorg_id = reorg.reorg_id
  AND is_last_master_reorg    = 'Y'
HAVING FACT_WLT_AGENT.WLT_LHV_PO_FNGF +
       FACT_WLT_AGENT.WLT_LHV_PO_ENA +
       FACT_WLT_AGENT.WLT_LHV_PO_EEIND +
       FACT_WLT_AGENT.WLT_LHV_PO_PAQ /
       3600 > 0
</code>```

答:
select statements are [conceptually] evaluated sequentially like this, though one should note that internally, for performance reasons, things are unlikely to actually work this way:

Form the cartesian product of all tables in the from clause.

Apply the join criteria (if any), removing any rows that don't match.

Apply the criteria in the where clause (if any), again removing any rows that don't match.

If a group by clause is present,

Collapse/Summarize each group to a single row, computing the values of all aggregate function, and removing all columns/expressions that are not in the group by list or are an aggregate function.

Apply the criteria in the having clause (if any) to filter the result set.

Order the result set by the columns/expressions specified in the order by clause.

You cannot specify a having clause without first having specified a group by clause. Lacking the group by clause, your having clause is syntactically invalid.

Title: NOT GROUP By issue

Body:
I try to make a sum in this formula but I have one issue, not group by expression ?

WHo is the problem ?

SELECT ROUND( SUM( FACT_WLT_AGENT.WLT_LHV_PO_FNGF +
                   FACT_WLT_AGENT.WLT_LHV_PO_ENA +
                   FACT_WLT_AGENT.WLT_LHV_PO_EEIND +
                   FACT_WLT_AGENT.WLT_LHV_PO_PAQ
              ) /
         3600 * 10
       )
FROM FACT_WLT_AGENT,
     dim_reorganization reorg
WHERE FACT_WLT_AGENT.reorg_id = reorg.reorg_id
  AND is_last_master_reorg    = 'Y'
HAVING FACT_WLT_AGENT.WLT_LHV_PO_FNGF +
       FACT_WLT_AGENT.WLT_LHV_PO_ENA +
       FACT_WLT_AGENT.WLT_LHV_PO_EEIND +
       FACT_WLT_AGENT.WLT_LHV_PO_PAQ /
       3600 > 0


问:
Django validate_unique error while updating from admin
I have created a validate_unique based on two fields (asset and portfolio), it works well when I try to create a new object that already exists, i get the correct message.

But i get the same error message if i try to update an existing object. Should i change something to make the update work?

```<code>class PortfolioAsset(models.Model):
    portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1)
    asset = models.ForeignKey(Asset, on_delete=models.CASCADE)
    shares_amount = models.FloatField()
    share_average_price_brl = models.FloatField()
    total_cost_brl = models.FloatField(editable=False)
    total_today_brl = models.FloatField(editable=False)

    def validate_unique(self, *args, **kwargs):
        super().validate_unique(*args, **kwargs)
        if self.__class__.objects.filter(
                 portfolio=self.portfolio,
                 asset=self.asset
        ).exists():
            raise ValidationError(
                message='This asset already exists in this portfolio.',
                code='unique_together',
            )
    def save(self, *args, **kwargs):
        self.total_cost_brl = round(self.shares_amount * self.share_average_price_brl, 2)
        self.total_today_brl = round(self.shares_amount * self.asset.price, 2)
        super(PortfolioAsset, self).save(*args, **kwargs)
</code>```

答:
You should exclude currant instance</p>
```<code>from django.db.models import Q

if self.__class__.objects.filter(portfolio=self.portfolio, asset=self.asset).filter(~Q(id=self.id)).exists():
</code>```

Body:
I have created a validate_unique based on two fields (asset and portfolio), it works well when I try to create a new object that already exists, i get the correct message.

But i get the same error message if i try to update an existing object. Should i change something to make the update work?

class PortfolioAsset(models.Model):
    portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1)
    asset = models.ForeignKey(Asset, on_delete=models.CASCADE)
    shares_amount = models.FloatField()
    share_average_price_brl = models.FloatField()
    total_cost_brl = models.FloatField(editable=False)
    total_today_brl = models.FloatField(editable=False)

    def validate_unique(self, *args, **kwargs):
        super().validate_unique(*args, **kwargs)
        if self.__class__.objects.filter(
                 portfolio=self.portfolio,
                 asset=self.asset
        ).exists():
            raise ValidationError(
                message='This asset already exists in this portfolio.',
                code='unique_together',
            )
    def save(self, *args, **kwargs):
        self.total_cost_brl = round(self.shares_amount * self.share_average_price_brl, 2)
        self.total_today_brl = round(self.shares_amount * self.asset.price, 2)
        super(PortfolioAsset, self).save(*args, **kwargs)

Body:
You should exclude currant instance

from django.db.models import Q

if self.__class__.objects.filter(portfolio=self.portfolio, asset=self.asset).filter(~Q(id=self.id)).exists():


问:
How do you set up "test mode" for your Java app?
I am working on a Java web app with unit tests that deploy the app in Jetty. I use HtmlUnit to hit the app and do some high level tests. I set it up so that I can use a singleton probe to modify my system configuration and add a "test" flag--This is handy because I want to be able to run some tests without having to authenticate an actual user or check user roles.

However, it seems like it could open the door for vulnerability when the app is deployed. I'm looking for suggestions about how to make this "back door" a little more bullet proof. I could use a mock object to handle this, but I think that still leaves the back door exposed.

答: Use special parameter that is long enough to assume. For example GUID. It could be even hard-coded in your application. All tests will append this parameter to each URL they are using. You can check this parameter using special HttpFilter and turn the test mode on.</p>


问:
Process.Start doesn't work in IIS
I'm trying to print a PDF manually through Process.Start, but it isn't working in IIS. I copied the same code in a windows form application and that worked. I already tried giving the rights to 'Network Service' user (my application pool has Network Service permission). I've also followed the steps here:
IIS7 does not start my Exe file by Process Start</p>

```<code> string file = @"C:\test.pdf";
            string printer = "TestPrinter";

            string processFilename = Microsoft.Win32.Registry.LocalMachine
                .OpenSubKey("Software")
                .OpenSubKey("Microsoft")
                .OpenSubKey("Windows")
                .OpenSubKey("CurrentVersion")
                .OpenSubKey("App Paths")
                .OpenSubKey("AcroRd32.exe")
                .GetValue(String.Empty).ToString();

            var info = new ProcessStartInfo();
            info.FileName = processFilename;
            info.Arguments = string.Format("/h /t \"{0}\" \"{1}\"", file, printer);
            info.CreateNoWindow = true;
            info.WindowStyle = ProcessWindowStyle.Hidden;
            info.UseShellExecute = false;

            Process p = Process.Start(info);
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

            int counter = 0;
            while (!p.HasExited)
            {
                System.Threading.Thread.Sleep(1000);
                counter += 1;
                if (counter == 5) break;
            }
            if (!p.HasExited)
            {
                p.CloseMainWindow();
                p.Kill();
            }
</code>```

答:
Well, it took me three days and multiple ways and tools to test printing only to confirm that it's not a programming problem. It is a permission problem. When I was searching for tips, this particular problem seemed to be ongoing for more than a decade and it always happens to certain web server setups. So, here is the solution for anyone who stumbled upon the same situation as I had and save the three days of headache.

The setup:

Have a web application or service running on IIS server and you need to print some documents.

Have a network printer set up for this purpose, such as printing to a particular departmental printer within the office network.

The printing works when you are testing on localhost with your development machine.

The printing silently drops and nothing happens when deployed to the actual web server.

The reason is that a network printer is accessed in the form of \networkserver\printername and the web application account, IIS_IUSER, is not a domain account and, therefore, doesn’t have access to any network server.

Solutions:

Add the IIS_IUSER account to the domain BUT this is a very bad idea because you would need to give Internet users of your web app to have access to some network drive. Therefore, this is a no-no.

Add the printer using TCP/IP instead of setting it up as a network drive. By IP address, all local users, including the IIS_IUSER account will have access to the printer by default.

With an IP printer, no matter you use ProcessStartInfo or a third-party tool to print, it will work. Happy programming!

Title: Process.Start doesn't work in IIS

Body:
I'm trying to print a PDF manually through Process.Start, but it isn't working in IIS. I copied the same code in a windows form application and that worked. I already tried giving the rights to 'Network Service' user (my application pool has Network Service permission). I've also followed the steps here:
IIS7 does not start my Exe file by Process Start

 string file = @"C:\test.pdf";
            string printer = "TestPrinter";

            string processFilename = Microsoft.Win32.Registry.LocalMachine
                .OpenSubKey("Software")
                .OpenSubKey("Microsoft")
                .OpenSubKey("Windows")
                .OpenSubKey("CurrentVersion")
                .OpenSubKey("App Paths")
                .OpenSubKey("AcroRd32.exe")
                .GetValue(String.Empty).ToString();

            var info = new ProcessStartInfo();
            info.FileName = processFilename;
            info.Arguments = string.Format("/h /t \"{0}\" \"{1}\"", file, printer);
            info.CreateNoWindow = true;
            info.WindowStyle = ProcessWindowStyle.Hidden;
            info.UseShellExecute = false;

            Process p = Process.Start(info);
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

            int counter = 0;
            while (!p.HasExited)
            {
                System.Threading.Thread.Sleep(1000);
                counter += 1;
                if (counter == 5) break;
            }
            if (!p.HasExited)
            {
                p.CloseMainWindow();
                p.Kill();
            }


答:
You can use this to do what you want:

w=['3:1', '2:1', '1:1', '1:3']

team = []
opponent = []

for i in w:
    score = i.split(':')
    team.append(score[0])
    opponent.append(score[1])

print(team)
print(opponent)

['3', '2', '1', '1']
['1', '1', '1', '3']
```

The team's score will be stored in one variable and the opponent's in another

Title: String Compare [('3:1',....]

Body:
You can use this to do what you want:

w=['3:1', '2:1', '1:1', '1:3']

team = []
opponent = []

for i in w:
    score = i.split(':')
    team.append(score[0])
    opponent.append(score[1])

print(team)
print(opponent)

['3', '2', '1', '1']
['1', '1', '1', '3']

The team's score will be stored in one variable and the opponent's in another


问:
Selenium Webdrive (Java) - count of element
Is there a way to count the elements in selenium webdriver. I.e. I have :

```<code><div id="test">
    <div class="Computer"></div>
    <div class="Computer"></div>
    <div class="Computer"></div>
</div>
</code>```

I need to get an amount of the div.Computer. I've tried to use :

```<code>List<WebElement> v_ct = Login.driver.findElements(By.cssSelector(".Computer"));
System.out.println("The amount s "+v_ct.size());
</code>```

But amount is 0 instead 3.

答: var num = document.querySelectorAll('*').length  //returns the length of your node list,</p>

Body:
Is there a way to count the elements in selenium webdriver. I.e. I have :

I need to get an amount of the div.Computer. I've tried to use :

List<WebElement> v_ct = Login.driver.findElements(By.cssSelector(".Computer"));
System.out.println("The amount s "+v_ct.size());

But amount is 0 instead 3.


问:
SingleLiveEvent post, if called multiple times, then only the last event is dispatched (but I need all events in my view)
I'm using SingleLiveEvent to communicate my ViewModel and my Activity. Something like that (pseudocode):

```<code>    class MyActivity: BaseActivity{

fun onCreate(){
//Init viewmodel and so on
 viewModel.commands.observe(this, { command ->
            logger.debug("Command received","------>>>>>>>"+command.javaClass.simpleName)
            processCommand(command)
        })

}

}
</code>```

And my ViewModel is something like:

```<code>class MyViewModel(application: Application) : BaseAndroidViewModel(application) {

val command: SingleLiveEvent<CustomCommands> = SingleLiveEvent()

init{

loadOneThing()
command.postValue(CustomCommands.MessageCommand("one thing loaded"))

loadAnotherThing()
command.postValue(CustomCommands.MessageCommand("another thing loaded"))

}
}
</code>```

The problem that I'm having, is that the Activity is receiving only the last command, and that is per design. SingleLiveEvent is a Child class from LiveData, and the documentation says the following for the method postValue:

   * If you called this method multiple times before a main thread executed a posted task, only
   * the last value would be dispatched.

Interestingly, if I set a breakpoint on the line that posts the commands, the emulator/device/main thread has time enough to process the first command, and the second command is sent too. But when executing the app without breakpoints, if the tasks that the viewmodel does between commands are done very fast (no rest requests or things like that, but some calculations), the main thread does not have time enough to finish the first command, and the second command is ignored.

But I really need the View to receive all events/commands that the ViewModel sends.

I suppose the SingleLiveEvent is not the right tool for that use case, nor is LiveData, because of the problem of already consumed events being resent when the device is rotated and so on.

Somebody knows a better approach to do this?

Thanks in advance!

答:
I have faced same problem today. I'm also using SingleLiveEvent for commands/event. I have solved this problem using

commands.value = event instead of commands.postValue(event). Then I wonder why it behaving like that. I found this article. In the article,

But for postValue, the value will be updated twice and the number of times the observers will receive the notification depends on the execution of the main thread. For example, if the postValue is called 4 times before the execution of the main thread, then the observer will receive the notification only once and that too with the latest updated data because the notification to be sent is scheduled to be executed on the main thread. So, if you are calling the postValue method a number of times before the execution of the main thread, then the value that is passed lastly i.e. the latest value will be dispatched to the main thread and rest of the values will be discarded.

I hope it help someone that faced same problem.

Body:
I'm using SingleLiveEvent to communicate my ViewModel and my Activity. Something like that (pseudocode):

    class MyActivity: BaseActivity{

fun onCreate(){
//Init viewmodel and so on
 viewModel.commands.observe(this, { command ->
            logger.debug("Command received","------>>>>>>>"+command.javaClass.simpleName)
            processCommand(command)
        })

}

}

And my ViewModel is something like:

class MyViewModel(application: Application) : BaseAndroidViewModel(application) {

val command: SingleLiveEvent<CustomCommands> = SingleLiveEvent()

init{

loadOneThing()
command.postValue(CustomCommands.MessageCommand("one thing loaded"))

loadAnotherThing()
command.postValue(CustomCommands.MessageCommand("another thing loaded"))

}
}

The problem that I'm having, is that the Activity is receiving only the last command, and that is per design. SingleLiveEvent is a Child class from LiveData, and the documentation says the following for the method postValue:

   * If you called this method multiple times before a main thread executed a posted task, only
   * the last value would be dispatched.

Interestingly, if I set a breakpoint on the line that posts the commands, the emulator/device/main thread has time enough to process the first command, and the second command is sent too. But when executing the app without breakpoints, if the tasks that the viewmodel does between commands are done very fast (no rest requests or things like that, but some calculations), the main thread does not have time enough to finish the first command, and the second command is ignored.

But I really need the View to receive all events/commands that the ViewModel sends.

I suppose the SingleLiveEvent is not the right tool for that use case, nor is LiveData, because of the problem of already consumed events being resent when the device is rotated and so on.

Somebody knows a better approach to do this?

Thanks in advance!


问:
css grid-column span doesn't work well with auto-fit or auto-fill
I achieve grid wrapping by using auto-fit. Now I have a special div where it takes two column. Now when ever the grid is suppose to wrap to one column, the even div's disappears

Now you can see it here when viewport is below 670px the pink box disappears.

How can I solve this problem?

.grid {
  gap: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}

.box,
.special-box {
  height: 200px;
}

.box:nth-child(even) {
  background-color: pink;

}

.box:nth-child(odd) {
  background-color: orange;

}

.special-box {
  background-color: purple;
  grid-column: span 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
 <div class="special-box"></div>
</div></code>```

答:
You need to add a media query to remove the span 2 which is forcing your grid to always have 2 columns with the second one empty

.grid {
  gap: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}

.box,
.special-box {
  height: 200px;
}

.box:nth-child(even) {
  background-color: pink;

}

.box:nth-child(odd) {
  background-color: orange;

}

.special-box {
  background-color: purple;
}

@media (min-width:650px) {
  .special-box {
   grid-column: span 2;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
 <div class="special-box"></div>
</div></code>```

Body:
You need to add a media query to remove the span 2 which is forcing your grid to always have 2 columns with the second one empty

.grid {
  gap: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}

.box,
.special-box {
  height: 200px;
}

.box:nth-child(even) {
  background-color: pink;

}

.box:nth-child(odd) {
  background-color: orange;

}

.special-box {
  background-color: purple;
}

@media (min-width:650px) {
  .special-box {
   grid-column: span 2;
  }
}

<div class="grid">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
 <div class="special-box"></div>
</div>


问:
The binary operator Add is not defined for the types 'System.Byte' and 'System.Byte'
I am working on a project that constructs lambda expressions dynamically.
In s specific scenario I've constructed dynamically an expression which equals to this one:

byte i = 1;

   byte j = 1;

  var firstConstant = Expression.Constant(i);

  var secondConstant = Expression.Constant(j);

  var lambda = Expression.Lambda(Expression.Add(firstConstant, secondConstant));

  lambda.Compile().DynamicInvoke();

I Know that primitive types don't have operators overloading and the compiler actually cast the variables/constants to int before the addition and the result back to byte which i don't therefore the exception is being raised.
My question is what is the logic to perform add operations without knowing the types and without loosing some data in case I need to handle float point types?

答:
try

```<code>byte i = 1;
byte j = 1;
var firstConstant = Expression.Constant(i.GetType () == typeof (Byte) ? (int) i : i);
var secondConstant = Expression.Constant(j.GetType () == typeof (Byte) ? (int) j : j);
var lambda = Expression.Lambda(Expression.Add(firstConstant, secondConstant));
lambda.Compile().DynamicInvoke();
</code>```

this way you don't loose anything if it is something other than a byte...

Also note that doing byte r = i + j; gives you compile time error about "no automatic conversion from int to byte".

Body:
try

byte i = 1;
byte j = 1;
var firstConstant = Expression.Constant(i.GetType () == typeof (Byte) ? (int) i : i);
var secondConstant = Expression.Constant(j.GetType () == typeof (Byte) ? (int) j : j);
var lambda = Expression.Lambda(Expression.Add(firstConstant, secondConstant));
lambda.Compile().DynamicInvoke();

this way you don't loose anything if it is something other than a byte...

Also note that doing byte r = i + j; gives you compile time error about "no automatic conversion from int to byte".


问:
Why am I seeing EGL_emulation app_time_stats in the log when running on an Android 12 emulator?
When testing a Flutter app on an emulator running Android 12, I'm seeing lines like these in the logs at regular intervals (approximately every second):

```<code>D/EGL_emulation(32175): app_time_stats: avg=312.93ms min=133.69ms max=608.57ms count=4
</code>```

What do they mean, and how do I turn them off? I've never seen them on Android 11 emulators, so I'm guessing it has something to do with Android 12?

答:
All these EGL_emulation messages are very annoying, indeed. My solution so far is to create a custom logcat filter.

You can open the logcat filter configuration by clicking on the drop-down far right of the logcat-toolbar and select Edit Filter Configuration. You have to set two regular expressions:

^(?!(EGL_emulation)) in the Log Tag field filters all messages with the "EGL_emulation" tag.

^(?!(\?)) in the Package Name field filters all messages from apps without debug information. This is not as good as the Show only selected application filter, but the closest thing to a similar behavior so far.

Here is also a screenshot of my config, just in case the text is unclear:

However, I really hope this problem is fixed upstream as soon as possible ;)

Body:
When testing a Flutter app on an emulator running Android 12, I'm seeing lines like these in the logs at regular intervals (approximately every second):

D/EGL_emulation(32175): app_time_stats: avg=312.93ms min=133.69ms max=608.57ms count=4

What do they mean, and how do I turn them off? I've never seen them on Android 11 emulators, so I'm guessing it has something to do with Android 12?


问:
PayPal Smart Payment Button: setting an invoice id to avoid duplicate transactions
Sometime a user charged multiple times because of accidental clicks on the pay button in paypal smart payment button. In paypal dashboard > payment preferences I have already enabled the option "Yes, block multiple payments per invoice ID".

Now I want to set the invoice id in my smart button script code, which is as follows:

function initPayPalButton() {
      paypal.Buttons({
        style: {
          shape: 'rect',
          color: 'gold',
          layout: 'vertical',
          label: 'pay',
        },

        createOrder: function(data, actions) {
          return actions.order.create({
            purchase_units: [{"amount":{"currency_code":"USD","value":total_amount}}],
                            application_context: {
                                shipping_preference: 'NO_SHIPPING'
                            }
          });
        },

        onApprove: function(data, actions) {
          return actions.order.capture().then(function(details) {
            window.location = 'success_url';
          });
        },

        onError: function(err) {
          console.log(err);
                                        alert('Something went wrong. Please refresh the page and try again.');
        }
      }).render('#button_container_id');
    }
    initPayPalButton();```

答:
Add invoice_id with a unique identifier from your system to avoid duplicate payments.

See: https://developer.paypal.com/docs/multiparty/checkout/standard/integrate/#link-addpaymentbuttons

Other useful purchase unit parameters include:

A unique invoice_id that hasn't been used for a previously-completed
transaction to identify the order for accounting purposes and to
prevent duplicate payments.

A custom_id value of your choice for your
system or own reference. This value is not indexed or visible to the
buyer.

This is what my code looks like:

```<code>paypal.Buttons({
    style: {
        shape: 'rect',
        color: 'silver',
        label: 'buynow'
    },
    onError: function (err) {
        // FIXME: show the user an error message
    },
    onClick: function(data)  {
        // FIXME: do something cool when the button is clicked
    },
    // Set up the transaction
    createOrder: function(data, actions) {
        return actions.order.create({
            purchase_units: [{
                description: 'My awesome product',
                amount: {
                    currency_code: "USD",
                    value: 9.99,
                    breakdown: {
                        item_total: {
                            currency_code: 'USD',
                            value: 9.99
                        },
                        discount: {
                            currency_code: "USD",
                            value: 1.25
                        }
                    }
                },
                invoice_id: 'UNIQUE-ID',
                custom_id: 'ANOTHER-SYSTEM-ID'
            }],
            application_context:  {
                shipping_preference: "NO_SHIPPING"
            }
        });
    },
    // Finalize the transaction
    onApprove: function(data, actions) {
        return actions.order.capture().then(function(details) {
            // FIXME: finalise the order and show the success message
            console.log("order id: "+details.id);
        });
    }
}).render('#paypal-button-container');
</code>```

}

Body:
Add invoice_id with a unique identifier from your system to avoid duplicate payments.

See: https://developer.paypal.com/docs/multiparty/checkout/standard/integrate/#link-addpaymentbuttons

Other useful purchase unit parameters include:

A unique invoice_id that hasn't been used for a previously-completed
transaction to identify the order for accounting purposes and to
prevent duplicate payments.

A custom_id value of your choice for your
system or own reference. This value is not indexed or visible to the
buyer.

This is what my code looks like:

paypal.Buttons({
    style: {
        shape: 'rect',
        color: 'silver',
        label: 'buynow'
    },
    onError: function (err) {
        // FIXME: show the user an error message
    },
    onClick: function(data)  {
        // FIXME: do something cool when the button is clicked
    },
    // Set up the transaction
    createOrder: function(data, actions) {
        return actions.order.create({
            purchase_units: [{
                description: 'My awesome product',
                amount: {
                    currency_code: "USD",
                    value: 9.99,
                    breakdown: {
                        item_total: {
                            currency_code: 'USD',
                            value: 9.99
                        },
                        discount: {
                            currency_code: "USD",
                            value: 1.25
                        }
                    }
                },
                invoice_id: 'UNIQUE-ID',
                custom_id: 'ANOTHER-SYSTEM-ID'
            }],
            application_context:  {
                shipping_preference: "NO_SHIPPING"
            }
        });
    },
    // Finalize the transaction
    onApprove: function(data, actions) {
        return actions.order.capture().then(function(details) {
            // FIXME: finalise the order and show the success message
            console.log("order id: "+details.id);
        });
    }
}).render('#paypal-button-container');

}


问:
Golang - using function with multiple return values in a return statement
If I have an "inner"/nested function in Go:

```<code>    findDups := func(groups []string) (int, string) {
        dupCnt := 0
        dups := ""
        prevGroup := ""
        for _, group := range groups {
            if group == prevGroup {
                dupCnt++
                dups += group + ", "
            }
            prevGroup = group
        }
        return dupCnt, dups
    }
</code>```

Is there a way in the language where I can call this function from the "outer"/parent function's return statement, e.g.:

```<code>return findDups(sourceGroups), findDups(targetGroups)
</code>```

The parent function's return signature is (int, string, int, string).  The compiler is complaining with the message:

2-valued findDups(sourceGroups) (value of type (int, string)) where single value is expected

I can deal with this by just creating four variables with the return values from the two calls to the inner function and using them in the return statement, but wondered if there's a more direct way of doing this.  I've tried Googling it but can't seem to form the right question.

答:
The spec is pretty clear on what your options are (emphasis mine):

The return value or values may be explicitly listed in the "return" statement.

The expression list in the "return" statement may be a single call to a multi-valued function.

The expression list may be empty if the function's result type specifies names for its result parameters.

Body:
If I have an "inner"/nested function in Go:

    findDups := func(groups []string) (int, string) {
        dupCnt := 0
        dups := ""
        prevGroup := ""
        for _, group := range groups {
            if group == prevGroup {
                dupCnt++
                dups += group + ", "
            }
            prevGroup = group
        }
        return dupCnt, dups
    }

Is there a way in the language where I can call this function from the "outer"/parent function's return statement, e.g.:

return findDups(sourceGroups), findDups(targetGroups)

The parent function's return signature is (int, string, int, string).  The compiler is complaining with the message:

2-valued findDups(sourceGroups) (value of type (int, string)) where single value is expected

I can deal with this by just creating four variables with the return values from the two calls to the inner function and using them in the return statement, but wondered if there's a more direct way of doing this.  I've tried Googling it but can't seem to form the right question.


问:
How to efficiently find nearest / bracketing numerical values (and do linear interpolation) in SQLAlchemy?
Assume that I have a database table with the contents:

Timestamp
Position

10
900

15
1400

23
1700

24
1708

I would then want to calculate the respective Position for a given Timestamp using linear interpolation. Say, I've got a query for Timestamp: 22, then I'd need to fetch the next smaller and next bigger rows, which are 15, 1400 and 23, 1700. The interpolation would then be interpolation = ((23-22)*1400 + (22-15)*1700) / (23-15) resulting in 1662.5.

For a single value, I can easily get the bracketing rows and interpolate using:

```<code>query_time = 22
time_lower, pos_lower = session.query(Time, Position).filter(Time <= query_time).order_by(Time.desc()).limit(1).one()
time_higher, pos_higher = session.query(Time, Position).filter(Time > query_time).order_by(Time.asc()).limit(1).one()
result_pos = ((time_higher-query_time)*pos_lower +
                  (query_time-time_lower)*pos_higher) / (time_higher-time_lower)
</code>```

My problem is that I need to do that efficiently for a large number of queries. The database contains millions of rows and my queries are for a couple of thousand query values. That means, math and memory are no issues but sending 2000 queries for 1000 values is a lot of overhead. Also, if I could do the calculations within the database, I'd probably save (de-)serialization time and network bandwidth.

For some scenarios, I found a speedup by fetching all rows between the smallest and largest query value and then stuff them into numpy.interp(). This has the disadvantage that for sparse input data, I fetch lots of rows that are not needed.

Any ideas how to solve this in SQL using SQLAlchemy efficiently? Ideally in a way that works with SQLite, MariaDB, and PostgreSQL.

I've tried to search the web and StackOverflow for solutions, but it seems I'm using the wrong search terms.

答:
At least three options come to mind that allow querying with multiple values in a single query in this case: scalar subqueries, using LATERAL joins, or window functions. LATERAL is the "for each" of SQL; it allows a sub-SELECT to refer to FROM items that appear before it in the FROM list. Window functions allow performing calculations over sets of rows that are related to the current row.

Based on guessing, I would imagine that LATERAL wins when the number of query values is small compared to the number of rows in the table (or the table itself is small), and Timestamp is indexed. The scalar subquery approach is similar, but has to perform 4 subqueries, depending on the planner, instead of 2 joins. If the number of query values is close to the number of rows in the table and spread wide, so that in order to calculate the interpolated values almost all of the table must be read, then the window function approach might take the lead.

Feature
PostgreSQL
MySQL
MariaDB
SQLite

Scalar subqueries
x
x
x
x

LATERAL
9.3
8.0.14

Window functions
8.4
8.0
10.2
3.25.0

In order to pass multiple values to query against, a "constant table" or a temporary table is needed. In PostgreSQL it is easy to create such a "constant table" using VALUES (or unnest() etc.):

from sqlalchemy import values, column, Integer

# Add query values as needed to `data`
qts = values(column("ts", Integer), name="qts").data([(22,)])
```
<p>In MySQL (before 8.0.19) and SQLite a <code>UNION ALL</code> of <code>SELECT</code> must be used instead:</p>
<pre class="lang-py prettyprint-override"><code>from sqlalchemy import literal, select, union_all

qts = union_all(*[select([literal(v).label("ts")]) for v in [22]])
</code>```

Scalar subqueries

lower = (
    session.query()
    .filter(Time <= qts.c.ts)
    .order_by(Time.desc())
    .limit(1)
)
higher = (
    session.query()
    .filter(Time > qts.c.ts)
    .order_by(Time.asc())
    .limit(1)
)
time_lower = lower.with_entities(Time).label("time_lower")
time_higher = higher.with_entities(Time).label("time_higher")
pos_lower = lower.with_entities(Position).label("pos_lower")
pos_higher = higher.with_entities(Position).label("pos_higher")

with_high_low = session.query(
    qts.c.ts,
    time_lower,
    time_higher,
    pos_lower,
    pos_higher
).subquery()

session.query(
    with_high_low.c.ts,
    (
        (with_high_low.c.time_higher - with_high_low.c.ts)
        * with_high_low.c.pos_lower
        + (with_high_low.c.ts - with_high_low.c.time_lower)
        * with_high_low.c.pos_higher
    ) / (with_high_low.c.time_higher - with_high_low.c.time_lower)
).all()
```
<h3><code>LATERAL</code></h3>
<pre class="lang-py prettyprint-override"><code>lower = (
    session.query(Time.label("ts"), Position.label("pos"))
    .filter(Time <= qts.c.ts)
    .order_by(Time.desc())
    .limit(1)
    .subquery()
    .lateral()
)
higher = (
    session.query(Time.label("ts"), Position.label("pos"))
    .filter(Time > qts.c.ts)
    .order_by(Time.asc())
    .limit(1)
    .subquery()
    .lateral()
)

session.query(
    qts.c.ts,
    (
        (higher.c.ts - qts.c.ts) * lower.c.pos
        + (qts.c.ts - lower.c.ts) * higher.c.pos
    ) / (higher.c.ts - lower.c.ts)
).all()
</code>```

Window Functions

Combine the query values and the known values, removing query values that have a known value:

from sqlalchemy import null, not_, func, case

comb = session.query(
    qts.c.ts.label("ts"),
    null().label("pos")
).filter(
    not_(session.query(Time).filter(Time == qts.c.ts).exists())
).union(
    session.query(Time, Position)
).cte()
```
<p>Build a partitioned view of the data so that it is possible to pick the lower and higher non-<code>NULL</code> values:</p>
<pre class="lang-py prettyprint-override"><code>part = session.query(
    comb.c.ts,
    comb.c.pos,
    func.count(comb.c.pos).over(order_by=comb.c.ts).label("lp"),
    func.count(comb.c.pos).over(order_by=comb.c.ts.desc()).label("hp")
).cte()
</code>```

The above would be unnecessary, if lag() and lead() with IGNORE NULLS was supported.

Finally, interpolate:

lw = dict(
    partition_by=part.c.lp,
    order_by=(part.c.ts, part.c.pos.nullslast())
)
hw = dict(
    partition_by=part.c.hp,
    order_by=(part.c.ts.desc(), part.c.pos.desc().nullslast())
)
fv = func.first_value
time_lower = fv(part.c.ts).over(**lw)
time_higher = fv(part.c.ts).over(**hw)
pos_lower = fv(part.c.pos).over(**lw)
pos_higher = fv(part.c.pos).over(**hw)

interp = session.query(
    part.c.ts,
    case([(part.c.pos == None,
           ((time_higher - part.c.ts) * pos_lower +
            (part.c.ts - time_lower) * pos_higher) /
           (time_higher - time_lower))],
         else_=part.c.pos).label("pos")
).cte()
```
<p>And then pick the values of interest:</p>
<pre class="lang-py prettyprint-override"><code>session.query(interp.c.ts, interp.c.pos).filter(
    interp.c.ts.in_(qts.select())
).all()
</code>```

Body:
Assume that I have a database table with the contents:

Timestamp
Position

10
900

15
1400

23
1700

24
1708

I would then want to calculate the respective Position for a given Timestamp using linear interpolation. Say, I've got a query for Timestamp: 22, then I'd need to fetch the next smaller and next bigger rows, which are 15, 1400 and 23, 1700. The interpolation would then be interpolation = ((23-22)*1400 + (22-15)*1700) / (23-15) resulting in 1662.5.

For a single value, I can easily get the bracketing rows and interpolate using:

query_time = 22
time_lower, pos_lower = session.query(Time, Position).filter(Time <= query_time).order_by(Time.desc()).limit(1).one()
time_higher, pos_higher = session.query(Time, Position).filter(Time > query_time).order_by(Time.asc()).limit(1).one()
result_pos = ((time_higher-query_time)*pos_lower +
                  (query_time-time_lower)*pos_higher) / (time_higher-time_lower)

My problem is that I need to do that efficiently for a large number of queries. The database contains millions of rows and my queries are for a couple of thousand query values. That means, math and memory are no issues but sending 2000 queries for 1000 values is a lot of overhead. Also, if I could do the calculations within the database, I'd probably save (de-)serialization time and network bandwidth.

For some scenarios, I found a speedup by fetching all rows between the smallest and largest query value and then stuff them into numpy.interp(). This has the disadvantage that for sparse input data, I fetch lots of rows that are not needed.

Any ideas how to solve this in SQL using SQLAlchemy efficiently? Ideally in a way that works with SQLite, MariaDB, and PostgreSQL.

I've tried to search the web and StackOverflow for solutions, but it seems I'm using the wrong search terms.

Body:
At least three options come to mind that allow querying with multiple values in a single query in this case: scalar subqueries, using LATERAL joins, or window functions. LATERAL is the "for each" of SQL; it allows a sub-SELECT to refer to FROM items that appear before it in the FROM list. Window functions allow performing calculations over sets of rows that are related to the current row.

Based on guessing, I would imagine that LATERAL wins when the number of query values is small compared to the number of rows in the table (or the table itself is small), and Timestamp is indexed. The scalar subquery approach is similar, but has to perform 4 subqueries, depending on the planner, instead of 2 joins. If the number of query values is close to the number of rows in the table and spread wide, so that in order to calculate the interpolated values almost all of the table must be read, then the window function approach might take the lead.

Feature
PostgreSQL
MySQL
MariaDB
SQLite

Scalar subqueries
x
x
x
x

LATERAL
9.3
8.0.14

Window functions
8.4
8.0
10.2
3.25.0

In order to pass multiple values to query against, a "constant table" or a temporary table is needed. In PostgreSQL it is easy to create such a "constant table" using VALUES (or unnest() etc.):

from sqlalchemy import values, column, Integer

# Add query values as needed to `data`
qts = values(column("ts", Integer), name="qts").data([(22,)])

In MySQL (before 8.0.19) and SQLite a UNION ALL of SELECT must be used instead:

from sqlalchemy import literal, select, union_all

qts = union_all(*[select([literal(v).label("ts")]) for v in [22]])

Scalar subqueries

lower = (
    session.query()
    .filter(Time <= qts.c.ts)
    .order_by(Time.desc())
    .limit(1)
)
higher = (
    session.query()
    .filter(Time > qts.c.ts)
    .order_by(Time.asc())
    .limit(1)
)
time_lower = lower.with_entities(Time).label("time_lower")
time_higher = higher.with_entities(Time).label("time_higher")
pos_lower = lower.with_entities(Position).label("pos_lower")
pos_higher = higher.with_entities(Position).label("pos_higher")

with_high_low = session.query(
    qts.c.ts,
    time_lower,
    time_higher,
    pos_lower,
    pos_higher
).subquery()

session.query(
    with_high_low.c.ts,
    (
        (with_high_low.c.time_higher - with_high_low.c.ts)
        * with_high_low.c.pos_lower
        + (with_high_low.c.ts - with_high_low.c.time_lower)
        * with_high_low.c.pos_higher
    ) / (with_high_low.c.time_higher - with_high_low.c.time_lower)
).all()

LATERAL

lower = (
    session.query(Time.label("ts"), Position.label("pos"))
    .filter(Time <= qts.c.ts)
    .order_by(Time.desc())
    .limit(1)
    .subquery()
    .lateral()
)
higher = (
    session.query(Time.label("ts"), Position.label("pos"))
    .filter(Time > qts.c.ts)
    .order_by(Time.asc())
    .limit(1)
    .subquery()
    .lateral()
)

session.query(
    qts.c.ts,
    (
        (higher.c.ts - qts.c.ts) * lower.c.pos
        + (qts.c.ts - lower.c.ts) * higher.c.pos
    ) / (higher.c.ts - lower.c.ts)
).all()

Window Functions

Combine the query values and the known values, removing query values that have a known value:

from sqlalchemy import null, not_, func, case

comb = session.query(
    qts.c.ts.label("ts"),
    null().label("pos")
).filter(
    not_(session.query(Time).filter(Time == qts.c.ts).exists())
).union(
    session.query(Time, Position)
).cte()

Build a partitioned view of the data so that it is possible to pick the lower and higher non-NULL values:

part = session.query(
    comb.c.ts,
    comb.c.pos,
    func.count(comb.c.pos).over(order_by=comb.c.ts).label("lp"),
    func.count(comb.c.pos).over(order_by=comb.c.ts.desc()).label("hp")
).cte()

The above would be unnecessary, if lag() and lead() with IGNORE NULLS was supported.

Finally, interpolate:

lw = dict(
    partition_by=part.c.lp,
    order_by=(part.c.ts, part.c.pos.nullslast())
)
hw = dict(
    partition_by=part.c.hp,
    order_by=(part.c.ts.desc(), part.c.pos.desc().nullslast())
)
fv = func.first_value
time_lower = fv(part.c.ts).over(**lw)
time_higher = fv(part.c.ts).over(**hw)
pos_lower = fv(part.c.pos).over(**lw)
pos_higher = fv(part.c.pos).over(**hw)

interp = session.query(
    part.c.ts,
    case([(part.c.pos == None,
           ((time_higher - part.c.ts) * pos_lower +
            (part.c.ts - time_lower) * pos_higher) /
           (time_higher - time_lower))],
         else_=part.c.pos).label("pos")
).cte()

And then pick the values of interest:

session.query(interp.c.ts, interp.c.pos).filter(
    interp.c.ts.in_(qts.select())
).all()


问:
SQLAlchemy Invalid Foreign Key with PostgreSQL but not SQLite
I can create the following tables in an SQLite database:

```<code>class Article(db.Model):
    id = db.Column(db.Integer, primary_key=True)

class Paragraph(db.Model):
    article_id = db.Column(db.ForeignKey('article.id'), primary_key=True)
    index = db.Column(db.Integer, primary_key=True)

class Summary(db.Model):
    article_id = db.Column(db.ForeignKey('article.id'), primary_key=True)
    paragraph_index = db.Column(db.ForeignKey('paragraph.index'), primary_key=True)
    level = db.Column(db.Integer, primary_key=True)
</code>```

However, when I create the same tables in PostgreSQL, I get the following error:

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.InvalidForeignKey) there is no unique constraint matching given keys for referenced table "paragraph"

Removing Summary.paragraph_index allows me to create the tables, so it appears that the issue lies here. However, the column does reference a primary key, which I feel should satisfy the requirement.

Adding unique=True to Paragraph.index also allows me to create the tables. I can then remove the unique constraint using pgAdmin and have everything work fine. However, this seems improper.

I have also tried:

declaring the relationship via the ORM

declaring ForeignKeyConstraint in Summary table args

declaring UniqueConstraint in Paragraph table args for the primary key columns

答:
In response to the comments by Adrian Klaver, of which I am grateful, I have used __table_args__ to point Summary at both halves of the composite primary key on Paragraph:

```<code>class Article(db.Model):
    id = db.Column(db.Integer, primary_key=True)

class Paragraph(db.Model):
    article_id = db.Column(db.ForeignKey('article.id'), primary_key=True)
    index = db.Column(db.Integer, primary_key=True)

class Summary(db.Model):
    article_id = db.Column(db.ForeignKey('article.id'), primary_key=True)
    paragraph_index = db.Column(db.Integer, primary_key=True)
    level = db.Column(db.Integer, primary_key=True)
    __table_args__ = (db.ForeignKeyConstraint(
        ['article_id', 'paragraph_index'],
        ['paragraph.article_id', 'paragraph.index']),)
</code>```

Body:
I can create the following tables in an SQLite database:

class Article(db.Model):
    id = db.Column(db.Integer, primary_key=True)

class Paragraph(db.Model):
    article_id = db.Column(db.ForeignKey('article.id'), primary_key=True)
    index = db.Column(db.Integer, primary_key=True)

class Summary(db.Model):
    article_id = db.Column(db.ForeignKey('article.id'), primary_key=True)
    paragraph_index = db.Column(db.ForeignKey('paragraph.index'), primary_key=True)
    level = db.Column(db.Integer, primary_key=True)

However, when I create the same tables in PostgreSQL, I get the following error:

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.InvalidForeignKey) there is no unique constraint matching given keys for referenced table "paragraph"

Removing Summary.paragraph_index allows me to create the tables, so it appears that the issue lies here. However, the column does reference a primary key, which I feel should satisfy the requirement.

Adding unique=True to Paragraph.index also allows me to create the tables. I can then remove the unique constraint using pgAdmin and have everything work fine. However, this seems improper.

I have also tried:

declaring the relationship via the ORM

declaring ForeignKeyConstraint in Summary table args

declaring UniqueConstraint in Paragraph table args for the primary key columns

Body:
In response to the comments by Adrian Klaver, of which I am grateful, I have used __table_args__ to point Summary at both halves of the composite primary key on Paragraph:

class Article(db.Model):
    id = db.Column(db.Integer, primary_key=True)

class Paragraph(db.Model):
    article_id = db.Column(db.ForeignKey('article.id'), primary_key=True)
    index = db.Column(db.Integer, primary_key=True)

class Summary(db.Model):
    article_id = db.Column(db.ForeignKey('article.id'), primary_key=True)
    paragraph_index = db.Column(db.Integer, primary_key=True)
    level = db.Column(db.Integer, primary_key=True)
    __table_args__ = (db.ForeignKeyConstraint(
        ['article_id', 'paragraph_index'],
        ['paragraph.article_id', 'paragraph.index']),)


问:
VueX dispatch action doesnt work, no error displayed in console VueJs
I'm trying to use an action to call method with boolean value using the store

In the store app.js, i've defined :

```<code>export default {
  namespaced: true,
    state: () => {
        return {
          isScrollDisabled: true,
        }
    },
    mutations: {
        setScrollDisabled(state, value) {
          state.isScrollDisabled = value
    },
    actions: {
        setScrollDisabled(context, value) {
          console.log('Action called in store')
          context.commit('setScrollDisabled', value)
    },
    getters: {
        getScrollDisabled: state => state.isScrollDisabled,
    }
</code>```

,

In the component, i dispatch the action like this :

```<code>this.$store.dispatch('app/setScrollDisabled', false) // with true or false
</code>```

And in other component, i use the store getter to retrieve the value :

```<code>computed: {
    isDisabled() {
      return this.$store.getters.getScrollDisabled
},
</code>```

I see nothing in the console and also in the VueJs Chrome extension, there are no event displayed

What i forgot here ?

答:
More friendly and easy

    computed: {
      ...mapGetters('app', [
        'getScrollDisabled'
      ])
    },
    methods: {
      ...mapActions('app', [
        'setScrollDisabled'
      ])
    }
```

Body:
I'm trying to use an action to call method with boolean value using the store

In the store app.js, i've defined :

export default {
  namespaced: true,
    state: () => {
        return {
          isScrollDisabled: true,
        }
    },
    mutations: {
        setScrollDisabled(state, value) {
          state.isScrollDisabled = value
    },
    actions: {
        setScrollDisabled(context, value) {
          console.log('Action called in store')
          context.commit('setScrollDisabled', value)
    },
    getters: {
        getScrollDisabled: state => state.isScrollDisabled,
    }

,

In the component, i dispatch the action like this :

this.$store.dispatch('app/setScrollDisabled', false) // with true or false

And in other component, i use the store getter to retrieve the value :

computed: {
    isDisabled() {
      return this.$store.getters.getScrollDisabled
},

I see nothing in the console and also in the VueJs Chrome extension, there are no event displayed

What i forgot here ?


问:
How to fix an error with images when deploying my streamlit webapp?
I started by making a text file (requirements.txt) with all the versions of the libraries used in the code. So I opened a folder on GitHub and added all the necessary files.

I used Streamlit Sharing to deploy and it returned the following error:

```<code>File "/home/appuser/venv/lib/python3.7/site-packages/streamlit/script_runner.py", line 379, in _run_script
    exec(code, module.__dict__)
File "/app/orbitas-relativistics/webapp.py", line 15, in <module>
    image1 = Image.open(r'C:/Users/isabe/.streamlit/titulo11.png')
File "/home/appuser/venv/lib/python3.7/site-packages/PIL/Image.py", line 2953, in open
    fp = builtins.open(filename, "rb")
</code>```

My code doesn't have the command fp = builtins.open(filename, "rb") and it doesn't even have 2953 lines. It only has 395.

About the images, I uploaded them inside the .streamlit folder of my Visual Studio Code (where the code is hosted). And it gives the error

FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/isabe/.streamlit/titulo11.png'

Does anyone know what I should do to fix this error and proceed with the deployment of my site?

Thanks for any help.

答:
In general, referring to exact filenames isn't a good idea when deploying, as it's almost certain that the machine you deploy on will have different drive mappings than your development machine.

In this case, you are using a Windows filepath and Streamlit Cloud is a Debian image. Based on your Git link, your file is located in the root directory, so you can specify image1 = Image.open('titulo11.png') and it will work on Streamlit Cloud (though it may not work on your development machine).

To make your code work on both machines, I suggest using something like pathlib to programmatically determine where a file is located, instead of having to inspect what level of file directory it might be in.

Body:
I started by making a text file (requirements.txt) with all the versions of the libraries used in the code. So I opened a folder on GitHub and added all the necessary files.

I used Streamlit Sharing to deploy and it returned the following error:

File "/home/appuser/venv/lib/python3.7/site-packages/streamlit/script_runner.py", line 379, in _run_script
    exec(code, module.__dict__)
File "/app/orbitas-relativistics/webapp.py", line 15, in <module>
    image1 = Image.open(r'C:/Users/isabe/.streamlit/titulo11.png')
File "/home/appuser/venv/lib/python3.7/site-packages/PIL/Image.py", line 2953, in open
    fp = builtins.open(filename, "rb")

My code doesn't have the command fp = builtins.open(filename, "rb") and it doesn't even have 2953 lines. It only has 395.

About the images, I uploaded them inside the .streamlit folder of my Visual Studio Code (where the code is hosted). And it gives the error

FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/isabe/.streamlit/titulo11.png'

Does anyone know what I should do to fix this error and proceed with the deployment of my site?

Thanks for any help.


问:
Laravel attach a non-physically saved file
I'm trying to find a way to attach a non-physical file to an email that's being made on the spot.

I'm using the following lines in my controller:

```<code>$columns = ['line1', 'line2'];
$rows    = [
    ['line1' => 'first', 'line2' => 'second'],
    ['line1' => 'first', 'line2' => 'second'],
    ['line1' => 'first', 'line2' => 'second'],
];

Mail::to('email@email.com')->send(new ExportMail($columns, $rows));
</code>```

And the following build function in the ExportMail class:

```<code>public function build()
{
    $file = fopen('php://output', 'w'); // Tried w+ too
    fputcsv($file, $this->columns);

    foreach ($this->rows as $row) {
        fputcsv($file, $row);
    }

</code>```

// I tried a couple of things:

```<code>    return $this->view('emails.myTestMail')
        ->attach($file);

    return $this->view('emails.myTestMail')
        ->attach(fopen($file, 'r'));

    return $this->view('emails.myTestMail')
        ->attach(fopen('php://output', 'r'));

    return $this->view('emails.myTestMail')
        ->attach(file_get_contents($file));

    return $this->view('emails.myTestMail')
        ->attach(file_get_contents(fopen($file, 'r')));

    return $this->view('emails.myTestMail')
        ->attach(file_get_contents(fopen('php://output', 'r')));
}
</code>```

But none if it works so I'm beginning to question if there is a way to send an email with a file that is never physically saved.

答:
You can attach file data directly with the attachData method documented here:

https://laravel.com/docs/9.x/mail#raw-data-attachments

I use this regularly to attach dynamically generated PDF files, for example.

You should be able to do something like this:

```<code>return $this->view('emails.myTestMail')
    ->attachData($yourCsvData, "attachment.csv");
</code>```

Also, I think you want to look at how you are generating your CSV data. Right now using php://output the CSV data will be sent out to the browser immediately, not stored in a variable.

There are a couple ways you can solve this, output buffering being one, or using php://temp instead, or using one of many CSV libraries (like https://csv.thephpleague.com/). I put together a fully working example for you here using php://temp:

https://laravelplayground.com/#/snippets/aa5b6594-4493-4ca4-9d12-837c102b7cc5

Expand the rawAttachments attribute on that Message on the right, and you'll see the attached CSV file.

Body:
I'm trying to find a way to attach a non-physical file to an email that's being made on the spot.

I'm using the following lines in my controller:

$columns = ['line1', 'line2'];
$rows    = [
    ['line1' => 'first', 'line2' => 'second'],
    ['line1' => 'first', 'line2' => 'second'],
    ['line1' => 'first', 'line2' => 'second'],
];

Mail::to('email@email.com')->send(new ExportMail($columns, $rows));

And the following build function in the ExportMail class:

public function build()
{
    $file = fopen('php://output', 'w'); // Tried w+ too
    fputcsv($file, $this->columns);

    foreach ($this->rows as $row) {
        fputcsv($file, $row);
    }

// I tried a couple of things:

    return $this->view('emails.myTestMail')
        ->attach($file);

    return $this->view('emails.myTestMail')
        ->attach(fopen($file, 'r'));

    return $this->view('emails.myTestMail')
        ->attach(fopen('php://output', 'r'));

    return $this->view('emails.myTestMail')
        ->attach(file_get_contents($file));

    return $this->view('emails.myTestMail')
        ->attach(file_get_contents(fopen($file, 'r')));

    return $this->view('emails.myTestMail')
        ->attach(file_get_contents(fopen('php://output', 'r')));
}

But none if it works so I'm beginning to question if there is a way to send an email with a file that is never physically saved.

Body:
You can attach file data directly with the attachData method documented here:

https://laravel.com/docs/9.x/mail#raw-data-attachments

I use this regularly to attach dynamically generated PDF files, for example.

You should be able to do something like this:

return $this->view('emails.myTestMail')
    ->attachData($yourCsvData, "attachment.csv");

Also, I think you want to look at how you are generating your CSV data. Right now using php://output the CSV data will be sent out to the browser immediately, not stored in a variable.

There are a couple ways you can solve this, output buffering being one, or using php://temp instead, or using one of many CSV libraries (like https://csv.thephpleague.com/). I put together a fully working example for you here using php://temp:

https://laravelplayground.com/#/snippets/aa5b6594-4493-4ca4-9d12-837c102b7cc5

Expand the rawAttachments attribute on that Message on the right, and you'll see the attached CSV file.


问:
Convert a value as a result of google colab which has e to a real value?
I have something like 3.34985746e-06  as a result of a calculation in colab. How can I convert this to a more readable value?</p>

答:
If you're just confused why it's represented as a string you can get it back to a float using float().

In [11]: val = '{:e}'.format(12312312312123)

In [12]: val
Out[12]: '1.231231e+13'

In [13]: float(val)
Out[13]: 12312310000000.0
```
<p>If instead you want fewer decimals displayed you can format your scientific notation with <code>{:.Ne}</code> where N is the number of decimals places:</p>
```In [14]: '{:.3e}'.format(0.00000334985756)
Out[14]: '3.350e-06'
```

Notice that the above also takes care of rounding for you.

Body:
If you're just confused why it's represented as a string you can get it back to a float using float().

In [11]: val = '{:e}'.format(12312312312123)

In [12]: val
Out[12]: '1.231231e+13'

In [13]: float(val)
Out[13]: 12312310000000.0

If instead you want fewer decimals displayed you can format your scientific notation with {:.Ne} where N is the number of decimals places:

In [14]: '{:.3e}'.format(0.00000334985756)
Out[14]: '3.350e-06'

Notice that the above also takes care of rounding for you.


问:
Python script repeat
I have an LED strip on a raspberry and would like to indicate the status of the internet on the LED strip by means of a color.

Now I came up with this:

```<code>import os
hostname = "google.com" #example

response = os.system("ping -c 1 " + hostname)

#and then check the response...

if response == 0:
    exec(open("random_blink.py").read())

else:
    exec(open("random_blink_colours.py").read())
</code>```

How can I get the script to rerun every 10 seconds?

答:
you can use time.sleep() along with a loop:

```<code>import time
import os
while True:
    import os
    hostname = "google.com" #example

    response = os.system("ping -c 1 " + hostname)

    #and then check the response...

    if response == 0:
        exec(open("random_blink.py").read())

    else:
        exec(open("random_blink_colours.py").read())

    time.sleep(10)
</code>```

I would recommend implementing a stop condition also.

Title: Python script repeat

Body:
I have an LED strip on a raspberry and would like to indicate the status of the internet on the LED strip by means of a color.

Now I came up with this:

import os
hostname = "google.com" #example

response = os.system("ping -c 1 " + hostname)

#and then check the response...

if response == 0:
    exec(open("random_blink.py").read())

else:
    exec(open("random_blink_colours.py").read())

How can I get the script to rerun every 10 seconds?

Body:
you can use time.sleep() along with a loop:

import time
import os
while True:
    import os
    hostname = "google.com" #example

    response = os.system("ping -c 1 " + hostname)

    #and then check the response...

    if response == 0:
        exec(open("random_blink.py").read())

    else:
        exec(open("random_blink_colours.py").read())

    time.sleep(10)

I would recommend implementing a stop condition also.


问:
How to use a wireless controller on the Google Coral Dev Board?
With the Jetson Nano I connected a PS4 controller via bluetooth and the device showed up under /dev/input/js0. However when I connect the controller via bluetooth to my Coral board, I am seeing nothing at that location, maybe because of Mendel instead of Ubuntu? What is the recommended way to connect a PS4 controller and access it from C++? Is there a different joystick I should use?

答:
After doing some research I learned about the difference between joydev and evdev on linux. It seems my PS4 controller showed up as a joydev device on the Jetson, whereas on the Coral running Mendel it showed up as an evdev device. I found some example C++ code for evdev devices from Croepha
/ David Butler here: https://handmade.network/forums/t/3673-modern_way_to_read_gamepad_input_with_c_on_linux

I modified this code for the PS4 controller like this:

```<code>void runJoystick() {
    auto gamepad = open("/dev/input/event4", O_RDONLY | O_NONBLOCK); //todo use /proc/bus/input/devices instead
    assert(gamepad != -1);
    std::cout << "Running joystick" << std::endl;

    while (m_still_running) {
        struct input_event events[8];  // 8 events per frame is pretty extreme, more like 1 or 2, sometimes as high as 4
        auto r1 = read(gamepad, events, sizeof events);
        if (r1 != -1) {
            int new_event_count = r1 / sizeof(struct input_event);
            for (int evi = 0; evi < new_event_count; evi++) {
                auto& ev = events[evi];

                switch (ev.type) {
                    case EV_ABS: {
                        switch (ev.code) {
                            case ABS_X: {  // left x
                                // std::cout << "type " << ev.code << "value:" << ev.value << std::endl;
                            } break;
                            case ABS_Y: {  // left y
                                // std::cout << "type " << ev.code << "value:" << ev.value << std::endl;
                            } break;
                            case ABS_Z: {  // right x
                                // std::cout << "type " << ev.code << "value:" << ev.value << std::endl;
                            } break;
                            case ABS_RZ: {  // right y
                                // std::cout << "type " << ev.code << "value:" << ev.value << std::endl;
                            } break;
                        }
                    } break;
                    case EV_KEY: {
                        switch (ev.code) {
                            case BTN_A: {  // square
                                std::cout << "Square ";
                            } break;
                            case BTN_B: {  // x
                                std::cout << "X ";
                            } break;
                            case BTN_C: {  // circle
                                std::cout << "Circle ";
                            } break;
                            case BTN_X: {  // triangle
                                std::cout << "Triangle ";
                            } break;
                        }

                        if (ev.value) {
                            std::cout << "Pressed " << std::endl;
                        } else {
                            std::cout << "Released " << std::endl;
                        }

                    } break;
                }
            }
        }

        assert(r1 != -1 || errno == EWOULDBLOCK || errno == EAGAIN);
        std::this_thread::sleep_for(std::chrono::milliseconds(20));
    }
}
</code>```

Body:
After doing some research I learned about the difference between joydev and evdev on linux. It seems my PS4 controller showed up as a joydev device on the Jetson, whereas on the Coral running Mendel it showed up as an evdev device. I found some example C++ code for evdev devices from Croepha
/ David Butler here: https://handmade.network/forums/t/3673-modern_way_to_read_gamepad_input_with_c_on_linux

I modified this code for the PS4 controller like this:

void runJoystick() {
    auto gamepad = open("/dev/input/event4", O_RDONLY | O_NONBLOCK); //todo use /proc/bus/input/devices instead
    assert(gamepad != -1);
    std::cout << "Running joystick" << std::endl;

    while (m_still_running) {
        struct input_event events[8];  // 8 events per frame is pretty extreme, more like 1 or 2, sometimes as high as 4
        auto r1 = read(gamepad, events, sizeof events);
        if (r1 != -1) {
            int new_event_count = r1 / sizeof(struct input_event);
            for (int evi = 0; evi < new_event_count; evi++) {
                auto& ev = events[evi];

                switch (ev.type) {
                    case EV_ABS: {
                        switch (ev.code) {
                            case ABS_X: {  // left x
                                // std::cout << "type " << ev.code << "value:" << ev.value << std::endl;
                            } break;
                            case ABS_Y: {  // left y
                                // std::cout << "type " << ev.code << "value:" << ev.value << std::endl;
                            } break;
                            case ABS_Z: {  // right x
                                // std::cout << "type " << ev.code << "value:" << ev.value << std::endl;
                            } break;
                            case ABS_RZ: {  // right y
                                // std::cout << "type " << ev.code << "value:" << ev.value << std::endl;
                            } break;
                        }
                    } break;
                    case EV_KEY: {
                        switch (ev.code) {
                            case BTN_A: {  // square
                                std::cout << "Square ";
                            } break;
                            case BTN_B: {  // x
                                std::cout << "X ";
                            } break;
                            case BTN_C: {  // circle
                                std::cout << "Circle ";
                            } break;
                            case BTN_X: {  // triangle
                                std::cout << "Triangle ";
                            } break;
                        }

                        if (ev.value) {
                            std::cout << "Pressed " << std::endl;
                        } else {
                            std::cout << "Released " << std::endl;
                        }

                    } break;
                }
            }
        }

        assert(r1 != -1 || errno == EWOULDBLOCK || errno == EAGAIN);
        std::this_thread::sleep_for(std::chrono::milliseconds(20));
    }
}


问:
How to execute a stored procedure inside a select query
```<code>SELECT col1,
       col2,
       col3,

EXEC GetAIntFromStoredProc(T.col1) AS col4
     FROM Tbl AS T
     WHERE (col2 = @parm)
</code>```

How to write this SQL query in SQL Server 2008?

答: Don't forget, if you just want to use the SP as a one-off query real quick to check something, all you have to do is pull the innards of the SP out and paste it in a new query window and do whatever you like at that point because it is no longer a SP.</p>

Body:
SELECT col1,
       col2,
       col3,

EXEC GetAIntFromStoredProc(T.col1) AS col4
     FROM Tbl AS T
     WHERE (col2 = @parm)

How to write this SQL query in SQL Server 2008?


问:
How to use jti claim in a JWT
The JWT spec mentions a jti claim which allegedly can be used as a nonce to prevent replay attacks:

The "jti" (JWT ID) claim provides a unique identifier for the JWT. The identifier value MUST be assigned in a manner that ensures that there is a negligible probability that the same value will be accidentally assigned to a different data object; if the application uses multiple issuers, collisions MUST be prevented among values produced by different issuers as well. The "jti" claim can be used to prevent the JWT from being replayed. The "jti" value is a case-sensitive string. Use of this claim is OPTIONAL.

My question is, how would I go about implementing this? Do I need to store the previously used jtis and issue a new JWT with every request? If so, doesn't this defeat the purpose of JWTs? Why use a JWT instead of just storing a randomly-generated session ID in a database?

My REST API has a Mongo database and I'm not opposed to adding a Redis instance. Is there a better authentication option than JWT? I mainly just don't want to store passwords on the client which eliminates HTTP authentication as an option, however, as I'm getting deeper into this JWT stuff, I'm starting to feel as if a custom token implementation or different standard might better suit my needs. Are there any node/express packages for token based authentication that supports token revocation and rotating tokens?

Would appreciate any advice.

答: While in most cases JWT tokens should be validated offline, there are cases in which it might make sense to validate online. Your application almost certainly exposes many types of actions, some of which are more risky (and probably less frequent) than others. These risky actions could sometimes benefit from online token validation, since by the time the token is validated, it might not be safe to use it anymore (as it might have been revoked, for instance, which is particularly visible for longer-lived JWTs - which in turn minimize the pressure on refreshes). Another thing is that you might have some sort of a risk engine solution, which can decide whether issuing a token have been a good decision or not.</p>

Title: How to use jti claim in a JWT