问:
Lifecycle OnLifecycleEvent is deprecated
After updating lifecycle library to 2.4.0 Android studio marked all Lifecycle events as deprecated.

```<code>@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun create() {
    tts = TextToSpeech(context, this)
}

@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun stopTTS() {
    tts?.stop()
}
</code>```

Is there any equivalent replacement such as DefaultLifecycleObserver ?

答:
Your class must implement DefaultLifecycleObserver like so

```<code>public class MyFavoriteClass implements DefaultLifecycleObserver
</code>```

Then implement the methods needed (Android Studio: ALT + i)

```<code>@Override
public void onResume(@NonNull LifecycleOwner owner) {
    methodRunsAtOnResume();
}

@Override
public void onDestroy(@NonNull LifecycleOwner owner) {
    myFavoriteOnDestroyMethod();
}
</code>```

In your activity or fragment add this to onCreate()

```<code>@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    MyOtherClass clazz = new MyOtherClass();
    getLifecycle().addObserver(clazz);
}
</code>```

To implement it more correctly create your own observer class, pass the object you like to observe to it. Nice article about it is https://medium.com/@MinaSamy/android-architecture-components-lifecycle-433ace1ec05d

Body:
After updating lifecycle library to 2.4.0 Android studio marked all Lifecycle events as deprecated.

@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun create() {
    tts = TextToSpeech(context, this)
}

@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun stopTTS() {
    tts?.stop()
}

Is there any equivalent replacement such as DefaultLifecycleObserver ?

Body:
Your class must implement DefaultLifecycleObserver like so

public class MyFavoriteClass implements DefaultLifecycleObserver

Then implement the methods needed (Android Studio: ALT + i)

@Override
public void onResume(@NonNull LifecycleOwner owner) {
    methodRunsAtOnResume();
}

@Override
public void onDestroy(@NonNull LifecycleOwner owner) {
    myFavoriteOnDestroyMethod();
}

In your activity or fragment add this to onCreate()

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    MyOtherClass clazz = new MyOtherClass();
    getLifecycle().addObserver(clazz);
}

To implement it more correctly create your own observer class, pass the object you like to observe to it. Nice article about it is https://medium.com/@MinaSamy/android-architecture-components-lifecycle-433ace1ec05d


来源: stackexchange

ContentLicense: CC BY-SA 4.0

Title: I want normalize data by dividing every row by the price on the first row

Body:
I have a dataframe in pandas. I want to normalize my Close column by dividing every row by the price on the first row. This is my attempt:

import pandas as pd
import yfinance as yf

bova=yf.download('BOVA11.SA',
                 start='2014-01-01',
                 end='2021-12-31',
                 progress=False,
                 )
bova

output:

              Open          High     Low          Close     Adj Close   Volume
Date
2014-01-02  50.220001   50.270000   49.060001   49.080002   49.080002   1001210
2014-01-03  49.099998   49.470001   49.049999   49.259998   49.259998   1227270
2014-01-06  49.259998   49.990002   49.200001   49.840000   49.840000   702060
2014-01-07  49.549999   50.290001   49.230000   49.230000   49.230000   1304100
2014-01-08  49.540001   49.590000   49.209999   49.279999   49.279999   951950
... ... ... ... ... ... ...
2021-12-23  101.599998  101.599998  100.709999  100.849998  100.849998  5047637
2021-12-27  101.400002  101.800003  100.949997  101.599998  101.599998  5274352
2021-12-28  101.830002  101.830002  100.589996  101.059998  101.059998  7167734
2021-12-29  101.239998  101.349998  99.940002   100.250000  100.250000  7343838
2021-12-30  100.809998  101.449997  100.290001  100.800003  100.800003  3404622

Body:
Use:

bova['Norm Close'] = bova['Close'] / bova['Close'][0]
print(bova[['Close', 'Norm Close']])

# Output
                 Close  Norm Close
Date
2014-01-02   49.080002    1.000000
2014-01-03   49.259998    1.003667
2014-01-06   49.840000    1.015485
2014-01-07   49.230000    1.003056
2014-01-08   49.279999    1.004075
...                ...         ...
2021-12-23  100.849998    2.054808
2021-12-27  101.599998    2.070090
2021-12-28  101.059998    2.059087
2021-12-29  100.250000    2.042583
2021-12-30  100.800003    2.053790

[1986 rows x 2 columns]


问:
Not sure what is causing index error in my code
I am working on a small project which is intended to read, create, and manipulate virtual to-do lists. There is a checkbox class, a function open_create_boxes to create a list of checkbox objects based on the contents of a plaintext file, and a function create_to_do_list_file to write a file which can be read by the other function.

```<code># Define the checkbox class
class checkbox:
    def __init__(self,label):
        self.label = label
        self.checked = False
    def check(self):
        self.checked = True
    def read(self):
        if self.checked:
            return f"x | {self.label}"
        if not self.checked:
            return f"o | {self.label}"

def open_create_boxes(file):
    # Open the to-do list
    opened_list = open(f"{file}.dat", "r")
    #Split the to-do list by line
    parsed_line = opened_list.read().split("\n")
    next_parsed = []
    # Split each element in parsed list by the pipe symbol
    for i in parsed_line:
        next_parsed.append(i.split("|"))
    to_do_list = []
    # Iterates through the new list, creates checkbox object, checks to see if it is "checked" or not
    for i in next_parsed:
        b = checkbox(i[1])
        if i[0] == "x":
            b.check()
        to_do_list.append(b)
    return to_do_list

def create_to_do_list_file(list,label):
    # Open or create a file label.dat
    new_file = open(f"{label}.dat", "w")
    for n in list:
        new_file.write(f"\no|{n}")

create_to_do_list_file(["Task"],"filename")
open_create_boxes("filename")
</code>```

Running this code gives me the error:

```<code>  File "/home/genie/Desktop/checkboxes/checkboxes.py", line 41, in <module>
    open_create_boxes("filename")
  File "/home/genie/Desktop/checkboxes/checkboxes.py", line 28, in open_create_boxes
    b = checkbox(i[1])
IndexError: list index out of range
</code>```

So something is going wrong in my open_create_boxes function, where the list is coming out with <2 elements. I have re-written this code several times and get the same, or similar, errors.

Any help here? I'm a beginner, so I imagine there's an obvious fix, but I can't seem to manage.

Thanks!!

答:
Quickly running your code and examining the created file reveals that its first line is empty. Of course you will only get one field if you attempt to split that. Why are you writing \n in front of the data?

Similarly, your code to read the file fails to account for the empty line, whether at the beginning or the end of the file.

More tangentially, you are forgetting to close the file you write, and generally overcomplicate matters.

Here is a quick refactoring of the two file-management functions.

```<code>def open_create_boxes(file):
    to_do_list = []
    with open(f"{file}.dat", "r") as lines:
        for line in lines:
            i = line.rstrip("\n").split("|")
            # print("#", i)
            b = checkbox(i[1])
            if i[0] == "x":
                b.check()
            to_do_list.append(b)
    return to_do_list

# Don't call your variable "list"
def create_to_do_list_file (items ,label):
    with open(f"{label}.dat", "w") as new_file:
        for n in items:
            new_file.write(f"o|{n}\n")
</code>```

As a general first tip for how to debug things, break your problem into smaller steps and add a print statement at various points to verify that the variables contain what you hope they should, or use a debugger and set a breakpoint to examine the program's state at those spots.

Body:
I am working on a small project which is intended to read, create, and manipulate virtual to-do lists. There is a checkbox class, a function open_create_boxes to create a list of checkbox objects based on the contents of a plaintext file, and a function create_to_do_list_file to write a file which can be read by the other function.

# Define the checkbox class
class checkbox:
    def __init__(self,label):
        self.label = label
        self.checked = False
    def check(self):
        self.checked = True
    def read(self):
        if self.checked:
            return f"x | {self.label}"
        if not self.checked:
            return f"o | {self.label}"

def open_create_boxes(file):
    # Open the to-do list
    opened_list = open(f"{file}.dat", "r")
    #Split the to-do list by line
    parsed_line = opened_list.read().split("\n")
    next_parsed = []
    # Split each element in parsed list by the pipe symbol
    for i in parsed_line:
        next_parsed.append(i.split("|"))
    to_do_list = []
    # Iterates through the new list, creates checkbox object, checks to see if it is "checked" or not
    for i in next_parsed:
        b = checkbox(i[1])
        if i[0] == "x":
            b.check()
        to_do_list.append(b)
    return to_do_list

def create_to_do_list_file(list,label):
    # Open or create a file label.dat
    new_file = open(f"{label}.dat", "w")
    for n in list:
        new_file.write(f"\no|{n}")

create_to_do_list_file(["Task"],"filename")
open_create_boxes("filename")

Running this code gives me the error:

  File "/home/genie/Desktop/checkboxes/checkboxes.py", line 41, in <module>
    open_create_boxes("filename")
  File "/home/genie/Desktop/checkboxes/checkboxes.py", line 28, in open_create_boxes
    b = checkbox(i[1])
IndexError: list index out of range

So something is going wrong in my open_create_boxes function, where the list is coming out with <2 elements. I have re-written this code several times and get the same, or similar, errors.

Any help here? I'm a beginner, so I imagine there's an obvious fix, but I can't seem to manage.

Thanks!!

Body:
Quickly running your code and examining the created file reveals that its first line is empty. Of course you will only get one field if you attempt to split that. Why are you writing \n in front of the data?

Similarly, your code to read the file fails to account for the empty line, whether at the beginning or the end of the file.

More tangentially, you are forgetting to close the file you write, and generally overcomplicate matters.

Here is a quick refactoring of the two file-management functions.

def open_create_boxes(file):
    to_do_list = []
    with open(f"{file}.dat", "r") as lines:
        for line in lines:
            i = line.rstrip("\n").split("|")
            # print("#", i)
            b = checkbox(i[1])
            if i[0] == "x":
                b.check()
            to_do_list.append(b)
    return to_do_list

# Don't call your variable "list"
def create_to_do_list_file (items ,label):
    with open(f"{label}.dat", "w") as new_file:
        for n in items:
            new_file.write(f"o|{n}\n")

As a general first tip for how to debug things, break your problem into smaller steps and add a print statement at various points to verify that the variables contain what you hope they should, or use a debugger and set a breakpoint to examine the program's state at those spots.


问:
Programatically make a QToolButton identical to one from Qt Designer
I need to make a QToolButton that looks exactly like the default QToolButton you get when you drag one into your form in Qt Designer. Simply creating a QToolButton like this:

```<code>QToolButton *toolButton = new QToolButton(this)
</code>```

does not work. You get a button, but it has no background (although it does display text). I tried creating a QToolButton in a Ui file to copy from, but you can't copy one, it's just not possible.

Any ideas on how to perform something this simple?!

答:
It works for me, but you do have to set the geometry/text on it.

you can look in the file generated by UIC on your ui file with an example QToolButton to see what you are missing.

Make sure that the toolbutton has the correct parent - this could result in drawing strangeness if it is wrong.

e.g:

```<code>QToolButton* tb = new QToolButton(ui.centralWidget);
tb->setGeometry(QRect(10, 40, 25, 19));
tb->setText("...");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to make a QToolButton that looks exactly like the default QToolButton you get when you drag one into your form in Qt Designer. Simply creating a QToolButton like this:

QToolButton *toolButton = new QToolButton(this)

does not work. You get a button, but it has no background (although it does display text). I tried creating a QToolButton in a Ui file to copy from, but you can't copy one, it's just not possible.

Any ideas on how to perform something this simple?!

Body:
It works for me, but you do have to set the geometry/text on it.

you can look in the file generated by UIC on your ui file with an example QToolButton to see what you are missing.

Make sure that the toolbutton has the correct parent - this could result in drawing strangeness if it is wrong.

e.g:

QToolButton* tb = new QToolButton(ui.centralWidget);
tb->setGeometry(QRect(10, 40, 25, 19));
tb->setText("...");


问:
How to count occurrences by day using dplyr
I am trying to use dplyr to do some basic statistics. The two parts of my data that I’m interested in are the dates and the outcomes of an event.

My data has three events that occur, reward, stop, or none (meaning neither a reward or stop occurred). What I want to do is calculate which days have the highest average of rewards by day. I was also hoping to try and obtain the count for overall occurrences, number of stops, rewards, and nones per day.

I have had some success obtaining the unique days and the overall occurrences per day. However, I am struggling to get the remaining data. When I try to adjust the group_by, it ends up causing issues trying to find the unique days.

```<code>df %>%
  mutate(ind, ind2 = case_when(ind=="Reward"~1, ind=="Stop"~0, ind=="None"~0)) %>%
  group_by(time2) %>%
  count(time2, sort = TRUE)
</code>```

Here, I try to create a new column that converts the event to binary formate so I could then try and calculate the average reward per day. This code is not required in an answer, just an example

Desires output:

```<code>Date        num_occ stop    reward  none        avg_reward
2022-01-03  3   1   1   1   0.3333333
2022-01-04  9   5   3   1   0.3333333
2022-01-05  2   1   1   0   0.5
2022-01-06  3   3   0   0   0
</code>```

My question is, how can I calculate the average reward occurrences per day as well as obtain count information regarding the number of overall (reward, stop, none) occurrences per day, number of stops per day, number of rewards per day, and number of nones per day?

Example data:

```<code>structure(list(values = c(0, 18, 3, 2, 1, 9, 15, 13, 0, 12, 8,
2, 3, 7, 6, 3), ind = structure(c(1L, 2L, 3L, 3L, 3L, 3L, 2L,
2L, 1L, 2L, 3L, 3L, 2L, 3L, 3L, 3L), .Label = c("None", "Reward",
"Stop"), class = "factor"), entry = c(TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE), time = structure(c(1641234180, 1641235020, 1641308400,
1641312840, 1641312900, 1641316920, 1641322920, 1641325080, 1641325560,
1641328740, 1641329220, 1641393900, 1641412140, 1641491040, 1641491640,
1641493200), class = c("POSIXct", "POSIXt"), tzone = ""), time2 = structure(c(18995,
18995, 18996, 18996, 18996, 18996, 18996, 18996, 18996, 18996,
18996, 18997, 18997, 18998, 18998, 18998), class = "Date")), row.names = c(NA,
16L), class = "data.frame")
</code>```

Body:
I am trying to use dplyr to do some basic statistics. The two parts of my data that I’m interested in are the dates and the outcomes of an event.

My data has three events that occur, reward, stop, or none (meaning neither a reward or stop occurred). What I want to do is calculate which days have the highest average of rewards by day. I was also hoping to try and obtain the count for overall occurrences, number of stops, rewards, and nones per day.

I have had some success obtaining the unique days and the overall occurrences per day. However, I am struggling to get the remaining data. When I try to adjust the group_by, it ends up causing issues trying to find the unique days.

df %>%
  mutate(ind, ind2 = case_when(ind=="Reward"~1, ind=="Stop"~0, ind=="None"~0)) %>%
  group_by(time2) %>%
  count(time2, sort = TRUE)

Here, I try to create a new column that converts the event to binary formate so I could then try and calculate the average reward per day. This code is not required in an answer, just an example

Desires output:

Date        num_occ stop    reward  none        avg_reward
2022-01-03  3   1   1   1   0.3333333
2022-01-04  9   5   3   1   0.3333333
2022-01-05  2   1   1   0   0.5
2022-01-06  3   3   0   0   0

My question is, how can I calculate the average reward occurrences per day as well as obtain count information regarding the number of overall (reward, stop, none) occurrences per day, number of stops per day, number of rewards per day, and number of nones per day?

Example data:

structure(list(values = c(0, 18, 3, 2, 1, 9, 15, 13, 0, 12, 8,
2, 3, 7, 6, 3), ind = structure(c(1L, 2L, 3L, 3L, 3L, 3L, 2L,
2L, 1L, 2L, 3L, 3L, 2L, 3L, 3L, 3L), .Label = c("None", "Reward",
"Stop"), class = "factor"), entry = c(TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE), time = structure(c(1641234180, 1641235020, 1641308400,
1641312840, 1641312900, 1641316920, 1641322920, 1641325080, 1641325560,
1641328740, 1641329220, 1641393900, 1641412140, 1641491040, 1641491640,
1641493200), class = c("POSIXct", "POSIXt"), tzone = ""), time2 = structure(c(18995,
18995, 18996, 18996, 18996, 18996, 18996, 18996, 18996, 18996,
18996, 18997, 18997, 18998, 18998, 18998), class = "Date")), row.names = c(NA,
16L), class = "data.frame")

Body:
Something like this may work for you

library(tidyverse)

example_data <- structure(list(values = c(0, 18, 3, 2, 1, 9, 15, 13, 0, 12, 8,
                          2, 3, 7, 6, 3), ind = structure(c(1L, 2L, 3L, 3L, 3L, 3L, 2L,
                                                            2L, 1L, 2L, 3L, 3L, 2L, 3L, 3L, 3L), .Label = c("None", "Reward",
                                                                                "Stop"), class = "factor"), entry = c(TRUE, TRUE, TRUE, TRUE,
                                                                                TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
                                                                                TRUE), time = structure(c(1641234180, 1641235020, 1641308400,
                                                                                1641312840, 1641312900, 1641316920, 1641322920, 1641325080, 1641325560,
                                                                                1641328740, 1641329220, 1641393900, 1641412140, 1641491040, 1641491640,
                                                                                1641493200), class = c("POSIXct", "POSIXt"), tzone = ""), time2 = structure(c(18995,
                                                                                18995, 18996, 18996, 18996, 18996, 18996, 18996, 18996, 18996,
                                                                                18996, 18997, 18997, 18998, 18998, 18998), class = "Date")), row.names = c(NA,
                                                                                16L), class = "data.frame")
example_data |>
  group_by(day = time |> lubridate::as_date()) |>
  summarise(num_occ = n(),
            stop = length(ind[ind == 'Stop']),
            Reward = length(ind[ind == 'Reward']),
            None = length(ind[ind == 'None']),
            sum_reward = sum(values[ind[ind == 'Reward']])
            )
#> # A tibble: 4 x 6
#>   day        num_occ  stop Reward  None sum_reward
#>   <date>       <int> <int>  <int> <int>      <dbl>
#> 1 2022-01-03       2     0      1     1         18
#> 2 2022-01-04       9     5      3     1          6
#> 3 2022-01-05       2     1      1     0          3
#> 4 2022-01-06       3     3      0     0          0

Created on 2022-02-10 by the reprex package (v2.0.1)


问:
Loop R merge multiple data frames together
I am trying to merge multiple dataset (left_join) together inside a loop.

Here is what the data looks like:

```<code>Fr1 <- data.frame (v1  = c("a", "b", "c"),
                  period1 = c("Yes", "Yes", "Yes")
)

Fr2 <- data.frame (v1  = c("b", "d"),
                   period2 = c("Yes", "Yes")
)

Fr3 <- data.frame (v1  = c("c"),
                   period3 = c("Yes")
)

Be1 <- data.frame (v1  = c("a", "b", "c"),
                   period1 = c("Yes", "Yes", "Yes")
)

Be2 <- data.frame (v1  = c("b", "c"),
                   period2 = c("Yes", "Yes")
)

Be3 <- data.frame (v1  = c("d"),
                   period3 = c("Yes")
)

table_Fr <- data.frame (v1 = c("a", "b", "c", "d"))

table_Be <- data.frame (v1 = c("a", "b", "c", "d"))
</code>```

The idea is simple: Fr1, Fr2, and Fr3 go with table_Fr and Be1, Be2 and Be3 go with table_Be.

A simple way to do it dataframe by dataframe goes like this:

```<code>table_Fr <- left_join(table_Fr, Fr1, by="v1")
table_Fr <- left_join(table_Fr, Fr2, by="v1")
table_Fr <- left_join(table_Fr, Fr3, by="v1")
table_Fr <- table_Fr %>%
  mutate(period1 = ifelse(is.na(period1), "No", period1)) %>%
  mutate(period2 = ifelse(is.na(period2), "No", period2)) %>%
  mutate(period3 = ifelse(is.na(period3), "No", period3))
</code>```

However, I have a large number of data frames to merge together, hence I want to use a loop (I know loop are not best in R but I have to do it through a loop...). Unfortunately, I can't get it to work, does anyone can help?

```<code>countries <- c("Fr", "Be")

for(c in countries) {
  for(i in 1:6) {
p <- paste0("period", i)
cp <- paste0(c, i)
t <- paste0("table_", c)
a <- left_join(t, cp, by="v1") %>%
  mutate(!!p := ifelse(is.na(!!p), "No", !!p))
  assign(paste0("table_",c), a)
}
}
</code>```

答:
You can use base R Reduce or purrr::reduce.

base R

ll <- mget(ls(pattern = "Fr"))
table_Fr <- Reduce(function(x, y) merge(x, y, all=TRUE), ll)
table_Fr[is.na(table_Fr)] <- "No"

#   v1 period1 period2 period3
# 1  a     Yes      No      No
# 2  b     Yes     Yes      No
# 3  c     Yes      No     Yes
# 4  d      No     Yes      No
```
<h4>tidyverse</h4>
<pre class="lang-r prettyprint-override"><code>library(tidyverse)
reduce(ll, full_join, by = 'v1') %>%
  mutate(across(everything(), ~ replace_na(., 'No')))

#   v1 period1 period2 period3
# 1  a     Yes      No      No
# 2  b     Yes     Yes      No
# 3  c     Yes      No     Yes
# 4  d      No     Yes      No
</code>```

Body:
I am trying to merge multiple dataset (left_join) together inside a loop.

Here is what the data looks like:

Fr1 <- data.frame (v1  = c("a", "b", "c"),
                  period1 = c("Yes", "Yes", "Yes")
)

Fr2 <- data.frame (v1  = c("b", "d"),
                   period2 = c("Yes", "Yes")
)

Fr3 <- data.frame (v1  = c("c"),
                   period3 = c("Yes")
)

Be1 <- data.frame (v1  = c("a", "b", "c"),
                   period1 = c("Yes", "Yes", "Yes")
)

Be2 <- data.frame (v1  = c("b", "c"),
                   period2 = c("Yes", "Yes")
)

Be3 <- data.frame (v1  = c("d"),
                   period3 = c("Yes")
)

table_Fr <- data.frame (v1 = c("a", "b", "c", "d"))

table_Be <- data.frame (v1 = c("a", "b", "c", "d"))

The idea is simple: Fr1, Fr2, and Fr3 go with table_Fr and Be1, Be2 and Be3 go with table_Be.

A simple way to do it dataframe by dataframe goes like this:

table_Fr <- left_join(table_Fr, Fr1, by="v1")
table_Fr <- left_join(table_Fr, Fr2, by="v1")
table_Fr <- left_join(table_Fr, Fr3, by="v1")
table_Fr <- table_Fr %>%
  mutate(period1 = ifelse(is.na(period1), "No", period1)) %>%
  mutate(period2 = ifelse(is.na(period2), "No", period2)) %>%
  mutate(period3 = ifelse(is.na(period3), "No", period3))

However, I have a large number of data frames to merge together, hence I want to use a loop (I know loop are not best in R but I have to do it through a loop...). Unfortunately, I can't get it to work, does anyone can help?

countries <- c("Fr", "Be")

for(c in countries) {
  for(i in 1:6) {
p <- paste0("period", i)
cp <- paste0(c, i)
t <- paste0("table_", c)
a <- left_join(t, cp, by="v1") %>%
  mutate(!!p := ifelse(is.na(!!p), "No", !!p))
  assign(paste0("table_",c), a)
}
}

Body:
You can use base R Reduce or purrr::reduce.

base R

ll <- mget(ls(pattern = "Fr"))
table_Fr <- Reduce(function(x, y) merge(x, y, all=TRUE), ll)
table_Fr[is.na(table_Fr)] <- "No"

#   v1 period1 period2 period3
# 1  a     Yes      No      No
# 2  b     Yes     Yes      No
# 3  c     Yes      No     Yes
# 4  d      No     Yes      No

tidyverse

library(tidyverse)
reduce(ll, full_join, by = 'v1') %>%
  mutate(across(everything(), ~ replace_na(., 'No')))

#   v1 period1 period2 period3
# 1  a     Yes      No      No
# 2  b     Yes     Yes      No
# 3  c     Yes      No     Yes
# 4  d      No     Yes      No


问:
Process certain properties in array of objects
I am trying to process some properties from an array of objects.

The order is always the same, in that after the second property always comes a range of dates for the next 12 entries, everything after that is to be excluded and sometimes can be two like in this instance or it could be more.

So what I want to do is exclude everything but the keyword and the range of dates.

const data = [{
  "keyword": "foo",
  // This key never changes
  "search_vol": 0,
  // These keys can change when they start, i.e. starts jan-21
  "jul-20": 10,
  "aug-20": 10,
  "sep-20": 10,
  "oct-20": 10,
  "nov-20": 10,
  "dec-20": 10,
  "jan-21": 10,
  "feb-21": 10,
  "mar-21": 10,
  "apr-21": 20,
  "may-21": 10,
  "jun-21": 10,
  // These would change to different properties in name and amount
  "drain": "FALSE",
  "toilet": "TRUE"
}, {
  "keyword": "faa",

  "search_vol": 100,

  "jul-20": 880,
  "aug-20": 880,
  "sep-20": 880,
  "oct-20": 880,
  "nov-20": 880,
  "dec-20": 880,
  "jan-21": 1000,
  "feb-21": 880,
  "mar-21": 1000,
  "apr-21": 720,
  "may-21": 880,
  "jun-21": 880,

  "drain": "TRUE",
  "toilet": "TRUE"
}]
```
<p>I want to do this so later I can get the max value for the dates on each object and have an entry with the months that hit that max</p>
<p>Expected final output:</p>
<pre class="lang-js prettyprint-override"><code>const data = [{
  "keyword": "foo",
  "search_vol": 0,
  "jul-20": 10,
  "aug-20": 10,
  "sep-20": 10,
  "oct-20": 10,
  "nov-20": 10,
  "dec-20": 10,
  "jan-21": 10,
  "feb-21": 10,
  "mar-21": 10,
  "apr-21": 20,
  "may-21": 10,
  "jun-21": 10,
  "Max months": ['apr-21'],
  "drain": "FALSE",
  "toilet": "TRUE"
}, {
  "keyword": "faa",
  "search_vol": 100,
  "jul-20": 880,
  "aug-20": 880,
  "sep-20": 880,
  "oct-20": 880,
  "nov-20": 880,
  "dec-20": 880,
  "jan-21": 1000,
  "feb-21": 880,
  "mar-21": 1000,
  "apr-21": 720,
  "may-21": 880,
  "jun-21": 880,
  "Max months": ['jan-21','mar-21'],
  "drain": "TRUE",
  "toilet": "TRUE"
}]
</code>```

Is it worth separating the processes, first set aside the dates and then get the max, or is it best to do it all in one go?

This is my attempt, excluding the mergin back with the data, but I think is over complicated

const data = [{
  "keyword": "foo",
  "search_vol": 0,

  "jul-20": 10,
  "aug-20": 10,
  "sep-20": 10,
  "oct-20": 10,
  "nov-20": 10,
  "dec-20": 10,
  "jan-21": 10,
  "feb-21": 10,
  "mar-21": 10,
  "apr-21": 20,
  "may-21": 10,
  "jun-21": 10,

  "drain": "FALSE",
  "toilet": "TRUE"
}, {
  "keyword": "faa",
  "search_vol": 100,

  "jul-20": 880,
  "aug-20": 880,
  "sep-20": 880,
  "oct-20": 880,
  "nov-20": 880,
  "dec-20": 880,
  "jan-21": 1000,
  "feb-21": 880,
  "mar-21": 1000,
  "apr-21": 720,
  "may-21": 880,
  "jun-21": 880,

  "drain": "TRUE",
  "toilet": "TRUE"
}]

const headers = Object.keys(data[0]).filter((_, index) => index === 0 || ( index >=  1 && index <= 13))

const dates = data.reduce((acc, obj) => {
  const filtered = headers.reduce((entries, key) => ({ ...entries, [key]: obj[key] }), {})
  acc.push(filtered)
  return acc
}, [])

const months = dates.map(({ keyword, ...dates }) => {
  const max = Math.max(...Object.values(dates))

  const maxMonths = Object.entries(dates).reduce((acc, [key, value]) => {
    if (value === max) acc.push(key)
    return acc
  }, [])

  return {
    keyword,
    'Max months': maxMonths,
  }
})

console.log(months)```

答:
@abranhe's answer is good, but I'd still be wary of relying on the order of the keys. The keys are sorted when you do Object.keys.

You could replace this:

  const filteredArr = Object.entries(_obj)
    .filter(entry => !['keyword', 'search_vol'].includes(entry[0]))
    .slice(0, 12);
```
<p>with this:</p>
<pre class="lang-js prettyprint-override"><code>  const filteredArr = Object.entries(_obj)
    .filter(entry => entry[0].match(/[a-z]{3}-[0-9]{2}/) !== null)
</code>```

This will be more robust as the code changes over time :)

Body:
I am trying to process some properties from an array of objects.

The order is always the same, in that after the second property always comes a range of dates for the next 12 entries, everything after that is to be excluded and sometimes can be two like in this instance or it could be more.

So what I want to do is exclude everything but the keyword and the range of dates.

const data = [{
  "keyword": "foo",
  // This key never changes
  "search_vol": 0,
  // These keys can change when they start, i.e. starts jan-21
  "jul-20": 10,
  "aug-20": 10,
  "sep-20": 10,
  "oct-20": 10,
  "nov-20": 10,
  "dec-20": 10,
  "jan-21": 10,
  "feb-21": 10,
  "mar-21": 10,
  "apr-21": 20,
  "may-21": 10,
  "jun-21": 10,
  // These would change to different properties in name and amount
  "drain": "FALSE",
  "toilet": "TRUE"
}, {
  "keyword": "faa",

  "search_vol": 100,

  "jul-20": 880,
  "aug-20": 880,
  "sep-20": 880,
  "oct-20": 880,
  "nov-20": 880,
  "dec-20": 880,
  "jan-21": 1000,
  "feb-21": 880,
  "mar-21": 1000,
  "apr-21": 720,
  "may-21": 880,
  "jun-21": 880,

  "drain": "TRUE",
  "toilet": "TRUE"
}]

I want to do this so later I can get the max value for the dates on each object and have an entry with the months that hit that max

Expected final output:

const data = [{
  "keyword": "foo",
  "search_vol": 0,
  "jul-20": 10,
  "aug-20": 10,
  "sep-20": 10,
  "oct-20": 10,
  "nov-20": 10,
  "dec-20": 10,
  "jan-21": 10,
  "feb-21": 10,
  "mar-21": 10,
  "apr-21": 20,
  "may-21": 10,
  "jun-21": 10,
  "Max months": ['apr-21'],
  "drain": "FALSE",
  "toilet": "TRUE"
}, {
  "keyword": "faa",
  "search_vol": 100,
  "jul-20": 880,
  "aug-20": 880,
  "sep-20": 880,
  "oct-20": 880,
  "nov-20": 880,
  "dec-20": 880,
  "jan-21": 1000,
  "feb-21": 880,
  "mar-21": 1000,
  "apr-21": 720,
  "may-21": 880,
  "jun-21": 880,
  "Max months": ['jan-21','mar-21'],
  "drain": "TRUE",
  "toilet": "TRUE"
}]

Is it worth separating the processes, first set aside the dates and then get the max, or is it best to do it all in one go?

This is my attempt, excluding the mergin back with the data, but I think is over complicated

const data = [{
  "keyword": "foo",
  "search_vol": 0,

  "jul-20": 10,
  "aug-20": 10,
  "sep-20": 10,
  "oct-20": 10,
  "nov-20": 10,
  "dec-20": 10,
  "jan-21": 10,
  "feb-21": 10,
  "mar-21": 10,
  "apr-21": 20,
  "may-21": 10,
  "jun-21": 10,

  "drain": "FALSE",
  "toilet": "TRUE"
}, {
  "keyword": "faa",
  "search_vol": 100,

  "jul-20": 880,
  "aug-20": 880,
  "sep-20": 880,
  "oct-20": 880,
  "nov-20": 880,
  "dec-20": 880,
  "jan-21": 1000,
  "feb-21": 880,
  "mar-21": 1000,
  "apr-21": 720,
  "may-21": 880,
  "jun-21": 880,

  "drain": "TRUE",
  "toilet": "TRUE"
}]

const headers = Object.keys(data[0]).filter((_, index) => index === 0 || ( index >=  1 && index <= 13))

const dates = data.reduce((acc, obj) => {
  const filtered = headers.reduce((entries, key) => ({ ...entries, [key]: obj[key] }), {})
  acc.push(filtered)
  return acc
}, [])

const months = dates.map(({ keyword, ...dates }) => {
  const max = Math.max(...Object.values(dates))

  const maxMonths = Object.entries(dates).reduce((acc, [key, value]) => {
    if (value === max) acc.push(key)
    return acc
  }, [])

  return {
    keyword,
    'Max months': maxMonths,
  }
})

console.log(months)

Body:
@abranhe's answer is good, but I'd still be wary of relying on the order of the keys. The keys are sorted when you do Object.keys.

You could replace this:

  const filteredArr = Object.entries(_obj)
    .filter(entry => !['keyword', 'search_vol'].includes(entry[0]))
    .slice(0, 12);

with this:

  const filteredArr = Object.entries(_obj)
    .filter(entry => entry[0].match(/[a-z]{3}-[0-9]{2}/) !== null)

This will be more robust as the code changes over time :)


问:
Why does my app throw an `android.permission.REBOOT SecurityException`?
I wrote an Android app that uses android.os.PowerManager.reboot(), and I added <uses-permission android:name="android.permission.REBOOT" /> in my AndroidManifest.xml. However, when I run the app, it always throws the following exception:

```<code>java.lang.SecurityException: Neither user 10039 nor current process has android.permission.REBOOT. at android.os.Parcel.readException(Parcel.java:1247)
at android.os.Parcel.readException(Parcel.java:1247)
at android.os.Parcel.readException(Parcel.java:1235)
at android.os.IPowerManager$Stub$Proxy.reboot(IPowerManager.java:427)
at android.os.PowerManager.reboot(PowerManager.java:481)
at Test.testPower(Test.java:374)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:204)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:194)
at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:186)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:520)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)
at android.os.Parcel.readException(Parcel.java:1247)
at android.os.Parcel.readException(Parcel.java:1235)
at android.os.IPowerManager$Stub$Proxy.reboot(IPowerManager.java:427)
at android.os.PowerManager.reboot(PowerManager.java:481)
at com.fsl.cts.FSLPlaybackTest.testPower(FSLPlaybackTest.java:374)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:204)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:194)
at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:186)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:520)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)
</code>```

Is the anything I'm doing wrong, or does froyo have some problem with rebooting?

答:
To reboot the device using code needs REBOOT permission.

This permission is available for system applications. You can make your application a system application only if you have the certificate used in building the system image.

Please check the link below on applications being signed with the platform certificate https://groups.google.com/d/msg/android-developers/wsRr-VhzKZ4/dAUbLPszOQ8J

http://developer.android.com/guide/topics/security/security.html

ContentLicense: CC BY-SA 2.5

Body:
I wrote an Android app that uses android.os.PowerManager.reboot(), and I added <uses-permission android:name="android.permission.REBOOT" /> in my AndroidManifest.xml. However, when I run the app, it always throws the following exception:

java.lang.SecurityException: Neither user 10039 nor current process has android.permission.REBOOT. at android.os.Parcel.readException(Parcel.java:1247)
at android.os.Parcel.readException(Parcel.java:1247)
at android.os.Parcel.readException(Parcel.java:1235)
at android.os.IPowerManager$Stub$Proxy.reboot(IPowerManager.java:427)
at android.os.PowerManager.reboot(PowerManager.java:481)
at Test.testPower(Test.java:374)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:204)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:194)
at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:186)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:520)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)
at android.os.Parcel.readException(Parcel.java:1247)
at android.os.Parcel.readException(Parcel.java:1235)
at android.os.IPowerManager$Stub$Proxy.reboot(IPowerManager.java:427)
at android.os.PowerManager.reboot(PowerManager.java:481)
at com.fsl.cts.FSLPlaybackTest.testPower(FSLPlaybackTest.java:374)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:204)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:194)
at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:186)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:520)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)

Is the anything I'm doing wrong, or does froyo have some problem with rebooting?


问:
Optimize PDF files (with Ghostscript or other)
Is Ghostscript the best option if you want to optimize a PDF file and reduce the file size?

I need to store alot of PDF files and therefore I need to optimize and reduce the file size as much as possible

Does anyone have any experience with Ghostscript and/or other?

command line

```<code>exec('gs -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dCompatibilityLevel=1.4
-dPDFSETTINGS=/screen -sOutputFile='.$file_new.' '.$file);
</code>```

答: For the PDF which size is mainly due to embedded images (pdfimages -list is your friend), typically scanned documents, I would recommend the use of ocrmypdf which is quite good at optimizing, with optional OCR layer as a bonus.

Body:
Is Ghostscript the best option if you want to optimize a PDF file and reduce the file size?

I need to store alot of PDF files and therefore I need to optimize and reduce the file size as much as possible

Does anyone have any experience with Ghostscript and/or other?

command line

exec('gs -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dCompatibilityLevel=1.4
-dPDFSETTINGS=/screen -sOutputFile='.$file_new.' '.$file);


问:
How to remove deferred azure service bus messages?
I'm using deferred messages and manage to retrieve them and process them the way I want.
Now I need a way to delete them (normal messages can be "Completed") so they don't stay forever but I can't find out how.

Here's how I retrieve the message:

```<code>var message = await ServiceBusReceiver.ReceiveDeferredMessageAsync(
    deferredMessage.SequenceNumber,
    cancellationToken
);
</code>```

And this is what I tried first to delete them

```<code>await ServiceBusReceiver.CompleteMessageAsync(message, cancellationToken);
</code>```

Which failed with an error claiming the lock was not valid so I tried

```<code>await ServiceBusReceiver.RenewMessageLockAsync(message, cancellationToken);
await ServiceBusReceiver.CompleteMessageAsync(message, cancellationToken);
</code>```

But the error persist.

EDIT:

I created a demo:

```<code>using Azure.Identity;
using Azure.Messaging.ServiceBus;

const string ToDefer = nameof(ToDefer);
const string UnDefer = nameof(UnDefer);

const string TopicName = "demo-deferred-sj";
const string ServiceBusNamespace = "#######";
const string SubscriptionName = "all";

var oneSecondMoreThanLockDuration = TimeSpan.FromSeconds(6);

var userName = System.Environment.GetEnvironmentVariable("USERNAME");

var serviceBusClient = new ServiceBusClient(
    $"{ServiceBusNamespace}.servicebus.windows.net",
    new VisualStudioCredential()
);

var sender = serviceBusClient.CreateSender(TopicName);
var processor = serviceBusClient.CreateProcessor(TopicName, SubscriptionName, new ServiceBusProcessorOptions
{
    AutoCompleteMessages = false
});
var receiver = serviceBusClient.CreateReceiver(TopicName, SubscriptionName);

async Task SendMessagesAsync(string kind, string param = "", DateTimeOffset? scheduleTime = null)
{
    var messageId = $"{kind}|{userName}|{param}|{Guid.NewGuid()}";
    Console.WriteLine($"Sending {messageId}"
        + (scheduleTime.HasValue ? $" scheduled for {scheduleTime}" : "")
    );
    var serviceBusMessage = new ServiceBusMessage()
    {
        MessageId = messageId
    };
    if (scheduleTime.HasValue)
    {
        serviceBusMessage.ScheduledEnqueueTime = scheduleTime.Value;
    }
    await sender.SendMessageAsync(serviceBusMessage);
}

async Task ProcessMessageAsync(ProcessMessageEventArgs args)
{
    Console.WriteLine($"Handling {args.Message.MessageId} ");

    var messageParts = args.Message.MessageId.Split('|');
    var kind = messageParts[0];
    var user = messageParts[1];
    var param = messageParts[2];

    if (user != userName)
    {
        Console.WriteLine($"Caution handling message of another user: {user}");
    }

    switch (kind)
    {
        case ToDefer:
            await args.DeferMessageAsync(args.Message);
            var scheduleTime = args.Message.EnqueuedTime + oneSecondMoreThanLockDuration;
            await SendMessagesAsync(UnDefer, args.Message.SequenceNumber.ToString(), scheduleTime);
            break;
        case UnDefer:
            var deferredMessage = await receiver.ReceiveDeferredMessageAsync(long.Parse(param));
            Console.WriteLine($"Deferd message {deferredMessage.MessageId} processed");
            await args.CompleteMessageAsync(args.Message);
            try
            {
                // THIS WOULD DELETE THE MESSAGE IF THE LOCK WAS STILL ON
                await receiver.CompleteMessageAsync(deferredMessage);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Ignoring {ex.Message}");
            }

            break;
    }
}

processor.ProcessMessageAsync += ProcessMessageAsync;
processor.ProcessErrorAsync += eventArgs =>
{
    Console.WriteLine(eventArgs.Exception.Message);

    return Task.CompletedTask;
};

var cancellationTokenSource = new CancellationTokenSource();
await processor.StartProcessingAsync(cancellationTokenSource.Token);

await SendMessagesAsync(ToDefer);

Console.ReadKey();
cancellationTokenSource.Cancel();
</code>```

答:
According to this SO discussion, Deferred messages can also be returned by peeking messages from a queue or subscription. You may acquire the sequence numbers of the deferred messages this way, and then process or delete them.

Please refer the above given link for more information.

Body:
I'm using deferred messages and manage to retrieve them and process them the way I want.
Now I need a way to delete them (normal messages can be "Completed") so they don't stay forever but I can't find out how.

Here's how I retrieve the message:

var message = await ServiceBusReceiver.ReceiveDeferredMessageAsync(
    deferredMessage.SequenceNumber,
    cancellationToken
);

And this is what I tried first to delete them

await ServiceBusReceiver.CompleteMessageAsync(message, cancellationToken);

Which failed with an error claiming the lock was not valid so I tried

await ServiceBusReceiver.RenewMessageLockAsync(message, cancellationToken);
await ServiceBusReceiver.CompleteMessageAsync(message, cancellationToken);

But the error persist.

EDIT:

I created a demo:

using Azure.Identity;
using Azure.Messaging.ServiceBus;

const string ToDefer = nameof(ToDefer);
const string UnDefer = nameof(UnDefer);

const string TopicName = "demo-deferred-sj";
const string ServiceBusNamespace = "#######";
const string SubscriptionName = "all";

var oneSecondMoreThanLockDuration = TimeSpan.FromSeconds(6);

var userName = System.Environment.GetEnvironmentVariable("USERNAME");

var serviceBusClient = new ServiceBusClient(
    $"{ServiceBusNamespace}.servicebus.windows.net",
    new VisualStudioCredential()
);

var sender = serviceBusClient.CreateSender(TopicName);
var processor = serviceBusClient.CreateProcessor(TopicName, SubscriptionName, new ServiceBusProcessorOptions
{
    AutoCompleteMessages = false
});
var receiver = serviceBusClient.CreateReceiver(TopicName, SubscriptionName);

async Task SendMessagesAsync(string kind, string param = "", DateTimeOffset? scheduleTime = null)
{
    var messageId = $"{kind}|{userName}|{param}|{Guid.NewGuid()}";
    Console.WriteLine($"Sending {messageId}"
        + (scheduleTime.HasValue ? $" scheduled for {scheduleTime}" : "")
    );
    var serviceBusMessage = new ServiceBusMessage()
    {
        MessageId = messageId
    };
    if (scheduleTime.HasValue)
    {
        serviceBusMessage.ScheduledEnqueueTime = scheduleTime.Value;
    }
    await sender.SendMessageAsync(serviceBusMessage);
}

async Task ProcessMessageAsync(ProcessMessageEventArgs args)
{
    Console.WriteLine($"Handling {args.Message.MessageId} ");

    var messageParts = args.Message.MessageId.Split('|');
    var kind = messageParts[0];
    var user = messageParts[1];
    var param = messageParts[2];

    if (user != userName)
    {
        Console.WriteLine($"Caution handling message of another user: {user}");
    }

    switch (kind)
    {
        case ToDefer:
            await args.DeferMessageAsync(args.Message);
            var scheduleTime = args.Message.EnqueuedTime + oneSecondMoreThanLockDuration;
            await SendMessagesAsync(UnDefer, args.Message.SequenceNumber.ToString(), scheduleTime);
            break;
        case UnDefer:
            var deferredMessage = await receiver.ReceiveDeferredMessageAsync(long.Parse(param));
            Console.WriteLine($"Deferd message {deferredMessage.MessageId} processed");
            await args.CompleteMessageAsync(args.Message);
            try
            {
                // THIS WOULD DELETE THE MESSAGE IF THE LOCK WAS STILL ON
                await receiver.CompleteMessageAsync(deferredMessage);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Ignoring {ex.Message}");
            }

            break;
    }
}

processor.ProcessMessageAsync += ProcessMessageAsync;
processor.ProcessErrorAsync += eventArgs =>
{
    Console.WriteLine(eventArgs.Exception.Message);

    return Task.CompletedTask;
};

var cancellationTokenSource = new CancellationTokenSource();
await processor.StartProcessingAsync(cancellationTokenSource.Token);

await SendMessagesAsync(ToDefer);

Console.ReadKey();
cancellationTokenSource.Cancel();


问:
What am I doing wrong (Navigator)?
I'm trying to create a navigator with two screens. One of them has another navigator. I got this error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named inports. Check the render methon of 'Navigation'.

My code:

```<code>import * as React from 'react';
import { NavigationContainer, StackActions } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons';

// Screens
import Primary from './Screens/Primary';
import Secondary from './Screens/Secondary';
import Map_map from './Screens/Map_map';
import { createStackNavigator } from '@react-navigation/stack';

// Locations
const mesta = [
  {
    name: 'Praha',
    coordinates: {
      latitude: 50.072829,
      longitude: 14.433817
  }},
  ,
  {
    name: 'České Budějovice',
    coordinates: {
      latitude: 48.975250,
      longitude: 14.479161
}},
]

//Screen names
export const screenNames = {
  mapa: "Mapa", //home
  lokace: "Lokace",  //details
  mapaDet: "Map_map",  //innerDetails
  mapaStack: "MapaStackScreen", //homeStack
  lokaceStack: "LokaceStackScreen",  //detailsStack
};

const MapaStack = createStackNavigator();

function MapaStackScreen() {
  return (
      <MapaStack.Navigator
        initialRouteName={screenNames.mapa}
        >
        <MapaStack.Screen name={screenNames.mapa} children={() => <Secondary towns={mesta}/>}/>
      </MapaStack.Navigator>
  );
}

const LokaceStack = createStackNavigator();

function LokaceStackScreen({ navigation, route }){
  const tabHiddenRoutes = ["Map_map"];
  useEffect(() => {
    if (tabHiddenRoutes.includes(getFocusedRouteNameFromRoute(route))) {
      navigation.setOptions({ tabBarVisible: false });
    } else {
      navigation.setOptions({ tabBarVisible: true });
    }

  }, [navigation, route]);
  return(
      <LokaceStack.Navigator initialRouteName={screenNames.lokace}>
        <LokaceStack.Screen name={screenNames.lokace} children={() => <Primary towns={mesta}/>}/>
        <LokaceStack.Screen name={screenNames.mapaDet} component={Map_map}/>
      </LokaceStack.Navigator>
  )
}

const Tab = createBottomTabNavigator

export default function Navigation()
{
  return(
    <Tab.Navigator
    initialRouteName={screenNames.mapaStack}
    tabBarOptions={{
      activeTintColor: '#007aff',
      inactiveTintColor: 'grey',
      labelStyle: { paddingBottom: 10, fontSize: 10 },
      style: { padding: 10, height: 70}
    }}
    >
      <Tab.Screen
        name={screenNames.mapaStack}
        component={MapaStackScreen}
        options={{
          tabBarLabel: "",
          tabBarIcon: ({ color, focused }) => (
            <Icon
              name={focused ? 'map' : 'map-outline'}
              size="24"
              color={color}
            />
          ),
        }}
      />
      <Tab.Screen
        name={screenNames.LokaceStackScreen}
        component={LokaceStackScreen}
        options={{
          tabBarLabel: "",
          tabBarIcon: ({ color, focused }) => (
            <Icon
              name={focused ? 'home' : 'home-outline'}
              size="24"
              color={color}
            />
          ),
        }}
      />
    </Tab.Navigator>
  )
}
</code>```

答:
I've found my answer:

```<code>const Tab = createBottomTabNavigator
</code>```

should have been:

```<code>const Tab = createBottomTabNavigator();
</code>```

Title: What am I doing wrong (Navigator)?

Body:
I'm trying to create a navigator with two screens. One of them has another navigator. I got this error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named inports. Check the render methon of 'Navigation'.

My code:

import * as React from 'react';
import { NavigationContainer, StackActions } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons';

// Screens
import Primary from './Screens/Primary';
import Secondary from './Screens/Secondary';
import Map_map from './Screens/Map_map';
import { createStackNavigator } from '@react-navigation/stack';

// Locations
const mesta = [
  {
    name: 'Praha',
    coordinates: {
      latitude: 50.072829,
      longitude: 14.433817
  }},
  ,
  {
    name: 'České Budějovice',
    coordinates: {
      latitude: 48.975250,
      longitude: 14.479161
}},
]

//Screen names
export const screenNames = {
  mapa: "Mapa", //home
  lokace: "Lokace",  //details
  mapaDet: "Map_map",  //innerDetails
  mapaStack: "MapaStackScreen", //homeStack
  lokaceStack: "LokaceStackScreen",  //detailsStack
};

const MapaStack = createStackNavigator();

function MapaStackScreen() {
  return (
      <MapaStack.Navigator
        initialRouteName={screenNames.mapa}
        >
        <MapaStack.Screen name={screenNames.mapa} children={() => <Secondary towns={mesta}/>}/>
      </MapaStack.Navigator>
  );
}

const LokaceStack = createStackNavigator();

function LokaceStackScreen({ navigation, route }){
  const tabHiddenRoutes = ["Map_map"];
  useEffect(() => {
    if (tabHiddenRoutes.includes(getFocusedRouteNameFromRoute(route))) {
      navigation.setOptions({ tabBarVisible: false });
    } else {
      navigation.setOptions({ tabBarVisible: true });
    }

  }, [navigation, route]);
  return(
      <LokaceStack.Navigator initialRouteName={screenNames.lokace}>
        <LokaceStack.Screen name={screenNames.lokace} children={() => <Primary towns={mesta}/>}/>
        <LokaceStack.Screen name={screenNames.mapaDet} component={Map_map}/>
      </LokaceStack.Navigator>
  )
}

const Tab = createBottomTabNavigator

export default function Navigation()
{
  return(
    <Tab.Navigator
    initialRouteName={screenNames.mapaStack}
    tabBarOptions={{
      activeTintColor: '#007aff',
      inactiveTintColor: 'grey',
      labelStyle: { paddingBottom: 10, fontSize: 10 },
      style: { padding: 10, height: 70}
    }}
    >
      <Tab.Screen
        name={screenNames.mapaStack}
        component={MapaStackScreen}
        options={{
          tabBarLabel: "",
          tabBarIcon: ({ color, focused }) => (
            <Icon
              name={focused ? 'map' : 'map-outline'}
              size="24"
              color={color}
            />
          ),
        }}
      />
      <Tab.Screen
        name={screenNames.LokaceStackScreen}
        component={LokaceStackScreen}
        options={{
          tabBarLabel: "",
          tabBarIcon: ({ color, focused }) => (
            <Icon
              name={focused ? 'home' : 'home-outline'}
              size="24"
              color={color}
            />
          ),
        }}
      />
    </Tab.Navigator>
  )
}

Body:
I've found my answer:

const Tab = createBottomTabNavigator

should have been:

const Tab = createBottomTabNavigator();


问:
v-model on Component returning type string instead of type null
Link to Example

I'm trying to create a Vue 3 component that can handle a v-model binding. The component contains a simple <select>.

The 1st <option> contains a null value with the inner text 'Default placeholder'. The others <option> contain actual values.

If I try to select the option with the null value, rather than returning null it returns the inner text 'Default placeholder'.

I need it to return null.

I can get the null value (see the changeValue() method) but it feels hacky using event.target.selectedOptions[0]._value.

If I try to build the same functionality without using a custom component using v-model then it works as expected.

Child Component

```<code><script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
    emits: ['update:modelValue'],
    methods: {
        changeValue(event) {
            // Output the event for testing purposes
            console.dir(event);
            console.log(event.target.value);
            console.dir(event.target.selectedOptions[0]);
            console.log(event.target.selectedOptions[0].text);
            // This is the correct value but im unsure if I can use it.
            console.log(event.target.selectedOptions[0]._value);
            console.log(typeof event.target.value);

            // Emit the handler
            this.$emit('update:modelValue', event.target.value);
        }
    },
    name: 'HtmlSelect',
    props: ['modelValue'],
})
</script>
<template>
    <select :value='modelValue' @input="changeValue">
        <option :value="null">Should be null. Get inner text.</option>
        <option :value="1">Number: 1</option>
        <option value="1">String: 1</option>
        <option :value="'Some Text'">String: Some Text</option>
    </select>
</template>
</code>```

The parent instance is not doing anything special.

Parent Component

```<code><html-select v-model="someVal"></html-select>
</code>```

** Edit ** I've simplified the example component to better illustrate the error. Added a link to a working example.

答: It's related to how <option> gives you a value. null is an absence of a value. If the value of the option is nullish, then text between opening and closing tags returned. Try use "0" instead of null and check for "0", not null, and then replace "0" with null if you really need null

Body:
<a href="https://sfc.vuejs.org/#[encoded data, 4104 characters]" rel="nofollow noreferrer">Link to Example

I'm trying to create a Vue 3 component that can handle a v-model binding. The component contains a simple <select>.

The 1st <option> contains a null value with the inner text 'Default placeholder'. The others <option> contain actual values.

If I try to select the option with the null value, rather than returning null it returns the inner text 'Default placeholder'.

I need it to return null.

I can get the null value (see the changeValue() method) but it feels hacky using event.target.selectedOptions[0]._value.

If I try to build the same functionality without using a custom component using v-model then it works as expected.

Child Component

<template>
    <select :value='modelValue' @input="changeValue">
        <option :value="null">Should be null. Get inner text.</option>
        <option :value="1">Number: 1</option>
        <option value="1">String: 1</option>
        <option :value="'Some Text'">String: Some Text</option>
    </select>
</template>

The parent instance is not doing anything special.

Parent Component

** Edit ** I've simplified the example component to better illustrate the error. Added a link to a working example.


答:
np.split could be applied too but you are required to do it one-dimensionally. So you might like to create a one-dimensional view of your data first:

```<code>%%timeit
data_ravel = data.ravel()
out = np.split(data_ravel, len(data))
>>> 14.5 µs ± 337 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code>```

Note that creating a view is costless (it took 0.13 µs on my computer)

Internally, it's being done like so:

```<code>out = []
div_points = range(0, data.size+1, data.shape[1])
start = div_points[:-1]
end = div_points[1:]
out = list(data_ravel[i:j] for i,j in zip(start, end))
>>> 2.31 µs ± 44.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code>```

Note that it's faster because I'd doing a couple of optimisations here:

using range instead of np.array

using lazy list comprehension instead of list.append

However, it can't compete with classical methods like in @mozway 's answer. They are optimal:

```<code>%%timeit
out = [*data]
>>> 902 ns ± 8.09 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%%timeit
out = list(data)
>>> 979 ns ± 12.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%%timeit
out = [n for n in data]
>>> 1.04 µs ± 14.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%%timeit
out = list(n for n in data)
>>> 1.37 µs ± 80.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
</code>```

Title: Converting multidimensional array into arrays in list for every row

Body:
I have a data set like this,

data = np.array([[ 5, 31, 61],
                 [ 10, 31, 67],
                 [ 15, 31, 69],
                 [ 4, 31, 72],
                 [ 14, 31, 73],
                 [ 21, 31, 77],
                 [ 19, 31, 78]])

I want to convert it into arrays in list for every single row. I tried,

np.split(data,len(data))

#[array([[ 5, 31, 61]]),
# array([[10, 31, 67]]),
# array([[15, 31, 69]]),
# array([[ 4, 31, 72]]),
# array([[14, 31, 73]]),
# array([[21, 31, 77]]),
# array([[19, 31, 78]])]

But as you can see it gives double [ to me. What I simply want is;

[np.array([5, 31, 61]),
np.array([10, 31, 67]),
np.array([15, 31, 69]),
np.array([4, 31, 72]),
np.array([14, 31, 73]),
np.array([21, 31, 77]),
np.array([19, 31, 78])]

Body:
np.split could be applied too but you are required to do it one-dimensionally. So you might like to create a one-dimensional view of your data first:

%%timeit
data_ravel = data.ravel()
out = np.split(data_ravel, len(data))
>>> 14.5 µs ± 337 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Note that creating a view is costless (it took 0.13 µs on my computer)

Internally, it's being done like so:

out = []
div_points = range(0, data.size+1, data.shape[1])
start = div_points[:-1]
end = div_points[1:]
out = list(data_ravel[i:j] for i,j in zip(start, end))
>>> 2.31 µs ± 44.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Note that it's faster because I'd doing a couple of optimisations here:

using range instead of np.array

using lazy list comprehension instead of list.append

However, it can't compete with classical methods like in @mozway 's answer. They are optimal:

%%timeit
out = [*data]
>>> 902 ns ± 8.09 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%%timeit
out = list(data)
>>> 979 ns ± 12.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%%timeit
out = [n for n in data]
>>> 1.04 µs ± 14.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%%timeit
out = list(n for n in data)
>>> 1.37 µs ± 80.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)


问:
SQL Dynamic Exchange Rate
I'm trying to create a stored procedure that provided the exchange rate based on the users selection.

When I simply type this query, it works fine:

```<code>SELECT RATE

FROM USERCONFIG.dbo.curr

WHERE CODE = 'GBP'
</code>```

However when I try to transfer this into a stored procedure:

```<code>ALTER PROCEDURE [dbo].[TEST] (@CCY char(3))

AS
BEGIN

    SET NOCOUNT ON;

EXEC('

SELECT RATE

FROM USERCONFIG.dbo.curr

WHERE CODE = ' + @CCY + '

    ')

END
</code>```

I get the following error message and I can't work out why.

答:
It's unclear why you are using dynamic SQL here, perhaps you should flesh out your example.

But what you need to do is parameterize it properly, using sp_executesql. Do not inject it like in the other answer.

ALTER PROCEDURE [dbo].[TEST] (@CCY char(3))

AS

SET NOCOUNT ON;

DECLARE @sql nvarchar(max) = N'
SELECT RATE
FROM USERCONFIG.dbo.curr
WHERE CODE = @CCY;
';

EXEC sp_executesql
  @sql,
  N'@CCY char(3)',
  @CCY = @CCY;
```

Title: SQL Dynamic Exchange Rate

Body:
I'm trying to create a stored procedure that provided the exchange rate based on the users selection.

When I simply type this query, it works fine:

SELECT RATE

FROM USERCONFIG.dbo.curr

WHERE CODE = 'GBP'

However when I try to transfer this into a stored procedure:

ALTER PROCEDURE [dbo].[TEST] (@CCY char(3))

AS
BEGIN

    SET NOCOUNT ON;

EXEC('

SELECT RATE

FROM USERCONFIG.dbo.curr

WHERE CODE = ' + @CCY + '

    ')

END

I get the following error message and I can't work out why.


问:
Spring cloud function routing api gateway null pointer exception
I have a problem with routing using API Gateway headers. I am using org.springframework.cloud.function.adapter.aws.FunctionInvoker::handleRequest as a handler request. I have two functions, they work locally. They work if I set environment variable.

If I use API Gateway headers (spring.cloud.function.definition:lowercase), I get:

```<code>{
  "errorMessage": "java.lang.NullPointerException",
  "errorType": "java.lang.NullPointerException",
  "stackTrace": [
    "org.springframework.cloud.function.adapter.aws.AWSLambdaUtils.generateMessage(AWSLambdaUtils.java:123)",
    "org.springframework.cloud.function.adapter.aws.FunctionInvoker.handleRequest(FunctionInvoker.java:105)",
    "java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)",
    "java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)",
    "java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)",
    "java.base/java.lang.reflect.Method.invoke(Unknown Source)"
  ]
}
</code>```

Example code reproducing the issue is here: https://github.com/cygi/cloudexample

POM is based on samples from Spring Cloud Function codebase (example code (https://github.com/spring-cloud/spring-cloud-function/tree/main/spring-cloud-function-samples/function-sample-aws-routing). Spring Cloud Function version is 3.2.1 (sample had a SNAPSHOT version, that uses JAVA 11, which is not available in AWS Lambda, at least without docker).

答:
Reverting to Spring Cloud Function 3.1.6 has resolved the problem.

Test event for AWS Lambda:

```<code>{
  "body": "foo",
  "httpMethod": "POST",
  "isBase64Encoded": false,
  "headers": {
      "spring.cloud.function.definition": "uppercase"
  }
}
</code>```

Result on 3.2.2

```<code>{
  "statusCode": 417,
  "headers": null,
  "body": "Failed to establish route, since neither were provided: 'spring.cloud.function.definition' as Message header or as application property or 'spring.cloud.function.routing-expression' as application property."
}
</code>```

Result on 3.1.6

```<code>{
  "isBase64Encoded": false,
  "headers": {
    "id": "758c1873-9377-25af-5ca2-84f55710ff2a",
    "contentType": "application/json",
    "timestamp": "1644500775689"
  },
  "body": "\"bbbb\"",
  "statusCode": 200
}
</code>```

Body:
I have a problem with routing using API Gateway headers. I am using org.springframework.cloud.function.adapter.aws.FunctionInvoker::handleRequest as a handler request. I have two functions, they work locally. They work if I set environment variable.

If I use API Gateway headers (spring.cloud.function.definition:lowercase), I get:

{
  "errorMessage": "java.lang.NullPointerException",
  "errorType": "java.lang.NullPointerException",
  "stackTrace": [
    "org.springframework.cloud.function.adapter.aws.AWSLambdaUtils.generateMessage(AWSLambdaUtils.java:123)",
    "org.springframework.cloud.function.adapter.aws.FunctionInvoker.handleRequest(FunctionInvoker.java:105)",
    "java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)",
    "java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)",
    "java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)",
    "java.base/java.lang.reflect.Method.invoke(Unknown Source)"
  ]
}

Example code reproducing the issue is here: https://github.com/cygi/cloudexample

POM is based on samples from Spring Cloud Function codebase (example code (https://github.com/spring-cloud/spring-cloud-function/tree/main/spring-cloud-function-samples/function-sample-aws-routing). Spring Cloud Function version is 3.2.1 (sample had a SNAPSHOT version, that uses JAVA 11, which is not available in AWS Lambda, at least without docker).

Body:
Reverting to Spring Cloud Function 3.1.6 has resolved the problem.

Test event for AWS Lambda:

{
  "body": "foo",
  "httpMethod": "POST",
  "isBase64Encoded": false,
  "headers": {
      "spring.cloud.function.definition": "uppercase"
  }
}

Result on 3.2.2

{
  "statusCode": 417,
  "headers": null,
  "body": "Failed to establish route, since neither were provided: 'spring.cloud.function.definition' as Message header or as application property or 'spring.cloud.function.routing-expression' as application property."
}

Result on 3.1.6

{
  "isBase64Encoded": false,
  "headers": {
    "id": "758c1873-9377-25af-5ca2-84f55710ff2a",
    "contentType": "application/json",
    "timestamp": "1644500775689"
  },
  "body": "\"bbbb\"",
  "statusCode": 200
}


答:
Using base r libraries

```<code>for(table in list(Fr1,Fr2,Fr3)) table_Fr <- merge(table_Fr, table, all.x=T)
for(table in list(Be1,Be2,Be3)) table_Be <- merge(table_Be, table, all.x=T)
</code>```

Or if you want to cycle through many countries and tables in a loop:

```<code>countries <- c('Fr','Be')
for(c in countries) {
  master_table <- get(paste0('table_',c))
  for(i in 1:3){
    master_table <- merge(master_table, get(paste0(c,i)), all.x=T)
  }
  assign(paste0('table_',c),master_table)
}
</code>```

Title: Loop R merge multiple data frames together

Body:
Using base r libraries

for(table in list(Fr1,Fr2,Fr3)) table_Fr <- merge(table_Fr, table, all.x=T)
for(table in list(Be1,Be2,Be3)) table_Be <- merge(table_Be, table, all.x=T)

Or if you want to cycle through many countries and tables in a loop:

countries <- c('Fr','Be')
for(c in countries) {
  master_table <- get(paste0('table_',c))
  for(i in 1:3){
    master_table <- merge(master_table, get(paste0(c,i)), all.x=T)
  }
  assign(paste0('table_',c),master_table)
}


问:
Find by the first characters of a string with a variable mongodb, nodejs
I want to find a document in my mongodb database by the first characters.

I have a string in my document like this:

```<code>name: 'Georges'
</code>```

This name is generate just before but it can be too long until 16MB !
So its too long to do a find on a string of 16 MB.
So I have the name in a variable

```<code>var name = 'Georges'
</code>```

I do a insert in my database. And I want to find it with the characters.
For example :

```<code>  var query = {name: /^Geo/};
  res = await db.collection('people').find(query).toArray());
</code>```

And its works like that but I want this :

```<code>var first = 'Geo';
var query = {name: /^first/};
res = await db.collection('people').find(query).toArray());
</code>```

But it cant work because its a variable, not a string.

Thanks in advance

答:
Use RegExp

```<code>var first = 'Geo';
var regex = new RegExp("^" + first, "g");
var query = {name: regex};
</code>```

Body:
I want to find a document in my mongodb database by the first characters.

I have a string in my document like this:

name: 'Georges'

This name is generate just before but it can be too long until 16MB !
So its too long to do a find on a string of 16 MB.
So I have the name in a variable

var name = 'Georges'

I do a insert in my database. And I want to find it with the characters.
For example :

  var query = {name: /^Geo/};
  res = await db.collection('people').find(query).toArray());

And its works like that but I want this :

var first = 'Geo';
var query = {name: /^first/};
res = await db.collection('people').find(query).toArray());

But it cant work because its a variable, not a string.

Thanks in advance

Body:
Use RegExp

var first = 'Geo';
var regex = new RegExp("^" + first, "g");
var query = {name: regex};


问:
How to stream cloudfront real time logs to cloudwatch
I need to monitor the CloudFront real time logs in cloud watch. Is there any way to stream CloudFront real time logs to the cloudwatch?

I know how to stream CloudFront standard(access)logs to cloudwatch(But it won't stream live logs and there will be a huge delay between live log time and log streaming time. so I won't prefer it) and how to stream real time logs to AWS OpenSearch through kinesis firehouse.

But in our project, we stream all service logs to the cloudwatch. So it would be better if any way to stream CloudFront logs to the cloudwatch.
Is there any possibility to do as my request?

答:
Barring any unannounced product that will stream CloudFront to CloudWatch (talk to your AWS account manager), you will need to write a Lambda to do this.

Configure CloudFront to write to Kinesis, and then attach a Lambda function to that Kinesis stream.

Where things will get tricky is that you may have multiple Lambdas running concurrently, reading from different shards in the Kinesis stream. If you attempt to write to the same log stream, you will need to retrieve the latest sequence token before calling PutLogEvents, and be prepared for (1) collisions, and (2) running up against quotas for writing to log streams.

Instead, I recommend that the first call to a handler Lambda create a new log stream, and subsequent calls to that Lambda write to that stream using the sequence token from the previous request. This may result in a lot of log streams, which may be challenging to read in real-time (although CloudWatch Logs Insights helps there).


问:
Sending values from Javascript to Blazor doesn't work (Two-data-binding)
In my java script I'm sending the Lan/Long of my map to blazor. I can see the the the longitude and latitude changes on the browser, but I want to pass them to my blazor method to do some processing. the values returned always 0.

Here is my have script method:

```<code>function GetCircle(e){
    r = document.getElementById("InputRadius").value;

    if (circle !== null) {
        map.removeLayer(circle);

    }
        circle = new  L.circle([ Lat,Long],{radius:r});
    map.addLayer(circle);
    circle.bindPopup( "<br/> Radius is : " + r +" Meter"

    ).openPopup();
    document.getElementById("Lat").value = Lat; //send this to blazor
    document.getElementById("Long").value = Long; // send this to blazor

}
</code>```

As you can see from the above code, when the user click on the map I'm getting the long/lat and then send them to blazor.

My razor page:
I have the following inputs which I'm using them to store the data inside them then pass the data to blazor method in the 'code' section

```<code>
<input type="text" @bind="Lat" id="Lat" name="Lat"   >
<input type="text" @bind="Long" id="Long" name = "Long" >

@code {

   int InputRadius;
  double Long;
  double Lat;
  string date_selected;
  string time_selected;

    public async Task GetTgas()
        {
         AllTags = await Task.Run(() => tagsService.Map(   InputRadius, Long,Lat,date_selected,time_selected));

        }

 public async Task GetCircle()

    {
        await JSRuntime.InvokeVoidAsync("GetCircle");

    }

}

</code>```

I can see the Lan/Long in my view perfectly when I'm clicking on GetCircle, which means that they passed from JS to blazor page successfully, but when doing the GetTags function they don't pass to my blazor method.

Any help would be appriciated!

答:
Your GetCircle method should be like this, need to send .net object reference to javascript function

```<code>await JS.InvokeVoidAsync("GetCircle", DotNetObjectReference.Create(this));
</code>```

And your GetTags function should be like this, should be invokable from javascript

```<code>[JSInvokable]
public async Task GetTags(double lati, double longi)
   {
      AllTags = await Task.Run(() => tagsService.Map(InputRadius, longi,lati,date_selected,time_selected));
   }
</code>```

Your javascript function should be like this

```<code>function GetCircle(dotNetHelper){
    r = document.getElementById("InputRadius").value;

    if (circle !== null) {
        map.removeLayer(circle);

    }
        circle = new  L.circle([ Lat,Long],{radius:r});
    map.addLayer(circle);
    circle.bindPopup( "<br/> Radius is : " + r +" Meter"

    ).openPopup();

    //  send this to blazor
    dotNetHelper.invokeMethodAsync('GetTags', Lat, Long);
}
</code>```

Body:
In my java script I'm sending the Lan/Long of my map to blazor. I can see the the the longitude and latitude changes on the browser, but I want to pass them to my blazor method to do some processing. the values returned always 0.

Here is my have script method:

function GetCircle(e){
    r = document.getElementById("InputRadius").value;

    if (circle !== null) {
        map.removeLayer(circle);

    }
        circle = new  L.circle([ Lat,Long],{radius:r});
    map.addLayer(circle);
    circle.bindPopup( "
 Radius is : " + r +" Meter"

    ).openPopup();
    document.getElementById("Lat").value = Lat; //send this to blazor
    document.getElementById("Long").value = Long; // send this to blazor

}

As you can see from the above code, when the user click on the map I'm getting the long/lat and then send them to blazor.

My razor page:
I have the following inputs which I'm using them to store the data inside them then pass the data to blazor method in the 'code' section

<input type="text" @bind="Lat" id="Lat" name="Lat"   >
<input type="text" @bind="Long" id="Long" name = "Long" >

@code {

   int InputRadius;
  double Long;
  double Lat;
  string date_selected;
  string time_selected;

    public async Task GetTgas()
        {
         AllTags = await Task.Run(() => tagsService.Map(   InputRadius, Long,Lat,date_selected,time_selected));

        }

 public async Task GetCircle()

    {
        await JSRuntime.InvokeVoidAsync("GetCircle");

    }

}

I can see the Lan/Long in my view perfectly when I'm clicking on GetCircle, which means that they passed from JS to blazor page successfully, but when doing the GetTags function they don't pass to my blazor method.

Any help would be appriciated!

Body:
Your GetCircle method should be like this, need to send .net object reference to javascript function

await JS.InvokeVoidAsync("GetCircle", DotNetObjectReference.Create(this));

And your GetTags function should be like this, should be invokable from javascript

[JSInvokable]
public async Task GetTags(double lati, double longi)
   {
      AllTags = await Task.Run(() => tagsService.Map(InputRadius, longi,lati,date_selected,time_selected));
   }

Your javascript function should be like this

function GetCircle(dotNetHelper){
    r = document.getElementById("InputRadius").value;

    if (circle !== null) {
        map.removeLayer(circle);

    }
        circle = new  L.circle([ Lat,Long],{radius:r});
    map.addLayer(circle);
    circle.bindPopup( "<br/> Radius is : " + r +" Meter"

    ).openPopup();

    //  send this to blazor
    dotNetHelper.invokeMethodAsync('GetTags', Lat, Long);
}


问:
Why are the slides of my carousel not changing when the buttons are clicked?
I found a carousel on internet made from HTML and CSS and copy pasted it into my website code. The code i found had the code for the buttons written before the code of carousel  that's why the buttons were showing at the top of carousel. I corrected the layout but for some reason the buttons stopped working.

.products {
  grid-template-rows: 500px 100px;
  grid-template-columns: 30px 30px 30px 30px 30px 30px 30px 30px;
}

.rbn {
  margin: 0px 5px 0px 5px;
}

.images {
  width: auto;
  height: 500px;
  max-height: 400px;
  margin: auto;
  display: block;
}

main#carousel {
  grid-row: 1 / 2;
  grid-column: 1 / 8;
  width: 100vw;
  height: 500px;
  padding-right: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  transform-style: preserve-3d;
  perspective: 600px;
  --items: 8;
  --middle: 3;
  --position: 1;
  pointer-events: none;
}

div.item {
  position: absolute;
  width: 300px;
  height: 400px;
  background-color: coral;
  --r: calc(var(--position) - var(--offset));
  --abs: max(calc(var(--r) * -1), var(--r));
  transition: all 0.25s linear;
  transform: rotateY(calc(-10deg * var(--r))) translateX(calc(-300px * var(--r)));
  z-index: calc((var(--position) - var(--abs)));
}

div.item:nth-of-type(1) {
  --offset: 1;
  background-color: #90f1ef;
}

div.item:nth-of-type(2) {
  --offset: 2;
  background-color: #ff70a6;
}

div.item:nth-of-type(3) {
  --offset: 3;
  background-color: #ff9770;
}

div.item:nth-of-type(4) {
  --offset: 4;
  background-color: #ffd670;
}

div.item:nth-of-type(5) {
  --offset: 5;
  background-color: #e9ff70;
}

div.item:nth-of-type(6) {
  --offset: 6;
  background-color: #f76e11;
}

div.item:nth-of-type(7) {
  --offset: 7;
  background-color: #2eb086;
}

div.item:nth-of-type(8) {
  --offset: 8;
  background-color: #faeee7;
}

input:nth-of-type(1) {
  grid-column: 2 / 3;
  grid-row: 2 / 3;
}

input:nth-of-type(1):checked~main#carousel {
  --position: 1;
}

input:nth-of-type(2) {
  grid-column: 3 / 4;
  grid-row: 2 / 3;
}

input:nth-of-type(2):checked~main#carousel {
  --position: 2;
}

input:nth-of-type(3) {
  grid-column: 4 /5;
  grid-row: 2 / 3;
}

input:nth-of-type(3):checked~main#carousel {
  --position: 3;
}

input:nth-of-type(4) {
  grid-column: 5 / 6;
  grid-row: 2 / 3;
}

input:nth-of-type(4):checked~main#carousel {
  --position: 4;
}

input:nth-of-type(5) {
  grid-column: 6 / 7;
  grid-row: 2 / 3;
}

input:nth-of-type(5):checked~main#carousel {
  --position: 5;
}

input:nth-of-type(6) {
  grid-column: 7 / 8;
  grid-row: 2 / 3;
}

input:nth-of-type(6):checked~main#carousel {
  --position: 6;
}

input:nth-of-type(7) {
  grid-column: 8 / 9;
  grid-row: 2 / 3;
}

input:nth-of-type(7):checked~main#carousel {
  --position: 7;
}

input:nth-of-type(8) {
  grid-column: 9 / 10;
  grid-row: 2 / 3;
}

input:nth-of-type(8):checked~main#carousel {
  --position: 8;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div "products">
  <main id="carousel">
    <div class="item">
      <img class="images" src="almondflakes.png" alt="af" />
    </div>
    <div class="item">
      <img class="images" src="butterscotchballs.png" alt="bb" />
    </div>
    <div class="item">
      <img class="images" src="chocoballs.png" alt="cb" />
    </div>
    <div class="item">
      <img class="images" src="chocolatesprinklers.png" alt="cs" />
    </div>
    <div class="item">
      <img class="images" src="oreodust.png" alt="od" />
    </div>
    <div class="item">
      <img class="images" src="rainbowsprinkles.png" alt="rs" />
    </div>
    <div class="item">
      <img class="images" src="ricekrispies.png" alt="rk" />
    </div>
    <div class="item">
      <img class="images" src="whitecreamballs.png" alt="wc" />
    </div>
  </main>
  <input class="rbn" type="radio" name="position" checked />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />
</div></code>```

答:
The tilde (~) in your CSS is a subsequent sibling combination selector. When you reversed the structure of your HTML you broke those. They don't work in reverse.

You'll need to use another means of relocating the buttons that doesn't involve changing the markup. Reversing column order might do.

.products {
  grid-template-rows: 500px 100px;
  grid-template-columns: 30px 30px 30px 30px 30px 30px 30px 30px;
}

.rbn {
  margin: 0px 5px 0px 5px;
}

.images {
  width: auto;
  height: 500px;
  max-height: 400px;
  margin: auto;
  display: block;
}

main#carousel {
  grid-row: 1 / 2;
  grid-column: 1 / 8;
  width: 100vw;
  height: 500px;
  padding-right: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  transform-style: preserve-3d;
  perspective: 600px;
  --items: 8;
  --middle: 3;
  --position: 1;
  pointer-events: none;
}

div.item {
  position: absolute;
  width: 300px;
  height: 400px;
  background-color: coral;
  --r: calc(var(--position) - var(--offset));
  --abs: max(calc(var(--r) * -1), var(--r));
  transition: all 0.25s linear;
  transform: rotateY(calc(-10deg * var(--r))) translateX(calc(-300px * var(--r)));
  z-index: calc((var(--position) - var(--abs)));
}

div.item:nth-of-type(1) {
  --offset: 1;
  background-color: #90f1ef;
}

div.item:nth-of-type(2) {
  --offset: 2;
  background-color: #ff70a6;
}

div.item:nth-of-type(3) {
  --offset: 3;
  background-color: #ff9770;
}

div.item:nth-of-type(4) {
  --offset: 4;
  background-color: #ffd670;
}

div.item:nth-of-type(5) {
  --offset: 5;
  background-color: #e9ff70;
}

div.item:nth-of-type(6) {
  --offset: 6;
  background-color: #f76e11;
}

div.item:nth-of-type(7) {
  --offset: 7;
  background-color: #2eb086;
}

div.item:nth-of-type(8) {
  --offset: 8;
  background-color: #faeee7;
}

input:nth-of-type(1) {
  grid-column: 2 / 3;
  grid-row: 2 / 3;
}

input:nth-of-type(1):checked~main#carousel {
  --position: 1;
}

input:nth-of-type(2) {
  grid-column: 3 / 4;
  grid-row: 2 / 3;
}

input:nth-of-type(2):checked~main#carousel {
  --position: 2;
}

input:nth-of-type(3) {
  grid-column: 4 /5;
  grid-row: 2 / 3;
}

input:nth-of-type(3):checked~main#carousel {
  --position: 3;
}

input:nth-of-type(4) {
  grid-column: 5 / 6;
  grid-row: 2 / 3;
}

input:nth-of-type(4):checked~main#carousel {
  --position: 4;
}

input:nth-of-type(5) {
  grid-column: 6 / 7;
  grid-row: 2 / 3;
}

input:nth-of-type(5):checked~main#carousel {
  --position: 5;
}

input:nth-of-type(6) {
  grid-column: 7 / 8;
  grid-row: 2 / 3;
}

input:nth-of-type(6):checked~main#carousel {
  --position: 6;
}

input:nth-of-type(7) {
  grid-column: 8 / 9;
  grid-row: 2 / 3;
}

input:nth-of-type(7):checked~main#carousel {
  --position: 7;
}

input:nth-of-type(8) {
  grid-column: 9 / 10;
  grid-row: 2 / 3;
}

input:nth-of-type(8):checked~main#carousel {
  --position: 8;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div "products">
  <input class="rbn" type="radio" name="position" checked />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />

  <main id="carousel">
    <div class="item">
      <img class="images" src="almondflakes.png" alt="af" />
    </div>
    <div class="item">
      <img class="images" src="butterscotchballs.png" alt="bb" />
    </div>
    <div class="item">
      <img class="images" src="chocoballs.png" alt="cb" />
    </div>
    <div class="item">
      <img class="images" src="chocolatesprinklers.png" alt="cs" />
    </div>
    <div class="item">
      <img class="images" src="oreodust.png" alt="od" />
    </div>
    <div class="item">
      <img class="images" src="rainbowsprinkles.png" alt="rs" />
    </div>
    <div class="item">
      <img class="images" src="ricekrispies.png" alt="rk" />
    </div>
    <div class="item">
      <img class="images" src="whitecreamballs.png" alt="wc" />
    </div>
  </main>
</div></code>```

Body:
I found a carousel on internet made from HTML and CSS and copy pasted it into my website code. The code i found had the code for the buttons written before the code of carousel  that's why the buttons were showing at the top of carousel. I corrected the layout but for some reason the buttons stopped working.

.products {
  grid-template-rows: 500px 100px;
  grid-template-columns: 30px 30px 30px 30px 30px 30px 30px 30px;
}

.rbn {
  margin: 0px 5px 0px 5px;
}

.images {
  width: auto;
  height: 500px;
  max-height: 400px;
  margin: auto;
  display: block;
}

main#carousel {
  grid-row: 1 / 2;
  grid-column: 1 / 8;
  width: 100vw;
  height: 500px;
  padding-right: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  transform-style: preserve-3d;
  perspective: 600px;
  --items: 8;
  --middle: 3;
  --position: 1;
  pointer-events: none;
}

div.item {
  position: absolute;
  width: 300px;
  height: 400px;
  background-color: coral;
  --r: calc(var(--position) - var(--offset));
  --abs: max(calc(var(--r) * -1), var(--r));
  transition: all 0.25s linear;
  transform: rotateY(calc(-10deg * var(--r))) translateX(calc(-300px * var(--r)));
  z-index: calc((var(--position) - var(--abs)));
}

div.item:nth-of-type(1) {
  --offset: 1;
  background-color: #90f1ef;
}

div.item:nth-of-type(2) {
  --offset: 2;
  background-color: #ff70a6;
}

div.item:nth-of-type(3) {
  --offset: 3;
  background-color: #ff9770;
}

div.item:nth-of-type(4) {
  --offset: 4;
  background-color: #ffd670;
}

div.item:nth-of-type(5) {
  --offset: 5;
  background-color: #e9ff70;
}

div.item:nth-of-type(6) {
  --offset: 6;
  background-color: #f76e11;
}

div.item:nth-of-type(7) {
  --offset: 7;
  background-color: #2eb086;
}

div.item:nth-of-type(8) {
  --offset: 8;
  background-color: #faeee7;
}

input:nth-of-type(1) {
  grid-column: 2 / 3;
  grid-row: 2 / 3;
}

input:nth-of-type(1):checked~main#carousel {
  --position: 1;
}

input:nth-of-type(2) {
  grid-column: 3 / 4;
  grid-row: 2 / 3;
}

input:nth-of-type(2):checked~main#carousel {
  --position: 2;
}

input:nth-of-type(3) {
  grid-column: 4 /5;
  grid-row: 2 / 3;
}

input:nth-of-type(3):checked~main#carousel {
  --position: 3;
}

input:nth-of-type(4) {
  grid-column: 5 / 6;
  grid-row: 2 / 3;
}

input:nth-of-type(4):checked~main#carousel {
  --position: 4;
}

input:nth-of-type(5) {
  grid-column: 6 / 7;
  grid-row: 2 / 3;
}

input:nth-of-type(5):checked~main#carousel {
  --position: 5;
}

input:nth-of-type(6) {
  grid-column: 7 / 8;
  grid-row: 2 / 3;
}

input:nth-of-type(6):checked~main#carousel {
  --position: 6;
}

input:nth-of-type(7) {
  grid-column: 8 / 9;
  grid-row: 2 / 3;
}

input:nth-of-type(7):checked~main#carousel {
  --position: 7;
}

input:nth-of-type(8) {
  grid-column: 9 / 10;
  grid-row: 2 / 3;
}

input:nth-of-type(8):checked~main#carousel {
  --position: 8;
}

  <input class="rbn" type="radio" name="position" checked />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />

Body:
The tilde (~) in your CSS is a subsequent sibling combination selector. When you reversed the structure of your HTML you broke those. They don't work in reverse.

You'll need to use another means of relocating the buttons that doesn't involve changing the markup. Reversing column order might do.

.products {
  grid-template-rows: 500px 100px;
  grid-template-columns: 30px 30px 30px 30px 30px 30px 30px 30px;
}

.rbn {
  margin: 0px 5px 0px 5px;
}

.images {
  width: auto;
  height: 500px;
  max-height: 400px;
  margin: auto;
  display: block;
}

main#carousel {
  grid-row: 1 / 2;
  grid-column: 1 / 8;
  width: 100vw;
  height: 500px;
  padding-right: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  transform-style: preserve-3d;
  perspective: 600px;
  --items: 8;
  --middle: 3;
  --position: 1;
  pointer-events: none;
}

div.item {
  position: absolute;
  width: 300px;
  height: 400px;
  background-color: coral;
  --r: calc(var(--position) - var(--offset));
  --abs: max(calc(var(--r) * -1), var(--r));
  transition: all 0.25s linear;
  transform: rotateY(calc(-10deg * var(--r))) translateX(calc(-300px * var(--r)));
  z-index: calc((var(--position) - var(--abs)));
}

div.item:nth-of-type(1) {
  --offset: 1;
  background-color: #90f1ef;
}

div.item:nth-of-type(2) {
  --offset: 2;
  background-color: #ff70a6;
}

div.item:nth-of-type(3) {
  --offset: 3;
  background-color: #ff9770;
}

div.item:nth-of-type(4) {
  --offset: 4;
  background-color: #ffd670;
}

div.item:nth-of-type(5) {
  --offset: 5;
  background-color: #e9ff70;
}

div.item:nth-of-type(6) {
  --offset: 6;
  background-color: #f76e11;
}

div.item:nth-of-type(7) {
  --offset: 7;
  background-color: #2eb086;
}

div.item:nth-of-type(8) {
  --offset: 8;
  background-color: #faeee7;
}

input:nth-of-type(1) {
  grid-column: 2 / 3;
  grid-row: 2 / 3;
}

input:nth-of-type(1):checked~main#carousel {
  --position: 1;
}

input:nth-of-type(2) {
  grid-column: 3 / 4;
  grid-row: 2 / 3;
}

input:nth-of-type(2):checked~main#carousel {
  --position: 2;
}

input:nth-of-type(3) {
  grid-column: 4 /5;
  grid-row: 2 / 3;
}

input:nth-of-type(3):checked~main#carousel {
  --position: 3;
}

input:nth-of-type(4) {
  grid-column: 5 / 6;
  grid-row: 2 / 3;
}

input:nth-of-type(4):checked~main#carousel {
  --position: 4;
}

input:nth-of-type(5) {
  grid-column: 6 / 7;
  grid-row: 2 / 3;
}

input:nth-of-type(5):checked~main#carousel {
  --position: 5;
}

input:nth-of-type(6) {
  grid-column: 7 / 8;
  grid-row: 2 / 3;
}

input:nth-of-type(6):checked~main#carousel {
  --position: 6;
}

input:nth-of-type(7) {
  grid-column: 8 / 9;
  grid-row: 2 / 3;
}

input:nth-of-type(7):checked~main#carousel {
  --position: 7;
}

input:nth-of-type(8) {
  grid-column: 9 / 10;
  grid-row: 2 / 3;
}

input:nth-of-type(8):checked~main#carousel {
  --position: 8;
}

<div "products">
  <input class="rbn" type="radio" name="position" checked />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />
  <input class="rbn" type="radio" name="position" />

  <main id="carousel">
    <div class="item">
      <img class="images" src="almondflakes.png" alt="af" />
    </div>
    <div class="item">
      <img class="images" src="butterscotchballs.png" alt="bb" />
    </div>
    <div class="item">
      <img class="images" src="chocoballs.png" alt="cb" />
    </div>
    <div class="item">
      <img class="images" src="chocolatesprinklers.png" alt="cs" />
    </div>
    <div class="item">
      <img class="images" src="oreodust.png" alt="od" />
    </div>
    <div class="item">
      <img class="images" src="rainbowsprinkles.png" alt="rs" />
    </div>
    <div class="item">
      <img class="images" src="ricekrispies.png" alt="rk" />
    </div>
    <div class="item">
      <img class="images" src="whitecreamballs.png" alt="wc" />
    </div>
  </main>
</div>