问:
How to remove a specific value that is based on a specific date
Below is a portion of my dataframe:

```<code>    Year Date        Location Tag Section domsec atDominantLocation
    2017 2017-08-13        a wnd       n      n                  1
    2017 2017-08-14        a wnd       n      n                  1
    2017 2017-08-15        a wnd       n      n                  1
    2017 2017-08-16        a wnd       n      n                  1
    2017 2017-08-17        a wnd       n      n                  1
    2017 2017-08-18        a wnd       n      n                  1
    2017 2017-08-19        a wnd       n      n                  1
    2017 2017-08-20        a wnd       n      n                  1
    2017 2017-08-21        a wnd       b      n                  0
    2017 2017-08-21        a wnd       u      n                  0
    2017 2017-08-23        a wnd       f      n                  0
    2018 2018-08-21        a wnd       f      s                  0
    2018 2018-08-18        a wnd       h      s                  0
    2018 2018-08-19        a wnd       o      s                  0
    2018 2018-08-15        a wnd       s      s                  1
    2018 2018-08-17        a wnd       s      s                  1
    2018 2018-08-14        c wnd      ss      s                  0
    2018 2018-08-16        a wnd       t      s                  0
    2018 2018-08-21        a wnd       t      s                  0
    2018 2018-08-13        c wnd      ww      s                  0
    2018 2018-08-20        a wnd       y      s                  0
</code>```

The column "atDominantLocation" contains "1"s and "0"s. I want to keep all the "0"s but only keep the "1" with the earliest date. So, there should ONLY be one "1" for each tag and year and that "1" should be the earliest date in that year.

Below is my desired output:

```<code>    Year Date        Location Tag Section domsec atDominantLocation
    2017 2017-08-13        a wnd       n      n                  1
    2017 2017-08-21        a wnd       b      n                  0
    2017 2017-08-21        a wnd       u      n                  0
    2017 2017-08-23        a wnd       f      n                  0
    2018 2018-08-21        a wnd       f      s                  0
    2018 2018-08-18        a wnd       h      s                  0
    2018 2018-08-19        a wnd       o      s                  0
    2018 2018-08-15        a wnd       s      s                  1
    2018 2018-08-14        c wnd      ss      s                  0
    2018 2018-08-16        a wnd       t      s                  0
    2018 2018-08-21        a wnd       t      s                  0
    2018 2018-08-13        c wnd      ww      s                  0
    2018 2018-08-20        a wnd       y      s                  0
</code>```

I've tried both the duplicate and unique functions without any success. Thanks for your help.

答:
Another tidyverse option is to filter atDominantLocation to just the 1s. Then, sort and group by Year and Tag, then get the row with the earliest date using slice. Then, we can bind those rows back to the original dataframe, but just to the rows where atDominantLocation is 0.

```<code>library(tidyverse)

df %>%
  filter(atDominantLocation == 1) %>%
  arrange(Date) %>%
  group_by(Year, Tag) %>%
  slice(1) %>%
  bind_rows(df %>% filter(atDominantLocation == 0)) %>%
  arrange(Date)
</code>```

Output

```<code>    Year Date       Location Tag   Section domsec atDominantLocation
   <int> <chr>      <chr>    <chr> <chr>   <chr>               <int>
 1  2017 2017-08-13 a        wnd   n       n                       1
 2  2017 2017-08-21 a        wnd   b       n                       0
 3  2017 2017-08-21 a        wnd   u       n                       0
 4  2017 2017-08-23 a        wnd   f       n                       0
 5  2018 2018-08-13 c        wnd   ww      s                       0
 6  2018 2018-08-14 c        wnd   ss      s                       0
 7  2018 2018-08-15 a        wnd   s       s                       1
 8  2018 2018-08-16 a        wnd   t       s                       0
 9  2018 2018-08-18 a        wnd   h       s                       0
10  2018 2018-08-19 a        wnd   o       s                       0
11  2018 2018-08-20 a        wnd   y       s                       0
12  2018 2018-08-21 a        wnd   f       s                       0
13  2018 2018-08-21 a        wnd   t       s                       0
</code>```

Data

```<code>df <- structure(list(Year = c(2017L, 2017L, 2017L, 2017L, 2017L, 2017L,
                              2017L, 2017L, 2017L, 2017L, 2017L, 2018L, 2018L, 2018L, 2018L,
                              2018L, 2018L, 2018L, 2018L, 2018L, 2018L),
                     Date = c("2017-08-13", "2017-08-14", "2017-08-15", "2017-08-16", "2017-08-17", "2017-08-18",
                              "2017-08-19", "2017-08-20", "2017-08-21", "2017-08-21", "2017-08-23",
                              "2018-08-21", "2018-08-18", "2018-08-19", "2018-08-15", "2018-08-17",
                               "2018-08-14", "2018-08-16", "2018-08-21", "2018-08-13", "2018-08-20"
                              ), Location = c("a", "a", "a", "a", "a", "a", "a", "a", "a",
                                              "a", "a", "a", "a", "a", "a", "a", "c", "a", "a", "c", "a"),
                     Tag = c("wnd", "wnd", "wnd", "wnd", "wnd", "wnd", "wnd",
                             "wnd", "wnd", "wnd", "wnd", "wnd", "wnd", "wnd", "wnd", "wnd",
                             "wnd", "wnd", "wnd", "wnd", "wnd"),
                     Section = c("n", "n", "n", "n", "n", "n", "n", "n", "b", "u", "f", "f", "h", "o",
                                 "s", "s", "ss", "t", "t", "ww", "y"),
                     domsec = c("n", "n", "n", "n", "n", "n", "n", "n", "n", "n", "n", "s", "s", "s",
                                "s", "s", "s", "s", "s", "s", "s"),
                     atDominantLocation = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L,
                                            0L, 0L, 0L, 0L, 0L)), class = "data.frame", row.names = c(NA, -21L))
</code>```

Body:
Below is a portion of my dataframe:

    Year Date        Location Tag Section domsec atDominantLocation
    2017 2017-08-13        a wnd       n      n                  1
    2017 2017-08-14        a wnd       n      n                  1
    2017 2017-08-15        a wnd       n      n                  1
    2017 2017-08-16        a wnd       n      n                  1
    2017 2017-08-17        a wnd       n      n                  1
    2017 2017-08-18        a wnd       n      n                  1
    2017 2017-08-19        a wnd       n      n                  1
    2017 2017-08-20        a wnd       n      n                  1
    2017 2017-08-21        a wnd       b      n                  0
    2017 2017-08-21        a wnd       u      n                  0
    2017 2017-08-23        a wnd       f      n                  0
    2018 2018-08-21        a wnd       f      s                  0
    2018 2018-08-18        a wnd       h      s                  0
    2018 2018-08-19        a wnd       o      s                  0
    2018 2018-08-15        a wnd       s      s                  1
    2018 2018-08-17        a wnd       s      s                  1
    2018 2018-08-14        c wnd      ss      s                  0
    2018 2018-08-16        a wnd       t      s                  0
    2018 2018-08-21        a wnd       t      s                  0
    2018 2018-08-13        c wnd      ww      s                  0
    2018 2018-08-20        a wnd       y      s                  0

The column "atDominantLocation" contains "1"s and "0"s. I want to keep all the "0"s but only keep the "1" with the earliest date. So, there should ONLY be one "1" for each tag and year and that "1" should be the earliest date in that year.

Below is my desired output:

    Year Date        Location Tag Section domsec atDominantLocation
    2017 2017-08-13        a wnd       n      n                  1
    2017 2017-08-21        a wnd       b      n                  0
    2017 2017-08-21        a wnd       u      n                  0
    2017 2017-08-23        a wnd       f      n                  0
    2018 2018-08-21        a wnd       f      s                  0
    2018 2018-08-18        a wnd       h      s                  0
    2018 2018-08-19        a wnd       o      s                  0
    2018 2018-08-15        a wnd       s      s                  1
    2018 2018-08-14        c wnd      ss      s                  0
    2018 2018-08-16        a wnd       t      s                  0
    2018 2018-08-21        a wnd       t      s                  0
    2018 2018-08-13        c wnd      ww      s                  0
    2018 2018-08-20        a wnd       y      s                  0

I've tried both the duplicate and unique functions without any success. Thanks for your help.

Body:
Another tidyverse option is to filter atDominantLocation to just the 1s. Then, sort and group by Year and Tag, then get the row with the earliest date using slice. Then, we can bind those rows back to the original dataframe, but just to the rows where atDominantLocation is 0.

library(tidyverse)

df %>%
  filter(atDominantLocation == 1) %>%
  arrange(Date) %>%
  group_by(Year, Tag) %>%
  slice(1) %>%
  bind_rows(df %>% filter(atDominantLocation == 0)) %>%
  arrange(Date)

Output

    Year Date       Location Tag   Section domsec atDominantLocation
   <int> <chr>      <chr>    <chr> <chr>   <chr>               <int>
 1  2017 2017-08-13 a        wnd   n       n                       1
 2  2017 2017-08-21 a        wnd   b       n                       0
 3  2017 2017-08-21 a        wnd   u       n                       0
 4  2017 2017-08-23 a        wnd   f       n                       0
 5  2018 2018-08-13 c        wnd   ww      s                       0
 6  2018 2018-08-14 c        wnd   ss      s                       0
 7  2018 2018-08-15 a        wnd   s       s                       1
 8  2018 2018-08-16 a        wnd   t       s                       0
 9  2018 2018-08-18 a        wnd   h       s                       0
10  2018 2018-08-19 a        wnd   o       s                       0
11  2018 2018-08-20 a        wnd   y       s                       0
12  2018 2018-08-21 a        wnd   f       s                       0
13  2018 2018-08-21 a        wnd   t       s                       0

Data

df <- structure(list(Year = c(2017L, 2017L, 2017L, 2017L, 2017L, 2017L,
                              2017L, 2017L, 2017L, 2017L, 2017L, 2018L, 2018L, 2018L, 2018L,
                              2018L, 2018L, 2018L, 2018L, 2018L, 2018L),
                     Date = c("2017-08-13", "2017-08-14", "2017-08-15", "2017-08-16", "2017-08-17", "2017-08-18",
                              "2017-08-19", "2017-08-20", "2017-08-21", "2017-08-21", "2017-08-23",
                              "2018-08-21", "2018-08-18", "2018-08-19", "2018-08-15", "2018-08-17",
                               "2018-08-14", "2018-08-16", "2018-08-21", "2018-08-13", "2018-08-20"
                              ), Location = c("a", "a", "a", "a", "a", "a", "a", "a", "a",
                                              "a", "a", "a", "a", "a", "a", "a", "c", "a", "a", "c", "a"),
                     Tag = c("wnd", "wnd", "wnd", "wnd", "wnd", "wnd", "wnd",
                             "wnd", "wnd", "wnd", "wnd", "wnd", "wnd", "wnd", "wnd", "wnd",
                             "wnd", "wnd", "wnd", "wnd", "wnd"),
                     Section = c("n", "n", "n", "n", "n", "n", "n", "n", "b", "u", "f", "f", "h", "o",
                                 "s", "s", "ss", "t", "t", "ww", "y"),
                     domsec = c("n", "n", "n", "n", "n", "n", "n", "n", "n", "n", "n", "s", "s", "s",
                                "s", "s", "s", "s", "s", "s", "s"),
                     atDominantLocation = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L,
                                            0L, 0L, 0L, 0L, 0L)), class = "data.frame", row.names = c(NA, -21L))


来源: stackexchange

问:
Mongoose insertMany not inserting in correct order
I am trying to insert an array of 26 items in my mongodb database using following code:

```<code>const items = [item1, item2, ....., item26]
Model.remove({}).then(() => Model.insertMany(items));
</code>```

When I run this for a local database, the order of items in the collection is as expected. But when I change my connection to a remote m-lab database, the items are not in a correct order in the database. It becomes something like item13...item26, item1...item12.

PS: I am doing this to run some tests.

答:
We can provide an "ordered" option to insertmany as true.

```<code>db.collection.insertMany(
   [ <document 1> , <document 2>, ... ],
   {
      writeConcern: <document>,
      ordered: <boolean>
   }
)
</code>```

See the docs:
https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/

ContentLicense: CC BY-SA 3.0

Body:
I am trying to insert an array of 26 items in my mongodb database using following code:

const items = [item1, item2, ....., item26]
Model.remove({}).then(() => Model.insertMany(items));

When I run this for a local database, the order of items in the collection is as expected. But when I change my connection to a remote m-lab database, the items are not in a correct order in the database. It becomes something like item13...item26, item1...item12.

PS: I am doing this to run some tests.

Body:
We can provide an "ordered" option to insertmany as true.

db.collection.insertMany(
   [ <document 1> , <document 2>, ... ],
   {
      writeConcern: <document>,
      ordered: <boolean>
   }
)

See the docs:
https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/

ContentLicense: CC BY-SA 4.0


问:
Filter rows on the condition that at least two distinct key words must be present
I have a dataframe with speech data, like this:

```<code>df <- data.frame(
  id = 1:12,
  partcl = c("yeah yeah yeah absolutely", "well you know it 's", "oh well yeah that's right",
             "yeah I mean well oh", "well erm well Peter will be there", "well yeah well",
             "yes yes yes totally", "yeah yeah yeah yeah", "well well I did n't do it",
             "er well yeah that 's true", "oh hey where 's he gone?", "er"
))
</code>```

and a vector with key words called parts:

```<code>parts <- c("yeah", "oh", "no", "well", "mm", "yes", "so", "right", "er", "like")
</code>```

What I need to do is filter those rows with at least two distinct parts values. What I can do is filter those rows with at least two parts values, regardless of whether they're distinct or the same:

```<code>library(dplyr)
df %>%
  filter(
    str_count(partcl, paste0("\\b(", paste0(parts, collapse = "|"), ")\\b")) > 1
  )
  id                            partcl
1  1         yeah yeah yeah absolutely
2  3         oh well yeah that's right
3  4               yeah I mean well oh
4  5 well erm well Peter will be there
5  6                    well yeah well
6  7               yes yes yes totally
7  8               yeah yeah yeah yeah
8  9         well well I did n't do it
9 10         er well yeah that 's true
</code>```

How can I assert that the matched partsbe distinct so that the result is this:

```<code>  id                            partcl
1  3         oh well yeah that's right
2  4               yeah I mean well oh
3  6                    well yeah well
4 10         er well yeah that 's true
</code>```

答:
You can iterate over parts with sapply() to check df$partcl for occurrences of the keywords. The paste0("\\b", x, "\\b") part ensures that we only detect full words, otherwise "so" will also be found in "absolutely" for example. rowSums() creates a vector we can add to df and we can then dplyr::filter() the desired rows.

library(dplyr)

df$distinct_parts_count <-
  sapply(parts, \(x) grepl(paste0("\\b", x, "\\b"), df$partcl)) |>
  rowSums()

df |>
  filter(distinct_parts_count >= 2)
#>   id                    partcl distinct_parts_count
#> 1  3 oh well yeah that's right                    4
#> 2  4       yeah I mean well oh                    3
#> 3  6            well yeah well                    2
#> 4 10 er well yeah that 's true                    3
```

Body:
I have a dataframe with speech data, like this:

df <- data.frame(
  id = 1:12,
  partcl = c("yeah yeah yeah absolutely", "well you know it 's", "oh well yeah that's right",
             "yeah I mean well oh", "well erm well Peter will be there", "well yeah well",
             "yes yes yes totally", "yeah yeah yeah yeah", "well well I did n't do it",
             "er well yeah that 's true", "oh hey where 's he gone?", "er"
))

and a vector with key words called parts:

parts <- c("yeah", "oh", "no", "well", "mm", "yes", "so", "right", "er", "like")

What I need to do is filter those rows with at least two distinct parts values. What I can do is filter those rows with at least two parts values, regardless of whether they're distinct or the same:

library(dplyr)
df %>%
  filter(
    str_count(partcl, paste0("\\b(", paste0(parts, collapse = "|"), ")\\b")) > 1
  )
  id                            partcl
1  1         yeah yeah yeah absolutely
2  3         oh well yeah that's right
3  4               yeah I mean well oh
4  5 well erm well Peter will be there
5  6                    well yeah well
6  7               yes yes yes totally
7  8               yeah yeah yeah yeah
8  9         well well I did n't do it
9 10         er well yeah that 's true

How can I assert that the matched partsbe distinct so that the result is this:

  id                            partcl
1  3         oh well yeah that's right
2  4               yeah I mean well oh
3  6                    well yeah well
4 10         er well yeah that 's true


问:
outh2 using external form to authenticate with google account
We have a system that is using its own authentication system and I need to make it use our Google Workspace accounts to integrate with Google SSO so that when the user gives their credentials to the webpage, it will be authenticated in both google account and on our web app account.

Google default workflow redirects the user to its own form, so we have the problem of the password not being passed to our server.

Crossed my mind the fact that this would be too insecure to exist, but remember that all users that would log in to our website would have an account created in a workplace totally managed by us.

how could I auth the user this way?

答:
Why not use "Sign-in with Google" -> OpenID Connect to access to the website. That way it will authenticate with Google.

Or add the website as a custom SAML application in the Admin console, and use Google as the IDP since the users will be provided by your organization.


问:
Angular Material Expansion Panel Header with Input
I have an angular 12 application using Angular Material components.  I have an Expansion Panel which in the header has an Input.

```<code><mat-expansion-panel class="mt-2 mat-elevation-z4" *ngFor="let segmentGroup of segmentGroups">
            <mat-expansion-panel-header>
                    <mat-form-field appearance="outline" class="w-25 tableInput">
                        <input matInput [(ngModel)]="segmentGroup.name" (change)="segmentGroup.isDirty = true" (click)="$event.stopPropagation();">
                    </mat-form-field>
                    <button mat-icon-button *ngIf="segmentGroup.isDirty" (click)="Save()">
                        <mat-icon>save</mat-icon>
                    </button>
            </mat-expansion-panel-header>
</code>```

I want top be able to edit the value that is within the Header.  Original issue was when you clicked into the Input it would expand and collapse the Expansion panel.  The onclick stop propagation fixed that issue.   However, the current issue is you cannot enter a space using the spacebar.  The spacebar causes the Expansion Panel to expand and collapse.  How can I prevent this behavior and allow spaces within the input.

答:
You can stop the spacebar event propagation by fetching the spacebar keydown-event and then using event.stopPropagation() to stop it from collapsing the mat-expansion:

<mat-form-field appearance="outline" class="w-25 tableInput">
          <input matInput [(ngModel)]="name" (click)="$event.stopPropagation();" (keydown)="handleSpacebar($event)">
</mat-form-field>
```
<pre class="lang-js prettyprint-override"><code>handleSpacebar(event) {
    if (event.keyCode === 32) {
      event.stopPropagation();
    }
   }
</code>```

or if you to do template only solution then you can directly do it in the template by binding to the keyDown event.

  <mat-form-field appearance="outline" class="w-25 tableInput">
          <input matInput [(ngModel)]="name"
           (click)="$event.stopPropagation()"
           (keydown.Space)="$event.stopImmediatePropagation()"
          >
  </mat-form-field>
```

Body:
I have an angular 12 application using Angular Material components.  I have an Expansion Panel which in the header has an Input.

<mat-expansion-panel class="mt-2 mat-elevation-z4" *ngFor="let segmentGroup of segmentGroups">
            <mat-expansion-panel-header>
                    <mat-form-field appearance="outline" class="w-25 tableInput">
                        <input matInput [(ngModel)]="segmentGroup.name" (change)="segmentGroup.isDirty = true" (click)="$event.stopPropagation();">
                    </mat-form-field>
                    <button mat-icon-button *ngIf="segmentGroup.isDirty" (click)="Save()">
                        <mat-icon>save</mat-icon>
                    </button>
            </mat-expansion-panel-header>

I want top be able to edit the value that is within the Header.  Original issue was when you clicked into the Input it would expand and collapse the Expansion panel.  The onclick stop propagation fixed that issue.   However, the current issue is you cannot enter a space using the spacebar.  The spacebar causes the Expansion Panel to expand and collapse.  How can I prevent this behavior and allow spaces within the input.

Body:
You can stop the spacebar event propagation by fetching the spacebar keydown-event and then using event.stopPropagation() to stop it from collapsing the mat-expansion:

<mat-form-field appearance="outline" class="w-25 tableInput">
          <input matInput [(ngModel)]="name" (click)="$event.stopPropagation();" (keydown)="handleSpacebar($event)">
</mat-form-field>

handleSpacebar(event) {
    if (event.keyCode === 32) {
      event.stopPropagation();
    }
   }

or if you to do template only solution then you can directly do it in the template by binding to the keyDown event.

  <mat-form-field appearance="outline" class="w-25 tableInput">
          <input matInput [(ngModel)]="name"
           (click)="$event.stopPropagation()"
           (keydown.Space)="$event.stopImmediatePropagation()"
          >
  </mat-form-field>


问:
Google OAuth Developer Verification form submitted but no response from google
I need google oauth for google+ login on my opencart store. My app is requesting the following scopes only and app is public.

https://googleapis.com/auth/plus.me

https://googleapis.com/auth/userinfo.profile

https://googleapis.com/auth/userinfo.email

These are not sensitive scopes and on my oauth consent screen I see the submit verification button is disabled and it says
Your changes don't require verification

Still customers see Unverified app screen (This app isn't verified)

I have also submitted oauth app verification form https://support.google.com/code/contact/oauth_app_verification . Its been more than a week not got any response from google.

Please suggest any way how to remove Unverified app screen for my customers?

答: scope parameter in the URL that starts with https://accounts.google.com/o/oauth2/auth?https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcontacts.readonly[other params here]</p>


问:
Start a powershell script at the end of Windows 10 installation?
I have a custom ISO image and I would like at the end of its installation, before logging in to the user, to run my PowerShell script.

I've seen some custom ISOs that do this. How is it done?

答:
Before capturing your WIM image, you can set up a script to run on first boot in a few different ways. There's a lot of detail and examples here to read: Add a custom script to Windows setup. I would recommend one of these options:

Simple CMD Create a script here: %WINDIR%\Setup\Scripts\SetupComplete.cmd. This script runs with local system permissions and starts immediately after the user sees the desktop.

More Complex Create an Unattend.xml file with the FirstLogonCommands\SynchronousCommand setting to run after the Out of Box Experience (OOBE) but before the user sees the desktop.

Powershell Create a scheduled task set to run once at startup, then copy your script to C:\Windows\Tasks\MyScript.ps1:

```<code># schedule to run at next startup
$trigger = New-ScheduledTaskTrigger -AtStartup

# first, it runs your script
$action1 = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-F "C:\Windows\Tasks\MyScript.ps1"'
# then it removes this task when done so it doesn't run again
$action2 = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-C Unregister-ScheduledTask -TaskName "MyTask" -Confirm:$false'

# run as local admin
$principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest

# finally, register everything and you're done!
Register-ScheduledTask -TaskName 'MyTask' -Action $action -Trigger $trigger -Principal $principal -Description 'My task to run after first startup' -ErrorAction Stop
</code>```

Capture wim after doing one of the above, and you should be set.

Body:
Before capturing your WIM image, you can set up a script to run on first boot in a few different ways. There's a lot of detail and examples here to read: Add a custom script to Windows setup. I would recommend one of these options:

Simple CMD Create a script here: %WINDIR%\Setup\Scripts\SetupComplete.cmd. This script runs with local system permissions and starts immediately after the user sees the desktop.

More Complex Create an Unattend.xml file with the FirstLogonCommands\SynchronousCommand setting to run after the Out of Box Experience (OOBE) but before the user sees the desktop.

Powershell Create a scheduled task set to run once at startup, then copy your script to C:\Windows\Tasks\MyScript.ps1:

# schedule to run at next startup
$trigger = New-ScheduledTaskTrigger -AtStartup

# first, it runs your script
$action1 = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-F "C:\Windows\Tasks\MyScript.ps1"'
# then it removes this task when done so it doesn't run again
$action2 = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-C Unregister-ScheduledTask -TaskName "MyTask" -Confirm:$false'

# run as local admin
$principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest

# finally, register everything and you're done!
Register-ScheduledTask -TaskName 'MyTask' -Action $action -Trigger $trigger -Principal $principal -Description 'My task to run after first startup' -ErrorAction Stop

Capture wim after doing one of the above, and you should be set.


问:
Why do I get strange result when & (anding) bits on __int64 variable?
Here is the code:

```<code>#include <iostream>

using namespace std;

template<class T>
void printbinary3(T num){
   for(int i = sizeof(T) * 8 - 1; i >= 0 ; --i) {
      if((1 << i) &  num)
         cout << "1";
      else
         cout << "0";
   }
   cout << endl;
}

int main ()
{
   char a = 1;
   short b = 1;
   int c = 1;
   long d = 1;
   __int64 e = 1;
   unsigned __int64 f = 1;

   printbinary3(a);
   printbinary3(b);
   printbinary3(c);
   printbinary3(d);
   printbinary3(e);
   printbinary3(f);
   return 0;
}
</code>```

Here is the output:

```
00000001
0000000000000001
00000000000000000000000000000001
00000000000000000000000000000001
0000000000000000000000000000000100000000000000000000000000000001
```

When compiling I get this error for the unsigned __int64 variable - f.

```<code>1> : warning C4334: '<<' : result of 32-bit shift implicitly converted to
     64 bits (was 64-bit shift intended?)
1>   xx.cpp(66) : see reference to function template instantiation
     'void printbinary3<unsigned __int64>(T)' being compiled
</code>```

Why am I not seeing

```
0000000000000000000000000000000000000000000000000000000000000001
```

as the output for the 64 bit integer?

Angus

答:
Read the warnings and fix the code.

In C++0x or as an extension in g++'s current C++ implementation , 64 bit unsigned integer literals need an ull postfix: 50ull. 64 bit unsigned integer need be declared unsigned long long.

Body:
Here is the code:

#include <iostream>

using namespace std;

template<class T>
void printbinary3(T num){
   for(int i = sizeof(T) * 8 - 1; i >= 0 ; --i) {
      if((1 << i) &  num)
         cout << "1";
      else
         cout << "0";
   }
   cout << endl;
}

int main ()
{
   char a = 1;
   short b = 1;
   int c = 1;
   long d = 1;
   __int64 e = 1;
   unsigned __int64 f = 1;

   printbinary3(a);
   printbinary3(b);
   printbinary3(c);
   printbinary3(d);
   printbinary3(e);
   printbinary3(f);
   return 0;
}

Here is the output:

00000001
0000000000000001
00000000000000000000000000000001
00000000000000000000000000000001
0000000000000000000000000000000100000000000000000000000000000001

When compiling I get this error for the unsigned __int64 variable - f.

1> : warning C4334: '<<' : result of 32-bit shift implicitly converted to
     64 bits (was 64-bit shift intended?)
1>   xx.cpp(66) : see reference to function template instantiation
     'void printbinary3<unsigned __int64>(T)' being compiled

Why am I not seeing

0000000000000000000000000000000000000000000000000000000000000001

as the output for the 64 bit integer?

Angus


问:
Unable to get stats for Caffeine cache (Spring 5)
I got stuck on a (hopefully) very simple problem. I added a Caffeine cache to my Spring application and this cache works well.
Now I tried to get the statistics for this cache, but I can't find a way to get to the right methods...

```<code>import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
@EnableCaching
public class CachingConfig {

    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager("bin");
        cacheManager.setCaffeine(Caffeine.newBuilder()
                .maximumSize(10000)
                .expireAfterWrite(1, TimeUnit.DAYS)
                .recordStats());
        return cacheManager;
    }

}
</code>```

How can I get stats for this cache?

答:
Inject CacheManager and then just get it.

```<code>CacheStats stats = ((CaffeineCache) cacheManager.getCache("bin")).getNativeCache().stats();
</code>```

Works for me.

Body:
I got stuck on a (hopefully) very simple problem. I added a Caffeine cache to my Spring application and this cache works well.
Now I tried to get the statistics for this cache, but I can't find a way to get to the right methods...

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
@EnableCaching
public class CachingConfig {

    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager("bin");
        cacheManager.setCaffeine(Caffeine.newBuilder()
                .maximumSize(10000)
                .expireAfterWrite(1, TimeUnit.DAYS)
                .recordStats());
        return cacheManager;
    }

}

How can I get stats for this cache?

Body:
Inject CacheManager and then just get it.

CacheStats stats = ((CaffeineCache) cacheManager.getCache("bin")).getNativeCache().stats();

Works for me.


问:
How to sum values of one column, based on two conditions, grouped by another column value, in R?
I have a dataset that includes many "transects", and a multiple "transects" comprise a "plane" (e.g. Plane P1 = Transect T1 + Transect T2)

The current data structure (see example below) has the length of each transect repeated in the column "transect length" for each sample that was collected in the transect. I need to sum the transect lengths to get the "plane length" for EACH plane.

Here is what the data structure I've been given looks like:

Plane name
Transect name
Transect length
Sample

P1
T1
1002
x

P1
T1
1002
y

P1
T2
1034
z

P1
T2
1034
a

P1
T2
1034
b

P2
T3
1222
c

P2
T3
1222
d

P2
T4
1324
e

I added an "index" column, thinking there must be some way I can add the transect lengths when the index for that row = 1.

```<code>data3 <- data2 %>%
  group_by(transect)%>%
  mutate(index = seq(n())) %>%
  ungroup() %>%
</code>```

Table showing the added index column:

Plane name
Transect name
Transect length
Sample
Index

P1
T1
1002
x
1

P1
T1
1002
y
2

P1
T2
1034
z
1

P1
T2
1034
a
2

P1
T2
1034
b
3

P2
T3
1222
c
1

P2
T3
1222
d
2

P2
T4
1324
e
1

But now I am stuck on how to add only the transect lengths with index = 1 for a certain plane, and iterate over all the planes...

So for example, in the end, what I need it to look like is this:

Plane name
Transect name
Transect length
Sample
Index
Plane length

P1
T1
1002
x
1
2036

P1
T1
1002
y
2
2036

P1
T2
1034
z
1
2036

P1
T2
1034
a
2
2036

P1
T2
1034
b
3
2036

P2
T3
1222
c
1
2546

P2
T3
1222
d
2
2546

P2
T4
1324
e
1
2546

Notice the plane length for plane P1 is the sum of only the T1 transect lengths that have index = 1.
So: 1002 + 1034 = 2036, NOT 1002 + 1002 + 1034 + 1034 + 1034 = 5106.

I tried several variations of code using mutate, sum, summarize, etc. with no luck:

```<code>plane_lengths <- data3 %>%
  mutate(plane_length = sum(transect_length[index ==1]))
</code>```

^ this one seems to do nothing. :(

```<code>plane_lengths <- data3 %>% group_by(plane_name) %>% summarize(plane_length = sum(transect_length))
</code>```

^ this one just adds every value of transect length (all index values, not just index = 1)

Is there some way to modify the code above to take only values for transect length where the index = 1?

I am still a bit new to R, and I really appreciate any help I can get!!! Thank you.

答:
After creating the 'index', change the grouping to 'Planename' before we create the 'PlaneLength' column

```<code>library(dplyr)
data2 %>%
   group_by(Transectname) %>%
   mutate(index = row_number()) %>%
   group_by(Planename) %>%
   mutate(PlaneLength = sum(Transectlength[index == 1])) %>%
   ungroup
</code>```

-output

```<code># A tibble: 8 × 6
  Planename Transectname Transectlength Sample index PlaneLength
  <chr>     <chr>                 <int> <chr>  <int>       <int>
1 P1        T1                     1002 x          1        2036
2 P1        T1                     1002 y          2        2036
3 P1        T2                     1034 z          1        2036
4 P1        T2                     1034 a          2        2036
5 P1        T2                     1034 b          3        2036
6 P2        T3                     1222 c          1        2546
7 P2        T3                     1222 d          2        2546
8 P2        T4                     1324 e          1        2546
</code>```

We may also use with_groups so that it won't create the group attrribute

```<code>data2 %>%
  with_groups(Transectname, mutate, index = row_number()) %>%
  with_groups(Planename, mutate,
    PlaneLength = sum(Transectlength[index == 1]))
</code>```

-output

```<code> Planename Transectname Transectlength Sample index PlaneLength
1        P1           T1           1002      x     1        2036
2        P1           T1           1002      y     2        2036
3        P1           T2           1034      z     1        2036
4        P1           T2           1034      a     2        2036
5        P1           T2           1034      b     3        2036
6        P2           T3           1222      c     1        2546
7        P2           T3           1222      d     2        2546
8        P2           T4           1324      e     1        2546
</code>```

data

```<code>data2 <- structure(list(Planename = c("P1", "P1", "P1", "P1", "P1", "P2",
"P2", "P2"), Transectname = c("T1", "T1", "T2", "T2", "T2", "T3",
"T3", "T4"), Transectlength = c(1002L, 1002L, 1034L, 1034L, 1034L,
1222L, 1222L, 1324L), Sample = c("x", "y", "z", "a", "b", "c",
"d", "e")), class = "data.frame", row.names = c(NA, -8L))
</code>```

Body:
I have a dataset that includes many "transects", and a multiple "transects" comprise a "plane" (e.g. Plane P1 = Transect T1 + Transect T2)

The current data structure (see example below) has the length of each transect repeated in the column "transect length" for each sample that was collected in the transect. I need to sum the transect lengths to get the "plane length" for EACH plane.

Here is what the data structure I've been given looks like:

Plane name
Transect name
Transect length
Sample

P1
T1
1002
x

P1
T1
1002
y

P1
T2
1034
z

P1
T2
1034
a

P1
T2
1034
b

P2
T3
1222
c

P2
T3
1222
d

P2
T4
1324
e

I added an "index" column, thinking there must be some way I can add the transect lengths when the index for that row = 1.

data3 <- data2 %>%
  group_by(transect)%>%
  mutate(index = seq(n())) %>%
  ungroup() %>%

Table showing the added index column:

Plane name
Transect name
Transect length
Sample
Index

P1
T1
1002
x
1

P1
T1
1002
y
2

P1
T2
1034
z
1

P1
T2
1034
a
2

P1
T2
1034
b
3

P2
T3
1222
c
1

P2
T3
1222
d
2

P2
T4
1324
e
1

But now I am stuck on how to add only the transect lengths with index = 1 for a certain plane, and iterate over all the planes...

So for example, in the end, what I need it to look like is this:

Plane name
Transect name
Transect length
Sample
Index
Plane length

P1
T1
1002
x
1
2036

P1
T1
1002
y
2
2036

P1
T2
1034
z
1
2036

P1
T2
1034
a
2
2036

P1
T2
1034
b
3
2036

P2
T3
1222
c
1
2546

P2
T3
1222
d
2
2546

P2
T4
1324
e
1
2546

Notice the plane length for plane P1 is the sum of only the T1 transect lengths that have index = 1.
So: 1002 + 1034 = 2036, NOT 1002 + 1002 + 1034 + 1034 + 1034 = 5106.

I tried several variations of code using mutate, sum, summarize, etc. with no luck:

plane_lengths <- data3 %>%
  mutate(plane_length = sum(transect_length[index ==1]))

^ this one seems to do nothing. :(

plane_lengths <- data3 %>% group_by(plane_name) %>% summarize(plane_length = sum(transect_length))

^ this one just adds every value of transect length (all index values, not just index = 1)

Is there some way to modify the code above to take only values for transect length where the index = 1?

I am still a bit new to R, and I really appreciate any help I can get!!! Thank you.

Body:
After creating the 'index', change the grouping to 'Planename' before we create the 'PlaneLength' column

library(dplyr)
data2 %>%
   group_by(Transectname) %>%
   mutate(index = row_number()) %>%
   group_by(Planename) %>%
   mutate(PlaneLength = sum(Transectlength[index == 1])) %>%
   ungroup

-output

# A tibble: 8 × 6
  Planename Transectname Transectlength Sample index PlaneLength
  <chr>     <chr>                 <int> <chr>  <int>       <int>
1 P1        T1                     1002 x          1        2036
2 P1        T1                     1002 y          2        2036
3 P1        T2                     1034 z          1        2036
4 P1        T2                     1034 a          2        2036
5 P1        T2                     1034 b          3        2036
6 P2        T3                     1222 c          1        2546
7 P2        T3                     1222 d          2        2546
8 P2        T4                     1324 e          1        2546

We may also use with_groups so that it won't create the group attrribute

data2 %>%
  with_groups(Transectname, mutate, index = row_number()) %>%
  with_groups(Planename, mutate,
    PlaneLength = sum(Transectlength[index == 1]))

-output

 Planename Transectname Transectlength Sample index PlaneLength
1        P1           T1           1002      x     1        2036
2        P1           T1           1002      y     2        2036
3        P1           T2           1034      z     1        2036
4        P1           T2           1034      a     2        2036
5        P1           T2           1034      b     3        2036
6        P2           T3           1222      c     1        2546
7        P2           T3           1222      d     2        2546
8        P2           T4           1324      e     1        2546

data

data2 <- structure(list(Planename = c("P1", "P1", "P1", "P1", "P1", "P2",
"P2", "P2"), Transectname = c("T1", "T1", "T2", "T2", "T2", "T3",
"T3", "T4"), Transectlength = c(1002L, 1002L, 1034L, 1034L, 1034L,
1222L, 1222L, 1324L), Sample = c("x", "y", "z", "a", "b", "c",
"d", "e")), class = "data.frame", row.names = c(NA, -8L))


问:
How to get all objects inside an array JSON in a C# controller
How do I retrieve all of the [names] that are part of the object called [items] in this JSON scenario below in C# ?

I am using a shopping cart api and want to show the customer all of the items listed off that were part of the order once they get to the thank you page. The parent object I am looking at in the api is called items and it has child object data such as price of each item, name of each item and product image of each item etc.....

In my controller I was doing this below when I only needed to retrieve simple info like the order only has 1 invoiceNumber, 1 payment method, 1 shipping method, 1 promo code etc.. This code below works and gets me that data in that simple scenario below.

```<code> using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            var obj = JObject.Parse(result);

            //Order Info
            string invoiceNumber = (string)obj["invoiceNumber"];
            string email = (string)obj["email"];
            string paymentMethod = (string)obj["paymentMethod"];
            string shippingMethod = (string)obj["shippingMethod"];

            //Discount info
            string amountSaved = (string)obj["discounts"][0]["amountSaved"];
            string promoCode = (string)obj["discounts"][0]["code"];
</code>```

But now I need to tap into an object called [items] (the data for the items that were part of the order) that is going to have many names of items depending on the number of individual items that were part of the customer order. This is what I attempted but then realized that it would only return one record based on what number I used inside the brackets.

```<code>string items = (string)obj["items"][0]["name"]; //This returned the product at index 0
string items = (string)obj["items"][1]["name"]; //This returned the product at index 1
string items = (string)obj["items"][2]["name"]; //This returned the product at index 2
</code>```

How do I write the syntax so that I can grab ALL of the name objects that currently reside in the item object for exaple? I know it has something to do with deserialize objects and list but I do not know the syntax and how to approach.

Any suggestions on how I can get this done?

答:
You can use Newtonsoft json package to convert an object into JSON array.
Refer below link

http://www.newtonsoft.com/json/help/html/SerializingJSON.htm

Body:
How do I retrieve all of the [names] that are part of the object called [items] in this JSON scenario below in C# ?

I am using a shopping cart api and want to show the customer all of the items listed off that were part of the order once they get to the thank you page. The parent object I am looking at in the api is called items and it has child object data such as price of each item, name of each item and product image of each item etc.....

In my controller I was doing this below when I only needed to retrieve simple info like the order only has 1 invoiceNumber, 1 payment method, 1 shipping method, 1 promo code etc.. This code below works and gets me that data in that simple scenario below.

 using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            var obj = JObject.Parse(result);

            //Order Info
            string invoiceNumber = (string)obj["invoiceNumber"];
            string email = (string)obj["email"];
            string paymentMethod = (string)obj["paymentMethod"];
            string shippingMethod = (string)obj["shippingMethod"];

            //Discount info
            string amountSaved = (string)obj["discounts"][0]["amountSaved"];
            string promoCode = (string)obj["discounts"][0]["code"];

But now I need to tap into an object called [items] (the data for the items that were part of the order) that is going to have many names of items depending on the number of individual items that were part of the customer order. This is what I attempted but then realized that it would only return one record based on what number I used inside the brackets.

string items = (string)obj["items"][0]["name"]; //This returned the product at index 0
string items = (string)obj["items"][1]["name"]; //This returned the product at index 1
string items = (string)obj["items"][2]["name"]; //This returned the product at index 2

How do I write the syntax so that I can grab ALL of the name objects that currently reside in the item object for exaple? I know it has something to do with deserialize objects and list but I do not know the syntax and how to approach.

Any suggestions on how I can get this done?


问:
How To Appropriately Type a Variable Using React's useState
How would I appropriately type variables in useState?

Below, basically alert needs to be "success" | "warning" | "error" | "info"

```<code>const [alertValue, setAlertValue] = useState("error");

<TextField
   label="Error State"
   message="this is an ERROR message"
   alert={alertValue} // error: Type 'string' is not assignable to type "success" | "warning" | "error" | "info";
   onChange={handleChange}
/>

</code>```

答:
The useState hook is a generic function. You can supply the type when you call it. For example:

```<code>type AlertStatus = "success" | "warning" | "error" | "info"

const [alertValue, setAlertValue] = useState<AlertStatus>("error");
</code>```

You should use the same property type defined for the alert property of the TextField component.

Body:
How would I appropriately type variables in useState?

Below, basically alert needs to be "success" | "warning" | "error" | "info"

const [alertValue, setAlertValue] = useState("error");

<TextField
   label="Error State"
   message="this is an ERROR message"
   alert={alertValue} // error: Type 'string' is not assignable to type "success" | "warning" | "error" | "info";
   onChange={handleChange}
/>

Body:
The useState hook is a generic function. You can supply the type when you call it. For example:

type AlertStatus = "success" | "warning" | "error" | "info"

const [alertValue, setAlertValue] = useState<AlertStatus>("error");

You should use the same property type defined for the alert property of the TextField component.


问:
How do I reduce the nex lines of Ruby code?
```<code>    def route_action(action)
    case action
    when 1 then @meals_controller.add
    when 2 then @meals_controller.list
    when 3 then @meals_controller.edit
    when 4 then @meals_controller.delete
    when 5 then @customers_controller.add
    when 6 then @customers_controller.list
    when 7 then @customers_controller.edit
    when 8 then @customers_controller.delete
    when 0 then stop
    else
      puts "Please press 1, 2, 3, 4, 5, 6, 7, 8 or 0"
    end
  end
</code>```

So I want to reduce this case when is there another way of implementing this?

答:
Heads up, this is just a general suggestion on how to use a bit of Ruby meta-programming to get out of the tangle of having to declare a long method full of case business logic. It won't fit perfectly and will need to extra work to do, for instance, the "quit" logic.

Also. I'll reiterate what's been said in one of the direct answers to the post. Your case solution is VERY clear. It's good code and we shouldn't jump into messier thing just to comply to the all-mighty gods of the ruby stylesheet guidelines. Just because a method is under 10 lines, it doesn't make it automatically better than an 11 (or... hell 40) lines one.

Now...

Here's a meta-programming suggestion...

You can define a hash on a constant to hold the variables needed for the business logic:

ROUTES = [
  { action: :add,  controller: :meals, description: "Add a meal" },
  { action: :list, controller: :meals, description: "List all meals" },
  { action: :add,  controller: :customers, description: "Add a customers" },
  { action: :list, controller: :customers, description: "List all customers" },
]
```
<p>You can then create a method that dispatches the user to the correct controller action using the hash info:</p>
<pre class="lang-rb prettyprint-override"><code>def dispatch(action_index)
  route_action     = ROUTES[action_index][:action]
  route_controller = ROUTES[action_index][:controller]
  instance_variable_get("@#{route_controller}_controller").send(route_action)
end
</code>```

It's very easy with the hash to iterate over it to display the route descriptions:

def display_options
  ROUTES.each_with_index do |route, index|
    puts "#{index + 1}. #{route[:description]}"
  end
end
```

You can at some point in your code dispatch the user to the relevant controller action with dispatch(gets.chomp.to_i - 1).

Cool thing about the hash is that you can always add more routes to it by just adding a single line.

Body:
    def route_action(action)
    case action
    when 1 then @meals_controller.add
    when 2 then @meals_controller.list
    when 3 then @meals_controller.edit
    when 4 then @meals_controller.delete
    when 5 then @customers_controller.add
    when 6 then @customers_controller.list
    when 7 then @customers_controller.edit
    when 8 then @customers_controller.delete
    when 0 then stop
    else
      puts "Please press 1, 2, 3, 4, 5, 6, 7, 8 or 0"
    end
  end

So I want to reduce this case when is there another way of implementing this?

Body:
Heads up, this is just a general suggestion on how to use a bit of Ruby meta-programming to get out of the tangle of having to declare a long method full of case business logic. It won't fit perfectly and will need to extra work to do, for instance, the "quit" logic.

Also. I'll reiterate what's been said in one of the direct answers to the post. Your case solution is VERY clear. It's good code and we shouldn't jump into messier thing just to comply to the all-mighty gods of the ruby stylesheet guidelines. Just because a method is under 10 lines, it doesn't make it automatically better than an 11 (or... hell 40) lines one.

Now...

Here's a meta-programming suggestion...

You can define a hash on a constant to hold the variables needed for the business logic:

ROUTES = [
  { action: :add,  controller: :meals, description: "Add a meal" },
  { action: :list, controller: :meals, description: "List all meals" },
  { action: :add,  controller: :customers, description: "Add a customers" },
  { action: :list, controller: :customers, description: "List all customers" },
]

You can then create a method that dispatches the user to the correct controller action using the hash info:

def dispatch(action_index)
  route_action     = ROUTES[action_index][:action]
  route_controller = ROUTES[action_index][:controller]
  instance_variable_get("@#{route_controller}_controller").send(route_action)
end

It's very easy with the hash to iterate over it to display the route descriptions:

def display_options
  ROUTES.each_with_index do |route, index|
    puts "#{index + 1}. #{route[:description]}"
  end
end

You can at some point in your code dispatch the user to the relevant controller action with dispatch(gets.chomp.to_i - 1).

Cool thing about the hash is that you can always add more routes to it by just adding a single line.


问:
Word 2016 Error copying shape to header. Method 'Paste' of object 'Range' failed (80010108)
I have Word 2016 MSO (16.0.4266.1001), 64-bit

I have a document that has two sections with different headers. In the first section, in the header, there is a shape with text that needs to be copied into the header of the second section.

In Word 2010 I had some code that worked.

```<code>Sub TEST()
    Set hHeaderRange = ActiveDocument.Sections(2).Headers(wdHeaderFooterPrimary).Range
    ActiveDocument.Sections(1).Headers(wdHeaderFooterFirstPage).Shapes.Item(1).Select
    Selection.Copy
    hHeaderRange.Paste
End Sub
</code>```

But in Word 2016, this code gives an error (see below) on the line hHeaderRange.Paste

When you click the End button, Word crashes and restarts in an attempt to restore the last saved version of the document.
Moreover, if you stop the code before the line hHeaderRange.Paste, then you can go to the header of the second section and click Paste, and the figure will be inserted.
I also tried PasteSpecial, same thing.
If you specify in the code to insert a shape on the page, there are no problems.

Can anyone please tell me how to solve this problem?

The task is simple, you need to copy the shape from the header of one section to the header of another section.

The strangest thing is that Word is crashing!

If anyone has other versions of Word 2016 (not 16.0.4266.1001) or Word 2019, please check the code.

答:
I can confirm that the code you are using causes Word to crash (Version 2201 Build 16.0.14827.20158)

As there is no other content in the header you are copying from there is a workaround that is actually better than your original method. A Range object has a FormattedText property (read/write) that can be used instead of copying and pasting. So your code should be:

```<code>Sub TEST()
    Dim hdr1 As Range, hdr2 As Range
    Set hdr2 = ActiveDocument.Sections(2).Headers(wdHeaderFooterPrimary).Range
    Set hdr1 = ActiveDocument.Sections(1).Headers(wdHeaderFooterFirstPage).Range
    hdr2.FormattedText = hdr1.FormattedText
End Sub
</code>```

Body:
I have Word 2016 MSO (16.0.4266.1001), 64-bit

I have a document that has two sections with different headers. In the first section, in the header, there is a shape with text that needs to be copied into the header of the second section.

In Word 2010 I had some code that worked.

Sub TEST()
    Set hHeaderRange = ActiveDocument.Sections(2).Headers(wdHeaderFooterPrimary).Range
    ActiveDocument.Sections(1).Headers(wdHeaderFooterFirstPage).Shapes.Item(1).Select
    Selection.Copy
    hHeaderRange.Paste
End Sub

But in Word 2016, this code gives an error (see below) on the line hHeaderRange.Paste

When you click the End button, Word crashes and restarts in an attempt to restore the last saved version of the document.
Moreover, if you stop the code before the line hHeaderRange.Paste, then you can go to the header of the second section and click Paste, and the figure will be inserted.
I also tried PasteSpecial, same thing.
If you specify in the code to insert a shape on the page, there are no problems.

Can anyone please tell me how to solve this problem?

The task is simple, you need to copy the shape from the header of one section to the header of another section.

The strangest thing is that Word is crashing!

If anyone has other versions of Word 2016 (not 16.0.4266.1001) or Word 2019, please check the code.

Body:
I can confirm that the code you are using causes Word to crash (Version 2201 Build 16.0.14827.20158)

As there is no other content in the header you are copying from there is a workaround that is actually better than your original method. A Range object has a FormattedText property (read/write) that can be used instead of copying and pasting. So your code should be:

Sub TEST()
    Dim hdr1 As Range, hdr2 As Range
    Set hdr2 = ActiveDocument.Sections(2).Headers(wdHeaderFooterPrimary).Range
    Set hdr1 = ActiveDocument.Sections(1).Headers(wdHeaderFooterFirstPage).Range
    hdr2.FormattedText = hdr1.FormattedText
End Sub


问:
Is the Grails 3.3.2 dependency on tomcat-embed-logging-log4j-8.5.2.jar an issue due to recent log4j vulnerabilities?
I have 5 grails servers built on 3.3.2 and they all have this dependency:</p>
```<code>+--- org.grails:grails-plugin-rest: -> 3.3.2
|    +--- org.grails:grails-plugin-datasource:3.3.2
|    |    \--- org.apache.tomcat.embed:tomcat-embed-logging-log4j:8.5.2
</code>```

答:
Is the Grails 3.3.2 dependency on tomcat-embed-logging-log4j-8.5.2.jar
an issue due to recent log4j vulnerabilities?

No.  Your app could still have a dependency on something that brings the vulnerability in, but tomcat-embed-logging-log4j-8.5.2.jar does not.

Body:
I have 5 grails servers built on 3.3.2 and they all have this dependency:

+--- org.grails:grails-plugin-rest: -> 3.3.2
|    +--- org.grails:grails-plugin-datasource:3.3.2
|    |    \--- org.apache.tomcat.embed:tomcat-embed-logging-log4j:8.5.2


问:
Row wise by group sum with conditions
The aim is for an ID to be treated as a group and sum the rows of the distinct ID based on a set of conditions row wise.

The data is time dependent for any item_ID, we are interested to see if at the check_date of a given item_ID, do all item_IDs (including the row selected) of that ID group have start_dates less than the given item_ID AND the fail_dates are either greater than the check_date of the given item_ID OR NA. When these conditions are met, sum the value column whilst maintaining the ID grouping.

Using the example below and starting at row 1 then iterating down rows, sum the row values of an ID's item_IDs when either:

df$fail_date == NA AND df$check_date[1] >= start_date, OR

df$fail_date > df$check_date[1] AND df$check_date[1] >= start_date

where df$start_date[1] is the first row of check_date which gets iterated down rows

Example data:

```<code>df <- data.frame(ID = c(1,1,1,1,1,1,2,2,2,3,3,3,3,3,3,3,3),
                 start_date = c(44107, 44107, 44107, 44226, 44233, 44289, 44107, 44107, 44226, 44107, 44107, 44107, 44107, 44233, 44233, 44233, 44233),
                 check_date = c(44121, 44121, 44121, 44240, 44247, 44303, 44121, 44121, 44240, 44121, 44121, 44121, 44121, 44247, 44247, 44247, 44247),
                 fail_date = c(NA, NA, 44114, NA, 44328, NA, 44207, 44196, NA, NA, NA, NA, NA, NA, NA, NA, NA),
                 value = c(30, 25, 60, 20, 30, 15, 50, 20, 15, 30, 25, 20, 30, 20, 50, 20, 15))
</code>```

The desired output would be:

```<code>   ID   item_ID start_date check_date fail_date value conditional_sum
1   1  B874_20K      44107      44121        NA    30              55
2   1 BB849_21E      44107      44121        NA    25              55
3   1 BB842_21E      44107      44121     44114    60              55
4   1  B873_20K      44226      44240        NA    20             105
5   1  B875_21E      44233      44247     44328    30             105
6   1 BB848_20K      44289      44303        NA    15             120
7   2  BD49_21K      44107      44121     44207    50              70
8   2  BU44_20J      44107      44121     44196    20              70
9   2  DD93_21E      44226      44240        NA    15              15
10  3  B874_20K      44107      44121        NA    30             105
11  3 BB849_21E      44107      44121        NA    25             105
12  3  B873_20K      44107      44121        NA    20             105
13  3  B875_21E      44107      44121        NA    30             105
14  3  B873_20K      44233      44247        NA    20             210
15  3  BD49_21K      44233      44247        NA    50             210
16  3  BU44_20J      44233      44247        NA    20             210
17  3 BB848_20K      44233      44247        NA    15             210
</code>```

I'm really not sure how to crack this, my usual toolkit of dplyr group_by and summarise doesn't fit the bill. Any direction is greatly appreciated!

答:
Alternatively, a concise solution with runner in the tidyverse:

Solution

```<code>library(tidyverse)
library(runner)

# ...
# Code to generate 'df'.
# ...

df %>%
  # Work within each 'ID' group.
  group_by(ID) %>%

  # Use 'runner' to go downwards from row to row.
  mutate(conditional_sum = runner(check_date, function(x) {
    # Use the check date for the latest row.
    cur_check_date <- last(x)

    # Sum only those 'value's whose rows meet the conditions.
    sum(value[
      cur_check_date >= start_date & (is.na(fail_date) | fail_date > cur_check_date)
    ])
  }))
</code>```

Result

Given a df like the one reproduced here

```<code>df <- structure(
  list(
    ID = c(1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3),
    item_ID = c(
      "B874_20K", "BB849_21E", "BB842_21E", "B873_20K", "B875_21E", "BB848_20K",
      "BD49_21K", "BU44_20J", "DD93_21E", "B874_20K", "BB849_21E", "B873_20K",
      "B875_21E", "B873_20K", "BD49_21K", "BU44_20J", "BB848_20K"
    ),
    start_date = c(
      44107, 44107, 44107, 44226, 44233, 44289, 44107, 44107, 44226, 44107,
      44107, 44107, 44107, 44233, 44233, 44233, 44233
    ),
    check_date = c(
      44121, 44121, 44121, 44240, 44247, 44303, 44121, 44121, 44240, 44121,
      44121, 44121, 44121, 44247, 44247, 44247, 44247
    ),
    fail_date = c(
      NA, NA, 44114, NA, 44328, NA, 44207, 44196, NA, NA, NA, NA, NA, NA, NA,
      NA, NA
    ),
    value = c(
      30, 25, 60, 20, 30, 15, 50, 20, 15, 30, 25, 20, 30, 20, 50, 20, 15
    )
  ),
  row.names = c(NA, -17L),
  class = "data.frame"
)
</code>```

this solution should yield the following result:

```<code># A tibble: 17 x 7
# Groups:   ID [3]
      ID item_ID   start_date check_date fail_date value contidional_sum
   <dbl> <chr>          <dbl>      <dbl>     <dbl> <dbl>           <dbl>
 1     1 B874_20K       44107      44121        NA    30              55
 2     1 BB849_21E      44107      44121        NA    25              55
 3     1 BB842_21E      44107      44121     44114    60              55
 4     1 B873_20K       44226      44240        NA    20             105
 5     1 B875_21E       44233      44247     44328    30             105
 6     1 BB848_20K      44289      44303        NA    15             120
 7     2 BD49_21K       44107      44121     44207    50              70
 8     2 BU44_20J       44107      44121     44196    20              70
 9     2 DD93_21E       44226      44240        NA    15              15
10     3 B874_20K       44107      44121        NA    30             105
11     3 BB849_21E      44107      44121        NA    25             105
12     3 B873_20K       44107      44121        NA    20             105
13     3 B875_21E       44107      44121        NA    30             105
14     3 B873_20K       44233      44247        NA    20             210
15     3 BD49_21K       44233      44247        NA    50             210
16     3 BU44_20J       44233      44247        NA    20             210
17     3 BB848_20K      44233      44247        NA    15             210
</code>```

Benchmarking

It appears this approach is roughly 7 times faster than the existing solution by @MichaelDewar

```<code>library(microbenchmark)

microbenchmark(
  michael = {
    df_no_na <- df %>% replace_na(list(fail_date = max(df$check_date) + 1))

    conditional_sum_by_ID_and_check_date <- function(this_ID, this_check_date){
      df_no_na %>%
        filter(ID == this_ID,
               fail_date > this_check_date,
               start_date <= this_check_date) %>%
        summarize(conditional_sum = sum(value)) %>%
        pull()
    }

    df %>%
      distinct(ID, check_date) %>%
      mutate(conditional_sum = map2_dbl(ID, check_date, conditional_sum_by_ID_and_check_date)) %>%
      right_join(df, by = c("ID", "check_date"))
  },
  greg = {
    df %>%
      group_by(ID) %>%
      mutate(conditional_sum = runner(check_date, function(x) {
        cur_check_date <- last(x)
        sum(value[
          cur_check_date >= start_date & (is.na(fail_date) | fail_date > cur_check_date)
        ])
      }))
  }
)
</code>```

as seen in the benchmarks for times = 100 evaluations apiece:

```<code>Unit: milliseconds
    expr     min       lq      mean   median       uq      max neval
 michael 17.2701 18.37395 21.964745 18.77340 22.27915 147.3653   100
    greg  2.4107  2.70395  3.288304  2.92825  3.28625   8.9233   100
</code>```

Note

The relative performance might change for a dataset much larger than df, where I suspect the *_join()s will prove more costly.

Title: Row wise by group sum with conditions

Body:
The aim is for an ID to be treated as a group and sum the rows of the distinct ID based on a set of conditions row wise.

The data is time dependent for any item_ID, we are interested to see if at the check_date of a given item_ID, do all item_IDs (including the row selected) of that ID group have start_dates less than the given item_ID AND the fail_dates are either greater than the check_date of the given item_ID OR NA. When these conditions are met, sum the value column whilst maintaining the ID grouping.

Using the example below and starting at row 1 then iterating down rows, sum the row values of an ID's item_IDs when either:

df$fail_date == NA AND df$check_date[1] >= start_date, OR

df$fail_date > df$check_date[1] AND df$check_date[1] >= start_date

where df$start_date[1] is the first row of check_date which gets iterated down rows

Example data:

df <- data.frame(ID = c(1,1,1,1,1,1,2,2,2,3,3,3,3,3,3,3,3),
                 start_date = c(44107, 44107, 44107, 44226, 44233, 44289, 44107, 44107, 44226, 44107, 44107, 44107, 44107, 44233, 44233, 44233, 44233),
                 check_date = c(44121, 44121, 44121, 44240, 44247, 44303, 44121, 44121, 44240, 44121, 44121, 44121, 44121, 44247, 44247, 44247, 44247),
                 fail_date = c(NA, NA, 44114, NA, 44328, NA, 44207, 44196, NA, NA, NA, NA, NA, NA, NA, NA, NA),
                 value = c(30, 25, 60, 20, 30, 15, 50, 20, 15, 30, 25, 20, 30, 20, 50, 20, 15))

The desired output would be:

   ID   item_ID start_date check_date fail_date value conditional_sum
1   1  B874_20K      44107      44121        NA    30              55
2   1 BB849_21E      44107      44121        NA    25              55
3   1 BB842_21E      44107      44121     44114    60              55
4   1  B873_20K      44226      44240        NA    20             105
5   1  B875_21E      44233      44247     44328    30             105
6   1 BB848_20K      44289      44303        NA    15             120
7   2  BD49_21K      44107      44121     44207    50              70
8   2  BU44_20J      44107      44121     44196    20              70
9   2  DD93_21E      44226      44240        NA    15              15
10  3  B874_20K      44107      44121        NA    30             105
11  3 BB849_21E      44107      44121        NA    25             105
12  3  B873_20K      44107      44121        NA    20             105
13  3  B875_21E      44107      44121        NA    30             105
14  3  B873_20K      44233      44247        NA    20             210
15  3  BD49_21K      44233      44247        NA    50             210
16  3  BU44_20J      44233      44247        NA    20             210
17  3 BB848_20K      44233      44247        NA    15             210

I'm really not sure how to crack this, my usual toolkit of dplyr group_by and summarise doesn't fit the bill. Any direction is greatly appreciated!

Body:
Alternatively, a concise solution with runner in the tidyverse:

Solution

library(tidyverse)
library(runner)

# ...
# Code to generate 'df'.
# ...

df %>%
  # Work within each 'ID' group.
  group_by(ID) %>%

  # Use 'runner' to go downwards from row to row.
  mutate(conditional_sum = runner(check_date, function(x) {
    # Use the check date for the latest row.
    cur_check_date <- last(x)

    # Sum only those 'value's whose rows meet the conditions.
    sum(value[
      cur_check_date >= start_date & (is.na(fail_date) | fail_date > cur_check_date)
    ])
  }))

Result

Given a df like the one reproduced here

df <- structure(
  list(
    ID = c(1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3),
    item_ID = c(
      "B874_20K", "BB849_21E", "BB842_21E", "B873_20K", "B875_21E", "BB848_20K",
      "BD49_21K", "BU44_20J", "DD93_21E", "B874_20K", "BB849_21E", "B873_20K",
      "B875_21E", "B873_20K", "BD49_21K", "BU44_20J", "BB848_20K"
    ),
    start_date = c(
      44107, 44107, 44107, 44226, 44233, 44289, 44107, 44107, 44226, 44107,
      44107, 44107, 44107, 44233, 44233, 44233, 44233
    ),
    check_date = c(
      44121, 44121, 44121, 44240, 44247, 44303, 44121, 44121, 44240, 44121,
      44121, 44121, 44121, 44247, 44247, 44247, 44247
    ),
    fail_date = c(
      NA, NA, 44114, NA, 44328, NA, 44207, 44196, NA, NA, NA, NA, NA, NA, NA,
      NA, NA
    ),
    value = c(
      30, 25, 60, 20, 30, 15, 50, 20, 15, 30, 25, 20, 30, 20, 50, 20, 15
    )
  ),
  row.names = c(NA, -17L),
  class = "data.frame"
)

this solution should yield the following result:

# A tibble: 17 x 7
# Groups:   ID [3]
      ID item_ID   start_date check_date fail_date value contidional_sum
   <dbl> <chr>          <dbl>      <dbl>     <dbl> <dbl>           <dbl>
 1     1 B874_20K       44107      44121        NA    30              55
 2     1 BB849_21E      44107      44121        NA    25              55
 3     1 BB842_21E      44107      44121     44114    60              55
 4     1 B873_20K       44226      44240        NA    20             105
 5     1 B875_21E       44233      44247     44328    30             105
 6     1 BB848_20K      44289      44303        NA    15             120
 7     2 BD49_21K       44107      44121     44207    50              70
 8     2 BU44_20J       44107      44121     44196    20              70
 9     2 DD93_21E       44226      44240        NA    15              15
10     3 B874_20K       44107      44121        NA    30             105
11     3 BB849_21E      44107      44121        NA    25             105
12     3 B873_20K       44107      44121        NA    20             105
13     3 B875_21E       44107      44121        NA    30             105
14     3 B873_20K       44233      44247        NA    20             210
15     3 BD49_21K       44233      44247        NA    50             210
16     3 BU44_20J       44233      44247        NA    20             210
17     3 BB848_20K      44233      44247        NA    15             210

Benchmarking

It appears this approach is roughly 7 times faster than the existing solution by @MichaelDewar

library(microbenchmark)

microbenchmark(
  michael = {
    df_no_na <- df %>% replace_na(list(fail_date = max(df$check_date) + 1))

    conditional_sum_by_ID_and_check_date <- function(this_ID, this_check_date){
      df_no_na %>%
        filter(ID == this_ID,
               fail_date > this_check_date,
               start_date <= this_check_date) %>%
        summarize(conditional_sum = sum(value)) %>%
        pull()
    }

    df %>%
      distinct(ID, check_date) %>%
      mutate(conditional_sum = map2_dbl(ID, check_date, conditional_sum_by_ID_and_check_date)) %>%
      right_join(df, by = c("ID", "check_date"))
  },
  greg = {
    df %>%
      group_by(ID) %>%
      mutate(conditional_sum = runner(check_date, function(x) {
        cur_check_date <- last(x)
        sum(value[
          cur_check_date >= start_date & (is.na(fail_date) | fail_date > cur_check_date)
        ])
      }))
  }
)

as seen in the benchmarks for times = 100 evaluations apiece:

Unit: milliseconds
    expr     min       lq      mean   median       uq      max neval
 michael 17.2701 18.37395 21.964745 18.77340 22.27915 147.3653   100
    greg  2.4107  2.70395  3.288304  2.92825  3.28625   8.9233   100

Note

The relative performance might change for a dataset much larger than df, where I suspect the *_join()s will prove more costly.


问:
Escaping strings in bash
I have this simple bash script:

```<code>#!/bin/bash
isRunning=$(ps -Af | awk '{if ($11 == "HomeDir") { print $0 }}' | wc -l)
if [ $isRunning == "0" ]; then
    echo "Script is running"
fi
</code>```

The script returns:

```<code>./script.sh: line 3: [ 0: command not found
</code>```

What did i do wrong?

答:
The test operator for equality is =, not ==. Also, take the custom to surround variables by " just in case:

```<code>if [ "$isRunning" = "0"] ; then ...
</code>```

or just use -eq, as codaddict suggests.

Title: Escaping strings in bash

Body:
I have this simple bash script:

#!/bin/bash
isRunning=$(ps -Af | awk '{if ($11 == "HomeDir") { print $0 }}' | wc -l)
if [ $isRunning == "0" ]; then
    echo "Script is running"
fi

The script returns:

./script.sh: line 3: [ 0: command not found

What did i do wrong?

Body:
The test operator for equality is =, not ==. Also, take the custom to surround variables by " just in case:

if [ "$isRunning" = "0"] ; then ...

or just use -eq, as codaddict suggests.


问:
How to handle a Promise into an array?
I have problems going further with my Promise that is returned from the getPostedPlaces(). When I run getAll() it prints out the Array seen below. The array seems correct, but how do I get the getAll() function to return an actual array. I can only print it, but I can't return the array itself. I have also tried to push the object inside the array onto an array, but the it returns empty. Frustrating.

```<code>const getPostedPlaces = async () => {
    const querySnapshot = await getDocs(collection(db, "posted_places"));
    const newSnapshot = querySnapshot.docs.map(doc => {
        let newDoc = doc.data();
        newDoc.id = doc.id;
        return newDoc;
    });
    return newSnapshot;
}

const getAll = () => {
    getPostedPlaces().then(res => console.log(res))
}
</code>```

The array:

```<code>Array [
      Object {
        "active": true,
        "category": Array [
          "tøj",
          "møbler",
        ],
        "email": "bar@gmail.com",
        "house_nr": 1,
        "id": "i3juWf6Rj4OPBoKAjkBD",
        "location": Object {
          "latitude": 55.69718057,
          "longitude": 12.52470763,
        },
        "price_interval": Array [
          100,
          700,
        ],
        "street_name": "Hvidkildevej",
        "time_end_actual": "",
        "time_end_expected": "Sat Feb 05 2022 18:00:00 GMT+0100 (CET)",
        "time_start": "Sat Feb 05 2022 09:00:00 GMT+0100 (CET)",
        "zip_code": 2400,
      },
    ]
</code>```

答:
You need to add a return since you are using {}

```<code>const getAll = async () => {
    // since you use {} you need to use return below
    return getPostedPlaces().then(res => {
      console.log(res)
      return res; //you need to return res here.
    })
}
</code>```

Then when you use getAll, it has to be

```<code>await getAll()
</code>```

Example where return is not needed, is when you don't use {}

```<code>const getAll = async() => getPostedPlaces()
</code>```

Title: How to handle a Promise into an array?

Body:
I have problems going further with my Promise that is returned from the getPostedPlaces(). When I run getAll() it prints out the Array seen below. The array seems correct, but how do I get the getAll() function to return an actual array. I can only print it, but I can't return the array itself. I have also tried to push the object inside the array onto an array, but the it returns empty. Frustrating.

const getPostedPlaces = async () => {
    const querySnapshot = await getDocs(collection(db, "posted_places"));
    const newSnapshot = querySnapshot.docs.map(doc => {
        let newDoc = doc.data();
        newDoc.id = doc.id;
        return newDoc;
    });
    return newSnapshot;
}

const getAll = () => {
    getPostedPlaces().then(res => console.log(res))
}

The array:

Array [
      Object {
        "active": true,
        "category": Array [
          "tøj",
          "møbler",
        ],
        "email": "bar@gmail.com",
        "house_nr": 1,
        "id": "i3juWf6Rj4OPBoKAjkBD",
        "location": Object {
          "latitude": 55.69718057,
          "longitude": 12.52470763,
        },
        "price_interval": Array [
          100,
          700,
        ],
        "street_name": "Hvidkildevej",
        "time_end_actual": "",
        "time_end_expected": "Sat Feb 05 2022 18:00:00 GMT+0100 (CET)",
        "time_start": "Sat Feb 05 2022 09:00:00 GMT+0100 (CET)",
        "zip_code": 2400,
      },
    ]

Body:
You need to add a return since you are using {}

const getAll = async () => {
    // since you use {} you need to use return below
    return getPostedPlaces().then(res => {
      console.log(res)
      return res; //you need to return res here.
    })
}

Then when you use getAll, it has to be

await getAll()

Example where return is not needed, is when you don't use {}

const getAll = async() => getPostedPlaces()


问:
Flatlist inside tab navigator is scrolling to top on state change in react native
Here you can see the gif

Here is my whole Navigator functional component. I'm trying to implement two tabs using Tab Navigator. One to display the cryptos and the other to display the forex data.

The problem is, when I try to load more data on reaching the flatlist's end, the flatlist is scrolling to the top since I'm making a state change [page+1].

```<code>const Navigator = () => {
  const Tab = createMaterialTopTabNavigator();

  const renderItems = ({ item }) => (
    <Text>{item.name}<Text>
  );

  const fetchMarketData = async () => {
    console.log("Fetching");
    const marketData = await getCryptoMarketData({ page });
    if (marketData != "Network Error") {
      const ids = data.map((item) => item.id);
      let newData = marketData.filter((item) => !ids.includes(item.id));
      setData([...data, ...newData]);
      setFetching(false);
    } else {
      setFetching(false);
      Alert.alert(marketData, "Sorry for the inconvenience");
    }
  };

  useEffect(() => {
    setFetching(true);
    const data = async () => {
      await fetchMarketData();
    };
  }, [page]);

  const handleLoadMore = async () => {
    setFetching(true);
    setPage((page) => page + 1);
  };

  const ScreenA = () => (
    <FlatList
      data={data}
      style={{ backgroundColor: "white" }}
      keyExtractor={(item) => item.id}
      renderItem={renderItems}
      scrollEventThrottle={16}
      onEndReached={handleLoadMore}
      onEndReachedThreshold={0}
    />
  );

  return (
    <Tab.Navigator
      screenOptions={({ route }) => screenOptions(route)}
      keyboardDismissMode="auto"
    >
      <Tab.Screen name="Crypto" component={ScreenA} />
      <Tab.Screen name="Forex" component={ScreenC} />
    </Tab.Navigator>
  );
};

export default Navigator;
</code>```

OnEndReached is firing the handleLoadMore function and after the state change on data, the Flatlist is scrolling to the top.

答:
1st reason

you have typo in "fetchMarketData", how exactly u get "newData" because i cant see it anywhere, maybe it should be "marketData" if not then u adding SAME old data PLUS undefined[...data, ...undefined]

2nd reason

reason why is that u call setPage(page + 1) and then "fetchMarketData" this is bad why ? because setState is async and it can be changed instant or after 5 secound, so u dont know when its changed and this is why we have hooks, you can use "useEffect" to handle this

change your "handleLoadMore" for example like this

const handleLoadMore = () => {
    setPage(page + 1);
  };
```
<p>add useEffect hook that runs when "page" state changes</p>
<pre class="lang-js prettyprint-override"><code>React.useEffect(() => {
 (async() => {
    setFetching(true)
    const marketData = await getCryptoMarketData({ page });
    if (marketData != "Network Error") {
      setData([...data, ...marketData]);
    } else {
      Alert.alert(marketData, "Sorry for the inconvenience");
    }
    setFetching(false)
})()
}, [page])
</code>```

Body:
Here you can see the gif

Here is my whole Navigator functional component. I'm trying to implement two tabs using Tab Navigator. One to display the cryptos and the other to display the forex data.

The problem is, when I try to load more data on reaching the flatlist's end, the flatlist is scrolling to the top since I'm making a state change [page+1].

const Navigator = () => {
  const Tab = createMaterialTopTabNavigator();

  const renderItems = ({ item }) => (
    <Text>{item.name}<Text>
  );

  const fetchMarketData = async () => {
    console.log("Fetching");
    const marketData = await getCryptoMarketData({ page });
    if (marketData != "Network Error") {
      const ids = data.map((item) => item.id);
      let newData = marketData.filter((item) => !ids.includes(item.id));
      setData([...data, ...newData]);
      setFetching(false);
    } else {
      setFetching(false);
      Alert.alert(marketData, "Sorry for the inconvenience");
    }
  };

  useEffect(() => {
    setFetching(true);
    const data = async () => {
      await fetchMarketData();
    };
  }, [page]);

  const handleLoadMore = async () => {
    setFetching(true);
    setPage((page) => page + 1);
  };

  const ScreenA = () => (
    <FlatList
      data={data}
      style={{ backgroundColor: "white" }}
      keyExtractor={(item) => item.id}
      renderItem={renderItems}
      scrollEventThrottle={16}
      onEndReached={handleLoadMore}
      onEndReachedThreshold={0}
    />
  );

  return (
    <Tab.Navigator
      screenOptions={({ route }) => screenOptions(route)}
      keyboardDismissMode="auto"
    >
      <Tab.Screen name="Crypto" component={ScreenA} />
      <Tab.Screen name="Forex" component={ScreenC} />
    </Tab.Navigator>
  );
};

export default Navigator;

OnEndReached is firing the handleLoadMore function and after the state change on data, the Flatlist is scrolling to the top.

Body:
1st reason

you have typo in "fetchMarketData", how exactly u get "newData" because i cant see it anywhere, maybe it should be "marketData" if not then u adding SAME old data PLUS undefined[...data, ...undefined]

2nd reason

reason why is that u call setPage(page + 1) and then "fetchMarketData" this is bad why ? because setState is async and it can be changed instant or after 5 secound, so u dont know when its changed and this is why we have hooks, you can use "useEffect" to handle this

change your "handleLoadMore" for example like this

const handleLoadMore = () => {
    setPage(page + 1);
  };

add useEffect hook that runs when "page" state changes

React.useEffect(() => {
 (async() => {
    setFetching(true)
    const marketData = await getCryptoMarketData({ page });
    if (marketData != "Network Error") {
      setData([...data, ...marketData]);
    } else {
      Alert.alert(marketData, "Sorry for the inconvenience");
    }
    setFetching(false)
})()
}, [page])