问:
Integrating a custom function in Django
I would like to access and print metadata (attributes and values) served by an ERDDAP server, which is a variety of OPeNDAP, on my Django website.

so I prepared a simple example function called get_conventions to access a metadata field on this public server hosting data and metadata. To get started, I install the required packages:

$ pip install pandas erddapy
```
<p>and then,</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
from erddapy import ERDDAP

def get_conventions(dataset_id):
    e = ERDDAP(server='https://gliders.ioos.us/erddap/', protocol='tabledap', response='csv')
    url = e.get_info_url(dataset_id, response='csv')
    df = pd.read_csv(url)

    # this replace spaces with underscores in column names
    df.columns = [col_name.replace(' ', '_') for col_name in df.columns]

    conventions = df[df.Attribute_Name == 'Conventions'].Value
    return conventions
</code>```

Using a Python interpreter, one could call the function like this with this sample dataset id as an argument (amelia-20180501T0000), which is found on the server; the output follows:

>>> get_conventions('amelia-20180501T0000')
6    Unidata Dataset Discovery v1.0, COARDS, CF-1.6
Name: Value, dtype: object
>>>
```

I would like my website to print on a webpage the output of the above function.

I can print the argument string in a page (model.py, views.py and a related html templates - those being similar to the Django tutorial), but I am unsure how to refer the argument to the function (and expect a return) or how/where to integrate the function in the Django structure.

The argument is stored in a local database which can be referred using models/views/template

But I am unsure how to integrate the part involving the function in Django?

答:
The approach is going to depend on whether the function is going to be used cross-app, in a single app, or is tied to a Django model.

For cross-app functions, I typically create a separate app called core or utils with python files for each set of functionality. For the sake of your example let's call it erddapy.py. In the views.py that your view is in, simply from utils.erddapy import get_conventions and call it in your view passing in the argument. Then return the result as context to the template.

If it's only being used in a single app but not tied to a model you can also create a utils.py file in that app and instead do from .utils import get_conventions in your views.py then call it in your view.

If you've defined a model for the datasets and store the dataset id there it's probably better suited for a model method. That way you can use the queryset API in your view to get the instance then simply call instance.get_conventions(). You wouldn't need an argument for this approach since you could simply get the dataset id from self.dataset_id in the method logic.

```<code># view
id = self.kwargs.get('id')
if id:
    instance = get_object_or_404(MyModel, id=id)
    data = instance.get_conventions()
# return the data as context in an http response

# model method
class MyModel(models.Model):
    # model fields

    def get_conventions(self):
        dataset_id = self.dataset_id
        # get the data

</code>```

I guess the underlying question is how are you storing or obtaining the dataset id? If it's in a separate local database you may need to query it to get the dataset id which I would do in a separate function. Then either pass it into the function as an argument or store it in your Django db as a model instance and use the method approach explained above.

Title: Integrating a custom function in Django

Body:
I would like to access and print metadata (attributes and values) served by an ERDDAP server, which is a variety of OPeNDAP, on my Django website.

so I prepared a simple example function called get_conventions to access a metadata field on this public server hosting data and metadata. To get started, I install the required packages:

$ pip install pandas erddapy

and then,

import pandas as pd
from erddapy import ERDDAP

def get_conventions(dataset_id):
    e = ERDDAP(server='https://gliders.ioos.us/erddap/', protocol='tabledap', response='csv')
    url = e.get_info_url(dataset_id, response='csv')
    df = pd.read_csv(url)

    # this replace spaces with underscores in column names
    df.columns = [col_name.replace(' ', '_') for col_name in df.columns]

    conventions = df[df.Attribute_Name == 'Conventions'].Value
    return conventions

Using a Python interpreter, one could call the function like this with this sample dataset id as an argument (amelia-20180501T0000), which is found on the server; the output follows:

>>> get_conventions('amelia-20180501T0000')
6    Unidata Dataset Discovery v1.0, COARDS, CF-1.6
Name: Value, dtype: object
>>>

I would like my website to print on a webpage the output of the above function.

I can print the argument string in a page (model.py, views.py and a related html templates - those being similar to the Django tutorial), but I am unsure how to refer the argument to the function (and expect a return) or how/where to integrate the function in the Django structure.

The argument is stored in a local database which can be referred using models/views/template

But I am unsure how to integrate the part involving the function in Django?

Body:
The approach is going to depend on whether the function is going to be used cross-app, in a single app, or is tied to a Django model.

For cross-app functions, I typically create a separate app called core or utils with python files for each set of functionality. For the sake of your example let's call it erddapy.py. In the views.py that your view is in, simply from utils.erddapy import get_conventions and call it in your view passing in the argument. Then return the result as context to the template.

If it's only being used in a single app but not tied to a model you can also create a utils.py file in that app and instead do from .utils import get_conventions in your views.py then call it in your view.

If you've defined a model for the datasets and store the dataset id there it's probably better suited for a model method. That way you can use the queryset API in your view to get the instance then simply call instance.get_conventions(). You wouldn't need an argument for this approach since you could simply get the dataset id from self.dataset_id in the method logic.

# view
id = self.kwargs.get('id')
if id:
    instance = get_object_or_404(MyModel, id=id)
    data = instance.get_conventions()
# return the data as context in an http response

# model method
class MyModel(models.Model):
    # model fields

    def get_conventions(self):
        dataset_id = self.dataset_id
        # get the data

I guess the underlying question is how are you storing or obtaining the dataset id? If it's in a separate local database you may need to query it to get the dataset id which I would do in a separate function. Then either pass it into the function as an argument or store it in your Django db as a model instance and use the method approach explained above.


来源: stackexchange

问:
How can I print the empty spaces with " | | " until the line ends
I am working with vectors and I wanna know how I can print the empty spaces in between until the line ends.

void print_vector(const std::vector < int > & v, int print_cols, int col_width) {
  //dash
  cout << string(print_cols * (col_width + 2) + 1, '-');
  cout << endl;
  //printing the vector in formated output
  cout << "|";
  for (size_t x = 0; x < v.size(); x++) {

    cout << right << setw(col_width) << v[x] << " |";
    //prints new line if it reaches limit of numbers per line
    if ((x + 1) % print_cols == 0) cout << endl << "|";

  }

  //dash
  cout << endl << string(print_cols * (col_width + 2) + 1, '-');
  cout << endl;
}
```

this is my current output: my output so far and sorry I can't embed images yet it wont let me.
But this is the output that I want output needed

ContentLicense: CC BY-SA 4.0

Body:
I am working with vectors and I wanna know how I can print the empty spaces in between until the line ends.

void print_vector(const std::vector < int > & v, int print_cols, int col_width) {
  //dash
  cout << string(print_cols * (col_width + 2) + 1, '-');
  cout << endl;
  //printing the vector in formated output
  cout << "|";
  for (size_t x = 0; x < v.size(); x++) {

    cout << right << setw(col_width) << v[x] << " |";
    //prints new line if it reaches limit of numbers per line
    if ((x + 1) % print_cols == 0) cout << endl << "|";

  }

  //dash
  cout << endl << string(print_cols * (col_width + 2) + 1, '-');
  cout << endl;
}

this is my current output: my output so far and sorry I can't embed images yet it wont let me.
But this is the output that I want output needed

Body:
void print_vector(const std::vector < int > & v, int print_cols, int col_width) {
  //dash
  cout << string(print_cols * (col_width + 2) + 1, '-');
  cout << endl;
  //printing the vector in formated output
  cout << "|";
  size_t x = 0;
  for (x = 0; x < v.size(); x++) {

    cout << right << setw(col_width) << v[x] << " |";
    //prints new line if it reaches limit of numbers per line
    if (x < v.size() - 1) {
      if ((x + 1) % print_cols == 0) {
         cout << endl << "|";
      }
    }

  }
  size_t remain = print_cols - (x % print_cols);
  for (size_t i = 0; (remain != print_cols) && i < remain; ++i) {
    cout << right << setw(col_width) << " " << " |";
  }
  //dash
  cout << endl << string(print_cols * (col_width + 2) + 1, '-');
  cout << endl;
}

Sample outputs:

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

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


问:
Error in opening text file from src folder in Java
I am making a Java program and want to open a text(notepad) file ,that i have saved in src folder in my Java Program, I have tried to do it by the following code , but it is giving error. "The method exec(String) in the type Runtime is not applicable for the arguments
(InputStream) , Any suggestions ? Thanks

```<code>Runtime runtime = Runtime.getRuntime();
InputStream lic = this.getClass().getClassLoader().getResourceAsStream("MyFile.txt");
Process process = runtime.exec(lic);
</code>```

答:
You can not execute an input-stream, it's just a collection of bytes, not a file.

You should store this file somewhere else inside your project (like a resources folder) and use the path to open the file. Here's how it would look like:

```<code>File file = new File("resources/my-file.txt");
String[] command = { "notepad.exe", file.getAbsolutePath() };
Runtime.getRuntime().exec( command );
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am making a Java program and want to open a text(notepad) file ,that i have saved in src folder in my Java Program, I have tried to do it by the following code , but it is giving error. "The method exec(String) in the type Runtime is not applicable for the arguments
(InputStream) , Any suggestions ? Thanks

Runtime runtime = Runtime.getRuntime();
InputStream lic = this.getClass().getClassLoader().getResourceAsStream("MyFile.txt");
Process process = runtime.exec(lic);

Body:
You can not execute an input-stream, it's just a collection of bytes, not a file.

You should store this file somewhere else inside your project (like a resources folder) and use the path to open the file. Here's how it would look like:

File file = new File("resources/my-file.txt");
String[] command = { "notepad.exe", file.getAbsolutePath() };
Runtime.getRuntime().exec( command );


问:
Axios post data shows in config, but not data, no body passed
I have a react frontend sending to a mongoose/express backend. Previously I was using flask for the backend and everything ran fine, this issue only started after switching to express. On postman, the call goes through perfect, but when I try through the browser, I get a 200 response, with an empty document created. In the console, the correct data shows in the config object, but not in the actual data object.

Heres the React/Formik onSubmit sending the post:

```<code>onSubmit={async (values) => {

      console.log(values);

      const headers = {
        'Content-Type': 'application/json,multipart/form-data'
      };

     await axios.post('http://localhost:5000/api/clients', values, {headers})
      .then(response => {
        console.log(response);
        return response;
      })
      //.then(this.props.history.push('/Clients'))
      .catch(function (error){
        console.log(error);
      });

    }}>

</code>```

Heres the console response (the first object is the console.log(response) from the onSubmit):

```<code>Object { firstName: "Johnny", lastName: "Cochrane", phone: "8585678899", id: "" }

firstName: "Johnny"

id: ""

lastName: "Cochrane"

phone: "8585678899"

<prototype>: Object { … }
AddClient.js:49
Object { data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, request: XMLHttpRequest }

config: Object { url: "http://localhost:5000/api/clients", method: "post", data: "{\"firstName\":\"Johnny\",\"lastName\":\"Cochrane\",\"phone\":\"8585678899\",\"id\":\"\"}", … }

data: Object { _id: "62043b723fe12d6b4ec354b8", clientId: 12, __v: 0, … }

headers: Object { "content-length": "71", "content-type": "application/json; charset=utf-8" }

request: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }

status: 200

statusText: "OK"
</code>```

Any help would be greatly appreciated as I'm at a total loss. Thanks

答: "application/json,multipart/form-data"... You can't have multiple content types in a single request. Axios defaults to application/json when posting objects so you don't need your customised headers at all. TL;DR just use axios.post(url, values) – Phil</p>

Body:
I have a react frontend sending to a mongoose/express backend. Previously I was using flask for the backend and everything ran fine, this issue only started after switching to express. On postman, the call goes through perfect, but when I try through the browser, I get a 200 response, with an empty document created. In the console, the correct data shows in the config object, but not in the actual data object.

Heres the React/Formik onSubmit sending the post:

onSubmit={async (values) => {

      console.log(values);

      const headers = {
        'Content-Type': 'application/json,multipart/form-data'
      };

     await axios.post('http://localhost:5000/api/clients', values, {headers})
      .then(response => {
        console.log(response);
        return response;
      })
      //.then(this.props.history.push('/Clients'))
      .catch(function (error){
        console.log(error);
      });

    }}>

Heres the console response (the first object is the console.log(response) from the onSubmit):

Object { firstName: "Johnny", lastName: "Cochrane", phone: "8585678899", id: "" }

firstName: "Johnny"

id: ""

lastName: "Cochrane"

phone: "8585678899"

<prototype>: Object { … }
AddClient.js:49
Object { data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, request: XMLHttpRequest }

config: Object { url: "http://localhost:5000/api/clients", method: "post", data: "{\"firstName\":\"Johnny\",\"lastName\":\"Cochrane\",\"phone\":\"8585678899\",\"id\":\"\"}", … }

data: Object { _id: "62043b723fe12d6b4ec354b8", clientId: 12, __v: 0, … }

headers: Object { "content-length": "71", "content-type": "application/json; charset=utf-8" }

request: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }

status: 200

statusText: "OK"

Any help would be greatly appreciated as I'm at a total loss. Thanks


问:
Formatter black is not working on my VSCode...but why?
I have started using Python and Django and I am very new in this field.
And this is my first time to ask a question here...I do apologise in advance if there is a known solution to this issue...

When I installed and set VSCode formatter 'black' (after setting linter as flake8), the tutorial video tutor's side shows up pop-up like 'formatter autopep8 is not installed. install?'. & Mine did not show up that message.

So what I did was...

manually input 'pipenv install flack --dev --pre' on terminal.

manually input "python.formatting.provider": "black", to 'settings.json' on '.vscode' folder.

Setting(VSCode) -> flake8, Python > Linting: Flake8 Enabled (Also modified in: workspace), (ticked the box) Whether to lint Python files using flake8

The bottom code is from settings.json (on vscode folder).

```<code>
{
  "python.linting.pylintEnabled": false,
  "python.linting.flake8Enabled": true,
  "python.linting.enabled": true,
  "python.formatting.provider": "black", # input manually
  "python.linting.flake8Args": ["--max-line-length=88"] # input manually
}

</code>```

I found a 'black formatter' document. https://github.com/psf/black & it stated...
python -m black {source_file_or_directory} & I get the following error message.

```<code>
    Usage: __main__.py [OPTIONS] [SRC]...
Try '__main__.py -h' for help.

Error: Invalid value for '[SRC]...': Path '{source_file_or_directory}' does not exist.

</code>```

Yes, honestly, I am not sure which source_file_or_directory I should set...but above all now I am afraid whether I am on the right track or not.

Can I hear your advice? At least some direction to go, please.
Thanks..

答:
For those who see this and none of the above solutions work.
If you set the black path to its absolute location it might solve the problem.

Body:
I have started using Python and Django and I am very new in this field.
And this is my first time to ask a question here...I do apologise in advance if there is a known solution to this issue...

When I installed and set VSCode formatter 'black' (after setting linter as flake8), the tutorial video tutor's side shows up pop-up like 'formatter autopep8 is not installed. install?'. & Mine did not show up that message.

So what I did was...

manually input 'pipenv install flack --dev --pre' on terminal.

manually input "python.formatting.provider": "black", to 'settings.json' on '.vscode' folder.

Setting(VSCode) -> flake8, Python > Linting: Flake8 Enabled (Also modified in: workspace), (ticked the box) Whether to lint Python files using flake8

The bottom code is from settings.json (on vscode folder).

{
  "python.linting.pylintEnabled": false,
  "python.linting.flake8Enabled": true,
  "python.linting.enabled": true,
  "python.formatting.provider": "black", # input manually
  "python.linting.flake8Args": ["--max-line-length=88"] # input manually
}

I found a 'black formatter' document. https://github.com/psf/black & it stated...
python -m black {source_file_or_directory} & I get the following error message.

    Usage: __main__.py [OPTIONS] [SRC]...
Try '__main__.py -h' for help.

Error: Invalid value for '[SRC]...': Path '{source_file_or_directory}' does not exist.

Yes, honestly, I am not sure which source_file_or_directory I should set...but above all now I am afraid whether I am on the right track or not.

Can I hear your advice? At least some direction to go, please.
Thanks..


问:
PHP password_hash and password_verify Not Working with MySQL
I am using password_hash to store passwords in a MySQL database field of type VARCHAR(255). When I try to login the user and verify credentials, the password_verify function always returns false.

Here is the code excerpt that stores the password in the MySQL database:

```<code>$password_hash = password_hash($password, PASSWORD_DEFAULT);

// Generate API Key
$api_key = $this->generateApiKey();

// Insert Query
$stmt = $this->conn->prepare("INSERT INTO user(email, password, name, api_key, status) values(?, ?, ?, ?, 1)");
$stmt->bind_param("ssss", $email, $password_hash, $name, $api_key);
$result = $stmt->execute();
$stmt->close();
</code>```

And the piece of code that checks the password:

```<code>// Query user by email
$stmt = $this->conn->prepare("SELECT password FROM user WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();

$stmt->bind_result($password_hash);
$stmt->store_result();

if ($stmt->num_rows > 0) {
    // Found user with that email address
    // Now verify the password

    $stmt->fetch();
    $stmt->close();

    if (password_verify($password, $password_hash)) {
        // User password is correct
        return TRUE;
</code>```

Then I wrote this test code and grabbed the data straight from the MySQL field and it still fails. When I create the password_hash in the same file ($hash2 in the file below) - then the password verifies correctly.

```<code>$password = 'pass1234567890';
$hash = '$2y$10$JLP/pPei6RYRdUmoH8H5RO7iJyImOtrBLsrRRfq3XpeqNE3lQ/l7O';
$hash2 = password_hash($password, PASSWORD_DEFAULT);

echo $hash . " - " . strlen($hash);
echo "<br />";
echo $hash2 . " - " . strlen($hash2);
echo "<br />";

if (password_verify($password, $hash)) {
    echo "Password Valid!";
} else {
    echo "Password invalid!";
}

echo "<br /><br />";

if (password_verify($password, $hash2)) {
    echo "Password 2 Valid!";
} else {
    echo "Password 2 invalid!";
}
</code>```

答:
```<code>password_verify($password,trim($password_hash)))
</code>```

While I am unsure if it happened when the hash was stored or during retrieval, the password_hash had a space at the end. Trimming the hash before feeding it to password_verify fixed the issue for me.

Body:
I am using password_hash to store passwords in a MySQL database field of type VARCHAR(255). When I try to login the user and verify credentials, the password_verify function always returns false.

Here is the code excerpt that stores the password in the MySQL database:

$password_hash = password_hash($password, PASSWORD_DEFAULT);

// Generate API Key
$api_key = $this->generateApiKey();

// Insert Query
$stmt = $this->conn->prepare("INSERT INTO user(email, password, name, api_key, status) values(?, ?, ?, ?, 1)");
$stmt->bind_param("ssss", $email, $password_hash, $name, $api_key);
$result = $stmt->execute();
$stmt->close();

And the piece of code that checks the password:

// Query user by email
$stmt = $this->conn->prepare("SELECT password FROM user WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();

$stmt->bind_result($password_hash);
$stmt->store_result();

if ($stmt->num_rows > 0) {
    // Found user with that email address
    // Now verify the password

    $stmt->fetch();
    $stmt->close();

    if (password_verify($password, $password_hash)) {
        // User password is correct
        return TRUE;

Then I wrote this test code and grabbed the data straight from the MySQL field and it still fails. When I create the password_hash in the same file ($hash2 in the file below) - then the password verifies correctly.

$password = 'pass1234567890';
$hash = '$2y$10$JLP/pPei6RYRdUmoH8H5RO7iJyImOtrBLsrRRfq3XpeqNE3lQ/l7O';
$hash2 = password_hash($password, PASSWORD_DEFAULT);

echo $hash . " - " . strlen($hash);
echo "
";
echo $hash2 . " - " . strlen($hash2);
echo "
";

if (password_verify($password, $hash)) {
    echo "Password Valid!";
} else {
    echo "Password invalid!";
}

echo "

";

if (password_verify($password, $hash2)) {
    echo "Password 2 Valid!";
} else {
    echo "Password 2 invalid!";
}

Body:
password_verify($password,trim($password_hash)))

While I am unsure if it happened when the hash was stored or during retrieval, the password_hash had a space at the end. Trimming the hash before feeding it to password_verify fixed the issue for me.


问:
Google Sheets Extracting Digits with Regex
I've been stuck on this for a while now. I want to extract only digits (numeric values) from the cell, but for some reason, it does not extract if it contains a single digit. See below for more details:

String
End Result

$8 - added to cart
8

Formula used: =REGEXEXTRACT(J92,"\d+.?\d+")

The formula would also grab digits that contain decimals. For some reason, this formula works if the string was "$81 - added to cart". Can someone help me fix this so it would work on strings with a single digit?

Body:
try:

=REGEXMATCH(A1&""; "\d+(?:.\d+)?")*1

for array use:

=INDEX(IFNA(REGEXEXTRACT(A2:A&""; "\d+(?:.\d+)?")*1))


问:
Pandas numpy how to convert a complicated .apply function to a vectorized function
I have a dataframe and you can have it by run this code:

```<code>import numpy as np
import pandas as pd
from io import StringIO
# np.prod(PofMinTab1[LowerIntegralAge1[0]-1:(LowerIntegralAge1[0])])
dfs = """
    M0  M1  M2  M3 M4  M5 M6 M7 M8 M9 M10 M11 M12  age0  age4
1   1   2   3    4  5   6  1  2 3    4  5  6   1     3    5
2   7   5   4    5  8   3  1  2 3    4  5  6   1     4     8
3   4   8   9    3  5   2  1  2 3    4  5  6   1     6      9
"""
df = pd.read_csv(StringIO(dfs.strip()), sep='\s+', )
</code>```

And I have a .apply function:

```<code>def func(row):
    age0=row['age0']
    age4=row['age4']
    mt =[row['M0'],row['M1'],row['M2'],row['M3'], row['M4'],row['M5'],row['M6'],
         row['M7'],row['M8'],row['M9'],row['M10'],row['M11'],row['M12']]

    return np.prod(mt[age0:age4])

df['newcol']=df.apply(lambda row: func(row), axis=1)
</code>```

the output is:

```<code>M0  M1  M2  M3  M4  M5  M6  M7  M8  M9  M10 M11 M12   age0  age4    newcol
1   1   2   3   4   5   6   1   2   3   4   5   6   1   3   5       20
2   7   5   4   5   8   3   1   2   3   4   5   6   1   4   8       48
3   4   8   9   3   5   2   1   2   3   4   5   6   1   6   9       6
</code>```

Since in my real business,I have 100000 rows data,each time I use .apply function it is very slow, so I've converted most of my functions to vectorized function.

So my question,is there any way I can convert this one to numpy vectorized way,or any other way that can make it runs very fast?

Any friend can help?

答:
You can test for loop</p>
```<code>[df.loc[z][x:y].prod() for x , y, z in zip(df['age0'],df['age4'],df.index)]
Out[43]: [20, 48, 6]
</code>```

Body:
I have a dataframe and you can have it by run this code:

import numpy as np
import pandas as pd
from io import StringIO
# np.prod(PofMinTab1[LowerIntegralAge1[0]-1:(LowerIntegralAge1[0])])
dfs = """
    M0  M1  M2  M3 M4  M5 M6 M7 M8 M9 M10 M11 M12  age0  age4
1   1   2   3    4  5   6  1  2 3    4  5  6   1     3    5
2   7   5   4    5  8   3  1  2 3    4  5  6   1     4     8
3   4   8   9    3  5   2  1  2 3    4  5  6   1     6      9
"""
df = pd.read_csv(StringIO(dfs.strip()), sep='\s+', )

And I have a .apply function:

def func(row):
    age0=row['age0']
    age4=row['age4']
    mt =[row['M0'],row['M1'],row['M2'],row['M3'], row['M4'],row['M5'],row['M6'],
         row['M7'],row['M8'],row['M9'],row['M10'],row['M11'],row['M12']]

    return np.prod(mt[age0:age4])

df['newcol']=df.apply(lambda row: func(row), axis=1)

the output is:

M0  M1  M2  M3  M4  M5  M6  M7  M8  M9  M10 M11 M12   age0  age4    newcol
1   1   2   3   4   5   6   1   2   3   4   5   6   1   3   5       20
2   7   5   4   5   8   3   1   2   3   4   5   6   1   4   8       48
3   4   8   9   3   5   2   1   2   3   4   5   6   1   6   9       6

Since in my real business,I have 100000 rows data,each time I use .apply function it is very slow, so I've converted most of my functions to vectorized function.

So my question,is there any way I can convert this one to numpy vectorized way,or any other way that can make it runs very fast?

Any friend can help?

Body:
You can test for loop

[df.loc[z][x:y].prod() for x , y, z in zip(df['age0'],df['age4'],df.index)]
Out[43]: [20, 48, 6]


问:
Cannot parse xml data with javascript HTML DOM on local system
I tried this sample code from tutorialspoint website on a number of browsers. But the xml data is not being parsed. Both these files are on my local system and the address.xml file is inside a folder "xml".

How can I parse data in javascript from the xml files on my local system?

Here is my HTML file sample.html from tutorialspoint website:

```<code><!DOCTYPE html>
<html>
   <body>
      <h1>TutorialsPoint DOM example </h1>
      <div>
         <b>Name:</b> <span id="name"></span><br>
         <b>Company:</b> <span id="company"></span><br>
         <b>Phone:</b> <span id="phone"></span>
      </div>
      <script>
         if (window.XMLHttpRequest)
         {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
         }
         else
         {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         }
         xmlhttp.open("GET","/xml/address.xml",false);
         xmlhttp.send();
         xmlDoc=xmlhttp.responseXML;

         document.getElementById("name").innerHTML=
         xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
         document.getElementById("company").innerHTML=
         xmlDoc.getElementsByTagName("company")[0].childNodes[0].nodeValue;
         document.getElementById("phone").innerHTML=
         xmlDoc.getElementsByTagName("phone")[0].childNodes[0].nodeValue;
      </script>
   </body>
</html>
</code>```

This is the xml data file address.xml:

```<code><?xml version="1.0"?>
<contact-info>
   <name>Tanmay Patil</name>
   <company>TutorialsPoint</company>
   <phone>(011) 123-4567</phone>
</contact-info>
</code>```

Update: The problem was with getting an http response on local system. It is solved after I installed XAMPP.

答:
As Jaromanda X mentioned in the comments, and as I found out the hard way, Chrome won't parse local xml files using the DOM parser.  However, if you directly use the console and save your xml text there (as a var/let,etc..) you will be able to parse it using the DOM parser.

Ex:

Body:
I tried this sample code from tutorialspoint website on a number of browsers. But the xml data is not being parsed. Both these files are on my local system and the address.xml file is inside a folder "xml".

How can I parse data in javascript from the xml files on my local system?

Here is my HTML file sample.html from tutorialspoint website:

<!DOCTYPE html>

TutorialsPoint DOM example

         Name:

         Company:

         Phone:

This is the xml data file address.xml:

<?xml version="1.0"?>
<contact-info>
   <name>Tanmay Patil</name>
   <company>TutorialsPoint</company>
   <phone>(011) 123-4567</phone>
</contact-info>

Update: The problem was with getting an http response on local system. It is solved after I installed XAMPP.


问:
Adding new column with multiple values per existing record
I'm interested in adding a column to an existing table with a set of explicit values that should duplicate existing records (similar to common join constructs).

For example, say we're starting with a table with a single column:

```<code>CREATE TABLE #DEMO (
    COLUMN_A NVARCHAR(100) NOT NULL
    PRIMARY KEY (COLUMN_A)
);
</code>```

COLUMN_A

ACCOUNT_001

ACCOUNT_002

ACCOUNT_003

...and I want to add Column_B with row values of 'A', 'B', and 'C'.  The end goal would be a table that looks like:

COLUMN_A
COLUMN_B

ACCOUNT_001
A

ACCOUNT_001
B

ACCOUNT_001
C

ACCOUNT_002
A

ACCOUNT_002
B

ACCOUNT_002
C

ACCOUNT_003
A

ACCOUNT_003
B

ACCOUNT_003
C

Is this possible?  Bonus Points if there is a name or phrase for this you know of.

答:
So I think you need couple of steps to first insert new rows and then update existing:

```<code>alter table #demo add COLUMN_B char(1);

with x as (
    select * from (values('A'),('B'))x(B)
)
insert into #demo(COLUMN_A, COLUMN_B)
select COLUMN_A, B
from #DEMO cross join x

update #DEMO set COLUMN_B = 'C'
where COLUMN_B is null
</code>```

Demo Fiddle

Body:
I'm interested in adding a column to an existing table with a set of explicit values that should duplicate existing records (similar to common join constructs).

For example, say we're starting with a table with a single column:

CREATE TABLE #DEMO (
    COLUMN_A NVARCHAR(100) NOT NULL
    PRIMARY KEY (COLUMN_A)
);

COLUMN_A

ACCOUNT_001

ACCOUNT_002

ACCOUNT_003

...and I want to add Column_B with row values of 'A', 'B', and 'C'.  The end goal would be a table that looks like:

COLUMN_A
COLUMN_B

ACCOUNT_001
A

ACCOUNT_001
B

ACCOUNT_001
C

ACCOUNT_002
A

ACCOUNT_002
B

ACCOUNT_002
C

ACCOUNT_003
A

ACCOUNT_003
B

ACCOUNT_003
C

Is this possible?  Bonus Points if there is a name or phrase for this you know of.

Body:
So I think you need couple of steps to first insert new rows and then update existing:

alter table #demo add COLUMN_B char(1);

with x as (
    select * from (values('A'),('B'))x(B)
)
insert into #demo(COLUMN_A, COLUMN_B)
select COLUMN_A, B
from #DEMO cross join x

update #DEMO set COLUMN_B = 'C'
where COLUMN_B is null

Demo Fiddle


问:
Docker image fails to build on Google Container Registry
I have setup a trigger from Bitbucket to Google Container Registry.
I have a Dockerfile in the root, and am able to build the container fine from my local machine.

I get this error in Google Container Registry when the trigger runs (I did not modify the command that GCR wanted to run - it's the default).  My project name has been replaced with "project":

```<code>FETCHSOURCE
Initialized empty Git repository in /workspace/.git/
From https://source.developers.google.com/p/project/r/bitbucket-project-gateway
* branch c65f16b3f52262a047c71e7140aecc4300265497 -> FETCH_HEAD
HEAD is now at c65f16b testing
BUILD
Already have image (with digest): gcr.io/cloud-builders/docker
invalid argument "gcr.io/project/bitbucket-project-gateway:" for t: invalid reference format
See 'docker build --help'.
ERROR
ERROR: build step "gcr.io/cloud-builders/docker@sha256:e576df764ae28d3c072019a235b6c8966df11eecb472c59b0963d783bb8a713b" failed: exit status 125
</code>```

答:
For others who come along, when running into this same issue when pushing a Dockerfile with a Cloud Build YAML file - my mistakes:

Had ${SHORT_SHA} in one place and not the other (was on the Artifact push and not the build) [https://stackoverflow.com/a/44716934/18176030credit to Philmod for the tag not being right]

I was using the "grc.io" on during the build process and not the Artifact push (was using "us-east1-docker.pkg.dev").

Body:
I have setup a trigger from Bitbucket to Google Container Registry.
I have a Dockerfile in the root, and am able to build the container fine from my local machine.

I get this error in Google Container Registry when the trigger runs (I did not modify the command that GCR wanted to run - it's the default).  My project name has been replaced with "project":

FETCHSOURCE
Initialized empty Git repository in /workspace/.git/
From https://source.developers.google.com/p/project/r/bitbucket-project-gateway
* branch c65f16b3f52262a047c71e7140aecc4300265497 -> FETCH_HEAD
HEAD is now at c65f16b testing
BUILD
Already have image (with digest): gcr.io/cloud-builders/docker
invalid argument "gcr.io/project/bitbucket-project-gateway:" for t: invalid reference format
See 'docker build --help'.
ERROR
ERROR: build step "gcr.io/cloud-builders/docker@sha256:e576df764ae28d3c072019a235b6c8966df11eecb472c59b0963d783bb8a713b" failed: exit status 125


问:
Java RestAssured Cucumber - sharing variable value between scenarios in the same class
I have written a number of Rest Assured Cucumber tests to test my API. I have written cucumber feature/step definition files do the following:-

Add a new category
Update the category
Delete the Category.

So I have a single step definition class with three scenarios.

The first scenario creates a new category and I store the category ID in a global scope variable (this variable was declared at the top of the class file). I wrote the variable to the console to make sure it has a value (it did) after the new category is deleted. After the scenario has finished it moves onto scenario 2 where it tries to update the category. The problem is that value of the global variable has now become empty and the test fails.

Does anyone know if its possible to share the content of global variables between different scenarios in the same step definition class file?

答:
It is intentionally difficult to share information between scenarios. Each scenario is it's own little experiment and should not be influenced by others.

Now if you're used to writing manual test scripts you may think it's efficient to reuse things. And it is. But a computer is much faster so you don't have to be efficient. Rather because it's cheap to do everything from scratch, a little inefficiency is worth reducing the chance tests can interact by accident.

So rather consider writing three different scenarios:

```<code>Scenario: Create
  Given the things needed to make a category
  When a new category is created
  Then it has all the things used to make it

Scenario: Update
  Given a category with some property
  When the property of the category is changed
  Then fetching the category again shows the updated
property

Scenario: Delete
  Given a category
  When the category is deleted
  Then the category is not found when fetched
</code>```

The second and third create the category in the given step.

Now if this is a system that isn't shutdown after a test run you may also want to use after hooks to try and delete any categories created when the test is done.

Body:
It is intentionally difficult to share information between scenarios. Each scenario is it's own little experiment and should not be influenced by others.

Now if you're used to writing manual test scripts you may think it's efficient to reuse things. And it is. But a computer is much faster so you don't have to be efficient. Rather because it's cheap to do everything from scratch, a little inefficiency is worth reducing the chance tests can interact by accident.

So rather consider writing three different scenarios:

Scenario: Create
  Given the things needed to make a category
  When a new category is created
  Then it has all the things used to make it

Scenario: Update
  Given a category with some property
  When the property of the category is changed
  Then fetching the category again shows the updated
property

Scenario: Delete
  Given a category
  When the category is deleted
  Then the category is not found when fetched

The second and third create the category in the given step.

Now if this is a system that isn't shutdown after a test run you may also want to use after hooks to try and delete any categories created when the test is done.


问:
Codeigniter 4 how to load a configuration file from BaseController to use it on all pages
In my BaseController I have tried to load my configuration file in various ways, but I cannot find the values

Inside the initController function I tried:

```<code>$this->myconfig = new \Config\MyConfig;
or
$myconfig = config('\Config\\MyConfig');
or
$myconfig = config('MyConfig');
or
$this->myconfig = config('MyConfig');
</code>```

None of these work

This is my MyConfig test configuration file located in the Config folder

```<code>namespace Config;

use CodeIgniter\Config\BaseConfig;

class MyConfig extends BaseConfig
{
    public $ada_default_lang = 'en';
    public $ada_site_name = 'Site name';
}
</code>```

答:
You don't need to extend your BaseController at all.

Just create your MyConfig.php files following the upgrade docs:

In CI4, the configurations are now stored in classes which extend
CodeIgniter\Config\BaseConfig.

which you do correctly:

<?php
    namespace Config;

    use CodeIgniter\Config\BaseConfig;

    class MyConfig extends BaseConfig
    {
        public $ada_default_lang = 'en';
        public $ada_site_name = 'Site name';
    }
```
<p>now to access your $ada_default_lang in any controller, you just have to call it inside a controller method with e.g.:</p>
<pre class="lang-php prettyprint-override"><code>$lang= config('MyConfig')->ada_default_lang );
die($lang); // would halt the program and output 'en'
</code>```

which corresponds to the CI3.x way of something like:    $this->config->item('ada_default_lang ');

Body:
In my BaseController I have tried to load my configuration file in various ways, but I cannot find the values

Inside the initController function I tried:

$this->myconfig = new \Config\MyConfig;
or
$myconfig = config('\Config\\MyConfig');
or
$myconfig = config('MyConfig');
or
$this->myconfig = config('MyConfig');

None of these work

This is my MyConfig test configuration file located in the Config folder

namespace Config;

use CodeIgniter\Config\BaseConfig;

class MyConfig extends BaseConfig
{
    public $ada_default_lang = 'en';
    public $ada_site_name = 'Site name';
}

Body:
You don't need to extend your BaseController at all.

Just create your MyConfig.php files following the upgrade docs:

In CI4, the configurations are now stored in classes which extend
CodeIgniter\Config\BaseConfig.

which you do correctly:

<?php
    namespace Config;

    use CodeIgniter\Config\BaseConfig;

    class MyConfig extends BaseConfig
    {
        public $ada_default_lang = 'en';
        public $ada_site_name = 'Site name';
    }

now to access your $ada_default_lang in any controller, you just have to call it inside a controller method with e.g.:

$lang= config('MyConfig')->ada_default_lang );
die($lang); // would halt the program and output 'en'

which corresponds to the CI3.x way of something like:    $this->config->item('ada_default_lang ');


问:
How to get hello world to change colors on every click?
Hey everyone I am trying to complete a project and i feel as If i am just right there any advice would help greatly. The goal is to get hello world to change to one of the six colors on a click and have the color change on each click.

});

```<code>    Button b2 = (Button) findViewById(R.id.button2);
    b2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        switch (ch)
        { case 0:
            t.setTextColor(Color.RED);
            break;
            case 1:
            t.setTextColor(Color.BLUE);
            break;
            case 2:
                t.setTextColor(Color.GREEN);
                break;
            case 3:
                t.setTextColor(Color.MAGENTA);
                break;
            case 4:
                t.setTextColor(Color.CYAN);
                break;
            case 5:
                t.setTextColor(Color.YELLOW);
                break;
        }}
</code>```

答:
Make ch int type if not already.

Add ch=(ch+1)%5; after the switch block.

Body:
Hey everyone I am trying to complete a project and i feel as If i am just right there any advice would help greatly. The goal is to get hello world to change to one of the six colors on a click and have the color change on each click.

});

    Button b2 = (Button) findViewById(R.id.button2);
    b2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        switch (ch)
        { case 0:
            t.setTextColor(Color.RED);
            break;
            case 1:
            t.setTextColor(Color.BLUE);
            break;
            case 2:
                t.setTextColor(Color.GREEN);
                break;
            case 3:
                t.setTextColor(Color.MAGENTA);
                break;
            case 4:
                t.setTextColor(Color.CYAN);
                break;
            case 5:
                t.setTextColor(Color.YELLOW);
                break;
        }}


问:
Combine enumerate + itertools.izip in Python
I would like to iterate + enumerate over two lists in Python. The following code looks ugly. Is there any better solution?

```<code>for id, elements in enumerate(itertools.izip(as, bs)):
  a = elements[0]
  b = elements[1]
  # do something with id, a and b
</code>```

Thank you.

答:
You could use itertools.count instead of enumerate:

```<code>for id_, a, b in itertools.izip(itertools.count(), as_, bs):
  # do something with id_, a and b
</code>```

Note that I've changed the variable names slightly to avoid a reserved word and the name of a builtin.

Body:
I would like to iterate + enumerate over two lists in Python. The following code looks ugly. Is there any better solution?

for id, elements in enumerate(itertools.izip(as, bs)):
  a = elements[0]
  b = elements[1]
  # do something with id, a and b

Thank you.

Body:
You could use itertools.count instead of enumerate:

for id_, a, b in itertools.izip(itertools.count(), as_, bs):
  # do something with id_, a and b

Note that I've changed the variable names slightly to avoid a reserved word and the name of a builtin.


问:
Compare hashed password with passwords from file in php
Alright so I have a script where you register an account and it adds a line with your username and password in a .txt file. The problem is it's not correctly checking the password for some reason.

Here's the contents of the .txt file:

```<code>aa;$2y$10$VPU65Et3ndqpCuxilZSLYO5Z9hA1rHy0BVCCBRANsqzGy.TKncKNG
alan;$2y$10$69osQF6KBRfYeHRdqkkzRenXpwMMR4jIK5n0xxMJRQTFsKsgR2ZN2
ala;$2y$10$/rcufuupuBVoG216aF7kfOlkvBxwHbI1kzsFg9BbQ2fbj/OyOQmeK
</code>```

And here's the code:

```<code><form action="login.php" method="post">
Username: <input type="text" name="namn"><br> Password: <input
type="text" name="pass"><br>
<input type="submit" name="login" value="Log in">
</form>
<?php
session_start();
$userN = $_POST['namn'];
$passW = password_hash($_POST['pass'], PASSWORD_DEFAULT);
$userList = file ('users.txt');

if (isset($_POST['login'])) {
    if (empty($userN) && empty($_POST['pass'])) {
        echo "Both fields are empty.";
    } else if (empty($_POST['pass'])) {
        echo "Please enter your password";
    } else if (empty($userN)) {
        echo "Please enter your username.";
    } else {
        foreach($userList as $row) {
            $parts = explode(";",$row);
                if($userN==$parts[0] && password_verify($passW, $parts[1])) {
                    $_SESSION['username'] = $_POST['namn'];
                    header("Location:index.php");
                } else {
                    echo "Wrong username/password!";
                }
           }
      }
 }
</code>```

It just says "Wrong username/password!Wrong username/password!Wrong username/password!" when I attempt to login. Hope it's nothing too glaringly obvious and a stupid question.

Please tell me if I should include anything else.

答:
```<code>password_verify($passW,trim($parts[1])))
</code>```

While I am unsure if it happened when the hash was stored or during retrieval, the password_hash had a space at the end. Trimming the hash before feeding it to password_verify fixed the issue for me.

Body:
Alright so I have a script where you register an account and it adds a line with your username and password in a .txt file. The problem is it's not correctly checking the password for some reason.

Here's the contents of the .txt file:

aa;$2y$10$VPU65Et3ndqpCuxilZSLYO5Z9hA1rHy0BVCCBRANsqzGy.TKncKNG
alan;$2y$10$69osQF6KBRfYeHRdqkkzRenXpwMMR4jIK5n0xxMJRQTFsKsgR2ZN2
ala;$2y$10$/rcufuupuBVoG216aF7kfOlkvBxwHbI1kzsFg9BbQ2fbj/OyOQmeK

And here's the code:

<form action="login.php" method="post">
Username: <input type="text" name="namn">
 Password: <input
type="text" name="pass">

<input type="submit" name="login" value="Log in">
</form>
<?php
session_start();
$userN = $_POST['namn'];
$passW = password_hash($_POST['pass'], PASSWORD_DEFAULT);
$userList = file ('users.txt');

if (isset($_POST['login'])) {
    if (empty($userN) && empty($_POST['pass'])) {
        echo "Both fields are empty.";
    } else if (empty($_POST['pass'])) {
        echo "Please enter your password";
    } else if (empty($userN)) {
        echo "Please enter your username.";
    } else {
        foreach($userList as $row) {
            $parts = explode(";",$row);
                if($userN==$parts[0] && password_verify($passW, $parts[1])) {
                    $_SESSION['username'] = $_POST['namn'];
                    header("Location:index.php");
                } else {
                    echo "Wrong username/password!";
                }
           }
      }
 }

It just says "Wrong username/password!Wrong username/password!Wrong username/password!" when I attempt to login. Hope it's nothing too glaringly obvious and a stupid question.

Please tell me if I should include anything else.

Body:
password_verify($passW,trim($parts[1])))

While I am unsure if it happened when the hash was stored or during retrieval, the password_hash had a space at the end. Trimming the hash before feeding it to password_verify fixed the issue for me.


问:
How can I add an item to a struct member that is an `Option<Vec<...>>`?
How can I add an item to a struct member that is an Option<Vec<...>>?

In other words, what do I need to to to make add_foo below work?

struct Foo {
    value: u32,
}

struct Bar {
    foos: Option<Vec<Foo>>,
}

impl Bar {
    fn add_foo(&mut self, foo: Foo) {
        if self.foos.is_none() {
            self.foos = Some(vec![]);
        }
        self.foos.unwrap().push(foo);
//      ^^^^^^^^^ move occurs because `self.foos` has type `Option<Vec<Foo>>`, which does not implement the `Copy` trait
    }
}

fn main() {
    let mut bar = Bar{foos: None};
    bar.add_foo(Foo{value:42});
}
```
<p>The error message suggests adding <code>as_ref()</code> but that doesn't help:</p>
```        self.foos.as_ref().unwrap().push(foo);
//      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable

```

I though there might be something as as_mutref() but there is no such thing. Since I already hold a mutable reference to the Bar struct, I would expect to be able to change the foos field in the Bar struct.

Apologies if my terminology is off; still getting used to the whole Rust ownership concept.

答:
Something like the following might be what you're looking for:

fn add_foo(&mut self, foo: Foo) {
  if let Some(foos) = self.foos.as_mut() {
    // foos has type: &mut Vec<Foo>
    foos.push(foo);
  } else {
    self.foos = Some(vec![foo]);
  }
}
```

In general, using an if let or match or some other destructuring syntax is considered more idiomatic than using a is_some() check followed by an unwrap(). At the very least it saves on a comparison, but more importantly is harder to make accidentally panic.

Body:
How can I add an item to a struct member that is an Option<Vec<...>>?

In other words, what do I need to to to make add_foo below work?

struct Foo {
    value: u32,
}

struct Bar {
    foos: Option<Vec<Foo>>,
}

impl Bar {
    fn add_foo(&mut self, foo: Foo) {
        if self.foos.is_none() {
            self.foos = Some(vec![]);
        }
        self.foos.unwrap().push(foo);
//      ^^^^^^^^^ move occurs because `self.foos` has type `Option<Vec<Foo>>`, which does not implement the `Copy` trait
    }
}

fn main() {
    let mut bar = Bar{foos: None};
    bar.add_foo(Foo{value:42});
}

The error message suggests adding as_ref() but that doesn't help:

        self.foos.as_ref().unwrap().push(foo);
//      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable

I though there might be something as as_mutref() but there is no such thing. Since I already hold a mutable reference to the Bar struct, I would expect to be able to change the foos field in the Bar struct.

Apologies if my terminology is off; still getting used to the whole Rust ownership concept.

Body:
Something like the following might be what you're looking for:

fn add_foo(&mut self, foo: Foo) {
  if let Some(foos) = self.foos.as_mut() {
    // foos has type: &mut Vec<Foo>
    foos.push(foo);
  } else {
    self.foos = Some(vec![foo]);
  }
}

In general, using an if let or match or some other destructuring syntax is considered more idiomatic than using a is_some() check followed by an unwrap(). At the very least it saves on a comparison, but more importantly is harder to make accidentally panic.


问:
If the mysql result value is an array and generic T is not an array, can it be removed in typescript?
```<code>type User = {
  name: string
  email: string
}
</code>```

This is my code,

```<code>import type { PoolConnection, RowDataPacket, OkPacket } from "mysql2/promise";

type dbDefaults = RowDataPacket[] | RowDataPacket[][] | OkPacket | OkPacket[];
type dbQuery<T> = T & dbDefaults;

type FlattenIfArray<T> = T extends (infer R)[] ? R : T;

function isFlattenArray<T>(rows: any[]): rows is T[] {
  return rows.length < 1;
}

// eslint-disable-next-line consistent-return
export async function queryWrapper<T>(
  { query, values }: { query: string; values?: string[] },
  conn: PoolConnection
): Promise<T | undefined> {
  try {
    await conn.beginTransaction();
    const [rows, _] = await conn.query<dbQuery<T>>(query, values || undefined);
    await conn.commit();

    if (isFlattenArray<FlattenIfArray<T>>(rows)) {
      return rows;
    }

    return rows;
  } catch (error) {
    await conn.rollback();
  } finally {
    conn.release();
  }
}

</code>```

Mysql code only returns the array

There is no problem with User[].
But When using User, I want to remove the arrangement.

So I used this code, but it didn't work. What should I do?

I added additional explanation.

const result = queryWrapper<User>(query, values, conn)

When use user, It comes out like this.

```<code>[
  {
   name: "user-name",
   email: "user@gmail.com"
  }
]
</code>```

But I want it comes out like this.

```<code>{
 name: "user-name",
 email: "user@gmail.com"
}
</code>```

答:
I'll reply by myself.

```<code>type dbDefaults =
  | RowDataPacket[]
  | RowDataPacket[][]
  | OkPacket
  | OkPacket[]
  | ResultSetHeader;

type Query = { query: string; values?: any[] };

type QueryFunction<T = any> = () => Promise<[T & dbDefaults, FieldPacket[]]>;

type AlwaysArray<T> = T extends (infer R)[] ? R[] : T[];
// eslint-disable-next-line consistent-return
export async function queryTransactionWrapper<T = any>(
  queries: QueryFunction[],
  conn: PoolConnection
): Promise<[AlwaysArray<T>, FieldPacket[]][] | undefined> {
  try {
    await conn.beginTransaction();
    // await conn.query("START TRANSACTION;");

    const executedQueries = await Promise.all(
      queries.map((query) => {
        return query();
      })
    );

    // await conn.query("COMMIT;");
    await conn.commit();
    return executedQueries;
  } catch (error) {
    logger.error(colors.blue(JSON.stringify(error)));
    await conn.rollback();
  } finally {
    conn.release();
  }
}

export function findOne({ query, values }: Query, conn: PoolConnection) {
  return function () {
    return conn.query<RowDataPacket[]>(query, values);
  };
}

export function find({ query, values }: Query, conn: PoolConnection) {
  return function () {
    return conn.query<RowDataPacket[]>(query, values);
  };
}

export function update({ query, values }: Query, conn: PoolConnection) {
  return function () {
    return conn.query<ResultSetHeader>(query, values);
  };
}

export function insert({ query, values }: Query, conn: PoolConnection) {
  return function () {
    return conn.query<OkPacket>(query, values);
  };
}

</code>```

when call findOneUser

```<code>async findByEmail(email: string): Promise<IUser | undefined> {
    const conn = await this.mysql.getConnection();
    const query = `Select * FROM ${USER_TABLE} WHERE email=?`;

    const findUserQueryFunction = findOne({ query, values: [email] }, conn);

    const executedQueries = await queryTransactionWrapper<IUser>(
      [findUserQueryFunction],
      conn
    );
    if (!executedQueries) {
      throw new Error();
    }
    const [[rows]] = executedQueries;

    return rows[0];
  }
</code>```

if <IUser[]>, findByEmail returns rows
else returns rows

Body:
type User = {
  name: string
  email: string
}

This is my code,

import type { PoolConnection, RowDataPacket, OkPacket } from "mysql2/promise";

type dbDefaults = RowDataPacket[] | RowDataPacket[][] | OkPacket | OkPacket[];
type dbQuery<T> = T & dbDefaults;

type FlattenIfArray<T> = T extends (infer R)[] ? R : T;

function isFlattenArray<T>(rows: any[]): rows is T[] {
  return rows.length < 1;
}

// eslint-disable-next-line consistent-return
export async function queryWrapper<T>(
  { query, values }: { query: string; values?: string[] },
  conn: PoolConnection
): Promise<T | undefined> {
  try {
    await conn.beginTransaction();
    const [rows, _] = await conn.query<dbQuery<T>>(query, values || undefined);
    await conn.commit();

    if (isFlattenArray<FlattenIfArray<T>>(rows)) {
      return rows;
    }

    return rows;
  } catch (error) {
    await conn.rollback();
  } finally {
    conn.release();
  }
}

Mysql code only returns the array

There is no problem with User[].
But When using User, I want to remove the arrangement.

So I used this code, but it didn't work. What should I do?

I added additional explanation.

const result = queryWrapper<User>(query, values, conn)

When use user, It comes out like this.

[
  {
   name: "user-name",
   email: "user@gmail.com"
  }
]

But I want it comes out like this.

{
 name: "user-name",
 email: "user@gmail.com"
}

Body:
I'll reply by myself.

type dbDefaults =
  | RowDataPacket[]
  | RowDataPacket[][]
  | OkPacket
  | OkPacket[]
  | ResultSetHeader;

type Query = { query: string; values?: any[] };

type QueryFunction<T = any> = () => Promise<[T & dbDefaults, FieldPacket[]]>;

type AlwaysArray<T> = T extends (infer R)[] ? R[] : T[];
// eslint-disable-next-line consistent-return
export async function queryTransactionWrapper<T = any>(
  queries: QueryFunction[],
  conn: PoolConnection
): Promise<[AlwaysArray<T>, FieldPacket[]][] | undefined> {
  try {
    await conn.beginTransaction();
    // await conn.query("START TRANSACTION;");

    const executedQueries = await Promise.all(
      queries.map((query) => {
        return query();
      })
    );

    // await conn.query("COMMIT;");
    await conn.commit();
    return executedQueries;
  } catch (error) {
    logger.error(colors.blue(JSON.stringify(error)));
    await conn.rollback();
  } finally {
    conn.release();
  }
}

export function findOne({ query, values }: Query, conn: PoolConnection) {
  return function () {
    return conn.query<RowDataPacket[]>(query, values);
  };
}

export function find({ query, values }: Query, conn: PoolConnection) {
  return function () {
    return conn.query<RowDataPacket[]>(query, values);
  };
}

export function update({ query, values }: Query, conn: PoolConnection) {
  return function () {
    return conn.query<ResultSetHeader>(query, values);
  };
}

export function insert({ query, values }: Query, conn: PoolConnection) {
  return function () {
    return conn.query<OkPacket>(query, values);
  };
}

when call findOneUser

async findByEmail(email: string): Promise<IUser | undefined> {
    const conn = await this.mysql.getConnection();
    const query = `Select * FROM ${USER_TABLE} WHERE email=?`;

    const findUserQueryFunction = findOne({ query, values: [email] }, conn);

    const executedQueries = await queryTransactionWrapper<IUser>(
      [findUserQueryFunction],
      conn
    );
    if (!executedQueries) {
      throw new Error();
    }
    const [[rows]] = executedQueries;

    return rows[0];
  }

if <IUser[]>, findByEmail returns rows
else returns rows


问:
Trying to get spaces between codons and stop the generation when reaching a certain codon for RNA to protein simulation
Here's some things I need help with.

But first of all, please let me pull up the code first.

```<code>from base_printer import *

def dna_complement(dna):
  coup = ""
  for letter in dna:
    if letter == "C":
      coup += "G"
    if letter == "G":
      coup += "C"
    if letter == "A":
      coup += "T"
    if letter == "T":
      coup += "A"
  return coup

def convert_to_rna(dna):
  coup2 = ""
  for letter in dna:
    if letter == "C":
      coup2 += "G"
    if letter == "G":
      coup2 += "C"
    if letter == "A":
      coup2 += "U"
    if letter == "T":
      coup2 += "A"
  return coup2

def translate(rna):
  amino_acid = ""
  for i in range(len(rna)-2):
    three_letter = rna[i:i+3]
    if three_letter in CODON_TABLE:
      amino_acid += CODON_TABLE[three_letter]
      i += 2
  return amino_acid

CODON_TABLE = {'UUU':'Phe','UUC':'Phe','UUA':'Leu','UUG':'Leu','CUU':'Leu','CUC':'Leu','CUA':'Leu','CUG':'Leu','AUU':'Ile','AUC':'Ile','AUA':'Ile','AUG':'Met','GUU':'Val','GUC':'Val','GUA':'Val','GUG':'Val','UCU':'Ser','UCC':'Ser','UCA':'Ser','UCG':'Ser','CCU':'Pro','CCC':'Pro','CCA':'Pro','CCG':'Pro','ACU':'Thr','ACC':'Thr','ACA':'Thr','ACG':'Thr','GCU':'Ala','GCC':'Ala','GCA':'Ala','GCG':'Ala','UAU':'Tyr','UAC':'Tyr','UAA':'STOP','UAG':'STOP','CAU':'His','CAC':'His','CAA':'Gln','CAG':'Gln','AAU':'Asn','AAC':'Asn','AAA':'Lys','AAG':'Lys','GAU':'Asp','GAC':'Asp','GAA':'Glu','GAG':'Glu','UGU':'Cys','UGC':'Cys','UGA':'STOP','UGG':'Trp','CGU':'Arg','CGC':'Arg','CGA':'Arg','CGG':'Arg','AGU':'Ser','AGC':'Ser','AGA':'Arg','AGG':'Arg','GGU':'Gly','GGC':'Gly','GGA':'Gly','GGG':'Gly'}

dna="AAGAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTCTTAGCGGGGCCACATCGGCCACCGCTGCCCTGCCCCTGGAGGGTGGCCCCACCGGCCGTTACAGCGAGCATAC"

def main():
  print("\nWelcome to the DNA program: The Code of Life.")
  print("\nSample DNA strand:\n")
  print("Regular DNA:")
  print_bases(dna)
  print("DNA after complement: ")
  dna2 = dna_complement(dna)
  print_bases(dna2)
  print("DNA after RNA convertion: ")
  rna = convert_to_rna(dna)
  print_bases(rna)
  print("The result of translation: ")
  amino_acid = translate(rna)
  print_bases(amino_acid)

main()
</code>```

I was trying to get the Codon printing out as everyone can see, the output of translation have been successfully printed out as

```<code>PHESERLEUSERLEUTYRTHRARGGLYVALSTOPASNTHRGLNARGGLYGLYGLYGLYALAPROARGGLYGLUARGGLYASPTHRARGASPTHRARGASPTHRARGGLUARGGLUASNILESERARGALAPROPROPROARGGLYVALCYSVALSTOPSERALAPROARGGLYVALTRPGLYALAARGASPTHRARGGLYGLYASPTHRARGGLYGLYGLYASPTHRPROLEUSERPROPROHISTHRPROARGGLYGLYGLYVALTRPGLYALAPROARGGLYALAGLNASNMETCYSVALSERARGALALEUSERARGVALTYRMET
</code>```

Now what I want to do is to have spaces separating each of the Codons listed in the program outputs and stop the generation once it reached UAA/UGA/UAG which is what I'm trying to figure out. But now the problem is I don't know where I should even start with which is embarrassing.

An example of output I want: Phe Ser Leu Ser Leu Tyr (Stops once reaching the UAA/UGA/UAG)

Would someone be willing to offer some tips?

Edit: Here's the information of base_print , it basically prints the output out in different colors

```<code>import colorama as cr
cr.init(autoreset=True)

def print_bases(string):
    """prints dna/rna bases with color coding for each base"""
    for char in string.upper():
        if char == "A":
            print(cr.Back.BLACK + cr.Fore.GREEN + cr.Style.BRIGHT + char, end="")
        elif char == "C":
            print(cr.Back.BLACK + cr.Fore.YELLOW + cr.Style.BRIGHT + char, end="")
        elif char == "T":
            print(cr.Back.BLACK + cr.Fore.BLUE + cr.Style.BRIGHT + char, end="")
        elif char == "G":
            print(cr.Back.BLACK + cr.Fore.MAGENTA + cr.Style.BRIGHT + char, end="")
        elif char == "U":
            print(cr.Back.BLACK + cr.Fore.WHITE + char, end="")
        else:
            print(char, end="")
    print()
</code>```

答:
Here is how I would do it

def translate(rna):
    amino_acid = []
    for i in range(len(rna) - 2):
        three_letter = rna[i:i + 3]
        if three_letter in ['UAA', 'UGA', 'UAG']:
            break
        if three_letter in CODON_TABLE:
            amino_acid.append(CODON_TABLE[three_letter])
            i += 2
    return ' '.join(amino_acid)
```

Body:
Here's some things I need help with.

But first of all, please let me pull up the code first.

from base_printer import *

def dna_complement(dna):
  coup = ""
  for letter in dna:
    if letter == "C":
      coup += "G"
    if letter == "G":
      coup += "C"
    if letter == "A":
      coup += "T"
    if letter == "T":
      coup += "A"
  return coup

def convert_to_rna(dna):
  coup2 = ""
  for letter in dna:
    if letter == "C":
      coup2 += "G"
    if letter == "G":
      coup2 += "C"
    if letter == "A":
      coup2 += "U"
    if letter == "T":
      coup2 += "A"
  return coup2

def translate(rna):
  amino_acid = ""
  for i in range(len(rna)-2):
    three_letter = rna[i:i+3]
    if three_letter in CODON_TABLE:
      amino_acid += CODON_TABLE[three_letter]
      i += 2
  return amino_acid

CODON_TABLE = {'UUU':'Phe','UUC':'Phe','UUA':'Leu','UUG':'Leu','CUU':'Leu','CUC':'Leu','CUA':'Leu','CUG':'Leu','AUU':'Ile','AUC':'Ile','AUA':'Ile','AUG':'Met','GUU':'Val','GUC':'Val','GUA':'Val','GUG':'Val','UCU':'Ser','UCC':'Ser','UCA':'Ser','UCG':'Ser','CCU':'Pro','CCC':'Pro','CCA':'Pro','CCG':'Pro','ACU':'Thr','ACC':'Thr','ACA':'Thr','ACG':'Thr','GCU':'Ala','GCC':'Ala','GCA':'Ala','GCG':'Ala','UAU':'Tyr','UAC':'Tyr','UAA':'STOP','UAG':'STOP','CAU':'His','CAC':'His','CAA':'Gln','CAG':'Gln','AAU':'Asn','AAC':'Asn','AAA':'Lys','AAG':'Lys','GAU':'Asp','GAC':'Asp','GAA':'Glu','GAG':'Glu','UGU':'Cys','UGC':'Cys','UGA':'STOP','UGG':'Trp','CGU':'Arg','CGC':'Arg','CGA':'Arg','CGG':'Arg','AGU':'Ser','AGC':'Ser','AGA':'Arg','AGG':'Arg','GGU':'Gly','GGC':'Gly','GGA':'Gly','GGG':'Gly'}

dna="AAGAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTCTTAGCGGGGCCACATCGGCCACCGCTGCCCTGCCCCTGGAGGGTGGCCCCACCGGCCGTTACAGCGAGCATAC"

def main():
  print("\nWelcome to the DNA program: The Code of Life.")
  print("\nSample DNA strand:\n")
  print("Regular DNA:")
  print_bases(dna)
  print("DNA after complement: ")
  dna2 = dna_complement(dna)
  print_bases(dna2)
  print("DNA after RNA convertion: ")
  rna = convert_to_rna(dna)
  print_bases(rna)
  print("The result of translation: ")
  amino_acid = translate(rna)
  print_bases(amino_acid)

main()

I was trying to get the Codon printing out as everyone can see, the output of translation have been successfully printed out as

PHESERLEUSERLEUTYRTHRARGGLYVALSTOPASNTHRGLNARGGLYGLYGLYGLYALAPROARGGLYGLUARGGLYASPTHRARGASPTHRARGASPTHRARGGLUARGGLUASNILESERARGALAPROPROPROARGGLYVALCYSVALSTOPSERALAPROARGGLYVALTRPGLYALAARGASPTHRARGGLYGLYASPTHRARGGLYGLYGLYASPTHRPROLEUSERPROPROHISTHRPROARGGLYGLYGLYVALTRPGLYALAPROARGGLYALAGLNASNMETCYSVALSERARGALALEUSERARGVALTYRMET

Now what I want to do is to have spaces separating each of the Codons listed in the program outputs and stop the generation once it reached UAA/UGA/UAG which is what I'm trying to figure out. But now the problem is I don't know where I should even start with which is embarrassing.

An example of output I want: Phe Ser Leu Ser Leu Tyr (Stops once reaching the UAA/UGA/UAG)

Would someone be willing to offer some tips?

Edit: Here's the information of base_print , it basically prints the output out in different colors

import colorama as cr
cr.init(autoreset=True)

def print_bases(string):
    """prints dna/rna bases with color coding for each base"""
    for char in string.upper():
        if char == "A":
            print(cr.Back.BLACK + cr.Fore.GREEN + cr.Style.BRIGHT + char, end="")
        elif char == "C":
            print(cr.Back.BLACK + cr.Fore.YELLOW + cr.Style.BRIGHT + char, end="")
        elif char == "T":
            print(cr.Back.BLACK + cr.Fore.BLUE + cr.Style.BRIGHT + char, end="")
        elif char == "G":
            print(cr.Back.BLACK + cr.Fore.MAGENTA + cr.Style.BRIGHT + char, end="")
        elif char == "U":
            print(cr.Back.BLACK + cr.Fore.WHITE + char, end="")
        else:
            print(char, end="")
    print()


问:
How can I put a String message with a line break in gherkin?

Example: Then I get the message "Registration successful

Welcome Administrator"

答:
You can use doc strings in Gherkin:

```<code>Then the message reads
"""
Hello

World
"""
</code>```

In your step definition you can use the String parameter type.

Body:
You can use doc strings in Gherkin:

Then the message reads
"""
Hello

World
"""

In your step definition you can use the String parameter type.


问:
numpy.random.normal() in multithreaded environment
I was trying to parallelize the generation of normally-distributed random arrays with the numpy.random.normal() function but it looks like the calls from the threads are executed sequentially instead.

```<code>import numpy as np

start = time.time()

active_threads = 0
for i in range(100000):
    t = threading.Thread(target=lambda x : np.random.normal(0,2,4000), args = [0])
    t.start()

    while active_threads >= 12:
        time.sleep(0.1)
        continue

end = time.time()
print(str(end-start))
</code>```

If i measure the time for a 1 thread process i get the same result as the 12 thread one.
I know this kind of parallelization suffers from a lot of overhead, but even then it should still get some time off with the multithread version.

答: np.random.normal use a seed variable internally. This variable is retrieved from default_rng() and it is certainly shared between thread so it is not safe to call it using multiple threads (due to possible race conditions). In fact, the documentation provides examples for such a case (see here and there). Alternatively, you can use multiple processes (you need to configure the seed to get different results in different processes). Another solution is to use custom random number generators (RNG) so to use a different RNG object in each thread.

Body:
I was trying to parallelize the generation of normally-distributed random arrays with the numpy.random.normal() function but it looks like the calls from the threads are executed sequentially instead.

import numpy as np

start = time.time()

active_threads = 0
for i in range(100000):
    t = threading.Thread(target=lambda x : np.random.normal(0,2,4000), args = [0])
    t.start()

    while active_threads >= 12:
        time.sleep(0.1)
        continue

end = time.time()
print(str(end-start))

If i measure the time for a 1 thread process i get the same result as the 12 thread one.
I know this kind of parallelization suffers from a lot of overhead, but even then it should still get some time off with the multithread version.


问:
writing .mat data to file in Google Drive using google colab
I'm using google colab and I want to save an array in a .mat file, I used this code

```<code>import scipy.io
x = np.array([1,2,3,4,5,6,7,8,9])
mdic = {"x": x, "label": "array_data"}
scipy.io.savemat('x.mat', mdic)
</code>```

here I could download this file on my computer, I want to know if there is any code that can save this file automatically to a folder in my google drive?

答:
At first, you need to connect to your Google Drive:

```<code>from google.colab import drive
import os
drive.mount('/content/drive')
</code>```

After this you can access contents of your Google Drive at `/content/drive/MyDrive':

```<code>! ls /content/drive/MyDrive
</code>```

Body:
I'm using google colab and I want to save an array in a .mat file, I used this code

import scipy.io
x = np.array([1,2,3,4,5,6,7,8,9])
mdic = {"x": x, "label": "array_data"}
scipy.io.savemat('x.mat', mdic)

here I could download this file on my computer, I want to know if there is any code that can save this file automatically to a folder in my google drive?

Body:
At first, you need to connect to your Google Drive:

from google.colab import drive
import os
drive.mount('/content/drive')

After this you can access contents of your Google Drive at `/content/drive/MyDrive':

! ls /content/drive/MyDrive


问:
Persistent Volume Claim Kubernetes
Kubectl version gives the following output.

```<code>Client Version: version.Info{Major:"1", Minor:"22", GitVersion:"v1.22.4", GitCommit:"b695d79d4f967c403a96986f1750a35eb75e75f1", GitTreeState:"clean", BuildDate:"2021-11-17T15:48:33Z", GoVersion:"go1.16.10", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"21", GitVersion:"v1.21.5", GitCommit:"aea7bbadd2fc0cd689de94a54e5b7b758869d691", GitTreeState:"clean", BuildDate:"2021-09-15T21:04:16Z", GoVersion:"go1.16.8", Compiler:"gc", Platform:"linux/amd64"}
</code>```

I have used kubectl to edit persistent volume from 8Gi to 30Gi as

However, when I exec the pod and run df -h I see the following:

I have deleted the pods but it again shows the same thing. if I cd into cd/dev I don't see disk and vda1 folder there as well. I think I actually want the bitnami/influxdb to be 30Gi. Please guide and let me know if more info is needed.

答:
This is a community wiki answer posted for better visibility. Feel free to expand it.

Based on the comments provided here, there could be several reasons for this behavior.

According to the documentation from the Kubernetes website, manually changing the PersistentVolume size will not change the volume size:

Warning: Directly editing the size of a PersistentVolume can prevent
an automatic resize of that volume. If you edit the capacity of a
PersistentVolume, and then edit the .spec of a matching
PersistentVolumeClaim to make the size of the PersistentVolumeClaim
match the PersistentVolume, then no storage resize happens. The
Kubernetes control plane will see that the desired state of both
resources matches, conclude that the backing volume size has been
manually increased and that no resize is necessary.

It also depends on how Kubernetes running and support for the allowVolumeExpansion feature. From DigitalOcean:

are you running one of DigitalOcean's managed clusters, or a DIY
cluster running on DigitalOcean infrastructure? In case of the latter,
which version of our CSI driver do you use? (You need v1.2.0 or later
for volume expansion to be supported.)

Title: Persistent Volume Claim Kubernetes

Body:
Kubectl version gives the following output.

Client Version: version.Info{Major:"1", Minor:"22", GitVersion:"v1.22.4", GitCommit:"b695d79d4f967c403a96986f1750a35eb75e75f1", GitTreeState:"clean", BuildDate:"2021-11-17T15:48:33Z", GoVersion:"go1.16.10", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"21", GitVersion:"v1.21.5", GitCommit:"aea7bbadd2fc0cd689de94a54e5b7b758869d691", GitTreeState:"clean", BuildDate:"2021-09-15T21:04:16Z", GoVersion:"go1.16.8", Compiler:"gc", Platform:"linux/amd64"}

I have used kubectl to edit persistent volume from 8Gi to 30Gi as

However, when I exec the pod and run df -h I see the following:

I have deleted the pods but it again shows the same thing. if I cd into cd/dev I don't see disk and vda1 folder there as well. I think I actually want the bitnami/influxdb to be 30Gi. Please guide and let me know if more info is needed.


问:
What is Mirror in Maven settings.xml file?
Correct me if I'm wrong, but a Mirror is used to redirect all traffic to a specific repository URL and block everything else (including Maven central repo).

Now what if I have a Mirror to http://a.com:8081 and a repository to http://b.com:8081. Would the second URL ever get used? I assume the answer is a No. Can you have multiple Mirrors?

答:
To answer your questions:

Correct me if I'm wrong, but a Mirror is used to redirect all traffic to a specific repository URL and block everything else (including Maven central repo).

Kind of right, but I would say all artifacts are redirected to the mirror.

The blocking doesn't happen because it's a mirror.  The filtering or re-direction happens based on what is defined in the <mirrorOf> element.
The syntax <mirrofOf>*</mirrorOf> causes ALL repositories to be directed to that mirror.  To use your words, the mirror blocks the other repository http://b.com:8081. (but I wouldn't use those words).

If, however, you defined the mirror pattern as:
<mirrofOf>*,!third-party-repo</mirrorOf>
then the mirror would handle all artifacts that were not found in the other repositories.  So in this case (in your words), the mirror would not block access to the other repositories.

Now what if I have a Mirror to http://a.com:8081 and a repository to http://b.com:8081. Would the second URL ever get used? I assume the answer is a No.

This all depends on how you've defined your mirror and repositories as explained above, it is possible for them both to be used.

Can you have multiple Mirrors?

Yes.  The maven docs explain how to do that here: https://maven.apache.org/guides/mini/guide-mirror-settings.html#advanced-mirror-specification

But I've never personally had the need to deal with multiple mirrors.  Instead, I typically have one mirror and then one or more repos.
I'll explain that next.

Example using a mirror and two repos

In this example, I have:

One public mirror of Maven central (called acme-central) for my fictitious company Acme.

One repo for my companies locally developed artifacts (called acme-repo).

One repo for a 3rd party company third-party-repo that has some artifacts I needed (called third-party-repo).

The simplified syntax for all of this is shown below.  I'm only showing the bits of the configuration that affect this example.

```<code><settings>
    <mirrors>
      <mirror>
    <mirrorOf>central,!acme-repo,!third-party-repo</mirrorOf>

    <profiles>
        <profile>
        <id>default</id>
        <repositories>
            <repository>
                <id>acme-repo</id>
                <url>https://acme.com/repository/releases</url>

            <repository>
                <id>third-party-repo</id>
                <url>https://third-party.com/repository/releases</url>

    <activeProfiles>
      <activeProfile>default</activeProfile>
</code>```

So we have a mirror (of maven central), and two other repositories.
The mirror statement says to use the mirror instead of maven central, but not for the two repos acme-repo and third-party-repo.

The profile is required (just because that is the syntax of the settings.xml file).  You can only define <repositories> within a profile.

The repositories have names, and the way artifacts are looked up is as follows (see Repository Order in Maven docs).  What follows is simplified for this answer.

settings.xml file is used

pom.xml file is used

Before downloading from a repository, mirrors configuration is applied.
The maven docs show an example with two <mirror>s.

Running the command mvn help:effective-pom -Dverbose is a good way to see which repo/mirror was used to download an artifact because the syntax is:

```<code>Downloading from third-party-repo: https://third-party.com/...
Downloading from acme-repo: https://third-party.com/...

</code>```

Body:
To answer your questions:

Correct me if I'm wrong, but a Mirror is used to redirect all traffic to a specific repository URL and block everything else (including Maven central repo).

Kind of right, but I would say all artifacts are redirected to the mirror.

The blocking doesn't happen because it's a mirror.  The filtering or re-direction happens based on what is defined in the <mirrorOf> element.
The syntax <mirrofOf>*</mirrorOf> causes ALL repositories to be directed to that mirror.  To use your words, the mirror blocks the other repository http://b.com:8081. (but I wouldn't use those words).

If, however, you defined the mirror pattern as:
<mirrofOf>*,!third-party-repo</mirrorOf>
then the mirror would handle all artifacts that were not found in the other repositories.  So in this case (in your words), the mirror would not block access to the other repositories.

Now what if I have a Mirror to http://a.com:8081 and a repository to http://b.com:8081. Would the second URL ever get used? I assume the answer is a No.

This all depends on how you've defined your mirror and repositories as explained above, it is possible for them both to be used.

Can you have multiple Mirrors?

Yes.  The maven docs explain how to do that here: https://maven.apache.org/guides/mini/guide-mirror-settings.html#advanced-mirror-specification

But I've never personally had the need to deal with multiple mirrors.  Instead, I typically have one mirror and then one or more repos.
I'll explain that next.

Example using a mirror and two repos

In this example, I have:

One public mirror of Maven central (called acme-central) for my fictitious company Acme.

One repo for my companies locally developed artifacts (called acme-repo).

One repo for a 3rd party company third-party-repo that has some artifacts I needed (called third-party-repo).

The simplified syntax for all of this is shown below.  I'm only showing the bits of the configuration that affect this example.

<settings>
    <mirrors>
      <mirror>
    <mirrorOf>central,!acme-repo,!third-party-repo</mirrorOf>

    <profiles>
        <profile>
        <id>default</id>
        <repositories>
            <repository>
                <id>acme-repo</id>
                <url>https://acme.com/repository/releases</url>

            <repository>
                <id>third-party-repo</id>
                <url>https://third-party.com/repository/releases</url>

    <activeProfiles>
      <activeProfile>default</activeProfile>

So we have a mirror (of maven central), and two other repositories.
The mirror statement says to use the mirror instead of maven central, but not for the two repos acme-repo and third-party-repo.

The profile is required (just because that is the syntax of the settings.xml file).  You can only define <repositories> within a profile.

The repositories have names, and the way artifacts are looked up is as follows (see Repository Order in Maven docs).  What follows is simplified for this answer.

settings.xml file is used

pom.xml file is used

Before downloading from a repository, mirrors configuration is applied.
The maven docs show an example with two <mirror>s.

Running the command mvn help:effective-pom -Dverbose is a good way to see which repo/mirror was used to download an artifact because the syntax is:

Downloading from third-party-repo: https://third-party.com/...
Downloading from acme-repo: https://third-party.com/...


问:
Invalid frame dimension (negative or non-finite)
I'm new to this platform but swift is giving me a headache it is seeming to have a problem with the value (Infinity) although what should I put instead?</p>
```<code> .bold()
 .frame(width: .infinity, height: 20, alignment: .topLeading)
 Text(course.type)
 .font(.system(size: 15, weight: .light))
 .frame(width: .infinity, height: 10, alignment: .topLeading )
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
                Button {
                    openURL(URL(string: course.link)!)
                       }
            label: {
                Text("GET").bold()
                    .frame(width: 35, height: 1)

                    .padding()
                    .foregroundColor(Color(.white))
                    .background(Color(.orange))

                    .cornerRadius(25)
}
}.frame(width: .infinity, height: .infinity)
.padding()
</code>```

答:
An infinite width or height doesn't make sense. If instead you want the view to expand as much as possible, use the maxWidth and maxHeight variants instead:

```<code>.frame(maxWidth: .infinity, maxHeight: .infinity)
</code>```

Body:
I'm new to this platform but swift is giving me a headache it is seeming to have a problem with the value (Infinity) although what should I put instead?

 .bold()
 .frame(width: .infinity, height: 20, alignment: .topLeading)
 Text(course.type)
 .font(.system(size: 15, weight: .light))
 .frame(width: .infinity, height: 10, alignment: .topLeading )
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
                Button {
                    openURL(URL(string: course.link)!)
                       }
            label: {
                Text("GET").bold()
                    .frame(width: 35, height: 1)

                    .padding()
                    .foregroundColor(Color(.white))
                    .background(Color(.orange))

                    .cornerRadius(25)
}
}.frame(width: .infinity, height: .infinity)
.padding()

Body:
An infinite width or height doesn't make sense. If instead you want the view to expand as much as possible, use the maxWidth and maxHeight variants instead:

.frame(maxWidth: .infinity, maxHeight: .infinity)


问:
Invalid behavior for arguments in Bash version 4.4 vs version 5.1?
I am confused with this behavior, I have the following script:

backup.sh

```<code>#!/bin/bash -x

set -e

if [[ $# -eq 0 ]] ; then
    echo 'No arguments passed'
    exit 1
fi

# Get the arguments
for ARGUMENT in "$@"; do
  KEY=$(echo $ARGUMENT | cut -f1 -d=)
  VALUE=$(echo $ARGUMENT | cut -f2 -d=)

  case "$KEY" in
  backup_dir) BACKUP_DIR=${VALUE} ;;
  postgres_dbs) POSTGRES_DBS=${VALUE} ;;
  backup_name) BACKUP_NAME=${VALUE} ;;
  postgres_port) POSTGRES_PORT=${VALUE} ;;
  postgres_host) POSTGRES_HOST=${VALUE} ;;
  *) ;;
  esac
done
</code>```

And I am executing it using:

1.

```<code>/bin/bash -c /usr/bin/backup.sh postgres_dbs=grafana,keycloak backup_name=postgres-component-test-20220210.165630 backup_dir=/backups/postgres postgres_port=5432 postgres_host=postgres.default.svc.cluster.local
</code>```

```<code>/usr/bin/backup.sh postgres_dbs=grafana,keycloak backup_name=postgres-component-test-20220210.165630 backup_dir=/backups/postgres postgres_port=5432 postgres_host=postgres.default.svc.cluster.local
</code>```

But the output is:

```<code>+ set -e
+ [[ 0 -eq 0 ]]
+ echo 'No arguments passed'
No arguments passed
+ exit 1
</code>```

Environment:

```<code># cat /etc/os-release
NAME="Ubuntu"
VERSION="18.04.3 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.3 LTS"
VERSION_ID="18.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=bionic
UBUNTU_CODENAME=bionic
</code>```

Bash version where I can reproduce this issue:

```<code>GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu)
</code>```

However, this is not happening in the Bash version:

```<code>GNU bash, version 5.1.8(1)-release (x86_64-apple-darwin20.3.0)
</code>```

答:
You wrote two ways to invoke the script, which boil down to:

bash -c ./script.sh arg1 arg2 arg3

./script.sh arg1 arg2 arg3

The second way is the preferred way to invoke scripts. Running them directly tells Linux to use the interpreter listed in the shebang line. There's no reason I can see for this invocation style to drop arguments.

The first, however, does indeed lose all the arguments. It's because -c doesn't belong there. If you want to invoke an explicit bash shell you should write simply:

```<code>bash ./script.sh arg1 arg2 arg3
</code>```

That will correctly pass all the arguments to the script.

When you add -c it turns ./script.sh from the name of a script into a full blown command line. What's the difference? Well, now that command line is responsible for forwarding its arguments to the script, if that's what it wants to have happen. With -c you need to explicitly pass them on:

```<code>bash -c './script.sh "$@"' bash arg1 arg2 arg3
</code>```

Yuck! It's encased in single quotes, and there's an ugly "$@" in there. It's needed, though. Without "$@" the arguments are simply dropped on the floor.

-c also takes an extra argument, the value for $0. So not only is "$@" needed, you also have to add an extra bash argument to set $0. (bash is a good choice since that's what $0 is normally set to when running a bash script.)

Body:
I am confused with this behavior, I have the following script:

backup.sh

#!/bin/bash -x

set -e

if [[ $# -eq 0 ]] ; then
    echo 'No arguments passed'
    exit 1
fi

# Get the arguments
for ARGUMENT in "$@"; do
  KEY=$(echo $ARGUMENT | cut -f1 -d=)
  VALUE=$(echo $ARGUMENT | cut -f2 -d=)

  case "$KEY" in
  backup_dir) BACKUP_DIR=${VALUE} ;;
  postgres_dbs) POSTGRES_DBS=${VALUE} ;;
  backup_name) BACKUP_NAME=${VALUE} ;;
  postgres_port) POSTGRES_PORT=${VALUE} ;;
  postgres_host) POSTGRES_HOST=${VALUE} ;;
  *) ;;
  esac
done

And I am executing it using:

1.

/bin/bash -c /usr/bin/backup.sh postgres_dbs=grafana,keycloak backup_name=postgres-component-test-20220210.165630 backup_dir=/backups/postgres postgres_port=5432 postgres_host=postgres.default.svc.cluster.local

/usr/bin/backup.sh postgres_dbs=grafana,keycloak backup_name=postgres-component-test-20220210.165630 backup_dir=/backups/postgres postgres_port=5432 postgres_host=postgres.default.svc.cluster.local

But the output is:

+ set -e
+ [[ 0 -eq 0 ]]
+ echo 'No arguments passed'
No arguments passed
+ exit 1

Environment:

# cat /etc/os-release
NAME="Ubuntu"
VERSION="18.04.3 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.3 LTS"
VERSION_ID="18.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=bionic
UBUNTU_CODENAME=bionic

Bash version where I can reproduce this issue:

GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu)

However, this is not happening in the Bash version:

GNU bash, version 5.1.8(1)-release (x86_64-apple-darwin20.3.0)

Body:
You wrote two ways to invoke the script, which boil down to:

bash -c ./script.sh arg1 arg2 arg3

./script.sh arg1 arg2 arg3

The second way is the preferred way to invoke scripts. Running them directly tells Linux to use the interpreter listed in the shebang line. There's no reason I can see for this invocation style to drop arguments.

The first, however, does indeed lose all the arguments. It's because -c doesn't belong there. If you want to invoke an explicit bash shell you should write simply:

bash ./script.sh arg1 arg2 arg3

That will correctly pass all the arguments to the script.

When you add -c it turns ./script.sh from the name of a script into a full blown command line. What's the difference? Well, now that command line is responsible for forwarding its arguments to the script, if that's what it wants to have happen. With -c you need to explicitly pass them on:

bash -c './script.sh "$@"' bash arg1 arg2 arg3

Yuck! It's encased in single quotes, and there's an ugly "$@" in there. It's needed, though. Without "$@" the arguments are simply dropped on the floor.

-c also takes an extra argument, the value for $0. So not only is "$@" needed, you also have to add an extra bash argument to set $0. (bash is a good choice since that's what $0 is normally set to when running a bash script.)


问:
Remove underscores from a response
Here's the controller:

```<code>@Controller('products')
@UsePipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }))
export class ProductController {
    constructor(
        private readonly productService: ProductService,
    ) {}

    @Get()
    public async all(): Promise<ProductDto[]> {
        return this.productService.all();
    }

    @Post()
    @ApiResponse({type: ProductDto})
    public async create(@Body() createProductDto: CreateProductDto): Promise<ProductDto> {
        return this.productService.create(createProductDto);
    }
}
</code>```

Here's the service:

```<code>@Injectable()
export class ProductService {
    constructor(
        @InjectRepository(ProductEntity)
        private readonly productRepository: Repository<ProductEntity>,
    ) {}

    public async all(): Promise<ProductDto[]> {
        return this.productRepository.find().then(products => products.map(p => new ProductDto().deserialize(p)));
    }

    public async create(createProductDto: CreateProductDto): Promise<ProductDto> {
        const productEntity = new ProductEntity();
        productEntity.image = createProductDto.image;
        productEntity.title = createProductDto.title;
        return productEntity.save().then(pe => new ProductDto().deserialize(pe));
    }
}

</code>```

And here is the ProductDto:

```<code>export class ProductDto implements Readonly<ProductDto>, IDeserializable<ProductDto, ProductEntity> {
    @ApiProperty({name: 'id'})
    @IsNumber()
    private _id: number;

    @ApiProperty({name: 'likes'})
    @IsNumber()
    private _likes: number;

    @ApiProperty({name: 'title'})
    @IsString()
    private _title: string;

    @ApiProperty({name: 'image'})
    @IsString()
    private _image: string;

    public set id(val: number) {
        this._id = val;
    }

    public get id(): number {
        return this._id;
    }

    public set title(val: string) {
        this._title = val;
    }

    public get title(): string {
        return this._title;
    }

    public set image(val: string) {
        this._image = val;
    }

    public get image(): string {
        return this._image;
    }

    public set likes(val: number) {
        this._likes = val;
    }

    public get likes(): number {
        return this._likes;
    }

    public deserialize(data: ProductEntity): ProductDto {
        this.image = data.image;
        this.title = data.title;
        this.likes = data.likes;
        this.id = data.id;

        return this;
    }
}
</code>```

The response contains underscores, I forgot how to remove them.

When I create a new product I get this:

```<code>{
    "_image": "https://www.images.com/763267382.jpg",
    "_title": "porsche",
    "_likes": 0,
    "_id": 26
}
</code>```

but I want this:

```<code>{
    "image": "https://www.images.com/763267382.jpg",
    "title": "porsche",
    "likes": 0,
    "id": 26
}
</code>```

How do I do that?

EDIT:

I could write a custom pipe that would trim them, but unless I'm very much mistaken there's a built-in trim or something, I don't remember.

答:
You can enable ClassSerializerInterceptor by adding @UseInterceptors(ClassSerializerInterceptor) to controller, and then use @Expose decorator from class-transformer package to change the name during serialization.

Here is what it looks like:

@Controller('products')
@UseInterceptors(ClassSerializerInterceptor)
@UsePipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }))
export class ProductController {
...
}
```
<p>And <code>ProductDto</code>:</p>
<pre class="lang-js prettyprint-override"><code>import { Expose } from 'class-transformer';

export class ProductDto implements Readonly<ProductDto>, IDeserializable<ProductDto, ProductEntity> {
    @Expose({ name: 'id' })
    @ApiProperty({name: 'id'})
    @IsNumber()
    private _id: number;

    @Expose({ name: 'likes' })
    @ApiProperty({name: 'likes'})
    @IsNumber()
    private _likes: number;

    @Expose({ name: 'title' })
    @ApiProperty({name: 'title'})
    @IsString()
    private _title: string;

    @Expose({ name: 'image' })
    @ApiProperty({name: 'image'})
    @IsString()
    private _image: string;

    ...
</code>```

You can find more information here.

Title: Remove underscores from a response

Body:
Here's the controller:

@Controller('products')
@UsePipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }))
export class ProductController {
    constructor(
        private readonly productService: ProductService,
    ) {}

    @Get()
    public async all(): Promise<ProductDto[]> {
        return this.productService.all();
    }

    @Post()
    @ApiResponse({type: ProductDto})
    public async create(@Body() createProductDto: CreateProductDto): Promise<ProductDto> {
        return this.productService.create(createProductDto);
    }
}

Here's the service:

@Injectable()
export class ProductService {
    constructor(
        @InjectRepository(ProductEntity)
        private readonly productRepository: Repository<ProductEntity>,
    ) {}

    public async all(): Promise<ProductDto[]> {
        return this.productRepository.find().then(products => products.map(p => new ProductDto().deserialize(p)));
    }

    public async create(createProductDto: CreateProductDto): Promise<ProductDto> {
        const productEntity = new ProductEntity();
        productEntity.image = createProductDto.image;
        productEntity.title = createProductDto.title;
        return productEntity.save().then(pe => new ProductDto().deserialize(pe));
    }
}

And here is the ProductDto:

export class ProductDto implements Readonly<ProductDto>, IDeserializable<ProductDto, ProductEntity> {
    @ApiProperty({name: 'id'})
    @IsNumber()
    private _id: number;

    @ApiProperty({name: 'likes'})
    @IsNumber()
    private _likes: number;

    @ApiProperty({name: 'title'})
    @IsString()
    private _title: string;

    @ApiProperty({name: 'image'})
    @IsString()
    private _image: string;

    public set id(val: number) {
        this._id = val;
    }

    public get id(): number {
        return this._id;
    }

    public set title(val: string) {
        this._title = val;
    }

    public get title(): string {
        return this._title;
    }

    public set image(val: string) {
        this._image = val;
    }

    public get image(): string {
        return this._image;
    }

    public set likes(val: number) {
        this._likes = val;
    }

    public get likes(): number {
        return this._likes;
    }

    public deserialize(data: ProductEntity): ProductDto {
        this.image = data.image;
        this.title = data.title;
        this.likes = data.likes;
        this.id = data.id;

        return this;
    }
}

The response contains underscores, I forgot how to remove them.

When I create a new product I get this:

{
    "_image": "https://www.images.com/763267382.jpg",
    "_title": "porsche",
    "_likes": 0,
    "_id": 26
}

but I want this:

{
    "image": "https://www.images.com/763267382.jpg",
    "title": "porsche",
    "likes": 0,
    "id": 26
}

How do I do that?

EDIT:

I could write a custom pipe that would trim them, but unless I'm very much mistaken there's a built-in trim or something, I don't remember.

Body:
You can enable ClassSerializerInterceptor by adding @UseInterceptors(ClassSerializerInterceptor) to controller, and then use @Expose decorator from class-transformer package to change the name during serialization.

Here is what it looks like:

@Controller('products')
@UseInterceptors(ClassSerializerInterceptor)
@UsePipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }))
export class ProductController {
...
}

And ProductDto:

import { Expose } from 'class-transformer';

export class ProductDto implements Readonly<ProductDto>, IDeserializable<ProductDto, ProductEntity> {
    @Expose({ name: 'id' })
    @ApiProperty({name: 'id'})
    @IsNumber()
    private _id: number;

    @Expose({ name: 'likes' })
    @ApiProperty({name: 'likes'})
    @IsNumber()
    private _likes: number;

    @Expose({ name: 'title' })
    @ApiProperty({name: 'title'})
    @IsString()
    private _title: string;

    @Expose({ name: 'image' })
    @ApiProperty({name: 'image'})
    @IsString()
    private _image: string;

    ...

You can find more information here.