问:
ggspatial: geom_sf fails with certain xlim values in coord_sf
What I'm trying to do: plot spatial objects with ggspatial::geom_sf(), using coord_sf() or a combination of ggspatial::layer_spatial() and ggspatial::annotation_spatial() to specify the extent of the of the plot.

This ggplot/ggspatial behavior has been described in several posts, but the "solutions" have been just ad-hoc hacks that do nothing to ensure the issue doesn't re-occur. See:
Setting limits for x and y using coord_sf after updating ggplot2
Error when plotting latitude and longitude points on US map in RStudio

This code works just fine:

```<code>require(sf); require(ggspatial); require(rnaturalearth)
country_polygons <- st_as_sf(ne_countries())
ggplot() + geom_sf(data=country_polygons)
</code>```

As does this:

```<code>ggplot() + geom_sf(data=country_polygons) + coord_sf(xlim=c(-100,100), ylim=c(-60,60))
</code>```

But:

```<code>ggplot() + geom_sf(data=country_polygons) + coord_sf(xlim=c(-160,150), ylim=c(-60,60))
</code>```

Results in the error:
Error in st_cast.POINT(X[[i]], ...) :
cannot create MULTILINESTRING from POINT

Obviously this should not be happening. I don't understand why geom_sf calls st_cast.POINT() since there should be no points in the input. I've tried with three different world maps (the GADM 3.6 shapefile, rworldmap::countriesLow and the rnaturalearth one), so it doesn't seem to be dataset specific.

Using these x and y limits values, even a simple sf point object fails to plot!

```<code>set.seed(80085)
tibble(Lon=runif(1000,-180,180),
       Lat=runif(1000,-90,90)) %>%
  st_as_sf(coords=1:2, remove=F, crs=4326) -> random_points

random_points %>%
      ggplot() + geom_sf() + coord_sf(xlim=c(-160,150), ylim=c(-60,60))
</code>```

The error message is again "cannot create MULTILINESTRING from POINT" which I have no idea why it would try to create a MULTILINESTRING.

UPDATE: The solution suggested here doesn't work:
Why do some xlims and ylims produce this error in ggplot and sf?

```<code>random_points %>%
  st_crop(xmin=-160, xmax=150, ymin=-60, ymax=60) %>%
  ggplot() + geom_sf()
</code>```

Results, weirdly, in only the points between 150oE and 160oW, i.e. over the Pacific Ocean around the 180th longitude, being preserved. I tried using longitudes from 0 to 360 and swapping the xmin and xmax, to no avail.

Faulty behavior of st_crop aside, passing a correct cropped object gives the same error again:

```<code>random_points %>%
  filter(Lon<150, Lon>-160, Lat>-60, Lat<60) %>%
  ggplot() + geom_sf()

> Error in st_cast.POINT(x[[1]], to, ...) :
  cannot create MULTILINESTRING from POINT
In addition: Warning message:
In st_cast.GEOMETRYCOLLECTION(X[[i]], ...) :
  only first part of geometrycollection is retained
</code>```

END UPDATE

Is there a solution or a workaround?

答:
I believe this has something to do with the s2 geometry engine behaving in an unexpected fashion.

TL;DR: consider using sf_use_s2(F) in your code.

Long version:

```<code>library(sf)
library(dplyr)
library(mapview)

set.seed(80085)

random_points <- tibble(Lon = runif(1000,-180,180),
                        Lat = runif(1000,-90,90)) %>%
  st_as_sf(coords=1:2, remove=F, crs=4326)

mapview(random_points)  # this is "truth"
</code>```

```<code>area_of_interest <- matrix(c(-160, -60,
                             150, -60,
                             150, 60,
                             -160, 60,
                             -160, -60),
                           byrow = TRUE,
                           ncol = 2) %>%
  list() %>%
  st_polygon() %>%
  st_sfc(crs = 4326)

mapview(area_of_interest) # this is our area of interest
</code>```

```<code># an atribute of points - in AOI or not?
random_points$aoi <- st_contains(area_of_interest,
                                 random_points,
                                 sparse = F) %>%
  t() %>%
  c()

# a visual overview; this is _not_ expected!
# the topology of AOI was not applied correctly
mapview(random_points, zcol = "aoi")
</code>```

```<code># let us try turning S2 engine off, and fall back to good old GEOS
sf_use_s2(F)

# exactly the same code as before!!
random_points$aoi <- st_contains(area_of_interest,
                                 random_points,
                                 sparse = F) %>%
  t() %>%
  c()

# but the output behaves much better!
mapview(random_points, zcol = "aoi")
</code>```

```<code># a seletion of random points; cropped to area of interest
library(ggplot2)

random_points %>%
  filter(aoi) %>%
  ggplot() + geom_sf(pch = 4, color = "red")
</code>```

Body:
What I'm trying to do: plot spatial objects with ggspatial::geom_sf(), using coord_sf() or a combination of ggspatial::layer_spatial() and ggspatial::annotation_spatial() to specify the extent of the of the plot.

This ggplot/ggspatial behavior has been described in several posts, but the "solutions" have been just ad-hoc hacks that do nothing to ensure the issue doesn't re-occur. See:
Setting limits for x and y using coord_sf after updating ggplot2
Error when plotting latitude and longitude points on US map in RStudio

This code works just fine:

require(sf); require(ggspatial); require(rnaturalearth)
country_polygons <- st_as_sf(ne_countries())
ggplot() + geom_sf(data=country_polygons)

As does this:

ggplot() + geom_sf(data=country_polygons) + coord_sf(xlim=c(-100,100), ylim=c(-60,60))

But:

ggplot() + geom_sf(data=country_polygons) + coord_sf(xlim=c(-160,150), ylim=c(-60,60))

Results in the error:
Error in st_cast.POINT(X[[i]], ...) :
cannot create MULTILINESTRING from POINT

Obviously this should not be happening. I don't understand why geom_sf calls st_cast.POINT() since there should be no points in the input. I've tried with three different world maps (the GADM 3.6 shapefile, rworldmap::countriesLow and the rnaturalearth one), so it doesn't seem to be dataset specific.

Using these x and y limits values, even a simple sf point object fails to plot!

set.seed(80085)
tibble(Lon=runif(1000,-180,180),
       Lat=runif(1000,-90,90)) %>%
  st_as_sf(coords=1:2, remove=F, crs=4326) -> random_points

random_points %>%
      ggplot() + geom_sf() + coord_sf(xlim=c(-160,150), ylim=c(-60,60))

The error message is again "cannot create MULTILINESTRING from POINT" which I have no idea why it would try to create a MULTILINESTRING.

UPDATE: The solution suggested here doesn't work:
Why do some xlims and ylims produce this error in ggplot and sf?

random_points %>%
  st_crop(xmin=-160, xmax=150, ymin=-60, ymax=60) %>%
  ggplot() + geom_sf()

Results, weirdly, in only the points between 150oE and 160oW, i.e. over the Pacific Ocean around the 180th longitude, being preserved. I tried using longitudes from 0 to 360 and swapping the xmin and xmax, to no avail.

Faulty behavior of st_crop aside, passing a correct cropped object gives the same error again:

random_points %>%
  filter(Lon<150, Lon>-160, Lat>-60, Lat<60) %>%
  ggplot() + geom_sf()

> Error in st_cast.POINT(x[[1]], to, ...) :
  cannot create MULTILINESTRING from POINT
In addition: Warning message:
In st_cast.GEOMETRYCOLLECTION(X[[i]], ...) :
  only first part of geometrycollection is retained

END UPDATE

Is there a solution or a workaround?

Body:
I believe this has something to do with the s2 geometry engine behaving in an unexpected fashion.

TL;DR: consider using sf_use_s2(F) in your code.

Long version:

library(sf)
library(dplyr)
library(mapview)

set.seed(80085)

random_points <- tibble(Lon = runif(1000,-180,180),
                        Lat = runif(1000,-90,90)) %>%
  st_as_sf(coords=1:2, remove=F, crs=4326)

mapview(random_points)  # this is "truth"

area_of_interest <- matrix(c(-160, -60,
                             150, -60,
                             150, 60,
                             -160, 60,
                             -160, -60),
                           byrow = TRUE,
                           ncol = 2) %>%
  list() %>%
  st_polygon() %>%
  st_sfc(crs = 4326)

mapview(area_of_interest) # this is our area of interest

# an atribute of points - in AOI or not?
random_points$aoi <- st_contains(area_of_interest,
                                 random_points,
                                 sparse = F) %>%
  t() %>%
  c()

# a visual overview; this is _not_ expected!
# the topology of AOI was not applied correctly
mapview(random_points, zcol = "aoi")

# let us try turning S2 engine off, and fall back to good old GEOS
sf_use_s2(F)

# exactly the same code as before!!
random_points$aoi <- st_contains(area_of_interest,
                                 random_points,
                                 sparse = F) %>%
  t() %>%
  c()

# but the output behaves much better!
mapview(random_points, zcol = "aoi")

# a seletion of random points; cropped to area of interest
library(ggplot2)

random_points %>%
  filter(aoi) %>%
  ggplot() + geom_sf(pch = 4, color = "red")


来源: stackexchange

问:
How to change soft input panel (SIP) to digits only?
I've use the "Digits" and "Numeric" input scopes on the emulator for windows phone7 but on the actual device it ends up being the default input scope.

How do I change it to "Numeric" on the actual device? Is there something that I'm missing?

答:
Here is the full code:</p>

```<code>InputScope scope = new InputScope();
InputScopeName scopeName = new InputScopeName();
scopeName.NameValue = InputScopeNameValue.Number;
scope.Names.Add(scopeName);

tblInputField.Inputscope = scope;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is the full code:

InputScope scope = new InputScope();
InputScopeName scopeName = new InputScopeName();
scopeName.NameValue = InputScopeNameValue.Number;
scope.Names.Add(scopeName);

tblInputField.Inputscope = scope;


问:
Combining data from multiple tables when using Group By
I have data in about 20 different tables. Each table has a column EnterDateTime for the data / time the data in those tables was added. I'm already using a combination of DATEPART (ISO_WEEK) and GROUP BY to view how much data was added for each week using the following query:

```<code>SELECT DATEPART (ISO_WEEK, EnterDateTime) WeekNum, COUNT (*) as COUNT
FROM TABLE 1
GROUP BY DATEPART (ISO_WEEK, EnterDateTime)
ORDER BY WeekNum
</code>```

Which is giving results like this, for the data in Table 1:

```<code>WeekNum | Count
1       | 1084
2       | 5257
3       | 2152
4       | 5172
</code>```

I am then doing the same query on Table 2:

```<code>WeekNum | Count
1       | 362
2       | 153
3       | 78
4       | 216
</code>```

And so on, and so on, for each of the 20 tables. This is time consuming.

Ideally, I'd like to see this in a single output, like this, so I only have to run one query, instead of about 20:

```<code>WeekNum | Table 1 Count  | Table 2 Count | Table 3 Count
1       | 1084           | 362           |  x
2       | 5257           | 153           |  x
3       | 2152           | 78            |  x
4       | 5172           | 216           |  x
</code>```

Is this possible? Thank you for your help.

答:
The DRYest code I can think of would be to generate the normalised structure, then pivot it.

```<code>WITH
  combined AS
(
            SELECT 1 AS table_id, EnterDateTime FROM table_1
  UNION ALL SELECT 2 AS table_id, EnterDateTime FROM table_2
  UNION ALL SELECT 3 AS table_id, EnterDateTime FROM table_3
  ...
  UNION ALL SELECT n AS table_id, EnterDateTime FROM table_n
),
  aggregated AS
(
  SELECT
    table_id,
    DATEPART(ISO_WEEK, EnterDateTime)   AS week_num,
    COUNT(*)                            AS row_count
  FROM
    combined
  GROUP BY
    table_id,
    DATEPART(ISO_WEEK, EnterDateTime)
)
SELECT
  week_num,
  MAX(CASE WHEN table_id = 1 THEN row_count END)  AS row_count_1,
  MAX(CASE WHEN table_id = 2 THEN row_count END)  AS row_count_2,
  MAX(CASE WHEN table_id = 3 THEN row_count END)  AS row_count_3,
  ...
  MAX(CASE WHEN table_id = n THEN row_count END)  AS row_count_n
FROM
  aggregated
GROUP BY
  week_num
ORDER BY
  week_num
</code>```

This can be collapsed a bit to two steps...

```<code>WITH
  combined AS
(
            SELECT 1 AS table_id, EnterDateTime FROM table_1
  UNION ALL SELECT 2 AS table_id, EnterDateTime FROM table_2
  UNION ALL SELECT 3 AS table_id, EnterDateTime FROM table_3
  ...
  UNION ALL SELECT n AS table_id, EnterDateTime FROM table_n
)
SELECT
  DATEPART(ISO_WEEK, EnterDateTime)       AS week_num,
  SUM(CASE WHEN table_id = 1 THEN 1 END)  AS row_count_1,
  SUM(CASE WHEN table_id = 2 THEN 1 END)  AS row_count_2,
  SUM(CASE WHEN table_id = 3 THEN 1 END)  AS row_count_3,
  ...
  SUM(CASE WHEN table_id = n THEN 1 END)  AS row_count_n
FROM
  combined
GROUP BY
  1
ORDER BY
  1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have data in about 20 different tables. Each table has a column EnterDateTime for the data / time the data in those tables was added. I'm already using a combination of DATEPART (ISO_WEEK) and GROUP BY to view how much data was added for each week using the following query:

SELECT DATEPART (ISO_WEEK, EnterDateTime) WeekNum, COUNT (*) as COUNT
FROM TABLE 1
GROUP BY DATEPART (ISO_WEEK, EnterDateTime)
ORDER BY WeekNum

Which is giving results like this, for the data in Table 1:

WeekNum | Count
1       | 1084
2       | 5257
3       | 2152
4       | 5172

I am then doing the same query on Table 2:

WeekNum | Count
1       | 362
2       | 153
3       | 78
4       | 216

And so on, and so on, for each of the 20 tables. This is time consuming.

Ideally, I'd like to see this in a single output, like this, so I only have to run one query, instead of about 20:

WeekNum | Table 1 Count  | Table 2 Count | Table 3 Count
1       | 1084           | 362           |  x
2       | 5257           | 153           |  x
3       | 2152           | 78            |  x
4       | 5172           | 216           |  x

Is this possible? Thank you for your help.

Body:
The DRYest code I can think of would be to generate the normalised structure, then pivot it.

WITH
  combined AS
(
            SELECT 1 AS table_id, EnterDateTime FROM table_1
  UNION ALL SELECT 2 AS table_id, EnterDateTime FROM table_2
  UNION ALL SELECT 3 AS table_id, EnterDateTime FROM table_3
  ...
  UNION ALL SELECT n AS table_id, EnterDateTime FROM table_n
),
  aggregated AS
(
  SELECT
    table_id,
    DATEPART(ISO_WEEK, EnterDateTime)   AS week_num,
    COUNT(*)                            AS row_count
  FROM
    combined
  GROUP BY
    table_id,
    DATEPART(ISO_WEEK, EnterDateTime)
)
SELECT
  week_num,
  MAX(CASE WHEN table_id = 1 THEN row_count END)  AS row_count_1,
  MAX(CASE WHEN table_id = 2 THEN row_count END)  AS row_count_2,
  MAX(CASE WHEN table_id = 3 THEN row_count END)  AS row_count_3,
  ...
  MAX(CASE WHEN table_id = n THEN row_count END)  AS row_count_n
FROM
  aggregated
GROUP BY
  week_num
ORDER BY
  week_num

This can be collapsed a bit to two steps...

WITH
  combined AS
(
            SELECT 1 AS table_id, EnterDateTime FROM table_1
  UNION ALL SELECT 2 AS table_id, EnterDateTime FROM table_2
  UNION ALL SELECT 3 AS table_id, EnterDateTime FROM table_3
  ...
  UNION ALL SELECT n AS table_id, EnterDateTime FROM table_n
)
SELECT
  DATEPART(ISO_WEEK, EnterDateTime)       AS week_num,
  SUM(CASE WHEN table_id = 1 THEN 1 END)  AS row_count_1,
  SUM(CASE WHEN table_id = 2 THEN 1 END)  AS row_count_2,
  SUM(CASE WHEN table_id = 3 THEN 1 END)  AS row_count_3,
  ...
  SUM(CASE WHEN table_id = n THEN 1 END)  AS row_count_n
FROM
  combined
GROUP BY
  1
ORDER BY
  1


问:
Exporting multiple variables in a for loop
I am having trouble exporting multiple env variables in a for loop of a bash script.

The full script looks something like:

```<code>IFS_old="$IFS"
IFS=';'
test_data="secret1='data1';secret2='data2';secret3='data3'"
for secret in $test_data
do
    eval "export $secret"
done
IFS="$IFS_old"
</code>```

So the input string consists of variables and their values separated by a semicolon.
I loop through it and want to export each of them; however, the variables that get exported have "null" values.

I also tried composing a full command string in a separate variable, and executing it both via         bash -c "$command" and eval "$command" statements, but it didn't work.

Can you please help me figure out what's wrong?

答:
This works fine. The variables exported are local and only available until the end of your script. When the script closes they are no longer available in the shell. This is normal.
if you write bash on the last line of your script it will open a new terminal with the exported variables available.

Body:
I am having trouble exporting multiple env variables in a for loop of a bash script.

The full script looks something like:

IFS_old="$IFS"
IFS=';'
test_data="secret1='data1';secret2='data2';secret3='data3'"
for secret in $test_data
do
    eval "export $secret"
done
IFS="$IFS_old"

So the input string consists of variables and their values separated by a semicolon.
I loop through it and want to export each of them; however, the variables that get exported have "null" values.

I also tried composing a full command string in a separate variable, and executing it both via         bash -c "$command" and eval "$command" statements, but it didn't work.

Can you please help me figure out what's wrong?


问:
How to fill NA's when you have enough information to calculate what the NA should be in R
I've got a dataset where there are some NA's but I can manually work out what the values should be as the df is a column for name and the rest of the columns are just numbers followed by a final column with total. Only one NA appears per row at most so I can work out what the value should be by using the total column and the sum of all the other columns. Just wondering what would be the best way to fill these NA's without having to hardcode one by one as the df I'm using is pretty big

example df:

```<code>df = structure(list(city = c("sydney", "new york", "london", "beijing", "paris", "madrid"),
                    year = c(2005:2010),
                    A = c(1, 4, 5 , NA, 2, 1),
                    B = c(3, NA, 4 , 9, 0, 6),
                    C = c(3, 4 , 6, 1, 8, NA),
                    total = c(NA, 10, 15, 14, NA, 15)),
               class = "data.frame", row.names = c(NA, -6L))

df
</code>```

答:
This solution can also help you.

```<code>library(purrr)
library(dplyr)

df %>%
  rowwise() %>%
  mutate(total = ifelse(is.na(total), sum(c_across(A:C)), total),
         pmap_df(select(cur_data(), A:total), ~ {x <- c(...)[1:3]
         replace(x, is.na(x), c(...)[4] - sum(x, na.rm = TRUE))}))

# A tibble: 6 x 6
# Rowwise:
  city      year     A     B     C total
  <chr>    <int> <dbl> <dbl> <dbl> <dbl>
1 sydney    2005     1     3     3     7
2 new york  2006     4     2     4    10
3 london    2007     5     4     6    15
4 beijing   2008     4     9     1    14
5 paris     2009     2     0     8    10
6 madrid    2010     1     6     8    15
</code>```

A bit hardcoded but can be modified in that sense.

Body:
I've got a dataset where there are some NA's but I can manually work out what the values should be as the df is a column for name and the rest of the columns are just numbers followed by a final column with total. Only one NA appears per row at most so I can work out what the value should be by using the total column and the sum of all the other columns. Just wondering what would be the best way to fill these NA's without having to hardcode one by one as the df I'm using is pretty big

example df:

df = structure(list(city = c("sydney", "new york", "london", "beijing", "paris", "madrid"),
                    year = c(2005:2010),
                    A = c(1, 4, 5 , NA, 2, 1),
                    B = c(3, NA, 4 , 9, 0, 6),
                    C = c(3, 4 , 6, 1, 8, NA),
                    total = c(NA, 10, 15, 14, NA, 15)),
               class = "data.frame", row.names = c(NA, -6L))

df

Body:
This solution can also help you.

library(purrr)
library(dplyr)

df %>%
  rowwise() %>%
  mutate(total = ifelse(is.na(total), sum(c_across(A:C)), total),
         pmap_df(select(cur_data(), A:total), ~ {x <- c(...)[1:3]
         replace(x, is.na(x), c(...)[4] - sum(x, na.rm = TRUE))}))

# A tibble: 6 x 6
# Rowwise:
  city      year     A     B     C total
  <chr>    <int> <dbl> <dbl> <dbl> <dbl>
1 sydney    2005     1     3     3     7
2 new york  2006     4     2     4    10
3 london    2007     5     4     6    15
4 beijing   2008     4     9     1    14
5 paris     2009     2     0     8    10
6 madrid    2010     1     6     8    15

A bit hardcoded but can be modified in that sense.


答:
Here is one more option, but @Serg's query would probably perform better:</p>
```<code>;WITH cte
AS(
    SELECT  COALESCE( DATEPART( ISO_WEEK, t1.EnterDateTime), DATEPART (ISO_WEEK, t2.EnterDateTime), DATEPART (ISO_WEEK, t3.EnterDateTime), ...) WeekNum
    ,       t1.[ColumnOnWhichYouCanCount] AS T1, t2.[ColumnOnWhichYouCanCount] AS T2, t3.[ColumnOnWhichYouCanCount] T3, ...
    FROM t1
    FULL JOIN t2 ON DATEPART( ISO_WEEK, t2.EnterDateTime) = DATEPART( ISO_WEEK, t1.EnterDateTime)
    FULL JOIN t3 ON DATEPART( ISO_WEEK, t3.EnterDateTime) = DATEPART( ISO_WEEK, t1.EnterDateTime)
    ...
)
SELECT WeekNum, SUM(T1) AS [Table 1 Count], SUM(T2) AS [Table 2 Count] ...
FROM cte
GROUP BY WeekNum
</code>```

Title: Combining data from multiple tables when using Group By

Body:
Here is one more option, but @Serg's query would probably perform better:

;WITH cte
AS(
    SELECT  COALESCE( DATEPART( ISO_WEEK, t1.EnterDateTime), DATEPART (ISO_WEEK, t2.EnterDateTime), DATEPART (ISO_WEEK, t3.EnterDateTime), ...) WeekNum
    ,       t1.[ColumnOnWhichYouCanCount] AS T1, t2.[ColumnOnWhichYouCanCount] AS T2, t3.[ColumnOnWhichYouCanCount] T3, ...
    FROM t1
    FULL JOIN t2 ON DATEPART( ISO_WEEK, t2.EnterDateTime) = DATEPART( ISO_WEEK, t1.EnterDateTime)
    FULL JOIN t3 ON DATEPART( ISO_WEEK, t3.EnterDateTime) = DATEPART( ISO_WEEK, t1.EnterDateTime)
    ...
)
SELECT WeekNum, SUM(T1) AS [Table 1 Count], SUM(T2) AS [Table 2 Count] ...
FROM cte
GROUP BY WeekNum


问:
How to disable autoindent on enter
I see multiple settings for Code in terms of how to indent (spaces vs tabs), but nothing about how to disable indents. So for example, I enter a
 tag, hit enter, and Code auto indents the next line. I'd like to disable that but cannot find the setting to do so.

答:
You can now set the configuration property editor.autoIndent in your settings.json file (which for me was in C:\Users\$USER\AppData\Roaming\Code\User\settings.json). the value you want to set it to is the string "none".

see this thread for more details https://github.com/microsoft/vscode/issues/5446#issuecomment-559145939

Title: How to disable autoindent on enter


问:
Retrieving values from multidimensional arrays
I have an array something like this:

```<code>   int[,] multiDimensionalArray2 = { { 1, 2 }, { 4, 5 } };
</code>```

if I want to retrieve 1 and 2 and feed them into this:

```<code>int a;
int b;
</code>```

How do I do it?

Is it something like this:

```<code>multiDimensionalArray2[0,0]
</code>```

What if I wanted to put more numbers in the same form  e.g. { { 2, 1 }, { 4, 1 } };, in the same form as above. Would it be something like this:

```<code>   int[,] multiDimensionalArray2 = { { 1, 2 }, { 4, 5 } },{ { 2, 1 }, { 4, 1 } };
</code>```

To retrieve the second set would I do this, multiDimensionalArray2[1,1]

答:
Double dimention arrays are stored like this (picture it in your mind) as per your example

```<code>Row0  Row1
1       2
4       5
2       1
4       1
</code>```

Now follow what Dominik suggested.

Body:
I have an array something like this:

   int[,] multiDimensionalArray2 = { { 1, 2 }, { 4, 5 } };

if I want to retrieve 1 and 2 and feed them into this:

int a;
int b;

How do I do it?

Is it something like this:

multiDimensionalArray2[0,0]

What if I wanted to put more numbers in the same form  e.g. { { 2, 1 }, { 4, 1 } };, in the same form as above. Would it be something like this:

   int[,] multiDimensionalArray2 = { { 1, 2 }, { 4, 5 } },{ { 2, 1 }, { 4, 1 } };

To retrieve the second set would I do this, multiDimensionalArray2[1,1]

Body:
Double dimention arrays are stored like this (picture it in your mind) as per your example

Row0  Row1
1       2
4       5
2       1
4       1

Now follow what Dominik suggested.


问:
Jackson deserialize fails with class containing a Map with specific types
I have a class that extends HashMap<Locale,String>, and which is referenced in another class that is being serialized into JSON with Jackson (jackson-core 2.10.5).
The result of serialization is:

```<code>{"code":null,"translations":{"@class":"c...TranslationMap","nb_NO":"Minimum","en_US":"Minimum","nn_NO":"Minimum"}}
</code>```

(class package name censored)

But when de-serializing an exception is thrown that I haven't been able to figure out, how to work around:

Could not resolve type id 'c...TranslationMap' as a subtype of c...TranslationMap<java.util.Locale,java.lang.String>: Not a subtype

The strange part is that I couldn't replicate this issue while using JDK that's part of DCEVM, but as soon as I switched to customer JDK adopt-openjdk-11 I started running into this issue.
Considering this issue occurs on servers as well, I have to make this work with adopt-openjdk-11.

Any ideas?

TranslationMap.java

```<code>@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
public class TranslationMap extends HashMap<Locale, String> {
   ...
   // empty constructor
   // some additional methods
}
</code>```

Translation.java

```<code>public class Translation {
    private String code;
    private TranslationMap translations;
    ...
    // empty constructor
    // get / set methods
}
</code>```

Deserialize method:

```<code>private Object deserialize(String value, String className) {
    try {
        var classType = Class.forName(className);
        return new ObjectMapper().readValue(value, classType);
    } catch (IOException | ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}
</code>```

Exception:

```<code>Caused by: com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve type id 'c...TranslationMap' as a subtype of `c...TranslationMap<java.util.Locale,java.lang.String>`: Not a subtype
 at [Source: (String)"{"code":null,"translations":{"@class":"c...TranslationMap","nb_NO":"Minimum","en_US":"Minimum","nn_NO":"Minimum"}}"; line: 1, column: 39] (through reference chain: c...Translation["translations"])
    at com.fasterxml.jackson.databind.exc.InvalidTypeIdException.from(InvalidTypeIdException.java:43)
    at com.fasterxml.jackson.databind.DeserializationContext.invalidTypeIdException(DeserializationContext.java:1761)
    at com.fasterxml.jackson.databind.DatabindContext._throwNotASubtype(DatabindContext.java:280)
    at com.fasterxml.jackson.databind.DatabindContext.resolveAndValidateSubType(DatabindContext.java:241)
    at com.fasterxml.jackson.databind.jsontype.impl.ClassNameIdResolver._typeFromId(ClassNameIdResolver.java:72)
    at com.fasterxml.jackson.databind.jsontype.impl.ClassNameIdResolver.typeFromId(ClassNameIdResolver.java:66)
    at com.fasterxml.jackson.databind.jsontype.impl.TypeDeserializerBase._findDeserializer(TypeDeserializerBase.java:156)
    at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer._deserializeTypedForId(AsPropertyTypeDeserializer.java:113)
    at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer.deserializeTypedFromObject(AsPropertyTypeDeserializer.java:97)
    at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer.deserializeTypedFromAny(AsPropertyTypeDeserializer.java:193)
</code>```

答:
I don't know why, but the Class.forName(className) does not resolve to the same Class object that is referenced in object mapper type factory, but seems to create another Class object for the same class. That's why it considers the types equal.
Solution for me was to use class from type factory instead.

```<code>private Object deserialize(String value, String className) {
    try {
        var jackson = new ObjectMapper();
        var classType = jackson.getTypeFactory().findClass(className));
        return jackson.readValue(value, classType);
    } catch (IOException | ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}
</code>```

Body:
I have a class that extends HashMap<Locale,String>, and which is referenced in another class that is being serialized into JSON with Jackson (jackson-core 2.10.5).
The result of serialization is:

{"code":null,"translations":{"@class":"c...TranslationMap","nb_NO":"Minimum","en_US":"Minimum","nn_NO":"Minimum"}}

(class package name censored)

But when de-serializing an exception is thrown that I haven't been able to figure out, how to work around:

Could not resolve type id 'c...TranslationMap' as a subtype of c...TranslationMap<java.util.Locale,java.lang.String>: Not a subtype

The strange part is that I couldn't replicate this issue while using JDK that's part of DCEVM, but as soon as I switched to customer JDK adopt-openjdk-11 I started running into this issue.
Considering this issue occurs on servers as well, I have to make this work with adopt-openjdk-11.

Any ideas?

TranslationMap.java

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
public class TranslationMap extends HashMap<Locale, String> {
   ...
   // empty constructor
   // some additional methods
}

Translation.java

public class Translation {
    private String code;
    private TranslationMap translations;
    ...
    // empty constructor
    // get / set methods
}

Deserialize method:

private Object deserialize(String value, String className) {
    try {
        var classType = Class.forName(className);
        return new ObjectMapper().readValue(value, classType);
    } catch (IOException | ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}

Exception:

Caused by: com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve type id 'c...TranslationMap' as a subtype of `c...TranslationMap<java.util.Locale,java.lang.String>`: Not a subtype
 at [Source: (String)"{"code":null,"translations":{"@class":"c...TranslationMap","nb_NO":"Minimum","en_US":"Minimum","nn_NO":"Minimum"}}"; line: 1, column: 39] (through reference chain: c...Translation["translations"])
    at com.fasterxml.jackson.databind.exc.InvalidTypeIdException.from(InvalidTypeIdException.java:43)
    at com.fasterxml.jackson.databind.DeserializationContext.invalidTypeIdException(DeserializationContext.java:1761)
    at com.fasterxml.jackson.databind.DatabindContext._throwNotASubtype(DatabindContext.java:280)
    at com.fasterxml.jackson.databind.DatabindContext.resolveAndValidateSubType(DatabindContext.java:241)
    at com.fasterxml.jackson.databind.jsontype.impl.ClassNameIdResolver._typeFromId(ClassNameIdResolver.java:72)
    at com.fasterxml.jackson.databind.jsontype.impl.ClassNameIdResolver.typeFromId(ClassNameIdResolver.java:66)
    at com.fasterxml.jackson.databind.jsontype.impl.TypeDeserializerBase._findDeserializer(TypeDeserializerBase.java:156)
    at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer._deserializeTypedForId(AsPropertyTypeDeserializer.java:113)
    at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer.deserializeTypedFromObject(AsPropertyTypeDeserializer.java:97)
    at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer.deserializeTypedFromAny(AsPropertyTypeDeserializer.java:193)

Body:
I don't know why, but the Class.forName(className) does not resolve to the same Class object that is referenced in object mapper type factory, but seems to create another Class object for the same class. That's why it considers the types equal.
Solution for me was to use class from type factory instead.

private Object deserialize(String value, String className) {
    try {
        var jackson = new ObjectMapper();
        var classType = jackson.getTypeFactory().findClass(className));
        return jackson.readValue(value, classType);
    } catch (IOException | ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}


问:
How to calculate the sum of numbers in deeply nested array of objects using JavaScript?
I just started learning JavaScript, and ran into such a problem, I have a nested array, I want to summarize the price value of these arrays and return the existing sum, I wonder which method is applicable for it, which does not hurt the performance, I need one example to understand the way to solve the problem. Thanks in advance

const initialData = [
      {
          title: 'm2212',
          data: [
              {
                  id: 98233181232,
                  variations:[{
                          warranty: '',
                          price: 120,
                          comment: '',
                      }]

              },
          ]
      },
      {
          title: 'm2',
          data: [
              {
                  id: 982812,
                  variations:[{
                          warranty: '',
                          price: 92,
                          comment: '',
                      }]

              },
               {
                  id: 92182812,
                  variations:[{
                          warranty: '',
                          price: 922,
                          comment: '',
                      }]

              },
          ]
      },
 ]

 //what i tried
 let sum = 0
 initialData.forEach((el)=>{
   el.data.forEach((el1)=>{
     sum = sum + el1.variations[0].price
    })
 })

 console.log(sum);```

答:
You could add some checks for having an array or object and if so iterate the values.

This approach does not need to know the structure of the data, it takes breadth-first search for finding the wanted key.

const
    sum = (value, key) => {
        if (!value || typeof value !== 'object') return 0;
        if (Array.isArray(value)) return value.reduce((t, o) => t + sum(o, key), 0);
        if (key in value) return value[key];
        return sum(Object.values(value), key);
    },
    data = [{ title: 'm2212', data: [{ id: 98233181232, variations: [{ warranty: '', price: 120, comment: '' }] }] }, { title: 'm2', data: [{ id: 982812, variations: [{ warranty: '', price: 92, comment: '' }] }, { id: 92182812, variations: [{ warranty: '', price: 922, comment: '' }] }] }];

console.log(sum(data, 'price'));```


问:
left Join with right table filtered for every rows
I have two tables:

Customer: customer_id

Order: order_id, customer_id, createdAt

I want to retry for every customer the only last order.

I tried to do this:

```<code>    SELECT C.customer_id, ORD.*
    FROM "Customer" as C
    LEFT JOIN (
            SELECT "Order".customer_id, "Order".order_id, "Order"."createdAt"
            FROM "Order", "Customer"
            WHERE "Order".customer_id = "Customer".customer_id
            ORDER BY "Order"."createdAt" DESC limit 1
    ) ORD ON C.customer_id = ORD.customer_id
</code>```

but the result is:

Customer.customer_id
Order.order_id
createdAt

1
null
null

2
null
null

3
123
2022-03-04

The result is correct only for a customer. I lose the information of the others.

I also tried to do this:

```<code>    SELECT  C.customer_id, ORD.*
    FROM    "Customer" as C
    LEFT JOIN "Order" as ORD
    ON ORD.customer_id = (
                    SELECT  ORD.customer_id
                    FROM    "Order" as ORD
                    WHERE   ORD.customer_id = C.customer_id
                    ORDER BY
                                    ORD."createdAt" DESC limit 1
                    )
</code>```

the result in this case is:

Customer.customer_id
Order.order_id
createdAt

1
119
2022-01-04

2
120
2022-01-04

3
123
2022-03-04

3
121
2022-02-04

I have more information about customer 3, when I just need the row where order_id is 123.

I've been working on it for a couple of days, could someone help me? Thanks so much.

答:
Use this query.. Hope it will cover your requirement.</p>
```<code>select
  cust.customer_id,
  max(ord.order_id) AS order_id,
  max(ord.createdAt) AS createdAt
from Customer as cust
join "Order" ord on cust.customer_id = ord.customer_id
group by cust.customer_id;
</code>```

Body:
I have two tables:

Customer: customer_id

Order: order_id, customer_id, createdAt

I want to retry for every customer the only last order.

I tried to do this:

    SELECT C.customer_id, ORD.*
    FROM "Customer" as C
    LEFT JOIN (
            SELECT "Order".customer_id, "Order".order_id, "Order"."createdAt"
            FROM "Order", "Customer"
            WHERE "Order".customer_id = "Customer".customer_id
            ORDER BY "Order"."createdAt" DESC limit 1
    ) ORD ON C.customer_id = ORD.customer_id

but the result is:

Customer.customer_id
Order.order_id
createdAt

1
null
null

2
null
null

3
123
2022-03-04

The result is correct only for a customer. I lose the information of the others.

I also tried to do this:

    SELECT  C.customer_id, ORD.*
    FROM    "Customer" as C
    LEFT JOIN "Order" as ORD
    ON ORD.customer_id = (
                    SELECT  ORD.customer_id
                    FROM    "Order" as ORD
                    WHERE   ORD.customer_id = C.customer_id
                    ORDER BY
                                    ORD."createdAt" DESC limit 1
                    )

the result in this case is:

Customer.customer_id
Order.order_id
createdAt

1
119
2022-01-04

2
120
2022-01-04

3
123
2022-03-04

3
121
2022-02-04

I have more information about customer 3, when I just need the row where order_id is 123.

I've been working on it for a couple of days, could someone help me? Thanks so much.

Body:
Use this query.. Hope it will cover your requirement.

select
  cust.customer_id,
  max(ord.order_id) AS order_id,
  max(ord.createdAt) AS createdAt
from Customer as cust
join "Order" ord on cust.customer_id = ord.customer_id
group by cust.customer_id;


问:
Form fields stability php
How can I make fields still in the form fields after submitting the form and return with invalid input data?

```<code> <form action="" method="post">
             <label for="cellPhoneNo">البريد الالكتروني</label>
                <input type="text" name="emailAddress" class="textField"/>
                <span>*</span>
                <span><?php
                       if($emailValidator != CORRECT_VALUE)
                        echo $errorMessage[$emailValidator];?>
                </span>
                <br>

</form>
</code>```

and here's where I check the input

```<code> $emailValidator=checkInput($_POST['emailAddress'],INVALID_EMAIL_ADDRESS,'/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$/');
</code>```

when user submit invalid email address, the validation result shows the error message to user. How can I make the invalid error email address still in the input?

答:
Try,

<input type="text" name="emailAddress" value="<?php echo $_POST['emailAddress']; ?>" class="textField"/>

Title: Form fields stability php

Body:
How can I make fields still in the form fields after submitting the form and return with invalid input data?

 <form action="" method="post">
             البريد الالكتروني
                <input type="text" name="emailAddress" class="textField"/>
                *
                <?php
                       if($emailValidator != CORRECT_VALUE)
                        echo $errorMessage[$emailValidator];?>

</form>

and here's where I check the input

 $emailValidator=checkInput($_POST['emailAddress'],INVALID_EMAIL_ADDRESS,'/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$/');

when user submit invalid email address, the validation result shows the error message to user. How can I make the invalid error email address still in the input?


答:
Your derived table (subquery in the from clause) only selects one row. Your are using a join syntax here that got deprecated in the early 1990s. Here is your subquery with an up-to-date syntax:

```<code>select o.customer_id, o.order_id, o.createdat
from "Order" o
join customer c on c.customer_id = o.customer_id
order by o.createdat desc
limit 1;
</code>```

Or shorter without the superfluos join:

```<code>select customer_id, order_id, createdat
from "Order"
order by createdat desc
limit 1;
</code>```

In your main query you join this to your customer table and the one row that the subquery produces does get joined. It's just not what you actually intended.

One way to get the last order per customer is by using a window function such as ROW_NUMBER OVER or MAX OVER:

```<code>select c.customer_id, ord.*
from customer as c
left join
(
  select
    o.*,
    row_number() over (partition by order_id order by createdat desc) as rn
  from "Order" o
) ord on ord.customer_id = c.customer_id and ord.rn = 1
order by c.customer_id;
</code>```

Here is another approach using a fetch with ties clause:

```<code>select c.customer_id, ord.*
from customer as c
left join
(
  select *
  from "Order"
  order by row_number() over (partition by order_id order by createdat desc)
  fetch first row with ties
) ord on ord.customer_id = c.customer_id
order by c.customer_id;
</code>```

And here is the same with a lateral join:

```<code>select c.customer_id, ord.*
from customer as c
left join lateral
(
  select o.*
  from "Order" o
  where o.customer_id = c.customer_id
  order by o.createdat desc
  fetch first row only
) ord on true
order by c.customer_id;
</code>```

Title: left Join with right table filtered for every rows

Body:
Your derived table (subquery in the from clause) only selects one row. Your are using a join syntax here that got deprecated in the early 1990s. Here is your subquery with an up-to-date syntax:

select o.customer_id, o.order_id, o.createdat
from "Order" o
join customer c on c.customer_id = o.customer_id
order by o.createdat desc
limit 1;

Or shorter without the superfluos join:

select customer_id, order_id, createdat
from "Order"
order by createdat desc
limit 1;

In your main query you join this to your customer table and the one row that the subquery produces does get joined. It's just not what you actually intended.

One way to get the last order per customer is by using a window function such as ROW_NUMBER OVER or MAX OVER:

select c.customer_id, ord.*
from customer as c
left join
(
  select
    o.*,
    row_number() over (partition by order_id order by createdat desc) as rn
  from "Order" o
) ord on ord.customer_id = c.customer_id and ord.rn = 1
order by c.customer_id;

Here is another approach using a fetch with ties clause:

select c.customer_id, ord.*
from customer as c
left join
(
  select *
  from "Order"
  order by row_number() over (partition by order_id order by createdat desc)
  fetch first row with ties
) ord on ord.customer_id = c.customer_id
order by c.customer_id;

And here is the same with a lateral join:

select c.customer_id, ord.*
from customer as c
left join lateral
(
  select o.*
  from "Order" o
  where o.customer_id = c.customer_id
  order by o.createdat desc
  fetch first row only
) ord on true
order by c.customer_id;


问:
Call a Widget based on the result of an If statement Flutter
I want to be able to call either one of two different widgets based on the result of an if statement.
I am able to get a Text Widget to show two different answers based on the result of the first dropdown box, but I am not able to call another widget the same way ...

```<code>import 'package:flutter/material.dart';

class FilterPage extends StatefulWidget {
  const FilterPage({Key? key}) : super(key: key);

  @override
  State<FilterPage> createState() => _FilterPageState();
}

class _FilterPageState extends State<FilterPage> {
  String firstDropdownValue = 'Option A';
  String secondDropdownValue = 'Option B';

  @override
  void dispose() {
    super.dispose();
  }

  static const String _title = 'Filter Code Sample';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          Padding(
            padding: EdgeInsets.all(4),
          ),
        ],
        title: Column(
          children: [
            Text(
              'Filter',
              style: TextStyle(fontSize: 22, color: Colors.amberAccent),
            ),
          ],
        ),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: [
              Text(
                'What are the Options ?',
                style: TextStyle(fontSize: 16, color: Colors.white),
              ),

              /*
              * This is the first dropdown that is called, This dropdown provides
              * two possible options,
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: firstDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    firstDropdownValue = newValue!;
                  });
                },
                items: <String>['Option A', 'Option B']
                    .map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),

              /*
              * So this is the if Statement that works based upon the first
              * drop down box's answer...
              *
              * The problem is I can not get the system to call another Drop down Butten
              * Widget based on the answer of the first DropdownBox,
              * However, i can get a Text Widget to print...
              * */
              Text((() {
                if (firstDropdownValue == 'Option A') {
                  return "Option is Option A";
                }
                return "Option is Option B";
              })()),

              /*
              * This is the second dropbox that I would like to be called if the
              * previous statement is met instead of the Text Widget above...
              *(DROPBOX 2)
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: secondDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    secondDropdownValue = newValue!;
                  });
                },
                items: <String>[
                  'Option 1',
                  'Option 2',
                  'Option 3',
                ].map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),

              /*
              * This is also drop box two, but this dropbox with these different
              * options should be called when the if statement is not met ..
              *(DROPBOX 2)
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: secondDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    secondDropdownValue = newValue!;
                  });
                },
                items: <String>[
                  'Option 4',
                  'Option 5',
                  'Option 6',
                ].map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

The flow diagram is maybe easier to get the whole picture from.

答:
You can use the Dart short if form: if ? then : else.
Since the only thing that changes are the dropdown options, you can dynamically change them without the need to use another widget.</p>
```<code>import 'package:flutter/material.dart';

class FilterPage extends StatefulWidget {
  const FilterPage({Key? key}) : super(key: key);

  @override
  State<FilterPage> createState() => _FilterPageState();
}

class _FilterPageState extends State<FilterPage> {
  String firstDropdownValue = '';
  String secondDropdownValue = 'Option B';

  @override
  void dispose() {
    super.dispose();
  }

  static const String _title = 'Filter Code Sample';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          Padding(
            padding: EdgeInsets.all(4),
          ),
        ],
        title: Column(
          children: [
            Text(
              'Filter',
              style: TextStyle(fontSize: 22, color: Colors.amberAccent),
            ),
          ],
        ),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: [
              Text(
                'What are the Options ?',
                style: TextStyle(fontSize: 16, color: Colors.white),
              ),
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: firstDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    firstDropdownValue = newValue!;
                  });
                },
                items: <String>['Option A', 'Option B']
                    .map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),
              if(firstDropdownValue.isNotEmpty)
               DropdownButton<String>(
                 dropdownColor: Colors.blueGrey.shade700,
                 value: secondDropdownValue,
                 icon: const Icon(Icons.arrow_downward),
                 elevation: 16,
                 style: const TextStyle(color: Colors.white),
                 underline: Container(
                   height: 2,
                   color: Colors.blueGrey.shade900,
                 ),
                 onChanged: (String? newValue) {
                   setState(() {
                     secondDropdownValue = newValue!;
                   });
                 },
                 items: <String>[
                   firstDropdownValue == 'Option A' ?
                   ...['Option 1',
                   'Option 2',
                   'Option 3'] : ...['Option 5',
                   'Option 6',
                   'Option 7']
                 ].map<DropdownMenuItem<String>>((String doaValue) {
                   return DropdownMenuItem<String>(
                     value: doaValue,
                     child: Text(doaValue),
                   );
                 }).toList(),
               ),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

Body:
I want to be able to call either one of two different widgets based on the result of an if statement.
I am able to get a Text Widget to show two different answers based on the result of the first dropdown box, but I am not able to call another widget the same way ...

import 'package:flutter/material.dart';

class FilterPage extends StatefulWidget {
  const FilterPage({Key? key}) : super(key: key);

  @override
  State<FilterPage> createState() => _FilterPageState();
}

class _FilterPageState extends State<FilterPage> {
  String firstDropdownValue = 'Option A';
  String secondDropdownValue = 'Option B';

  @override
  void dispose() {
    super.dispose();
  }

  static const String _title = 'Filter Code Sample';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          Padding(
            padding: EdgeInsets.all(4),
          ),
        ],
        title: Column(
          children: [
            Text(
              'Filter',
              style: TextStyle(fontSize: 22, color: Colors.amberAccent),
            ),
          ],
        ),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: [
              Text(
                'What are the Options ?',
                style: TextStyle(fontSize: 16, color: Colors.white),
              ),

              /*
              * This is the first dropdown that is called, This dropdown provides
              * two possible options,
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: firstDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    firstDropdownValue = newValue!;
                  });
                },
                items: <String>['Option A', 'Option B']
                    .map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),

              /*
              * So this is the if Statement that works based upon the first
              * drop down box's answer...
              *
              * The problem is I can not get the system to call another Drop down Butten
              * Widget based on the answer of the first DropdownBox,
              * However, i can get a Text Widget to print...
              * */
              Text((() {
                if (firstDropdownValue == 'Option A') {
                  return "Option is Option A";
                }
                return "Option is Option B";
              })()),

              /*
              * This is the second dropbox that I would like to be called if the
              * previous statement is met instead of the Text Widget above...
              *(DROPBOX 2)
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: secondDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    secondDropdownValue = newValue!;
                  });
                },
                items: <String>[
                  'Option 1',
                  'Option 2',
                  'Option 3',
                ].map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),

              /*
              * This is also drop box two, but this dropbox with these different
              * options should be called when the if statement is not met ..
              *(DROPBOX 2)
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: secondDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    secondDropdownValue = newValue!;
                  });
                },
                items: <String>[
                  'Option 4',
                  'Option 5',
                  'Option 6',
                ].map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

The flow diagram is maybe easier to get the whole picture from.

Body:
You can use the Dart short if form: if ? then : else.
Since the only thing that changes are the dropdown options, you can dynamically change them without the need to use another widget.

import 'package:flutter/material.dart';

class FilterPage extends StatefulWidget {
  const FilterPage({Key? key}) : super(key: key);

  @override
  State<FilterPage> createState() => _FilterPageState();
}

class _FilterPageState extends State<FilterPage> {
  String firstDropdownValue = '';
  String secondDropdownValue = 'Option B';

  @override
  void dispose() {
    super.dispose();
  }

  static const String _title = 'Filter Code Sample';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          Padding(
            padding: EdgeInsets.all(4),
          ),
        ],
        title: Column(
          children: [
            Text(
              'Filter',
              style: TextStyle(fontSize: 22, color: Colors.amberAccent),
            ),
          ],
        ),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: [
              Text(
                'What are the Options ?',
                style: TextStyle(fontSize: 16, color: Colors.white),
              ),
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: firstDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    firstDropdownValue = newValue!;
                  });
                },
                items: <String>['Option A', 'Option B']
                    .map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),
              if(firstDropdownValue.isNotEmpty)
               DropdownButton<String>(
                 dropdownColor: Colors.blueGrey.shade700,
                 value: secondDropdownValue,
                 icon: const Icon(Icons.arrow_downward),
                 elevation: 16,
                 style: const TextStyle(color: Colors.white),
                 underline: Container(
                   height: 2,
                   color: Colors.blueGrey.shade900,
                 ),
                 onChanged: (String? newValue) {
                   setState(() {
                     secondDropdownValue = newValue!;
                   });
                 },
                 items: <String>[
                   firstDropdownValue == 'Option A' ?
                   ...['Option 1',
                   'Option 2',
                   'Option 3'] : ...['Option 5',
                   'Option 6',
                   'Option 7']
                 ].map<DropdownMenuItem<String>>((String doaValue) {
                   return DropdownMenuItem<String>(
                     value: doaValue,
                     child: Text(doaValue),
                   );
                 }).toList(),
               ),
            ],
          ),
        ),
      ),
    );
  }
}


问:
how to import JQuery to another html file
I have a html file and in that i have some html and jquery i want to import the jquery to another html file this is my html code ↓↓↓

```<code> <!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Register Form Test JQuery</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
        var data = "";
        let arr = [];

        $(document).ready(function() {
            var skills = [];
            var subjects = [];

            $("button").click(function() {
                $.each($("input[name='subject']:checked"), function() {
                    subjects.push($(this).val());

                });

                $.each($("input[name='skill']:checked"), function() {
                    skills.push($(this).val());
                });

                var email = $("#email").val();
                var password = $("#password").val();
                var dob = $("#dob").val();
                var gender = $("#gender").val();
                var address = $("#address").val();
                var city = $("#city").val();
                var telephone = $("#telephone").val();
                var aadhaar = $("#aadhaar").val();
                var role = $("#role").val();

                data = "Email: " + email + ", " + "Password: " + password + ", " + "Date Of Birth: " + dob + ", " + "Gender: " + gender + ", " + "Address: " + address + ", " + "City: " + city + ", " + "Subjects: " + subjects.join(", ") + ", " + "Skills: " + skills.join(", ") + ", " + "Telephone Number: " + telephone + ", " + "Aadhaar Number: " + aadhaar + ", " + "Role: " + role;
                arr.push(data);
                console.log(data)
            });
        });
    </script>
</head>

<body>
    <form>
        <label>Email:</label><br>
        <input id="email" type="email" required><br>
        <label>Date Of Birth:</label><br>
        <input id="dob" type="date" required><br>
        <label>Role:</label><br>
        <select id="role" required>
    <option>Learner</option>
    <option>Educator</option>
    <option>Both</option>
    </select><br>
        <label>Gender:</label><br>
        <select id="gender" required>
      <option>Male</option>
      <option>Female</option>
      <option>other</option>
    </select><br>
        <label>Address:</label><br/>
        <input id="address" type="text" required><br/>
        <label>City:</label><br>
        <input id="city" type="text" required><br>
        <label>Subject/s</label><br>
        <label><input type="checkbox" value="Math" name="subject"> Math</label>
        <label><input type="checkbox" value="Science" name="subject"> Science</label>
        <label><input type="checkbox" value="SST" name="subject"> SST</label>
        <label><input type="checkbox" value="English" name="subject"> English</label>
        <label><input type="checkbox" value="Computer Science" name="subject"> Computer Science</label>
        <label><input type="checkbox" value="Kannada" name="subject"> Kannada</label><br>
        <label><input type="checkbox" value="Hindi" name="subject"> Hindi</label><br>
        <label>Skill/s</label>
        <BR>
        <label><input type="checkbox" value="Drawing/Doodling" name="skill"> Drawing/Doodling</label>
        <label><input type="checkbox" value="Instrument Playing" name="skill"> Instrument Playing</label>
        <label><input type="checkbox" value="Dance and/or Music" name="skill"> Dance and/or Music</label>
        <label><input type="checkbox" value="sports (any)" name="skill"> sports (any)</label><br>
        <label>Telephone Number:</label><br>
        <input type="tel" id="telephone" placeholder="1234-567890" pattern="[0-9]{4}-[0-9]{6}"><br>
        <label>Aadhaar Number (if available):</label><br>
        <input id="aadhaar" placeholder="1234-5678-9000" pattern="[0-9]{4}-[0-9]{4}-[0-9]{4}"><br>
        <label>Password:</label><br>
        <input type="password" id="password" required><br><br>
        <button type="button" value="submit">Submit</button>
    </form>
</body>

</html>
</code>```

How do i import the jquery script which is in this html file to another html file which also contains jquery? Is there any code which i need to input in my other file or do i need to link it in this html file?

Thanks for your help!

答:
What we can do is take a script file and add the jQuery link in that JS file.
ex: MyJSFile.js

```<code>var script = document.createElement('script');
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);

    var data = "";
    let arr = [];

    $(document).ready(function() {
        var skills = [];
        var subjects = [];

        $("button").click(function() {
            $.each($("input[name='subject']:checked"), function() {
                subjects.push($(this).val());

            });

            $.each($("input[name='skill']:checked"), function() {
                skills.push($(this).val());
            });

            var email = $("#email").val();
            var password = $("#password").val();
            var dob = $("#dob").val();
            var gender = $("#gender").val();
            var address = $("#address").val();
            var city = $("#city").val();
            var telephone = $("#telephone").val();
            var aadhaar = $("#aadhaar").val();
            var role = $("#role").val();

            data = "Email: " + email + ", " + "Password: " + password + ", " + "Date Of Birth: " + dob + ", " + "Gender: " + gender + ", " + "Address: " + address + ", " + "City: " + city + ", " + "Subjects: " + subjects.join(", ") + ", " + "Skills: " + skills.join(", ") + ", " + "Telephone Number: " + telephone + ", " + "Aadhaar Number: " + aadhaar + ", " + "Role: " + role;
            arr.push(data);
            console.log(data)
        });
    });
</code>```

Now you can import your MyJSFile.js file in as many HTML files as you can as shown in below.

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Register Form Test JQuery</title>
    <script src="MyJSFile.js"></script>
</head>
   <body>
   </body>
</html>
</code>```

Body:
I have a html file and in that i have some html and jquery i want to import the jquery to another html file this is my html code ↓↓↓

 <!DOCTYPE html>

    <meta charset="utf-8">
    <title>Register Form Test JQuery</title>

    <form>
        Email:

        <input id="email" type="email" required>

        Date Of Birth:

        <input id="dob" type="date" required>

        Role:

        <select id="role" required>
    <option>Learner</option>
    <option>Educator</option>
    <option>Both</option>
    </select>

        Gender:

        <select id="gender" required>
      <option>Male</option>
      <option>Female</option>
      <option>other</option>
    </select>

        Address:

        <input id="address" type="text" required>

        City:

        <input id="city" type="text" required>

        Subject/s

        <input type="checkbox" value="Math" name="subject"> Math
        <input type="checkbox" value="Science" name="subject"> Science
        <input type="checkbox" value="SST" name="subject"> SST
        <input type="checkbox" value="English" name="subject"> English
        <input type="checkbox" value="Computer Science" name="subject"> Computer Science
        <input type="checkbox" value="Kannada" name="subject"> Kannada

        <input type="checkbox" value="Hindi" name="subject"> Hindi

        Skill/s

        <input type="checkbox" value="Drawing/Doodling" name="skill"> Drawing/Doodling
        <input type="checkbox" value="Instrument Playing" name="skill"> Instrument Playing
        <input type="checkbox" value="Dance and/or Music" name="skill"> Dance and/or Music
        <input type="checkbox" value="sports (any)" name="skill"> sports (any)

        Telephone Number:

        <input type="tel" id="telephone" placeholder="1234-567890" pattern="[0-9]{4}-[0-9]{6}">

        Aadhaar Number (if available):

        <input id="aadhaar" placeholder="1234-5678-9000" pattern="[0-9]{4}-[0-9]{4}-[0-9]{4}">

        Password:

        <input type="password" id="password" required>

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

How do i import the jquery script which is in this html file to another html file which also contains jquery? Is there any code which i need to input in my other file or do i need to link it in this html file?

Thanks for your help!

Body:
What we can do is take a script file and add the jQuery link in that JS file.
ex: MyJSFile.js

var script = document.createElement('script');
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);

    var data = "";
    let arr = [];

    $(document).ready(function() {
        var skills = [];
        var subjects = [];

        $("button").click(function() {
            $.each($("input[name='subject']:checked"), function() {
                subjects.push($(this).val());

            });

            $.each($("input[name='skill']:checked"), function() {
                skills.push($(this).val());
            });

            var email = $("#email").val();
            var password = $("#password").val();
            var dob = $("#dob").val();
            var gender = $("#gender").val();
            var address = $("#address").val();
            var city = $("#city").val();
            var telephone = $("#telephone").val();
            var aadhaar = $("#aadhaar").val();
            var role = $("#role").val();

            data = "Email: " + email + ", " + "Password: " + password + ", " + "Date Of Birth: " + dob + ", " + "Gender: " + gender + ", " + "Address: " + address + ", " + "City: " + city + ", " + "Subjects: " + subjects.join(", ") + ", " + "Skills: " + skills.join(", ") + ", " + "Telephone Number: " + telephone + ", " + "Aadhaar Number: " + aadhaar + ", " + "Role: " + role;
            arr.push(data);
            console.log(data)
        });
    });

Now you can import your MyJSFile.js file in as many HTML files as you can as shown in below.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Register Form Test JQuery</title>
    <script src="MyJSFile.js"></script>
</head>
   <body>
   </body>
</html>


问:
C++ how to add destructor to anonymous class?
how do you add a destructor to an anonymous class in C++? like in PHP if i want to run something when my class go out of scope it'd be

$foo = new class() {
        public $i=0;
        public function __destruct()
        {
            echo "foo is going out of scope!\n";
        }
    };
```
<p>but in C++ with normal non-anonymous classes you specify the destructor with <code>~ClassName(){}</code>, but anonymous classes doesn't have a name! so how do you add a destructor to</p>
<pre class="lang-cpp prettyprint-override"><code>class {public: int i=0; } foo;
</code>```

in c++? i tried using the variable name as the class name, but that didn't work:

class {
public:
  int i;
  ~foo(){std::cout << "foo is going out of scope!" << std::endl;}
} foo;
```
<p>resulting in</p>
<pre class="lang-none prettyprint-override"><code>prog.cc: In function 'int main()':
prog.cc:51:31: error: expected class-name before '(' token
   51 |     class {public: int i=0; ~foo(){std::cout << "foo is going out of scope!" << std::endl;};} foo;
      |                               ^
</code>```

i also tried specifying just ~ but that didn't work either,

class {
public:
  int i=0;
  ~(){std::cout << "foo is going out of scope" << std::endl;}
} foo;
```
<p>resulted in</p>
<pre class="lang-none prettyprint-override"><code>prog.cc:48:30: error: expected class-name before '(' token
   48 |     class {public: int i=0; ~(){std::cout << "foo is going out of scope" << std::endl;};} foo;
      |                              ^
</code>```

答:
This cannot be done in C++. However, the real C++ analogue of anonymous classes is called an anonymous namespace:

```<code>namespace {
   struct foo {
     // ... whatever
     ~foo();
   };
}

// ... later in the same C++ source.

foo bar;
</code>```

Now you can use and reference foos everywhere in this specific C++ source file. Other C++ source files may have their own anonymous namespace, with their own foos, without creating a conflict. The end result is pretty much the same thing as C-style anonymous structs (a.k.a. classes), except that they're not really anonymous, only their namespace is.

Body:
how do you add a destructor to an anonymous class in C++? like in PHP if i want to run something when my class go out of scope it'd be

$foo = new class() {
        public $i=0;
        public function __destruct()
        {
            echo "foo is going out of scope!\n";
        }
    };

but in C++ with normal non-anonymous classes you specify the destructor with ~ClassName(){}, but anonymous classes doesn't have a name! so how do you add a destructor to

class {public: int i=0; } foo;

in c++? i tried using the variable name as the class name, but that didn't work:

class {
public:
  int i;
  ~foo(){std::cout << "foo is going out of scope!" << std::endl;}
} foo;

resulting in

prog.cc: In function 'int main()':
prog.cc:51:31: error: expected class-name before '(' token
   51 |     class {public: int i=0; ~foo(){std::cout << "foo is going out of scope!" << std::endl;};} foo;
      |                               ^

i also tried specifying just ~ but that didn't work either,

class {
public:
  int i=0;
  ~(){std::cout << "foo is going out of scope" << std::endl;}
} foo;

resulted in

prog.cc:48:30: error: expected class-name before '(' token
   48 |     class {public: int i=0; ~(){std::cout << "foo is going out of scope" << std::endl;};} foo;
      |                              ^

Body:
This cannot be done in C++. However, the real C++ analogue of anonymous classes is called an anonymous namespace:

namespace {
   struct foo {
     // ... whatever
     ~foo();
   };
}

// ... later in the same C++ source.

foo bar;

Now you can use and reference foos everywhere in this specific C++ source file. Other C++ source files may have their own anonymous namespace, with their own foos, without creating a conflict. The end result is pretty much the same thing as C-style anonymous structs (a.k.a. classes), except that they're not really anonymous, only their namespace is.


问:
how to search and get herf's value
```<code><a class="wiki-link-external" href="http://example.com" target="_blank" rel="nofollow noopener" title="http://example.com">
</code>```

I want to get http://example.com

I tried

```<code>img = driver.find_elements_by_css_selector('a.wiki-link-external')

print(len(img))

for a in img:
    print(a.get_attribute('herf'))
</code>```

but only get [] and 1 ...

答:
```<code>img = driver.find_elements_by_css_selector('a.wiki-link-external')

print(len(img))

for a in img:
    print(a.get_attribute('href'))
</code>```

href not herf

Title: how to search and get herf's value

Body:
I want to get http://example.com

I tried

img = driver.find_elements_by_css_selector('a.wiki-link-external')

print(len(img))

for a in img:
    print(a.get_attribute('herf'))

but only get [] and 1 ...

Body:
img = driver.find_elements_by_css_selector('a.wiki-link-external')

print(len(img))

for a in img:
    print(a.get_attribute('href'))

href not herf


问:
how to change table command results and add p-value in R
I have such data

```<code>AE=structure(list(TRTGROUP_E1_C18 = c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 2L, 2L, 2L, 2L), AETERM = c("increase in lymphocytes", "increase in lymphocytes",
"increase in abs. lymphocytes", "increase in lymphocytes", "decrease in abs. neutrophils",
"decrease in neutrophils", "decrease in abs. monocytes", "decrease in monocytes",
"increase in lymphocytes", "decrease in hemoglobin", "decrease in neutrophils",
"decrease in abs. monocytes ")), class = "data.frame", row.names = c(NA,
-12L))
</code>```

I want to see the ratio of different types of adverse events for each group.
I use table(AE) and the output format is not in the form of a table that I would like.
I need this format

N=number people in group.
0(0,0%) - Absolute value (and percentage)  and also p-value via chisq.test(table(AE$RTGROUP, dat$AETERM)) for each ae.
How to get such desired table?
Thank you for your help.

答:
You can use the function table1() from the package table1.

Since your calculation of p-value includes some columns that are not present in AE, I'll ignore it.

```<code>library(table1)

table1(~AETERM | TRTGROUP_E1_C18, data = AE)
</code>```

Body:
I have such data

AE=structure(list(TRTGROUP_E1_C18 = c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 2L, 2L, 2L, 2L), AETERM = c("increase in lymphocytes", "increase in lymphocytes",
"increase in abs. lymphocytes", "increase in lymphocytes", "decrease in abs. neutrophils",
"decrease in neutrophils", "decrease in abs. monocytes", "decrease in monocytes",
"increase in lymphocytes", "decrease in hemoglobin", "decrease in neutrophils",
"decrease in abs. monocytes ")), class = "data.frame", row.names = c(NA,
-12L))

I want to see the ratio of different types of adverse events for each group.
I use table(AE) and the output format is not in the form of a table that I would like.
I need this format

N=number people in group.
0(0,0%) - Absolute value (and percentage)  and also p-value via chisq.test(table(AE$RTGROUP, dat$AETERM)) for each ae.
How to get such desired table?
Thank you for your help.

Body:
You can use the function table1() from the package table1.

Since your calculation of p-value includes some columns that are not present in AE, I'll ignore it.

library(table1)

table1(~AETERM | TRTGROUP_E1_C18, data = AE)


问:
why a captured image bitmap from Android camera is rotated
I am using IMAGE_CAPTURE camera intent to capture and image and storing it in a file using MediaStore.EXTRA_OUTPUT. When I receive the image in onActivityResult, the bitmap is rotated.

Any suggestions on how to resolve this please.

Intent and passing the uri where I want the file to be stored

```<code>private fun capturePhoto() {
    val capturedImage = File(this.requireContext().externalCacheDir, "utility_bill.jpg")
    if (capturedImage.exists()) {
        capturedImage.delete()
    }
    capturedImage.createNewFile()
    mUri = if (Build.VERSION.SDK_INT >= 24) {
        FileProvider.getUriForFile(
            this.requireContext(),
            this.requireContext().applicationContext.packageName,
            capturedImage
        )
    } else {
        Uri.fromFile(capturedImage)
    }

    val intent = Intent("android.media.action.IMAGE_CAPTURE")
    intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri)
    startActivityForResult(intent, CAMERA_REQUEST_CODE)
}
</code>```

in onActivityResult bitmap is rotated.

```<code>override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        hideScreen.visibility = View.GONE
        if (resultCode == Activity.RESULT_OK && requestCode == CAMERA_REQUEST_CODE) {
            uploadedImageCount++
            val bitmap = BitmapFactory.decodeStream(
                this.requireContext().contentResolver.openInputStream(mUri!!)
            )
}}
</code>```

Image that I captured

when I debugged the bitmap received in the code, it is rotataed

Any suggestions on how I can resolve this please

Thanks in advance
R

答:
I Faced The Same issue when i was developing the app most this was the case for devices like Samsung, HTC and some devices....This Happens because of Exif Interface which is different for the devices mentioned Above so make a separate Java class ExifUtil.java and the code goes like this
Note This Code Is In Java

```<code>import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.Build;

public class ExifUtil {
    /**
//     * @see https://sylvana.net/jpegcrop/exif_orientation.html
     */
    public static Bitmap rotateBitmap(String src, Bitmap bitmap) {
        try {
            int orientation = getExifOrientation(src);

            if (orientation == 1) {
                return bitmap;
            }

            Matrix matrix = new Matrix();
            switch (orientation) {
                case 2:
                    matrix.setScale(-1, 1);
                    break;
                case 3:
                    matrix.setRotate(180);
                    break;
                case 4:
                    matrix.setRotate(180);
                    matrix.postScale(-1, 1);
                    break;
                case 5:
                    matrix.setRotate(90);
                    matrix.postScale(-1, 1);
                    break;
                case 6:
                    matrix.setRotate(90);
                    break;
                case 7:
                    matrix.setRotate(-90);
                    matrix.postScale(-1, 1);
                    break;
                case 8:
                    matrix.setRotate(-90);
                    break;
                default:
                    return bitmap;
            }

            try {
                Bitmap oriented = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                bitmap.recycle();
                return oriented;
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
                return bitmap;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return bitmap;
    }

    private static int getExifOrientation(String src) throws IOException {
        int orientation = 1;

        try {
            /**
             * if your are targeting only api level >= 5
             * ExifInterface exif = new ExifInterface(src);
             * orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
             */
            if (Build.VERSION.SDK_INT >= 5) {
                Class<?> exifClass = Class.forName("android.media.ExifInterface");
                Constructor<?> exifConstructor = exifClass.getConstructor(new Class[] { String.class });
                Object exifInstance = exifConstructor.newInstance(new Object[] { src });
                Method getAttributeInt = exifClass.getMethod("getAttributeInt", new Class[] { String.class, int.class });
                Field tagOrientationField = exifClass.getField("TAG_ORIENTATION");
                String tagOrientation = (String) tagOrientationField.get(null);
                orientation = (Integer) getAttributeInt.invoke(exifInstance, new Object[] { tagOrientation, 1});
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

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

and OnActivityResult where save it like this
Bitmap orientedBitmap = ExifUtil.rotateBitmap(img_path, myBitmap);

```<code>this will automatically determine the orientation of the mage and rotate it to Potrait...!!
</code>```

Body:
I am using IMAGE_CAPTURE camera intent to capture and image and storing it in a file using MediaStore.EXTRA_OUTPUT. When I receive the image in onActivityResult, the bitmap is rotated.

Any suggestions on how to resolve this please.

Intent and passing the uri where I want the file to be stored

private fun capturePhoto() {
    val capturedImage = File(this.requireContext().externalCacheDir, "utility_bill.jpg")
    if (capturedImage.exists()) {
        capturedImage.delete()
    }
    capturedImage.createNewFile()
    mUri = if (Build.VERSION.SDK_INT >= 24) {
        FileProvider.getUriForFile(
            this.requireContext(),
            this.requireContext().applicationContext.packageName,
            capturedImage
        )
    } else {
        Uri.fromFile(capturedImage)
    }

    val intent = Intent("android.media.action.IMAGE_CAPTURE")
    intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri)
    startActivityForResult(intent, CAMERA_REQUEST_CODE)
}

in onActivityResult bitmap is rotated.

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        hideScreen.visibility = View.GONE
        if (resultCode == Activity.RESULT_OK && requestCode == CAMERA_REQUEST_CODE) {
            uploadedImageCount++
            val bitmap = BitmapFactory.decodeStream(
                this.requireContext().contentResolver.openInputStream(mUri!!)
            )
}}

Image that I captured

when I debugged the bitmap received in the code, it is rotataed

Any suggestions on how I can resolve this please

Thanks in advance
R

Body:
I Faced The Same issue when i was developing the app most this was the case for devices like Samsung, HTC and some devices....This Happens because of Exif Interface which is different for the devices mentioned Above so make a separate Java class ExifUtil.java and the code goes like this
Note This Code Is In Java

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.Build;

public class ExifUtil {
    /**
//     * @see https://sylvana.net/jpegcrop/exif_orientation.html
     */
    public static Bitmap rotateBitmap(String src, Bitmap bitmap) {
        try {
            int orientation = getExifOrientation(src);

            if (orientation == 1) {
                return bitmap;
            }

            Matrix matrix = new Matrix();
            switch (orientation) {
                case 2:
                    matrix.setScale(-1, 1);
                    break;
                case 3:
                    matrix.setRotate(180);
                    break;
                case 4:
                    matrix.setRotate(180);
                    matrix.postScale(-1, 1);
                    break;
                case 5:
                    matrix.setRotate(90);
                    matrix.postScale(-1, 1);
                    break;
                case 6:
                    matrix.setRotate(90);
                    break;
                case 7:
                    matrix.setRotate(-90);
                    matrix.postScale(-1, 1);
                    break;
                case 8:
                    matrix.setRotate(-90);
                    break;
                default:
                    return bitmap;
            }

            try {
                Bitmap oriented = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                bitmap.recycle();
                return oriented;
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
                return bitmap;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return bitmap;
    }

    private static int getExifOrientation(String src) throws IOException {
        int orientation = 1;

        try {
            /**
             * if your are targeting only api level >= 5
             * ExifInterface exif = new ExifInterface(src);
             * orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
             */
            if (Build.VERSION.SDK_INT >= 5) {
                Class<?> exifClass = Class.forName("android.media.ExifInterface");
                Constructor<?> exifConstructor = exifClass.getConstructor(new Class[] { String.class });
                Object exifInstance = exifConstructor.newInstance(new Object[] { src });
                Method getAttributeInt = exifClass.getMethod("getAttributeInt", new Class[] { String.class, int.class });
                Field tagOrientationField = exifClass.getField("TAG_ORIENTATION");
                String tagOrientation = (String) tagOrientationField.get(null);
                orientation = (Integer) getAttributeInt.invoke(exifInstance, new Object[] { tagOrientation, 1});
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        return orientation;
    }
}

and OnActivityResult where save it like this
Bitmap orientedBitmap = ExifUtil.rotateBitmap(img_path, myBitmap);

this will automatically determine the orientation of the mage and rotate it to Potrait...!!


问:
How to encode a file in base 64 a certain number of times in python?
Lets say that I have a file named input.txt and I need to encode this specific file in base-64 a certain number of times (script asks the user how many times they want to encode the file ) and then save the result to an output file say encoded_input.txt. For example:

Lets say that the content of file input.txt is:

```<code>"Hello world_1 and Hello world_2"
</code>```

And that the user of the script wants to encode the file input.txt 2 times.
So the script should generate a file named  encoded_input.txt which contains:

```<code>U0dWc2JHOGdkMjl5YkdSZk1TQmhibVFnU0dWc2JHOGdkMjl5YkdSZk1nPT0=
</code>```

Hence encoding the contents of input.txt 2 times in base-64.

Any idea to how to approach it? I do not want to import any other module than import base64

答:
You could repeat the encoding function after loading up the file any amount of times you want using a for loop:

import base64

times_to_encode = 2

with open('input.txt') as f:
    file_to_encode = f.read().encode('utf-8')

for _ in range(times_to_encode):
    file_to_encode = base64.b64encode(file_to_encode)

with open('encoded_input.txt', 'w') as f:
    f.write(file_to_encode.decode('utf-8'))
```

The times_to_encode variable sets how many times the string is encoded.

Body:
Lets say that I have a file named input.txt and I need to encode this specific file in base-64 a certain number of times (script asks the user how many times they want to encode the file ) and then save the result to an output file say encoded_input.txt. For example:

Lets say that the content of file input.txt is:

"Hello world_1 and Hello world_2"

And that the user of the script wants to encode the file input.txt 2 times.
So the script should generate a file named  encoded_input.txt which contains:

U0dWc2JHOGdkMjl5YkdSZk1TQmhibVFnU0dWc2JHOGdkMjl5YkdSZk1nPT0=

Hence encoding the contents of input.txt 2 times in base-64.

Any idea to how to approach it? I do not want to import any other module than import base64

Body:
You could repeat the encoding function after loading up the file any amount of times you want using a for loop:

import base64

times_to_encode = 2

with open('input.txt') as f:
    file_to_encode = f.read().encode('utf-8')

for _ in range(times_to_encode):
    file_to_encode = base64.b64encode(file_to_encode)

with open('encoded_input.txt', 'w') as f:
    f.write(file_to_encode.decode('utf-8'))

The times_to_encode variable sets how many times the string is encoded.


问:
Can I force the use of 'this' keyword in c# .NET?
Is there a way to force the use of the this keyword in Visual Studio when referencing current instance members?

Example with a bug in the constructor:

```<code>class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        Foo = Foo; // this should of course be lowercase but it's easy to miss
    }
}
</code>```

This code will probably generate the infamous 'object reference not set to an instance of an object' exception somewhere later on.

How to make it work but still It's easy to miss:

```<code>class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        Foo = foo; // Valid syntax but unclear.
    }
}
</code>```

This is valid syntax but it's easy to miss.

The syntax I'd like visual studio enforce:

```<code>class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        this.Foo = foo; // this is "safe".
    }
}
</code>```

If this convention is enforced i would have to type this.Foo = this.Foo to create the same type of bug as in the first example.

I always use the this keyword anyway since it makes my life easier while switching between c# and other languages so there wouldn't be any disadvantages at all.

答:
You can fix this simply by enabling "Treat warnings as errors":

Warning   2   Assignment made to same variable; did you mean to assign something else?

(CS1717 if you want to enable it just for this one)

The compiler already tells you about this; you should be reviewing the warnings (and aim for zero warnings).

Re the middle one being unclear:

```<code>Foo = foo;
</code>```

I disagree - that is perfectly clear to me (unless you come from a VB background and have developed case-blindness).

Body:
Is there a way to force the use of the this keyword in Visual Studio when referencing current instance members?

Example with a bug in the constructor:

class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        Foo = Foo; // this should of course be lowercase but it's easy to miss
    }
}

This code will probably generate the infamous 'object reference not set to an instance of an object' exception somewhere later on.

How to make it work but still It's easy to miss:

class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        Foo = foo; // Valid syntax but unclear.
    }
}

This is valid syntax but it's easy to miss.

The syntax I'd like visual studio enforce:

class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        this.Foo = foo; // this is "safe".
    }
}

If this convention is enforced i would have to type this.Foo = this.Foo to create the same type of bug as in the first example.

I always use the this keyword anyway since it makes my life easier while switching between c# and other languages so there wouldn't be any disadvantages at all.

Body:
You can fix this simply by enabling "Treat warnings as errors":

Warning   2   Assignment made to same variable; did you mean to assign something else?

(CS1717 if you want to enable it just for this one)

The compiler already tells you about this; you should be reviewing the warnings (and aim for zero warnings).

Re the middle one being unclear:

Foo = foo;

I disagree - that is perfectly clear to me (unless you come from a VB background and have developed case-blindness).


问:
Rust Async Executor Memory Ordering Guarantees When Moving Tasks Across Threads?
This is a rather basic question regarding the memory ordering guarantees inside the Rust async ecosystems. However, I don't seem to find a clear answer anywhere.

C++ memory ordering specifies the memory ordering from a thread-based perspective:

Release-Acquire ordering

If an atomic store in thread A is tagged memory_order_release and an atomic load in thread B from the same variable is tagged memory_order_acquire, all memory writes (non-atomic and relaxed atomic) that happened-before the atomic store from the point of view of thread A, become visible side-effects in thread B. That is, once the atomic load is completed, thread B is guaranteed to see everything thread A wrote to memory.

Various Rust async executors supports moving tasks across thread at .await points. A natural scenario would be:

Task A was at Thread 1 and performed a Relaxed store at variable x.

Task A hit a .await point

Task A was moved to Thread 2 and awaked. And then performed a Release store at variable y.

Task B was at Thread 3 and performed an Acquire load at variable y.

The question is: Is the Relaxed store from Thread 1 guaranteed to be visible in Task B after the Acquire load? E.g. if Task B at Thread 3 performed an Relaxed load at variable x afterwards, is it guaranteed that Task A's side effect will be visible?

This should depend on the implementation of synchronization mechanisms inside each async executor's task scheduler. Anyone familiar with them is appreciated.

答:
Comment from Tokio maintainer:

When the task is moved from one thread to another, there is a synchronizes-with relation between the things before and after the .await. Depending on the exact circumstances, the synchronization comes from a mutex or an atomic using acquire & release semantics.

In C++ memory spec, synchronizse-with guarantees inter-thread happens-before. Therefore at least in Tokio, it should be safe to ignore memory ordering impact from a .await point.