问:
Automatically categorize and add annotations using pheatmap in R
I have a dataframe made by the school grades of some students in different subjects. The students are also characterized by their gender (F or M), that is included as a suffix in their names (e.g. Anne_F, Albert_M, etc...)
With these data I have created an heatmap with the package pheatmap(), in this way:

```<code>library(pheatmap)

  Anne_F <- c(9,7,6,10,6)
  Carl_M <- c(6,7,9,5,7)
  Albert_M <- c(8,8,8,7,9)
  Kate_F <- c(10,5,10,9,5)
  Emma_F <- c(6,8,10,8,7)

  matrix <- cbind(Anne_F, Carl_M, Albert_M, Kate_F, Emma_F)
  rownames(matrix) <- c("Math", "Literature", "Arts", "Science", "Music")

  print(matrix)

  heatmap <- pheatmap(
     mat = matrix,
     cluster_rows = F,
     cluster_cols = F,
     cellwidth = 30,
     cellheight = 30,
  )

heatmap

</code>```

Which gives this matrix

and the relative plot:

Now I would like to automatically recognize if a student is Male or Female and add this as a column annotation in the heatmap, in order to have a graph like this:

I have thought to create two vectors, one with the name of the students:
name <- c("Anne", "Carl", "Albert", "Kate", "Emma") and one with the respective genders:  gender <- c("F", "M", "M", "F", "F") , but I can't figure out how to associate names with genders, and to show them on the heatmap.

I don't mean to manually associate one-name to one-gender (as Anne to F, Albert to M, etc,). I need to take the entire vector of names and associate it with the corresponding vector of genders (and then annotate them on the heatmap), because their number will increase in the future.

Many thanks in advance for your help.

答:
With the given data, you could achieve your desired output like this:

  Gender <- sapply(colnames(matrix), function(x) strsplit(x, "_")[[1]][2])
  df     <- as.data.frame(Gender)

  pheatmap(
     mat = matrix,
     cluster_rows = F,
     cluster_cols = F,
     cellwidth = 30,
     cellheight = 30,
     annotation_col = df,
     annotation_colors = list(Gender = c(M = "#6ef88a", F = "#d357fe"))
  )
```

Body:
I have a dataframe made by the school grades of some students in different subjects. The students are also characterized by their gender (F or M), that is included as a suffix in their names (e.g. Anne_F, Albert_M, etc...)
With these data I have created an heatmap with the package pheatmap(), in this way:

library(pheatmap)

  Anne_F <- c(9,7,6,10,6)
  Carl_M <- c(6,7,9,5,7)
  Albert_M <- c(8,8,8,7,9)
  Kate_F <- c(10,5,10,9,5)
  Emma_F <- c(6,8,10,8,7)

  matrix <- cbind(Anne_F, Carl_M, Albert_M, Kate_F, Emma_F)
  rownames(matrix) <- c("Math", "Literature", "Arts", "Science", "Music")

  print(matrix)

  heatmap <- pheatmap(
     mat = matrix,
     cluster_rows = F,
     cluster_cols = F,
     cellwidth = 30,
     cellheight = 30,
  )

heatmap

Which gives this matrix

and the relative plot:

Now I would like to automatically recognize if a student is Male or Female and add this as a column annotation in the heatmap, in order to have a graph like this:

I have thought to create two vectors, one with the name of the students:
name <- c("Anne", "Carl", "Albert", "Kate", "Emma") and one with the respective genders:  gender <- c("F", "M", "M", "F", "F") , but I can't figure out how to associate names with genders, and to show them on the heatmap.

I don't mean to manually associate one-name to one-gender (as Anne to F, Albert to M, etc,). I need to take the entire vector of names and associate it with the corresponding vector of genders (and then annotate them on the heatmap), because their number will increase in the future.

Many thanks in advance for your help.


来源: stackexchange

问:
Android - multiple EditText fields in window resize
In one of my views, I have three EditText fields. The first two are single-line, and the third is multi-line. I'm using android:windowSoftInputMode="stateVisible|adjustResize". however the third field collapses far too small in portrait mode when the IME comes up and it has focus.

Is there an option to set a minimum height that would force the window to scroll down to accommodate the third field?

I have tried setting android:minHeight="20dip" in the xml file, but this has no effect.

The EditText in question looks like:

```<code><EditText
        android:id="@+id/msgreplyarea"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:gravity="top"
        android:layout_weight="1"
        android:layout_marginLeft="10dip" android:layout_marginRight="10dip"
        android:layout_marginTop="10px"
        android:inputType="textCapSentences|textMultiLine"
        android:imeOptions="flagNoEnterAction">
</code>```

Thanks.

答:
android:minHeight does work, but the parent view needs to be wrapped in a ScollView</p>

```<code><ScrollView
  android:layout_width="fill_parent"
  android:layout_height="0dip"
  android:layout_weight="1"
  android:scrollbarStyle="outsideInset"
  android:fillViewport="true">
    <LinearLayout
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical" >
        <EditText
          android:id="@+id/replyarea"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content" android:gravity="top"
          android:singleLine="false" android:layout_weight="1"
          android:layout_marginLeft="10dip" android:layout_marginRight="10dip"
          android:layout_marginTop="10px"
          android:minHeight="120dp"
          android:inputType="textAutoCorrect|textCapSentences|textMultiLine"
          android:imeOptions="flagNoEnterAction" />
    </LinearLayout>
</ScrollView>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In one of my views, I have three EditText fields. The first two are single-line, and the third is multi-line. I'm using android:windowSoftInputMode="stateVisible|adjustResize". however the third field collapses far too small in portrait mode when the IME comes up and it has focus.

Is there an option to set a minimum height that would force the window to scroll down to accommodate the third field?

I have tried setting android:minHeight="20dip" in the xml file, but this has no effect.

The EditText in question looks like:

<EditText
        android:id="@+id/msgreplyarea"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:gravity="top"
        android:layout_weight="1"
        android:layout_marginLeft="10dip" android:layout_marginRight="10dip"
        android:layout_marginTop="10px"
        android:inputType="textCapSentences|textMultiLine"
        android:imeOptions="flagNoEnterAction">

Thanks.

Body:
android:minHeight does work, but the parent view needs to be wrapped in a ScollView

<ScrollView
  android:layout_width="fill_parent"
  android:layout_height="0dip"
  android:layout_weight="1"
  android:scrollbarStyle="outsideInset"
  android:fillViewport="true">
    <LinearLayout
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical" >
        <EditText
          android:id="@+id/replyarea"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content" android:gravity="top"
          android:singleLine="false" android:layout_weight="1"
          android:layout_marginLeft="10dip" android:layout_marginRight="10dip"
          android:layout_marginTop="10px"
          android:minHeight="120dp"
          android:inputType="textAutoCorrect|textCapSentences|textMultiLine"
          android:imeOptions="flagNoEnterAction" />
    </LinearLayout>
</ScrollView>


问:
How to remove all grid lines except left Y axis and bottom X axis using Charts ios?
In my app I'm using the iOS-Charts framework, and I figured out how to remove the grid (vertical and horizontal) by using:

```<code>barChartView.leftAxis.drawGridLinesEnabled = false
barChartView.rightAxis.drawGridLinesEnabled = false
</code>```

However, I still want to have left side Y axis and bottom X axis.

Any kind of help is highly appreciated.

答:
Tried every solution available for none worked for me. Seems like from Swift 4 you can not disable grid lines totally. One solution you have though is making the grid lines clear color so that they are not visible.</p>
```<code>chartView.xAxis.gridColor = .clear
chartView.leftAxis.gridColor = .clear
chartView.rightAxis.gridColor = .clear
</code>```

Body:
In my app I'm using the iOS-Charts framework, and I figured out how to remove the grid (vertical and horizontal) by using:

barChartView.leftAxis.drawGridLinesEnabled = false
barChartView.rightAxis.drawGridLinesEnabled = false

However, I still want to have left side Y axis and bottom X axis.

Any kind of help is highly appreciated.

Body:
Tried every solution available for none worked for me. Seems like from Swift 4 you can not disable grid lines totally. One solution you have though is making the grid lines clear color so that they are not visible.

chartView.xAxis.gridColor = .clear
chartView.leftAxis.gridColor = .clear
chartView.rightAxis.gridColor = .clear

ContentLicense: CC BY-SA 4.0


问:
How to act on an error code and collect stdout at the same time?
I have this python3 program.  It sets error code 0 when it works and non-zero when it fails.  It puts the good message into stdout and the failure string into stderr.  I think it's well-behaved.

#! /bin/python3

import sys

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

cs = sys.argv[1]

if str(cs) == "1":
    print("GOOD")
else:
    eprint("BAD")
    sys.exit(1)
```
<p>See how I test it:</p>
```$ X=`python3 example.py 1`; echo It is: $X
It is: GOOD
$ X=`python3 example.py 0`; echo It is: $X
BAD
It is:
```
<p>I have this bash program that calls the python program:</p>
```#! /bin/bash

function do_example() {
    local DB=$1
    local URI=`python3 example.py $DB`
    RESULT=$?
    if [ $RESULT -eq 0 ]; then
        echo $URI
        echo success
    else
        echo $URI
        echo failed
    fi
}

do_example 1
do_example 0
```
<p>It runs a python program first. Captures the stdout. Then it checks the return value.  It doesn't work.  It should say success and then failed.  Instead, it says success both times. It doesn't work.  It doesn't handle the error code correctly.</p>
```$ ./example.sh
success
BAD
success
$ ./example.sh
GOOD
success
BAD
```

The generalized question is how to collect the stdout into a local variable and act on the error code at the same time?

答:
local's exit code overrides the one from the command substitution. To work around this, always split apart local declarations from assignments if the assignments could fail:

```<code>local URI
URI=`python3 example.py $DB`
RESULT=$?
</code>```

By the way,  you don't need to save the exit code in a variable if you check it in the if statement. Also, it's best to avoid uppercase variable names as they could clash with built-in names. Finally, I recommend using $(...) in place of backticks; it is easier to nest substitutions.

```<code>local db=$1

local uri
if uri=$(python3 example.py "$db"); then
    echo "$uri"
    echo success
else
    echo failed
fu
</code>```

Body:
I have this python3 program.  It sets error code 0 when it works and non-zero when it fails.  It puts the good message into stdout and the failure string into stderr.  I think it's well-behaved.

#! /bin/python3

import sys

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

cs = sys.argv[1]

if str(cs) == "1":
    print("GOOD")
else:
    eprint("BAD")
    sys.exit(1)

See how I test it:

$ X=`python3 example.py 1`; echo It is: $X
It is: GOOD
$ X=`python3 example.py 0`; echo It is: $X
BAD
It is:

I have this bash program that calls the python program:

#! /bin/bash

function do_example() {
    local DB=$1
    local URI=`python3 example.py $DB`
    RESULT=$?
    if [ $RESULT -eq 0 ]; then
        echo $URI
        echo success
    else
        echo $URI
        echo failed
    fi
}

do_example 1
do_example 0

It runs a python program first. Captures the stdout. Then it checks the return value.  It doesn't work.  It should say success and then failed.  Instead, it says success both times. It doesn't work.  It doesn't handle the error code correctly.

$ ./example.sh
success
BAD
success
$ ./example.sh
GOOD
success
BAD

The generalized question is how to collect the stdout into a local variable and act on the error code at the same time?

Body:
local's exit code overrides the one from the command substitution. To work around this, always split apart local declarations from assignments if the assignments could fail:

local URI
URI=`python3 example.py $DB`
RESULT=$?

By the way,  you don't need to save the exit code in a variable if you check it in the if statement. Also, it's best to avoid uppercase variable names as they could clash with built-in names. Finally, I recommend using $(...) in place of backticks; it is easier to nest substitutions.

local db=$1

local uri
if uri=$(python3 example.py "$db"); then
    echo "$uri"
    echo success
else
    echo failed
fu


问:
Make modal without Javascript
How to make modal without javascript code with just html and css?

I have a project that I can't use javascript and I need modal.

```<code><!DOCTYPE html>
<html>
<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>

<div class="w3-container">
  <h2>W3.CSS Modal</h2>
  <button onclick="document.getElementById('id01').style.display='block'" class="w3-button w3-black">Open Modal</button>

  <div id="id01" class="w3-modal">
    <div class="w3-modal-content">
      <div class="w3-container">
        <span onclick="document.getElementById('id01').style.display='none'" class="w3-button w3-display-topright">×</span>
        <p>Some text. Some text. Some text.</p>
        <p>Some text. Some text. Some text.</p>
      </div>
    </div>
  </div>
</div>

</body>
</html>
</code>```

答:
Here is another simple solution using CSS :target and anchor links.

dialog { display: block; }

dialog:not(:target):not([open]) { display: none; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
  <body>
      <p>
        Open dialog
      </p>

      <dialog id="dialog">
        <h2>Dialog</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
        Close
      </dialog>
  </body>
</html></code>```

Title: Make modal without Javascript

Body:
How to make modal without javascript code with just html and css?

I have a project that I can't use javascript and I need modal.

<!DOCTYPE html>

<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

W3.CSS Modal

  <button onclick="document.getElementById('id01').style.display='block'" class="w3-button w3-black">Open Modal</button>

        ×

Some text. Some text. Some text.

Some text. Some text. Some text.

Body:
Here is another simple solution using CSS :target and anchor links.

dialog { display: block; }

dialog:not(:target):not([open]) { display: none; }

<html>
  <body>
      <p>
        <a href="#dialog">Open dialog</a>
      </p>

      <dialog id="dialog">
        <h2>Dialog</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
        <a href="#!">Close</a>
      </dialog>
  </body>
</html>


答:
You need to use annotation_col option in pheatmap.

```<code>library(pheatmap)

# split matrix into "Name" and "Gender"
name_gender_matrix <- str_split_fixed(colnames(matrix), "_", 2)

# Data that maps to the heatmap should be set at the rownames
annot_col <- data.frame(row.names = name_gender_matrix[, 1], Gender = name_gender_matrix[, 2])

# Align the column name of your matrix and with the annotation
colnames(matrix) <- rownames(annot_col)

heatmap <- pheatmap(
  mat = matrix,
  cluster_rows = F,
  cluster_cols = F,
  cellwidth = 30,
  cellheight = 30,
  annotation_col = annot_col
)
</code>```

Title: Automatically categorize and add annotations using pheatmap in R

Body:
You need to use annotation_col option in pheatmap.

library(pheatmap)

# split matrix into "Name" and "Gender"
name_gender_matrix <- str_split_fixed(colnames(matrix), "_", 2)

# Data that maps to the heatmap should be set at the rownames
annot_col <- data.frame(row.names = name_gender_matrix[, 1], Gender = name_gender_matrix[, 2])

# Align the column name of your matrix and with the annotation
colnames(matrix) <- rownames(annot_col)

heatmap <- pheatmap(
  mat = matrix,
  cluster_rows = F,
  cluster_cols = F,
  cellwidth = 30,
  cellheight = 30,
  annotation_col = annot_col
)


问:
Getting image URL embedded in
```

I guess this tag is somehow responsible to insert the image in the rendered webpage... but how?

Is it possible to use requests alone to parse this web and obtain this filename?

NOTE: I'm aware that this can be accomplished using selenium. I'm specifically looking for a selenium-free solution.

答:
This is a solution with requests and regex to find the data that you are looking for.</p>
```<code>import requests
import re

weburl = (
    "https://smn.conagua.gob.mx/tools/GUI/visor_radares_v2/radares/cabos/cabos_ppi.php"
)
headers = {
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36"
    "(KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"
}
response = requests.get(weburl, verify=False, headers=headers)

source = response.content.decode("utf-8")

imagen_eco = re.search("imagen_eco((.*?));", source)
if not imagen_eco:
    exit("Not found")

image_name = re.search(r"([\w-]+)\.png", imagen_eco.group(0))
if not image_name:
    exit("Not found")
print(image_name.group(0))
print(
    f"https://smn.conagua.gob.mx/tools/GUI/visor_radares_v2/ecos/cabos/ppi/{image_name.group(0)}"
)
</code>```

Title: Getting image URL embedded in <script> tag with Python requests

Body:
I'm trying to use Python requests to get the url of an image in this web. Especifically, I'd like to get the URL to the image that starts with PPI_Z_005...

Now, to get this, I try to get the html with Python requests.

weburl="https://smn.conagua.gob.mx/tools/GUI/visor_radares_v2/radares/cabos/cabos_ppi.php"
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36'
           '(KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'}
response = requests.get(weburl, verify=False, headers=headers)

The problem is that the response has no explicit reference to the file name I'm looking for. I guess the problem is that it is somehow rendered by JavaScript, and inserted within a

I guess this tag is somehow responsible to insert the image in the rendered webpage... but how?

Is it possible to use requests alone to parse this web and obtain this filename?

NOTE: I'm aware that this can be accomplished using selenium. I'm specifically looking for a selenium-free solution.

Body:
This is a solution with requests and regex to find the data that you are looking for.

import requests
import re

weburl = (
    "https://smn.conagua.gob.mx/tools/GUI/visor_radares_v2/radares/cabos/cabos_ppi.php"
)
headers = {
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36"
    "(KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"
}
response = requests.get(weburl, verify=False, headers=headers)

source = response.content.decode("utf-8")

imagen_eco = re.search("imagen_eco((.*?));", source)
if not imagen_eco:
    exit("Not found")

image_name = re.search(r"([\w-]+)\.png", imagen_eco.group(0))
if not image_name:
    exit("Not found")
print(image_name.group(0))
print(
    f"https://smn.conagua.gob.mx/tools/GUI/visor_radares_v2/ecos/cabos/ppi/{image_name.group(0)}"
)


问:
Why does my while loop only go through one name in the database, instead of all of them? my program should sum values assigned to the same name
```<code>String name;
            int sum;
            myRs = myStmt.executeQuery("SELECT DISTINCT person FROM Todo_tbl");
            while (myRs.next()) {
                name = myRs.getString("person");
                System.out.println(name);
                sum = 0;
                ResultSet myRs2 = myStmt.executeQuery("SELECT duration FROM Todo_tbl WHERE person ='" + name + "' ");
                while (myRs2.next()) {
                    sum += (int) myRs2.getInt("duration");
                    JList<Integer> list2 = new JList<>();
                }
                dfduration.addElement(sum);
            }
</code>```

That is the code I use, the problem is that the loop only goes through one name and closes after. I am not sure why, the code is supposed to go through all the names in the database and sum the values assigned to the same name.
I will be so grateful for any help!

答:
You are attempting to use two ResultSets generated by the same Statement in interleaving fashion.  This will not work.  As the API docs for java.sql.Statement put it:

By default, only one ResultSet object per Statement object can be open
at the same time. Therefore, if the reading of one ResultSet object is
interleaved with the reading of another, each must have been generated
by different Statement objects. All execution methods in the Statement
interface implicitly close a current ResultSet object of the statement
if an open one exists.

Thus, as soon as you perform the myStmt.executeQuery() inside the inner loop, the ResultSet to which myRs refers is closed.  The next call to myRs.next() therefore returns false, and no further loop iterations are performed.

I suggest a different query:

SELECT person, duration FROM Todo_tbl ORDER BY person
```
<p>Then use a single loop over the results.  Aside from not requiring multiple <code>Statements</code>, it would use only one query, which is much more efficient.</p>
<p>Alternatively, leave out the <code>ORDER BY</code> clause, and perform the grouping by person on the Java side, with the help of a <code>Map</code>.</p>
<p>On the other hand, if all you want to do is get the sum of all of each person's durations (the code presented does nothing else, but maybe you want the individual points for some purpose not reflected in the question) then the best alternative would probably be to make the database do the work:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT person, SUM(duration) as total_duration FROM Todo_tbl GROUP BY person
</code>```

Any way around, details of how to write the appropriate loop for handling those results are left as an exercise.

Body:
String name;
            int sum;
            myRs = myStmt.executeQuery("SELECT DISTINCT person FROM Todo_tbl");
            while (myRs.next()) {
                name = myRs.getString("person");
                System.out.println(name);
                sum = 0;
                ResultSet myRs2 = myStmt.executeQuery("SELECT duration FROM Todo_tbl WHERE person ='" + name + "' ");
                while (myRs2.next()) {
                    sum += (int) myRs2.getInt("duration");
                    JList<Integer> list2 = new JList<>();
                }
                dfduration.addElement(sum);
            }

That is the code I use, the problem is that the loop only goes through one name and closes after. I am not sure why, the code is supposed to go through all the names in the database and sum the values assigned to the same name.
I will be so grateful for any help!

Body:
You are attempting to use two ResultSets generated by the same Statement in interleaving fashion.  This will not work.  As the API docs for java.sql.Statement put it:

By default, only one ResultSet object per Statement object can be open
at the same time. Therefore, if the reading of one ResultSet object is
interleaved with the reading of another, each must have been generated
by different Statement objects. All execution methods in the Statement
interface implicitly close a current ResultSet object of the statement
if an open one exists.

Thus, as soon as you perform the myStmt.executeQuery() inside the inner loop, the ResultSet to which myRs refers is closed.  The next call to myRs.next() therefore returns false, and no further loop iterations are performed.

I suggest a different query:

SELECT person, duration FROM Todo_tbl ORDER BY person

Then use a single loop over the results.  Aside from not requiring multiple Statements, it would use only one query, which is much more efficient.

Alternatively, leave out the ORDER BY clause, and perform the grouping by person on the Java side, with the help of a Map.

On the other hand, if all you want to do is get the sum of all of each person's durations (the code presented does nothing else, but maybe you want the individual points for some purpose not reflected in the question) then the best alternative would probably be to make the database do the work:

SELECT person, SUM(duration) as total_duration FROM Todo_tbl GROUP BY person

Any way around, details of how to write the appropriate loop for handling those results are left as an exercise.


问:
How can I apply reinforcement learning to continuous action spaces?
I'm trying to get an agent to learn the mouse movements necessary to best perform some task in a reinforcement learning setting (i.e. the reward signal is the only feedback for learning).

I'm hoping to use the Q-learning technique, but while I've found a way to extend this method to continuous state spaces, I can't seem to figure out how to accommodate a problem with a continuous action space.

I could just force all mouse movement to be of a certain magnitude and in only a certain number of different directions, but any reasonable way of making the actions discrete would yield a huge action space. Since standard Q-learning requires the agent to evaluate all possible actions, such an approximation doesn't solve the problem in any practical sense.

答: The common way of dealing with this problem is with actor-critic methods. These naturally extend to continuous action spaces. Basic Q-learning could diverge when working with approximations, however, if you still want to use it, you can try combining it with a self-organizing map, as done in "Applications of the self-organising map to reinforcement learning". The paper also contains some further references you might find useful.</p>


问:
Calculating the cumulative product of a matrix error, setting an array element with a sequence
```<code>matrix = np.matrix([[1, 0.01], [2, 0.003], [3, 0.015], [4, 0.026], [5, 0.006]])
cumulative = np.zeros(5)
for i in range(len(matrix[0])):
    p = 1
    for j in range(0, i+1):
        p = p*(1 + matrix[1][j])
    p = p-1
    cumulative[i] = p
print(cumulative)
</code>```

I get a value error when I run this code:

```<code>TypeError: only size-1 arrays can be converted to Python scalars

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 6, in <module>
ValueError: setting an array element with a sequence.
</code>```

答:
The expression matrix[1][j] is an array, not a single value. Matrixes try to maintain their 2D nature, so indexing with a single value gives you another matrix.

You need to use a tuple index to get individual values:

```<code>p = p * (1 + matrix[1, j])
</code>```

Note the comma!

Demo:

```<code>>>> import numpy as np
>>> matrix = np.matrix([[1, 0.01], [2, 0.003], [3, 0.015], [4, 0.026], [5, 0.006]])
>>> cumulative = np.zeros(5)
>>> for i in range(len(matrix[0])):
...     p = 1
...     for j in range(0, i+1):
...         p = p*(1 + matrix[1, j])
...     p = p-1
...     cumulative[i] = p
...
>>> print(cumulative)
[2. 0. 0. 0. 0.]
</code>```

Note that only the first column of the first and second rows (with the values 1, 0.01 and 2, 0.003) are being used in your code, each having a length of 1. The contained matrix has a shape of (1, 2):

```<code>>>> matrix[0]
matrix([[1.  , 0.01]])
>>> matrix[1]
matrix([[2.   , 0.003]])
>>> len(matrix[0])
1
>>> matrix[0].shape
(1, 2)
</code>```

You are not processing the matrix per column (so across all 5 rows), and len(matrix[0]) is never going to give you 2 or 5.

You may want to use matrix.getA() to get a numpy array for a given matrix column, and then just use numpy.ndarray.cumprod() to calculate the cumulative product. Add 1 to all values in the column, then subtract 1 again afterwards:

```<code>cumulative =  (1 + matrix[:, 1].getA()).cumprod() - 1
</code>```

Here, [:, 1] takes the second column (the values 0.01, 0.003, 0.015, etc.), turns that into an array (unwrapping the matrix), adds 1 to each value and calculates their cumulative product (5 values again). We then subtract 1 from each of those 5 values.

This produces:

```<code>>>> cumulative = (1 + matrix[:, 1].getA()).cumprod() - 1
>>> print(cumulative)
[0.01       0.01303    0.02822545 0.05495931 0.06128907]
</code>```

Body:
matrix = np.matrix([[1, 0.01], [2, 0.003], [3, 0.015], [4, 0.026], [5, 0.006]])
cumulative = np.zeros(5)
for i in range(len(matrix[0])):
    p = 1
    for j in range(0, i+1):
        p = p*(1 + matrix[1][j])
    p = p-1
    cumulative[i] = p
print(cumulative)

I get a value error when I run this code:

TypeError: only size-1 arrays can be converted to Python scalars

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 6, in <module>
ValueError: setting an array element with a sequence.

Body:
The expression matrix[1][j] is an array, not a single value. Matrixes try to maintain their 2D nature, so indexing with a single value gives you another matrix.

You need to use a tuple index to get individual values:

p = p * (1 + matrix[1, j])

Note the comma!

Demo:

>>> import numpy as np
>>> matrix = np.matrix([[1, 0.01], [2, 0.003], [3, 0.015], [4, 0.026], [5, 0.006]])
>>> cumulative = np.zeros(5)
>>> for i in range(len(matrix[0])):
...     p = 1
...     for j in range(0, i+1):
...         p = p*(1 + matrix[1, j])
...     p = p-1
...     cumulative[i] = p
...
>>> print(cumulative)
[2. 0. 0. 0. 0.]

Note that only the first column of the first and second rows (with the values 1, 0.01 and 2, 0.003) are being used in your code, each having a length of 1. The contained matrix has a shape of (1, 2):

>>> matrix[0]
matrix([[1.  , 0.01]])
>>> matrix[1]
matrix([[2.   , 0.003]])
>>> len(matrix[0])
1
>>> matrix[0].shape
(1, 2)

You are not processing the matrix per column (so across all 5 rows), and len(matrix[0]) is never going to give you 2 or 5.

You may want to use matrix.getA() to get a numpy array for a given matrix column, and then just use numpy.ndarray.cumprod() to calculate the cumulative product. Add 1 to all values in the column, then subtract 1 again afterwards:

cumulative =  (1 + matrix[:, 1].getA()).cumprod() - 1

Here, [:, 1] takes the second column (the values 0.01, 0.003, 0.015, etc.), turns that into an array (unwrapping the matrix), adds 1 to each value and calculates their cumulative product (5 values again). We then subtract 1 from each of those 5 values.

This produces:

>>> cumulative = (1 + matrix[:, 1].getA()).cumprod() - 1
>>> print(cumulative)
[0.01       0.01303    0.02822545 0.05495931 0.06128907]


问:
SQL select query not as intended
I want to select the rows that column a is the same, but column b has different values (while removing duplicates in column b, so only one row represent the rows that have the same value in column b)

Table:

```<code>a   b
--  --
1   111
1   111
1   222
1   333
1   222

2   523
5   323
</code>```

I tried this query:

```<code>SELECT * FROM table GROUP BY b HAVING a = 1;
</code>```

which returns what i want with current inputs:

output

```<code>1 111
1 222
1 333
</code>```

however if the result is one row, nothing is selected.
for example:

```<code>SELECT * FROM table GROUP BY b HAVING a = 2;
</code>```

doesn't return anything, and I want it to return one row.

```<code>2 523
</code>```

what is the problem with the query?

Thanks.

答:
Your query is invalid in most databases because you are using a non-aggregated value in the HAVING clause.

Instead, you should check if each group contains only 1 distinct vale:

```<code>SELECT MAX(a) a, b
FROM tablename
GROUP BY b
HAVING COUNT(DISTINCT a) = 1 AND MAX(a) = ?;
</code>```

Replace ? with the value that you search for.

See the demo.

Title: SQL select query not as intended

Body:
I want to select the rows that column a is the same, but column b has different values (while removing duplicates in column b, so only one row represent the rows that have the same value in column b)

Table:

a   b
--  --
1   111
1   111
1   222
1   333
1   222

2   523
5   323

I tried this query:

SELECT * FROM table GROUP BY b HAVING a = 1;

which returns what i want with current inputs:

output

1 111
1 222
1 333

however if the result is one row, nothing is selected.
for example:

SELECT * FROM table GROUP BY b HAVING a = 2;

doesn't return anything, and I want it to return one row.

2 523

what is the problem with the query?

Thanks.

Body:
Your query is invalid in most databases because you are using a non-aggregated value in the HAVING clause.

Instead, you should check if each group contains only 1 distinct vale:

SELECT MAX(a) a, b
FROM tablename
GROUP BY b
HAVING COUNT(DISTINCT a) = 1 AND MAX(a) = ?;

Replace ? with the value that you search for.

See the demo.


问:
CRSError: Invalid projection: epsg:4326: for geopandas
I am using anaconda for geopandas.
However, everytime I try to use epsg:4326:, it gives an error.

```<code>CRSError: Invalid projection: epsg:4326: (Internal Proj Error: proj_create: SQLite error on SELECT name, type, coordinate_system_auth_name, coordinate_system_code, datum_auth_name, datum_code, area_of_use_auth_name, area_of_use_code, text_definition, deprecated FROM geodetic_crs WHERE auth_name = ? AND code = ?: no such column: area_of_use_auth_name)
</code>```

How can I solve this problem?

I tried:

```<code>from functools import partial
from pyproj import Proj, transform
proj_4326 = Proj(init="epsg:4326")
proj_3857 = Proj(init="epsg:3857")
</code>```

I also tried to reset the environment:

```<code>conda update anaconda
</code>```

but they both gave the same CRSError

My versions are:

```<code>import sys
import pyproj
import geopandas
</code>```
```<code>print(sys.version)
print(pyproj.__version__)
print(geopandas.__version__)
</code>```
```<code>3.8.5 (default, Sep  4 2020, 02:22:02)
[Clang 10.0.0 ]
2.6.1.post1
0.8.2
</code>```

How can I resolve this?

答:
I had the same problem. After a bit of a research I found out that anaconda will have a specific directory for geopandas and once it looks for pyproj there it won't find because in my case it was installed with pip as it was an ordeal to install geopandas in Windows(I usually work with Linux). The solution was remove geopandas with conda, then remove pyproj with pip. After it all is clean(try conda list to double check) I just use  conda install -c conda-forge geopandas and voilà!
I decided to share in case someone faces this annoyance. There is no point to look for the right format for your geodata.</p>

Body:
I am using anaconda for geopandas.
However, everytime I try to use epsg:4326:, it gives an error.

CRSError: Invalid projection: epsg:4326: (Internal Proj Error: proj_create: SQLite error on SELECT name, type, coordinate_system_auth_name, coordinate_system_code, datum_auth_name, datum_code, area_of_use_auth_name, area_of_use_code, text_definition, deprecated FROM geodetic_crs WHERE auth_name = ? AND code = ?: no such column: area_of_use_auth_name)

How can I solve this problem?

I tried:

from functools import partial
from pyproj import Proj, transform
proj_4326 = Proj(init="epsg:4326")
proj_3857 = Proj(init="epsg:3857")

I also tried to reset the environment:

conda update anaconda

but they both gave the same CRSError

My versions are:

import sys
import pyproj
import geopandas

print(sys.version)
print(pyproj.__version__)
print(geopandas.__version__)

3.8.5 (default, Sep  4 2020, 02:22:02)
[Clang 10.0.0 ]
2.6.1.post1
0.8.2

How can I resolve this?


问:
MudBlazor: How to remove padding from TitleContent in MudExpansionPanel
Looking to align TitleContent with ChildContent left. This expansion panel is in a tight space and I'd like to remove the gutters on the title content but DisableGutters only seems to apply to ChildContent:

Screenshot

TryMudblazor:
https://try.mudblazor.com/snippet/QEQwYmkTgJGCChXP

Thanks in advance!

答:
From GitHub MudBlazor Discussions:

You have to use CSS to call out the mud-expand-panel-header class

```<code><style>
    .my-panels .mud-expand-panel-header { padding: 0px; }
</style>

<MudExpansionPanels Class="my-panels" Elevation="0" DisableGutters="true" Dense="true">
    <MudExpansionPanel Dense="true" Style="padding: 0px;">
        <TitleContent>
                <MudText Class="mud-text-primary">$[ItemPrice1] [ItemPrice1Label]</MudText>
        </TitleContent>
        <ChildContent>
                <MudText Class="mud-text-primary">$[ItemPrice2] [ItemPrice2Label]</MudText>
                <MudText Class="mud-text-primary">$[ItemPrice3] [ItemPrice3Label]</MudText>
        </ChildContent>
    </MudExpansionPanel>
</MudExpansionPanels>
</code>```

Body:
From GitHub MudBlazor Discussions:

You have to use CSS to call out the mud-expand-panel-header class

<style>
    .my-panels .mud-expand-panel-header { padding: 0px; }
</style>

<MudExpansionPanels Class="my-panels" Elevation="0" DisableGutters="true" Dense="true">
    <MudExpansionPanel Dense="true" Style="padding: 0px;">
        <TitleContent>
                <MudText Class="mud-text-primary">$[ItemPrice1] [ItemPrice1Label]</MudText>
        </TitleContent>
        <ChildContent>
                <MudText Class="mud-text-primary">$[ItemPrice2] [ItemPrice2Label]</MudText>
                <MudText Class="mud-text-primary">$[ItemPrice3] [ItemPrice3Label]</MudText>
        </ChildContent>
    </MudExpansionPanel>
</MudExpansionPanels>


问:
Updated the Navigation framework and getting error - "getActionId overrides nothing"
I have updated the Navigation framework from 2.3.5 to the 2.4.0-alpha01 version. I use it with Safe Args gradle plugin. After update, I started getting 'getActionId' overrides nothing and 'getArguments' overrides nothing errors.

I think this is happening because Safe Args is overriding the actionId and arguments fields of NavDirections improperly when generating the Direction classes.

For example, this is what is being generated:

```<code> public override fun getActionId(): Int =
        R.id.action_navigation_articles_to_articleReaderFragment
</code>```

This is what should be generated:

```<code>public override val actionId: Int = R.id.action_navigation_articles_to_articleReaderFragment
</code>```

How can I get the Safe Args to generate proper builder classes?

答: update to 2.5.0-alpha01 version and wrapper-properties distributionUrl -7.0.2-bin.zip for a fix.</p>

Body:
I have updated the Navigation framework from 2.3.5 to the 2.4.0-alpha01 version. I use it with Safe Args gradle plugin. After update, I started getting 'getActionId' overrides nothing and 'getArguments' overrides nothing errors.

I think this is happening because Safe Args is overriding the actionId and arguments fields of NavDirections improperly when generating the Direction classes.

For example, this is what is being generated:

 public override fun getActionId(): Int =
        R.id.action_navigation_articles_to_articleReaderFragment

This is what should be generated:

public override val actionId: Int = R.id.action_navigation_articles_to_articleReaderFragment

How can I get the Safe Args to generate proper builder classes?


问:
Flextable label not created in rmarkdown
I am using flextable to produce tables for a pdf document rendered with rmarkdwown. I want to cross-reference the tables, but they do not produce the label needed for the cross reference to work.

My Minimum Reproducible Example

What follows is the content of the file test.Rmd:

```<code>---
title: "document title"
author: "author here"
date: "2022-01-20"
output:
  pdf_document:
    fig_caption: yes
    includes:
      in_header: header.tex
    number_sections: yes
    toc: yes
    toc_depth: 4
    latex_engine: xelatex
    keep_tex: true
---

```{r, include = FALSE}
library(flextable)
library(bookdown)

opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, out.width = "85%", fig.align = "center")

```

```{r, tab.id = "anyTable", tab.cap = "Invented data", tab.lp = "tab:"}

a = data.frame(id = LETTERS[1:3], x = 1:3)

flextable(a) |> theme_vanilla()
```

```{r secondTable}

b = data.frame(id = LETTERS[4:6], x = 4:6)

flextable(b) |> theme_vanilla() |> set_caption(caption = "This is secondTable")
```

# Standard rmarkdown crossreference

Trying anyTable: \ref{tab:anyTable}.

Trying secondTable: \ref{tab:secondTable}.

# Bookdown crossreference

Trying anyTable: \@ref(tab:anyTable).

Trying secondTable: \@ref(tab:secondTable).
</code>```

Contents of header.tex:

```<code>\usepackage{caption}
\renewcommand{\contentsname}{Contenidos}
\captionsetup[table]{name=Tabla}
\captionsetup[figure]{name=Figura}
%\usepackage{float} #use the 'float' package
%\floatplacement{figure}{H}
\usepackage{fancyhdr}
\pagestyle{fancy}
\usepackage{xcolor}
\usepackage{multicol}
\usepackage{pdflscape}
\newcommand{\blandscape}{\begin{landscape}}
\newcommand{\elandscape}{\end{landscape}}
</code>```

When I do rmarkdown::render("test.Rmd", output_file = "test.pdf") the file is rendered in pdf, but the following warning comes out:

```<code>Output created: test.pdf
Warning message:
LaTeX Warning: Reference `tab:anyTable' on page 1 undefined on input line 198.
LaTeX Warning: Reference `tab:secondTable' on page 1 undefined on input line 20
0.
LaTeX Warning: There were undefined references.
</code>```

If I check the .tex file, I can see that the captions are there, but they do not have the labels. The relevant lines of the intermediate test.tex file:

lines 106 to 109

```<code>\begin{longtable}[c]{|p{0.75in}|p{0.75in}}

\caption{Invented data
}\\
</code>```

lines 153 to 156

```<code>\begin{longtable}[c]{|p{0.75in}|p{0.75in}}

\caption{This is secondTable
}\\
</code>```

I expected that the caption line in the tex file was something like \caption{This is secondTable}\label{tab:secondTable}\\

What I've tried

Changing latex engines (lualatex, pdflatex, xelatex).

Editing the tex file (adding the label after the caption), but it fails to convert to dvi with multiple errors (mostly "undefined control sequence")

What am I doing wrong?

How can I cross-reference the tables produced by flextable?
Alternatively, I am open to other packages you may suggest. As some of the headers in my real data are somewhat complex (multi-span headers and the like), I would like to steer away from kable and kableExtra if at all possible.

答:
You need to use a format from bookdown to get cross references, see https://bookdown.org/yihui/rmarkdown-cookbook/cross-ref.html

```<code>---
title: "document title"
author: "author here"
date: "2022-01-20"
output:
  bookdown::pdf_document2:
    fig_caption: yes
    number_sections: yes
    toc: yes
    toc_depth: 4
    latex_engine: xelatex
    keep_tex: true
---

```{r, include = FALSE}
library(flextable)
library(knitr)
library(bookdown)

opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, out.width = "85%", fig.align = "center")
```

```{r, tab.id = "anyTable", tab.cap = "Invented data"}
a = data.frame(id = LETTERS[1:3], x = 1:3)
flextable(a) |> theme_vanilla()
```

```{r secondTable}
b = data.frame(id = LETTERS[4:6], x = 4:6)
flextable(b) |> theme_vanilla() |> set_caption(caption = "This is secondTable")
```

# Bookdown crossreference

Trying anyTable: \@ref(tab:anyTable).

Trying secondTable: \@ref(tab:secondTable).

</code>```

Body:
I am using flextable to produce tables for a pdf document rendered with rmarkdwown. I want to cross-reference the tables, but they do not produce the label needed for the cross reference to work.

My Minimum Reproducible Example

What follows is the content of the file test.Rmd:

---
title: "document title"
author: "author here"
date: "2022-01-20"
output:
  pdf_document:
    fig_caption: yes
    includes:
      in_header: header.tex
    number_sections: yes
    toc: yes
    toc_depth: 4
    latex_engine: xelatex
    keep_tex: true
---

```{r, include = FALSE}
library(flextable)
library(bookdown)

opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, out.width = "85%", fig.align = "center")

```

```{r, tab.id = "anyTable", tab.cap = "Invented data", tab.lp = "tab:"}

a = data.frame(id = LETTERS[1:3], x = 1:3)

flextable(a) |> theme_vanilla()
```

```{r secondTable}

b = data.frame(id = LETTERS[4:6], x = 4:6)

flextable(b) |> theme_vanilla() |> set_caption(caption = "This is secondTable")
```

# Standard rmarkdown crossreference

Trying anyTable: \ref{tab:anyTable}.

Trying secondTable: \ref{tab:secondTable}.

# Bookdown crossreference

Trying anyTable: \@ref(tab:anyTable).

Trying secondTable: \@ref(tab:secondTable).

Contents of header.tex:

\usepackage{caption}
\renewcommand{\contentsname}{Contenidos}
\captionsetup[table]{name=Tabla}
\captionsetup[figure]{name=Figura}
%\usepackage{float} #use the 'float' package
%\floatplacement{figure}{H}
\usepackage{fancyhdr}
\pagestyle{fancy}
\usepackage{xcolor}
\usepackage{multicol}
\usepackage{pdflscape}
\newcommand{\blandscape}{\begin{landscape}}
\newcommand{\elandscape}{\end{landscape}}

When I do rmarkdown::render("test.Rmd", output_file = "test.pdf") the file is rendered in pdf, but the following warning comes out:

Output created: test.pdf
Warning message:
LaTeX Warning: Reference `tab:anyTable' on page 1 undefined on input line 198.
LaTeX Warning: Reference `tab:secondTable' on page 1 undefined on input line 20
0.
LaTeX Warning: There were undefined references.

If I check the .tex file, I can see that the captions are there, but they do not have the labels. The relevant lines of the intermediate test.tex file:

lines 106 to 109

\begin{longtable}[c]{|p{0.75in}|p{0.75in}}

\caption{Invented data
}\\

lines 153 to 156

\begin{longtable}[c]{|p{0.75in}|p{0.75in}}

\caption{This is secondTable
}\\

I expected that the caption line in the tex file was something like \caption{This is secondTable}\label{tab:secondTable}\\

What I've tried

Changing latex engines (lualatex, pdflatex, xelatex).

Editing the tex file (adding the label after the caption), but it fails to convert to dvi with multiple errors (mostly "undefined control sequence")

What am I doing wrong?

How can I cross-reference the tables produced by flextable?
Alternatively, I am open to other packages you may suggest. As some of the headers in my real data are somewhat complex (multi-span headers and the like), I would like to steer away from kable and kableExtra if at all possible.

Body:
You need to use a format from bookdown to get cross references, see https://bookdown.org/yihui/rmarkdown-cookbook/cross-ref.html

---
title: "document title"
author: "author here"
date: "2022-01-20"
output:
  bookdown::pdf_document2:
    fig_caption: yes
    number_sections: yes
    toc: yes
    toc_depth: 4
    latex_engine: xelatex
    keep_tex: true
---

```{r, include = FALSE}
library(flextable)
library(knitr)
library(bookdown)

opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, out.width = "85%", fig.align = "center")
```

```{r, tab.id = "anyTable", tab.cap = "Invented data"}
a = data.frame(id = LETTERS[1:3], x = 1:3)
flextable(a) |> theme_vanilla()
```

```{r secondTable}
b = data.frame(id = LETTERS[4:6], x = 4:6)
flextable(b) |> theme_vanilla() |> set_caption(caption = "This is secondTable")
```

# Bookdown crossreference

Trying anyTable: \@ref(tab:anyTable).

Trying secondTable: \@ref(tab:secondTable).


问:
how to keep session enabled in firebase/auth js?
When I log in or register everything works perfectly. But if I reload the page I have to log in again. Is there any way around this? I have tried setting up persistence myself but it doesn't work.
This is my code</p>
```<code>const iniciarSesion = (e) => {
    const auth = getAuth();
    setPersistence(auth, browserLocalPersistence)
    .then(() => {
        signInWithEmailAndPassword(auth, email, password)
            .then((userCredential) => {
                setVentana("Tienda")
            })
            .catch((error) => {
                console.log(error)
            });
    })
}
const registar = (e) => {
    const auth = getAuth();
    createUserWithEmailAndPassword(auth, email, password)
        .then((userCredential) => {
            setVentana("Tienda")
        })
        .catch((error) => {
            console.error(error)
        });
}
</code>```

答:
In most browser-based environments Firebase already persists and restores the user credentials upon reloading the page. From the Firebase documentation on auth persistence:

For a web application, the default behavior is to persist a user's session even after the user closes the browser. This is convenient as the user is not required to continuously sign-in every time the web page is visited on the same device.

So if your code runs in a browser, you shouldn't need to call setPersistence(auth, browserLocalPersistence). What you do need however, it so detect in your code when Firebase has restored the signed in user.

Restoring the user upon reloading the page requires that Firebase call to the server, to amongst others check if the account has been disabled. While this call is being made, the currentUser will be null. To get notified when the user has been restored, and for other changes in authentication state, you'll want to use an auth state listener as shown in the first code snippet in the documentation on getting the current user:

```<code>import { getAuth, onAuthStateChanged } from "firebase/auth";

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/firebase.User
    const uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});
</code>```

In this code you'll then call setVentana("Tienda") to navigate to the correct window.

Body:
When I log in or register everything works perfectly. But if I reload the page I have to log in again. Is there any way around this? I have tried setting up persistence myself but it doesn't work.
This is my code

const iniciarSesion = (e) => {
    const auth = getAuth();
    setPersistence(auth, browserLocalPersistence)
    .then(() => {
        signInWithEmailAndPassword(auth, email, password)
            .then((userCredential) => {
                setVentana("Tienda")
            })
            .catch((error) => {
                console.log(error)
            });
    })
}
const registar = (e) => {
    const auth = getAuth();
    createUserWithEmailAndPassword(auth, email, password)
        .then((userCredential) => {
            setVentana("Tienda")
        })
        .catch((error) => {
            console.error(error)
        });
}

Body:
In most browser-based environments Firebase already persists and restores the user credentials upon reloading the page. From the Firebase documentation on auth persistence:

For a web application, the default behavior is to persist a user's session even after the user closes the browser. This is convenient as the user is not required to continuously sign-in every time the web page is visited on the same device.

So if your code runs in a browser, you shouldn't need to call setPersistence(auth, browserLocalPersistence). What you do need however, it so detect in your code when Firebase has restored the signed in user.

Restoring the user upon reloading the page requires that Firebase call to the server, to amongst others check if the account has been disabled. While this call is being made, the currentUser will be null. To get notified when the user has been restored, and for other changes in authentication state, you'll want to use an auth state listener as shown in the first code snippet in the documentation on getting the current user:

import { getAuth, onAuthStateChanged } from "firebase/auth";

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/firebase.User
    const uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});

In this code you'll then call setVentana("Tienda") to navigate to the correct window.


问:
ModuleNotFoundError: No module named 'dash.dash_table'
I am trying to run a simple code like this:

```<code>import dash
import dash_table
import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/solar.csv')

app = dash.Dash(__name__)

app.layout = dash_table.DataTable(
    id='table',
    columns=[{"name": i, "id": i} for i in df.columns],
    data=df.to_dict('records'),
)

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

But get this error:

```<code> Traceback (most recent call last):
  File "/Users/.../PycharmProjects/pythonProject1/main.py", line 2, in <module>
    import dash_table
  File "/Users/.../PycharmProjects/pythonProject1/venv/bin/py/lib/python3.8/site-packages/dash_table/__init__.py", line 1, in <module>
    from dash.dash_table import *  # noqa: F401, F403, E402
ModuleNotFoundError: No module named 'dash.dash_table'
</code>```

Please help :(

P.S. I have already pip installed dash-table. Didn't help..

答: It looks like you have incompatible versions of dash and dash_table, with recent versions of Dash, when you install the dash package it also installs other packages including dash_table. Could you maybe uninstall dash_table and dash, reinstall dash, and see if it works?</p>

Body:
I am trying to run a simple code like this:

import dash
import dash_table
import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/solar.csv')

app = dash.Dash(__name__)

app.layout = dash_table.DataTable(
    id='table',
    columns=[{"name": i, "id": i} for i in df.columns],
    data=df.to_dict('records'),
)

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

But get this error:

 Traceback (most recent call last):
  File "/Users/.../PycharmProjects/pythonProject1/main.py", line 2, in <module>
    import dash_table
  File "/Users/.../PycharmProjects/pythonProject1/venv/bin/py/lib/python3.8/site-packages/dash_table/__init__.py", line 1, in <module>
    from dash.dash_table import *  # noqa: F401, F403, E402
ModuleNotFoundError: No module named 'dash.dash_table'

Please help :(

P.S. I have already pip installed dash-table. Didn't help..


问:
Change language of SupaBase error message

Hello stackoverflow!

Does anyone knows if you can change the language of a error message from SupaBase when a user Register/Login.

Example: User tries to register without email, the error is "Please enter a valid email adress"

I want to be able to change the error message. :)

Code:

```<code><!-- language: javascript -->
const handleSignUp = async (email, pass, username, kon) => {
console.log(email, pass, username, kon);

setLoading(true);
const { data, error } = await supabase.auth.signUp(
  {
    email: email,
    password: pass,
  },
  {
    data: {
      username,
      kon,
    },
  }
);

error ? seterrorMessage(error) : console.log(data);

setLoading(false);
};
</code>```

答:
Solution -> Get the status code of the error and make a message for each error code. :)

How to get error code?

```<code>Console.log(error.status)
</code>```

Body:
Hello stackoverflow!

Does anyone knows if you can change the language of a error message from SupaBase when a user Register/Login.

Example: User tries to register without email, the error is "Please enter a valid email adress"

I want to be able to change the error message. :)

Code:

const handleSignUp = async (email, pass, username, kon) => {
console.log(email, pass, username, kon);

setLoading(true);
const { data, error } = await supabase.auth.signUp(
  {
    email: email,
    password: pass,
  },
  {
    data: {
      username,
      kon,
    },
  }
);

error ? seterrorMessage(error) : console.log(data);

setLoading(false);
};

Body:
Solution -> Get the status code of the error and make a message for each error code. :)

How to get error code?

Console.log(error.status)


问:
How is @ElementCollection stored?
Here is part of my User Entity, as you can see, it has Enum Roles

```<code>@Entity
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String name;
    private String email;
    private String password;
    @ElementCollection(fetch = FetchType.EAGER)
    private List<Role> roles;
}
</code>```

The table role is missing, I only have one linking table user_roles. How is the data stored if I can't see it? How can I manually change role in PostgreSQL if I can't edit linking table?

答:
The role information is stored in user_roles. It is the nature of @ElementCollection which the collection will be mapped to a table which does not have any primary key column and have a FK column reference to its parent (i.e users) .

The value in the user_role 's roles column is not any role ID that you can find its record in some role master table. It is just the ordinal of the Role enum.

If you change it to :

@ElementCollection
@Enumerated(EnumType.STRING)
private List<Role> roles;
```
<p>Then the data in user_role will become :</p>
```user_id | roles
----------------
    1   | ADMIN
    1   | DEV
    2   | DEV
    3   | ADMIN
```

where the value in the roles column become the item name of Role enum.

Title: How is @ElementCollection stored?

Body:
Here is part of my User Entity, as you can see, it has Enum Roles

@Entity
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String name;
    private String email;
    private String password;
    @ElementCollection(fetch = FetchType.EAGER)
    private List<Role> roles;
}

The table role is missing, I only have one linking table user_roles. How is the data stored if I can't see it? How can I manually change role in PostgreSQL if I can't edit linking table?

Body:
The role information is stored in user_roles. It is the nature of @ElementCollection which the collection will be mapped to a table which does not have any primary key column and have a FK column reference to its parent (i.e users) .

The value in the user_role 's roles column is not any role ID that you can find its record in some role master table. It is just the ordinal of the Role enum.

If you change it to :

@ElementCollection
@Enumerated(EnumType.STRING)
private List<Role> roles;

Then the data in user_role will become :

user_id | roles
----------------
    1   | ADMIN
    1   | DEV
    2   | DEV
    3   | ADMIN

where the value in the roles column become the item name of Role enum.


问:
Why does my WPF application crash when I bump my mousewheel?
When I bump my mousewheel, my WPF application crashes sometimes, with an OverflowException. Here's the start of the stack trace:

```<code>at System.Windows.Shell.WindowChromeWorker._HandleNCHitTest(WM uMsg, IntPtr wParam, IntPtr lParam, Boolean& handled)
</code>```

From that, I've traced it down to the WindowChrome - I can even reproduce it with just the WindowChrome. But it seems like it has to be fullscreen. What's going on here? Is there a workaround?

答:
The workaround that Ivan Golović included in a comment above needs to be in an answer so it can be spotted easily and in case the link goes dead.

Preprocess the message in a HookProc and mark it as handled if the conversion from lParam to int32 overflows.

```<code>protected override void OnSourceInitialized( EventArgs e )
  {
     base.OnSourceInitialized( e );
     ( (HwndSource)PresentationSource.FromVisual( this ) ).AddHook( HookProc );
  }
  private IntPtr HookProc( IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled )
  {
     if ( msg == 0x0084 /*WM_NCHITTEST*/ )
     {
        // This prevents a crash in WindowChromeWorker._HandleNCHitTest
        try
        {
           lParam.ToInt32();
        }
        catch ( OverflowException )
        {
           handled = true;
        }
     }
     return IntPtr.Zero;
  }
</code>```

Body:
When I bump my mousewheel, my WPF application crashes sometimes, with an OverflowException. Here's the start of the stack trace:

at System.Windows.Shell.WindowChromeWorker._HandleNCHitTest(WM uMsg, IntPtr wParam, IntPtr lParam, Boolean& handled)

From that, I've traced it down to the WindowChrome - I can even reproduce it with just the WindowChrome. But it seems like it has to be fullscreen. What's going on here? Is there a workaround?

Body:
The workaround that Ivan Golović included in a comment above needs to be in an answer so it can be spotted easily and in case the link goes dead.

Preprocess the message in a HookProc and mark it as handled if the conversion from lParam to int32 overflows.

protected override void OnSourceInitialized( EventArgs e )
  {
     base.OnSourceInitialized( e );
     ( (HwndSource)PresentationSource.FromVisual( this ) ).AddHook( HookProc );
  }
  private IntPtr HookProc( IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled )
  {
     if ( msg == 0x0084 /*WM_NCHITTEST*/ )
     {
        // This prevents a crash in WindowChromeWorker._HandleNCHitTest
        try
        {
           lParam.ToInt32();
        }
        catch ( OverflowException )
        {
           handled = true;
        }
     }
     return IntPtr.Zero;
  }


答:
Don't bother checking $? explicitly.  Just do:

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

do_example() {
    local DB=$1
    local URI
    if URI=$(python3 example.py $DB); then
        echo "$URI"
        echo success
    else
        echo "$URI"
        echo failed
    fi
}

do_example 1
do_example 0
</code>```

Title: How to act on an error code and collect stdout at the same time?

Body:
I have this python3 program.  It sets error code 0 when it works and non-zero when it fails.  It puts the good message into stdout and the failure string into stderr.  I think it's well-behaved.

#! /bin/python3

import sys

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

cs = sys.argv[1]

if str(cs) == "1":
    print("GOOD")
else:
    eprint("BAD")
    sys.exit(1)

See how I test it:

$ X=`python3 example.py 1`; echo It is: $X
It is: GOOD
$ X=`python3 example.py 0`; echo It is: $X
BAD
It is:

I have this bash program that calls the python program:

#! /bin/bash

function do_example() {
    local DB=$1
    local URI=`python3 example.py $DB`
    RESULT=$?
    if [ $RESULT -eq 0 ]; then
        echo $URI
        echo success
    else
        echo $URI
        echo failed
    fi
}

do_example 1
do_example 0

It runs a python program first. Captures the stdout. Then it checks the return value.  It doesn't work.  It should say success and then failed.  Instead, it says success both times. It doesn't work.  It doesn't handle the error code correctly.

$ ./example.sh
success
BAD
success
$ ./example.sh
GOOD
success
BAD

The generalized question is how to collect the stdout into a local variable and act on the error code at the same time?

Body:
Don't bother checking $? explicitly.  Just do:

#! /bin/bash

do_example() {
    local DB=$1
    local URI
    if URI=$(python3 example.py $DB); then
        echo "$URI"
        echo success
    else
        echo "$URI"
        echo failed
    fi
}

do_example 1
do_example 0


问:
Create an array of strings
Is it possibe to create an array of strings in MATLAB within a for loop?

For example,

```<code>for i=1:10
Names(i)='Sample Text';
end
</code>```

I don't seem to be able to do it this way.

答:
You need to use cell-arrays:</p>

```<code>names = cell(10,1);
for i=1:10
    names{i} = ['Sample Text ' num2str(i)];
end
</code>```

Title: Create an array of strings

Body:
Is it possibe to create an array of strings in MATLAB within a for loop?

For example,

for i=1:10
Names(i)='Sample Text';
end

I don't seem to be able to do it this way.

Body:
You need to use cell-arrays:

names = cell(10,1);
for i=1:10
    names{i} = ['Sample Text ' num2str(i)];
end


问:
react rollup no styling with tailwind css and css
I want to build a npm package with rollup but the styling is not available. I want to use style with tailwindcss, css or scss.
I created a repo with demo code to demonstrate this issue.
You can do the steps in README.md and then you will see that the styling is not applied
Repo

This is my rollup.config.js

```<code>import babel from "@rollup/plugin-babel";
import image from "@rollup/plugin-image";
import json from "@rollup/plugin-json";
import commonjs from "rollup-plugin-commonjs";
import { nodeResolve } from "@rollup/plugin-node-resolve";
import replace from "@rollup/plugin-replace";
import sourcemaps from "rollup-plugin-sourcemaps";
import postcss from "rollup-plugin-postcss";

const input = "src/index.jsx";

var MODE = [
  {
    fomart: "es",
  },
];

var config = [];

MODE.map((m) => {
  var conf = {
    input: input,
    output: {
      dir: `dist`,
      format: m.fomart,
      sourcemap: true,
    },

    inlineDynamicImports: true,
    plugins: [
      replace({
        "process.env.NODE_ENV": JSON.stringify("development"),
      }),
      nodeResolve({
        extensions: [".js", ".jsx"],
      }),
      postcss({
        minimize: true,
        modules: true,

        extract: true,
      }),

      json(),
      image(),
      babel({
        exclude: "node_modules/**",
        plugins: ["@babel/transform-runtime"],
        babelHelpers: "runtime",
      }),
      commonjs({
        include: "node_modules/**",
      }),
      sourcemaps(),
    ],
  };
  config.push(conf);
});

export default [...config];
</code>```

答:
The Bootstrap styles aren't working because of the PostCSS "modules" option in rollup config. This option prefixes the class names (you can see it in dist/index.css generated file, by looking for "bootstrap-min") in order to avoid conflicts, but in our case we want Bootstrap styles to be global.

postcss({
  minimize: true,
  modules: true, // <--- this line

  extract: true,
}),
```

by removing it, the Bootstrap CSS is generated without any CSS module prefix.

Regarding Tailwind, you have to install the compatibility build of Tailwind and configure its PostCSS plugin in the rollup config, like described in https://samrobbins.uk/blog/tailwind-component-library

Body:
I want to build a npm package with rollup but the styling is not available. I want to use style with tailwindcss, css or scss.
I created a repo with demo code to demonstrate this issue.
You can do the steps in README.md and then you will see that the styling is not applied
Repo

This is my rollup.config.js

import babel from "@rollup/plugin-babel";
import image from "@rollup/plugin-image";
import json from "@rollup/plugin-json";
import commonjs from "rollup-plugin-commonjs";
import { nodeResolve } from "@rollup/plugin-node-resolve";
import replace from "@rollup/plugin-replace";
import sourcemaps from "rollup-plugin-sourcemaps";
import postcss from "rollup-plugin-postcss";

const input = "src/index.jsx";

var MODE = [
  {
    fomart: "es",
  },
];

var config = [];

MODE.map((m) => {
  var conf = {
    input: input,
    output: {
      dir: `dist`,
      format: m.fomart,
      sourcemap: true,
    },

    inlineDynamicImports: true,
    plugins: [
      replace({
        "process.env.NODE_ENV": JSON.stringify("development"),
      }),
      nodeResolve({
        extensions: [".js", ".jsx"],
      }),
      postcss({
        minimize: true,
        modules: true,

        extract: true,
      }),

      json(),
      image(),
      babel({
        exclude: "node_modules/**",
        plugins: ["@babel/transform-runtime"],
        babelHelpers: "runtime",
      }),
      commonjs({
        include: "node_modules/**",
      }),
      sourcemaps(),
    ],
  };
  config.push(conf);
});

export default [...config];

Body:
The Bootstrap styles aren't working because of the PostCSS "modules" option in rollup config. This option prefixes the class names (you can see it in dist/index.css generated file, by looking for "bootstrap-min") in order to avoid conflicts, but in our case we want Bootstrap styles to be global.

postcss({
  minimize: true,
  modules: true, // <--- this line

  extract: true,
}),

by removing it, the Bootstrap CSS is generated without any CSS module prefix.

Regarding Tailwind, you have to install the compatibility build of Tailwind and configure its PostCSS plugin in the rollup config, like described in https://samrobbins.uk/blog/tailwind-component-library


问:
Issues with list index after swapping first and last number in the list
I am new to Python and with the swapping exercise, I cannot swap the first and last element of the list using the following code (the line with issue noted below).

def swapList(list):

    first = list.pop(0)
    last = list.pop(-1)

    list.insert(0, last)
    list.insert(-1, first)  # this line is the issue.
    # It does not swap first to the last position in the list,
    # but instead place it just before the last number. If I change
    # it to list.append(first) then the issue is solved.
    # I cannot understand why.

    return list
```

Can you please help?

答:
Try this</p>
```<code>def swaplist(list):

    first = list.pop(0)
    last = list.pop(-1)

    list.insert(0, last)
    list.append(first)

    return list

list = [10 , 20 , 30 , 40 , 50 , 60]

print(swaplist(list))
</code>```

Body:
I am new to Python and with the swapping exercise, I cannot swap the first and last element of the list using the following code (the line with issue noted below).

def swapList(list):

    first = list.pop(0)
    last = list.pop(-1)

    list.insert(0, last)
    list.insert(-1, first)  # this line is the issue.
    # It does not swap first to the last position in the list,
    # but instead place it just before the last number. If I change
    # it to list.append(first) then the issue is solved.
    # I cannot understand why.

    return list

Can you please help?

Body:
Try this

def swaplist(list):

    first = list.pop(0)
    last = list.pop(-1)

    list.insert(0, last)
    list.append(first)

    return list

list = [10 , 20 , 30 , 40 , 50 , 60]

print(swaplist(list))


问:
How can I use window.scrollby with react?
I am trying to click a button which scrolls down to a specific portion of my app. So currently I have:

```<code>class Nav extends Component {
  foo(){
    console.log('baz')
    window.scrollTo(0, 100);
  }
  render() {
    return (
        <nav>
          <a href="#" onClick={()=> this.foo()}>About</a>

        </nav>
    );
  }
}
</code>```

This will console.log "baz" but won't scroll down to 100

答:
You can do like this -

const handleRef = (param) => window.scrollTo(0, param);

 handleRef(1000)} >Drops

```

Body:
I am trying to click a button which scrolls down to a specific portion of my app. So currently I have:

class Nav extends Component {
  foo(){
    console.log('baz')
    window.scrollTo(0, 100);
  }
  render() {
    return (

           this.foo()}>About

    );
  }
}

This will console.log "baz" but won't scroll down to 100

Body:
You can do like this -

const handleRef = (param) => window.scrollTo(0, param);
<p onClick={()=> handleRef(1000)} >Drops</p>


问:
PHP Multidimensional Array problem
iam trying to build a multidimensional array.

```<code>public function saveRateTemplateData($RateTemplateInfo)
{
    $RateTemplateID = $RateTemplateInfo['id'];
    $Zones = $RateTemplateInfo['premium_zones'];
    //$ZoneZipCodeIDs[] = array();
    for ($n = 1; $n <= $RateTemplateInfo['premium_zones']; $n++) {
        $ZoneNum = 'zone' . $n;
        $ZipCodeArray = explode(",",$_POST[$ZoneNum]);
        $ZipCodeIDs=array();
        foreach ($ZipCodeArray as $v) {
            $v = intval(trim($v));
            if (strlen($v) == 5) {
                array_push($ZipCodeIDs, $this->addZipCode($v));
            } else {
                echo "it isnt 5";
            }
        }
    }
}
</code>```

so what iam trying to do is make an array of an array. so this is how its supposed to look

```<code>Array
(
  [1] => Array
    (
        [0] => 34
        [1] => 31
        [2] => 23
    )

  [2] => Array
    (
        [0] => 18
        [1] => 4
        [2] => 35
        [3] => 1
    )
)
</code>```

i have tried numerous ways it doesnt work
basically i want it in this format VarName[ZoneNumbers][ZipCodeID]

so i can loop through it later on. so i can print like this $VarName[$n] then a array of all zipcodeID will print for Zone Number 1 in this case it will print 34,31,23

答:
```<code>public function saveRateTemplateData($RateTemplateInfo)
{
    $RateTemplateID = $RateTemplateInfo['id'];
    $zones = array(); // you weren't using this so I'll use it to hold the data

    for ($n = 1; $n <= $RateTemplateInfo['premium_zones']; $n++) {
        $ZoneNum = 'zone' . $n;

        // create an array under the zone number for holding the IDs
        $zones[$n] = array();

        $ZipCodeArray = explode(",",$_POST[$ZoneNum]);
        foreach ($ZipCodeArray as $v) {
            $v = (int) trim($v);
            if (strlen($v) == 5) {
                $zones[$n][] = $this->addZipCode($v);
            } else {
                // use exceptions for exceptional circumstances
                throw new RuntimeException(sprintf('Invalid zone ID "%s"', $v));
            }
        }
    }

    return $zones;
}
</code>```

Title: PHP Multidimensional Array problem

Body:
iam trying to build a multidimensional array.

public function saveRateTemplateData($RateTemplateInfo)
{
    $RateTemplateID = $RateTemplateInfo['id'];
    $Zones = $RateTemplateInfo['premium_zones'];
    //$ZoneZipCodeIDs[] = array();
    for ($n = 1; $n <= $RateTemplateInfo['premium_zones']; $n++) {
        $ZoneNum = 'zone' . $n;
        $ZipCodeArray = explode(",",$_POST[$ZoneNum]);
        $ZipCodeIDs=array();
        foreach ($ZipCodeArray as $v) {
            $v = intval(trim($v));
            if (strlen($v) == 5) {
                array_push($ZipCodeIDs, $this->addZipCode($v));
            } else {
                echo "it isnt 5";
            }
        }
    }
}

so what iam trying to do is make an array of an array. so this is how its supposed to look

Array
(
  [1] => Array
    (
        [0] => 34
        [1] => 31
        [2] => 23
    )

  [2] => Array
    (
        [0] => 18
        [1] => 4
        [2] => 35
        [3] => 1
    )
)

i have tried numerous ways it doesnt work
basically i want it in this format VarName[ZoneNumbers][ZipCodeID]

so i can loop through it later on. so i can print like this $VarName[$n] then a array of all zipcodeID will print for Zone Number 1 in this case it will print 34,31,23


答:
It looks like all you really need is distinct, eg

```<code>select distinct a, b
from t
where a=2;
</code>```

Title: SQL select query not as intended

Body:
I want to select the rows that column a is the same, but column b has different values (while removing duplicates in column b, so only one row represent the rows that have the same value in column b)

Table:

a   b
--  --
1   111
1   111
1   222
1   333
1   222

2   523
5   323

I tried this query:

SELECT * FROM table GROUP BY b HAVING a = 1;

which returns what i want with current inputs:

output

1 111
1 222
1 333

however if the result is one row, nothing is selected.
for example:

SELECT * FROM table GROUP BY b HAVING a = 2;

doesn't return anything, and I want it to return one row.

2 523

what is the problem with the query?

Thanks.

Body:
It looks like all you really need is distinct, eg

select distinct a, b
from t
where a=2;


问:
Cant upload multilple images using django
I'm trying to create page to add new product with it's images in other model on my website using Djnago.
The length of the list of images I get is always 0 and i'm getting IndexError: list index out of range. I guess that i'm getting files from request not properly using images = request.FILES.getlist('images')

models.py

```<code>class Products(models.Model):
    product_name = models.CharField(
        max_length=255, verbose_name='Product name')
    product_slug = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    product_image = models.ImageField(
        default='image-placeholder.png', verbose_name='Image')
    creaton_date = models.DateTimeField(auto_now_add=True)
    brand = models.ForeignKey(
        Brands, verbose_name='Brand', on_delete=models.PROTECT)
    price = models.FloatField(verbose_name='Price')
    description = models.TextField(null=True, verbose_name='Description')
    category = models.ForeignKey(
        Categories, on_delete=models.CASCADE, verbose_name='Category')
    bought_count = models.IntegerField(null=True, default=0)

class ProductImage(models.Model):
    product = models.ForeignKey(Products, on_delete=models.CASCADE)
    image = models.ImageField()
    default = models.BooleanField(default=False)

    def __str__(self):
        return str(self.product)
</code>```

template.html

```<code><form id="checkoutform" action="" method="post">
{% csrf_token %}
<div class="caption">
    <div class="form-group">
        <input class="input" type="text" name="product-name" placeholder="Product name">
    </div>
    <div class="form-group">
        <input class="input" type="text" name="brand" placeholder="Brand">
    </div>
    <div class="form-group">
        <input class="input" type="number" name="price" placeholder="Price">
    </div>
    <div class="form-group">
        <input class="input" type="file" multiple name="images" placeholder="Images">
    </div>
    <div class="form-group">
        <input class="input" type="text" name="desc" placeholder="Description">
    </div>
    <div class="form-group">
        <input class="input" type="text" name="category" placeholder="Category">
    </div>
    <input type="submit" value="Submit">
</form>
</code>```

views.py

```<code>def create_product(request):
    if request.user.is_superuser:
        if request.method == 'POST':
            data = request.POST
            images = request.FILES.getlist('images')
            brand = Brands.objects.get(name=data['brand'])
            category =  Categories.objects.get(name=data['category'])
            product = Products.objects.create(
                product_name = data['product-name'],
                brand=brand,
                price = data['price'],
                description = data['desc'],
                category = category,
                image = images[0],
            )
            for i in range (1, len(images)):
                image = ProductImage.objects.create(
                    product = product,
                    image = images[i]
            )

        return render(request, 'store/create_product.html')
    else:
        return HttpResponse("You are not allowed here")
</code>```

答:
Well if you don't mind am going to suggest a another way to upload multiple images, by first creating separate model to handle images and also  a form to handle multiple images upload.

```<code>Models.py

 class Products(models.Model):
    product_name = models.CharField(
        max_length=255, verbose_name='Product name')
    product_slug = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    product_image = models.ImageField(
        default='image-placeholder.png', verbose_name='Image')
    creaton_date = models.DateTimeField(auto_now_add=True)
    brand = models.ForeignKey(
        Brands, verbose_name='Brand', on_delete=models.PROTECT)
    price = models.FloatField(verbose_name='Price')
    description = models.TextField(null=True, verbose_name='Description')
    category = models.ForeignKey(
        Categories, on_delete=models.CASCADE, verbose_name='Category')
    bought_count = models.IntegerField(null=True, default=0)

class productImage(models.Model):
      product = models.ForeignKey(Product,on_delete=models.CASCADE)
      image = models.ImageField(default='image-placeholder.png', verbose_name='Image')

</code>```

Your would have to link the two models together in the admin by using StackedInine Like so:

```<code>Admin.py

from .models import Products,ProductImage

class ProductAdminImage(Admin.StackedInline)
      model = ProductImage

@Admin.register(Products)
class ProductAdmin(Admin.ModelAdmin):
      list_display = [] # fields that you want to display
      inlines = [ProductAdminImage] # Here we are linking both models with an inline

</code>```

Now We are going to work on the forms.py to handle multiple images upload

```<code>from .models import ProductImage

class ProductImageForm(forms.ModelForm):
      class Meta:
            model = ProductImage
            fields = ['image']
            widgets ={'image' :forms.ClearableFileInput(attrs={'multiple':True})}

</code>```

Finally we focus on the view to manipulate uploads for our images, what you have done  so far is good and but there's another way of uploading multiple images, this has worked for me in many cases!

```<code>from .forms import ProductImageForm

def create_product(request):
    if request.user.is_superuser:
        if request.method == 'POST':
            data = request.POST
            images = request.FILES.getlist('images')
            brand = Brands.objects.get(name=data['brand'])
            category =  Categories.objects.get(name=data['category'])
            form = ProductImageForm(request.POST, request.FILES)
            product = Products(product_name = data['product-name'],brand=brand,
                price = data['price'],
                description = data['desc'],
                category = category,
                product_image = images[0],)
            product.save()
            if form.is_valid():
               data = form.save(commit=False)
               for files in images:
                   data =ProductImage(product = product, image = files)
                   data.save()
                   return render(request, 'store/create_product.html')
            else:
                   return HttpResponse("You are not allowed here")
</code>```

Body:
I'm trying to create page to add new product with it's images in other model on my website using Djnago.
The length of the list of images I get is always 0 and i'm getting IndexError: list index out of range. I guess that i'm getting files from request not properly using images = request.FILES.getlist('images')

models.py

class Products(models.Model):
    product_name = models.CharField(
        max_length=255, verbose_name='Product name')
    product_slug = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    product_image = models.ImageField(
        default='image-placeholder.png', verbose_name='Image')
    creaton_date = models.DateTimeField(auto_now_add=True)
    brand = models.ForeignKey(
        Brands, verbose_name='Brand', on_delete=models.PROTECT)
    price = models.FloatField(verbose_name='Price')
    description = models.TextField(null=True, verbose_name='Description')
    category = models.ForeignKey(
        Categories, on_delete=models.CASCADE, verbose_name='Category')
    bought_count = models.IntegerField(null=True, default=0)

class ProductImage(models.Model):
    product = models.ForeignKey(Products, on_delete=models.CASCADE)
    image = models.ImageField()
    default = models.BooleanField(default=False)

    def __str__(self):
        return str(self.product)

template.html

<form id="checkoutform" action="" method="post">
{% csrf_token %}

        <input class="input" type="text" name="product-name" placeholder="Product name">

        <input class="input" type="text" name="brand" placeholder="Brand">

        <input class="input" type="number" name="price" placeholder="Price">

        <input class="input" type="file" multiple name="images" placeholder="Images">

        <input class="input" type="text" name="desc" placeholder="Description">

        <input class="input" type="text" name="category" placeholder="Category">

    <input type="submit" value="Submit">
</form>

views.py

def create_product(request):
    if request.user.is_superuser:
        if request.method == 'POST':
            data = request.POST
            images = request.FILES.getlist('images')
            brand = Brands.objects.get(name=data['brand'])
            category =  Categories.objects.get(name=data['category'])
            product = Products.objects.create(
                product_name = data['product-name'],
                brand=brand,
                price = data['price'],
                description = data['desc'],
                category = category,
                image = images[0],
            )
            for i in range (1, len(images)):
                image = ProductImage.objects.create(
                    product = product,
                    image = images[i]
            )

        return render(request, 'store/create_product.html')
    else:
        return HttpResponse("You are not allowed here")

Body:
Well if you don't mind am going to suggest a another way to upload multiple images, by first creating separate model to handle images and also  a form to handle multiple images upload.

Models.py

 class Products(models.Model):
    product_name = models.CharField(
        max_length=255, verbose_name='Product name')
    product_slug = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    product_image = models.ImageField(
        default='image-placeholder.png', verbose_name='Image')
    creaton_date = models.DateTimeField(auto_now_add=True)
    brand = models.ForeignKey(
        Brands, verbose_name='Brand', on_delete=models.PROTECT)
    price = models.FloatField(verbose_name='Price')
    description = models.TextField(null=True, verbose_name='Description')
    category = models.ForeignKey(
        Categories, on_delete=models.CASCADE, verbose_name='Category')
    bought_count = models.IntegerField(null=True, default=0)

class productImage(models.Model):
      product = models.ForeignKey(Product,on_delete=models.CASCADE)
      image = models.ImageField(default='image-placeholder.png', verbose_name='Image')

Your would have to link the two models together in the admin by using StackedInine Like so:

Admin.py

from .models import Products,ProductImage

class ProductAdminImage(Admin.StackedInline)
      model = ProductImage

@Admin.register(Products)
class ProductAdmin(Admin.ModelAdmin):
      list_display = [] # fields that you want to display
      inlines = [ProductAdminImage] # Here we are linking both models with an inline

Now We are going to work on the forms.py to handle multiple images upload

from .models import ProductImage

class ProductImageForm(forms.ModelForm):
      class Meta:
            model = ProductImage
            fields = ['image']
            widgets ={'image' :forms.ClearableFileInput(attrs={'multiple':True})}

Finally we focus on the view to manipulate uploads for our images, what you have done  so far is good and but there's another way of uploading multiple images, this has worked for me in many cases!

from .forms import ProductImageForm

def create_product(request):
    if request.user.is_superuser:
        if request.method == 'POST':
            data = request.POST
            images = request.FILES.getlist('images')
            brand = Brands.objects.get(name=data['brand'])
            category =  Categories.objects.get(name=data['category'])
            form = ProductImageForm(request.POST, request.FILES)
            product = Products(product_name = data['product-name'],brand=brand,
                price = data['price'],
                description = data['desc'],
                category = category,
                product_image = images[0],)
            product.save()
            if form.is_valid():
               data = form.save(commit=False)
               for files in images:
                   data =ProductImage(product = product, image = files)
                   data.save()
                   return render(request, 'store/create_product.html')
            else:
                   return HttpResponse("You are not allowed here")


问:
How to search contents of multiple pdf files?
How could I search the contents of PDF files in a directory/subdirectory? I am looking for some command line tools. It seems that grep can't search PDF files.

答:
Thanks for all the good ideas here!

I tried the xargs method, but as pointed out here, xargs will make it impossible (or very hard) to include printing the actual file name...

So I tried the whole thing with GNU parallel.

```<code>parallel "pdftotext -q {} - | grep --with-filename --label='['{}']' --color=always --context=5 'pattern'" ::: *.pdf
</code>```

This prints not only the pattern, but with --context=5 also 5 lines above and below as well for context.

With -q pdftotext won't print any error messages or warnings (quiet).

I use brackets [] as labels instead of braces {}. If you wanted braces --label='{'{}'}' will make that happen. Note that {} is replaced by the actual filename by GNU parallel, e.g. 'Example portable document file name with spaces.pdf' ({} is already using single quotes ').

By using --label={} only the filename will be printed, which may be the favored way of displaying the filename.

I also noticed that the output was without color when I tried it, except when forcing it by adding --color=always with grep.

It may be useful to add --ignore-case to the grep command for a case-insensitive keyword search.

If all PDF files should be processed recursively, including all sub-directories in the current directory (.), this can be accomplished through find:

```<code>find . -type f -iname '*.pdf' -print0 | parallel -0 "pdftotext -q {} - | grep --with-filename --label='['{}']' --color=always --context=5 'pattern'"
</code>```

With find, -iname '*.pdf' acts case-insensitive. With -name '*.pdf' only lower-case .pdf files will be included (the normal case). Since I sometimes also encountered Windows PDF-files with an upper-case .PDF file extension, I tend to prefer -iname...

The above command also works with the -print find option (instead of -print0), so it will be line-based (one file name per line), then -0 (NUL delimiter) must be omitted from the parallel command.

Again, including --ignore-case in the grep command will make the search case-insensitive.

As a general recommendation when playing with the whole command line, parallel --dry-run will print which commands would be executed.

```<code>$ find . -type f -iname '*.pdf' -print0 | parallel --dry-run -0 "pdftotext -q {} - | grep --with-filename --label='['{}']' --color=always --ignore-case --context=5 'pattern'"
pdftotext -q ./test PDF file 1.pdf - | grep --with-filename --label='['./test PDF file 1.pdf']' --color=always --ignore-case --context=5 'pattern'
pdftotext -q ./subdir1/test PDF file 2.pdf - | grep --with-filename --label='['./subdir1/test PDF file 2.pdf']' --color=always --ignore-case --context=5 'pattern'
pdftotext -q ./subdir2/test PDF file 3.pdf - | grep --with-filename --label='['./subdir2/test PDF file 3.pdf']' --color=always --ignore-case --context=5 'pattern'
</code>```

Body:
Thanks for all the good ideas here!

I tried the xargs method, but as pointed out here, xargs will make it impossible (or very hard) to include printing the actual file name...

So I tried the whole thing with GNU parallel.

parallel "pdftotext -q {} - | grep --with-filename --label='['{}']' --color=always --context=5 'pattern'" ::: *.pdf

This prints not only the pattern, but with --context=5 also 5 lines above and below as well for context.

With -q pdftotext won't print any error messages or warnings (quiet).

I use brackets [] as labels instead of braces {}. If you wanted braces --label='{'{}'}' will make that happen. Note that {} is replaced by the actual filename by GNU parallel, e.g. 'Example portable document file name with spaces.pdf' ({} is already using single quotes ').

By using --label={} only the filename will be printed, which may be the favored way of displaying the filename.

I also noticed that the output was without color when I tried it, except when forcing it by adding --color=always with grep.

It may be useful to add --ignore-case to the grep command for a case-insensitive keyword search.

If all PDF files should be processed recursively, including all sub-directories in the current directory (.), this can be accomplished through find:

find . -type f -iname '*.pdf' -print0 | parallel -0 "pdftotext -q {} - | grep --with-filename --label='['{}']' --color=always --context=5 'pattern'"

With find, -iname '*.pdf' acts case-insensitive. With -name '*.pdf' only lower-case .pdf files will be included (the normal case). Since I sometimes also encountered Windows PDF-files with an upper-case .PDF file extension, I tend to prefer -iname...

The above command also works with the -print find option (instead of -print0), so it will be line-based (one file name per line), then -0 (NUL delimiter) must be omitted from the parallel command.

Again, including --ignore-case in the grep command will make the search case-insensitive.

As a general recommendation when playing with the whole command line, parallel --dry-run will print which commands would be executed.

$ find . -type f -iname '*.pdf' -print0 | parallel --dry-run -0 "pdftotext -q {} - | grep --with-filename --label='['{}']' --color=always --ignore-case --context=5 'pattern'"
pdftotext -q ./test PDF file 1.pdf - | grep --with-filename --label='['./test PDF file 1.pdf']' --color=always --ignore-case --context=5 'pattern'
pdftotext -q ./subdir1/test PDF file 2.pdf - | grep --with-filename --label='['./subdir1/test PDF file 2.pdf']' --color=always --ignore-case --context=5 'pattern'
pdftotext -q ./subdir2/test PDF file 3.pdf - | grep --with-filename --label='['./subdir2/test PDF file 3.pdf']' --color=always --ignore-case --context=5 'pattern'


问:
jQuery .click() event for multiple div's
I have some search results that I'm outputting that are of this form:

```<code>  <div id="result" title="nCgQDjiotG0"><img src="http://i.ytimg.com/vi/nCgQDjiotG0/default.jpg"></div>
</code>```

There is one of these for each result. I'm trying to detect which one is clicked and then do some stuff. Each result has a unique title, but the same id. How do I use .click() to know which one was clicked so I can get it's ID and use it?

Here's how I'm getting the HTML from above:

```<code>$.each(response.data.items, function(i,data)
{
var video_id=data.id;
var video_title=data.title;
var video_thumb=data.thumbnail.sqDefault;

var search_results="<div id='result' title='"+video_id+"'><img src='"+video_thumb+"'></div>";
$("#searchresults").append($(search_results));
</code>```

I tried

```<code> $('div').click(function(){
    alert(this.id);
});
</code>```

and the alert says "searchresults" (no quotes).

答: you could get the title using $(this).attr("title").val()

Body:
I have some search results that I'm outputting that are of this form:

There is one of these for each result. I'm trying to detect which one is clicked and then do some stuff. Each result has a unique title, but the same id. How do I use .click() to know which one was clicked so I can get it's ID and use it?

Here's how I'm getting the HTML from above:

$.each(response.data.items, function(i,data)
{
var video_id=data.id;
var video_title=data.title;
var video_thumb=data.thumbnail.sqDefault;

var search_results="

";
$("#searchresults").append($(search_results));

I tried

 $('div').click(function(){
    alert(this.id);
});

and the alert says "searchresults" (no quotes).