问:
Representing a subnet mask and return the CIDR value
New to coding and stuck on this IP subnetting thing.

I have the code built out for a program running on 2 c files and a h file. When I try running, it says my IP address is invalid, but then I enter for example 10.152.34 that will work. But if I enter 10.152.34.67 then it says invalid.
It also says my subnet mask is invalid no matter what I put in. It should accept binary and subnet mask values (periods included) and return binary numbers.

e.g.

```<code>IP Address:  00001010 11000101 10011000 00001000 = 10.197.152.8

</code>```

Pretty sure my CIDR function (or lack there of) is part of the problem, but I'm honestly just lost at this point. I have tried two versions of this code - the first one got mad because I had declared functions several times. This one seems to at least get past compiling, but doesn't give the desired result. Any help or thoughts on  fixing the IP and subnet mask portion and building the CIDR function would me AMAZING!

Main Function

```<code>#include <stdio.h>
#include <string.h>

/*This program will display the IP address and subnet mask in binary
 format. It will also display the network address in binary and in
 CIDR formats.
*/

int main(void)
{

int i;
int ip[4];
int sub[4];
char *piece;
char ip_str[50];
char ip_str2[50];
char sub_str[50];
char sub_str2[50];

printf("Enter an IP address: ");
scanf("%s", & ip_str);
strcpy(ip_str2, ip_str);
   if(!ipVal(ip_str2))
   {
    printf("The ip address you entered (%s) is not valid.\n", ip_str);
    return 1;
   }
piece = strtok(ip_str, ".");
 i = 0;
while(piece && i <= 4)
{
 ip[i++] = atoi(piece);
 piece = strtok(NULL, ".");
}
printf("\n Enter the subnet mask: ");
scanf("%s", &sub_str);
strcpy(sub_str2, sub_str);
if(!subVal(sub_str2))

{
printf("The subnet address you entered (%s) is not valid.\n", sub_str);
return 1;
}

piece = strtok(sub_str, ".");
i = 0;
while(piece && i < 4)

{
sub[i++] = atoi (piece);
piece = strtok(NULL, ".");
}

printf("\n");

bit_print(pack(ip[0], ip[1], ip[2], ip[3]));
bit_print(pack(sub[0], sub[1], sub[2], sub[3]));

printf("IP Address: %s\n", ip_str);
printf("Subnet Mask: %s\n", sub_str);

printf("\nThank you for using ip158.\n");

}
</code>```

# ipfunc.c

```<code>#include "ipfunc.h"
#include <string.h>
#include <stdio.h>
#include <limits.h>

int val_digit(char *ptr)
{

while(*ptr)
{
if(!isdigit(*ptr))
 {
return 0;
}
ptr++;
 }
return 1;
}

int valid_sub(int num)
{
int found = -1;
int sub[] = {0, 128, 192, 224, 240, 248, 252, 254, 255};
int i;

for (i = 0; i < 9; i++)
{
if (num == sub[i])
{
found = i;
break;
 }
}

if (found != -1)
{
return 1;
else {
return 0;
 }
}

int pack (int a, int b, int c, int d)
{
int p = a;

p = (p << CHAR_BIT) | b;
p = (p << CHAR_BIT) | c;
p = (p << CHAR_BIT) | d;
return p;
}
char unpack(int p, int k)
{
int n = k * CHAR_BIT;
unsigned mask = 225;

mask <<= n;
return ((p & mask) >> n);
}

int ipVal(char *ip_str)
{
int i, num, dec = 0;
char *buff = ip_str;
char *ptr;

if (buff == NULL)
return 0;
ptr = strtok(buff, ".");
if (ptr == NULL)
return 0;

while (ptr)
{
if (!val_digit(ptr))
return 0;
num = atoi(ptr);

if (num >= 0 && num <= 255)
{
ptr = strtok(NULL, ".");
if (ptr != NULL)
dec++;
else
return 0;
}
if (dec != 3)
return 1;
}

int subVal(char *sub_str)
{
int i, num, dec = 0;
char *ptr;

if (sub_str == NULL)
return 0;
ptr - strtok(sub_str, ".");
if (ptr == NULL)
return 0;
while (ptr)
{
if (!val_digit(ptr))
return 0;
num = atoi(ptr);
if (valid_sub(num))
{
ptr = strtok(NULL, ".");
if (ptr != NULL)
dec++;
else
return 0;
}
if (dec != 3)
return 0;
return 1;
}

int cmpCIDR(unsigned int p) {}
</code>```

# ipfunc.h

```<code>#include <stdio.h>

int pack(int a, int b, int c, int d);
char unpack(int p, int k);
int ipVal(char *ip_str);
int subVal(char *cub_str);
int cmpCIDR(unsigned int p);`
</code>```

Thank you so much!!

I've tried two sets of different code - this set gave me the least errors and at least got past compiling stage and the program began to run. I'm expecting the program to request user input for the IP and subnet mask, and to return the values in binary.

Body:
New to coding and stuck on this IP subnetting thing.

I have the code built out for a program running on 2 c files and a h file. When I try running, it says my IP address is invalid, but then I enter for example 10.152.34 that will work. But if I enter 10.152.34.67 then it says invalid.
It also says my subnet mask is invalid no matter what I put in. It should accept binary and subnet mask values (periods included) and return binary numbers.

e.g.

IP Address:  00001010 11000101 10011000 00001000 = 10.197.152.8

Pretty sure my CIDR function (or lack there of) is part of the problem, but I'm honestly just lost at this point. I have tried two versions of this code - the first one got mad because I had declared functions several times. This one seems to at least get past compiling, but doesn't give the desired result. Any help or thoughts on  fixing the IP and subnet mask portion and building the CIDR function would me AMAZING!

Main Function

#include <stdio.h>
#include <string.h>

/*This program will display the IP address and subnet mask in binary
 format. It will also display the network address in binary and in
 CIDR formats.
*/

int main(void)
{

int i;
int ip[4];
int sub[4];
char *piece;
char ip_str[50];
char ip_str2[50];
char sub_str[50];
char sub_str2[50];

printf("Enter an IP address: ");
scanf("%s", & ip_str);
strcpy(ip_str2, ip_str);
   if(!ipVal(ip_str2))
   {
    printf("The ip address you entered (%s) is not valid.\n", ip_str);
    return 1;
   }
piece = strtok(ip_str, ".");
 i = 0;
while(piece && i <= 4)
{
 ip[i++] = atoi(piece);
 piece = strtok(NULL, ".");
}
printf("\n Enter the subnet mask: ");
scanf("%s", &sub_str);
strcpy(sub_str2, sub_str);
if(!subVal(sub_str2))

{
printf("The subnet address you entered (%s) is not valid.\n", sub_str);
return 1;
}

piece = strtok(sub_str, ".");
i = 0;
while(piece && i < 4)

{
sub[i++] = atoi (piece);
piece = strtok(NULL, ".");
}

printf("\n");

bit_print(pack(ip[0], ip[1], ip[2], ip[3]));
bit_print(pack(sub[0], sub[1], sub[2], sub[3]));

printf("IP Address: %s\n", ip_str);
printf("Subnet Mask: %s\n", sub_str);

printf("\nThank you for using ip158.\n");

}

# ipfunc.c

#include "ipfunc.h"
#include <string.h>
#include <stdio.h>
#include <limits.h>

int val_digit(char *ptr)
{

while(*ptr)
{
if(!isdigit(*ptr))
 {
return 0;
}
ptr++;
 }
return 1;
}

int valid_sub(int num)
{
int found = -1;
int sub[] = {0, 128, 192, 224, 240, 248, 252, 254, 255};
int i;

for (i = 0; i < 9; i++)
{
if (num == sub[i])
{
found = i;
break;
 }
}

if (found != -1)
{
return 1;
else {
return 0;
 }
}

int pack (int a, int b, int c, int d)
{
int p = a;

p = (p << CHAR_BIT) | b;
p = (p << CHAR_BIT) | c;
p = (p << CHAR_BIT) | d;
return p;
}
char unpack(int p, int k)
{
int n = k * CHAR_BIT;
unsigned mask = 225;

mask <<= n;
return ((p & mask) >> n);
}

int ipVal(char *ip_str)
{
int i, num, dec = 0;
char *buff = ip_str;
char *ptr;

if (buff == NULL)
return 0;
ptr = strtok(buff, ".");
if (ptr == NULL)
return 0;

while (ptr)
{
if (!val_digit(ptr))
return 0;
num = atoi(ptr);

if (num >= 0 && num <= 255)
{
ptr = strtok(NULL, ".");
if (ptr != NULL)
dec++;
else
return 0;
}
if (dec != 3)
return 1;
}

int subVal(char *sub_str)
{
int i, num, dec = 0;
char *ptr;

if (sub_str == NULL)
return 0;
ptr - strtok(sub_str, ".");
if (ptr == NULL)
return 0;
while (ptr)
{
if (!val_digit(ptr))
return 0;
num = atoi(ptr);
if (valid_sub(num))
{
ptr = strtok(NULL, ".");
if (ptr != NULL)
dec++;
else
return 0;
}
if (dec != 3)
return 0;
return 1;
}

int cmpCIDR(unsigned int p) {}

# ipfunc.h

#include <stdio.h>

int pack(int a, int b, int c, int d);
char unpack(int p, int k);
int ipVal(char *ip_str);
int subVal(char *cub_str);
int cmpCIDR(unsigned int p);`

Thank you so much!!

I've tried two sets of different code - this set gave me the least errors and at least got past compiling stage and the program began to run. I'm expecting the program to request user input for the IP and subnet mask, and to return the values in binary.


来源: stackexchange

问:
How can I update previous logs from winston in the console?
I need to use multiple logger instances at the same time, so the logs of all loggers need to be updated on each line of each logger

How can I do this?

I tried to use one instance logger, but the logs is unreadable and hard to understand

That's a example of what I wanted:

Example code:

Logger.getLogger("A").info("test1: A");
Logger.getLogger("B").info("Message with label: B");
Logger.getLogger("A").info("test2: A");

```
<p>Output should be:</p>
<pre class="lang-ts prettyprint-override"><code>2022-12-11T14:49:39.829Z info [A]     test2: A // prev log was 'test1: A'
2022-12-11T14:49:39.828Z info [B]     Message with label: B
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to use multiple logger instances at the same time, so the logs of all loggers need to be updated on each line of each logger

How can I do this?

I tried to use one instance logger, but the logs is unreadable and hard to understand

That's a example of what I wanted:

Example code:

Logger.getLogger("A").info("test1: A");
Logger.getLogger("B").info("Message with label: B");
Logger.getLogger("A").info("test2: A");

Output should be:

2022-12-11T14:49:39.829Z info [A]     test2: A // prev log was 'test1: A'
2022-12-11T14:49:39.828Z info [B]     Message with label: B


问:
Background push notification with websocket
I'm tring to show push notification on background (even the browser closed) when websocket received message.
What can i do?</p>


问:
MVC vs Native style in terms of Latency of the system
Are there any concise proven studies/article on the advantage and disadvantage of Model View Controller (MVC) : in terms of its latency of the system development vs the Native ways?

So let's say I have hundreds of user transact the system at the same time and it causes network latency/delay, what are the advantage of MVC if applied in the system? vs native, Thanks in advance!


问:
why vscode debug doesn't recognize local #include?
I have been stuck on this bug for a few hours now.
I wrote some code in C that uses functions and structs from another C file that I wrote. when I run the code manually (with the makefile I wrote) it runs.
the makefile:

```<code>    exec: ../LineParser.c main_c_file.c
        gcc -g -m32 -Wall -c ../LineParser.c -o LineParser.o
        gcc -g -m32 -Wall -c main_c_file.c -o main_c_file.o
        gcc -g -m32 -Wall LineParser.o main_c_file.o  -o main_c_file

        rm LineParser.o main_c_file.o
</code>```

but when I am trying to debug it I get the error:

```<code>    /dir1/dir2/task2/main_c_file.c:123: undefined reference to imported_function'
    collect2: error: ld returned 1 exit status

    Build finished with error(s).
     *  The terminal process failed to launch (exit code: -1).
</code>```

I tried

adding -g to the make file.

to first compile the code
and then add its full path to the program tag in the debug configuration file

```<code>    {
    linkid=830387
        "version": "0.2.0",
        "configurations": [
            {
                "type": "by-gdb",
                "request": "launch",
                "name": "Launch(gdb)",
                "program": "/dir1/dir2/main_c_file",
                "cwd": "${workspaceRoot}"
            }
        ]
    }
</code>```

by the way I am runing this code in Linux

Body:
I have been stuck on this bug for a few hours now.
I wrote some code in C that uses functions and structs from another C file that I wrote. when I run the code manually (with the makefile I wrote) it runs.
the makefile:

    exec: ../LineParser.c main_c_file.c
        gcc -g -m32 -Wall -c ../LineParser.c -o LineParser.o
        gcc -g -m32 -Wall -c main_c_file.c -o main_c_file.o
        gcc -g -m32 -Wall LineParser.o main_c_file.o  -o main_c_file

        rm LineParser.o main_c_file.o

but when I am trying to debug it I get the error:

    /dir1/dir2/task2/main_c_file.c:123: undefined reference to imported_function'
    collect2: error: ld returned 1 exit status

    Build finished with error(s).
     *  The terminal process failed to launch (exit code: -1).

I tried

adding -g to the make file.

to first compile the code
and then add its full path to the program tag in the debug configuration file

    {
    linkid=830387
        "version": "0.2.0",
        "configurations": [
            {
                "type": "by-gdb",
                "request": "launch",
                "name": "Launch(gdb)",
                "program": "/dir1/dir2/main_c_file",
                "cwd": "${workspaceRoot}"
            }
        ]
    }

by the way I am runing this code in Linux


问:
Excel VBA: How to remove cell fill colour whenever a string is entered into the cell
I am fairly new, so bear with me. I have a shared excel file that multiple users can read/write. It comes with a section where a user can acknowledge they've read the worksheet  using this code:

```<code>Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    If Not Intersect(Target, Range("I9:J359")) Is Nothing Then
    If Target.Cells.Count > 1 Then Exit Sub
    Cancel = True
        If Target.Interior.ColorIndex = xlNone Then
            Target.Interior.ColorIndex = 35
        Else
           If Target.Interior.ColorIndex = 35 Then Target.Interior.ColorIndex = xlNone
        End If
    End If
    End Sub
</code>```

Users would just double click to colour their names in. Users can also input new messages into the worksheet. Therein lies the problem of new 'messages' being input with names coloured in showing they have read the message when they have not.

Is there a code that would 'uncolour' the users list when a new message is entered - meaning user would know there are new inputs and would need to acknowledge the latest update in the worksheet.

Body:
I am fairly new, so bear with me. I have a shared excel file that multiple users can read/write. It comes with a section where a user can acknowledge they've read the worksheet  using this code:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    If Not Intersect(Target, Range("I9:J359")) Is Nothing Then
    If Target.Cells.Count > 1 Then Exit Sub
    Cancel = True
        If Target.Interior.ColorIndex = xlNone Then
            Target.Interior.ColorIndex = 35
        Else
           If Target.Interior.ColorIndex = 35 Then Target.Interior.ColorIndex = xlNone
        End If
    End If
    End Sub

Users would just double click to colour their names in. Users can also input new messages into the worksheet. Therein lies the problem of new 'messages' being input with names coloured in showing they have read the message when they have not.

Is there a code that would 'uncolour' the users list when a new message is entered - meaning user would know there are new inputs and would need to acknowledge the latest update in the worksheet.


问:
Google Cloud Functions with Google Cloud Storage
I am planning to deploy a small project on Google Cloud Functions and is using the Google Cloud Storage as well.

I notice that instead of using the os module to call the credential, I need to call from the service account file.

e.g.

credentials = service_account.Credentials.from_service_account_file('xx.json')
 storage_client = storage.Client(credentials=credentials)
```

Then, the errorI　dont' have much experence to tell which point shall I check.

I have do the from google.oauth2 import service_account and from google.cloud import storage and put the credential json key under the cloud functions' temp.

I wonder which process or details have I missed?

Do I need to manually activate the Oauth permision on somewhere or something?
Any pointers? Welcome for any advices and comments.

Body:
I am planning to deploy a small project on Google Cloud Functions and is using the Google Cloud Storage as well.

I notice that instead of using the os module to call the credential, I need to call from the service account file.

e.g.

credentials = service_account.Credentials.from_service_account_file('xx.json')
 storage_client = storage.Client(credentials=credentials)

Then, the errorI　dont' have much experence to tell which point shall I check.

I have do the from google.oauth2 import service_account and from google.cloud import storage and put the credential json key under the cloud functions' temp.

I wonder which process or details have I missed?

Do I need to manually activate the Oauth permision on somewhere or something?
Any pointers? Welcome for any advices and comments.


问:
I am getting an error while debugging the demo program on Flutter using both vs code and also android studio,
So, i've installed all the requirements for flutter doctor and its showing all green. but when i create a new project and debug it to check whether its working. its giving me this error on both vs code as well as android studio:

```<code>Launching lib\main.dart on sdk gphone64 x86 64 in debug mode...
lib\main.dart:1
Exception in thread "main" java.net.ConnectException: Connection refused: connect
    at java.base/java.net.PlainSocketImpl.connect0(Native Method)
    at java.base/java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:101)
    at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399)
    at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242)
        at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224)
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.base/java.net.Socket.connect(Socket.java:609)
    at java.base/sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:299)
    at java.base/sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:173)
    at java.base/sun.net.NetworkClient.doConnect(NetworkClient.java:182)
    at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:474)
    at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:569)
        at java.base/sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:266)
    at java.base/sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:373)
    at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:203)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1187)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1081)
    at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:189)
        at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1592)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1520)
    at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:250)
    at org.gradle.wrapper.Download.downloadInternal(Download.java:58)
    at org.gradle.wrapper.Download.download(Download.java:44)
    at org.gradle.wrapper.Install$1.call(Install.java:61)
    at org.gradle.wrapper.Install$1.call(Install.java:48)
        at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65)
    at org.gradle.wrapper.Install.createDist(Install.java:48)
    at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128)
    at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
Exception: Gradle task assembleDebug failed with exit code 1
Exited (sigterm)
</code>```

I tried running the demo flutter code and expect it to gave me an emulator showing the incrementing app

Body:
So, i've installed all the requirements for flutter doctor and its showing all green. but when i create a new project and debug it to check whether its working. its giving me this error on both vs code as well as android studio:

Launching lib\main.dart on sdk gphone64 x86 64 in debug mode...
lib\main.dart:1
Exception in thread "main" java.net.ConnectException: Connection refused: connect
    at java.base/java.net.PlainSocketImpl.connect0(Native Method)
    at java.base/java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:101)
    at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399)
    at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242)
        at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224)
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.base/java.net.Socket.connect(Socket.java:609)
    at java.base/sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:299)
    at java.base/sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:173)
    at java.base/sun.net.NetworkClient.doConnect(NetworkClient.java:182)
    at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:474)
    at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:569)
        at java.base/sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:266)
    at java.base/sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:373)
    at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:203)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1187)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1081)
    at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:189)
        at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1592)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1520)
    at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:250)
    at org.gradle.wrapper.Download.downloadInternal(Download.java:58)
    at org.gradle.wrapper.Download.download(Download.java:44)
    at org.gradle.wrapper.Install$1.call(Install.java:61)
    at org.gradle.wrapper.Install$1.call(Install.java:48)
        at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65)
    at org.gradle.wrapper.Install.createDist(Install.java:48)
    at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128)
    at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
Exception: Gradle task assembleDebug failed with exit code 1
Exited (sigterm)

I tried running the demo flutter code and expect it to gave me an emulator showing the incrementing app


问:
FileNotFoundError every time I try to download a video using PyTube
Every time I try to download a video using Pytube, it generates this error:

```<code>FileNotFoundError: [Errno 2] No such file or directory:
</code>```

Recently it has been showing this error. Before, it worked completely fine. Here's my code:

```<code>def vid_only():
    for stream in yt.streams.filter(only_video=True, adaptive=True, file_extension="mp4"):
        res_avail.add((stream.resolution))
    r = ", ".join(res_avail)
    print(f"Available resolutions:  {r}")

    res_choose = input("Input your desired resolution: ")
    print("Downloading . . .")
    vid_download = yt.streams.filter(res=res_choose.lower()).first()
    vid_download.download(filename=yt.title + " VIDEO ONLY.mp4")

link = input("Input youtube link: ")
yt = YouTube(link)
res_avail = set()
stream_type = int(input("Types: \n1. Video only \n2. Audio only \n3. Video with audio \nEnter the number of the type you want to download: "))

if stream_type == 1:
    vid_only()
</code>```

Is there something wrong with this line?

```<code>vid_download.download(filename=yt.title + " VIDEO ONLY.mp4")
</code>```

Body:
Every time I try to download a video using Pytube, it generates this error:

FileNotFoundError: [Errno 2] No such file or directory:

Recently it has been showing this error. Before, it worked completely fine. Here's my code:

def vid_only():
    for stream in yt.streams.filter(only_video=True, adaptive=True, file_extension="mp4"):
        res_avail.add((stream.resolution))
    r = ", ".join(res_avail)
    print(f"Available resolutions:  {r}")

    res_choose = input("Input your desired resolution: ")
    print("Downloading . . .")
    vid_download = yt.streams.filter(res=res_choose.lower()).first()
    vid_download.download(filename=yt.title + " VIDEO ONLY.mp4")

link = input("Input youtube link: ")
yt = YouTube(link)
res_avail = set()
stream_type = int(input("Types: \n1. Video only \n2. Audio only \n3. Video with audio \nEnter the number of the type you want to download: "))

if stream_type == 1:
    vid_only()

Is there something wrong with this line?

vid_download.download(filename=yt.title + " VIDEO ONLY.mp4")


问:
Getting native Xcode on m1 to build x86 packages for simulator
I'm tying to get Xcode in native mode to use the simulators in Rosetta mode, I found this site, which seems to be trying to work except the packages will not build x86 simulator binaries for the simulator, and so I get errors now saying "Could not find module 'xxx' for target 'x86_64-apple-ios-simulator'; found: arm64, arm64-apple-ios-simulator...", it does work if you target a physical device.

We can't switch to m1 completely yet, because of a library built for us by a third party vendor doesn't include the binary for arm simulators, I don't know why it can't just use the normal arm binary.

We have problems with Xcode code in Rosetta mode as well as we have a few IBDesignable UIView subclasses, rosetta Xcode runs a seperate process to generate binaries for these elements to show their fields in Interface Builder, but this process is generating arm64 binaries, which Xcode in rosetta mode doesn't like and throws errors.

I have asked for the supplier of the framework to compile it to support m1 as they are giving us a new version soon, but its unlikely to happen.

In the mean time, I'm trying to find a way to tell Xcode to build the Packages for x86 simulator, the fields Architectures, Exclude Architectures and Build Active Architecture Only don't seem to effect how the packages are built.


问:
How to use Genetic Algorithm as an optimizer in LSTM
I wish to train an LSTM sequential model for prediction analysis.

The network looks as such:

```<code>model = Sequential()

## Add the 1st LSTM layer
model.add(LSTM(units=hidden_neurons_1,
               input_shape=(sequence_length, nb_features),
               return_sequences=True))

## Avoid overfitting
model.add(Dropout(DROPOUT_VALUE))

## Add the 2nd LSTM layer
model.add(LSTM( units=hidden_neurons_2,
                return_sequences=False))

## Avoid overfitting
model.add(Dropout(DROPOUT_VALUE))

## Number of outputs
model.add(Dense(units = 1))

## Select activation function
model.add(Activation("linear"))

## Compile the model
model.compile(loss='mean_squared_error', ## Loss function
              optimizer='rmsprop')       ## Optimizer to update the weights and biases
</code>```

Here, by default Keras offers a list of certain optimizers as given here.

However, I wish to use Genetic Algorithm as an optimizer to update the weights and biases.

Can somebody please help me out to understand how to achieve this.

Body:
I wish to train an LSTM sequential model for prediction analysis.

The network looks as such:

model = Sequential()

## Add the 1st LSTM layer
model.add(LSTM(units=hidden_neurons_1,
               input_shape=(sequence_length, nb_features),
               return_sequences=True))

## Avoid overfitting
model.add(Dropout(DROPOUT_VALUE))

## Add the 2nd LSTM layer
model.add(LSTM( units=hidden_neurons_2,
                return_sequences=False))

## Avoid overfitting
model.add(Dropout(DROPOUT_VALUE))

## Number of outputs
model.add(Dense(units = 1))

## Select activation function
model.add(Activation("linear"))

## Compile the model
model.compile(loss='mean_squared_error', ## Loss function
              optimizer='rmsprop')       ## Optimizer to update the weights and biases

Here, by default Keras offers a list of certain optimizers as given here.

However, I wish to use Genetic Algorithm as an optimizer to update the weights and biases.

Can somebody please help me out to understand how to achieve this.


问:
Why JSX part is causing syntax error: unexpected token error while deploying?
I have built a MERN application and trying to deploy it on render.com

The JSX part is causing error as:

```<code>                           SyntaxError: dist/client/src/App.js: Unexpected token (35:8)
Dec 10 01:30:11 PM    33 |     }, []);
Dec 10 01:30:11 PM    34 |     return (
Dec 10 01:30:11 PM  > 35 |         <react_router_1.Routes>
Dec 10 01:30:11 PM       |         ^
.....
.....

</code>```

I tried to add babel dependencies in my package.json:

```<code>"@babel/cli": "^7.10.3",
"@babel/core": "^7.10.3",
"@babel/node": "^7.10.3",
"@babel/preset-env": "^7.10.3",

</code>```

But still, the error persists. please guide me.

Body:
I have built a MERN application and trying to deploy it on render.com

The JSX part is causing error as:

                           SyntaxError: dist/client/src/App.js: Unexpected token (35:8)
Dec 10 01:30:11 PM    33 |     }, []);
Dec 10 01:30:11 PM    34 |     return (
Dec 10 01:30:11 PM  > 35 |         <react_router_1.Routes>
Dec 10 01:30:11 PM       |         ^
.....
.....

I tried to add babel dependencies in my package.json:

"@babel/cli": "^7.10.3",
"@babel/core": "^7.10.3",
"@babel/node": "^7.10.3",
"@babel/preset-env": "^7.10.3",

But still, the error persists. please guide me.


问:
Why is this error occurring? I'd also like to know how to fix it
You have configured a VPC in AWS and created an EC2 instance. After installing apache, mysql, php on the EC2 server, I downloaded wordpress and copied it to the /var/www/html directory. I entered my db credentials in wp-config.php and accessed the website through public ip.

Select a country

Enter website information (sitename, username, password etc.)

The following error occurred when I proceeded to the above procedure and pressed the WordPress installation button. I tried the solution suggested in aws.

https://aws.amazon.com/ko/premiumsupport/knowledge-center/rds-mysql-access-denied/

However, the same error is still occurring. I want to know the cause and solution.

error img)

sql connection)

rds state)

```<code>1. IAM authentication is off
2. Insufficient IAM Role Permissions
3. Database User Improperly Configured
4. Invalid connection string
</code>```

Body:
You have configured a VPC in AWS and created an EC2 instance. After installing apache, mysql, php on the EC2 server, I downloaded wordpress and copied it to the /var/www/html directory. I entered my db credentials in wp-config.php and accessed the website through public ip.

Select a country

Enter website information (sitename, username, password etc.)

The following error occurred when I proceeded to the above procedure and pressed the WordPress installation button. I tried the solution suggested in aws.

https://aws.amazon.com/ko/premiumsupport/knowledge-center/rds-mysql-access-denied/

However, the same error is still occurring. I want to know the cause and solution.

error img)

sql connection)

rds state)

1. IAM authentication is off
2. Insufficient IAM Role Permissions
3. Database User Improperly Configured
4. Invalid connection string


问:
How down I implement the load more data button to a list in react?
I'm struggling to find a solution that works to implement a load more button properly. I want the button to show when the list is 50. Also it disappears when its less that 50 or length of list(i.e the end of the list)

```<code>function AllReferral() {
           const [formalDetails, setFormalDetails] = useState([]);
           const [limit, setLimit] = useState(50);

const getFormalDetails = useCallback(async () => {
        await Axios.post(
            `${baseUrl}/records?limit=${limit}&skip=0`,
        ).then((response) => {
            const details = response.data.Details;
            setFormalDetails(details);
        });
    }, [limit, baseUrl]);

    const getFormalDetails2 = useCallback(async () => {

        try {
            const fetch = await Axios.post(
                `${baseUrl}/records?limit=${limit}&skip=0`,
            );
            const result = fetch.data.Details;
            return result;
        } catch (err) {
            console.log(err);
        }
    }, [limit, baseUrl]);

const fetchData = async () => {
        const nextPage = await getFormalDetails2();
        setFormalDetails([...formalDetails, ...nextPage]);
        if (nextPage.length === 0) {
            return;
        }
        setLimit(limit + 50);
    };

  return (
    <section>
      <div>

        {formalDetails?.length > 0 && (
          <div>
            <table>
              <thead>
                <tr>
                  <th >Service Name</th>

                </tr>
              </thead>
              {formalDetails?.map((item, index) => (
                <tbody key={index}>
                  <tr>

                    <td>{item?.label}</td>
                  </tr>
                </tbody>
              ))}
            </table>
{
                limit < formalDetails?.length && (
                <button
                type="button"
                onClick={() => fetchData()}
            >
            load More
            </button>
                )
            }
          </div>
        )}
      </div>
    </section>
  );
}

</code>```

From the above code, the button doesn't show on first render. I also tried to use css such that when formalDetails.length === 0 display to none, it worked but not expected because if I have 30 items on list the button shows. I only want the button to show if the list items is 50 and disappears when items === 0 or at the end of the list.

Body:
I'm struggling to find a solution that works to implement a load more button properly. I want the button to show when the list is 50. Also it disappears when its less that 50 or length of list(i.e the end of the list)

function AllReferral() {
           const [formalDetails, setFormalDetails] = useState([]);
           const [limit, setLimit] = useState(50);

const getFormalDetails = useCallback(async () => {
        await Axios.post(
            `${baseUrl}/records?limit=${limit}&skip=0`,
        ).then((response) => {
            const details = response.data.Details;
            setFormalDetails(details);
        });
    }, [limit, baseUrl]);

    const getFormalDetails2 = useCallback(async () => {

        try {
            const fetch = await Axios.post(
                `${baseUrl}/records?limit=${limit}&skip=0`,
            );
            const result = fetch.data.Details;
            return result;
        } catch (err) {
            console.log(err);
        }
    }, [limit, baseUrl]);

const fetchData = async () => {
        const nextPage = await getFormalDetails2();
        setFormalDetails([...formalDetails, ...nextPage]);
        if (nextPage.length === 0) {
            return;
        }
        setLimit(limit + 50);
    };

  return (

        {formalDetails?.length > 0 && (

                  Service Name

              {formalDetails?.map((item, index) => (

                    {item?.label}

              ))}

{
                limit < formalDetails?.length && (
                <button
                type="button"
                onClick={() => fetchData()}
            >
            load More
            </button>
                )
            }

        )}

  );
}

From the above code, the button doesn't show on first render. I also tried to use css such that when formalDetails.length === 0 display to none, it worked but not expected because if I have 30 items on list the button shows. I only want the button to show if the list items is 50 and disappears when items === 0 or at the end of the list.


问:
show table td using flex box direction in column
I need to add flex-direction: column into table tr to show td on order column like this:

HTML:

```<code><table>
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
  </tbody>
</table>
</code>```

CSS:

```<code>table {
  width: 100%;
  height: 150px
}

tr {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
}

td {
  flex: 1 1 20px;
  background-color: #ddd
}
</code>```

But in action I see :

How do can I fix this problem?!

Body:
I need to add flex-direction: column into table tr to show td on order column like this:

HTML:

      1
      2
      3
      4

CSS:

table {
  width: 100%;
  height: 150px
}

tr {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
}

td {
  flex: 1 1 20px;
  background-color: #ddd
}

But in action I see :

How do can I fix this problem?!


问:
When I save my HTML file in WebStorm, it reloads from disk with file watcher
When I save my html file in WebStorm, all changes are revert (as if I would press Ctrl + Alt + Y). But it happens only if any file watcher is active. I use standard SCSS file watcher.

I tried to change settings (files to refresh, arguments, auto-save) but it changed nothing.

P.S. Sorry for bad English.

UPDATE: It also works in other JetBrains IDEs.

UPDATE 2:

I invalidated caches, created other project, created other scss file watcher, added $ProjectFileDir$ to "outputs paths to refresh" and the issue was solved!

It's so strange, even using other IDE didn't help, but creating other project did.


问:
Sharing file handles across worker threads in node.js
In very simple term i have an application which appends to file post doing some compute, to speed up this i broke the operation in chuncks equal to worker threads available to me so that each can run the compute and purge it to disk, since they are going to append to the same file can i open the file handle on main thread and pass it to the worker threads or i have to open same file on all worker threads?</p>


问:
Is it possible to replace Thymeleaf fragment via JQuery directly?
I'm trying to figure out how to replace the Thymeleaf fragment with jQuery.

This is what I tried:

```<code>$("#dataTable").replaceWith("user_panel/fragments/languages_list_fragment.html :: #languages_list_element");
</code>```

It performs a replacement, but the element is replaced with text rather than a fragment.

What I anticipate is simply reloading the data without involving the backend.

As I previously stated, I couldn't find any examples on the internet that directly answered my question, which is why I'm asking here.

Body:
I'm trying to figure out how to replace the Thymeleaf fragment with jQuery.

This is what I tried:

$("#dataTable").replaceWith("user_panel/fragments/languages_list_fragment.html :: #languages_list_element");

It performs a replacement, but the element is replaced with text rather than a fragment.

What I anticipate is simply reloading the data without involving the backend.

As I previously stated, I couldn't find any examples on the internet that directly answered my question, which is why I'm asking here.


问:
How to pass an array into an hidden input value in javascript and retrieve it
I want to pass an array into an hidden  input and be able to return it, but instead of doing this, the value is a string, as shown below :

Input :

<input type="hidden" name="LabelProduitInput" value=${labelProduitsArray}>```
</div>
</div>
</p>
<p>retrieve hidden input value and log it :</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const labelProduitsArray = [product.fields.LabelProduitInput];

console.log(labelProduitsArray);</code>```

Result :

[ "BlaBla,BloBlo" ]

Now, i should split this string to have the result i want like so:

["BlaBla","BloBlo"]

Is there a way to directly return an array ?

Body:
I want to pass an array into an hidden  input and be able to return it, but instead of doing this, the value is a string, as shown below :

Input :

<input type="hidden" name="LabelProduitInput" value=${labelProduitsArray}>

retrieve hidden input value and log it :

const labelProduitsArray = [product.fields.LabelProduitInput];

console.log(labelProduitsArray);

Result :

[ "BlaBla,BloBlo" ]

Now, i should split this string to have the result i want like so:

["BlaBla","BloBlo"]

Is there a way to directly return an array ?


问:
Vue3 delay DefineAsyncComponent
I like to lazyload components in my Vue3 SPA with:

```<code>    "GoogleMap": defineAsyncComponent(() => import('@/components/GoogleMap.vue')),
</code>```

This Component is at my pagebottom, so I think it should only loads if I scroll it into my view?

My problem is that all of the chunks are directly loaded on Pageload, even if my page is very long?

How can I fix that or is this the normal behavior for async Components and it "only" loads the chunks async and not fireing on pagescroll if the component comes into my viewport?

Title: Vue3 delay DefineAsyncComponent

Body:
I like to lazyload components in my Vue3 SPA with:

    "GoogleMap": defineAsyncComponent(() => import('@/components/GoogleMap.vue')),

This Component is at my pagebottom, so I think it should only loads if I scroll it into my view?

My problem is that all of the chunks are directly loaded on Pageload, even if my page is very long?

How can I fix that or is this the normal behavior for async Components and it "only" loads the chunks async and not fireing on pagescroll if the component comes into my viewport?


问:
Unsupported operation: Nan or infinity toInt for Tween Animation
I have found a code that i tried to replicate. It has an app itself and it is working. However when i tried to write the code down it shows the problem Unsupported operation NaN or infinity toInt for a function named TweenAnimation. I am still trying to learn how to use tween animation so any pros have any idea on this problem?

below is the code for the animation

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

class AnimatedFlipCounter extends StatelessWidget {
  final int value;
  final Duration duration;
  final double size;
  final Color color;

  const AnimatedFlipCounter({
    Key? key,
    required this.value,
    required this.duration,
    this.size = 72,
    this.color = Colors.black,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    List<int> digits = value == 0 ? [0] : [];

    int v = value;
    if (v < 0) {
      v *= -1;
    }
    while (v > 0) {
      digits.add(v);
      v = v ~/ 10;
    }

    return Row(
      mainAxisSize: MainAxisSize.min,
      children: List.generate(digits.length, (int i) {
        return _SingleDigitFlipCounter(
          key: ValueKey(digits.length - i),
          value: digits[digits.length - i - 1].toDouble(),
          duration: duration,
          height: size,
          width: size / 1.8,
          color: color,
        );
      }),
    );
  }
}

class _SingleDigitFlipCounter extends StatelessWidget {
  final double value;
  final Duration duration;
  final double height;
  final double width;
  final Color color;

  const _SingleDigitFlipCounter({
    required Key key,
    required this.value,
    required this.duration,
    required this.height,
    required this.width,
    required this.color,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TweenAnimationBuilder(
      tween: Tween(begin: value, end: value),
      duration: duration,
      builder: (context,double value, child) {
        final whole = 1.0 ~/ value ;
        final decimal = value - whole;
        return SizedBox(
          height: height,
          width: width,
          child: Stack(
            fit: StackFit.expand,
            children: <Widget>[
              _buildSingleDigit(
                digit: whole % 10,
                offset: height * decimal,
                opacity: 1.0 - decimal,
              ),
              _buildSingleDigit(
                digit: (whole + 1) % 10,
                offset: height * decimal - height,
                opacity: decimal,
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildSingleDigit({required int digit, required double offset, required double opacity}) {
    return Positioned(
      child: SizedBox(
        width: width,
        child: Opacity(
          opacity: opacity,
          child: Text(
            "$digit",
            style: TextStyle(
                fontSize: height, color: color, fontWeight: FontWeight.bold),
            textAlign: TextAlign.center,
          ),
        ),
      ),
      bottom: offset,
    );
  }
</code>```

below is the main page that calls this widget

```<code>import 'package:carousel_slider/carousel_slider.dart';
import 'package:daily5/helpers/constants_tasbih.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:get_storage/get_storage.dart';
import 'package:vibration/vibration.dart';
import '../../helpers/animated_flip_counter.dart';

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

  @override
  _TasbihState createState() => _TasbihState();
}

class _TasbihState extends State<Tasbih> {
  final PageController _controller =
  PageController(viewportFraction: 0.1, initialPage: 5);
  final int _numberOfCountsToCompleteRound = 33;
  int _imageIndex = 1;
  int _beadCounter = 0;
  int _roundCounter = 0;
  int _accumulatedCounter = 0;
  bool _canVibrate = true;
  bool _isDisposed = false;
  final List<Color> _bgColour = [
    Colors.teal.shade50,
    Colors.lime.shade50,
    Colors.lightBlue.shade50,
    Colors.pink.shade50,
    Colors.black12
  ];

  final CarouselController _buttonCarouselController = CarouselController();

  @override
  void initState() {
    super.initState();
    _loadSettings();
  }

  @override
  void dispose() {
    _isDisposed = true;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: _clicked,
        onVerticalDragStart: (_) => _clicked(),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            Expanded(
                flex: 2,
                child: SafeArea(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Row(
                        children: [
                          const SizedBox(width: 45),
                          IconButton(
                              tooltip: 'Change colour',
                              icon: const Icon(Icons.palette),
                              onPressed: () {
                                setState(() {
                                  _imageIndex < 5
                                      ? _imageIndex++
                                      : _imageIndex = 1;
                                });
                              }),
                          IconButton(
                              tooltip: 'Reset counter',
                              icon: const Icon(Icons.refresh),
                              onPressed: () {
                                confirmReset(context, _resetEverything);
                              }),
                        ],
                      ),
                      const Spacer(),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        textDirection: TextDirection.ltr,
                        children: <Widget>[
                          _Counter(
                              counter: _roundCounter, counterName: 'Round'),
                          _Counter(counter: _beadCounter, counterName: 'Beads'),
                        ],
                      ),
                      Padding(
                        padding: const EdgeInsets.symmetric(vertical: 32),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            const Text('Accumulated'),
                            const SizedBox(width: 10),
                            AnimatedFlipCounter(
                                value: _accumulatedCounter,
                                duration: const Duration(milliseconds: 730),
                                size: 14),
                          ],
                        ),
                      ),
                      CarouselSlider(
                        carouselController: _buttonCarouselController,
                        options: CarouselOptions(
                          height: 100.0,
                          enlargeCenterPage: true,
                        ),
                        items: [1, 2, 3, 4].map((i) {
                          return Builder(
                            builder: (BuildContext context) {
                              return Container(
                                  width: MediaQuery.of(context).size.width,
                                  margin: const EdgeInsets.symmetric(
                                      horizontal: 5.0),
                                  decoration: BoxDecoration(
                                      color: _bgColour[_imageIndex - 1],
                                      borderRadius: BorderRadius.circular(12)),
                                  child: Image.asset('assets/images/zikr/$i.png'));
                            },
                          );
                        }).toList(),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          IconButton(
                              onPressed: () {
                                _buttonCarouselController.previousPage();
                              },
                              icon: const Icon(Icons.navigate_before)),
                          IconButton(
                              onPressed: () {
                                _buttonCarouselController.nextPage();
                              },
                              icon: const Icon(Icons.navigate_next)),
                        ],
                      ),
                      const Spacer()
                    ],
                  ),
                )),
            Expanded(
              flex: 1,
              child: PageView.builder(
                reverse: true,
                physics: const NeverScrollableScrollPhysics(),
                controller: _controller,
                scrollDirection: Axis.vertical,
                itemBuilder: (_, __) {
                  return Image.asset(
                    'assets/images/beads/bead-$_imageIndex.png',
                  );
                },
                itemCount: null,
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _loadSettings() async {
    bool? canVibrate = await Vibration.hasVibrator();
    if (!_isDisposed) {
      setState(() {
        _canVibrate = canVibrate!;
        _loadData();
      });
    }
  }

  void _loadData() {
    if (!_isDisposed) {
      setState(() {
        _beadCounter = GetStorage().read(kBeadsCount) ?? 0;
        _roundCounter = GetStorage().read(kRoundCount) ?? 0;
        _accumulatedCounter =
            _roundCounter * _numberOfCountsToCompleteRound + _beadCounter;
      });
    }
  }

  void _resetEverything() {
    GetStorage().write(kBeadsCount, 0);
    GetStorage().write(kRoundCount, 0);
    _loadData();
  }

  void _clicked() {
    if (!_isDisposed) {
      setState(() {
        _beadCounter++;
        _accumulatedCounter++;
        if (_beadCounter > _numberOfCountsToCompleteRound) {
          _beadCounter = 1;
          _roundCounter++;
          if (_canVibrate) Vibration.vibrate(duration: 100, amplitude: 100);
        }
      });
    }
    GetStorage().write(kBeadsCount, _beadCounter);
    GetStorage().write(kRoundCount, _roundCounter);
    int nextPage = _controller.page!.round() + 1;
    _controller.animateToPage(nextPage,
        duration: const Duration(milliseconds: 200), curve: Curves.easeIn);
  }
}

class _Counter extends StatelessWidget {
  const _Counter(
      {Key? key,
        required this.counter,
        this.tsCounter =
        const TextStyle(fontSize: 50, fontWeight: FontWeight.bold),
        required this.counterName,
        this.tsCounterName = const TextStyle(
            fontSize: 20,
            fontStyle: FontStyle.italic,
            fontWeight: FontWeight.w300)})
      : super(key: key);
  final int counter;
  final TextStyle tsCounter;
  final String counterName;
  final TextStyle tsCounterName;
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        AnimatedFlipCounter(
          duration: const Duration(milliseconds: 300),
          value: counter,
        ),
        Text(counterName, style: tsCounterName)
      ],
    );
  }
}

void confirmReset(BuildContext context, VoidCallback callback) {
  const _confirmText = Text('Confirm', style: TextStyle(color: Colors.red));
  const _cancelText = Text('Cancel');
  const _dialogTitle = Text("Reset Counter?");
  const _dialogContent = Text("This action can't be undone");

  void _confirmResetAction() {
    callback();
    showSnackBar(
        context: context,
        label: 'Cleared',
        icon: CupertinoIcons.check_mark_circled);
    Navigator.of(context).pop();
  }

  showDialog(
    context: context,
    builder: (_) {
      return kIsWeb
          ? AlertDialog(
        title: _dialogTitle,
        content: _dialogContent,
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: _cancelText,
          ),
          TextButton(
            onPressed: _confirmResetAction,
            child: _confirmText,
          ),
        ],
      )
          : CupertinoAlertDialog(
        title: _dialogTitle,
        content: _dialogContent,
        actions: [
          CupertinoDialogAction(
            child: _cancelText,
            onPressed: () => Navigator.of(context).pop(),
          ),
          CupertinoDialogAction(
            child: _confirmText,
            onPressed: _confirmResetAction,
          ),
        ],
      );
    },
  );
}

void showSnackBar({required BuildContext context, required String label, required IconData icon}) {
  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(
      behavior: SnackBarBehavior.floating,
      content: Row(
        children: [
          Icon(
            icon,
            color: Colors.white60,
          ),
          const SizedBox(width: 5),
          Text(label)
        ],
      ),
    ),
  );
}

</code>```

Supposedly it should beads that can be counted down but the animation cant load.

Body:
I have found a code that i tried to replicate. It has an app itself and it is working. However when i tried to write the code down it shows the problem Unsupported operation NaN or infinity toInt for a function named TweenAnimation. I am still trying to learn how to use tween animation so any pros have any idea on this problem?

below is the code for the animation

import 'package:flutter/material.dart';

class AnimatedFlipCounter extends StatelessWidget {
  final int value;
  final Duration duration;
  final double size;
  final Color color;

  const AnimatedFlipCounter({
    Key? key,
    required this.value,
    required this.duration,
    this.size = 72,
    this.color = Colors.black,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    List<int> digits = value == 0 ? [0] : [];

    int v = value;
    if (v < 0) {
      v *= -1;
    }
    while (v > 0) {
      digits.add(v);
      v = v ~/ 10;
    }

    return Row(
      mainAxisSize: MainAxisSize.min,
      children: List.generate(digits.length, (int i) {
        return _SingleDigitFlipCounter(
          key: ValueKey(digits.length - i),
          value: digits[digits.length - i - 1].toDouble(),
          duration: duration,
          height: size,
          width: size / 1.8,
          color: color,
        );
      }),
    );
  }
}

class _SingleDigitFlipCounter extends StatelessWidget {
  final double value;
  final Duration duration;
  final double height;
  final double width;
  final Color color;

  const _SingleDigitFlipCounter({
    required Key key,
    required this.value,
    required this.duration,
    required this.height,
    required this.width,
    required this.color,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TweenAnimationBuilder(
      tween: Tween(begin: value, end: value),
      duration: duration,
      builder: (context,double value, child) {
        final whole = 1.0 ~/ value ;
        final decimal = value - whole;
        return SizedBox(
          height: height,
          width: width,
          child: Stack(
            fit: StackFit.expand,
            children: <Widget>[
              _buildSingleDigit(
                digit: whole % 10,
                offset: height * decimal,
                opacity: 1.0 - decimal,
              ),
              _buildSingleDigit(
                digit: (whole + 1) % 10,
                offset: height * decimal - height,
                opacity: decimal,
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildSingleDigit({required int digit, required double offset, required double opacity}) {
    return Positioned(
      child: SizedBox(
        width: width,
        child: Opacity(
          opacity: opacity,
          child: Text(
            "$digit",
            style: TextStyle(
                fontSize: height, color: color, fontWeight: FontWeight.bold),
            textAlign: TextAlign.center,
          ),
        ),
      ),
      bottom: offset,
    );
  }

below is the main page that calls this widget

import 'package:carousel_slider/carousel_slider.dart';
import 'package:daily5/helpers/constants_tasbih.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:get_storage/get_storage.dart';
import 'package:vibration/vibration.dart';
import '../../helpers/animated_flip_counter.dart';

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

  @override
  _TasbihState createState() => _TasbihState();
}

class _TasbihState extends State<Tasbih> {
  final PageController _controller =
  PageController(viewportFraction: 0.1, initialPage: 5);
  final int _numberOfCountsToCompleteRound = 33;
  int _imageIndex = 1;
  int _beadCounter = 0;
  int _roundCounter = 0;
  int _accumulatedCounter = 0;
  bool _canVibrate = true;
  bool _isDisposed = false;
  final List<Color> _bgColour = [
    Colors.teal.shade50,
    Colors.lime.shade50,
    Colors.lightBlue.shade50,
    Colors.pink.shade50,
    Colors.black12
  ];

  final CarouselController _buttonCarouselController = CarouselController();

  @override
  void initState() {
    super.initState();
    _loadSettings();
  }

  @override
  void dispose() {
    _isDisposed = true;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: _clicked,
        onVerticalDragStart: (_) => _clicked(),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            Expanded(
                flex: 2,
                child: SafeArea(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Row(
                        children: [
                          const SizedBox(width: 45),
                          IconButton(
                              tooltip: 'Change colour',
                              icon: const Icon(Icons.palette),
                              onPressed: () {
                                setState(() {
                                  _imageIndex < 5
                                      ? _imageIndex++
                                      : _imageIndex = 1;
                                });
                              }),
                          IconButton(
                              tooltip: 'Reset counter',
                              icon: const Icon(Icons.refresh),
                              onPressed: () {
                                confirmReset(context, _resetEverything);
                              }),
                        ],
                      ),
                      const Spacer(),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        textDirection: TextDirection.ltr,
                        children: <Widget>[
                          _Counter(
                              counter: _roundCounter, counterName: 'Round'),
                          _Counter(counter: _beadCounter, counterName: 'Beads'),
                        ],
                      ),
                      Padding(
                        padding: const EdgeInsets.symmetric(vertical: 32),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            const Text('Accumulated'),
                            const SizedBox(width: 10),
                            AnimatedFlipCounter(
                                value: _accumulatedCounter,
                                duration: const Duration(milliseconds: 730),
                                size: 14),
                          ],
                        ),
                      ),
                      CarouselSlider(
                        carouselController: _buttonCarouselController,
                        options: CarouselOptions(
                          height: 100.0,
                          enlargeCenterPage: true,
                        ),
                        items: [1, 2, 3, 4].map((i) {
                          return Builder(
                            builder: (BuildContext context) {
                              return Container(
                                  width: MediaQuery.of(context).size.width,
                                  margin: const EdgeInsets.symmetric(
                                      horizontal: 5.0),
                                  decoration: BoxDecoration(
                                      color: _bgColour[_imageIndex - 1],
                                      borderRadius: BorderRadius.circular(12)),
                                  child: Image.asset('assets/images/zikr/$i.png'));
                            },
                          );
                        }).toList(),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          IconButton(
                              onPressed: () {
                                _buttonCarouselController.previousPage();
                              },
                              icon: const Icon(Icons.navigate_before)),
                          IconButton(
                              onPressed: () {
                                _buttonCarouselController.nextPage();
                              },
                              icon: const Icon(Icons.navigate_next)),
                        ],
                      ),
                      const Spacer()
                    ],
                  ),
                )),
            Expanded(
              flex: 1,
              child: PageView.builder(
                reverse: true,
                physics: const NeverScrollableScrollPhysics(),
                controller: _controller,
                scrollDirection: Axis.vertical,
                itemBuilder: (_, __) {
                  return Image.asset(
                    'assets/images/beads/bead-$_imageIndex.png',
                  );
                },
                itemCount: null,
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _loadSettings() async {
    bool? canVibrate = await Vibration.hasVibrator();
    if (!_isDisposed) {
      setState(() {
        _canVibrate = canVibrate!;
        _loadData();
      });
    }
  }

  void _loadData() {
    if (!_isDisposed) {
      setState(() {
        _beadCounter = GetStorage().read(kBeadsCount) ?? 0;
        _roundCounter = GetStorage().read(kRoundCount) ?? 0;
        _accumulatedCounter =
            _roundCounter * _numberOfCountsToCompleteRound + _beadCounter;
      });
    }
  }

  void _resetEverything() {
    GetStorage().write(kBeadsCount, 0);
    GetStorage().write(kRoundCount, 0);
    _loadData();
  }

  void _clicked() {
    if (!_isDisposed) {
      setState(() {
        _beadCounter++;
        _accumulatedCounter++;
        if (_beadCounter > _numberOfCountsToCompleteRound) {
          _beadCounter = 1;
          _roundCounter++;
          if (_canVibrate) Vibration.vibrate(duration: 100, amplitude: 100);
        }
      });
    }
    GetStorage().write(kBeadsCount, _beadCounter);
    GetStorage().write(kRoundCount, _roundCounter);
    int nextPage = _controller.page!.round() + 1;
    _controller.animateToPage(nextPage,
        duration: const Duration(milliseconds: 200), curve: Curves.easeIn);
  }
}

class _Counter extends StatelessWidget {
  const _Counter(
      {Key? key,
        required this.counter,
        this.tsCounter =
        const TextStyle(fontSize: 50, fontWeight: FontWeight.bold),
        required this.counterName,
        this.tsCounterName = const TextStyle(
            fontSize: 20,
            fontStyle: FontStyle.italic,
            fontWeight: FontWeight.w300)})
      : super(key: key);
  final int counter;
  final TextStyle tsCounter;
  final String counterName;
  final TextStyle tsCounterName;
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        AnimatedFlipCounter(
          duration: const Duration(milliseconds: 300),
          value: counter,
        ),
        Text(counterName, style: tsCounterName)
      ],
    );
  }
}

void confirmReset(BuildContext context, VoidCallback callback) {
  const _confirmText = Text('Confirm', style: TextStyle(color: Colors.red));
  const _cancelText = Text('Cancel');
  const _dialogTitle = Text("Reset Counter?");
  const _dialogContent = Text("This action can't be undone");

  void _confirmResetAction() {
    callback();
    showSnackBar(
        context: context,
        label: 'Cleared',
        icon: CupertinoIcons.check_mark_circled);
    Navigator.of(context).pop();
  }

  showDialog(
    context: context,
    builder: (_) {
      return kIsWeb
          ? AlertDialog(
        title: _dialogTitle,
        content: _dialogContent,
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: _cancelText,
          ),
          TextButton(
            onPressed: _confirmResetAction,
            child: _confirmText,
          ),
        ],
      )
          : CupertinoAlertDialog(
        title: _dialogTitle,
        content: _dialogContent,
        actions: [
          CupertinoDialogAction(
            child: _cancelText,
            onPressed: () => Navigator.of(context).pop(),
          ),
          CupertinoDialogAction(
            child: _confirmText,
            onPressed: _confirmResetAction,
          ),
        ],
      );
    },
  );
}

void showSnackBar({required BuildContext context, required String label, required IconData icon}) {
  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(
      behavior: SnackBarBehavior.floating,
      content: Row(
        children: [
          Icon(
            icon,
            color: Colors.white60,
          ),
          const SizedBox(width: 5),
          Text(label)
        ],
      ),
    ),
  );
}

Supposedly it should beads that can be counted down but the animation cant load.


问:
How can I insert data through api in Json format
How to insert multiple data through input method through postman in laravel.


问:
Error in console: Functions are not valid as a React child
I keep on getting this error when trying to update a product in my project:

react_devtools_backend.js:4012 Warning: Functions are not valid as a React child. This may happen if you return a Component instead of  from render. Or maybe you meant to call this function rather than return it.

Index.js:

```<code>import React from 'react';
import { Provider } from 'react-redux';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import store from './store';

ReactDOM.render(
  <Provider store={store}>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </Provider>,
  document.getElementById('root')
);

serviceWorker.unregister();

</code>```

ProductList:

```<code>import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Link, useParams, useNavigate, useLocation } from 'react-router-dom';
import {
  createProduct,
  deleteProduct,
  listProducts,
} from '../actions/productActions';
import LoadingBox from '../components/LoadingBox';
import MessageBox from '../components/MessageBox';
import {
  PRODUCT_CREATE_RESET,
  PRODUCT_DELETE_RESET,
} from '../constants/productConstants';

export default function ProductListScreen(props) {
  const navigate = useNavigate();
  const { pageNumber = 1 } = useParams();
  const { pathname } = useLocation();
  const sellerMode = pathname.indexOf('/seller') >= 0;
  const productList = useSelector((state) => state.productList);
  const { loading, error, products, page, pages } = productList;

  const productCreate = useSelector((state) => state.productCreate);
  const {
    loading: loadingCreate,
    error: errorCreate,
    success: successCreate,
    product: createdProduct,
  } = productCreate;

  const productDelete = useSelector((state) => state.productDelete);
  const {
    loading: loadingDelete,
    error: errorDelete,
    success: successDelete,
  } = productDelete;
  const userSignin = useSelector((state) => state.userSignin);
  const { userInfo } = userSignin;
  const dispatch = useDispatch();
  useEffect(() => {
    if (successCreate) {
      dispatch({ type: PRODUCT_CREATE_RESET });
      navigate(`/product/${createdProduct._id}/edit`);
    }
    if (successDelete) {
      dispatch({ type: PRODUCT_DELETE_RESET });
    }
    dispatch(
      listProducts({ seller: sellerMode ? userInfo._id : '', pageNumber })
    );
  }, [
    createdProduct,
    dispatch,
    navigate,
    sellerMode,
    successCreate,
    successDelete,
    userInfo._id,
    pageNumber,
  ]);

  const deleteHandler = (product) => {
    if (window.confirm('Are you sure to delete?')) {
      dispatch(deleteProduct(product._id));
    }
  };
  const createHandler = () => {
    dispatch(createProduct());
  };
  return (
    <div>
      <div className="row">
        <h1>Products</h1>
        <button type="button" className="primary" onClick={createHandler}>
          Create Product
        </button>
      </div>

      {loadingDelete && <LoadingBox></LoadingBox>}
      {errorDelete && <MessageBox variant="danger">{errorDelete}</MessageBox>}

      {loadingCreate && <LoadingBox></LoadingBox>}
      {errorCreate && <MessageBox variant="danger">{errorCreate}</MessageBox>}
      {loading ? (
        <LoadingBox></LoadingBox>
      ) : error ? (
        <MessageBox variant="danger">{error}</MessageBox>
      ) : (
        <>
          <table className="table">
            <thead>
              <tr>
                <th>ID</th>
                <th>NAME</th>
                <th>PRICE</th>
                <th>CATEGORY</th>
                <th>BRAND</th>
                <th>ACTIONS</th>
              </tr>
            </thead>
            <tbody>
              {products.map((product) => (
                <tr key={product._id}>
                  <td>{product._id}</td>
                  <td>{product.name}</td>
                  <td>{product.price}</td>
                  <td>{product.category}</td>
                  <td>{product.brand}</td>
                  <td>
                    <button
                      type="button"
                      className="small"
                      onClick={() => navigate(`/product/${product._id}/edit`)}
                    >
                      Edit
                    </button>
                    <button
                      type="button"
                      className="small"
                      onClick={() => deleteHandler(product)}
                    >
                      Delete
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          <div className="row center pagination">
            {[...Array(pages).keys()].map((x) => (
              <Link
                className={x + 1 === page ? 'active' : ''}
                key={x + 1}
                to={`/productlist/pageNumber/${x + 1}`}
              >
                {x + 1}
              </Link>
            ))}
          </div>
        </>
      )}
    </div>
  );
}

</code>```

Product Edit Page:

```<code>import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import Axios from 'axios';
import { useNavigate, useParams } from 'react-router-dom';
import { detailsProduct, updateProduct } from '../actions/productActions';
import LoadingBox from '../components/LoadingBox';
import MessageBox from '../components/MessageBox';
import { PRODUCT_UPDATE_RESET } from '../constants/productConstants';

export default function ProductEditScreen(props) {
  const navigate = useNavigate();
  const params = useParams();
  const { id: productId } = params;
  const [name, setName] = useState('');
  const [price, setPrice] = useState('');
  const [image, setImage] = useState('');
  const [category, setCategory] = useState('');
  const [countInStock, setCountInStock] = useState('');
  const [brand, setBrand] = useState('');
  const [description, setDescription] = useState('');

  const productDetails = useSelector((state) => state.productDetails);
  const { loading, error, product } = productDetails;

  const productUpdate = useSelector((state) => state.productUpdate);
  const {
    loading: loadingUpdate,
    error: errorUpdate,
    success: successUpdate,
  } = productUpdate;

  const dispatch = useDispatch();
  useEffect(() => {
    if (successUpdate) {
      navigate('/productlist');
    }
    if (!product || product._id !== productId || successUpdate) {
      dispatch({ type: PRODUCT_UPDATE_RESET });
      dispatch(detailsProduct(productId));
    } else {
      setName(product.name);
      setPrice(product.price);
      setImage(product.image);
      setCategory(product.category);
      setCountInStock(product.countInStock);
      setBrand(product.brand);
      setDescription(product.description);
    }
  }, [product, dispatch, productId, successUpdate, navigate]);
  const submitHandler = (e) => {
    e.preventDefault();
    // TODO: dispatch update product
    dispatch(
      updateProduct({
        _id: productId,
        name,
        price,
        image,
        category,
        brand,
        countInStock,
        description,
      })
    );
  };
  const [loadingUpload, setLoadingUpload] = useState(false);
  const [errorUpload, setErrorUpload] = useState('');

  const userSignin = useSelector((state) => state.userSignin);
  const { userInfo } = userSignin;
  const uploadFileHandler = async (e) => {
    const file = e.target.files[0];
    const bodyFormData = new FormData();
    bodyFormData.append('image', file);
    setLoadingUpload(true);
    try {
      const { data } = await Axios.post('/api/uploads', bodyFormData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: `Bearer ${userInfo.token}`,
        },
      });
      setImage(data);
      setLoadingUpload(false);
    } catch (error) {
      setErrorUpload(error.message);
      setLoadingUpload(false);
    }
  };

  return (
    <div>
      <form className="form" onSubmit={submitHandler}>
        <div>
          <h1>Edit Product {productId}</h1>
        </div>
        {loadingUpdate && <LoadingBox></LoadingBox>}
        {errorUpdate && <MessageBox variant="danger">{errorUpdate}</MessageBox>}
        {loading ? (
          <LoadingBox></LoadingBox>
        ) : error ? (
          <MessageBox variant="danger">{error}</MessageBox>
        ) : (
          <>
            <div>
              <label htmlFor="name">Name</label>
              <input
                id="name"
                type="text"
                placeholder="Enter name"
                value={name}
                onChange={(e) => setName(e.target.value)}
              ></input>
            </div>
            <div>
              <label htmlFor="price">Price</label>
              <input
                id="price"
                type="text"
                placeholder="Enter price"
                value={price}
                onChange={(e) => setPrice(e.target.value)}
              ></input>
            </div>
            <div>
              <label htmlFor="image">Image</label>
              <input
                id="image"
                type="text"
                placeholder="Enter image"
                value={image}
                onChange={(e) => setImage(e.target.value)}
              ></input>
            </div>
            <div>
              <label htmlFor="imageFile">Image File</label>
              <input
                type="file"
                id="imageFile"
                label="Choose Image"
                onChange={uploadFileHandler}
              ></input>
              {loadingUpload && <LoadingBox></LoadingBox>}
              {errorUpload && (
                <MessageBox variant="danger">{errorUpload}</MessageBox>
              )}
            </div>
            <div>
              <label htmlFor="category">Category</label>
              <input
                id="category"
                type="text"
                placeholder="Enter category"
                value={category}
                onChange={(e) => setCategory(e.target.value)}
              ></input>
            </div>
            <div>
              <label htmlFor="brand">Brand</label>
              <input
                id="brand"
                type="text"
                placeholder="Enter brand"
                value={brand}
                onChange={(e) => setBrand(e.target.value)}
              ></input>
            </div>
            <div>
              <label htmlFor="countInStock">Count In Stock</label>
              <input
                id="countInStock"
                type="text"
                placeholder="Enter countInStock"
                value={countInStock}
                onChange={(e) => setCountInStock(e.target.value)}
              ></input>
            </div>
            <div>
              <label htmlFor="description">Description</label>
              <textarea
                id="description"
                rows="3"
                type="text"
                placeholder="Enter description"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
              ></textarea>
            </div>
            <div>
              <label></label>
              <button className="primary" type="submit">
                Update
              </button>
            </div>
          </>
        )}
      </form>
    </div>
  );
}

</code>```

what could be the problem?

The code should redirect me to a new page in which i can create a new product and add it to my database

Body:
I keep on getting this error when trying to update a product in my project:

react_devtools_backend.js:4012 Warning: Functions are not valid as a React child. This may happen if you return a Component instead of  from render. Or maybe you meant to call this function rather than return it.

Index.js:

import React from 'react';
import { Provider } from 'react-redux';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import store from './store';

ReactDOM.render(
  <Provider store={store}>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </Provider>,
  document.getElementById('root')
);

serviceWorker.unregister();

ProductList:

import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Link, useParams, useNavigate, useLocation } from 'react-router-dom';
import {
  createProduct,
  deleteProduct,
  listProducts,
} from '../actions/productActions';
import LoadingBox from '../components/LoadingBox';
import MessageBox from '../components/MessageBox';
import {
  PRODUCT_CREATE_RESET,
  PRODUCT_DELETE_RESET,
} from '../constants/productConstants';

export default function ProductListScreen(props) {
  const navigate = useNavigate();
  const { pageNumber = 1 } = useParams();
  const { pathname } = useLocation();
  const sellerMode = pathname.indexOf('/seller') >= 0;
  const productList = useSelector((state) => state.productList);
  const { loading, error, products, page, pages } = productList;

  const productCreate = useSelector((state) => state.productCreate);
  const {
    loading: loadingCreate,
    error: errorCreate,
    success: successCreate,
    product: createdProduct,
  } = productCreate;

  const productDelete = useSelector((state) => state.productDelete);
  const {
    loading: loadingDelete,
    error: errorDelete,
    success: successDelete,
  } = productDelete;
  const userSignin = useSelector((state) => state.userSignin);
  const { userInfo } = userSignin;
  const dispatch = useDispatch();
  useEffect(() => {
    if (successCreate) {
      dispatch({ type: PRODUCT_CREATE_RESET });
      navigate(`/product/${createdProduct._id}/edit`);
    }
    if (successDelete) {
      dispatch({ type: PRODUCT_DELETE_RESET });
    }
    dispatch(
      listProducts({ seller: sellerMode ? userInfo._id : '', pageNumber })
    );
  }, [
    createdProduct,
    dispatch,
    navigate,
    sellerMode,
    successCreate,
    successDelete,
    userInfo._id,
    pageNumber,
  ]);

  const deleteHandler = (product) => {
    if (window.confirm('Are you sure to delete?')) {
      dispatch(deleteProduct(product._id));
    }
  };
  const createHandler = () => {
    dispatch(createProduct());
  };
  return (

Products

        <button type="button" className="primary" onClick={createHandler}>
          Create Product
        </button>

      {loadingDelete && <LoadingBox></LoadingBox>}
      {errorDelete && <MessageBox variant="danger">{errorDelete}</MessageBox>}

      {loadingCreate && <LoadingBox></LoadingBox>}
      {errorCreate && <MessageBox variant="danger">{errorCreate}</MessageBox>}
      {loading ? (
        <LoadingBox></LoadingBox>
      ) : error ? (
        <MessageBox variant="danger">{error}</MessageBox>
      ) : (
        <>

                ID
                NAME
                PRICE
                CATEGORY
                BRAND
                ACTIONS

              {products.map((product) => (

                  {product._id}
                  {product.name}
                  {product.price}
                  {product.category}
                  {product.brand}

                    <button
                      type="button"
                      className="small"
                      onClick={() => navigate(`/product/${product._id}/edit`)}
                    >
                      Edit
                    </button>
                    <button
                      type="button"
                      className="small"
                      onClick={() => deleteHandler(product)}
                    >
                      Delete
                    </button>

              ))}

            {[...Array(pages).keys()].map((x) => (
              <Link
                className={x + 1 === page ? 'active' : ''}
                key={x + 1}
                to={`/productlist/pageNumber/${x + 1}`}
              >
                {x + 1}
              </Link>
            ))}

        </>
      )}

  );
}

Product Edit Page:

import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import Axios from 'axios';
import { useNavigate, useParams } from 'react-router-dom';
import { detailsProduct, updateProduct } from '../actions/productActions';
import LoadingBox from '../components/LoadingBox';
import MessageBox from '../components/MessageBox';
import { PRODUCT_UPDATE_RESET } from '../constants/productConstants';

export default function ProductEditScreen(props) {
  const navigate = useNavigate();
  const params = useParams();
  const { id: productId } = params;
  const [name, setName] = useState('');
  const [price, setPrice] = useState('');
  const [image, setImage] = useState('');
  const [category, setCategory] = useState('');
  const [countInStock, setCountInStock] = useState('');
  const [brand, setBrand] = useState('');
  const [description, setDescription] = useState('');

  const productDetails = useSelector((state) => state.productDetails);
  const { loading, error, product } = productDetails;

  const productUpdate = useSelector((state) => state.productUpdate);
  const {
    loading: loadingUpdate,
    error: errorUpdate,
    success: successUpdate,
  } = productUpdate;

  const dispatch = useDispatch();
  useEffect(() => {
    if (successUpdate) {
      navigate('/productlist');
    }
    if (!product || product._id !== productId || successUpdate) {
      dispatch({ type: PRODUCT_UPDATE_RESET });
      dispatch(detailsProduct(productId));
    } else {
      setName(product.name);
      setPrice(product.price);
      setImage(product.image);
      setCategory(product.category);
      setCountInStock(product.countInStock);
      setBrand(product.brand);
      setDescription(product.description);
    }
  }, [product, dispatch, productId, successUpdate, navigate]);
  const submitHandler = (e) => {
    e.preventDefault();
    // TODO: dispatch update product
    dispatch(
      updateProduct({
        _id: productId,
        name,
        price,
        image,
        category,
        brand,
        countInStock,
        description,
      })
    );
  };
  const [loadingUpload, setLoadingUpload] = useState(false);
  const [errorUpload, setErrorUpload] = useState('');

  const userSignin = useSelector((state) => state.userSignin);
  const { userInfo } = userSignin;
  const uploadFileHandler = async (e) => {
    const file = e.target.files[0];
    const bodyFormData = new FormData();
    bodyFormData.append('image', file);
    setLoadingUpload(true);
    try {
      const { data } = await Axios.post('/api/uploads', bodyFormData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: `Bearer ${userInfo.token}`,
        },
      });
      setImage(data);
      setLoadingUpload(false);
    } catch (error) {
      setErrorUpload(error.message);
      setLoadingUpload(false);
    }
  };

  return (

      <form className="form" onSubmit={submitHandler}>

Edit Product {productId}

        {loadingUpdate && <LoadingBox></LoadingBox>}
        {errorUpdate && <MessageBox variant="danger">{errorUpdate}</MessageBox>}
        {loading ? (
          <LoadingBox></LoadingBox>
        ) : error ? (
          <MessageBox variant="danger">{error}</MessageBox>
        ) : (
          <>

              Name
              <input
                id="name"
                type="text"
                placeholder="Enter name"
                value={name}
                onChange={(e) => setName(e.target.value)}
              ></input>

              Price
              <input
                id="price"
                type="text"
                placeholder="Enter price"
                value={price}
                onChange={(e) => setPrice(e.target.value)}
              ></input>

              Image
              <input
                id="image"
                type="text"
                placeholder="Enter image"
                value={image}
                onChange={(e) => setImage(e.target.value)}
              ></input>

              Image File
              <input
                type="file"
                id="imageFile"
                label="Choose Image"
                onChange={uploadFileHandler}
              ></input>
              {loadingUpload && <LoadingBox></LoadingBox>}
              {errorUpload && (
                <MessageBox variant="danger">{errorUpload}</MessageBox>
              )}

              Category
              <input
                id="category"
                type="text"
                placeholder="Enter category"
                value={category}
                onChange={(e) => setCategory(e.target.value)}
              ></input>

              Brand
              <input
                id="brand"
                type="text"
                placeholder="Enter brand"
                value={brand}
                onChange={(e) => setBrand(e.target.value)}
              ></input>

              Count In Stock
              <input
                id="countInStock"
                type="text"
                placeholder="Enter countInStock"
                value={countInStock}
                onChange={(e) => setCountInStock(e.target.value)}
              ></input>

              Description
              <textarea
                id="description"
                rows="3"
                type="text"
                placeholder="Enter description"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
              ></textarea>

              <button className="primary" type="submit">
                Update
              </button>

          </>
        )}
      </form>

  );
}

what could be the problem?

The code should redirect me to a new page in which i can create a new product and add it to my database


问:
Adding css in Wordpress can’t be applied when editing
The adding css can be applied to the published article.
But the adding css in Wordpress can’t be applied when editing.
How can I apply my adding css to the page when editing?</p>


问:
Setting up nginx as reverse proxy
I have a nginx running on a linux ec2 instance.

Here's my configuration file

```<code>server {
  listen 80;
  listen [::]:80;

  server_name example.com;
  root /var/www/example.com;
  index index.html;

  location /hindiscript/ {
        proxy_pass         http://localhost:7778;
  }

  location /{
   try_files $uri $uri/ =404;
  }

}
</code>```

I have a nodejs server running on port 7778. curl from the instance to http://localhost:7778 is working fine.

When i try to curl http://example.com/hindiscript, I'm getting 301 permanently moved issue. Can someone help here ?

Title: Setting up nginx as reverse proxy

Body:
I have a nginx running on a linux ec2 instance.

Here's my configuration file

server {
  listen 80;
  listen [::]:80;

  server_name example.com;
  root /var/www/example.com;
  index index.html;

  location /hindiscript/ {
        proxy_pass         http://localhost:7778;
  }

  location /{
   try_files $uri $uri/ =404;
  }

}

I have a nodejs server running on port 7778. curl from the instance to http://localhost:7778 is working fine.

When i try to curl http://example.com/hindiscript, I'm getting 301 permanently moved issue. Can someone help here ?


问:
ClassNotFoundException: org.apache.flink.client.CliFrontend When running jar file using flink
I have downloaded Apache Flink on Microsoft Windows and ran the start-local.sh. It worked and I can successfully access the web interface by navigating to http://localhost:8081/.

But when i try to run the first example using ./bin/flink run ./examples/batch/WordCount.jar,
I keep getting the following error. I tried different versions of Flink, all yielding the same error.


问:
How to dynamically push new script to Nuxt pages at runtime?
In Nuxt v2 we could add some scripts to an page like this:

```<code>head() {
  return {
    title: this.pageTitle,
    script: [
      {
        src: this.scriptSrc,
        type: 'text/javascript',
        defer: true,
        callback: () => {
          this.setScriptLoaded(true)
        }
      }
    ]
  }
}
</code>```

But as you can see it's hard coded.
I need to add a new script at runtime under especial circumstances (e.g. if user click on a button.)

I know that we could just use Vanilla JS to add scripts dynamically like this:

```<code>const script = document.createElement('script')
script.setAttribute('src', this.scriptSrc)
document.head.appendChild(script)
</code>```

But I wonder if there is a Nuxt solution?

Body:
In Nuxt v2 we could add some scripts to an page like this:

head() {
  return {
    title: this.pageTitle,
    script: [
      {
        src: this.scriptSrc,
        type: 'text/javascript',
        defer: true,
        callback: () => {
          this.setScriptLoaded(true)
        }
      }
    ]
  }
}

But as you can see it's hard coded.
I need to add a new script at runtime under especial circumstances (e.g. if user click on a button.)

I know that we could just use Vanilla JS to add scripts dynamically like this:

const script = document.createElement('script')
script.setAttribute('src', this.scriptSrc)
document.head.appendChild(script)

But I wonder if there is a Nuxt solution?


问:
Difference between ".vscode" and ".config/Code"
When running vscode on Linux, ".vscode" and ".config/Code" are created. What are their difference?

It seems like .vscode is about workspace settings and .config/Code is about user settings.

Please tell me their difference.