问:
triyng run the crawler with docker image
I'm triyng run the crawler with docker image, but it's returning this error.

```<code>PS C:\Users\Santosgab\Desktop\documentation> docker run -it --env-file=.env -e "CONFIG=$(cat config.json | jq -r tostring)" algolia/docsearch-scraper
Traceback (most recent call last):
  File "/root/src/config/config_loader.py", line 101, in _load_config
    data = json.loads(config, object_pairs_hook=OrderedDict)
  File "/usr/lib/python3.6/json/__init__.py", line 367, in loads
    return cls(**kw).decode(s)
  File "/usr/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.6/json/decoder.py", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
</code>```

i used the config provided by Algolia, just made some small changes to run in my project, my config.json has no problem.

```<code>{
  "index_name": "Sequor",
  "sitemap_urls": ["http://localhost:3000/sitemap.xml"],
  "sitemap_alternate_links": true,
  "stop_urls": ["/tests"],
  "selectors": {
    "lvl0": {
      "selector": "(//ul[contains(@class,'menu__list')]//a[contains(@class, 'menu__link menu__link--sublist menu__link--active')]/text() | //nav[contains(@class, 'navbar')]//a[contains(@class, 'navbar__link--active')]/text())[last()]",
      "type": "xpath",
      "global": true,
      "default_value": "Documentation"
    },
    "lvl1": "header h1",
    "lvl2": "article h2",
    "lvl3": "article h3",
    "lvl4": "article h4",
    "lvl5": "article h5, article td:first-child",
    "lvl6": "article h6",
    "text": "article p, article li, article td:last-child"
  },
  "strip_chars": " .,;:#",
  "custom_settings": {
    "separatorsToIndex": "_",
    "attributesForFaceting": ["language", "version", "type", "docusaurus_tag"],
    "attributesToRetrieve": [
      "hierarchy",
      "content",
      "anchor",
      "url",
      "url_without_anchor",
      "type"
    ]
  },
  "conversation_id": ["833762294"],
  "nb_hits": 46250
}

</code>```

答:
Two things I notice:

There's no path on your config file. Can you try it with pathing (i.e. ./config.json)

Your config is missing any start_urls as entry points to crawling.

Body:
I'm triyng run the crawler with docker image, but it's returning this error.

PS C:\Users\Santosgab\Desktop\documentation> docker run -it --env-file=.env -e "CONFIG=$(cat config.json | jq -r tostring)" algolia/docsearch-scraper
Traceback (most recent call last):
  File "/root/src/config/config_loader.py", line 101, in _load_config
    data = json.loads(config, object_pairs_hook=OrderedDict)
  File "/usr/lib/python3.6/json/__init__.py", line 367, in loads
    return cls(**kw).decode(s)
  File "/usr/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.6/json/decoder.py", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

i used the config provided by Algolia, just made some small changes to run in my project, my config.json has no problem.

{
  "index_name": "Sequor",
  "sitemap_urls": ["http://localhost:3000/sitemap.xml"],
  "sitemap_alternate_links": true,
  "stop_urls": ["/tests"],
  "selectors": {
    "lvl0": {
      "selector": "(//ul[contains(@class,'menu__list')]//a[contains(@class, 'menu__link menu__link--sublist menu__link--active')]/text() | //nav[contains(@class, 'navbar')]//a[contains(@class, 'navbar__link--active')]/text())[last()]",
      "type": "xpath",
      "global": true,
      "default_value": "Documentation"
    },
    "lvl1": "header h1",
    "lvl2": "article h2",
    "lvl3": "article h3",
    "lvl4": "article h4",
    "lvl5": "article h5, article td:first-child",
    "lvl6": "article h6",
    "text": "article p, article li, article td:last-child"
  },
  "strip_chars": " .,;:#",
  "custom_settings": {
    "separatorsToIndex": "_",
    "attributesForFaceting": ["language", "version", "type", "docusaurus_tag"],
    "attributesToRetrieve": [
      "hierarchy",
      "content",
      "anchor",
      "url",
      "url_without_anchor",
      "type"
    ]
  },
  "conversation_id": ["833762294"],
  "nb_hits": 46250
}


来源: stackexchange

问:
Anylogic: How to create plot from database table?
In my Anylogic model I succesfully create plots of datasets that count the number of trucks arriving from terminals each hour in my simulation. Now, I want to add the actual/"observed" number of trucks arriving at a terminal, to compare my simulation to these numbers. I added these numbers in a database table (see picture below). Is there a simple way of adding this data to the plot?

I tried it by creating a variable that reads the database table for every hour and adding that to a dataset (like can be seen in the pictures below), but this did not work unfortunately (the plot was empty).

答:
You don't explain why it "didn't work" (what errors/problems did you get?), nor where you defined these elements.

(1) Since you want both observed (empirical) and simulated arrivals per terminal, datasets for each should be in the Terminal agent. And then the replicated plot (in Main) can have two data entries referring to data sets terminals(index).observedArrivals and terminals(index).simulatedArrivals or whatever you name them.

(2) Using getHourOfDay to add to the observed dataset is wrong because that just returns 0-23 (i.e., the hour in the current day for the current model date). Your database table looks like it has hours since model start, so you just want time(HOUR) to get the model time in elapsed hours (irrespective of what the model time unit is). Or possibly time(HOUR) - 1 if you only want to update the empirical arrivals for the hour at the end of that hour (i.e., at the same time that you updated the simulated arrivals).

(3) Using a Variable to get the database value each hour doesn't work because a variable's initial value is only evaluated once at model initialisation. You want an hourly cyclic Event in Terminal instead which adds the relevant row's value. (You need to use the Insert Database Query wizard to generate the relevant Java code for the query you need in the event's action.)

(4) Because you have a database table with specifically-named columns for each terminal (columns terminal_a and presumably terminal_b etc.) that makes it slightly more awkward. (This isn't proper relational table design where, instead of 4 columns for the 4 terminals, you'd instead have two columns for terminal_id and observed_value with a row for each time period and terminal combination.)

So your database query expression (in your Terminal agents) will need to use the SQL format (not the QueryDSL format) so that you can 'stitch in' the correct column name into the SQL.

ContentLicense: CC BY-SA 4.0


问:
Swift String variable
```<code>//First way
var myVar: String = " Hello"
print(myVar)
//Second way
var str = "Hello"
print(str)
</code>```

I get the same output no matter which of the two I use. What's the difference between them?

答:
These two are basically the same.

When you use var myVar: String = "Hello", you directly tell the swift compiler that your variable is type String.

When you use var myVar = "Hello", you do not specify the type of your variable, so the swift compiler has do do that for you.

Usually, you can get away without declaring your variable type and just have swift do it for you. However, in some cases, namely computed properties and custom classes/structures, you must manually declare your variable to be a specific type.

In your case, either way is fine. The end result is the same, just be aware of the difference for the future.

Title: Swift String variable

Body:
//First way
var myVar: String = " Hello"
print(myVar)
//Second way
var str = "Hello"
print(str)

I get the same output no matter which of the two I use. What's the difference between them?


问:
Sum across columns if date is not missing and if year of date is after a certain number
I want to create a new variable called bankruptcy_c, which will equal to the number of times the year of bankruptcy1, bankruptcy2, ..., bankruptcy10 is between 2007 and 2019, inclusive. At first, I created a variable that counted the number of times the columns had a date using the following code:

```<code>vars <- df %>%
  mutate(bankruptcy_c = rowSums(!is.na(across(contains("bankruptcy")))))
</code>```

However, now I'm looking to only count each instance if the year is between 2007 and 2019. Here is some sample data:

```<code>structure(list(rowid = c(16L, 28L, 29L, 37L, 80778L), bankruptcy1 = structure(c(9282,
11438, NA, 8664, 14048), class = "Date"), bankruptcy2 = structure(c(12892,
NA, NA, 14809, 15012), class = "Date"), bankruptcy3 = structure(c(14713,
NA, NA, NA, NA), class = "Date"), bankruptcy4 = structure(c(NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_), class = "Date"), bankruptcy5 = structure(c(NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_), class = "Date"), bankruptcy6 = structure(c(NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_), class = "Date"), bankruptcy7 = structure(c(NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_), class = "Date"), bankruptcy8 = structure(c(NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_), class = "Date"), bankruptcy9 = structure(c(NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_), class = "Date"), bankruptcy10 = structure(c(NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_), class = "Date")), row.names = c(NA,
-5L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

Using the sample data above, bankruptcy_c would equal to 1 for rowid = 16, 0 for rowid = 28 (because the dates are out of range), 0 for rowid = 29 (since all of the 10 instances are missing), 1 for rowid = 37, and 2 for rowid = 80778. Any help would be greatly appreciated!

答:
One approach would be to reshape the data longer, filter, and count.

```<code>library(tidyverse)
df %>%
  pivot_longer(-rowid) %>%
  filter(year(as.Date(value)) %in% 2007:2019) %>%
  count(rowid) %>%
  complete(rowid = df$rowid, fill = list(n=0)) # EDIT to list all rowids

# alternate filter syntax if you care about specific dates:
filter(value >= as.Date("2007-01-01"), value < as.Date("2020-01-01")) %>%
</code>```

Result

```<code># A tibble: 5 x 2
  rowid     n
  <int> <dbl>
1    16     1
2    28     0
3    29     0
4    37     1
5 80778     2
</code>```

Body:
I want to create a new variable called bankruptcy_c, which will equal to the number of times the year of bankruptcy1, bankruptcy2, ..., bankruptcy10 is between 2007 and 2019, inclusive. At first, I created a variable that counted the number of times the columns had a date using the following code:

vars <- df %>%
  mutate(bankruptcy_c = rowSums(!is.na(across(contains("bankruptcy")))))

However, now I'm looking to only count each instance if the year is between 2007 and 2019. Here is some sample data:

structure(list(rowid = c(16L, 28L, 29L, 37L, 80778L), bankruptcy1 = structure(c(9282,
11438, NA, 8664, 14048), class = "Date"), bankruptcy2 = structure(c(12892,
NA, NA, 14809, 15012), class = "Date"), bankruptcy3 = structure(c(14713,
NA, NA, NA, NA), class = "Date"), bankruptcy4 = structure(c(NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_), class = "Date"), bankruptcy5 = structure(c(NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_), class = "Date"), bankruptcy6 = structure(c(NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_), class = "Date"), bankruptcy7 = structure(c(NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_), class = "Date"), bankruptcy8 = structure(c(NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_), class = "Date"), bankruptcy9 = structure(c(NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_), class = "Date"), bankruptcy10 = structure(c(NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_), class = "Date")), row.names = c(NA,
-5L), class = c("tbl_df", "tbl", "data.frame"))

Using the sample data above, bankruptcy_c would equal to 1 for rowid = 16, 0 for rowid = 28 (because the dates are out of range), 0 for rowid = 29 (since all of the 10 instances are missing), 1 for rowid = 37, and 2 for rowid = 80778. Any help would be greatly appreciated!

Body:
One approach would be to reshape the data longer, filter, and count.

library(tidyverse)
df %>%
  pivot_longer(-rowid) %>%
  filter(year(as.Date(value)) %in% 2007:2019) %>%
  count(rowid) %>%
  complete(rowid = df$rowid, fill = list(n=0)) # EDIT to list all rowids

# alternate filter syntax if you care about specific dates:
filter(value >= as.Date("2007-01-01"), value < as.Date("2020-01-01")) %>%

Result

# A tibble: 5 x 2
  rowid     n
  <int> <dbl>
1    16     1
2    28     0
3    29     0
4    37     1
5 80778     2


问:
(bash/Linux) most efficient way to subset rows and columns based on row and column indices in other files
I have a data file with millions of rows and thousands of columns. I need the data for certain rows and certain columns. I have a text file with the line numbers I need, and another text file with the column headers I need. I have to subset a couple hundred data files like this, so I'm trying to figure out how to do it quickly, without creating huge intermediate files.

I'm not very experienced in bash scripting. My best approach so far has been to use awk to extract the necessary lines to create an intermediate file, and pipe the results to cut so that the output file only contains the necessary columns:

```<code>COLS=($(zcat big_zipped_file.txt.gz | head -n 1 | tr '\t' '\n' | grep -nf column_headers.txt | sed 's/:.*$//'))

awk 'NR==FNR{a[$0];next} FNR in a' line_numbers.txt <(zcat big_zipped_file.txt.gz) |
  cut -f 1$(printf ",%s" "${COLS[@]}") >> output_file
</code>```

Is there a way to do this that's faster, and doesn't create large temp files?

答:
The solution is to scan each file once.

We use gawk standard Linux awk script.

Reading first 2 files are columns.txt and rows.txt (order not important).

Reading 1 or more data files one after the other, without any temporary files.

Input files

rows.txt

```<code>1
7
5
2
</code>```

columns.txt

```<code>col5
col3
col2
</code>```

data.txt

```<code>col1 col2 col3 col4 col5
11   12    13    14   15
21   22    23    24   25
31   32    33    34   35
41   42    43    44   45
51   52    53    54   55
61   62    63    64   65
71   72    73    74   75
</code>```

script.awk

```<code>BEGIN {
    rowsNumbersFileName="rows.txt";
    clumnNamesFileName="columns.txt";
}

ENDFILE { # mark data files when inputFilesCount > 1
    ++inputFilesCount;
 }

FILENAME == rowsNumbersFileName { # read rows number
    rowsArr[$0] = ++rowsCount;
}

FILENAME == clumnNamesFileName { # read desired column headers
    columnHeadersArr[$0] = ++columnHeadersCount;
}

inputFilesCount > 1 && FNR == 1 { # caluculate column headers markers
    OFS = "";
    for (i = 1; i <= NF; i++) { # scan all header names
        if ($i in columnHeadersArr) { # if current field is in columnHeadersArr
            columnNumbersArr[++columnNumbersCount] = i; # collect field name in columnNumbersArr
            printf ("%s   %s", OFS, $i); # Ouput current field as header
            OFS = ",";
        }
    }
    printf("\n");
    next;
}

inputFilesCount > 1  && (FNR - 1) in rowsArr {
    OFS = "";
     for (currColumnNum in columnNumbersArr) {
        printf ("%s     %s", OFS, $columnNumbersArr[currColumnNum]);
        OFS = ",";
    }
    printf("\n");
}
</code>```

Output

```<code>awk -f script.awk rows.txt columns.txt data.txt
   col2,   col3,   col5
     12,     13,     15
     22,     23,     25
     52,     53,     55
     72,     73,     75
</code>```

Body:
I have a data file with millions of rows and thousands of columns. I need the data for certain rows and certain columns. I have a text file with the line numbers I need, and another text file with the column headers I need. I have to subset a couple hundred data files like this, so I'm trying to figure out how to do it quickly, without creating huge intermediate files.

I'm not very experienced in bash scripting. My best approach so far has been to use awk to extract the necessary lines to create an intermediate file, and pipe the results to cut so that the output file only contains the necessary columns:

COLS=($(zcat big_zipped_file.txt.gz | head -n 1 | tr '\t' '\n' | grep -nf column_headers.txt | sed 's/:.*$//'))

awk 'NR==FNR{a[$0];next} FNR in a' line_numbers.txt <(zcat big_zipped_file.txt.gz) |
  cut -f 1$(printf ",%s" "${COLS[@]}") >> output_file

Is there a way to do this that's faster, and doesn't create large temp files?

Body:
The solution is to scan each file once.

We use gawk standard Linux awk script.

Reading first 2 files are columns.txt and rows.txt (order not important).

Reading 1 or more data files one after the other, without any temporary files.

Input files

rows.txt

1
7
5
2

columns.txt

col5
col3
col2

data.txt

col1 col2 col3 col4 col5
11   12    13    14   15
21   22    23    24   25
31   32    33    34   35
41   42    43    44   45
51   52    53    54   55
61   62    63    64   65
71   72    73    74   75

script.awk

BEGIN {
    rowsNumbersFileName="rows.txt";
    clumnNamesFileName="columns.txt";
}

ENDFILE { # mark data files when inputFilesCount > 1
    ++inputFilesCount;
 }

FILENAME == rowsNumbersFileName { # read rows number
    rowsArr[$0] = ++rowsCount;
}

FILENAME == clumnNamesFileName { # read desired column headers
    columnHeadersArr[$0] = ++columnHeadersCount;
}

inputFilesCount > 1 && FNR == 1 { # caluculate column headers markers
    OFS = "";
    for (i = 1; i <= NF; i++) { # scan all header names
        if ($i in columnHeadersArr) { # if current field is in columnHeadersArr
            columnNumbersArr[++columnNumbersCount] = i; # collect field name in columnNumbersArr
            printf ("%s   %s", OFS, $i); # Ouput current field as header
            OFS = ",";
        }
    }
    printf("\n");
    next;
}

inputFilesCount > 1  && (FNR - 1) in rowsArr {
    OFS = "";
     for (currColumnNum in columnNumbersArr) {
        printf ("%s     %s", OFS, $columnNumbersArr[currColumnNum]);
        OFS = ",";
    }
    printf("\n");
}

Output

awk -f script.awk rows.txt columns.txt data.txt
   col2,   col3,   col5
     12,     13,     15
     22,     23,     25
     52,     53,     55
     72,     73,     75


问:
How can I write a loop/function to calculate the % difference between different rows/factors?
I'm looking to do something that's out of my coding league. I have included 2 snippets of real data below.

Basically I want to mutate/add a column (or even create a new dataframe if that is easier) that calculates the % difference of a measurement "median.fsc" that corresponds to the same "strain" but different "starvation state" but within the same experiment "run".

So for example

I want the % difference of median.fsc of 381-starved / 381-enriched for run 1

I presume i would be using dplyr but have no clue where to start!

Some further manipulation that I also want to do - but guessing I can adapt whatever code I do end up using.

Strain-comparison (median.fsc) expressed as % ie 381.dwecA (enriched) / 381 (enriched)  in run 1

```<code>structure(list(strain = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L,
        8L, 10L), .Label = c("381", "381.dwecA", "381.dwecA.cwecA", "381.dwecE",
        "381.dwecE.cwecE", "381.dwaaG", "381.dwaaG.cwaaG", "381.dE.dG",
        "381.dE.dG.cE.cG.c1", "381.dE.dG.cE.cG.c2"), class = "factor"),
            starvation = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
            2L), .Label = c("starved", "enriched"), class = "factor"),
            live.dead = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L
            ), .Label = c("live", "mixed"), class = "factor"), geomean.fsc = c(9283.6,
            8012.8, 8030.1, 9464.1, 8286, 7903.6, 10600.7, 8539.2, 8935.1
            ), mean.fsc = c(11002.9, 9551.4, 9606.6, 10747.4, 9824, 9277,
            11874.9, 9645.4, 10537.6), median.fsc = c(10581.7, 8420.3,
            8393.4, 10050.1, 8771.6, 7979.3, 11526, 8371.3, 9701.5),
            std.dv = c(5808.4, 5482.6, 5533, 5264, 5481.1, 5250, 5202.3,
            4816.8, 5654.1), run = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
            1L, 1L, 1L), .Label = c("1", "2", "3"), class = "factor")), row.names = c(NA,
        -9L), class = c("tbl_df", "tbl", "data.frame"))
</code>```
```<code>    structure(list(strain = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L,
    8L, 10L), .Label = c("381", "381.dwecA", "381.dwecA.cwecA", "381.dwecE",
    "381.dwecE.cwecE", "381.dwaaG", "381.dwaaG.cwaaG", "381.dE.dG",
    "381.dE.dG.cE.cG.c1", "381.dE.dG.cE.cG.c2"), class = "factor"),
        starvation = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
        1L), .Label = c("starved", "enriched"), class = "factor"),
        live.dead = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L
        ), .Label = c("live", "mixed"), class = "factor"), geomean.fsc = c(2123.8,
        2426.4, 2056.6, 2556.5, 2452, 2703.3, 2065, 3875, 2362.6),
        mean.fsc = c(2482.7, 2867, 2321, 2757.6, 2651.4, 3107.2,
        2368.9, 4308.2, 2571.1), median.fsc = c(1924.9, 2177, 1896,
        2512.2, 2378.8, 2442.8, 1883.6, 3882.8, 2263.4), std.dv = c(NA_real_,
        NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
        NA_real_, NA_real_), run = structure(c(1L, 1L, 1L, 1L, 1L,
        1L, 1L, 1L, 1L), .Label = c("1", "2", "3"), class = "factor")), row.names = c(NA,
    -9L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

答:
Let's assume your datasets are called:df_starved and df_enriched

```<code>library(dplyr)
df_new <- tibble(strain = df_starved$strain) %>%  mutate("diff_median" = df_starved$median.fsc/df_enriched$median.fsc*100,
                                                         "strain_comp_enriched" = df_enriched$median.fsc/df_enriched$median.fsc[1]*100)
df_new
</code>```

Body:
I'm looking to do something that's out of my coding league. I have included 2 snippets of real data below.

Basically I want to mutate/add a column (or even create a new dataframe if that is easier) that calculates the % difference of a measurement "median.fsc" that corresponds to the same "strain" but different "starvation state" but within the same experiment "run".

So for example

I want the % difference of median.fsc of 381-starved / 381-enriched for run 1

I presume i would be using dplyr but have no clue where to start!

Some further manipulation that I also want to do - but guessing I can adapt whatever code I do end up using.

Strain-comparison (median.fsc) expressed as % ie 381.dwecA (enriched) / 381 (enriched)  in run 1

structure(list(strain = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L,
        8L, 10L), .Label = c("381", "381.dwecA", "381.dwecA.cwecA", "381.dwecE",
        "381.dwecE.cwecE", "381.dwaaG", "381.dwaaG.cwaaG", "381.dE.dG",
        "381.dE.dG.cE.cG.c1", "381.dE.dG.cE.cG.c2"), class = "factor"),
            starvation = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
            2L), .Label = c("starved", "enriched"), class = "factor"),
            live.dead = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L
            ), .Label = c("live", "mixed"), class = "factor"), geomean.fsc = c(9283.6,
            8012.8, 8030.1, 9464.1, 8286, 7903.6, 10600.7, 8539.2, 8935.1
            ), mean.fsc = c(11002.9, 9551.4, 9606.6, 10747.4, 9824, 9277,
            11874.9, 9645.4, 10537.6), median.fsc = c(10581.7, 8420.3,
            8393.4, 10050.1, 8771.6, 7979.3, 11526, 8371.3, 9701.5),
            std.dv = c(5808.4, 5482.6, 5533, 5264, 5481.1, 5250, 5202.3,
            4816.8, 5654.1), run = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
            1L, 1L, 1L), .Label = c("1", "2", "3"), class = "factor")), row.names = c(NA,
        -9L), class = c("tbl_df", "tbl", "data.frame"))

    structure(list(strain = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L,
    8L, 10L), .Label = c("381", "381.dwecA", "381.dwecA.cwecA", "381.dwecE",
    "381.dwecE.cwecE", "381.dwaaG", "381.dwaaG.cwaaG", "381.dE.dG",
    "381.dE.dG.cE.cG.c1", "381.dE.dG.cE.cG.c2"), class = "factor"),
        starvation = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
        1L), .Label = c("starved", "enriched"), class = "factor"),
        live.dead = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L
        ), .Label = c("live", "mixed"), class = "factor"), geomean.fsc = c(2123.8,
        2426.4, 2056.6, 2556.5, 2452, 2703.3, 2065, 3875, 2362.6),
        mean.fsc = c(2482.7, 2867, 2321, 2757.6, 2651.4, 3107.2,
        2368.9, 4308.2, 2571.1), median.fsc = c(1924.9, 2177, 1896,
        2512.2, 2378.8, 2442.8, 1883.6, 3882.8, 2263.4), std.dv = c(NA_real_,
        NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
        NA_real_, NA_real_), run = structure(c(1L, 1L, 1L, 1L, 1L,
        1L, 1L, 1L, 1L), .Label = c("1", "2", "3"), class = "factor")), row.names = c(NA,
    -9L), class = c("tbl_df", "tbl", "data.frame"))

Body:
Let's assume your datasets are called:df_starved and df_enriched

library(dplyr)
df_new <- tibble(strain = df_starved$strain) %>%  mutate("diff_median" = df_starved$median.fsc/df_enriched$median.fsc*100,
                                                         "strain_comp_enriched" = df_enriched$median.fsc/df_enriched$median.fsc[1]*100)
df_new


问:
Convert BiDirectional Graph Edges to Undirected Edges in NetworkX
I am using NetworkX to do the following: I have a directed graph g that I want to
transform into an undirected graph h such that h has the same nodes as g and e
is an edge in h iff e is bidirectional in g. For example, I want to transform:

```<code>import networkx as nx
g = nx.DiGraph([("A", "B"), ("B", "A"), ("A", "C"), ("C", "A"), ("B", "C"), ("C", "B"), ("A", "D"), ("C", "D"), ("B", "E"), ("C", "E")])
</code>```

into

```<code>h = nx.Graph([("A", "B"), ("A", "C"), ("B", "C")])
h.add_nodes_from(["D", "E"])
</code>```

What f(g) = h should I write in NetworkX? I think it's some combination of graph
views and filters, but I'm new to NetworkX so I'm not sure exactly what.

答:
You can achieve that by iterating over the edges of you directed graph and checking if the reverse edge exist with the condition if edge[::-1] in g.edges():. If the reverse edge exist, just add it your graph. See code below:

import networkx as nx
import matplotlib.pyplot as plt

#Creating directed graph
g = nx.DiGraph([("A", "B"), ("B", "A"), ("A", "C"), ("C", "A"), ("B", "C"), ("C", "B"), ("A", "D"), ("C", "D"), ("B", "E"), ("C", "E")])

#Creating undirected graph
h=nx.Graph()
h.add_nodes_from(g)

for edge in g.edges():
  if edge[::-1] in g.edges(): #check if reverse edge exist in graph
    h.add_edge(edge[0],edge[1])

#plot both graphs
fig=plt.figure(figsize=(15,6))
plt.subplot(121)
plt.title('Directed graph')
pos1=nx.circular_layout(g)
nx.draw(g,pos=pos1,with_labels=True, node_color='tab:orange')

plt.subplot(122)
plt.title('Undirected graph')
pos2=nx.circular_layout(h)
nx.draw(h,pos=pos2,with_labels=True, node_color='tab:green')
```

And the output gives:

Body:
I am using NetworkX to do the following: I have a directed graph g that I want to
transform into an undirected graph h such that h has the same nodes as g and e
is an edge in h iff e is bidirectional in g. For example, I want to transform:

import networkx as nx
g = nx.DiGraph([("A", "B"), ("B", "A"), ("A", "C"), ("C", "A"), ("B", "C"), ("C", "B"), ("A", "D"), ("C", "D"), ("B", "E"), ("C", "E")])

into

h = nx.Graph([("A", "B"), ("A", "C"), ("B", "C")])
h.add_nodes_from(["D", "E"])

What f(g) = h should I write in NetworkX? I think it's some combination of graph
views and filters, but I'm new to NetworkX so I'm not sure exactly what.

Body:
You can achieve that by iterating over the edges of you directed graph and checking if the reverse edge exist with the condition if edge[::-1] in g.edges():. If the reverse edge exist, just add it your graph. See code below:

import networkx as nx
import matplotlib.pyplot as plt

#Creating directed graph
g = nx.DiGraph([("A", "B"), ("B", "A"), ("A", "C"), ("C", "A"), ("B", "C"), ("C", "B"), ("A", "D"), ("C", "D"), ("B", "E"), ("C", "E")])

#Creating undirected graph
h=nx.Graph()
h.add_nodes_from(g)

for edge in g.edges():
  if edge[::-1] in g.edges(): #check if reverse edge exist in graph
    h.add_edge(edge[0],edge[1])

#plot both graphs
fig=plt.figure(figsize=(15,6))
plt.subplot(121)
plt.title('Directed graph')
pos1=nx.circular_layout(g)
nx.draw(g,pos=pos1,with_labels=True, node_color='tab:orange')

plt.subplot(122)
plt.title('Undirected graph')
pos2=nx.circular_layout(h)
nx.draw(h,pos=pos2,with_labels=True, node_color='tab:green')

And the output gives:


问:
How can I guarantee that my enums definition doesn't change in JavaScript?
Would the following make the objects fulfil all characteristics that enums have in JavaScript? Something like:

my.namespace.ColorEnum = {
  RED : 0,
  GREEN : 1,
  BLUE : 2
}

// later on

if(currentColor == my.namespace.ColorEnum.RED) {
  // whatever
}

```

Or is there some other way I can do this?

答:
I was searching for an answer to this question too & found this page with an answer that I think seams to be different from most answers here:
https://www.sohamkamani.com/javascript/enums/

I will copy over the answer part of the article to here, just in case the link gets invalid in the future or something:

Enums with Symbols:

Symbols let us define values that are guaranteed not to collide
with one another.

For example:

```<code>const Summer1 = Symbol("summer")
const Summer2 = Symbol("summer")

// Even though they have the same apparent value
// Summer1 and Summer2 don't equate
console.log(Summer1 === Summer2)
// false

console.log(Summer1)
</code>```

We can define our enums using Symbols to ensure that they are not
duplicated:

```<code>const Summer = Symbol("summer")
const Autumn = Symbol("autumn")
const Winter = Symbol("winter")
const Spring = Symbol("spring")

let season = Spring

switch (season) {
    case Summer:
    console.log('the season is summer')
    break;
    case Winter:
    console.log('the season is winter')
    break;
    case Spring:
    console.log('the season is spring')
    break;
    case Autumn:
    console.log('the season is autumn')
    break;
    default:
    console.log('season not defined')
}
</code>```

Using Symbols ensures that the only way we can assign an enum value is by using the constants that we defined initially.

Enums with Classes:

To make our code more semantically correct, we can create a class to
hold groups of enums.

For example, our seasons should have a way for us to identify that
they all belong to a similar classification.

Let’s see how we can use classes and objects to create distinct enum
groups:

```<code>// Season enums can be grouped as static members of a class
class Season {
  // Create new instances of the same class as static attributes
  static Summer = new Season("summer")
  static Autumn = new Season("autumn")
  static Winter = new Season("winter")
  static Spring = new Season("spring")

  constructor(name) {
    this.name = name
  }
}

// Now we can access enums using namespaced assignments
// this makes it semantically clear that "Summer" is a "Season"
let season = Season.Summer

// We can verify whether a particular variable is a Season enum
console.log(season instanceof Season)
// true
console.log(Symbol('something') instanceof Season)
//false

// We can explicitly check the type based on each enums class
console.log(season.constructor.name)
// 'Season'
</code>```

personal note: I would have used this constructor instead: (Note: sets: this.name, to a string instead of an object, looses some of the verifications below. Optionally remove the: .description. I would also like to find a way to not have to type Seasons.summer.name but instead only need: Seasons.summer to make it return a string)

```<code>  constructor(name) {
    this.name = Symbol(name).description
  }
</code>```

Listing All Possible Enum Values:

If we used the class-based approach above, we can loop through the
keys of the Season class to obtain all the enum values under the same
group:

```<code>Object.keys(Season).forEach(season => console.log("season:", season))
// season: Summer
// season: Autumn
// season: Winter
// season: Spring
</code>```

When to Use Enums in Javascript?

In general, enums are helpful if there are a definite number of fixed
values for any one variable_

For example, the crypto standard library for Node.js has a list of supported algorithms, that can be considered an enum group.

Using enums in Javascript correctly will lead to better code that is
more stable, easier to read and less error prone.

OwnerDisplayName: David Citron

Body:
Would the following make the objects fulfil all characteristics that enums have in JavaScript? Something like:

my.namespace.ColorEnum = {
  RED : 0,
  GREEN : 1,
  BLUE : 2
}

// later on

if(currentColor == my.namespace.ColorEnum.RED) {
  // whatever
}

Or is there some other way I can do this?

Body:
I was searching for an answer to this question too & found this page with an answer that I think seams to be different from most answers here:
https://www.sohamkamani.com/javascript/enums/

I will copy over the answer part of the article to here, just in case the link gets invalid in the future or something:

Enums with Symbols:

Symbols let us define values that are guaranteed not to collide
with one another.

For example:

const Summer1 = Symbol("summer")
const Summer2 = Symbol("summer")

// Even though they have the same apparent value
// Summer1 and Summer2 don't equate
console.log(Summer1 === Summer2)
// false

console.log(Summer1)

We can define our enums using Symbols to ensure that they are not
duplicated:

const Summer = Symbol("summer")
const Autumn = Symbol("autumn")
const Winter = Symbol("winter")
const Spring = Symbol("spring")

let season = Spring

switch (season) {
    case Summer:
    console.log('the season is summer')
    break;
    case Winter:
    console.log('the season is winter')
    break;
    case Spring:
    console.log('the season is spring')
    break;
    case Autumn:
    console.log('the season is autumn')
    break;
    default:
    console.log('season not defined')
}

Using Symbols ensures that the only way we can assign an enum value is by using the constants that we defined initially.

Enums with Classes:

To make our code more semantically correct, we can create a class to
hold groups of enums.

For example, our seasons should have a way for us to identify that
they all belong to a similar classification.

Let’s see how we can use classes and objects to create distinct enum
groups:

// Season enums can be grouped as static members of a class
class Season {
  // Create new instances of the same class as static attributes
  static Summer = new Season("summer")
  static Autumn = new Season("autumn")
  static Winter = new Season("winter")
  static Spring = new Season("spring")

  constructor(name) {
    this.name = name
  }
}

// Now we can access enums using namespaced assignments
// this makes it semantically clear that "Summer" is a "Season"
let season = Season.Summer

// We can verify whether a particular variable is a Season enum
console.log(season instanceof Season)
// true
console.log(Symbol('something') instanceof Season)
//false

// We can explicitly check the type based on each enums class
console.log(season.constructor.name)
// 'Season'

personal note: I would have used this constructor instead: (Note: sets: this.name, to a string instead of an object, looses some of the verifications below. Optionally remove the: .description. I would also like to find a way to not have to type Seasons.summer.name but instead only need: Seasons.summer to make it return a string)

  constructor(name) {
    this.name = Symbol(name).description
  }

Listing All Possible Enum Values:

If we used the class-based approach above, we can loop through the
keys of the Season class to obtain all the enum values under the same
group:

Object.keys(Season).forEach(season => console.log("season:", season))
// season: Summer
// season: Autumn
// season: Winter
// season: Spring

When to Use Enums in Javascript?

In general, enums are helpful if there are a definite number of fixed
values for any one variable_

For example, the crypto standard library for Node.js has a list of supported algorithms, that can be considered an enum group.

Using enums in Javascript correctly will lead to better code that is
more stable, easier to read and less error prone.


问:
Lisp: How to get the reference (not the value) of an element in a 2D Matrix represented as a List of Lists?
I am trying to reference a specific element in a 2D Matrix represented as list of Lists so I can set that specific element to 0. However, when I run the code below:

```<code>(defvar listOfLists '( (1 3) (2 6) ))
(defvar referenceToTopLeftCorner (nth 0 (nth 0 listOfLists)))
(setq referenceToTopLeftCorner 0)
(print (format nil "listsOfLists = ~a" listOfLists))
</code>```

The following output is:

""listsOfLists = ((1 3) (2 6))"

This seems strange, as I thought that the nth method can be used to get references within a list?

答:
The variable you called reference is not a reference.

You need to do

(setf (nth 0 (nth 0 list-of-lists)) 0)
```
<p>Note that you could also do</p>
<pre class="lang-lisp prettyprint-override"><code>(defvar 1st-list (first list-of-lists))
(setf (first 1st-list) 0)
</code>```

for the same effect, because 1st-list refers to the 1st list in list-of-lists.

You could also use define-symbol-macro:

(define-symbol-macro reference-to-top-left-corner
  (first (first list-of-lists)))
(setf reference-to-top-left-corner 0)
```

because now reference-to-top-left-corner really is a reference.

I strongly advise you not to use symbol macros yet.
Such advanced tools should be used sparingly and cautiously.

Body:
I am trying to reference a specific element in a 2D Matrix represented as list of Lists so I can set that specific element to 0. However, when I run the code below:

(defvar listOfLists '( (1 3) (2 6) ))
(defvar referenceToTopLeftCorner (nth 0 (nth 0 listOfLists)))
(setq referenceToTopLeftCorner 0)
(print (format nil "listsOfLists = ~a" listOfLists))

The following output is:

""listsOfLists = ((1 3) (2 6))"

This seems strange, as I thought that the nth method can be used to get references within a list?

Body:
The variable you called reference is not a reference.

You need to do

(setf (nth 0 (nth 0 list-of-lists)) 0)

Note that you could also do

(defvar 1st-list (first list-of-lists))
(setf (first 1st-list) 0)

for the same effect, because 1st-list refers to the 1st list in list-of-lists.

You could also use define-symbol-macro:

(define-symbol-macro reference-to-top-left-corner
  (first (first list-of-lists)))
(setf reference-to-top-left-corner 0)

because now reference-to-top-left-corner really is a reference.

I strongly advise you not to use symbol macros yet.
Such advanced tools should be used sparingly and cautiously.


问:
Print all subarray of given array and than store maximum integer in each subarray to get the sum of all maximum's?
For Example - If given array is :-
int[] arr = { 1, 4, 8, 3 };

The result Subarray should be:

```<code>1 ,
1 ,4 ,
1 ,4 ,8 ,
1 ,4 ,8 ,3 ,

4 ,
4 ,8 ,
4 ,8 ,3 ,

8 ,
8 ,3 ,

3 ,
</code>```

and than , Maximum of each subarray are :- 1 ,4 ,8,8,4,8,8,8,8,3
therefore sum of all maximum should be :- 1 + 4 +8+8+4+8+8+8+8=3 = 60

To Write Subarray, I was able to do this with loop:-

```<code>{
            for(int j = i ; j <= n ; j++)
            {
                for(int k = i ; k < j ; k++)
                {
                    Console.Write(arr[k] + " ," );

                }

        Console.WriteLine(" " );
            }
        }

    }
</code>```

After this, I was trying to store maximum values in the Dictionary data structure but was not able to find where exactly use dictionary structure and how to use Math.max statement.

```<code>IDictionary<int, int> maxValue = new Dictionary<int, int>();
</code>```

答:
If you would only need the sum, then it could be solved in O(n). Because you need to print the sub-arrays this is not possible. But it also makes it pretty easy (I don't know C#, replace the print with what you need):

```<code>int total = 0;
for (int start = 0; start < n; start++) {
    for (int end = start + 1; end <= n; end++) {
        int max = arr[start];
        print(arr[start]);
        for (int i = start + 1; i < end; i++) {
            print(", " + arr[i]);
            if (arr[i] > max)
                max = arr[i];
        }
        total += max;
        print("\n");
    }
    print("\n");
}
print(total); // or whatever you want to do with it
</code>```

This avoids the last comma, but you can switch it back if you want to. Also readable variable names can be helpful.

end is not inclusive, I prefer it that way because then you could get the length of the sub-array with end - start. E.g. Java's substring works exactly the same.

Body:
For Example - If given array is :-
int[] arr = { 1, 4, 8, 3 };

The result Subarray should be:

1 ,
1 ,4 ,
1 ,4 ,8 ,
1 ,4 ,8 ,3 ,

4 ,
4 ,8 ,
4 ,8 ,3 ,

8 ,
8 ,3 ,

3 ,

and than , Maximum of each subarray are :- 1 ,4 ,8,8,4,8,8,8,8,3
therefore sum of all maximum should be :- 1 + 4 +8+8+4+8+8+8+8=3 = 60

To Write Subarray, I was able to do this with loop:-

{
            for(int j = i ; j <= n ; j++)
            {
                for(int k = i ; k < j ; k++)
                {
                    Console.Write(arr[k] + " ," );

                }

        Console.WriteLine(" " );
            }
        }

    }

After this, I was trying to store maximum values in the Dictionary data structure but was not able to find where exactly use dictionary structure and how to use Math.max statement.

IDictionary<int, int> maxValue = new Dictionary<int, int>();

Body:
If you would only need the sum, then it could be solved in O(n). Because you need to print the sub-arrays this is not possible. But it also makes it pretty easy (I don't know C#, replace the print with what you need):

int total = 0;
for (int start = 0; start < n; start++) {
    for (int end = start + 1; end <= n; end++) {
        int max = arr[start];
        print(arr[start]);
        for (int i = start + 1; i < end; i++) {
            print(", " + arr[i]);
            if (arr[i] > max)
                max = arr[i];
        }
        total += max;
        print("\n");
    }
    print("\n");
}
print(total); // or whatever you want to do with it

This avoids the last comma, but you can switch it back if you want to. Also readable variable names can be helpful.

end is not inclusive, I prefer it that way because then you could get the length of the sub-array with end - start. E.g. Java's substring works exactly the same.


问:
Static UILabel not showing in uiview
I have create a few static UILabel text in Interface Builder, but when running the application. the label is not shown in the application itself, i do not know why.

all other stuff like textfield, buttons except the label is not working
can anybody advise me what had gone wrong ?

This is in IB

this is in App

```<code>#import "SettingsViewController.h"

@implementation SettingsViewController

@synthesize drinkLimitText;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {

    appDelegate = (DrinkTabsAndNavAppDelegate *)[[UIApplication sharedApplication] delegate];
    [super viewDidLoad];

    NSLog(@"subView:%d",[self.view.subviews count]);
}

- (void) viewWillAppear:(BOOL)animated {

    if ([appDelegate.drinkLimit floatValue] >= 0)
        drinkLimitText.text = [NSString stringWithFormat:@"%.0f", [appDelegate.drinkLimit floatValue]];
    else
        drinkLimitText.text = @"0";

    [super viewWillAppear:animated];
}

- (IBAction)textFieldDoneEditing:(id)sender{
    NSDecimalNumber *tempValue = [[NSDecimalNumber alloc] initWithString:drinkLimitText.text];
    if (tempValue == [NSDecimalNumber notANumber] || [tempValue doubleValue] < 0) {
        NSString *msg = [[NSString alloc] initWithFormat: @"Make sure to enter a positive number."];
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Hang on..."
                              message:msg
                              delegate:self
                              cancelButtonTitle:@"Ok"
                              otherButtonTitles:nil];
        [alert show];
        [alert release];
        [msg release];
    } else {
        [sender resignFirstResponder];
        [self updateDrinkLimit];
    }
    [tempValue release];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)updateDrinkLimit {

    NSDecimalNumber *newLimit = [[NSDecimalNumber alloc] initWithString:[drinkLimitText text]];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([newLimit floatValue] >= 0) {
        [defaults setFloat:[newLimit floatValue] forKey:kDrinkLimitKey];
        appDelegate.drinkLimit = newLimit;
    } else {
        [defaults setFloat:0 forKey:kDrinkLimitKey];
        appDelegate.drinkLimit = 0;
    }
    [newLimit release];
}

- (IBAction)openOntrackWebsite {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.ontrack.org.au/"]];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [drinkLimitText release];

    [super dealloc];
}

@end
</code>```

答:
Clean your project and build again.

This is one of the most common problem with Xcode.

ContentLicense: CC BY-SA 3.0

Title: Static UILabel not showing in uiview

Body:
I have create a few static UILabel text in Interface Builder, but when running the application. the label is not shown in the application itself, i do not know why.

all other stuff like textfield, buttons except the label is not working
can anybody advise me what had gone wrong ?

This is in IB

this is in App

#import "SettingsViewController.h"

@implementation SettingsViewController

@synthesize drinkLimitText;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {

    appDelegate = (DrinkTabsAndNavAppDelegate *)[[UIApplication sharedApplication] delegate];
    [super viewDidLoad];

    NSLog(@"subView:%d",[self.view.subviews count]);
}

- (void) viewWillAppear:(BOOL)animated {

    if ([appDelegate.drinkLimit floatValue] >= 0)
        drinkLimitText.text = [NSString stringWithFormat:@"%.0f", [appDelegate.drinkLimit floatValue]];
    else
        drinkLimitText.text = @"0";

    [super viewWillAppear:animated];
}

- (IBAction)textFieldDoneEditing:(id)sender{
    NSDecimalNumber *tempValue = [[NSDecimalNumber alloc] initWithString:drinkLimitText.text];
    if (tempValue == [NSDecimalNumber notANumber] || [tempValue doubleValue] < 0) {
        NSString *msg = [[NSString alloc] initWithFormat: @"Make sure to enter a positive number."];
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Hang on..."
                              message:msg
                              delegate:self
                              cancelButtonTitle:@"Ok"
                              otherButtonTitles:nil];
        [alert show];
        [alert release];
        [msg release];
    } else {
        [sender resignFirstResponder];
        [self updateDrinkLimit];
    }
    [tempValue release];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)updateDrinkLimit {

    NSDecimalNumber *newLimit = [[NSDecimalNumber alloc] initWithString:[drinkLimitText text]];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([newLimit floatValue] >= 0) {
        [defaults setFloat:[newLimit floatValue] forKey:kDrinkLimitKey];
        appDelegate.drinkLimit = newLimit;
    } else {
        [defaults setFloat:0 forKey:kDrinkLimitKey];
        appDelegate.drinkLimit = 0;
    }
    [newLimit release];
}

- (IBAction)openOntrackWebsite {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.ontrack.org.au/"]];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [drinkLimitText release];

    [super dealloc];
}

@end


问:
Why are components not updating their content after a call to setState()?
I am trying to show user-specific data in a simple page using React. However, even after being able to fetch the user data using axios for HTTP requests and calling setState() to update the state of the root component, the data shown in the page is still not changing.

Here is the code for the main component:

    class UserPage extends React.Component {
    constructor (props) {
        super (props)

        this.state = {userId: null, username: null, clientId: null, jobs: null}
    }

    componentDidMount () {
        getSessionUserData ()
        .then (res => {
            this.setState({userId: res.data.id, username: res.data.username, clientId: res.data.client_id})
        })
    }

    render () {
        console.log ("rendering", this.state)
        return (

                <PageHeader text={"Welcome, " + this.state.username} id="user-page-header"/>

        )
    }
}
```
<p>As you can see, <code>PageHeader</code> takes data from the main component's state. Here is the code for the <code>PageHeader</code> component:</p>
<pre class="lang-js prettyprint-override"><code>export class PageHeader extends React.Component {
    constructor (props) {
        super(props)

        this.state = {text: props.text}
    }

    render () {
        console.log ("rendering header with text: ", this.props.text)
        return (
            <h1 id={this.props.id}>{this.state.text}</h1>
        )
    }
}
</code>```

I added the console.log() inside the UserPage component's render() method in order to check if it was being called after setState() and to make sure the state had been updated, and it turns out it is indeed being called, and the state is indeed being updated. Here is an image of what the console prints out whenever I reload the page:

Image showing page and console output

In the image you can see that the render() method is being called again after setState() and the state has the new user data. Also, I added console logs for the PageHeader component's render() method to check if for some reason it was not being re-rendered, but they are being printed and with the correct text, so I don't quite understand why the data in the page is not changing. Could you please help me figure out why this is happening?

答:
You are passing to

```<code><h1 id={this.props.id}>{this.state.text}</h1>
</code>```

State which was set in the constructor. Constructor is called once with initial props. Since you set ID to component, it is not recreated (reused). And you print this.props.text but render this.state.text. So you either have to implement 'componentDidUpdate' to react on props changes and there update your state or just simply replace
{this.state.text}
 to
{this.props.text}

Body:
I am trying to show user-specific data in a simple page using React. However, even after being able to fetch the user data using axios for HTTP requests and calling setState() to update the state of the root component, the data shown in the page is still not changing.

Here is the code for the main component:

    class UserPage extends React.Component {
    constructor (props) {
        super (props)

        this.state = {userId: null, username: null, clientId: null, jobs: null}
    }

    componentDidMount () {
        getSessionUserData ()
        .then (res => {
            this.setState({userId: res.data.id, username: res.data.username, clientId: res.data.client_id})
        })
    }

    render () {
        console.log ("rendering", this.state)
        return (

                <PageHeader text={"Welcome, " + this.state.username} id="user-page-header"/>

        )
    }
}

As you can see, PageHeader takes data from the main component's state. Here is the code for the PageHeader component:

export class PageHeader extends React.Component {
    constructor (props) {
        super(props)

        this.state = {text: props.text}
    }

    render () {
        console.log ("rendering header with text: ", this.props.text)
        return (

{this.state.text}

        )
    }
}

I added the console.log() inside the UserPage component's render() method in order to check if it was being called after setState() and to make sure the state had been updated, and it turns out it is indeed being called, and the state is indeed being updated. Here is an image of what the console prints out whenever I reload the page:

Image showing page and console output

In the image you can see that the render() method is being called again after setState() and the state has the new user data. Also, I added console logs for the PageHeader component's render() method to check if for some reason it was not being re-rendered, but they are being printed and with the correct text, so I don't quite understand why the data in the page is not changing. Could you please help me figure out why this is happening?

Body:
You are passing to

<h1 id={this.props.id}>{this.state.text}</h1>

State which was set in the constructor. Constructor is called once with initial props. Since you set ID to component, it is not recreated (reused). And you print this.props.text but render this.state.text. So you either have to implement 'componentDidUpdate' to react on props changes and there update your state or just simply replace <h1 id={this.props.id}>{this.state.text}</h1> to <h1 id={this.props.id}>{this.props.text}</h1>


问:
Openssl key generation on OS X failing
I am attempting to run our unit tests on a new clean mac for a Spring project. One test requires the generation of ssl keys.

I have installed openssl via homebrew but the error continues to persist.

Please see error below:

```<code>Using configuration from /Users/myuser/workspace/project/webapp/target/test-data/clientvpn/acc1/openssl.conf
default is an unsupported message digest type
13499:error:02001002:system library:fopen:No such file or directory:/BuildRoot/Library/Caches/com.apple.xbs/Sources/OpenSSL098/OpenSSL098-59/src/crypto/bio/bss_file.c:126:fopen('./index.txt.attr','rb')
13499:error:2006D080:BIO routines:BIO_new_file:no such file:/BuildRoot/Library/Caches/com.apple.xbs/Sources/OpenSSL098/OpenSSL098-59/src/crypto/bio/bss_file.c:129:
13499:error:0E078072:configuration file routines:DEF_LOAD:no such file:/BuildRoot/Library/Caches/com.apple.xbs/Sources/OpenSSL098/OpenSSL098-59/src/crypto/conf/conf_def.c:197:
</code>```

答:
This worked for me on Montery (12.2)

```<code>brew install openssl
brew link openssl # outputs :

Warning: Refusing to link macOS provided/shadowed software: openssl@3
If you need to have openssl@3 first in your PATH, run:
  echo 'export PATH="/usr/local/opt/openssl@3/bin:$PATH"' >> ~/.zshrc

For compilers to find openssl@3 you may need to set:
  export LDFLAGS="-L/usr/local/opt/openssl@3/lib"
  export CPPFLAGS="-I/usr/local/opt/openssl@3/include"

For pkg-config to find openssl@3 you may need to set:
  export PKG_CONFIG_PATH="/usr/local/opt/openssl@3/lib/pkgconfig"
</code>```

I was just using the command so I did :

```<code>echo 'export PATH="/usr/local/opt/openssl@3/bin:$PATH"' >> ~/.zshrc
</code>```

That worked, old output :

```<code>➜  ca git:(master) openssl version
LibreSSL 2.8.3
</code>```

After:

```<code>➜  ca git:(master) source ~/.zshrc
➜  ca git:(master) openssl version
OpenSSL 3.0.1 14 Dec 2021 (Library: OpenSSL 3.0.1 14 Dec 2021)
</code>```

Note : the other options that may be needed depending on your needs.
Note 2 : my default shell is zsh, add it to your bashrc if you use bash, or to your shell of choice and it's PATH.

Title: Openssl key generation on OS X failing

Body:
I am attempting to run our unit tests on a new clean mac for a Spring project. One test requires the generation of ssl keys.

I have installed openssl via homebrew but the error continues to persist.

Please see error below:

Using configuration from /Users/myuser/workspace/project/webapp/target/test-data/clientvpn/acc1/openssl.conf
default is an unsupported message digest type
13499:error:02001002:system library:fopen:No such file or directory:/BuildRoot/Library/Caches/com.apple.xbs/Sources/OpenSSL098/OpenSSL098-59/src/crypto/bio/bss_file.c:126:fopen('./index.txt.attr','rb')
13499:error:2006D080:BIO routines:BIO_new_file:no such file:/BuildRoot/Library/Caches/com.apple.xbs/Sources/OpenSSL098/OpenSSL098-59/src/crypto/bio/bss_file.c:129:
13499:error:0E078072:configuration file routines:DEF_LOAD:no such file:/BuildRoot/Library/Caches/com.apple.xbs/Sources/OpenSSL098/OpenSSL098-59/src/crypto/conf/conf_def.c:197:

Body:
This worked for me on Montery (12.2)

brew install openssl
brew link openssl # outputs :

Warning: Refusing to link macOS provided/shadowed software: openssl@3
If you need to have openssl@3 first in your PATH, run:
  echo 'export PATH="/usr/local/opt/openssl@3/bin:$PATH"' >> ~/.zshrc

For compilers to find openssl@3 you may need to set:
  export LDFLAGS="-L/usr/local/opt/openssl@3/lib"
  export CPPFLAGS="-I/usr/local/opt/openssl@3/include"

For pkg-config to find openssl@3 you may need to set:
  export PKG_CONFIG_PATH="/usr/local/opt/openssl@3/lib/pkgconfig"

I was just using the command so I did :

echo 'export PATH="/usr/local/opt/openssl@3/bin:$PATH"' >> ~/.zshrc

That worked, old output :

➜  ca git:(master) openssl version
LibreSSL 2.8.3

After:

➜  ca git:(master) source ~/.zshrc
➜  ca git:(master) openssl version
OpenSSL 3.0.1 14 Dec 2021 (Library: OpenSSL 3.0.1 14 Dec 2021)

Note : the other options that may be needed depending on your needs.
Note 2 : my default shell is zsh, add it to your bashrc if you use bash, or to your shell of choice and it's PATH.


问:
In VS Code, how can I break my project into multiple files?
I am trying to make a transition from Matlab to Python.  I completed the Udemy Python Bootcamp; it used Jupyter Notebook, which was a fine learning environment.  Now I'm trying to use VS Code - It has nice debugging features, but I can't figure out how to break a program into separate files.

In Matlab, my top-level program for a project would call functions that were in separate files in the same folder.  I just tried to do the same with a simple Python program in VS Code, and got a weird error message.  If I put the function and main program in the same file, then it works.

How can I use separate files for my Python functions, and have the top-level program know how to find them?

答:
You need to import the file at the beginning of your python script.

Example: If you have main.py and function.py and want to use the function test() from function.py, you have to write
the code below in your main.py file.

```<code>import function

function.test()
</code>```

or

```<code>from function import test

test()
</code>```

Body:
You need to import the file at the beginning of your python script.

Example: If you have main.py and function.py and want to use the function test() from function.py, you have to write
the code below in your main.py file.

import function

function.test()

or

from function import test

test()


问:
Would this class have a Strict Weak Ordering
Say I had class/struct Foo

```<code>struct Foo {
    int a, b;
    bool operator< (Foo const& r){
        return a < r.a;
    }
    bool operator== (Foo const& r){
        return a==r.a&&b==r.b;
    }
};
Foo bar = { 5, 1 };
Foo baz = { 5, 2 };
</code>```

Now bar == baz is false but so are bar < baz and baz < bar.

Note that here the ordering completely ignores b but b is part of the equality relation.

答:
According to the Wikipedia entry on strict weak ordering, it has the following properties:

For all x, it is not the case that x < x (irreflexivity).

For all x ≠ y, if x < y then it is not the case that y < x
  (asymmetric).

For all x, y, and z, if x < y and y < z then x < z (transitivity).

For all x, y, and z, if x is incomparable with y, and y is
  incomparable with z, then x is incomparable with z (transitivity of
  equivalence).

operator< for your class satisfies all these properties, and that by itself is sufficient to qualify as having strict weak ordering, because by definition the binary relationship required is <, not ==.

However, as Peter mentions in his answer, defining operator== that takes into consideration an additional member variable can lead to unintuitive results that will likely confuse the users of your class.

Body:
Say I had class/struct Foo

struct Foo {
    int a, b;
    bool operator< (Foo const& r){
        return a < r.a;
    }
    bool operator== (Foo const& r){
        return a==r.a&&b==r.b;
    }
};
Foo bar = { 5, 1 };
Foo baz = { 5, 2 };

Now bar == baz is false but so are bar < baz and baz < bar.

Note that here the ordering completely ignores b but b is part of the equality relation.


问:
Kotlin: Is there a tool that allows me to control parallelism when executing suspend functions?
I'm trying to execute certain suspend function multiple times, in such a way that never more than N of these are being executed at the same time.

For those acquainted with Akka and Scala Streaming libraries, something like mapAsync.

I did my own implementation using one input channel (as in kotlin channels) and N output channels. But it seems cumbersome and not very efficient.

The code I'm currently using is somewhat like this:

val inChannel = Channel<T>()
val outChannels = (0..n).map{
  Channel<T>()
}
launch{
   var i = 0
   for(t in inChannel){

     outChannels[i].offer(t)
     i = ((i+1)%n)
   }
}
outChannels.forEach{outChannel ->
  launch{
     for(t in outChannel){
        fn(t)
     }
  }
}
```
<p>Of course it has error management and everything, but still...</p>
<p>Edit: I did the following test, and it failed.</p>
<pre class="lang-kotlin prettyprint-override"><code>test("Parallelism is correctly capped") {
            val scope = CoroutineScope(Dispatchers.Default.limitedParallelism(3))
            var num = 0
            (1..100).map {
                scope.launch {
                    num ++
                    println("started $it")
                    delay(Long.MAX_VALUE)
                }
            }

            delay(500)
            assertEquals(3,num)

        }
</code>```

答:
Other answers already explained that it depends whether you need to limit parallelism or concurrency. If you need to limit concurrency, then you can do this similarly to your original solution, but with only a single channel:

val channel = Channel<T>()
repeat(n) {
    launch {
        for(t in channel){
            fn(t)
        }
    }
}
```

Also note that offer() in your example does not guarantee that the task will be ever executed. If the next consumer in the round robin is still occupied with the previous task, the new task is simply ignored.

Body:
I'm trying to execute certain suspend function multiple times, in such a way that never more than N of these are being executed at the same time.

For those acquainted with Akka and Scala Streaming libraries, something like mapAsync.

I did my own implementation using one input channel (as in kotlin channels) and N output channels. But it seems cumbersome and not very efficient.

The code I'm currently using is somewhat like this:

val inChannel = Channel<T>()
val outChannels = (0..n).map{
  Channel<T>()
}
launch{
   var i = 0
   for(t in inChannel){

     outChannels[i].offer(t)
     i = ((i+1)%n)
   }
}
outChannels.forEach{outChannel ->
  launch{
     for(t in outChannel){
        fn(t)
     }
  }
}

Of course it has error management and everything, but still...

Edit: I did the following test, and it failed.

test("Parallelism is correctly capped") {
            val scope = CoroutineScope(Dispatchers.Default.limitedParallelism(3))
            var num = 0
            (1..100).map {
                scope.launch {
                    num ++
                    println("started $it")
                    delay(Long.MAX_VALUE)
                }
            }

            delay(500)
            assertEquals(3,num)

        }

Body:
Other answers already explained that it depends whether you need to limit parallelism or concurrency. If you need to limit concurrency, then you can do this similarly to your original solution, but with only a single channel:

val channel = Channel<T>()
repeat(n) {
    launch {
        for(t in channel){
            fn(t)
        }
    }
}

Also note that offer() in your example does not guarantee that the task will be ever executed. If the next consumer in the round robin is still occupied with the previous task, the new task is simply ignored.


问:
Find the name of the employees with a particular letter
I'm having the schemas like:

```<code>Employee (Empno, Empname, City)
Project (Pno, Pname)
Part (Partno, Partname, Color)
Use (Pno, Partno)
Works (Empno, Pno)
</code>```

From these schemas I had created a sample tables:

The goal is to find the names of the projects where no employees are working whose name starts with 'S'

I'm using ORACLE 11g Express Edition.
Here I used this query :
For Names:

```<code>Select DISTINCT Pname FROM
(
SELECT w.Empno, p.Pno, p.Pname, e.Empname
FROM Works w
LEFT JOIN Project p ON w.Pno=p.Pno
LEFT JOIN Employee e ON e.Empno=w.Empno
)
WHERE Empname not like 'S%';
</code>```

答:
If you think about how to explain the process. There are several methods to solve this including:

You would start with each of the Projects and find out if there does not exist anybody who Works on the project where the Employees name starts with S. You can do this using NOT EXISTS.

or

Again, start with a Project and find, if any, who Works on the project and their corresponding Employees details using LEFT OUTER JOINs (but starting from the Project) and filtering for employee names starting with S in the JOIN condition. Then GROUP BY the primary key for the project and find those projects HAVING a COUNT of zero matched employees.

Since this appears to be a homework question, I'll leave the rest for you to complete.

Body:
I'm having the schemas like:

Employee (Empno, Empname, City)
Project (Pno, Pname)
Part (Partno, Partname, Color)
Use (Pno, Partno)
Works (Empno, Pno)

From these schemas I had created a sample tables:

The goal is to find the names of the projects where no employees are working whose name starts with 'S'

I'm using ORACLE 11g Express Edition.
Here I used this query :
For Names:

Select DISTINCT Pname FROM
(
SELECT w.Empno, p.Pno, p.Pname, e.Empname
FROM Works w
LEFT JOIN Project p ON w.Pno=p.Pno
LEFT JOIN Employee e ON e.Empno=w.Empno
)
WHERE Empname not like 'S%';


答:
If you use this.props.text instead of the this.state.text in the h1 tag then it should work. The state in the PageHeader component is being set on the constructor, which will only happen on the component creation, it will not be re-set on the second render.</p>
```<code>export class PageHeader extends React.Component {
    constructor (props) {
        super(props)

        this.state = {text: props.text}
    }

    render () {
        console.log ("rendering header with text: ", this.props.text)
        return (
            <h1 id={this.props.id}>{this.props.text}</h1>
        )
    }
}
</code>```

Title: Why are components not updating their content after a call to setState()?

Body:
If you use this.props.text instead of the this.state.text in the h1 tag then it should work. The state in the PageHeader component is being set on the constructor, which will only happen on the component creation, it will not be re-set on the second render.

export class PageHeader extends React.Component {
    constructor (props) {
        super(props)

        this.state = {text: props.text}
    }

    render () {
        console.log ("rendering header with text: ", this.props.text)
        return (
            <h1 id={this.props.id}>{this.props.text}</h1>
        )
    }
}


问:
Database Design For Developing 'Quiz' Web Application using PHP and MySQL
So, I'm trying to learn PHP and MySQL (I have a basic understanding of both; I've read the first half of both Head First SQL and Head First PHP & MySQL) and I figure the best way to solidify my knowledge is by building something rather than reading.

With that in mind, I would like to create a basic webpage that connects to a MySQL database on a server.  I will build a basic HTML form and allow users to input basic information, such as: last_name, first_name, email, birthday, gender.

My problem is I don't know how to design a database that will record the results of a basic quiz - I want just 5 multiple-choice problems.  Eventually, I would like to display the results of the user versus the previous users' results.

If you could help me understand how to design table(s) for a 5-question Quiz I'd appreciate it.  Thanks!

答:
I am not sure how new you are to programming in general, but even if you are just getting started, I would recommend you use a framework.

Using a framework will guide you by providing best-practice implementations of the tools you'll need in your project.

I personally use Symfony for php projects, and I would suggest you check out their guides and tutorials. Symfony is a well-established framework and it's based on widely accepted designs.

To answer your question more directly, though, I would suggest something like this for your application:

```<code> - user
  - id (PK)
  - last_name
  - first_name
  - email
  - gender

 - quiz
  - id (PK)
  - title

 - quiz_question
  - id (PK)
  - quiz_id (FK)
  - text

 - quiz_question_option
  - id (PK)
  - quiz_question_id (FK)
  - text
  - is_correct

 - quiz_user_answer
   - id (PK)
   - quiz_question_id (FK)
   - quiz_question_option_id  // this is the answer.
</code>```

The above would allow you to define multiple quizes each having multiple questions and create answer sets (a user's set of answers to a quiz) and record each answer.

Hope that helps :)

Body:
I am not sure how new you are to programming in general, but even if you are just getting started, I would recommend you use a framework.

Using a framework will guide you by providing best-practice implementations of the tools you'll need in your project.

I personally use Symfony for php projects, and I would suggest you check out their guides and tutorials. Symfony is a well-established framework and it's based on widely accepted designs.

To answer your question more directly, though, I would suggest something like this for your application:

 - user
  - id (PK)
  - last_name
  - first_name
  - email
  - gender

 - quiz
  - id (PK)
  - title

 - quiz_question
  - id (PK)
  - quiz_id (FK)
  - text

 - quiz_question_option
  - id (PK)
  - quiz_question_id (FK)
  - text
  - is_correct

 - quiz_user_answer
   - id (PK)
   - quiz_question_id (FK)
   - quiz_question_option_id  // this is the answer.

The above would allow you to define multiple quizes each having multiple questions and create answer sets (a user's set of answers to a quiz) and record each answer.

Hope that helps :)


问:
FFmpeg-Python audio getting dropped in final video
Im trying to place a video on top of a background image but the output video is getting generated without audio. Is there any way to keep the audio as it is?

```<code>def ConvertVideo(source,background,start,end,dest):
    stream = ffmpeg.input(source)
    strea1 = ffmpeg.input(background)
    duration = end - start
    stream = stream.trim(start=start,duration=duration).filter('setpts', 'PTS-STARTPTS')
    stream = stream.crop(100,0,1080,720)
    stream = ffmpeg.overlay(strea1,stream,x=0,y=180)
    stream = stream.output(dest)
</code>```

Does anyone know why audio gets dropped? Is there any workaround to this problem?

答:
We have to add the audio stream explicitly.

Something like: ffmpeg.output(overlaid_vid_stream, audio_stream, dest).

Start by creating synthetic input video and background using FFmpeg CLI (just for making the posted solution reproducible and "self contained").

Create input video with audio:

```<code> ffmpeg -y -f lavfi -i testsrc=size=128x72:rate=1 -f lavfi -i sine=frequency=400 -f lavfi -i sine=frequency=1000 -filter_complex "[1:a][2:a]amix=inputs=2" -vcodec libx264 -g 10 -crf 17 -pix_fmt yuv420p -acodec aac -ar 22050 -t 50 in.mp4
</code>```

Create yellow background image:

```<code> ffmpeg.exe -y -f lavfi -i color=yellow:size=128x72 -frames:v 1 background.png
</code>```

For the example, the size is 128x72 (assuming your input is 1280x720).

The following code sample applies trim, setpts, crop and overlay filters, and adds the source audio:

```<code>source = 'in.mp4'
background = 'background.png'
dest = 'out.mp4'
end = 40
start = 10

duration = end - start

vid_stream = ffmpeg.input(source).video  # Source video stream
audio_stream = ffmpeg.input(source).audio  # Source audio stream
vid_background = ffmpeg.input(background).video  # Background video stream

trimed_vid_stream = vid_stream.trim(start=start, duration=duration).filter('setpts', 'PTS-STARTPTS').crop(10, 0, 108, 72)  # Source video stream after trimming and cropping
overlaid_vid_stream = ffmpeg.overlay(vid_background, trimed_vid_stream, x=0, y=18)  # Video stream overlay of background and trimed_vid_stream

trimed_audio_stream = audio_stream.filter('atrim', start=start, duration=duration).filter('asetpts', 'PTS-STARTPTS')  # Trimming the audio
output_video_and_audio = ffmpeg.output(overlaid_vid_stream, trimed_audio_stream, dest)  # Output - video applies overlaid_vid_stream, and audio applies trimmed source audio

output_video_and_audio.overwrite_output().run() # Execute FFmpeg
</code>```

I modified your naming to be more meaningful (naming everything stream makes it difficult to follow).

I also removed the method, and set arguments to specific values (just for making the posted solution reproducible).

The solution applies the following main stages:

Create references to the video and the audio streams:

```<code> vid_stream = ffmpeg.input(source).video  # Source video stream
 audio_stream = ffmpeg.input(source).audio  # Source audio stream
</code>```

Define video filters:

```<code> vid_background = ffmpeg.input(background).video  # Background video stream
 trimed_vid_stream = vid_stream.trim(start=start, duration=duration).filter('setpts', 'PTS-STARTPTS').crop(10, 0, 108, 72)  # Source video stream after trimming and cropping
 overlaid_vid_stream = ffmpeg.overlay(vid_background, trimed_vid_stream, x=0, y=18)  # Video stream overlay of background and trimed_vid_stream
</code>```

Define audio filters (trimming the audio):

```<code> trimed_audio_stream = audio_stream.filter('atrim', start=start, duration=duration).filter('asetpts', 'PTS-STARTPTS')  # Trimming the audio
</code>```

Define the output to include the "filtered" video and the trimmed audio:

```<code> output_video_and_audio = ffmpeg.output(overlaid_vid_stream, trimed_audio_stream, dest)  # Output - video applies overlaid_vid_stream, and audio applies trimmed source audio
</code>```

Execute FFmpeg:

```<code> output_video_and_audio.overwrite_output().run() # Execute FFmpeg
</code>```

Sample output frame:

The video includes a beeping audio...

Body:
Im trying to place a video on top of a background image but the output video is getting generated without audio. Is there any way to keep the audio as it is?

def ConvertVideo(source,background,start,end,dest):
    stream = ffmpeg.input(source)
    strea1 = ffmpeg.input(background)
    duration = end - start
    stream = stream.trim(start=start,duration=duration).filter('setpts', 'PTS-STARTPTS')
    stream = stream.crop(100,0,1080,720)
    stream = ffmpeg.overlay(strea1,stream,x=0,y=180)
    stream = stream.output(dest)

Does anyone know why audio gets dropped? Is there any workaround to this problem?

Body:
We have to add the audio stream explicitly.

Something like: ffmpeg.output(overlaid_vid_stream, audio_stream, dest).

Start by creating synthetic input video and background using FFmpeg CLI (just for making the posted solution reproducible and "self contained").

Create input video with audio:

 ffmpeg -y -f lavfi -i testsrc=size=128x72:rate=1 -f lavfi -i sine=frequency=400 -f lavfi -i sine=frequency=1000 -filter_complex "[1:a][2:a]amix=inputs=2" -vcodec libx264 -g 10 -crf 17 -pix_fmt yuv420p -acodec aac -ar 22050 -t 50 in.mp4

Create yellow background image:

 ffmpeg.exe -y -f lavfi -i color=yellow:size=128x72 -frames:v 1 background.png

For the example, the size is 128x72 (assuming your input is 1280x720).

The following code sample applies trim, setpts, crop and overlay filters, and adds the source audio:

source = 'in.mp4'
background = 'background.png'
dest = 'out.mp4'
end = 40
start = 10

duration = end - start

vid_stream = ffmpeg.input(source).video  # Source video stream
audio_stream = ffmpeg.input(source).audio  # Source audio stream
vid_background = ffmpeg.input(background).video  # Background video stream

trimed_vid_stream = vid_stream.trim(start=start, duration=duration).filter('setpts', 'PTS-STARTPTS').crop(10, 0, 108, 72)  # Source video stream after trimming and cropping
overlaid_vid_stream = ffmpeg.overlay(vid_background, trimed_vid_stream, x=0, y=18)  # Video stream overlay of background and trimed_vid_stream

trimed_audio_stream = audio_stream.filter('atrim', start=start, duration=duration).filter('asetpts', 'PTS-STARTPTS')  # Trimming the audio
output_video_and_audio = ffmpeg.output(overlaid_vid_stream, trimed_audio_stream, dest)  # Output - video applies overlaid_vid_stream, and audio applies trimmed source audio

output_video_and_audio.overwrite_output().run() # Execute FFmpeg

I modified your naming to be more meaningful (naming everything stream makes it difficult to follow).

I also removed the method, and set arguments to specific values (just for making the posted solution reproducible).

The solution applies the following main stages:

Create references to the video and the audio streams:

 vid_stream = ffmpeg.input(source).video  # Source video stream
 audio_stream = ffmpeg.input(source).audio  # Source audio stream

Define video filters:

 vid_background = ffmpeg.input(background).video  # Background video stream
 trimed_vid_stream = vid_stream.trim(start=start, duration=duration).filter('setpts', 'PTS-STARTPTS').crop(10, 0, 108, 72)  # Source video stream after trimming and cropping
 overlaid_vid_stream = ffmpeg.overlay(vid_background, trimed_vid_stream, x=0, y=18)  # Video stream overlay of background and trimed_vid_stream

Define audio filters (trimming the audio):

 trimed_audio_stream = audio_stream.filter('atrim', start=start, duration=duration).filter('asetpts', 'PTS-STARTPTS')  # Trimming the audio

Define the output to include the "filtered" video and the trimmed audio:

 output_video_and_audio = ffmpeg.output(overlaid_vid_stream, trimed_audio_stream, dest)  # Output - video applies overlaid_vid_stream, and audio applies trimmed source audio

Execute FFmpeg:

 output_video_and_audio.overwrite_output().run() # Execute FFmpeg

Sample output frame:

The video includes a beeping audio...


问:
Multiple path names for a same component in React Router
I am using the same component for three different routes:

```<code><Router>
    <Route path="/home" component={Home} />
    <Route path="/users" component={Home} />
    <Route path="/widgets" component={Home} />
</Router>
</code>```

Is there anyway to combine it, to be like:

```<code><Router>
    <Route path=["/home", "/users", "/widgets"] component={Home} />
</Router>
</code>```

答:
here is a little function to transform your custom routes with a paths prop to multiple standard routes supported by react-router v6, with path prop:

const normalizeRoutes = (routes) =>
  routes.reduce((acc, curr) => {
    const newRoute = curr.children
      ? { ...curr, children: normalizeRoutes(curr.children) }
      : curr;
    if (newRoute.paths) {
      return [
        ...acc,
        ...newRoute.paths.map((path) => {
          const { paths, ...rest } = newRoute;
          return { ...rest, path };
        })
      ];
    }
    return [...acc, newRoute];
  }, []);
```

Body:
I am using the same component for three different routes:

<Router>
    <Route path="/home" component={Home} />
    <Route path="/users" component={Home} />
    <Route path="/widgets" component={Home} />
</Router>

Is there anyway to combine it, to be like:

<Router>
    <Route path=["/home", "/users", "/widgets"] component={Home} />
</Router>


问:
NavLink returns active to all links and no solution in SO seems to work
It seems none of the solutions presented elsewhere works, so I decided to ask. No matter what I do, I can't get the NavLinks to be rendered differently if they are active or not. I took the ternary operator straight from the part about NavLinks in react-router-dom's documentation and I'd try to create a function to avoid having all this code written three times, but before that I'd like to at least have the correct rendering working.

(side question: why does it break if I remove the Router tags from the return statement? They're there because, before I needed the NavLinks for different styling, I was using regular routes, but if I take them out it breaks with a message about useHref, something like that)

Here's my return statement and the styled-components below it:

```<code>return (
        <>
            <GlobalStyles />
            <Router>
                <Header />
                <Wrapper>
                    <NavBar>
                        <NavLink
                            to="/search"
                            exact
                            className={(isActive) =>
                                "nav-link" + (!isActive ? " inactive" : "")
                            }>
                            Search song
                        </NavLink>
                        <NavLink
                            to="/weekly-thread"
                            exact
                            className={(isActive) =>
                                "nav-link" + (!isActive ? " inactive" : "")
                            }>
                            Weekly thread
                        </NavLink>
                        <NavLink
                            to="/game"
                            exact
                            className={(isActive) =>
                                "nav-link" + (!isActive ? " inactive" : "")
                            }>
                            Game
                        </NavLink>
                    </NavBar>
                </Wrapper>
            </Router>
        </>
    );
};

const Wrapper = styled.div`
    width: 100vw;
    height: 100vh;
    position: absolute;
    z-index: -1;
`;
const NavBar = styled.div`
    display: flex;
    padding: 20px 20px;
    position: relative;
    gap: 20px;
    font-size: 18px;
    a {
        text-decoration: none;
    }
    .nav-link {
        color: blue;
        &:inactive {
            color: black;
        }
    }
`;

</code>```

EDIT: it's getting weirder. After even simply pasting the code from the answer below and not getting any results, I tried to mess with the font size for the active NavLink. To my surprise, now something changed, but in totally bizarre way, as it made the first element stay as it were before and second and third got transformed just in terms of font size, but nothing else. When I click on the other NavLinks, the URL changes, but they remain the same: the first in the original size, the other two altered.

SECOND EDIT: Trying to debug this a little further, I've done this to one of my NavLinks and the result is very weird:

```<code><NavLink to="/search" exact className={(isActive) => {
    console.log(isActive);
    isActive === false ? console.log(isActive) : console.log("foo");
}}>Search song</NavLink>
</code>```

Now, the first console.log returns the actual value of isActive, but the second and third console.logs always return, "foo", which is the second value in the ternary operator, even if I change "isActive === false" to "isActive === true", which should swap them. I have no idea what is going on here.

答:
Router

You might want to read up on the docs.

The primary components page explains why you would need a router.

It provides information for the other components; IE what the current route is.

NavLink

NavLink should be able to set their active class themselves, based on if the  router is matching on the to props of the NavLink

see this CodePen for an example.

Note that you would still need need to provide the CSS for the class that is applied. If you're using a framework like bootstrap, or material-ui; they would usually have a .active css styling already in there by default.

CSS

The css rule might be incorrect, there seems to be a colon at &:inactive which probable should be .inactive class:

```<code>.nav-link {
    color: blue;
    &.inactive {
      color: black;
    }
  }
</code>```

codepen

Body:
It seems none of the solutions presented elsewhere works, so I decided to ask. No matter what I do, I can't get the NavLinks to be rendered differently if they are active or not. I took the ternary operator straight from the part about NavLinks in react-router-dom's documentation and I'd try to create a function to avoid having all this code written three times, but before that I'd like to at least have the correct rendering working.

(side question: why does it break if I remove the Router tags from the return statement? They're there because, before I needed the NavLinks for different styling, I was using regular routes, but if I take them out it breaks with a message about useHref, something like that)

Here's my return statement and the styled-components below it:

return (
        <>
            <GlobalStyles />
            <Router>

                <Wrapper>
                    <NavBar>
                        <NavLink
                            to="/search"
                            exact
                            className={(isActive) =>
                                "nav-link" + (!isActive ? " inactive" : "")
                            }>
                            Search song
                        </NavLink>
                        <NavLink
                            to="/weekly-thread"
                            exact
                            className={(isActive) =>
                                "nav-link" + (!isActive ? " inactive" : "")
                            }>
                            Weekly thread
                        </NavLink>
                        <NavLink
                            to="/game"
                            exact
                            className={(isActive) =>
                                "nav-link" + (!isActive ? " inactive" : "")
                            }>
                            Game
                        </NavLink>
                    </NavBar>
                </Wrapper>
            </Router>
        </>
    );
};

const Wrapper = styled.div`
    width: 100vw;
    height: 100vh;
    position: absolute;
    z-index: -1;
`;
const NavBar = styled.div`
    display: flex;
    padding: 20px 20px;
    position: relative;
    gap: 20px;
    font-size: 18px;
    a {
        text-decoration: none;
    }
    .nav-link {
        color: blue;
        &:inactive {
            color: black;
        }
    }
`;

EDIT: it's getting weirder. After even simply pasting the code from the answer below and not getting any results, I tried to mess with the font size for the active NavLink. To my surprise, now something changed, but in totally bizarre way, as it made the first element stay as it were before and second and third got transformed just in terms of font size, but nothing else. When I click on the other NavLinks, the URL changes, but they remain the same: the first in the original size, the other two altered.

SECOND EDIT: Trying to debug this a little further, I've done this to one of my NavLinks and the result is very weird:

<NavLink to="/search" exact className={(isActive) => {
    console.log(isActive);
    isActive === false ? console.log(isActive) : console.log("foo");
}}>Search song</NavLink>

Now, the first console.log returns the actual value of isActive, but the second and third console.logs always return, "foo", which is the second value in the ternary operator, even if I change "isActive === false" to "isActive === true", which should swap them. I have no idea what is going on here.

Body:
Router

You might want to read up on the docs.

The primary components page explains why you would need a router.

It provides information for the other components; IE what the current route is.

NavLink

NavLink should be able to set their active class themselves, based on if the  router is matching on the to props of the NavLink

see this CodePen for an example.

Note that you would still need need to provide the CSS for the class that is applied. If you're using a framework like bootstrap, or material-ui; they would usually have a .active css styling already in there by default.

CSS

The css rule might be incorrect, there seems to be a colon at &:inactive which probable should be .inactive class:

.nav-link {
    color: blue;
    &.inactive {
      color: black;
    }
  }

codepen


问:
Why does my autoplay not consistently work on mobile devices?
I have a website with a video that is supposed to autoplay. Last week it was working on both the web browser and mobile devices, but now the video will not autoplay on my mobile device despite the code being the same, and I have to hit a play button for the video to start. The video still autoplays in the web browser. Does anyone know why this is? I have attached an image of my code below.

Code Image

答:
Try doing, using autoplay instead of autoPlay="autoplay"

According to developer.mozilla.org, the attribute is autoplay, not autoPlay


问:
Redirect a controller to main index
I have a controller I am using for redirects called redirect.php. This controller has a single _remap($method).

This _remap method works by attributing any URI string after the redirect controller back into the controller. For example, a request to http://mysite.com/redirect/sometext would send the request back to http://mysite.com/redirect

This is the behavior I want, but how I would make this happen at the index level so instead of having to type http://mysite.com/redirect/sometext , I could type http://mysite.com/sometext and get the same behavior. This is challenging because Index.php is used by CodeIgniter so I can't put the _remap method here. As, I'm not super familiar with routes and .htaccess any help would be appreciated to get this working.

答:
If you wanted to go the routes way, you would make a route for each controller you have, aka controller somepage would have a route $route["somepage"] = "somepage";, then after all of them (at the very bottom of the routes).  Routes work by finding the first matching regex and then using it, so to make sure all of your controllers work, and only catch regular text, you need each of these rules.

Then we make the 'default' rule, this would run for everything that didn't get caught in a previous route check.  Something like $route["(.*)"] = 'redirect/index/$1';.  This would redirect you to the controller redirect, with the first uri segment (segment 3) being the sometext in your example above.  Do note that this will also run for 404 pages, it would run for everything that isn't defined in the above rules.

I don't see a point in this, if I were you I would just send it to the redirect controller, it would make things a bit less messy, but there is of course a way as shown above.

Title: Redirect a controller to main index


问:
Setting state to a zero-filled array with Immer in react-toolkit
I was following the TS usage docs and now I'm trying to clear an array using Redux Toolkit but my turnOffAll(state) reducer causes thousands of rerenders (console log outputs) and an error about it in the browser.

I have read that it's possible to return state, rather than "mutate" it from within turnOffAll.
So I've tried a variation of turnOffAll having: return Array(screenSize.width * screenSize.height).fill(0) but this causes an error in app.jsx that dispatch(turnOffAll()); does not provide enough arguments.

Another approach I tried in turnOffAll is state = initialState; but while this doesn't cause unnececary rerenders, the state is not reset if I do a console.log(useAppSelector((state) => state.pixels)); in app.jsx.

The relevant info from the files are below. This code is the situation in my first paragraph above and causes thousands of rerenders when calling dispatch(turnOffAll()); from app.jsx:

pixelsSlice.ts:

```<code>import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import type { RootState } from "./store";
import { Pixel, ScreenSize } from "./types";

//Defining a type for the slice state
interface PixelsState {
  pixels: Array<number>;
}

const screenSize = { width: 128, height: 59 };

//Define the initial state using the above type.
const initialState: PixelsState = {
  pixels: Array(screenSize.width * screenSize.height).fill(0),
};

export const pixelsSlice = createSlice({
  name: "pixels",
  initialState,
  reducers: {
    turnOn(state, action: PayloadAction<Pixel>) {
      //This may look like mutating state, but Immer makes it ok:
      state.pixels[
        screenSize.width * action.payload.row + action.payload.column
      ] = 1;
    },
    turnOffAll(state) {
      state = initialState;
    },
  },
});

export const { turnOn, turnOffAll } = pixelsSlice.actions;

//Other code such as selectors can use the imported `RootState` type...
export const selectPixels = (state: RootState) => state.pixels;

export default pixelsSlice.reducer;

</code>```

app.tsx:

```<code>import React, { useEffect } from "react";
import { useAppSelector, useAppDispatch } from "./app/hooks";
import { turnOn, turnOffAll } from "./app/pixelsSlice";
import type { Pixel } from "./app/types";

function App() {
  const dispatch = useAppDispatch();

  //Demonstrating reading and writing pixels from the redux store.
  console.log(useAppSelector((state) => state.pixels));

  let p: Pixel = { row: 1, column: 2 };
  dispatch(turnOn(p));
  console.log(useAppSelector((state) => state.pixels));

  dispatch(turnOffAll()); //THIS CAUSES THOUSANDS OF RERENDERS AND CONSOLE LOG OUTPUTS :(
  console.log(useAppSelector((state) => state.pixels));

  return <div className="App"></div>;
}

export default App;
</code>```

hooks.ts:

```<code>import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux";
import type { RootState, AppDispatch } from "./store";

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
</code>```

答:
You are breaking a very fundamental rule of React - not even Redux - here:

You trigger side effects during render.

React can trigger that render function any amount of times and not commit it to the DOM. It can be triggered because a parent component rerenders, because state changes, any number of reasons. One such reason might be that your Redux state changes.

So you dispatch, change state, trigger a rerender, dispatch again, which changes state (setting to another empty array - [] !== []) and triggers yet another render.

It is of utmost importance that your side effects like dispatches or state setter calls always happen in a useEffect or an event handler - and in the case of the useEffect that you also use a correct dependency array - hit the React documentation on that.

Also, your workflow of dispatch - useSelector - dispatch useSelector will probably not do what you want here. State reliably only changes between renders, not within a render.

Body:
I was following the TS usage docs and now I'm trying to clear an array using Redux Toolkit but my turnOffAll(state) reducer causes thousands of rerenders (console log outputs) and an error about it in the browser.

I have read that it's possible to return state, rather than "mutate" it from within turnOffAll.
So I've tried a variation of turnOffAll having: return Array(screenSize.width * screenSize.height).fill(0) but this causes an error in app.jsx that dispatch(turnOffAll()); does not provide enough arguments.

Another approach I tried in turnOffAll is state = initialState; but while this doesn't cause unnececary rerenders, the state is not reset if I do a console.log(useAppSelector((state) => state.pixels)); in app.jsx.

The relevant info from the files are below. This code is the situation in my first paragraph above and causes thousands of rerenders when calling dispatch(turnOffAll()); from app.jsx:

pixelsSlice.ts:

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import type { RootState } from "./store";
import { Pixel, ScreenSize } from "./types";

//Defining a type for the slice state
interface PixelsState {
  pixels: Array<number>;
}

const screenSize = { width: 128, height: 59 };

//Define the initial state using the above type.
const initialState: PixelsState = {
  pixels: Array(screenSize.width * screenSize.height).fill(0),
};

export const pixelsSlice = createSlice({
  name: "pixels",
  initialState,
  reducers: {
    turnOn(state, action: PayloadAction<Pixel>) {
      //This may look like mutating state, but Immer makes it ok:
      state.pixels[
        screenSize.width * action.payload.row + action.payload.column
      ] = 1;
    },
    turnOffAll(state) {
      state = initialState;
    },
  },
});

export const { turnOn, turnOffAll } = pixelsSlice.actions;

//Other code such as selectors can use the imported `RootState` type...
export const selectPixels = (state: RootState) => state.pixels;

export default pixelsSlice.reducer;

app.tsx:

import React, { useEffect } from "react";
import { useAppSelector, useAppDispatch } from "./app/hooks";
import { turnOn, turnOffAll } from "./app/pixelsSlice";
import type { Pixel } from "./app/types";

function App() {
  const dispatch = useAppDispatch();

  //Demonstrating reading and writing pixels from the redux store.
  console.log(useAppSelector((state) => state.pixels));

  let p: Pixel = { row: 1, column: 2 };
  dispatch(turnOn(p));
  console.log(useAppSelector((state) => state.pixels));

  dispatch(turnOffAll()); //THIS CAUSES THOUSANDS OF RERENDERS AND CONSOLE LOG OUTPUTS :(
  console.log(useAppSelector((state) => state.pixels));

  return

;
}

export default App;

hooks.ts:

import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux";
import type { RootState, AppDispatch } from "./store";

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;