问:
Filesystemwatcher file created event not decompressing files
I got a simple script that should watch for new files in specified folder and uncompress them on arriving. Simple, but my script only works under the debugger of Powershell ISE. When outside the debugger, on file creation it only prints "New file xxx found" and "Done", without decompressing it, nor deleting, but also no errors. I'm I missing something here?</p>

```<code># Folder you to monitor
$PathToMonitor = "C:\tmp1".
$OutputPath = "C:\tmp"
$Filter = "*.zip"  # Filter for zip files.

$FileSystemWatcher = New-Object System.IO.FileSystemWatcher
$FileSystemWatcher.Path  = $PathToMonitor
$FileSystemWatcher.IncludeSubdirectories = $false
$FileSystemWatcher.Filter = $Filter

# make sure the watcher emits events
$FileSystemWatcher.EnableRaisingEvents = $true

# define the code that should execute when a file change is detected
$Action = {
    $details = $event.SourceEventArgs
    $FullPath = $details.FullPath
    $OldName = $details.OldName
    $Timestamp = $event.TimeGenerated
    try
    {
        Write-Host "New file " + $FullPath + " found"
        $TarProgram = "tar.exe"
        $TarArgs = 'xvf "' + $FullPath + '" -C ' + $OutputPath
        Start-Process $TarProgram $TarArgs -Wait -WindowStyle hidden
        Remove-Item -Path $FullPath -Force
        Write-Host "Done"
    }
    catch [System.SystemException]
    {
        Write-Host $_.ScriptStackTrace
    }
}

# add event handlers
$handlers = . {
    Register-ObjectEvent -InputObject $FileSystemWatcher -EventName Created -Action $Action -SourceIdentifier FSCreateFtpGe
}

Write-Host "Watching for changes to $PathToMonitor"

try
{
    do
    {
        Wait-Event -Timeout 10
    } while ($true)
}
catch [System.SystemException]
{
    Write-Host $_.ScriptStackTrace
}
finally
{
    # this gets executed when user presses CTRL+C
    # remove the event handlers
    Write-Host "Cleaning up"
    Unregister-Event -SourceIdentifier FSCreateFtpGe
    # remove background jobs
    $handlers | Remove-Job
    # remove filesystemwatcher
    $FileSystemWatcher.EnableRaisingEvents = $false
    $FileSystemWatcher.Dispose()
    "Event Handler disabled."
}
</code>```

答:
Why do you have a period here...

```<code>$PathToMonitor = "C:\tmp1".
</code>```

...that is invalid syntax and the script should fail anyway. Yet, that could be just a type you did on posting here.

Why are you using tar vs the PowerShell built-in archive cmdlets?

if tar.exe is not in your PowerShell or system paths, you have to fully qualify that path to it for it to be used.

$TarProgram = 'C:\ProgramFiles\tar.exe'

So, your code should work in any PowerShell host (ISE [in/out of debug mode])/powershell.exe/VSCode, et al. AS I just tested it. Yet again, the cmdlets are there. Example of the below running in the new Windows Terminal.

```<code>#region Begin Script

# Folder you to monitor
$PathToMonitor = 'D:\tmp1'
$OutputPath    = 'D:\tmp'
$Filter        = '*.zip'  # Filter for zip files.

$FileSystemWatcher        = New-Object System.IO.FileSystemWatcher
$FileSystemWatcher.Path   = $PathToMonitor
$FileSystemWatcher.IncludeSubdirectories = $false
$FileSystemWatcher.Filter = $Filter

# make sure the watcher emits events
$FileSystemWatcher.EnableRaisingEvents = $true

# define the code that should execute when a file change is detected
$Action = {
    $details   = $event.SourceEventArgs
    $FullPath  = $details.FullPath
    $OldName   = $details.OldName
    $Timestamp = $event.TimeGenerated

    try
    {
        "New file $FullPath  found"
        Expand-Archive -Path $FullPath -DestinationPath 'D:\tmp'

        # Start-Process $TarProgram $TarArgs -Wait -WindowStyle hidden
        Remove-Item -Path $FullPath -Force

        'Done'
    }
    catch [System.SystemException]
    {$PSItem.ScriptStackTrace}
}

# add event handlers
$handlers = . {
    $RegisterObjectEventSplat = @{
        InputObject      = $FileSystemWatcher
        EventName        = 'Created'
        Action           = $Action
        SourceIdentifier = 'FSCreateFtpGe'
    }
    Register-ObjectEvent @RegisterObjectEventSplat
}

"Watching for changes to $PathToMonitor"

try
{
    do { Wait-Event -Timeout 10 }
    while ($true)
}
catch [System.SystemException]
{$_.ScriptStackTrace}
finally
{
    <#
    this gets executed when user presses CTRL+C
    remove the event handlers
    #>
    'Cleaning up'
    Unregister-Event -SourceIdentifier FSCreateFtpGe

    # remove background jobs
    $handlers |
    Remove-Job

    # remove filesystemwatcher
    $FileSystemWatcher.EnableRaisingEvents = $false
    $FileSystemWatcher.Dispose()
    'Event Handler disabled.'
}

#endregion End Script

# Results

 Get-CimInstance -ClassName Win32_OperatingSystem | Select-Object -Property Caption, Version

Caption                  Version
$PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.18362.752
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0, 5.0, 5.1.18362.752}
BuildVersion                   10.0.18362.752
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3

 Get-ChildItem -Path 'D:\tmp' -Verbose
 (Get-ChildItem -Path 'D:\tmp').Count
0
 Get-ChildItem -Path 'D:\tmp1' -Verbose
 (Get-ChildItem -Path 'D:\tmp1').Count
0
 .\FSWCopyUnzip.ps1
Watching for changes to D:\tmp1
New file D:\tmp1\book1.zip  found
Done
Cleaning up

 Get-ChildItem -Path 'D:\tmp' -Verbose

    Directory: D:\tmp

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        13-Mar-20     12:19             70 abc.txt
-a----        13-Mar-20     22:27             71 book1.txt
-a----        06-Apr-20     21:51           2979 Data.zip
-a----        04-Mar-20     01:04             72 FileWithLines.txt

 Get-ChildItem -Path 'D:\tmp1' -Verbose
 (Get-ChildItem -Path 'D:\tmp1').Count
 0
</code>```

Body:
I got a simple script that should watch for new files in specified folder and uncompress them on arriving. Simple, but my script only works under the debugger of Powershell ISE. When outside the debugger, on file creation it only prints "New file xxx found" and "Done", without decompressing it, nor deleting, but also no errors. I'm I missing something here?

# Folder you to monitor
$PathToMonitor = "C:\tmp1".
$OutputPath = "C:\tmp"
$Filter = "*.zip"  # Filter for zip files.

$FileSystemWatcher = New-Object System.IO.FileSystemWatcher
$FileSystemWatcher.Path  = $PathToMonitor
$FileSystemWatcher.IncludeSubdirectories = $false
$FileSystemWatcher.Filter = $Filter

# make sure the watcher emits events
$FileSystemWatcher.EnableRaisingEvents = $true

# define the code that should execute when a file change is detected
$Action = {
    $details = $event.SourceEventArgs
    $FullPath = $details.FullPath
    $OldName = $details.OldName
    $Timestamp = $event.TimeGenerated
    try
    {
        Write-Host "New file " + $FullPath + " found"
        $TarProgram = "tar.exe"
        $TarArgs = 'xvf "' + $FullPath + '" -C ' + $OutputPath
        Start-Process $TarProgram $TarArgs -Wait -WindowStyle hidden
        Remove-Item -Path $FullPath -Force
        Write-Host "Done"
    }
    catch [System.SystemException]
    {
        Write-Host $_.ScriptStackTrace
    }
}

# add event handlers
$handlers = . {
    Register-ObjectEvent -InputObject $FileSystemWatcher -EventName Created -Action $Action -SourceIdentifier FSCreateFtpGe
}

Write-Host "Watching for changes to $PathToMonitor"

try
{
    do
    {
        Wait-Event -Timeout 10
    } while ($true)
}
catch [System.SystemException]
{
    Write-Host $_.ScriptStackTrace
}
finally
{
    # this gets executed when user presses CTRL+C
    # remove the event handlers
    Write-Host "Cleaning up"
    Unregister-Event -SourceIdentifier FSCreateFtpGe
    # remove background jobs
    $handlers | Remove-Job
    # remove filesystemwatcher
    $FileSystemWatcher.EnableRaisingEvents = $false
    $FileSystemWatcher.Dispose()
    "Event Handler disabled."
}

Body:
Why do you have a period here...

$PathToMonitor = "C:\tmp1".

...that is invalid syntax and the script should fail anyway. Yet, that could be just a type you did on posting here.

Why are you using tar vs the PowerShell built-in archive cmdlets?

if tar.exe is not in your PowerShell or system paths, you have to fully qualify that path to it for it to be used.

$TarProgram = 'C:\ProgramFiles\tar.exe'

So, your code should work in any PowerShell host (ISE [in/out of debug mode])/powershell.exe/VSCode, et al. AS I just tested it. Yet again, the cmdlets are there. Example of the below running in the new Windows Terminal.

#region Begin Script

# Folder you to monitor
$PathToMonitor = 'D:\tmp1'
$OutputPath    = 'D:\tmp'
$Filter        = '*.zip'  # Filter for zip files.

$FileSystemWatcher        = New-Object System.IO.FileSystemWatcher
$FileSystemWatcher.Path   = $PathToMonitor
$FileSystemWatcher.IncludeSubdirectories = $false
$FileSystemWatcher.Filter = $Filter

# make sure the watcher emits events
$FileSystemWatcher.EnableRaisingEvents = $true

# define the code that should execute when a file change is detected
$Action = {
    $details   = $event.SourceEventArgs
    $FullPath  = $details.FullPath
    $OldName   = $details.OldName
    $Timestamp = $event.TimeGenerated

    try
    {
        "New file $FullPath  found"
        Expand-Archive -Path $FullPath -DestinationPath 'D:\tmp'

        # Start-Process $TarProgram $TarArgs -Wait -WindowStyle hidden
        Remove-Item -Path $FullPath -Force

        'Done'
    }
    catch [System.SystemException]
    {$PSItem.ScriptStackTrace}
}

# add event handlers
$handlers = . {
    $RegisterObjectEventSplat = @{
        InputObject      = $FileSystemWatcher
        EventName        = 'Created'
        Action           = $Action
        SourceIdentifier = 'FSCreateFtpGe'
    }
    Register-ObjectEvent @RegisterObjectEventSplat
}

"Watching for changes to $PathToMonitor"

try
{
    do { Wait-Event -Timeout 10 }
    while ($true)
}
catch [System.SystemException]
{$_.ScriptStackTrace}
finally
{
    <#
    this gets executed when user presses CTRL+C
    remove the event handlers
    #>
    'Cleaning up'
    Unregister-Event -SourceIdentifier FSCreateFtpGe

    # remove background jobs
    $handlers |
    Remove-Job

    # remove filesystemwatcher
    $FileSystemWatcher.EnableRaisingEvents = $false
    $FileSystemWatcher.Dispose()
    'Event Handler disabled.'
}

#endregion End Script

# Results

 Get-CimInstance -ClassName Win32_OperatingSystem | Select-Object -Property Caption, Version

Caption                  Version
$PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.18362.752
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0, 5.0, 5.1.18362.752}
BuildVersion                   10.0.18362.752
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3

 Get-ChildItem -Path 'D:\tmp' -Verbose
 (Get-ChildItem -Path 'D:\tmp').Count
0
 Get-ChildItem -Path 'D:\tmp1' -Verbose
 (Get-ChildItem -Path 'D:\tmp1').Count
0
 .\FSWCopyUnzip.ps1
Watching for changes to D:\tmp1
New file D:\tmp1\book1.zip  found
Done
Cleaning up

 Get-ChildItem -Path 'D:\tmp' -Verbose

    Directory: D:\tmp

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        13-Mar-20     12:19             70 abc.txt
-a----        13-Mar-20     22:27             71 book1.txt
-a----        06-Apr-20     21:51           2979 Data.zip
-a----        04-Mar-20     01:04             72 FileWithLines.txt

 Get-ChildItem -Path 'D:\tmp1' -Verbose
 (Get-ChildItem -Path 'D:\tmp1').Count
 0


来源: stackexchange

问:
What is the purpose of using JSON.stringify()?
I'm using JSON.stringify in my react redux application. What's the purpose of JSON.stringify in the following context? Even without JSON.stringify it works, but yet I've been advised to use JSON.stringify.

```<code>if (JSON.stringify(earlyBird.eBird) !== JSON.stringify(prevProps.earlyBird.eBird)) {
</code>```

答:
First thing first

JSON.stringify converts objects into strings.

Now if you two objects

Like

```<code>const obj1 = {
   a: 10
}

const obj2 = {
   a: 10
}
</code>```

Now you want to compare them

```<code> obj1 === obj2; // returns false
</code>```

But

```<code>JSON.stringify(obj1) === JSON.stringify(obj2); // returns true
</code>```

Now why your code works

because you are comparing same object

ContentLicense: CC BY-SA 4.0

Body:
I'm using JSON.stringify in my react redux application. What's the purpose of JSON.stringify in the following context? Even without JSON.stringify it works, but yet I've been advised to use JSON.stringify.

if (JSON.stringify(earlyBird.eBird) !== JSON.stringify(prevProps.earlyBird.eBird)) {

Body:
First thing first

JSON.stringify converts objects into strings.

Now if you two objects

Like

const obj1 = {
   a: 10
}

const obj2 = {
   a: 10
}

Now you want to compare them

 obj1 === obj2; // returns false

But

JSON.stringify(obj1) === JSON.stringify(obj2); // returns true

Now why your code works

because you are comparing same object


问:
Trouble calling c++ function
I wrote a c++ function what takes in an array and prints some stuff with no output, yet when I try and call it I get the error:

```<code>main.cpp:11:2: error: no matching function for call to 'render'
        render(board);
        ^~~~~~
./functions.hpp:1:6: note: candidate function not viable: requires 0 arguments, but 1 was
      provided
void render();
</code>```

Here is my code:

I have a page for my functions (functions.hpp):

```<code>#include <iostream>
using namespace std;

void render(int board[]){
    cout << board[0] << "\n";
}
</code>```

Then my main file:

```<code>#include <iostream>
#include "functions.hpp"
using namespace std;

int main() {
    string board[] = {"_", "_", "_", "_", "_", "_", " ", " ", " "};

    render(board); // This is where I am hitting the error
}
</code>```

Can someone point out the error, I am very new to c++.

答:
Your render function accepts an array of integers, while you are trying to pass in an array of string.

You can fix this by changing your function to accept the type you are trying to pass.

```<code>void render(string board[]){
    cout << board[0] << "\n";
}
</code>```

Your compiler output points to a function prototype for void render();, which does not accept any arguments. You might be dealing with multiple header files with the same name (perhaps only varying by case). You will need to determine which header file is being included by your C++ source file, and then troubleshoot your code accordingly.

Title: Trouble calling c++ function

Body:
I wrote a c++ function what takes in an array and prints some stuff with no output, yet when I try and call it I get the error:

main.cpp:11:2: error: no matching function for call to 'render'
        render(board);
        ^~~~~~
./functions.hpp:1:6: note: candidate function not viable: requires 0 arguments, but 1 was
      provided
void render();

Here is my code:

I have a page for my functions (functions.hpp):

#include <iostream>
using namespace std;

void render(int board[]){
    cout << board[0] << "\n";
}

Then my main file:

#include <iostream>
#include "functions.hpp"
using namespace std;

int main() {
    string board[] = {"_", "_", "_", "_", "_", "_", " ", " ", " "};

    render(board); // This is where I am hitting the error
}

Can someone point out the error, I am very new to c++.

Body:
Your render function accepts an array of integers, while you are trying to pass in an array of string.

You can fix this by changing your function to accept the type you are trying to pass.

void render(string board[]){
    cout << board[0] << "\n";
}

Your compiler output points to a function prototype for void render();, which does not accept any arguments. You might be dealing with multiple header files with the same name (perhaps only varying by case). You will need to determine which header file is being included by your C++ source file, and then troubleshoot your code accordingly.


问:
Delete row containing #N/A
I am trying to delete rows from a table where a value within that row is #N/A

Sub remove_na()

Dim ws As Worksheet

Dim r As Variant
Dim i As Variant

Set ws = ThisWorkbook.ActiveSheet

r = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

For Each i In Range("A1:A" & r)
    If i = "#N/A" Then i.EntireRow.Delete
Next

End Sub
```
<p>I get a Type Mismatch error on the IF statement. I tried using WHILE loops as well as FOR. The same issue occurred.</p>
<p>An example of the data being processed is columns of data (a few hundred records):</p>
<pre class="lang-none prettyprint-override"><code>#N/A        #N/A
#N/A        #N/A
#N/A        #N/A
#N/A        #N/A
#N/A        #N/A
#N/A        #N/A
#N/A        #N/A
456699.512  6523052.64
456699.512  6523052.64
456699.512  6523052.64
456699.512  6523052.64
456699.512  6523052.64
</code>```

答:
```<code>Sub remove_na()

Dim ws As Worksheet

Dim r As Integer
Dim i As Integer

Set ws = ThisWorkbook.ActiveSheet

r = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

For i = r To 1 Step -1
    If IsError(Cells(i, 1).Value) Then Rows(i).EntireRow.Delete
Next

End Sub
</code>```

Edited to improve answer

Title: Delete row containing #N/A

Body:
I am trying to delete rows from a table where a value within that row is #N/A

Sub remove_na()

Dim ws As Worksheet

Dim r As Variant
Dim i As Variant

Set ws = ThisWorkbook.ActiveSheet

r = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

For Each i In Range("A1:A" & r)
    If i = "#N/A" Then i.EntireRow.Delete
Next

End Sub

I get a Type Mismatch error on the IF statement. I tried using WHILE loops as well as FOR. The same issue occurred.

An example of the data being processed is columns of data (a few hundred records):

#N/A        #N/A
#N/A        #N/A
#N/A        #N/A
#N/A        #N/A
#N/A        #N/A
#N/A        #N/A
#N/A        #N/A
456699.512  6523052.64
456699.512  6523052.64
456699.512  6523052.64
456699.512  6523052.64
456699.512  6523052.64

Body:
Sub remove_na()

Dim ws As Worksheet

Dim r As Integer
Dim i As Integer

Set ws = ThisWorkbook.ActiveSheet

r = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

For i = r To 1 Step -1
    If IsError(Cells(i, 1).Value) Then Rows(i).EntireRow.Delete
Next

End Sub

Edited to improve answer


问:
Exception: The file or folder has invalid access settings. (line 31, file "newfile")
```<code>var holderArray = [
  folder.getId(),
  folder.getName(),
  folder.getOwner(),
  folderPath,
  folder.getDateCreated(),
  folder.getLastUpdated(),
  folder.getAccess(user),
  folder.getSharingAccess(),
  folder.getSharingPermission(),
  folder.getUrl()
];
</code>```

For some reason, this above line is causing an error saying I have invalid access settings.
I am not sure why this is happening. I have specified which folder to access and I have also given access to my Drive folder as well.

答:
I was able to fix this.. The solution was that if you want to log all the information of all your folders and files then you have to make sure that you do not use folder.getAccess(user), folder.getSharingAccess(), folder.getSharingPermission()
if you use the above lines of code you will receive the same warning when trying to log all files and folders that are shared with you in your GDrive.

Body:
var holderArray = [
  folder.getId(),
  folder.getName(),
  folder.getOwner(),
  folderPath,
  folder.getDateCreated(),
  folder.getLastUpdated(),
  folder.getAccess(user),
  folder.getSharingAccess(),
  folder.getSharingPermission(),
  folder.getUrl()
];

For some reason, this above line is causing an error saying I have invalid access settings.
I am not sure why this is happening. I have specified which folder to access and I have also given access to my Drive folder as well.


问:
split string into groups with given condition
Given a String only made of only 2 letters a,b. Now the task is to split this string into exactly 3 groups such that the number of a's in each group must be same. Then find how many such groups are possible.

Example:

```<code>Input:
ababab

Possiblities:
ab ab ab

Output:
1 as we can create only 1 such group, with single a in each group
</code>```

Example:

```<code>Input:
ababbabbaaba

Possiblities:

aba bbabba aba
abab babba aba
ababb abba aba

Output:3
as we can create 3 such possible groups with 2 a's in each group.
</code>```

Now I came across below code that is solving this task.

```<code>public static int findGroups(String input) {
    int numberOfAs = 0;
    for (int i = 0; i < input.length(); i++) {
        if (input.charAt(i) == 'a')
            numberOfAs++;
    }
    int n = input.length();
    if (numberOfAs == 0) {
        return (n - 1) * (n - 2) / 2;
    }

    if (numberOfAs % 3 != 0)
        return 0;

    int numberOfAsInAGroup = numberOfAs / 3;

    int lastAIn1stGroup = 0; // last occurrence of A in 1st group
    int firstAIn2ndGroup = 0; // 1st occurrence of A in 2nd group
    int lastAIn2ndGroup = 0; // last occurrence of A in 2nd group
    int firstAIn3rdGroup = 0; // 1st occurrence of A in 3rd group
    int aCount = 0;
    for (int i = 0; i < n; i++) {
        if (input.charAt(i) == 'a') {
            aCount++;
            if (aCount == numberOfAsInAGroup) {
                lastAIn1stGroup = i;
            } else if (aCount == numberOfAsInAGroup + 1) {
                firstAIn2ndGroup = i;
            }
            if (aCount == 2 * numberOfAsInAGroup) {
                lastAIn2ndGroup = i;
            } else if (aCount == 2 * numberOfAsInAGroup + 1) {
                firstAIn3rdGroup = i;
                break;
            }
        }
    }

    int betweenSecondAndFirstGroup = firstAIn2ndGroup - lastAIn1stGroup;
    int betweenThirdAndSecondGroup = firstAIn3rdGroup - lastAIn2ndGroup;

    return betweenSecondAndFirstGroup * betweenThirdAndSecondGroup;
}
</code>```

This code is working perfectly finw without any errors. But I am trying to understand for past several days what formulas are being used in this code to solve this task.

Part - 1:

```<code>    if (numberOfAs == 0) {
        return (n - 1) * (n - 2) / 2;
    }
</code>```

After searching in google for several hrs I found the explanation here  - number-of-ways-of-distributing-n-identical-objects-among-r-groups:

Part - 2:

```<code>    int betweenSecondAndFirstGroup = firstAIn2ndGroup - lastAIn1stGroup;
    int betweenThirdAndSecondGroup = firstAIn3rdGroup - lastAIn2ndGroup;

    return betweenSecondAndFirstGroup * betweenThirdAndSecondGroup;
</code>```

I am not able to understand this part 2 formula, how this is solving the given problem, is there any explanation as mentioned for part 1.

Also just curious to know, is there any alternate version to solve this task without using formulas like this?

答:
The code you're looking at is finding the boundary As of each group, then is counting the number of spaces the dividing line between the groups could go. This depends on the number of Bs separating the groups of As, since these don't affect the count.

The answer is the number of possible dividing lines on the left, times the number on the right.

```<code>AA|B|B|AABAA <-- in this example there are 3 on the left
AABBAA|B|AA <-- and 2 on the right
for a total of 6.

AA|BBAA|BAA
AA|BBAAB|AA
AAB|BAA|BAA
AAB|BAAB|AA
AABB|AA|BAA
AABB|AAB|AA
</code>```

Body:
Given a String only made of only 2 letters a,b. Now the task is to split this string into exactly 3 groups such that the number of a's in each group must be same. Then find how many such groups are possible.

Example:

Input:
ababab

Possiblities:
ab ab ab

Output:
1 as we can create only 1 such group, with single a in each group

Example:

Input:
ababbabbaaba

Possiblities:

aba bbabba aba
abab babba aba
ababb abba aba

Output:3
as we can create 3 such possible groups with 2 a's in each group.

Now I came across below code that is solving this task.

public static int findGroups(String input) {
    int numberOfAs = 0;
    for (int i = 0; i < input.length(); i++) {
        if (input.charAt(i) == 'a')
            numberOfAs++;
    }
    int n = input.length();
    if (numberOfAs == 0) {
        return (n - 1) * (n - 2) / 2;
    }

    if (numberOfAs % 3 != 0)
        return 0;

    int numberOfAsInAGroup = numberOfAs / 3;

    int lastAIn1stGroup = 0; // last occurrence of A in 1st group
    int firstAIn2ndGroup = 0; // 1st occurrence of A in 2nd group
    int lastAIn2ndGroup = 0; // last occurrence of A in 2nd group
    int firstAIn3rdGroup = 0; // 1st occurrence of A in 3rd group
    int aCount = 0;
    for (int i = 0; i < n; i++) {
        if (input.charAt(i) == 'a') {
            aCount++;
            if (aCount == numberOfAsInAGroup) {
                lastAIn1stGroup = i;
            } else if (aCount == numberOfAsInAGroup + 1) {
                firstAIn2ndGroup = i;
            }
            if (aCount == 2 * numberOfAsInAGroup) {
                lastAIn2ndGroup = i;
            } else if (aCount == 2 * numberOfAsInAGroup + 1) {
                firstAIn3rdGroup = i;
                break;
            }
        }
    }

    int betweenSecondAndFirstGroup = firstAIn2ndGroup - lastAIn1stGroup;
    int betweenThirdAndSecondGroup = firstAIn3rdGroup - lastAIn2ndGroup;

    return betweenSecondAndFirstGroup * betweenThirdAndSecondGroup;
}

This code is working perfectly finw without any errors. But I am trying to understand for past several days what formulas are being used in this code to solve this task.

Part - 1:

    if (numberOfAs == 0) {
        return (n - 1) * (n - 2) / 2;
    }

After searching in google for several hrs I found the explanation here  - number-of-ways-of-distributing-n-identical-objects-among-r-groups:

Part - 2:

    int betweenSecondAndFirstGroup = firstAIn2ndGroup - lastAIn1stGroup;
    int betweenThirdAndSecondGroup = firstAIn3rdGroup - lastAIn2ndGroup;

    return betweenSecondAndFirstGroup * betweenThirdAndSecondGroup;

I am not able to understand this part 2 formula, how this is solving the given problem, is there any explanation as mentioned for part 1.

Also just curious to know, is there any alternate version to solve this task without using formulas like this?

Body:
The code you're looking at is finding the boundary As of each group, then is counting the number of spaces the dividing line between the groups could go. This depends on the number of Bs separating the groups of As, since these don't affect the count.

The answer is the number of possible dividing lines on the left, times the number on the right.

AA|B|B|AABAA <-- in this example there are 3 on the left
AABBAA|B|AA <-- and 2 on the right
for a total of 6.

AA|BBAA|BAA
AA|BBAAB|AA
AAB|BAA|BAA
AAB|BAAB|AA
AABB|AA|BAA
AABB|AAB|AA


问:
KeyError: 'Tipos' During handling of the above exception, another exception occurred: Traceback (most recent call last):
Pandas is so difficult i have rechecked a million times and my Python file and csv are indeed in the same folder.</p>

```<code>import pandas as pd
import matplotlib.pyplot as plt

plt.subplot(131) #Numero de choques por estado al mes
estados = ['NL','COAH','EDOMEX','VER','TAMP']
choques = [12000, 7600, 9500, 3000, 5430]
plt.title ("Numero de choques por estado al mes")
plt.xlabel ('Estados')
plt.ylabel ('choques')
plt.bar(estados, choques, color = 'green')
plt.plot(estados, choques,"r:*")
plt.xticks (rotation=45, fontsize=6)
plt.subplot(132) #grafica tips de accidentes

Tipos = {'tipos' : ['choque','atropellamiento','volcamiento','otro'],
'numeros': [752, 230,365,155]}
df=pd.DataFrame(Tipos)
plt.scatter(df['tipos'], df['numeros'])
plt.xticks(rotation=45)
plt.ylabel ('Accidentes Numero de Accidentes en Nuevo Leon')
plt.xlabel ('Tipos')
plt.title ('Numero de Accidentes en Nuevo Leon')
plt.subplot(133)

tiposdevehiculos = pd.read_csv('tiposdevehiculos.csv')
df = pd.DataFrame (tiposdevehiculos)

plt.title('tipos de vehiculos y numero de accidentes')
plt.plot (df['Tipos'], df['Numero'],'r*:')
plt.xticks(rotation=35, fontsize=6)
plt.xlabel('Tipos')
plt.yticks(rotation=35, fontsize=6)
plt.ylabel('Numeros')
plt.legend(['Tipos','Numeros'])
plt.tight_layout()
plt.show()
</code>```

答:
Hard to say what is going on, what line do you get the error? Sounds like the column 'Tipos' just doesnt exist in one of the data frames you are trying to use. Just printing the data frame can help you understand what is in it:</p>

```<code>print(df)
</code>```

Body:
Pandas is so difficult i have rechecked a million times and my Python file and csv are indeed in the same folder.

import pandas as pd
import matplotlib.pyplot as plt

plt.subplot(131) #Numero de choques por estado al mes
estados = ['NL','COAH','EDOMEX','VER','TAMP']
choques = [12000, 7600, 9500, 3000, 5430]
plt.title ("Numero de choques por estado al mes")
plt.xlabel ('Estados')
plt.ylabel ('choques')
plt.bar(estados, choques, color = 'green')
plt.plot(estados, choques,"r:*")
plt.xticks (rotation=45, fontsize=6)
plt.subplot(132) #grafica tips de accidentes

Tipos = {'tipos' : ['choque','atropellamiento','volcamiento','otro'],
'numeros': [752, 230,365,155]}
df=pd.DataFrame(Tipos)
plt.scatter(df['tipos'], df['numeros'])
plt.xticks(rotation=45)
plt.ylabel ('Accidentes Numero de Accidentes en Nuevo Leon')
plt.xlabel ('Tipos')
plt.title ('Numero de Accidentes en Nuevo Leon')
plt.subplot(133)

tiposdevehiculos = pd.read_csv('tiposdevehiculos.csv')
df = pd.DataFrame (tiposdevehiculos)

plt.title('tipos de vehiculos y numero de accidentes')
plt.plot (df['Tipos'], df['Numero'],'r*:')
plt.xticks(rotation=35, fontsize=6)
plt.xlabel('Tipos')
plt.yticks(rotation=35, fontsize=6)
plt.ylabel('Numeros')
plt.legend(['Tipos','Numeros'])
plt.tight_layout()
plt.show()

Body:
Hard to say what is going on, what line do you get the error? Sounds like the column 'Tipos' just doesnt exist in one of the data frames you are trying to use. Just printing the data frame can help you understand what is in it:

print(df)


问:
unable to execute query in omnidb
I'm using OmniDB from my company server. But queries are not executing. It will go running the whole day and still won't execute. If I click on cancel tab, then also noting happens. What's wrong?

答:
You need to force close the omnidb panel and then restart again.

And execute query like this :

```<code>SELECT * FROM `abc`.`XYZ` limit 1;
</code>```

abc is database, and XYZ is your table name.

Title: unable to execute query in omnidb

Body:
You need to force close the omnidb panel and then restart again.

And execute query like this :

SELECT * FROM `abc`.`XYZ` limit 1;

abc is database, and XYZ is your table name.


问:
Why am I getting an 'AnimationViewRenderer doesn't exist in the context' error in Xamarin Forms for Android?
Why doesn't AnimationViewRenderer exist in the context error when trying to add Lottie animation in Xamarin forms Android project's MainActivity.cs? I am using Visual Studio 2017.</p>

答:
After installing Lottie version 3.1.2 for Xamarin.Forms I had the same issue. The reason was that this specific version of Lottie has a dependency on Mono runtime version 10 but my Android project was Mono version 9. So once I upgraded MonoAndroid to 10, everything was working fine and I could use AnimationViewRenderer.Init(). However, I did not even need to initialize AnimationViewRenderer ; I just add the Lottie XAML component to my page and it is working perfectly.

You can check what version of Mono your Lottie requires by going to NuGet package manager, selecting the package and underneath Dependencies you should be able to see the required MonoAndroid version.


问:
With Spring Security how do i determine if the current api request should be authenticated or not?
With spring security you can have public api endpoints that are accessible by everyone and endpoints that need to be authenticated before getting a response. In my app users authenticate via a jwt token. For logged in users right now the token is always checked, regardless of whether a public api endpoint gets the request or not.

I would like to know how to check if the current endpoint is a public endpoint or a authenticated one, that way i can alter the code so that the token checking is only done when the endpoint requires authentication.

I could add all public endpoints in a hashset and compare the current request endpoint with the public ones but that isn't efficient and also, some of the public endpoints contain wildcards (**) so that would make comparing a bit of a hassle.

This is the only information i could find:

Spring Security - check if web url is secure / protected

but its about JSP.

I can't get the request information from SecurityContextHolder.getContext() either. My guess is that i should get the information from  org.springframework.security.config.annotation.web.builders.HttpSecurity because that is the same class used to define which endpoints don't require authentication. (with anthMatchers().permitall()). But i don't know which method to invoke and i'm not sure if HttpSecurity can even be autowired into another class. Can anyone give me some pointers?

Thank you

答:
Assuming that you're using a separate filter for the token check, you can avoid the token check for public endpoints by overriding the protected boolean shouldNotFilter(HttpServletRequest request) method of the OncePerRequestFilter in your JwtTokenFilter. By default, this method will always return false. So all requests will get filtered. Overriding this method to return true for the public endpoints will give you the desired functionality.
And to check the requests with the wildcards(**), you can use AntPathRequestMatcher. So, you can do something like below.

```<code>public class JwtTokenFilter extends OncePerRequestFilter {
    private static RequestMatcher requestMatcher;

    public static void ignorePatterns(String... antPatterns) {
        List<RequestMatcher> matchers = new ArrayList<>();
        for (String pattern : antPatterns) {
            matchers.add(new AntPathRequestMatcher(pattern, null));
        }
        requestMatcher = new OrRequestMatcher(matchers);
    }

    static {
        final String[] publicEndPoints = {"/public-api/**","/resources/**"};
        ignorePatterns(publicEndPoints);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        return requestMatcher.matches(request);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
    ....
    }
}

</code>```

Hope this helps!!

Body:
Assuming that you're using a separate filter for the token check, you can avoid the token check for public endpoints by overriding the protected boolean shouldNotFilter(HttpServletRequest request) method of the OncePerRequestFilter in your JwtTokenFilter. By default, this method will always return false. So all requests will get filtered. Overriding this method to return true for the public endpoints will give you the desired functionality.
And to check the requests with the wildcards(**), you can use AntPathRequestMatcher. So, you can do something like below.

public class JwtTokenFilter extends OncePerRequestFilter {
    private static RequestMatcher requestMatcher;

    public static void ignorePatterns(String... antPatterns) {
        List<RequestMatcher> matchers = new ArrayList<>();
        for (String pattern : antPatterns) {
            matchers.add(new AntPathRequestMatcher(pattern, null));
        }
        requestMatcher = new OrRequestMatcher(matchers);
    }

    static {
        final String[] publicEndPoints = {"/public-api/**","/resources/**"};
        ignorePatterns(publicEndPoints);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        return requestMatcher.matches(request);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
    ....
    }
}

Hope this helps!!


问:
Pyspark- Save each dataframe to a single file
I am trying to save filtered dataframe back to the same source file.

I wrote below code to transform the content of each file in a directory to separate Dataframe, filter it and save it back to the same file

```<code>rdd = sparkSession.sparkContext.wholeTextFiles("/content/sample_data/test_data")
# collect the RDD to a list
list_elements = rdd.collect()
for element in list_elements:
  path, data = element
  df = spark.read.json(spark.sparkContext.parallelize([data]))
  df = df.filter('d != 721')
  df.write.save(path, format="json", mode="overwrite")
</code>```

I was expecting that it will overwrite the file with the updated data, but it is creating a folder with the file name and creating below structure and part files:

How can I save each updated dataframe back to the same source file(.txt)?
Thanks in Advance.

答:
To save it to 1 file use .coalesce(1) or .repartition(1) option before .save(), that will result in the same folder-like structure, but there will be 1 json file inside.

To save it with a „normal” name after saving it you’d need to cut the 1 json file inside, paste and rename it with desired name. You can see code how it could look like for csv files here

Body:
I am trying to save filtered dataframe back to the same source file.

I wrote below code to transform the content of each file in a directory to separate Dataframe, filter it and save it back to the same file

rdd = sparkSession.sparkContext.wholeTextFiles("/content/sample_data/test_data")
# collect the RDD to a list
list_elements = rdd.collect()
for element in list_elements:
  path, data = element
  df = spark.read.json(spark.sparkContext.parallelize([data]))
  df = df.filter('d != 721')
  df.write.save(path, format="json", mode="overwrite")

I was expecting that it will overwrite the file with the updated data, but it is creating a folder with the file name and creating below structure and part files:

How can I save each updated dataframe back to the same source file(.txt)?
Thanks in Advance.


问:
Difference between "" and String.Empty()

Possible Duplicate:

  What is the difference between String.Empty and “”

What is the difference between code and where it is applicable??

```<code>string mystr = "";

string mystr1 = String.Empty();
</code>```

答: I think this will explain it for you: http://msdn.microsoft.com/en-us/library/system.string.empty.aspx</p>

ContentLicense: CC BY-SA 3.0

Body:
Possible Duplicate:

  What is the difference between String.Empty and “”

What is the difference between code and where it is applicable??

string mystr = "";

string mystr1 = String.Empty();


答:
That should be in function.hpp:

```<code>#pragma once
#include <iostream>
using namespace std;
void render(string board[])
{
    cout << board[0] << "\n";
}
</code>```

and the .cpp file:

```<code>#include <iostream>
#include "function.hpp"
using namespace std;

int main() {
    string board[] = { "_", "_", "_", "_", "_", "_", " ", " ", " " };

    render(board); // This is where I am hitting the error
}
</code>```

everything begins from wrong type of function argument but you still have int in you function in .hpp file

Title: Trouble calling c++ function

Body:
That should be in function.hpp:

#pragma once
#include <iostream>
using namespace std;
void render(string board[])
{
    cout << board[0] << "\n";
}

and the .cpp file:

#include <iostream>
#include "function.hpp"
using namespace std;

int main() {
    string board[] = { "_", "_", "_", "_", "_", "_", " ", " ", " " };

    render(board); // This is where I am hitting the error
}

everything begins from wrong type of function argument but you still have int in you function in .hpp file


问:
Python - Iterating over nested objects
What is an elegant way to iterate the nested object in Python? I am currently using nested loop as below.

```<code>for job in jobs:
    for task in job.tasks:
        for command in task.commands:
            print command.actual_cmd
</code>```

Is there a better way which is more Pythonic?

答:
It is pythonic. Already.

But if you worry about this goes to 10+ levels deep, with only the innermost loop has anything interesting, one thing you can consider is to create a generator. Your code can become:

```<code>def get_command(jobs):
    for job in jobs:
        for task in job.tasks:
            for command in task.commands:
                yield command

for command in get_command(jobs):
    print command.actual_cmd
</code>```

So the whole purpose is to avoid excessive indentation.

To make it generic for multiple level, so you don't worry even if it is 100+ levels deep:

```<code>def get_nested(objlist, attribs):
    for x in objlist:
        if len(attribs) == 0:
            yield x
        else:
            x_dot_attr = getattr(x, attribs[0])
            for y in get_nested(x_dot_attr, attribs[1:]):
                yield y

for command in get_nested(jobs, ["tasks", "commands"]):
    print command.actual_cmd
</code>```

But no, this generalization doesn't make it more pythonic. It only avoids excessive indentation.

Title: Python - Iterating over nested objects

Body:
What is an elegant way to iterate the nested object in Python? I am currently using nested loop as below.

for job in jobs:
    for task in job.tasks:
        for command in task.commands:
            print command.actual_cmd

Is there a better way which is more Pythonic?

Body:
It is pythonic. Already.

But if you worry about this goes to 10+ levels deep, with only the innermost loop has anything interesting, one thing you can consider is to create a generator. Your code can become:

def get_command(jobs):
    for job in jobs:
        for task in job.tasks:
            for command in task.commands:
                yield command

for command in get_command(jobs):
    print command.actual_cmd

So the whole purpose is to avoid excessive indentation.

To make it generic for multiple level, so you don't worry even if it is 100+ levels deep:

def get_nested(objlist, attribs):
    for x in objlist:
        if len(attribs) == 0:
            yield x
        else:
            x_dot_attr = getattr(x, attribs[0])
            for y in get_nested(x_dot_attr, attribs[1:]):
                yield y

for command in get_nested(jobs, ["tasks", "commands"]):
    print command.actual_cmd

But no, this generalization doesn't make it more pythonic. It only avoids excessive indentation.


问:
How do I run a different version of git on a server?
I have a git repository on a server with an old version of git (1.7.1). I need a feature only available starting in git 2.3, namely I want to run the command:

```<code>git config receive.denyCurrentBranch updateInstead
</code>```

After talking with the sysadmin, they installed a recent version of git (2.27.0) in a different location on the server. Using this newer version, I was able to run the above command for the repository.

However, whenever I push from my local machine to the server, I get the following error message:

```<code>fatal: bad config value for 'receive.denycurrentbranch' in ./config
fatal: Could not read from remote repository.
</code>```

This seems to suggest that when I push to the server, the server defaults to running the old version of git. Is there a way to tell the server to run git from a different exec-path? When running

```<code>git --exec-path=/path/to/new/git/env
</code>```

I am met with strange errors like git ignoring everything after the exec-path, or ignoring all the flags altogether. I am not sure if the --exec-path flag is even the right approach to this problem.

答:
You need to specify the new git-upload-pack/git-receive-pack

```<code>cd /path/to/local/repo
git config remote.origin.uploadpack /path/to/new/git/usr/bin/git-upload-pack
git config remote.origin.receivepack /path/to/new/git/usr/bin2/git-receive-pack
</code>```

That would be a good start for making sure git push/pull talk to the right Git.

Body:
I have a git repository on a server with an old version of git (1.7.1). I need a feature only available starting in git 2.3, namely I want to run the command:

git config receive.denyCurrentBranch updateInstead

After talking with the sysadmin, they installed a recent version of git (2.27.0) in a different location on the server. Using this newer version, I was able to run the above command for the repository.

However, whenever I push from my local machine to the server, I get the following error message:

fatal: bad config value for 'receive.denycurrentbranch' in ./config
fatal: Could not read from remote repository.

This seems to suggest that when I push to the server, the server defaults to running the old version of git. Is there a way to tell the server to run git from a different exec-path? When running

git --exec-path=/path/to/new/git/env

I am met with strange errors like git ignoring everything after the exec-path, or ignoring all the flags altogether. I am not sure if the --exec-path flag is even the right approach to this problem.

Body:
You need to specify the new git-upload-pack/git-receive-pack

cd /path/to/local/repo
git config remote.origin.uploadpack /path/to/new/git/usr/bin/git-upload-pack
git config remote.origin.receivepack /path/to/new/git/usr/bin2/git-receive-pack

That would be a good start for making sure git push/pull talk to the right Git.


问:
How to compare two blobs in JavaScript?
I load two blob files in JavaScript using the code below.

I want to compare them to see if they are precisely the same.

(blob1 === blob2) is returning false, even though the reported size of each blob is 574 bytes. What am I doing wrong?

```<code>  getHTTPAsBlob(url, callback) {
    let cacheBust = Math.random().toString()
    url = url + '?&cachebust=' + cacheBust
    let xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = function (e) {
      if (xhr.status == 200) {
        // get binary data as a response
        let fileData = this.response;
        let contentType = xhr.getResponseHeader("content-type")
        var reader = new FileReader()
        reader.onload = (e) => {
          console.log(reader.result)
          console.log(fileData)
          callback(null, {
              Body: reader.result,
              Blob: fileData,
              ContentType: contentType,
              Etag: null,
              LastModified: null,
            })
        }
        reader.readAsText(fileData)
        } else {
        callback(xhr)
      }
      }
      xhr.send();
    }
</code>```

答:
I think "blob compare" plug-in will be help you.
It can compare blob size,type and so on.
https://www.npmjs.com/package/blob-compare

but I don't know if this plug-in is the perfect way.

Title: How to compare two blobs in JavaScript?

Body:
I load two blob files in JavaScript using the code below.

I want to compare them to see if they are precisely the same.

(blob1 === blob2) is returning false, even though the reported size of each blob is 574 bytes. What am I doing wrong?

  getHTTPAsBlob(url, callback) {
    let cacheBust = Math.random().toString()
    url = url + '?&cachebust=' + cacheBust
    let xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = function (e) {
      if (xhr.status == 200) {
        // get binary data as a response
        let fileData = this.response;
        let contentType = xhr.getResponseHeader("content-type")
        var reader = new FileReader()
        reader.onload = (e) => {
          console.log(reader.result)
          console.log(fileData)
          callback(null, {
              Body: reader.result,
              Blob: fileData,
              ContentType: contentType,
              Etag: null,
              LastModified: null,
            })
        }
        reader.readAsText(fileData)
        } else {
        callback(xhr)
      }
      }
      xhr.send();
    }


问:
How to keep every two identical names red if both were clicked consecutively?
I have list items represent names, when clicking any name it turns red then take one second to return black again, but clicking two identical names consecutively make them keep red color, not turning black again

you can imagine it as a memory game, but i tried to make a simple example here of what i am trying to achieve in the original project

This is my code and my wrong trial:

```<code>const App = () => {
  const { useState } = React;
        const items = [
            {
                name: 'mark',
                id: 1,
                red: false
            },
            {
                name: 'peter',
                id: 2,
                red: false
            },
            {
                name: 'john',
                id: 3,
                red: false
            },

            {
                name: 'mark',
                id: 4,
                red: false,
            },
            {
                name: 'peter',
                id: 5,
                red: false
            },
            {
                name: 'john',
                id: 6,
                red: false
            }
        ];

        const [names, setNames] = useState(items);
        const [firstName, setFirstName] = useState(null);
        const [secondName, setSecondName] = useState(null)

        const handleItemClick = (item) => {
            setNames(prev => prev.map(i => i.id === item.id ? { ...i, red: true } : i));
            //the problem is here
            setTimeout(() => {
                setNames(prev => prev.map(n => {
                    if (secondName && (secondName.name === firstName.name) && n.name === firstName.name) {
                        return { ...n,red: true }
                    }

                    return { ...n, red: false };
                }))
            }, 1000)

            if (!firstName) setFirstName(item);
            else if (firstName && !secondName) setSecondName(item)
            else if (firstName && secondName) {
                setFirstName(item);
                setSecondName(null)
            }
        }

        return (
            <div class="app">
                <ul class="items">
                    {
                        names.map(i => {
                            return (
                                <Item
                                    item={i}
                                    handleItemClick={handleItemClick}
                                />
                            )
                        })
                    }
                </ul>
            </div>
        )

    }

    const Item = ({ item, ...props }) => {
        const { id, name, red } = item;
        const { handleItemClick } = props;

        return (
            <li
                className={`${red ? 'red' : ''}`}
                onClick={() => handleItemClick(item)}
            >
                {name}
            </li>
        )
    }

    ReactDOM.render(<App />, document.getElementById('root'))

</code>```

But this code doesn't work correctly, when clicking two identical names consecutively they don't keep red color and turning black again

答:
To me it seems the issue is overloading the event handler and violating the Single Responsibility Principle.

The handler should be responsible for handling the click event and nothing else. In this case, when the element is clicked you want to add the id to the state of selected/picked names, and toggle the red state value of item with matching id. Factor the timeout effect into (strangely enough) an useEffect hook, with the picks as dependencies. This inverts the logic of the timeout to clearing/resetting the state versus setting what is "red" or not. You can/should also move any logic of determining matches into this same effect (since it already has the dependencies anyway).

```<code>useEffect(() => {
  ... logic to determine matches

  const timer = setTimeout(() => {
    // time expired, reset only if two names selected
    if (firstName && secondName) {
      setFirstName(null);
      setSecondName(null);
      setNames(names => names.map(name => ({ ...name, red: false })));
    }
  }, 1000);

  // clean up old timeout when state updates, i.e. new selected
  return () => clearTimeout(timer);
}, [firstName, secondName]);
</code>```

This will allow you to simplify your name setting logic to

```<code>if (!firstName) {
  setFirstName(item);
} else {
  setSecondName(item);
}
</code>```

Note: I believe you need another data structure to hold/track/store existing matches made by the user.

How this works:

Starting from clean state, no names are chosen

When first name is picked, firstName is null and updated, red state updated

Timeout is set (but won't clear state yet)

When second name is picked, firstName is defined, so secondName is updated, red state updated

If match, add match to state (to keep red)

Timeout expire and reset state (go back to step 1)

The following is how I'd try to simplify state a bit more, using an array of selected ids that only update if the selected id isn't already chosen and 2 picks haven't been chosen yet.

```<code>const App = () => {
  const [names, setNames] = useState(items);
  const [picks, setPicks] = useState([]);
  const [matched, setMatched] = useState({});

  /**
   * On click event, add id to `picks` array, allow only two picks
   */
  const onClickHandler = id => () =>
    picks.length !== 2 &&
    !picks.includes(id) &&
    setPicks(picks => [...picks, id]);

  /**
   * Effect to toggle red state if id is included in current picks
   */
  useEffect(() => {
    setNames(names =>
      names.map(name => ({
        ...name,
        red: picks.includes(name.id)
      }))
    );
  }, [picks]);

  /**
   * Effect checks for name match, if a match is found it is added to the
   * `matched` array.
   */
  useEffect(() => {
    // matches example: { mark: 1, peter: 0, john: 0 }
    const matches = names.reduce((matches, { name, red }) => {
      if (!matches[name]) matches[name] = 0;
      red && matches[name]++;
      return matches;
    }, {});

    const match = Object.entries(matches).find(([_, count]) => count === 2);

    if (match) {
      const [matchedName] = match;
      setMatched(matched => ({ ...matched, [matchedName]: matchedName }));
    }

    const timer = setTimeout(() => {
      if (picks.length === 2) {
        setPicks([]);
        setNames(names => names.map(name => ({ ...name, red: false })));
      }
    }, 1000);
    return () => clearTimeout(timer);
  }, [names, picks]);

  return (
    <div className="App">
      <ul>
        {names.map(item => (
          <Item
            key={item.id}
            item={item}
            matches={matched}
            onClick={onClickHandler(item.id)}
          />
        ))}
      </ul>
    </div>
  );
};

const Item = ({ item, matches, ...props }) => {
  const { name, red } = item;
  return (
    <li
      className={classnames({
        red: red || matches[name], // for red text color
        matched: matches[name] // any other style to make matches stand out
      })}
      {...props}
    >
      {name}
    </li>
  );
};
</code>```

Body:
I have list items represent names, when clicking any name it turns red then take one second to return black again, but clicking two identical names consecutively make them keep red color, not turning black again

you can imagine it as a memory game, but i tried to make a simple example here of what i am trying to achieve in the original project

This is my code and my wrong trial:

const App = () => {
  const { useState } = React;
        const items = [
            {
                name: 'mark',
                id: 1,
                red: false
            },
            {
                name: 'peter',
                id: 2,
                red: false
            },
            {
                name: 'john',
                id: 3,
                red: false
            },

            {
                name: 'mark',
                id: 4,
                red: false,
            },
            {
                name: 'peter',
                id: 5,
                red: false
            },
            {
                name: 'john',
                id: 6,
                red: false
            }
        ];

        const [names, setNames] = useState(items);
        const [firstName, setFirstName] = useState(null);
        const [secondName, setSecondName] = useState(null)

        const handleItemClick = (item) => {
            setNames(prev => prev.map(i => i.id === item.id ? { ...i, red: true } : i));
            //the problem is here
            setTimeout(() => {
                setNames(prev => prev.map(n => {
                    if (secondName && (secondName.name === firstName.name) && n.name === firstName.name) {
                        return { ...n,red: true }
                    }

                    return { ...n, red: false };
                }))
            }, 1000)

            if (!firstName) setFirstName(item);
            else if (firstName && !secondName) setSecondName(item)
            else if (firstName && secondName) {
                setFirstName(item);
                setSecondName(null)
            }
        }

        return (

                    {
                        names.map(i => {
                            return (
                                <Item
                                    item={i}
                                    handleItemClick={handleItemClick}
                                />
                            )
                        })
                    }

        )

    }

    const Item = ({ item, ...props }) => {
        const { id, name, red } = item;
        const { handleItemClick } = props;

        return (
            <li
                className={`${red ? 'red' : ''}`}
                onClick={() => handleItemClick(item)}
            >
                {name}

        )
    }

    ReactDOM.render(<App />, document.getElementById('root'))

But this code doesn't work correctly, when clicking two identical names consecutively they don't keep red color and turning black again

Body:
To me it seems the issue is overloading the event handler and violating the Single Responsibility Principle.

The handler should be responsible for handling the click event and nothing else. In this case, when the element is clicked you want to add the id to the state of selected/picked names, and toggle the red state value of item with matching id. Factor the timeout effect into (strangely enough) an useEffect hook, with the picks as dependencies. This inverts the logic of the timeout to clearing/resetting the state versus setting what is "red" or not. You can/should also move any logic of determining matches into this same effect (since it already has the dependencies anyway).

useEffect(() => {
  ... logic to determine matches

  const timer = setTimeout(() => {
    // time expired, reset only if two names selected
    if (firstName && secondName) {
      setFirstName(null);
      setSecondName(null);
      setNames(names => names.map(name => ({ ...name, red: false })));
    }
  }, 1000);

  // clean up old timeout when state updates, i.e. new selected
  return () => clearTimeout(timer);
}, [firstName, secondName]);

This will allow you to simplify your name setting logic to

if (!firstName) {
  setFirstName(item);
} else {
  setSecondName(item);
}

Note: I believe you need another data structure to hold/track/store existing matches made by the user.

How this works:

Starting from clean state, no names are chosen

When first name is picked, firstName is null and updated, red state updated

Timeout is set (but won't clear state yet)

When second name is picked, firstName is defined, so secondName is updated, red state updated

If match, add match to state (to keep red)

Timeout expire and reset state (go back to step 1)

The following is how I'd try to simplify state a bit more, using an array of selected ids that only update if the selected id isn't already chosen and 2 picks haven't been chosen yet.

const App = () => {
  const [names, setNames] = useState(items);
  const [picks, setPicks] = useState([]);
  const [matched, setMatched] = useState({});

  /**
   * On click event, add id to `picks` array, allow only two picks
   */
  const onClickHandler = id => () =>
    picks.length !== 2 &&
    !picks.includes(id) &&
    setPicks(picks => [...picks, id]);

  /**
   * Effect to toggle red state if id is included in current picks
   */
  useEffect(() => {
    setNames(names =>
      names.map(name => ({
        ...name,
        red: picks.includes(name.id)
      }))
    );
  }, [picks]);

  /**
   * Effect checks for name match, if a match is found it is added to the
   * `matched` array.
   */
  useEffect(() => {
    // matches example: { mark: 1, peter: 0, john: 0 }
    const matches = names.reduce((matches, { name, red }) => {
      if (!matches[name]) matches[name] = 0;
      red && matches[name]++;
      return matches;
    }, {});

    const match = Object.entries(matches).find(([_, count]) => count === 2);

    if (match) {
      const [matchedName] = match;
      setMatched(matched => ({ ...matched, [matchedName]: matchedName }));
    }

    const timer = setTimeout(() => {
      if (picks.length === 2) {
        setPicks([]);
        setNames(names => names.map(name => ({ ...name, red: false })));
      }
    }, 1000);
    return () => clearTimeout(timer);
  }, [names, picks]);

  return (
    <div className="App">
      <ul>
        {names.map(item => (
          <Item
            key={item.id}
            item={item}
            matches={matched}
            onClick={onClickHandler(item.id)}
          />
        ))}
      </ul>
    </div>
  );
};

const Item = ({ item, matches, ...props }) => {
  const { name, red } = item;
  return (
    <li
      className={classnames({
        red: red || matches[name], // for red text color
        matched: matches[name] // any other style to make matches stand out
      })}
      {...props}
    >
      {name}
    </li>
  );
};


问:
What is the difference between SBT and IDEA when creating a Scala project in intelliJ?
When creting a project in IntelliJ, I am given options for sbt, Lightbend Project Starter, IDEA, Play 2.x, Dotty(experimental). What do these options mean, and how could I learn more about them?</p>

答:
IDEA is something related to IntelliJ IDE.
  SBT is a build tool(substitute for maven) for scala projects.
  When you enable SBT option, it will add sbt related configuration, sbt shell, sbt options. You can choose sbt if your project is built upon sbt (means your project will have a build.sbt file).

The other options also can be opted only if your project folder demands it.


问:
Placeholder in contenteditable - focus event issue
I have been trying to ask this before, without any luck of explaining/proving a working example where the bug happens. So here is another try:

I’m trying to replicate a placeholder effect on a contenteditable DIV. The core concept is simple:

```<code><div contenteditable><em>Edit me</em></div>

<script>
$('div').focus(function() {
    $(this).empty();
});
</script>
</code>```

This can sometomes work, but if the placeholder contains HTML, or if there some other processing being made, the editable DIV’s text caret is being removed, and the user must re-click the editable DIV to be able to start typing (even if it’s still in focus):

Example: http://jsfiddle.net/hHLXr/6/

I can’t use a focus trigger in the handler, since it will create an event loop. So I need a way to re-set the caret cursor in the editable DIV, or in some other way re-focus.

答:
In .css

```<code>.holder:before {
    content: attr(placeholder);
    color: lightgray;
    display: block;
    position:absolute;
    font-family: "Campton", sans-serif;
}
</code>```

in js.

```<code>clickedOnInput:boolean = false;
charactorCount:number = 0;
let charCount = document.getElementsByClassName('edit-box')[0];

if(charCount){
this.charactorCount = charCount.innerText.length;
}

if(charactorCount > 0 && clickedOnInput){
document.getElementById("MyConteditableElement").classList.add('holder');
}

if(charactorCount == 0 && !clickedOnInput){
document.getElementById("MyConteditableElement").classList.remove('holder');
}

getContent(innerText){
  this.clickedOnInput = false;
}
</code>```

In .html

```<code><div placeholder="Write your message.." id="MyConteditableElement" onclick="clickedOnInput = true;" contenteditable class="form-control edit-box"></div>
</code>```

this solution worked for me in angular project

Body:
I have been trying to ask this before, without any luck of explaining/proving a working example where the bug happens. So here is another try:

I’m trying to replicate a placeholder effect on a contenteditable DIV. The core concept is simple:

Edit me

This can sometomes work, but if the placeholder contains HTML, or if there some other processing being made, the editable DIV’s text caret is being removed, and the user must re-click the editable DIV to be able to start typing (even if it’s still in focus):

Example: http://jsfiddle.net/hHLXr/6/

I can’t use a focus trigger in the handler, since it will create an event loop. So I need a way to re-set the caret cursor in the editable DIV, or in some other way re-focus.

Body:
In .css

.holder:before {
    content: attr(placeholder);
    color: lightgray;
    display: block;
    position:absolute;
    font-family: "Campton", sans-serif;
}

in js.

clickedOnInput:boolean = false;
charactorCount:number = 0;
let charCount = document.getElementsByClassName('edit-box')[0];

if(charCount){
this.charactorCount = charCount.innerText.length;
}

if(charactorCount > 0 && clickedOnInput){
document.getElementById("MyConteditableElement").classList.add('holder');
}

if(charactorCount == 0 && !clickedOnInput){
document.getElementById("MyConteditableElement").classList.remove('holder');
}

getContent(innerText){
  this.clickedOnInput = false;
}

In .html

<div placeholder="Write your message.." id="MyConteditableElement" onclick="clickedOnInput = true;" contenteditable class="form-control edit-box"></div>

this solution worked for me in angular project


问:
Cannot install ggplot with conda-forge
I am trying to install ggplot with conda-forge. But it is showing some certain error. Details error message is given below.

```<code>(base) C:\Users\ASUS>conda install -c conda-forge ggplot=0.11.5
</code>```

```<code>Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: failed with repodata from current_repodata.json, will retry with next repodata source.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: -
Found conflicts! Looking for incompatible packages.
This can take several minutes.  Press CTRL-C to abort.
failed
</code>```

```<code>UnsatisfiableError: The following specifications were found
to be incompatible with the existing python installation in your environment:

Specifications:

  - ggplot=0.11.5 -> python[version='2.7.*|3.5.*|3.6.*|3.4.*']

Your python: python=3.7

If python is on the left-most side of the chain, that's the version you've asked for.
When python appears to the right, that indicates that the thing on the left is somehow
not available for the python version you are constrained to. Note that conda will not
change your python version to a different minor version unless you explicitly specify
that.

The following specifications were found to be incompatible with your CUDA driver:

  - feature:/win-64::__cuda==11.0=0
  - feature:|@/win-64::__cuda==11.0=0

Your installed CUDA driver is: 11.0
</code>```

Please help me with any solution.

答:
I have found an alternative of ggplot, which contains all ggplot function. It's plotnine.
To install plotnine

```<code># Using pip
$ pip install plotnine         # 1. should be sufficient for most
$ pip install 'plotnine[all]'  # 2. includes extra/optional packages

# Or using conda
$ conda install -c conda-forge plotnine
</code>```

For usage guideline please visit https://plotnine.readthedocs.io/en/stable/index.html

Title: Cannot install ggplot with conda-forge

Body:
I am trying to install ggplot with conda-forge. But it is showing some certain error. Details error message is given below.

(base) C:\Users\ASUS>conda install -c conda-forge ggplot=0.11.5

Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: failed with repodata from current_repodata.json, will retry with next repodata source.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: -
Found conflicts! Looking for incompatible packages.
This can take several minutes.  Press CTRL-C to abort.
failed

UnsatisfiableError: The following specifications were found
to be incompatible with the existing python installation in your environment:

Specifications:

  - ggplot=0.11.5 -> python[version='2.7.*|3.5.*|3.6.*|3.4.*']

Your python: python=3.7

If python is on the left-most side of the chain, that's the version you've asked for.
When python appears to the right, that indicates that the thing on the left is somehow
not available for the python version you are constrained to. Note that conda will not
change your python version to a different minor version unless you explicitly specify
that.

The following specifications were found to be incompatible with your CUDA driver:

  - feature:/win-64::__cuda==11.0=0
  - feature:|@/win-64::__cuda==11.0=0

Your installed CUDA driver is: 11.0

Please help me with any solution.

Body:
I have found an alternative of ggplot, which contains all ggplot function. It's plotnine.
To install plotnine

# Using pip
$ pip install plotnine         # 1. should be sufficient for most
$ pip install 'plotnine[all]'  # 2. includes extra/optional packages

# Or using conda
$ conda install -c conda-forge plotnine

For usage guideline please visit https://plotnine.readthedocs.io/en/stable/index.html


问:
Change page and URL without refreshing the Page
Hi and I'm terribly sorry for asking such question.

I'm quite catching up on Laravel, maybe 30% smarter than before but I'm stuck on this kind of scenario.

How do I call a blade with all parameters passed to its controller without refreshing the page.

Here's my folder structure (I will not place all just controller, pages)

Folrder Structure

Now, I'm in let's say dashboard.blade.php

In the Side bar of my dashboard I want to go to a link

```<code> <li class="nav-item">
   <a href="{{url('/get-greeting/{id}/{user}')}}" class="nav-link get-greeting">
      <i class="nav-icon fas fa-table"></i>
      <p>
         Requested Son
         <span class="right badge badge-danger side-span requested-span"></span>
      </p>
   </a>
</li>
</code>```

Route will be

```<code>Route::any('/get-greeting/{id}/{user}', 'DefaultController@pullGreeting')->name('getgreeting');
</code>```

Controller will be

```<code>public function pullGreeting($id, $user){

     $userName = User::activeUser($user);
     $defaultarray = array( 'greetingLogs' => recordLogs::pullgreetings($user) );
     return view('pages/department1/greetings',$defaultarray);

}
</code>```

When I click it, it refreshes the page. Anyone, can you help me and pinpoint where am I doing wrong so I can make it not refreshing the page but instead changing the blade dynamically?

Does this matter?

```<code>return view('pages/department1/greetings',$defaultarray);
</code>```

or

```<code>return view('pages.department1.greetings',$defaultarray);
</code>```

答:
PHP is a server-side programming language therefore any changes to the view will require a full page refresh.

Without the use of Javascript, achieving a part page refresh would require the use of an old school technique called Frames.

You could redesign your application to render HTML via different endpoints and have a Javascript powered frontend that calls to those endpoints.

You could easily achieve through the use of JS Libraries such as React or JQuery.

Body:
Hi and I'm terribly sorry for asking such question.

I'm quite catching up on Laravel, maybe 30% smarter than before but I'm stuck on this kind of scenario.

How do I call a blade with all parameters passed to its controller without refreshing the page.

Here's my folder structure (I will not place all just controller, pages)

Folrder Structure

Now, I'm in let's say dashboard.blade.php

In the Side bar of my dashboard I want to go to a link

         Requested Son

Route will be

Route::any('/get-greeting/{id}/{user}', 'DefaultController@pullGreeting')->name('getgreeting');

Controller will be

public function pullGreeting($id, $user){

     $userName = User::activeUser($user);
     $defaultarray = array( 'greetingLogs' => recordLogs::pullgreetings($user) );
     return view('pages/department1/greetings',$defaultarray);

}

When I click it, it refreshes the page. Anyone, can you help me and pinpoint where am I doing wrong so I can make it not refreshing the page but instead changing the blade dynamically?

Does this matter?

return view('pages/department1/greetings',$defaultarray);

or

return view('pages.department1.greetings',$defaultarray);


问:
What is the purpose of using JSON.stringify()?
I'm using JSON.stringify in my react redux application. What's the purpose of JSON.stringify in the following context? Even without JSON.stringify it works, but yet I've been advised to use JSON.stringify.

```<code>if (JSON.stringify(earlyBird.eBird) !== JSON.stringify(prevProps.earlyBird.eBird)) {
</code>```

答: it is used to convert the JSON objects to strings ..</p>

Body:
I'm using JSON.stringify in my react redux application. What's the purpose of JSON.stringify in the following context? Even without JSON.stringify it works, but yet I've been advised to use JSON.stringify.

if (JSON.stringify(earlyBird.eBird) !== JSON.stringify(prevProps.earlyBird.eBird)) {


问:
There's some error on my Flutter Local Notification
I need help, there's an error when calling Local Notification.

For the initState :

```<code>initState() {
    super.initState();
    flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
    // initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
    var initializationSettingsAndroid =
        new AndroidInitializationSettings('app_icon');
    var initializationSettingsIOS = new IOSInitializationSettings();
    var initializationSettings = new InitializationSettings(
        initializationSettingsAndroid, initializationSettingsIOS);
    FlutterLocalNotificationsPlugin().initialize(initializationSettings, onSelectNotification: onSelectNotification);
  }
</code>```

For the function :

```<code>showNotification() async {
    var android = new AndroidNotificationDetails('Channel ID', 'Channel Name', 'channelDescription');
    var iOS = new IOSNotificationDetails();
    var platform = new NotificationDetails(android, iOS);
    await flutterLocalNotificationsPlugin.show(
      0, 'New Notification', 'Flutter Local Notif', platform,payload: 'test notification');
  }
</code>```

The error is "PlatformException (PlatformException(error, Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference, null))"

I've already tried on the documentation and also youtube, but I always get this error message

答:
There is problem in your plugin initialization. I see in your code, you created the instance flutterLocalNotificationsPlugin but used FlutterLocalNotificationsPlugin().initialize() instead. And then you tried to show notification with the created instance which has not been initialized.

I got this error for the same reason - my FlutterLocalNotificationsPlugin was not initialized properly. To check if it is, I tried the below code:

```<code>void main() {
  runApp(MyApp());
  initializeNotification(); //Its Important to place this line after runApp() otherwise FlutterLocalNotificationsPlugin will not be initialize and you will get the error as mentioned in the question.
}

void initializeNotification() async {
  try {
    flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
    var initializationSettingsAndroid = AndroidInitializationSettings('app_icon');
    var initializationSettingsIOS = IOSInitializationSettings();
    var initializationSettings = InitializationSettings(initializationSettingsAndroid, initializationSettingsIOS);
    await flutterLocalNotificationsPlugin.initialize(initializationSettings, onSelectNotification: didSelectNotification);
  } catch(e) {
   print(e.toString());
  }
}
</code>```

If it catch any exception, your flutterLocalNotificationsPlugin has not been initialized, and you will get an error.

Also try to wrap initialization code in separate async-await function.

Body:
I need help, there's an error when calling Local Notification.

For the initState :

initState() {
    super.initState();
    flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
    // initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
    var initializationSettingsAndroid =
        new AndroidInitializationSettings('app_icon');
    var initializationSettingsIOS = new IOSInitializationSettings();
    var initializationSettings = new InitializationSettings(
        initializationSettingsAndroid, initializationSettingsIOS);
    FlutterLocalNotificationsPlugin().initialize(initializationSettings, onSelectNotification: onSelectNotification);
  }

For the function :

showNotification() async {
    var android = new AndroidNotificationDetails('Channel ID', 'Channel Name', 'channelDescription');
    var iOS = new IOSNotificationDetails();
    var platform = new NotificationDetails(android, iOS);
    await flutterLocalNotificationsPlugin.show(
      0, 'New Notification', 'Flutter Local Notif', platform,payload: 'test notification');
  }

The error is "PlatformException (PlatformException(error, Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference, null))"

I've already tried on the documentation and also youtube, but I always get this error message

Body:
There is problem in your plugin initialization. I see in your code, you created the instance flutterLocalNotificationsPlugin but used FlutterLocalNotificationsPlugin().initialize() instead. And then you tried to show notification with the created instance which has not been initialized.

I got this error for the same reason - my FlutterLocalNotificationsPlugin was not initialized properly. To check if it is, I tried the below code:

void main() {
  runApp(MyApp());
  initializeNotification(); //Its Important to place this line after runApp() otherwise FlutterLocalNotificationsPlugin will not be initialize and you will get the error as mentioned in the question.
}

void initializeNotification() async {
  try {
    flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
    var initializationSettingsAndroid = AndroidInitializationSettings('app_icon');
    var initializationSettingsIOS = IOSInitializationSettings();
    var initializationSettings = InitializationSettings(initializationSettingsAndroid, initializationSettingsIOS);
    await flutterLocalNotificationsPlugin.initialize(initializationSettings, onSelectNotification: didSelectNotification);
  } catch(e) {
   print(e.toString());
  }
}

If it catch any exception, your flutterLocalNotificationsPlugin has not been initialized, and you will get an error.

Also try to wrap initialization code in separate async-await function.


问:
How to import a Backbone/RequireJS module into a React/Webpack app
We have a legacy Backbone application that we are moving over to React. An interim step we are attempting is loading a bundled Backbone module into a React page, until we have time to fully rewrite it. I am halfway there, I can bundle up the app and all its dependencies with r.js using a config like this:

```<code>({
    ...
    baseUrl: './',
    name: 'myapp',
    paths: {
      'myapp': './legacy/app'
    },
    out: 'src/appbuilt.js'
    ...
})
</code>```

The module is set up like this:

```<code>define(function(require) {
    var $ = require('jquery'),
        _ = require('underscore'),
        ...
        templates = $(require('text!templates/app.html')),
        app = {};

    app.View = .....
    app.Model = .....

    return app;
});
</code>```

That bundle works on the Backbone side. Next I need to turn that into something I can import into React and render. I am trying things like this:

npx babel src/appbuilt.js --out-file src/appbuilt.es6.js --plugins=@babel/transform-modules-umd

Which works to give me a UMD module, but importing it like this:

import * as legacyapp from '../../appbuilt.es6';

Gives me warnings on the build like:

Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

And errors on page load that are probably symptoms of something:

Uncaught TypeError: name.split is not a function

What is the secret sauce to get my module converted into something I can use? I am open to modifying how the Backbone app does its imports, or making a wrapper of some kind that is more easily translatable.

答:
I am not sure but I can guess that the format of your AMD modules is the problem here. Try converting them to regular AMD modules:

define(
    ['jquery', 'underscore', 'text!templates/app.html' /* add rest of dependencies here */],
    function ($, underscore, templates /** add parameters for rest of dependencies here */)
    {
        var app = {};

        // app.View = ...
        // app.Model = ...

        return app;
    }
);
```

Body:
We have a legacy Backbone application that we are moving over to React. An interim step we are attempting is loading a bundled Backbone module into a React page, until we have time to fully rewrite it. I am halfway there, I can bundle up the app and all its dependencies with r.js using a config like this:

({
    ...
    baseUrl: './',
    name: 'myapp',
    paths: {
      'myapp': './legacy/app'
    },
    out: 'src/appbuilt.js'
    ...
})

The module is set up like this:

define(function(require) {
    var $ = require('jquery'),
        _ = require('underscore'),
        ...
        templates = $(require('text!templates/app.html')),
        app = {};

    app.View = .....
    app.Model = .....

    return app;
});

That bundle works on the Backbone side. Next I need to turn that into something I can import into React and render. I am trying things like this:

npx babel src/appbuilt.js --out-file src/appbuilt.es6.js --plugins=@babel/transform-modules-umd

Which works to give me a UMD module, but importing it like this:

import * as legacyapp from '../../appbuilt.es6';

Gives me warnings on the build like:

Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

And errors on page load that are probably symptoms of something:

Uncaught TypeError: name.split is not a function

What is the secret sauce to get my module converted into something I can use? I am open to modifying how the Backbone app does its imports, or making a wrapper of some kind that is more easily translatable.