问:
issue accessing elements of hash in perl
I have the below hash:

```<code>my %releaseMap = {"rel1.2.3" => {
                                    "supporedPorts" => ["lnx86", "lnppc"],
                                    "branch"        => ["DEV"],
                                },

                  "rel2.4" =>   {
                                    "supporedPorts" => ["lnx86", "lnppc"],
                                    "branch"        => ["DEV"],
                                }
                 };
</code>```

I want to get the values rel1.2.3 and rel2.4 in the variable $rel, I want to get the values lnx86 and lnppc in $port and I want to get the value DEV in $branch.

I am new to the Hash concept in perl, I am not able to figure out how this can be done.

Can someone please help. Thanks

答:
A hash is initialised from a list:

```<code>my %hash = ( key => value, ... );
</code>```

A hash reference is initialised using the anonymous hash constructor:

```<code>my $hash_ref = { key => value, ... };
</code>```

You are initialising your hash with an anonymous hash constructor. This does not work as you expect it. You end up with a hash containing a single key (which is the stringification of the anonymous hash reference:

```<code>my %hash = { key => value, ... };
</code>```

If you change your code to this:

```<code>my %releaseMap = ("rel1.2.3" => {
                                    "supporedPorts" => ["lnx86", "lnppc"],
                                    "branch"        => ["DEV"],
                                },

                  "rel2.4" =>   {
                                    "supporedPorts" => ["lnx86", "lnppc"],
                                    "branch"        => ["DEV"],
                                }
                 );
</code>```

Then things get easier. You can start with:

```<code>foreach my $key (keys %releaseMap) {
  say $key;
}
</code>```

Also, add use strict and use warnings to your code. They will catch a lot of problems for you.

Body:
I have the below hash:

my %releaseMap = {"rel1.2.3" => {
                                    "supporedPorts" => ["lnx86", "lnppc"],
                                    "branch"        => ["DEV"],
                                },

                  "rel2.4" =>   {
                                    "supporedPorts" => ["lnx86", "lnppc"],
                                    "branch"        => ["DEV"],
                                }
                 };

I want to get the values rel1.2.3 and rel2.4 in the variable $rel, I want to get the values lnx86 and lnppc in $port and I want to get the value DEV in $branch.

I am new to the Hash concept in perl, I am not able to figure out how this can be done.

Can someone please help. Thanks

Body:
A hash is initialised from a list:

my %hash = ( key => value, ... );

A hash reference is initialised using the anonymous hash constructor:

my $hash_ref = { key => value, ... };

You are initialising your hash with an anonymous hash constructor. This does not work as you expect it. You end up with a hash containing a single key (which is the stringification of the anonymous hash reference:

my %hash = { key => value, ... };

If you change your code to this:

my %releaseMap = ("rel1.2.3" => {
                                    "supporedPorts" => ["lnx86", "lnppc"],
                                    "branch"        => ["DEV"],
                                },

                  "rel2.4" =>   {
                                    "supporedPorts" => ["lnx86", "lnppc"],
                                    "branch"        => ["DEV"],
                                }
                 );

Then things get easier. You can start with:

foreach my $key (keys %releaseMap) {
  say $key;
}

Also, add use strict and use warnings to your code. They will catch a lot of problems for you.


来源: stackexchange

问:
C console application print out $ dollar sign
This is my program:

```<code>#include <stdio.h>
#include <stdlib.h>

int main ()
{
    printf("%c", "\n");
}
</code>```

I need to know why is it printing $ on the output,

答:
%c is for printing a char value, but "\n" is a string, which is char*.

Either use %s to print a string, or use '\n' to make a char value.

ContentLicense: CC BY-SA 4.0

Body:
This is my program:

#include <stdio.h>
#include <stdlib.h>

int main ()
{
    printf("%c", "\n");
}

I need to know why is it printing $ on the output,


问:
Select multiple columns from MySql to Java
I have a MySql database which contains a VARCHAR field (called nev here) and a couple INTs

What I want is select all of the integers which columns contains 'w' (w0, w1 etc) and put it into an array or an ArrayList. And also select those which has 'b' in the columns. And I want to only select those values whose has a specific 'nev' which comes from another class.

Here is my code so far:

```<code>public static Connection qry(){
        Connection qry=null;
        try {
           qry=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/feladat","admin","admin");
           String query ="SELECT * FROM pontszamok WHERE nev="+GUI.selected;
           Statement st2;
           st2 = qry.createStatement();
           ResultSet rs = st2.executeQuery(query);

            while (rs.next())
            {

            }
            st2.close();
        } catch (SQLException e) {
            System.out.println(e);
        }
        return qry;
</code>```

What should be the solution?

答:
This is an example how you get the values of the column w0 and nev and store them into a List, you can do the same way for all the columns you want

```<code>List<Integer> myValuesW0 = new ArrayList<Integer>();
List<String> myValuesNev = new ArrayList<String>();

while (rs.next())
{
     myValuesW0.add(rs.getInt("w0")); //the name of the column not the value
     myValuesNev.add(rs.getString("nev")); //for String Values
     .
     .
     //the same treatment for the rest
}
</code>```

Also you have an error in your query, since "nev" is a varchar type, so you have to apply single quotation marks  ( ' ' ) on the value this way:

```<code>String query ="SELECT * FROM pontszamok WHERE nev= '"+GUI.selected+"' ";
</code>```

or you can use this method too:

```<code>String query ="SELECT * FROM pontszamok WHERE nev= ? ";
query.setParameter(1, GUI.selected);
//replace the first question mark (?) with the variable GUI.selected
//this way you can avoid being confused between the quotation marks
</code>```

Body:
I have a MySql database which contains a VARCHAR field (called nev here) and a couple INTs

What I want is select all of the integers which columns contains 'w' (w0, w1 etc) and put it into an array or an ArrayList. And also select those which has 'b' in the columns. And I want to only select those values whose has a specific 'nev' which comes from another class.

Here is my code so far:

public static Connection qry(){
        Connection qry=null;
        try {
           qry=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/feladat","admin","admin");
           String query ="SELECT * FROM pontszamok WHERE nev="+GUI.selected;
           Statement st2;
           st2 = qry.createStatement();
           ResultSet rs = st2.executeQuery(query);

            while (rs.next())
            {

            }
            st2.close();
        } catch (SQLException e) {
            System.out.println(e);
        }
        return qry;

What should be the solution?

Body:
This is an example how you get the values of the column w0 and nev and store them into a List, you can do the same way for all the columns you want

List<Integer> myValuesW0 = new ArrayList<Integer>();
List<String> myValuesNev = new ArrayList<String>();

while (rs.next())
{
     myValuesW0.add(rs.getInt("w0")); //the name of the column not the value
     myValuesNev.add(rs.getString("nev")); //for String Values
     .
     .
     //the same treatment for the rest
}

Also you have an error in your query, since "nev" is a varchar type, so you have to apply single quotation marks  ( ' ' ) on the value this way:

String query ="SELECT * FROM pontszamok WHERE nev= '"+GUI.selected+"' ";

or you can use this method too:

String query ="SELECT * FROM pontszamok WHERE nev= ? ";
query.setParameter(1, GUI.selected);
//replace the first question mark (?) with the variable GUI.selected
//this way you can avoid being confused between the quotation marks


问:
Subquery with multiple sorted results
Struggling on a most probably very simple query for MS Access, but couldn't nail it for 3 days already.

Any help would be highly appreciated..

There are 2 tables - Regions (REGNAME) and Cities (REGNAME, NAME, POPULATION)

I need to get the top 10 cities sorted by the population in descending order for each region.

There's no problem to do this for some certain Region:

```<code>SELECT TOP 10 Cities.REGNAME, NAME from Cities, Regions
WHERE Cities.REGNAME = Regions.REGNAME
AND Regions.REGNAME = 'SOME_REGION_NAME'
ORDER BY POPULATION DESC
</code>```

But I need to see the similar list of Cities for any number of Regions.
For every region in subquery I should see sorded 10 cities' list.

Like below:

```<code>SOME_REGION_NAME - CITY 1
SOME_REGION_NAME - CITY 2
SOME_REGION_NAME - ..
SOME_REGION_NAME - CITY 10

ANOTHER_REGION_NAME - CITY 1
ANOTHER_REGION_NAME - CITY 2
ANOTHER_REGION_NAME - ..
ANOTHER_REGION_NAME - CITY 10

SOME_OTHER_REGION_NAME - CITY 1
SOME_OTHER_REGION_NAME - CITY 2
SOME_OTHER_REGION_NAME - ..
SOME_OTHER_REGION_NAME - CITY 10
</code>```

This query gives 10 cities in total from 3 regions:

```<code>SELECT TOP 10 Cities.REGNAME, NAME from Cities, Regions
WHERE Cities.REGNAME = Regions.REGNAME
AND Regions.REGNAME IN ('SOME_REGION_NAME' , 'ANOTHER_REGION_NAME', 'SOME_OTHER_REGION_NAME')
ORDER BY POPULATION DESC
</code>```

But I expect to see a 30 cities table, not 10.

Please, someone, show me the way :)

Thank you

答:
You can use a sub-query to select the top 10 cities for each region:

```<code>SELECT R.REGNAME, C.NAME, C.POPULATION
FROM Cities AS C INNER JOIN Regions AS R ON C.REGNAME = R.REGNAME
WHERE C.NAME IN (SELECT TOP 10 [NAME] FROM Cities AS C1 WHERE C1.REGNAME=R.REGNAME ORDER BY C1.POPULATION DESC)
ORDER BY R.REGNAME ASC, C.POPULATION DESC
</code>```

You may get more than 10 cities being returned for a region if there is a tie on the population.

Note that as well as it being better to use a foreign key to store the region in the cities table, NAME is a reserved word in Access, so you should rename the field - in the example SQL, I've just wrapped it in square brackets.

Regards,

Title: Subquery with multiple sorted results

Body:
Struggling on a most probably very simple query for MS Access, but couldn't nail it for 3 days already.

Any help would be highly appreciated..

There are 2 tables - Regions (REGNAME) and Cities (REGNAME, NAME, POPULATION)

I need to get the top 10 cities sorted by the population in descending order for each region.

There's no problem to do this for some certain Region:

SELECT TOP 10 Cities.REGNAME, NAME from Cities, Regions
WHERE Cities.REGNAME = Regions.REGNAME
AND Regions.REGNAME = 'SOME_REGION_NAME'
ORDER BY POPULATION DESC

But I need to see the similar list of Cities for any number of Regions.
For every region in subquery I should see sorded 10 cities' list.

Like below:

SOME_REGION_NAME - CITY 1
SOME_REGION_NAME - CITY 2
SOME_REGION_NAME - ..
SOME_REGION_NAME - CITY 10

ANOTHER_REGION_NAME - CITY 1
ANOTHER_REGION_NAME - CITY 2
ANOTHER_REGION_NAME - ..
ANOTHER_REGION_NAME - CITY 10

SOME_OTHER_REGION_NAME - CITY 1
SOME_OTHER_REGION_NAME - CITY 2
SOME_OTHER_REGION_NAME - ..
SOME_OTHER_REGION_NAME - CITY 10

This query gives 10 cities in total from 3 regions:

SELECT TOP 10 Cities.REGNAME, NAME from Cities, Regions
WHERE Cities.REGNAME = Regions.REGNAME
AND Regions.REGNAME IN ('SOME_REGION_NAME' , 'ANOTHER_REGION_NAME', 'SOME_OTHER_REGION_NAME')
ORDER BY POPULATION DESC

But I expect to see a 30 cities table, not 10.

Please, someone, show me the way :)

Thank you

Body:
You can use a sub-query to select the top 10 cities for each region:

SELECT R.REGNAME, C.NAME, C.POPULATION
FROM Cities AS C INNER JOIN Regions AS R ON C.REGNAME = R.REGNAME
WHERE C.NAME IN (SELECT TOP 10 [NAME] FROM Cities AS C1 WHERE C1.REGNAME=R.REGNAME ORDER BY C1.POPULATION DESC)
ORDER BY R.REGNAME ASC, C.POPULATION DESC

You may get more than 10 cities being returned for a region if there is a tie on the population.

Note that as well as it being better to use a foreign key to store the region in the cities table, NAME is a reserved word in Access, so you should rename the field - in the example SQL, I've just wrapped it in square brackets.

Regards,


问:
R fill in new column by filtered value by group
I want to create new column in my dat, filled in by values
satisfying a condition. So, I want to keep the value where where regime == "SA" and fill this value over the whole group in new column vals.sa.

This combines the filter and mutate, but I am unsure what is their correct combination? Filter just keeps rows satisfying condition, but how can I expand this value over all rows in a group?

My data:

```<code>dat <- data.frame(id = c(1,1,2,2,2,2,3,3),
                  regime = c("SA", "B", "SA", "B", "C", "F", "SA", "D"),
                  value = c(3,5,1,2,5,6,7,8))
</code>```

Process the data using dplyr

```<code>dat %>%
  # group data by id
  group_by(id) %>%
  # how to write this condition and get values instead or TRUE/FALSE?
  mutate(val.sa = regime == "SA")
</code>```

Expected output with filled in val.sa value corresponding regime == "SA"

```<code>     id regime value val.sa
  <dbl> <fct>  <dbl>  <dbl>
1     1 SA         3      3
2     1 B          5      3
3     2 SA         1      1
4     2 B          2      1
5     2 C          5      1
6     2 F          6      1
7     3 SA         7      7
8     3 D          8      7
</code>```

答:
You can use :

```<code>library(dplyr)
dat %>%
  group_by(id) %>%
  mutate(value.sa = value[regime == 'SA'])
  #OR
  #mutate(value.sa = value[match('SA', regime)])

#     id regime value value.sa
#  <dbl> <chr>  <dbl>    <dbl>
#1     1 SA         3        3
#2     1 B          5        3
#3     2 SA         1        1
#4     2 B          2        1
#5     2 C          5        1
#6     2 F          6        1
#7     3 SA         7        7
#8     3 D          8        7
</code>```

If there could be more than one regime in a group where it has value "SA", you can select the first value using which.max/match.

```<code>dat %>%
  group_by(id) %>%
  mutate(value.sa = value[which.max(regime == 'SA')])
</code>```

Body:
I want to create new column in my dat, filled in by values
satisfying a condition. So, I want to keep the value where where regime == "SA" and fill this value over the whole group in new column vals.sa.

This combines the filter and mutate, but I am unsure what is their correct combination? Filter just keeps rows satisfying condition, but how can I expand this value over all rows in a group?

My data:

dat <- data.frame(id = c(1,1,2,2,2,2,3,3),
                  regime = c("SA", "B", "SA", "B", "C", "F", "SA", "D"),
                  value = c(3,5,1,2,5,6,7,8))

Process the data using dplyr

dat %>%
  # group data by id
  group_by(id) %>%
  # how to write this condition and get values instead or TRUE/FALSE?
  mutate(val.sa = regime == "SA")

Expected output with filled in val.sa value corresponding regime == "SA"

     id regime value val.sa
  <dbl> <fct>  <dbl>  <dbl>
1     1 SA         3      3
2     1 B          5      3
3     2 SA         1      1
4     2 B          2      1
5     2 C          5      1
6     2 F          6      1
7     3 SA         7      7
8     3 D          8      7

Body:
You can use :

library(dplyr)
dat %>%
  group_by(id) %>%
  mutate(value.sa = value[regime == 'SA'])
  #OR
  #mutate(value.sa = value[match('SA', regime)])

#     id regime value value.sa
#  <dbl> <chr>  <dbl>    <dbl>
#1     1 SA         3        3
#2     1 B          5        3
#3     2 SA         1        1
#4     2 B          2        1
#5     2 C          5        1
#6     2 F          6        1
#7     3 SA         7        7
#8     3 D          8        7

If there could be more than one regime in a group where it has value "SA", you can select the first value using which.max/match.

dat %>%
  group_by(id) %>%
  mutate(value.sa = value[which.max(regime == 'SA')])


问:
Why is the training accuracy fluctuating?
I'm working with a video classification of 5 classes and using TimeDistributed CNN model in Google Colab platform. The training dataset contains 80 videos containing 5 frames each. The validation dataset contains 20 videos containing 5 frames each. The batch size I used is 64. So, in total, I'm working with 100 videos. I compiled the model using Adam optimizer and categorical cross_entropy loss.

```<code>model = Sequential()

input_shape=(5, 128, 128, 3)

model.add(TimeDistributed(Conv2D(32, (3, 3), strides=(1, 1),
            activation='relu', padding='same'), input_shape=input_shape))
model.add(TimeDistributed(MaxPooling2D((2, 2))))
model.add(TimeDistributed(Conv2D(64, (3, 3), strides=(1, 1),
            activation='relu', padding='same')))
model.add(TimeDistributed(Conv2D(128, (3, 3), strides=(1, 1),
            activation='relu', padding='same')))
model.add(TimeDistributed(BatchNormalization()))
model.add(TimeDistributed(MaxPooling2D((2, 2))))
model.add(TimeDistributed(Flatten()))

model.add(GRU(64, return_sequences=False))

model.add(BatchNormalization())

model.add((Dense(128, activation='relu')))
model.add(Dense(5, activation='softmax'))

from tensorflow.keras.optimizers import Adam

model.compile(loss='categorical_crossentropy',
              optimizer=Adam(lr=0.0001),
              metrics=['accuracy'])
</code>```

But, after fitting this model with the dataset, the training accuracy curve is fluctuating like this:

Can anyone help me out to understand the reason behind this fluctuation?

答:
You can try one or two things to stabilize the training:

You can try different batch sizes of 4, 8, 16, 32, 64. You can generate different plots. Have a look at this link. It'll generate mini plots for each batch size.

You can also alter the learning rate. You can apply Learning Rate scheduler or Reduce LR on plateau by directly calling keras callbacks. Alternatively, there is Cyclic LR that try to finds out the optimal learning rate. paper Github

Body:
I'm working with a video classification of 5 classes and using TimeDistributed CNN model in Google Colab platform. The training dataset contains 80 videos containing 5 frames each. The validation dataset contains 20 videos containing 5 frames each. The batch size I used is 64. So, in total, I'm working with 100 videos. I compiled the model using Adam optimizer and categorical cross_entropy loss.

model = Sequential()

input_shape=(5, 128, 128, 3)

model.add(TimeDistributed(Conv2D(32, (3, 3), strides=(1, 1),
            activation='relu', padding='same'), input_shape=input_shape))
model.add(TimeDistributed(MaxPooling2D((2, 2))))
model.add(TimeDistributed(Conv2D(64, (3, 3), strides=(1, 1),
            activation='relu', padding='same')))
model.add(TimeDistributed(Conv2D(128, (3, 3), strides=(1, 1),
            activation='relu', padding='same')))
model.add(TimeDistributed(BatchNormalization()))
model.add(TimeDistributed(MaxPooling2D((2, 2))))
model.add(TimeDistributed(Flatten()))

model.add(GRU(64, return_sequences=False))

model.add(BatchNormalization())

model.add((Dense(128, activation='relu')))
model.add(Dense(5, activation='softmax'))

from tensorflow.keras.optimizers import Adam

model.compile(loss='categorical_crossentropy',
              optimizer=Adam(lr=0.0001),
              metrics=['accuracy'])

But, after fitting this model with the dataset, the training accuracy curve is fluctuating like this:

Can anyone help me out to understand the reason behind this fluctuation?


问:
MySQL Text formatting
Hej guys,

I wrote a little php script which access a database and simply displays the rows which where found for a given query. It echos a table with them but it seems there are some typeset errors resulting in questionsmarks. Any hint what I could do to solve this? Here's a screenshot:  Text Formatting">

Here's the code I'm using to fetch and display the data

```<code>$result = mysql_query($sql);
        if(mysql_num_rows($result)>0){
            echo "<div style='float:top;clear:both;'>";
            echo "<table border='1'>";
            echo "<th>id</th><th>project</th><th>publisher</th><th>country</th><th>contact</th><th>mail</th><th>agent</th><th>report</th><th>todo</th><th>by who</th><th>done(date,text)</th><th>priority</th>";
            while($row = mysql_fetch_array($result)){
                echo "<tr>";
                echo "<td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td><td>".$row[3]."</td><td>".$row[4]."</td><td>".$row[5]."</td><td>".$row[6]."</td><td>".$row[7]."</td><td>".$row[8]."</td><td>".$row[9]."</td><td>".$row[10]."</td><td>".$row[11]."</td>";
                echo "<td><form method='POST' action='insert.php'><input type='submit' name='edit' value='edit'/><input type='hidden' name='hiddenID' value='".$row[0]."' /><input type='hidden' name='hiddenDB' value='".$_POST['db']."' /><input type='hidden' name='hiddenProject' value='".$row[1]."' /><input type='hidden' name='hiddenPublisher' value='".$row[2]."' /><input type='hidden' name='hiddenCountry' value='".$row[3]."' /><input type='hidden' name='hiddenContact' value='".$row[4]."' /><input type='hidden' name='hiddenMail' value='".$row[5]."' /><input type='hidden' name='hiddenAgent' value='".$row[6]."' /><input type='hidden' name='hiddenReport' value='".$row[7]."' /><input type='hidden' name='hiddenTodo' value='".$row[8]."' /><input type='hidden' name='hiddenBywho' value='".$row[9]."' /><input type='hidden' name='hiddenDone' value='".$row[10]."' /><input type='hidden' name='hiddenPriority' value='".$row[11]."' /></form></td>";
                echo "</tr>";
            }
            echo "</table>";
            echo "</div>";
</code>```

p.s.: It seems special chars like the german "ß" also aren¿t getting inserted properly into the database when I inspect the datasets using phpmyadmin

答:
as for displaying data, same issue for cyrillic chars is solved by running next code before getting data from DB:

```<code> mysql_query ("set character_set_client='cp1251'");
 mysql_query ("set character_set_results='cp1251'");
 mysql_query ("set collation_connection='cp1251_general_ci'");
</code>```

Use appropriate german charset for your case.

ContentLicense: CC BY-SA 3.0

Title: MySQL Text formatting

Body:
Hej guys,

I wrote a little php script which access a database and simply displays the rows which where found for a given query. It echos a table with them but it seems there are some typeset errors resulting in questionsmarks. Any hint what I could do to solve this? Here's a screenshot:  Text Formatting">

Here's the code I'm using to fetch and display the data

$result = mysql_query($sql);
        if(mysql_num_rows($result)>0){
            echo "
";
            echo "
";
            echo "id	project	publisher	country	contact	mail	agent	report	todo	by who	done(date,text)	priority	";
            while($row = mysql_fetch_array($result)){
                echo "
";
                echo "".$row[0]."	".$row[1]."	".$row[2]."	".$row[3]."	".$row[4]."	".$row[5]."	".$row[6]."	".$row[7]."	".$row[8]."	".$row[9]."	".$row[10]."	".$row[11]."	";
                echo "<form method='POST' action='insert.php'><input type='submit' name='edit' value='edit'/><input type='hidden' name='hiddenID' value='".$row[0]."' /><input type='hidden' name='hiddenDB' value='".$_POST['db']."' /><input type='hidden' name='hiddenProject' value='".$row[1]."' /><input type='hidden' name='hiddenPublisher' value='".$row[2]."' /><input type='hidden' name='hiddenCountry' value='".$row[3]."' /><input type='hidden' name='hiddenContact' value='".$row[4]."' /><input type='hidden' name='hiddenMail' value='".$row[5]."' /><input type='hidden' name='hiddenAgent' value='".$row[6]."' /><input type='hidden' name='hiddenReport' value='".$row[7]."' /><input type='hidden' name='hiddenTodo' value='".$row[8]."' /><input type='hidden' name='hiddenBywho' value='".$row[9]."' /><input type='hidden' name='hiddenDone' value='".$row[10]."' /><input type='hidden' name='hiddenPriority' value='".$row[11]."' /></form>	";
                echo "
";
            }
            echo "
";
            echo "
";

p.s.: It seems special chars like the german "ß" also aren¿t getting inserted properly into the database when I inspect the datasets using phpmyadmin

Body:
as for displaying data, same issue for cyrillic chars is solved by running next code before getting data from DB:

 mysql_query ("set character_set_client='cp1251'");
 mysql_query ("set character_set_results='cp1251'");
 mysql_query ("set collation_connection='cp1251_general_ci'");

Use appropriate german charset for your case.


问:
Javascript promise implementation
Whats best way to implement below in javascript.

```<code>/*
  A --|
      |-- D --|
  B --|       |-- E
              |
  C ----------|
</code>```

Each node is a async job, illustrated by setTimeout.

A, B, and C can run at the same time.

D, needs to wait for A and B to be done.

E needs to wait for C and D to be done.

How can I implement an interface which accepts the above nodes as args, which would take care of above implementation. Not sure what's best to implement whether async/await or JavaScript promise can be used and pros/cons.

答:
<pre class="lang-js prettyprint-override"><code>        /*
          A --|
             |-- D --|
        B --|       |-- E
                   |
      C ----------|
        */
        let A = new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve("im from A");
            }, 0);
        });
        let B = new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve("im from B");
            }, 0);
        });
        let C = new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve("im from C");
            }, 0);
        });
        let D = new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve("im from D");
            }, 0);
        });
        let E = new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve("im from E");
            }, 0);
        });

        (async () => {
            let [stringOfA, stringOfB] = await Promise.all([A, B]);
            let [stringOfD, stringOfC] = await Promise.all([D, C]);
            let stringOfE = await E;
            console.log(stringOfA, stringOfB, stringOfC, stringOfD, stringOfE);
        })();
</code>```

Title: Javascript promise implementation

Body:
Whats best way to implement below in javascript.

/*
  A --|
      |-- D --|
  B --|       |-- E
              |
  C ----------|

Each node is a async job, illustrated by setTimeout.

A, B, and C can run at the same time.

D, needs to wait for A and B to be done.

E needs to wait for C and D to be done.

How can I implement an interface which accepts the above nodes as args, which would take care of above implementation. Not sure what's best to implement whether async/await or JavaScript promise can be used and pros/cons.


问:
Multiple Subscribers to event source observable - async pipe keeps subscribing and unsubscribing
Bit of a headscratcher for me:

basically I am implementing a simple angular app to display and reassign names to ids.

```<code> export class Assignment {
   name: string;
   id?: string;
 }
</code>```

for this the backend publishes the endpoints:

```<code>GET /assignments
> [{"1": "id-a"},{"2": ""}] // where "2" is unassigned

PUT /assignments/:name/:id

GET /stream
> text/event-stream of new assignments as type="update", data = {"name": "1", "id":"id-a"} ...
</code>```

The frontend has a service that exposes all these endpoints, with the stream one set up like this:

```<code>export class HttpService {
  private source: EventSource;

  constructor(private http: HttpClient, private zone: NgZone) {
    this.source = new EventSource('/stream');
  }
  ...
   public getStream(): Observable<Assignment> {
    return  new Observable(observer => {
      console.log('subscribed to stream');
      this.source.addEventListener('update',(evt: MessageEvent) =>
          this.zone.run(() => observer.next(JSON.parse(evt.data))));
      this.source.onerror = evt => observer.error(evt);
      return () => { console.log('unsubscribing'); }
    });
  }
}
</code>```

I created a component to hold one assignment quite simple

```<code>template: `<div> {{assignment.name}} = {{assignment.id}} <div>`
@Input() assignment: Assignment
</code>```

Now comes the catch, my app component is set up like this:

template:

```<code> <app-assignment *ngFor="let item of assignments" [assignment]="getUpdatesForName(item) | async"></app-assignment >
</code>```

component:

```<code>export class MainComponent implements OnInit {

  public selected: string;
  public assignments: Assignment[];
  public update$: Observable<Assignment>;

  constructor(private httpservice: HttpService) {
  }

  ngOnInit() {
    this.httpservice.getAssignments().subscribe( it => this.assignments = it);
    this.update$ = this.httpservice.getStream();
  }

  public selectSound(soundid: string) {
    this.selected = soundid;
  }

  public getUpdatesForName(assignment: Assignment): Observable<Assignment> {
    return concat(
      of( assignment ),
      this.update$.pipe(
        filter(it => it.name=== assignment.name)
      )
    );
  }
}
</code>```

The issue is that the moment I change an assignment via the rest API no update ever hits the UI.
Instead the log steadily fills up with the 'subscribed' and 'unsubscribed' messages.
So it seems the async pipe is subscribing and unsubscribing over and over again and never gets anything done.

My first assumption was, that always adding new listeners to the source would clog up something, so I tried holding an array of subscribers and just one message listener

```<code>   export class HttpService {
      private source: EventSource;
      private subscribers :Subscriber<Assignment>[] = [];

      constructor(private http: HttpClient, private zone: NgZone) {
        this.source = new EventSource('/stream');
        this.source.addEventListener('update',(evt: MessageEvent) => this.zone.run(() => this.subscribers.forEach(it => it.next(JSON.parse(evt.data)), false)));
        this.source.onerror = evt => console.log('error in stream' + evt)
      }
    ...
     public getStream(): Observable<Assignment> {
        return  new Observable(observer => {
          console.log('subscribed to stream');
          this.subscribers.push(observer)
          return () => {
           this.subscribers = this.subscribers.filter(it => it !== observer)
          };
        });
      }
</code>```

which didn't change anything.

The whole thing works as expected when I replace the async pipe with passing in the Observable and doing a subscribe(input => localmember = input) in OnInit of the child component

EDIT:

I did some tests and found, that using a replay subject makes it work for exactly the number of messages that fit the replay buffer.

So I assume the async pipe resubscribes each time a CD cycle happens and unsubs at the end of it? But how would it know when a new item gets emitted when it unsubscribes at the end of CD?

答:
ok I got it, but I can see someone having this issue and did not want to just delete my question.

basically, thanks to https://www.lucidchart.com/techblog/2019/10/14/angulars-async-pipe-intricacies/

where it says:

While not the main focus of this article, another important note here
  is that the async pipe will only return the value retrieved from the
  Promise if the input is still the exact same Promise instance. If
  you’re calling an async method, or a method that creates a new Promise
  every time it’s called, the async pipe will assume that any value it
  has is no longer relevant and thus will likely never produce a usable
  value.

SO the way I set it up, on CD, angular would re evaluate the input for the child component [assignment]="getUpdatesForName(item) | async".

This, because of the filter I want to pipe it through will always return a new Observable, causing the constant sub-unsub pattern, and never resulting in a usable value.

The solution was to create all the filtered Observables once and store them to a Map>.

Body:
Bit of a headscratcher for me:

basically I am implementing a simple angular app to display and reassign names to ids.

 export class Assignment {
   name: string;
   id?: string;
 }

for this the backend publishes the endpoints:

GET /assignments
> [{"1": "id-a"},{"2": ""}] // where "2" is unassigned

PUT /assignments/:name/:id

GET /stream
> text/event-stream of new assignments as type="update", data = {"name": "1", "id":"id-a"} ...

The frontend has a service that exposes all these endpoints, with the stream one set up like this:

export class HttpService {
  private source: EventSource;

  constructor(private http: HttpClient, private zone: NgZone) {
    this.source = new EventSource('/stream');
  }
  ...
   public getStream(): Observable<Assignment> {
    return  new Observable(observer => {
      console.log('subscribed to stream');
      this.source.addEventListener('update',(evt: MessageEvent) =>
          this.zone.run(() => observer.next(JSON.parse(evt.data))));
      this.source.onerror = evt => observer.error(evt);
      return () => { console.log('unsubscribing'); }
    });
  }
}

I created a component to hold one assignment quite simple

template: `<div> {{assignment.name}} = {{assignment.id}} <div>`
@Input() assignment: Assignment

Now comes the catch, my app component is set up like this:

template:

 <app-assignment *ngFor="let item of assignments" [assignment]="getUpdatesForName(item) | async"></app-assignment >

component:

export class MainComponent implements OnInit {

  public selected: string;
  public assignments: Assignment[];
  public update$: Observable<Assignment>;

  constructor(private httpservice: HttpService) {
  }

  ngOnInit() {
    this.httpservice.getAssignments().subscribe( it => this.assignments = it);
    this.update$ = this.httpservice.getStream();
  }

  public selectSound(soundid: string) {
    this.selected = soundid;
  }

  public getUpdatesForName(assignment: Assignment): Observable<Assignment> {
    return concat(
      of( assignment ),
      this.update$.pipe(
        filter(it => it.name=== assignment.name)
      )
    );
  }
}

The issue is that the moment I change an assignment via the rest API no update ever hits the UI.
Instead the log steadily fills up with the 'subscribed' and 'unsubscribed' messages.
So it seems the async pipe is subscribing and unsubscribing over and over again and never gets anything done.

My first assumption was, that always adding new listeners to the source would clog up something, so I tried holding an array of subscribers and just one message listener

   export class HttpService {
      private source: EventSource;
      private subscribers :Subscriber<Assignment>[] = [];

      constructor(private http: HttpClient, private zone: NgZone) {
        this.source = new EventSource('/stream');
        this.source.addEventListener('update',(evt: MessageEvent) => this.zone.run(() => this.subscribers.forEach(it => it.next(JSON.parse(evt.data)), false)));
        this.source.onerror = evt => console.log('error in stream' + evt)
      }
    ...
     public getStream(): Observable<Assignment> {
        return  new Observable(observer => {
          console.log('subscribed to stream');
          this.subscribers.push(observer)
          return () => {
           this.subscribers = this.subscribers.filter(it => it !== observer)
          };
        });
      }

which didn't change anything.

The whole thing works as expected when I replace the async pipe with passing in the Observable and doing a subscribe(input => localmember = input) in OnInit of the child component

EDIT:

I did some tests and found, that using a replay subject makes it work for exactly the number of messages that fit the replay buffer.

So I assume the async pipe resubscribes each time a CD cycle happens and unsubs at the end of it? But how would it know when a new item gets emitted when it unsubscribes at the end of CD?


问:
How do I run Node.js on port 80?
My aim is to run Node.js on port 80. This is because I am finding node.js is being blocked from certain networks which do not allow traffic from any other port.

It appears that the best way to do this is by proxying Apache through Node.js. I have tried using node-http-proxy to do this but I have not had any luck.

The code I am using is here:

```<code>var util = require('util'),
    http = require('http'),
    httpProxy = require('http-proxy');

httpProxy.createServer(9000, 'localhost').listen(80);

http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
  res.end();
}).listen(9000);
</code>```

But I keep getting the error "Address in use" for port 80. I must be doing something wrong.

How do I proxy Apache through node.js using node-http-proxy? Will this enable me to run node.js on port 80? And is node-http-proxy the best way to achieve this?

Thank you.

答:
If you are a non-root user, you cannot run or bind with ports lower than 1024 (in Unix system). To allow non-root user can run node on port lower than 1024 use this command.</p>

```<code>$ sudo setcap 'cap_net_bind_service=+ep' $(which node)
</code>```

Title: How do I run Node.js on port 80?

Body:
My aim is to run Node.js on port 80. This is because I am finding node.js is being blocked from certain networks which do not allow traffic from any other port.

It appears that the best way to do this is by proxying Apache through Node.js. I have tried using node-http-proxy to do this but I have not had any luck.

The code I am using is here:

var util = require('util'),
    http = require('http'),
    httpProxy = require('http-proxy');

httpProxy.createServer(9000, 'localhost').listen(80);

http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
  res.end();
}).listen(9000);

But I keep getting the error "Address in use" for port 80. I must be doing something wrong.

How do I proxy Apache through node.js using node-http-proxy? Will this enable me to run node.js on port 80? And is node-http-proxy the best way to achieve this?

Thank you.

Body:
If you are a non-root user, you cannot run or bind with ports lower than 1024 (in Unix system). To allow non-root user can run node on port lower than 1024 use this command.

$ sudo setcap 'cap_net_bind_service=+ep' $(which node)


问:
React Hooks infinite loop with Array
I'm having an infinite loop when I assign an array to a state in a useEffect hook in React and I'm not sure why as I'm adding the state series as a dependency.

```<code>const [series, setSeries] = useState([]);
useEffect(() => {
  setSeries([1, 2, 3, 4]);
}, [series]);
</code>```

The same code with a string doesn't create an infinite loop

```<code>const [series, setSeries] = useState([]);
useEffect(() => {
  setSeries('No Infinite Loop');
}, [series]);
</code>```

答:
you have added series depandancy in hooks and you'r updating series so whenever series update that hook is called . so, it is goes into infinite .</p>

```<code>const [series, setSeries] = useState([]);
useEffect(() => {
  setSeries([1, 2, 3, 4]);
}, []);
</code>```

Title: React Hooks infinite loop with Array

Body:
I'm having an infinite loop when I assign an array to a state in a useEffect hook in React and I'm not sure why as I'm adding the state series as a dependency.

const [series, setSeries] = useState([]);
useEffect(() => {
  setSeries([1, 2, 3, 4]);
}, [series]);

The same code with a string doesn't create an infinite loop

const [series, setSeries] = useState([]);
useEffect(() => {
  setSeries('No Infinite Loop');
}, [series]);

Body:
you have added series depandancy in hooks and you'r updating series so whenever series update that hook is called . so, it is goes into infinite .

const [series, setSeries] = useState([]);
useEffect(() => {
  setSeries([1, 2, 3, 4]);
}, []);


问:
Button not hitting if statement in Knockout js
I have the following button

```<code>    <div class="pull-right" data-bind="tooltip: { title: DashboardEdit, placement: 'top' }">
    <button class="btn actionButtonIcon" id="DashboardEdit" data-bind="click: changeButtonText">
        <figure>
            <img src="../../../Images/NotesPink.png" />
            <figcaption data-bind="text: $data.ProcurementbuttonText() ? 'Save': 'Edit'"></figcaption>
        </figure>
    </button>
</div>
</code>```

It changes text when clicked, now what i am trying to achieve is when the button text is showing Save then it should execute a function, so i tried this:

```<code>            self.ProcurementbuttonText = ko.observable(false);

        self.changeButtonText = function(){
            self.ProcurementbuttonText(!self.ProcurementbuttonText())
            if (self.ProcurementbuttonText() === 'Save'){
            var data = {
                'ScorecardId':ko.observable(localStorage.getItem('scorecardId'))(),
                'DashboardConfig':ko.observable(localStorage.getItem('ElementDataWidget'))()
            };
            PreferentialProcurementDashboardApi.Save(data);
        }
    }
</code>```

so when ProcurementButtonText = save then it should do all that which is in the if statement, but i see its never hitting that if statement

What am i doing wrong?

答:
I think the problem is with what you are expecting in self.ProcurementbuttonText() because you set it up with a boolean like so - self.ProcurementbuttonText(false); and then toggle it self.ProcurementbuttonText(!self.ProcurementbuttonText()) in the changeButtonText function.  the next line you are checking to see if it equals 'Save' which it will never equal to.  it will only be true or false.
so this check just needs to be

```<code>if (self.ProcurementbuttonText()){
    var data = {
        'ScorecardId':ko.observable(localStorage.getItem('scorecardId'))(),
        'DashboardConfig':ko.observable(localStorage.getItem('ElementDataWidget'))()
    };
    PreferentialProcurementDashboardApi.Save(data);
}
</code>```

I would recommend that you look at how you are naming your variables and what they are used for because self.ProcurementbuttonText is misrepresenting what it actually contains.  At the moment it contains the view/edit state of this record and not the text of the procurement button.

Body:
I have the following button

    <button class="btn actionButtonIcon" id="DashboardEdit" data-bind="click: changeButtonText">

    </button>

It changes text when clicked, now what i am trying to achieve is when the button text is showing Save then it should execute a function, so i tried this:

            self.ProcurementbuttonText = ko.observable(false);

        self.changeButtonText = function(){
            self.ProcurementbuttonText(!self.ProcurementbuttonText())
            if (self.ProcurementbuttonText() === 'Save'){
            var data = {
                'ScorecardId':ko.observable(localStorage.getItem('scorecardId'))(),
                'DashboardConfig':ko.observable(localStorage.getItem('ElementDataWidget'))()
            };
            PreferentialProcurementDashboardApi.Save(data);
        }
    }

so when ProcurementButtonText = save then it should do all that which is in the if statement, but i see its never hitting that if statement

What am i doing wrong?

Body:
I think the problem is with what you are expecting in self.ProcurementbuttonText() because you set it up with a boolean like so - self.ProcurementbuttonText(false); and then toggle it self.ProcurementbuttonText(!self.ProcurementbuttonText()) in the changeButtonText function.  the next line you are checking to see if it equals 'Save' which it will never equal to.  it will only be true or false.
so this check just needs to be

if (self.ProcurementbuttonText()){
    var data = {
        'ScorecardId':ko.observable(localStorage.getItem('scorecardId'))(),
        'DashboardConfig':ko.observable(localStorage.getItem('ElementDataWidget'))()
    };
    PreferentialProcurementDashboardApi.Save(data);
}

I would recommend that you look at how you are naming your variables and what they are used for because self.ProcurementbuttonText is misrepresenting what it actually contains.  At the moment it contains the view/edit state of this record and not the text of the procurement button.


问:
If I have a favicon, do I need to link to it?
I have a Favicon and in my page I have something like:

```<code><link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
</code>```

This works fine. But inspired by the book "Ultra Fast asp" I am trying to remove all the small bits that are not necessary. I read a lot about browsers looking for favicon.ico anyway. (People complaining about 404 errors if they do not have a favicon).

So I was wondering: what is the use of the link if the browser looks for it anyway. It is "dead wood" -> so can I just remove this link completely or am I missing something.

thanks for your ideas,
Pleun

答:
The standard specified by W3C uses the link tag rather than automagically look for the file in the root, but all major browsers will support both ways.

The Wikipedia article about favicon is a good overview of the possibilities and the browser support.

Body:
I have a Favicon and in my page I have something like:

<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />

This works fine. But inspired by the book "Ultra Fast asp" I am trying to remove all the small bits that are not necessary. I read a lot about browsers looking for favicon.ico anyway. (People complaining about 404 errors if they do not have a favicon).

So I was wondering: what is the use of the link if the browser looks for it anyway. It is "dead wood" -> so can I just remove this link completely or am I missing something.

thanks for your ideas,
Pleun


问:
What is meant by saying that String is a numeric type in android SQlite?
I specified columns datatype as String while creating database in my android project.I encountered the below lines as suggestions.What does that mean?

Using column type STRING; did you mean to use TEXT? (STRING is a numeric type and its value can be adjusted; for example, strings that look like integers can drop leading zeroes.

答:
Don't use the data type String because there is no such data type in SQLite.

Actually SQLite does not use data types but 5 storage classes for each value stored (not for each column):

NULL, INTEGER, REAL, TEXT and BLOB

Also SQLite assigns 1 of 5 type affinities to each column:

TEXT, NUMERIC, INTEGER, REAL, BLOB

and you should use any of these affinities when you define the data type of a column.

For your case the type affinity determined for a column defined as String, according to these rules:

If the declared type contains the string "INT" then it is assigned INTEGER affinity.

If the declared type of the column contains any of the strings "CHAR", "CLOB", or "TEXT" then that column has TEXT affinity. Notice that the type VARCHAR contains the string "CHAR" and is thus assigned TEXT affinity.

If the declared type for a column contains the string "BLOB" or if no type is specified then the column has affinity BLOB.

If the declared type for a column contains any of the strings "REAL", "FLOA", or "DOUB" then the column has REAL affinity.

Otherwise, the affinity is NUMERIC.

will be NUMERIC because none of the first 4 rules can be applied.

So change it to TEXT which is the suitable affinity.

You can find all about data types in SQLite here: Datatypes In SQLite Version 3


问:
How can I start a another activity in this Dialog?
I want when I click the 'OK' button I get to the 'PickSeatActivity'.
This is what I tried, but android studio underlines 'Intent' Object with a red line   </p>

```<code>        val builder = AlertDialog.Builder(this.requireActivity())

         // Dialog will have "Make a selection" as the title
         builder.setMessage("Details successfully captured.Do you wish to proceed and book your seat?")
             .setPositiveButton("OK") { dialogInterface: DialogInterface, i: Int ->
                 val intent = Intent(PickSeatActivity::class.java)
                 startActivity(intent)

             }
             // A "Cancel" button that does nothing
             .setNegativeButton("Cancel") { dialog, id ->
                 // Nothing happening here either
             }
</code>```

答:
packageContext is required:  public Intent(Context packageContext, Class<?> cls)

```<code>    val builder = AlertDialog.Builder(this.requireActivity())

     // Dialog will have "Make a selection" as the title
     builder.setMessage("Details successfully captured.Do you wish to proceed and book your seat?")
         .setPositiveButton("OK") { dialogInterface: DialogInterface, i: Int ->
             val intent = Intent(this.requireActivity(),PickSeatActivity::class.java)
             startActivity(intent)

         }
         // A "Cancel" button that does nothing
         .setNegativeButton("Cancel") { dialog, id ->
             // Nothing happening here either
         }
</code>```

Body:
I want when I click the 'OK' button I get to the 'PickSeatActivity'.
This is what I tried, but android studio underlines 'Intent' Object with a red line

        val builder = AlertDialog.Builder(this.requireActivity())

         // Dialog will have "Make a selection" as the title
         builder.setMessage("Details successfully captured.Do you wish to proceed and book your seat?")
             .setPositiveButton("OK") { dialogInterface: DialogInterface, i: Int ->
                 val intent = Intent(PickSeatActivity::class.java)
                 startActivity(intent)

             }
             // A "Cancel" button that does nothing
             .setNegativeButton("Cancel") { dialog, id ->
                 // Nothing happening here either
             }

Body:
packageContext is required:  public Intent(Context packageContext, Class<?> cls)

    val builder = AlertDialog.Builder(this.requireActivity())

     // Dialog will have "Make a selection" as the title
     builder.setMessage("Details successfully captured.Do you wish to proceed and book your seat?")
         .setPositiveButton("OK") { dialogInterface: DialogInterface, i: Int ->
             val intent = Intent(this.requireActivity(),PickSeatActivity::class.java)
             startActivity(intent)

         }
         // A "Cancel" button that does nothing
         .setNegativeButton("Cancel") { dialog, id ->
             // Nothing happening here either
         }


问:
Isn't there a multidimensional set library in Python?
I want to do a multidimensional set compute.
For example:

```<code>a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
</code>```

This one's set.difference is:

```<code>c = a - b
c = [1, 2]
</code>```

But when it's multi-dimensional, I don't know.
How do I do this?

```<code>a = [['a',1],['b',2],['c',3]]
b = [['a',2],['c',7],['d',5]]
</code>```

I want to calculate around a string.
I wish I could get this value.

```<code>c = a - b
c = [['b',2]]
</code>```

答:
You can try

```<code>[i for i in a if i[0] in {str(i[0]) for i in a}.difference({str(i[0]) for i in b})]
</code>```

Output

```<code>[['b', 2]]
</code>```

This code will return the item that is in the list a by the first elements that is not in the b list.

Body:
I want to do a multidimensional set compute.
For example:

a = [1, 2, 3, 4]
b = [3, 4, 5, 6]

This one's set.difference is:

c = a - b
c = [1, 2]

But when it's multi-dimensional, I don't know.
How do I do this?

a = [['a',1],['b',2],['c',3]]
b = [['a',2],['c',7],['d',5]]

I want to calculate around a string.
I wish I could get this value.

c = a - b
c = [['b',2]]

Body:
You can try

[i for i in a if i[0] in {str(i[0]) for i in a}.difference({str(i[0]) for i in b})]

Output

[['b', 2]]

This code will return the item that is in the list a by the first elements that is not in the b list.


答:
React does shallow equality check when it comes to state, unless defined otherwise.
When you do this setSeries([1, 2, 3, 4]);, you create the array [1, 2, 3, 4] every single time this effect is called, and since your useEffect depends on series, it will be called infinitly.

On the other hand, shallow comparing of the strings will not cause infinite loop as they are "shallow equal".

Title: React Hooks infinite loop with Array


问:
I can't create Question in python manage.py shell.(Django)
in models.py i have created class Question and then i want to create Question in models.py shell i am getting an error

models.py

```<code>from django.db import models, migrations

class Question(models.Model):
    author = models.CharField(max_length = 20)
    title = models.CharField(max_length = 30)
    body = models.TextField(null = True, blank = True)
    rating = 0
    category = models.CharField(max_length = 10)

class Migration(migrations.Migration):
    initial = True
    dependencies = []

    operations = [
        migrations.CreateModel (
            name = 'question',
            fields = [
                ('id', models.AutoField(auto_created=True,
                primary_key=True, serialize=False, verbose_name='ID')),
                ('author', models.CharField(max_length=20)),
                ('title', models.CharField(max_length = 30)),
                ('body', models.TextField(null = True, blank = True)),
                ('rating', 0),
                ('category', models.CharField(max_length = 10)),
            ],
        ),
    ]
</code>```

shell

```<code>>>> from f.models import Queston
>>> first_question =  first_question = Question(author = 'testUser', title = 'some question??', body = 'hey this is question body, category = 'some_category')

 File "<console>", line 1
    first_question = Question(author = 'testUser', title = 'some question??', body = 'hey this is question body, category = 'some_category')
</code>```

答:
You have an apostrophe missing. Try this instead:

```<code>first_question = Question(author = 'testUser', title = 'some question??', body = 'hey this is question body', category = 'some_category')
</code>```

If you look at the syntax highlighting in my response and yours, you can see the word 'category' is a different colour, this is an easy way to tell you've made a typo :)

Body:
in models.py i have created class Question and then i want to create Question in models.py shell i am getting an error

models.py

from django.db import models, migrations

class Question(models.Model):
    author = models.CharField(max_length = 20)
    title = models.CharField(max_length = 30)
    body = models.TextField(null = True, blank = True)
    rating = 0
    category = models.CharField(max_length = 10)

class Migration(migrations.Migration):
    initial = True
    dependencies = []

    operations = [
        migrations.CreateModel (
            name = 'question',
            fields = [
                ('id', models.AutoField(auto_created=True,
                primary_key=True, serialize=False, verbose_name='ID')),
                ('author', models.CharField(max_length=20)),
                ('title', models.CharField(max_length = 30)),
                ('body', models.TextField(null = True, blank = True)),
                ('rating', 0),
                ('category', models.CharField(max_length = 10)),
            ],
        ),
    ]

shell

>>> from f.models import Queston
>>> first_question =  first_question = Question(author = 'testUser', title = 'some question??', body = 'hey this is question body, category = 'some_category')

 File "<console>", line 1
    first_question = Question(author = 'testUser', title = 'some question??', body = 'hey this is question body, category = 'some_category')

Body:
You have an apostrophe missing. Try this instead:

first_question = Question(author = 'testUser', title = 'some question??', body = 'hey this is question body', category = 'some_category')

If you look at the syntax highlighting in my response and yours, you can see the word 'category' is a different colour, this is an easy way to tell you've made a typo :)


问:
stdout and need to flush it C++
I have some C++ code that uses cout statements for debug purposes and for some reason I can't get all the data to print unless I do a std::cout.flush(); at the end.

I don't quite understand why this flush operation is needed.

Anyone have any insight?

答:
To add to the other answers: your debugging statements should instead go to cerr, because:

it writes to the standard error, which means that, running the application, you can easily separate the "normal" program output from the errors/debug information via redirection;

most importantly, cerr by default is unbuffered, which means that, after each output operation, it will automatically flush itself, and in general this is desirable for errors and debug output.

(source: C++ standard, §27.3.1 ¶4-5, §27.4.2.1.2 table 83)

Title: stdout and need to flush it C++


问:
Problems using setMarginEnd and setMarginStart on Android
I'm trying to set some margins by code. Nevertheless I'm having troubles setting the Start and End margins. For a strange reason using the methods setMarginStart and setMarginEnd does not modify the view left and right margins. I'm attaching the code that I'm using:

```<code>    RelativeLayout.MarginLayoutParams  params = (RelativeLayout.MarginLayoutParams) loopMainLayout.getLayoutParams();
    float fabRadius = context.getResources().getDimension(R.dimen.fab_size) / 2;
    params.bottomMargin = (int) (params.bottomMargin + fabRadius);
    params.topMargin = (int) (params.topMargin + fabRadius);
    params.setMarginEnd(params.getMarginEnd() + (int) fabRadius);
    params.setMarginStart(params.getMarginStart() + (int)
    loopMainLayout.setLayoutParams(
</code>```

Am I missing any kind of function call here in order to let the layout calculate the end and start margins?

Note: If I use params.leftMargin and params.rightMargin everything woks as supposed. But I'm trying to use end and start margins as best practice.

答: A bit late to the party but I found a working solution for whoever will stumble upon this like me. You need to call setLayoutParams(LayoutParams) back on the view with the updated params as per documentation in the source code (look for MarginLayoutParams.startMargin|endMargin) MarginLayoutParams

Body:
I'm trying to set some margins by code. Nevertheless I'm having troubles setting the Start and End margins. For a strange reason using the methods setMarginStart and setMarginEnd does not modify the view left and right margins. I'm attaching the code that I'm using:

    RelativeLayout.MarginLayoutParams  params = (RelativeLayout.MarginLayoutParams) loopMainLayout.getLayoutParams();
    float fabRadius = context.getResources().getDimension(R.dimen.fab_size) / 2;
    params.bottomMargin = (int) (params.bottomMargin + fabRadius);
    params.topMargin = (int) (params.topMargin + fabRadius);
    params.setMarginEnd(params.getMarginEnd() + (int) fabRadius);
    params.setMarginStart(params.getMarginStart() + (int)
    loopMainLayout.setLayoutParams(

Am I missing any kind of function call here in order to let the layout calculate the end and start margins?

Note: If I use params.leftMargin and params.rightMargin everything woks as supposed. But I'm trying to use end and start margins as best practice.


问:
Logloss metric in Fastai
i'm doing a competition in zindi plateform which they are using The evaluation metric for this challenge as Log Loss.

so i'm working with fastai library and i want the metric log loss .. i didn't find LogLoss as metric in this library !
i tried some codes like the function provided by sklearn from sklearn.metrics import log_loss but i didn't work

the link of the competition : https://zindi.africa/competitions/basic-needs-basic-rights-kenya-tech4mentalhealth

答:
if needed as a metric (typically mostly used as a loss) you should be able to use cross_entropy function from pytorch:

import torch.nn.functional as F

metrics=[F.cross_entropy,(plus other metrics if needed)]

model= cnn_learner(data, model, metrics=metrics,...)

Title: Logloss metric in Fastai


答:
Change your code to this

```<code>val intent = Intent(this@yourActivity, PickSeatActivity::class.java)
startActivity(intent)
</code>```

or

```<code>val intent = Intent(this.requireActivity(), PickSeatActivity::class.java)
startActivity(intent)
</code>```

Title: How can I start a another activity in this Dialog?

Body:
Change your code to this

val intent = Intent(this@yourActivity, PickSeatActivity::class.java)
startActivity(intent)

or

val intent = Intent(this.requireActivity(), PickSeatActivity::class.java)
startActivity(intent)


问:
Error in updateOne pre hook unit test case in mongoose
I'm trying to cover the unit test case for my product category updateOne prehook method. In my schema for generalizing save and updateOne pre hook i declared validateSaveHook() methods and in that save prehook it work fine and i am able to write a unit test case. But inupdateOne pre hook alone facing an issue. In that, i used getupdate() to get the value from mongoose query in code it works fine. While writing the Unit test case in terminal it throws error like TypeError: this.getUpdate is not a function. Can anyone please tell me what wrong in my test case code and how to overcome it?

Test case

```<code> it('should throw error when sub_category false and children is passed.', async () => {
      // Preparing
  const next = jest.fn();
      const context = {
        op: 'updateOne',
        _update: {
          product_category_has_sub_category: false,
        },
      };
      // Executing
        await validateSaveHook.call(context, next);
        expect(next).toHaveBeenCalled();
    });
</code>```

schama.ts:

```<code>    export async function validateSaveHook(this: any, next: NextFunction) {
      let productCategory = this as ProductCategoryType;
      if (this.op == 'updateOne') {
        productCategory = this.getUpdate() as ProductCategoryType;
               if (!productCategory.product_category_has_sub_category && !productCategory['product_category_children']) {
          productCategory.product_category_children = [];
        }
      }
      if (productCategory.product_category_has_sub_category && isEmpty(productCategory.product_category_children)) {
        throwError("'product_category_children' is required.", 400);
      }
      if (!productCategory.product_category_has_sub_category && !isEmpty(productCategory.product_category_children)) {
        throwError("'product_category_children' should be empty.", 400);
      }
      next();
    }
export class ProductCategorySchema extends AbstractSchema {
  entityName = 'product_category';
  schemaDefinition = {
    product_category_has_sub_category: {
      type: Boolean,
      required: [true, 'product_category_has_sub_category is required.'],
    },

    product_category_children: {
      type: [Schema.Types.Mixed],
    },
  };

  indexes = ['product_category_name'];

  hooks = () => {
    this.schema?.pre('updateOne', validateSaveHook);
  };
}
</code>```

答:
validateSaveHook expects a context to have getUpdate method. In case a context is mocked, it should provide this method:

```<code>const productCategory = {
  product_category_has_sub_category: ...,
  product_category_children: ...
};

const context = {
  getUpdate: jest.fn().mockReturnValue(productCategory),
  ...
</code>```

Body:
I'm trying to cover the unit test case for my product category updateOne prehook method. In my schema for generalizing save and updateOne pre hook i declared validateSaveHook() methods and in that save prehook it work fine and i am able to write a unit test case. But inupdateOne pre hook alone facing an issue. In that, i used getupdate() to get the value from mongoose query in code it works fine. While writing the Unit test case in terminal it throws error like TypeError: this.getUpdate is not a function. Can anyone please tell me what wrong in my test case code and how to overcome it?

Test case

 it('should throw error when sub_category false and children is passed.', async () => {
      // Preparing
  const next = jest.fn();
      const context = {
        op: 'updateOne',
        _update: {
          product_category_has_sub_category: false,
        },
      };
      // Executing
        await validateSaveHook.call(context, next);
        expect(next).toHaveBeenCalled();
    });

schama.ts:

    export async function validateSaveHook(this: any, next: NextFunction) {
      let productCategory = this as ProductCategoryType;
      if (this.op == 'updateOne') {
        productCategory = this.getUpdate() as ProductCategoryType;
               if (!productCategory.product_category_has_sub_category && !productCategory['product_category_children']) {
          productCategory.product_category_children = [];
        }
      }
      if (productCategory.product_category_has_sub_category && isEmpty(productCategory.product_category_children)) {
        throwError("'product_category_children' is required.", 400);
      }
      if (!productCategory.product_category_has_sub_category && !isEmpty(productCategory.product_category_children)) {
        throwError("'product_category_children' should be empty.", 400);
      }
      next();
    }
export class ProductCategorySchema extends AbstractSchema {
  entityName = 'product_category';
  schemaDefinition = {
    product_category_has_sub_category: {
      type: Boolean,
      required: [true, 'product_category_has_sub_category is required.'],
    },

    product_category_children: {
      type: [Schema.Types.Mixed],
    },
  };

  indexes = ['product_category_name'];

  hooks = () => {
    this.schema?.pre('updateOne', validateSaveHook);
  };
}

Body:
validateSaveHook expects a context to have getUpdate method. In case a context is mocked, it should provide this method:

const productCategory = {
  product_category_has_sub_category: ...,
  product_category_children: ...
};

const context = {
  getUpdate: jest.fn().mockReturnValue(productCategory),
  ...


问:
Android MapActivity : Couldn't get connection factory client
I'm trying to get the Map demos working, as provided in the Google API
sample projects.  I am using AVDs and have tried with versions 8, 10
and 11 and get the same issue.

I've generated my own debug key and added to the project.  I can see
the map on app start up, and can zoom in etc - so I am getting the map
tiles, fine.
Yes - I have the correct permissions and  library set in the Manifest
file (as per samples).

But, I cannot set a location on the map, either via DDMS or Telnet.  I
see the following error in LogCat:
MapActivity : Couldn't get connection factory client

I've read numerous threads regarding this issue, but they always seem
to be as a result of a bad API key; which I do not have, as I am
retrieving map tiles.

So I created my own project to test this further, and am executing the
following code on initialisation of my map:

```<code>    myLocationOverlay = new MyLocationOverlay(this, mapView);
       mapView.getOverlays().add(myLocationOverlay);
       myLocationOverlay.enableCompass();
       myLocationOverlay.enableMyLocation();
       Log.i("funkatron: ", "ABOUT TO CALL RUN ON FIRST FIX");
       myLocationOverlay.runOnFirstFix(new Runnable() {
           public void run() {
               String loc = "we have a location, executing AnimateTo().
"+myLocationOverlay.getMyLocation().toString();
               Log.i("funkatron:",loc);

mapController.animateTo(myLocationOverlay.getMyLocation());
           }
       });
</code>```

I see my first log statement, but never the second, and "MapActivity :
Couldn't get connection factory client" is written to LogCat at that
point.

I have read that there were issues with SDK v8 emulators, so I have
tried with v10 and 11 - but still no joy.
I have NOT yet tried this on an actual device - will do soon.

Any help on this issue would be greatly appreciated - it's really
baffling me  ;)

cheers

答:
i had exactly the same  initial situation as you described.

when you see the map tiles there are obviously some missing to see a position on the map:

1. you need a location.
i recognized that setting only a geo position via DDMS view to the emulator is not enough. you have to explicitly press every time the "Send" button in DDMS to trigger a location update on your emulator.
(just to mention: on a real the device you have sometimes to walk a bit to make your device get a location update ;), i was so pissed off until i walked around thinking of what to do now ^^)

2. you need a correct implementation of ItemizedOverlay with an correct OverlayItem.
i wrote my own overlay which got bit "complicated". if you're not sure if your implementation is correct, use this guide to create an implementation with minimal changes Map view tutorial android developers

or  use this:

```<code>private class MyItemizedOverlay extends ItemizedOverlay {
    private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();

    public MyItemizedOverlay(Drawable defaultMarker) {
          super(boundCenterBottom(defaultMarker));
    }

    public void addOverlay(OverlayItem overlay) {
        mOverlays.add(overlay);
        populate();
    }

    @Override
    protected OverlayItem createItem(int i) {
      return mOverlays.get(i);
    }

    @Override
    public int size() {
      return mOverlays.size();
    }
}

private void updateLocationOverlay() {
    if (location == null) { return };
    List<Overlay> mapOverlays = mapView.getOverlays();
    Drawable drawable = this.getResources().getDrawable(R.drawable.XXXX);
    MyItemizedOverlay myItemizedOverlay = new MyItemizedOverlay(drawable);
    GeoPoint point = new GeoPoint((int)(location.getLatitude() * 1E6), (int)(location.getLongitude() * 1E6));

    OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!");
    myItemizedOverlay.addOverlay(overlayitem);
    mapOverlays.add(myItemizedOverlay);
}
</code>```

i want specially point out that you must call boundCenter or boundCenterBottom on the drawable. else it will not be drawn. be also careful if you use different markers in the same overlay with overlayItem.setMarker, that u call it there too.

3. you have to move the view on the map to your point. you can achieve this like this:

```<code>MapController mapController = mapView.getController();
mapController.setCenter(point)
</code>```

i recognized that the function  mapController.zoomToSpan does not work. (at least for me, i am still developing on this app). maybe its the same with animateTo. i did not try. set center works. (and setZoom level also).

Maybe there is something in the points i mentioned which could lead to, that your map does not work like you want.

Good luck!

edit: i forgot to mention that i am still getting that factory client error even it works to get a valid location, real on device and fake on emulator via ddms send). i just ignore for now.

Body:
I'm trying to get the Map demos working, as provided in the Google API
sample projects.  I am using AVDs and have tried with versions 8, 10
and 11 and get the same issue.

I've generated my own debug key and added to the project.  I can see
the map on app start up, and can zoom in etc - so I am getting the map
tiles, fine.
Yes - I have the correct permissions and  library set in the Manifest
file (as per samples).

But, I cannot set a location on the map, either via DDMS or Telnet.  I
see the following error in LogCat:
MapActivity : Couldn't get connection factory client

I've read numerous threads regarding this issue, but they always seem
to be as a result of a bad API key; which I do not have, as I am
retrieving map tiles.

So I created my own project to test this further, and am executing the
following code on initialisation of my map:

    myLocationOverlay = new MyLocationOverlay(this, mapView);
       mapView.getOverlays().add(myLocationOverlay);
       myLocationOverlay.enableCompass();
       myLocationOverlay.enableMyLocation();
       Log.i("funkatron: ", "ABOUT TO CALL RUN ON FIRST FIX");
       myLocationOverlay.runOnFirstFix(new Runnable() {
           public void run() {
               String loc = "we have a location, executing AnimateTo().
"+myLocationOverlay.getMyLocation().toString();
               Log.i("funkatron:",loc);

mapController.animateTo(myLocationOverlay.getMyLocation());
           }
       });

I see my first log statement, but never the second, and "MapActivity :
Couldn't get connection factory client" is written to LogCat at that
point.

I have read that there were issues with SDK v8 emulators, so I have
tried with v10 and 11 - but still no joy.
I have NOT yet tried this on an actual device - will do soon.

Any help on this issue would be greatly appreciated - it's really
baffling me  ;)

cheers

Body:
i had exactly the same  initial situation as you described.

when you see the map tiles there are obviously some missing to see a position on the map:

1. you need a location.
i recognized that setting only a geo position via DDMS view to the emulator is not enough. you have to explicitly press every time the "Send" button in DDMS to trigger a location update on your emulator.
(just to mention: on a real the device you have sometimes to walk a bit to make your device get a location update ;), i was so pissed off until i walked around thinking of what to do now ^^)

2. you need a correct implementation of ItemizedOverlay with an correct OverlayItem.
i wrote my own overlay which got bit "complicated". if you're not sure if your implementation is correct, use this guide to create an implementation with minimal changes Map view tutorial android developers

or  use this:

private class MyItemizedOverlay extends ItemizedOverlay {
    private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();

    public MyItemizedOverlay(Drawable defaultMarker) {
          super(boundCenterBottom(defaultMarker));
    }

    public void addOverlay(OverlayItem overlay) {
        mOverlays.add(overlay);
        populate();
    }

    @Override
    protected OverlayItem createItem(int i) {
      return mOverlays.get(i);
    }

    @Override
    public int size() {
      return mOverlays.size();
    }
}

private void updateLocationOverlay() {
    if (location == null) { return };
    List<Overlay> mapOverlays = mapView.getOverlays();
    Drawable drawable = this.getResources().getDrawable(R.drawable.XXXX);
    MyItemizedOverlay myItemizedOverlay = new MyItemizedOverlay(drawable);
    GeoPoint point = new GeoPoint((int)(location.getLatitude() * 1E6), (int)(location.getLongitude() * 1E6));

    OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!");
    myItemizedOverlay.addOverlay(overlayitem);
    mapOverlays.add(myItemizedOverlay);
}

i want specially point out that you must call boundCenter or boundCenterBottom on the drawable. else it will not be drawn. be also careful if you use different markers in the same overlay with overlayItem.setMarker, that u call it there too.

3. you have to move the view on the map to your point. you can achieve this like this:

MapController mapController = mapView.getController();
mapController.setCenter(point)

i recognized that the function  mapController.zoomToSpan does not work. (at least for me, i am still developing on this app). maybe its the same with animateTo. i did not try. set center works. (and setZoom level also).

Maybe there is something in the points i mentioned which could lead to, that your map does not work like you want.

Good luck!

edit: i forgot to mention that i am still getting that factory client error even it works to get a valid location, real on device and fake on emulator via ddms send). i just ignore for now.


问:
Change Jenkins Installation path
I have a Jenkins installed by default on my Red Hat Linux Machine at below default locations using yum :-

```<code>Home - /var/lib/jenkins/
War - /usr/lib/jenkins/
</code>```

I want to install another jenkins on same server at different location and port.

```<code>New Home - /app/jenkins/data/jenkins/
New War - /app/jenkins/bin/
log location - /app/jenkins/logs/
</code>```

Any idea how we can mention path in yum while installing jenkins.

答:
You have four options here:

yum --installroot=/opt/jenkins1 --releasever=<your_release_version> install jenkins¹ You then can use chroot together with Systemd (very hacky)

Just download the jenkins.war and start it twice with different start options. Use Systemd again two manage the services.

Use Docker to create two instances.

Instead of creating two instances, use Jenkins' different permissions models, e.g. Matrix-based security. Your can also scale the instance then.

I can understand, why someone needs two instances (different departments with different requirements), but you're gonna need to manage two Jenkins instances, so you should try to extend the abilities of your first instance.

(¹): I just checked the dnf command on my Fedora machine, but it should be the same for (even older) Red Hat

Title: Change Jenkins Installation path

Body:
I have a Jenkins installed by default on my Red Hat Linux Machine at below default locations using yum :-

Home - /var/lib/jenkins/
War - /usr/lib/jenkins/

I want to install another jenkins on same server at different location and port.

New Home - /app/jenkins/data/jenkins/
New War - /app/jenkins/bin/
log location - /app/jenkins/logs/

Any idea how we can mention path in yum while installing jenkins.


问:
Node.js auto migrations
I have been doing Django for several years and was spoiled by their automigrations that they have supported for a very long time. Recently I started using SailsJS (which I am very new to) and noticed that it only supports alter for db migrations in development, NOT production. Is there any third party for node that does something to that effect? I looked at knex but that doesn't autodetect the changes made to my models. I'm looking for something similar to what Django has.

I read the below thoroughly:

https://sailsjs.com/documentation/concepts/models-and-orm/model-settings#?migrate

答: In development you can use alter settings for your models, it works perfectly fine. But doing auto migrations in production is a bad idea, you don't want to risk loosing any data. It's better to do migrations through some process that includes declaring migrations and rollbacks as well as keep a record of what migrations where ran already. Sequelize ORM has migrations so the frameworks that work with it will have them too, i.e. Actionhero.js. There is also Nodal.js not as popupar but has migrations inbuild. In Sails.js I usually just introduce migrations for the DB I'm using, for MySQL I'd just install and use mysql-migrations for Postgres postgres-migrations etc.

Title: Node.js auto migrations


问:
nested Dropdown Menu with lists
I am really desperated trying to find my error why this does not work for the level 4. Up to level 3 it works. I want a dropdown menu hide the child of the parents. I am very new to html/CSS and I think the error is within the CSS? I thought I properly adjusted it for the level 4...

Here is the code:

```<code>    <!DOCTYPE html>
    <html>
    <head>
    <style>
    html, body {
        margin:0;
        padding:0;
        height:100%;
    }
    * {box-sizing: border-box;}
    .container {
        height:100%;
    }
    a {
        color:#fff;
        text-decoration:none;
        border-bottom:1px dotted #fff;
        padding:0px 0px 20px 0px;
        width:100%;
        display:block;
        height:100%;
    }
    li {
        padding:20px 20px 0 20px;
        width:100%;
        color:#fff;
    }
    .container ul {height:100%;}
    .container > ul {
        width:250px;
        background-color:#224490;
        position:relative;
        overflow:visible;
    }
    .container > ul > li {}
    .container > ul > li:hover {background-color:#0f1e41;}
    .container > ul > li > ul {
        display:none;
        position:absolute;
        right:-250px;
        top:0;
        width:250px;
        background-color:#18316a;
    }
    .container > ul > li:hover > ul {
        display:block;
    }
    .container > ul > li > ul >li:hover {background-color:#0f1e41;}
    .container > ul > li > ul > li > ul {
        display:none;
        position:absolute;
        right:-250px;
        top:0;
        width:250px;
        background-color:#112551;
    }
    .container > ul > li > ul > li:hover ul {
        display:block;
    }
    .container > ul > li > ul > li > ul > li:hover {background-color:#0f1e41;}

    .container > ul > li > ul > li >ul >li:hover ul {
        display:block;
    }

    .container > ul > li > ul > li >ul >li >ul >li:hover ul {
        display:block;
    }

    .container > ul > li > ul > li > ul >li >ul >li:hover {background-color:#0f1e41;}

    .container > ul > li > ul > li > ul >li > ul {
        display:none;
        position:absolute;
        right:-250px;
        top:0;
        width:250px;
        background-color:#112551;
    }

    .container > ul > li > ul > li > ul >li>ul >li > ul {
        display:none;
        position:absolute;
        right:-250px;
        top:0;
        width:250px;
        background-color:#112551;
    }
    /* .container > ul > li > ul > li ul li ul li {
        border-bottom:1px dotted #fff;
        padding:20px;
    } */

</style>
</head>

<body>

<div class="container">

<ul class="parent">
    <li>str1str2str34
        <ul class="child">
            <li>A
                <ul class="parent">
                    <li>a11</li>
                    <li>a12 </li>
                </ul>
            </li>
            <li>B
                <ul class="parent">
                    <li>B1
                        <ul class="child">
                            <li>b11</li>
                            <li>b12 </li>
                        </ul>
                    </li>
                    <li>B2
                        <ul class="child">
                            <li>b21 </li>
                            <li>22 </li>
                            <li>23 </li>
                        </ul>
                    </li>
                    <li>B3
                        <ul class="child">
                            <li>B31
                                <ul class="parent">
                                    <li>b31</li>
                                    <li>b32 </li>
                                </ul>
                            </li>
                            <li>B32
                                <ul class="parent">
                                    <li>b41</li>
                                    <li>b42</li>
                                    <li>b43 </li>
                                </ul>
                            </li>
                        </ul>
                    </li>
                </ul>
            </li>
            <li>C
                <ul class="parent">
                    <li>c11</li>
                    <li>c12
                        <ul class="child">
                            <li>b41</li>
                            <li>b42</li>
                            <li>b43 </li>
                        </ul>
                    </li>
                    <li>c13 </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>
</div>

<script>

$('.child').hide(); //Hide children by default
$('.parent').children().click(function () {
        event.preventDefault();
        $(this).children('.child').slideToggle('slow');
        $(this).find('span').toggle();
    });
</script>

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

答:
* {
  box-sizing: border-box;
}
html,
body {
  margin: 0;
  padding: 0;
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  color: #fff;
  padding: 1rem;
}

li:hover {
  background-color: rgb(4, 50, 83);
}

.container>ul {
  width: 250px;
  background-color: #224490;
  position: relative;
  height: 100vh;
}

ul li{
  display: block;
  position: relative;
  background-color: #224490;
}

ul li:hover>ul{
  display: block;
  position: absolute;
  width: 250px;
  height: 100%;
  left: 250px;
  top: 0;
}

ul ul{
  display: none;
}

ul li {
  background-color: #336699;
}

ul li:hover {
  background-color: #5599aa;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">

    <ul class="lists">
      <li class="parent">str1str2str34
        <ul class="child">
          <li class="parent">A
            <ul class="child">
              <li>a11</li>
              <li>a12 </li>
            </ul>
          </li>
          <li class="parent">B
            <ul class="child">
              <li class="parent">B1
                <ul class="child">
                  <li>b11</li>
                  <li>b12 </li>
                </ul>
              </li>
              <li class="parent">B2
                <ul class="child">
                  <li>b21 </li>
                  <li>22 </li>
                  <li>23 </li>
                </ul>
              </li>
              <li class="parent">B3
                <ul class="child">
                  <li class="parent">B31
                    <ul class="child">
                      <li>b31</li>
                      <li>b32 </li>
                    </ul>
                  </li>
                  <li class="parent">B32
                    <ul class="child">
                      <li>b41</li>
                      <li>b42</li>
                      <li>b43 </li>
                    </ul>
                  </li>
                </ul>
              </li>
            </ul>
          </li>
          <li class="parent">C
            <ul class="child">
              <li>c11</li>
              <li class="parent">c12
                <ul class="child">
                  <li>b41</li>
                  <li>b42</li>
                  <li>b43 </li>
                </ul>
              </li>
              <li>c13 </li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </div></code>```

Title: nested Dropdown Menu with lists

Body:
I am really desperated trying to find my error why this does not work for the level 4. Up to level 3 it works. I want a dropdown menu hide the child of the parents. I am very new to html/CSS and I think the error is within the CSS? I thought I properly adjusted it for the level 4...

Here is the code:

    <!DOCTYPE html>

str1str2str34

A

a11

a12

B

B1

b11

b12

B2

b21

22

23

B3

B31

b31

b32

B32

b41

b42

b43

C

c11

c12

b41

b42

b43

c13

Body:
* {
  box-sizing: border-box;
}
html,
body {
  margin: 0;
  padding: 0;
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  color: #fff;
  padding: 1rem;
}

li:hover {
  background-color: rgb(4, 50, 83);
}

.container>ul {
  width: 250px;
  background-color: #224490;
  position: relative;
  height: 100vh;
}

ul li{
  display: block;
  position: relative;
  background-color: #224490;
}

ul li:hover>ul{
  display: block;
  position: absolute;
  width: 250px;
  height: 100%;
  left: 250px;
  top: 0;
}

ul ul{
  display: none;
}

ul li {
  background-color: #336699;
}

ul li:hover {
  background-color: #5599aa;
}

<div class="container">

    <ul class="lists">
      <li class="parent">str1str2str34
        <ul class="child">
          <li class="parent">A
            <ul class="child">
              <li>a11</li>
              <li>a12 </li>
            </ul>
          </li>
          <li class="parent">B
            <ul class="child">
              <li class="parent">B1
                <ul class="child">
                  <li>b11</li>
                  <li>b12 </li>
                </ul>
              </li>
              <li class="parent">B2
                <ul class="child">
                  <li>b21 </li>
                  <li>22 </li>
                  <li>23 </li>
                </ul>
              </li>
              <li class="parent">B3
                <ul class="child">
                  <li class="parent">B31
                    <ul class="child">
                      <li>b31</li>
                      <li>b32 </li>
                    </ul>
                  </li>
                  <li class="parent">B32
                    <ul class="child">
                      <li>b41</li>
                      <li>b42</li>
                      <li>b43 </li>
                    </ul>
                  </li>
                </ul>
              </li>
            </ul>
          </li>
          <li class="parent">C
            <ul class="child">
              <li>c11</li>
              <li class="parent">c12
                <ul class="child">
                  <li>b41</li>
                  <li>b42</li>
                  <li>b43 </li>
                </ul>
              </li>
              <li>c13 </li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </div>