问:
Forcing a popup to the foreground
I'm wondering if people can help me or if my way of thinking wont work. I am not a coder so I don't get to involved in writing, just learn as I go.

I have web page one that refreshes every 5 mins. This page launches a popup.

```<code><script type="text/JavaScript">
<!--
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}
//-->
</script>
</head>
<body  önload="MM_openBrWindow('call_notice.html','CallWaiting','width=200,height=200')">"
</code>```

Now if this page is currently in the background the popup also appears in the background. I need this page to come to the foreground to notify the user that the pages has refreshed. Popup has the following code:

```<code><i>
<body onblur="self.focus()"  önload="self.focus()">
<p align="center" class="style1">You have a call. </p>
<p align="center" class="style1">Please close this window to continue.</p>
<p align="center" class="style1"> </p>
<form method="post">
  <div align="center">
    <input type="button" value="Continue"
 ö'nclick="window.close()">
</div>
</form>
</i>
</code>```

I have tried set.focus seen some setforegroundwindow, but can't get it to work. Seen z-order but that doesn't make sens to me.

Has any one got any ideas on how I can do it, or has something that monitors windows titles and executes something?

Any help would be great. I don't write from scratch but take bits here and there just to let you now what type of person you are dealing with.

Basically I want the popup to popup in front of all windows when the web pages at the back (which could 4 programs back) refreshes. Not sure how to paste the code.

答:
yourpopupwindow.focus() should work. That's in javascript, have no idea about vbsript.

Like so:

```<code>        function win_open(oid) {
       yourpopupwindow = window.open('yoururl', 'popupwin',             'menubar=no,history=no,resizable=yes,scrollbars=yes,toolbar=no,width=600,height=300');
{yourpopupwindow.focus()}
       }
</code>```

Then on refresh you can either close popup if it's open and open new one and focus on it, or just focus on existing one.

Title: Forcing a popup to the foreground

Body:
I'm wondering if people can help me or if my way of thinking wont work. I am not a coder so I don't get to involved in writing, just learn as I go.

I have web page one that refreshes every 5 mins. This page launches a popup.

"

Now if this page is currently in the background the popup also appears in the background. I need this page to come to the foreground to notify the user that the pages has refreshed. Popup has the following code:

You have a call.

Please close this window to continue.

<form method="post">

    <input type="button" value="Continue"
 ö'nclick="window.close()">

</form>

I have tried set.focus seen some setforegroundwindow, but can't get it to work. Seen z-order but that doesn't make sens to me.

Has any one got any ideas on how I can do it, or has something that monitors windows titles and executes something?

Any help would be great. I don't write from scratch but take bits here and there just to let you now what type of person you are dealing with.

Basically I want the popup to popup in front of all windows when the web pages at the back (which could 4 programs back) refreshes. Not sure how to paste the code.

Body:
yourpopupwindow.focus() should work. That's in javascript, have no idea about vbsript.

Like so:

        function win_open(oid) {
       yourpopupwindow = window.open('yoururl', 'popupwin',             'menubar=no,history=no,resizable=yes,scrollbars=yes,toolbar=no,width=600,height=300');
{yourpopupwindow.focus()}
       }

Then on refresh you can either close popup if it's open and open new one and focus on it, or just focus on existing one.


来源: stackexchange

问:
Column sorting check of subcategory of data
I Have this excel table with me, which contains article types and their size against it, I want to check whether for each article type the sizes are sorted in ascending order or not, by adding a column with indicators as SORTED, NOT SORTED, UNIQUE
I want to do it with Excel formula

```<code>     A      B    C
1**ARTICLE SIZE STATUS**
2   A       10   SORTED
3   B       11   SORTED
4   A       12   SORTED
5   A       14   NOT SORTED
6   C       11   SORTED
7   D       12   UNIQUE
8   C       13   SORTED
9   A       13   NOT SORTED
10  B       15   NOT SORTED
11  B       14   NOT SORTED
</code>```

I tried to apply =IF($A2=$A3:$A$11,IF($B2ATTACHED IMAGE OF DATASET

答:
Uses MAXIFS() so you need Microsoft365.

Formula in C2 and copy down:

```<code>=IF(COUNTIF($B$2:$B$11;B2)=1;"UNIQUE";IF(OR(MAXIFS($C$1:C1;$B$1:B1;B2)>C2;AND(MAXIFS(C3:$C$11;B3:$B$11;B2)<C2;COUNTIF(B3:$B$11;B2)>0));"NOT SORTED";"SORTED"))
</code>```

EDIT

here is a solution for none 365 users.
It is an MATRIX-FORMULA, so use CTRL+SHIFT+ENTER to enter the formula:

for C2 use this

```<code>=IF(COUNTIF($B$2:$B$11;B2)=1;"UNIQUE";IF(OR(IFERROR(MAX($C$1:C1*($B$1:B1=B2));0)>C2;AND(IFERROR(MAX(C3:$C$11*(B3:$B$11=B2));0)<C2;COUNTIF(B3:$B$11;B2)>0));"NOT SORTED";"SORTED"))
</code>```

for C3 use this and copy down:

```<code>=IF(COUNTIF($B$2:$B$11;B3)=1;"UNIQUE";IF(OR(IFERROR(MAX($C$2:C2*($B$2:B2=B3));0)>C3;AND(IFERROR(MAX(C4:$C$11*(B4:$B$11=B3));0)<C3;COUNTIF(B4:$B$11;B3)>0));"NOT SORTED";"SORTED"))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I Have this excel table with me, which contains article types and their size against it, I want to check whether for each article type the sizes are sorted in ascending order or not, by adding a column with indicators as SORTED, NOT SORTED, UNIQUE
I want to do it with Excel formula

     A      B    C
1**ARTICLE SIZE STATUS**
2   A       10   SORTED
3   B       11   SORTED
4   A       12   SORTED
5   A       14   NOT SORTED
6   C       11   SORTED
7   D       12   UNIQUE
8   C       13   SORTED
9   A       13   NOT SORTED
10  B       15   NOT SORTED
11  B       14   NOT SORTED

I tried to apply =IF($A2=$A3:$A$11,IF($B2ATTACHED IMAGE OF DATASET

Body:
Uses MAXIFS() so you need Microsoft365.

Formula in C2 and copy down:

=IF(COUNTIF($B$2:$B$11;B2)=1;"UNIQUE";IF(OR(MAXIFS($C$1:C1;$B$1:B1;B2)>C2;AND(MAXIFS(C3:$C$11;B3:$B$11;B2)<C2;COUNTIF(B3:$B$11;B2)>0));"NOT SORTED";"SORTED"))

EDIT

here is a solution for none 365 users.
It is an MATRIX-FORMULA, so use CTRL+SHIFT+ENTER to enter the formula:

for C2 use this

=IF(COUNTIF($B$2:$B$11;B2)=1;"UNIQUE";IF(OR(IFERROR(MAX($C$1:C1*($B$1:B1=B2));0)>C2;AND(IFERROR(MAX(C3:$C$11*(B3:$B$11=B2));0)<C2;COUNTIF(B3:$B$11;B2)>0));"NOT SORTED";"SORTED"))

for C3 use this and copy down:

=IF(COUNTIF($B$2:$B$11;B3)=1;"UNIQUE";IF(OR(IFERROR(MAX($C$2:C2*($B$2:B2=B3));0)>C3;AND(IFERROR(MAX(C4:$C$11*(B4:$B$11=B3));0)<C3;COUNTIF(B4:$B$11;B3)>0));"NOT SORTED";"SORTED"))


问:
Android instrumented test no tests found
I am new to Android instrumented unit tests. I have a simple test that looks like this. This is in instrumented tests; before I really write an actual instrumented test, I just want to test a simple one:

```<code>@RunWith(AndroidJUnit4.class)
@SmallTest
public class AddressBookKeepingInstrumentedTest {

    public static final String TEST_STRING = "This is a string";
    public static final long TEST_LONG = 12345678L;

    @Test
    public void test_simple() {
        assertEquals(2,1+1);
    }
}
</code>```

When I run this, I get the following error:

```<code>junit.framework.AssertionFailedError: No tests found in com.example.myfirstapp.AddressBookKeepingInstrumentedTest
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1729)

Tests ran to completion.
</code>```

Gradle build passed with success before this.
Any ideas why this is happening?

答:
The typical cause of this can be seen as an exception in Logcat.

I had a specific issue regarding an instrumented multidex run on < API 21, I had to both install MultiDex on a subclass of androidx.test.runner.AndroidJUnitRunner, and override:

AndroidJUnitRunner::createTestRequestBuilder

TestRequestBuilder::createClassPathScanner

ClassPathScanner::getClassPathEntries with the implementation as:

Unzip and extract the dex files from the APK

Run dexlib2 to obtain the type names.

Convert from the type names to a readable format: Ljava/lang/String; -> java.lang.string

This is because ClassPathScanner uses dalvik.system.DexFile, which on API 16, only reads APKs, and then only reads classes.dex

Body:
I am new to Android instrumented unit tests. I have a simple test that looks like this. This is in instrumented tests; before I really write an actual instrumented test, I just want to test a simple one:

@RunWith(AndroidJUnit4.class)
@SmallTest
public class AddressBookKeepingInstrumentedTest {

    public static final String TEST_STRING = "This is a string";
    public static final long TEST_LONG = 12345678L;

    @Test
    public void test_simple() {
        assertEquals(2,1+1);
    }
}

When I run this, I get the following error:

junit.framework.AssertionFailedError: No tests found in com.example.myfirstapp.AddressBookKeepingInstrumentedTest
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1729)

Tests ran to completion.

Gradle build passed with success before this.
Any ideas why this is happening?


问:
Encountering a logic error while looping to find unique numbers in an array
This is a problem in my textbook for my Java class where the user enters 10 integers. The program is supposed to read all integers and only display the unique numbers (not duplicated) as the output.

-When run the output is:
 Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
 The number of distinct numbers is 5
 The distinct numbers are: 1 2 3 0 0

-When it should really be:
 Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
 The number of distinct numbers is 5
 The distinct numbers are: 1 2 3 6 4 5

Since we are in the early stages of the class and understanding the language, our assignment is to complete this using a nested loop. Any help would be appreciated.

```<code>import java.util.Scanner;

public class chapter7e5 {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        //create Scanner

        System.out.print("Enter 10 numbers: ");

        int[] numberArray = new int[10];
        //create array for all numbers

        int[] distinctArray = new int[10];
        //create array for distinct numbers

        int distinct = 0;

        for (int i = 0; i < 10; i++)
        //for loop to have user enter numbers and put them into array

            numberArray[i] = input.nextInt();

        distinctArray[0] = numberArray[0];
        //first value will be distinct

        for (int i = 1; i < numberArray.length; i++) {
        //loop to go through remaining values in numberArray

            boolean exists = false;
            //create boolean

            for (int j = 0; j < distinctArray.length; j++) {
            //loop to check if value exists already in distinctArray

                if (numberArray[i] == distinctArray[j]) {

                    exists = true;
                    //if value does already exists, then exist = true

                    break;
                    //break out of inner loop

                }
            }

            if (exists == false) {
            //if value is unique then add it to the distinct array

                distinctArray[i] = numberArray[i];

                distinct++;
                //increment variable distinct

            }
        }
        //}

        System.out.println("The number of distinct numbers is " + distinct);

        System.out.print("The distinct numbers are: ");

        for (int k = 0; k < distinct; k++)

            System.out.print(distinctArray[k] + " ");

    }

}
</code>```

答:
I have the following suggestions:

Assign each number in the outer loop numbArray to  testNumber

e.g. int testNumber = numbArray[i];

in the inner loop, check that no other number is equal to testNumber.  Note that
testing is not done when i == j since that number was the one assigned to testNumber

```<code>     if (i != j && numberArray[j] == testNumber) {
            exists = true;
            break;
     }
</code>```

Then in your if clause to determine whether to assign the number or not you can do this

```<code>  if (!exists) {
     // if value is unique then add it to the distinct array
     distinctArray[distinct++] = testNumber;
 }
</code>```

Note above that is is common practice to not explicitly test boolean against true or
 false. Since the if statement evaluates on true or false conditions, you can just use the
value. So exists means it is there and !exists means it isn't

Body:
This is a problem in my textbook for my Java class where the user enters 10 integers. The program is supposed to read all integers and only display the unique numbers (not duplicated) as the output.

-When run the output is:
 Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
 The number of distinct numbers is 5
 The distinct numbers are: 1 2 3 0 0

-When it should really be:
 Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
 The number of distinct numbers is 5
 The distinct numbers are: 1 2 3 6 4 5

Since we are in the early stages of the class and understanding the language, our assignment is to complete this using a nested loop. Any help would be appreciated.

import java.util.Scanner;

public class chapter7e5 {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        //create Scanner

        System.out.print("Enter 10 numbers: ");

        int[] numberArray = new int[10];
        //create array for all numbers

        int[] distinctArray = new int[10];
        //create array for distinct numbers

        int distinct = 0;

        for (int i = 0; i < 10; i++)
        //for loop to have user enter numbers and put them into array

            numberArray[i] = input.nextInt();

        distinctArray[0] = numberArray[0];
        //first value will be distinct

        for (int i = 1; i < numberArray.length; i++) {
        //loop to go through remaining values in numberArray

            boolean exists = false;
            //create boolean

            for (int j = 0; j < distinctArray.length; j++) {
            //loop to check if value exists already in distinctArray

                if (numberArray[i] == distinctArray[j]) {

                    exists = true;
                    //if value does already exists, then exist = true

                    break;
                    //break out of inner loop

                }
            }

            if (exists == false) {
            //if value is unique then add it to the distinct array

                distinctArray[i] = numberArray[i];

                distinct++;
                //increment variable distinct

            }
        }
        //}

        System.out.println("The number of distinct numbers is " + distinct);

        System.out.print("The distinct numbers are: ");

        for (int k = 0; k < distinct; k++)

            System.out.print(distinctArray[k] + " ");

    }

}

Body:
I have the following suggestions:

Assign each number in the outer loop numbArray to  testNumber

e.g. int testNumber = numbArray[i];

in the inner loop, check that no other number is equal to testNumber.  Note that
testing is not done when i == j since that number was the one assigned to testNumber

     if (i != j && numberArray[j] == testNumber) {
            exists = true;
            break;
     }

Then in your if clause to determine whether to assign the number or not you can do this

  if (!exists) {
     // if value is unique then add it to the distinct array
     distinctArray[distinct++] = testNumber;
 }

Note above that is is common practice to not explicitly test boolean against true or
 false. Since the if statement evaluates on true or false conditions, you can just use the
value. So exists means it is there and !exists means it isn't


问:
Comparing string data received from a socket in C
I have a question on sockets.  I have this code:

```<code>while(bytes = recv(sClient, cClientMessage, 599, 0)){
</code>```

This puts the message it recives into cClientMessage and the message is always "Message".  How I made an if statement like if(cClientMessage == "Message"){//do func}.  Now this code will not do the function I want.  I think this is because it's not receiving the message right.  Can someone help me?

答:
Try:

```<code>if( strcmp( cClientMessage, "Message")) == 0 ) {
   // do something
}
</code>```

Edit, following suggestion from strager:

A better solution, which does not depend on the received data being null terminated is to use memcmp:

```<code>if( memcmp( cClientMessage, "Message", strlen( "Message") )) == 0 ) {
   // do something
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a question on sockets.  I have this code:

while(bytes = recv(sClient, cClientMessage, 599, 0)){

This puts the message it recives into cClientMessage and the message is always "Message".  How I made an if statement like if(cClientMessage == "Message"){//do func}.  Now this code will not do the function I want.  I think this is because it's not receiving the message right.  Can someone help me?

LastEditorDisplayName: Brian R. Bondy

Body:
Try:

if( strcmp( cClientMessage, "Message")) == 0 ) {
   // do something
}

Edit, following suggestion from strager:

A better solution, which does not depend on the received data being null terminated is to use memcmp:

if( memcmp( cClientMessage, "Message", strlen( "Message") )) == 0 ) {
   // do something
}

OwnerDisplayName: anon

LastEditorDisplayName: anon


问:
How to select an option from a dropdown menu through partial text using Selenium and Python
I'm using the Selenium Kit in Python and am trying to select an option from a drop-down menu.

For this I'm using python driver.select_by_visible_text() .
My problem is now that the visible text always contains the value I'm looking but with something added afterwards. The select_by_visible_text() just finds the exact option, but I can´t name it exactly.

For example: I'm looking for the option "W33", the website then says "W33 (only 4 left)". I would like to select "W33 (only 4 left)", but don´t know how to achieve this?

答:
You can get a list of all options with the options attribute on your Select object:

```<code>from selenium.webdriver.support.ui import Select

elem = driver.find_element_by_id('myselect')
elem_select = Select(elem)
opts = elem_select.options
</code>```

Then, check which of them matches. In your example, check the text attribute:

```<code>opts_to_select = [o for o in opts if o.text.startswith('W33')]
my_option = opts_to_select[0] # select first match
                              # (Maybe you also want to raise an error if
                              # there is more than one match.)
</code>```

And select it:

```<code>if not my_elem.is_selected():
    my_elem.click()
</code>```

Source: Select at selenium-python documentation

Body:
You can get a list of all options with the options attribute on your Select object:

from selenium.webdriver.support.ui import Select

elem = driver.find_element_by_id('myselect')
elem_select = Select(elem)
opts = elem_select.options

Then, check which of them matches. In your example, check the text attribute:

opts_to_select = [o for o in opts if o.text.startswith('W33')]
my_option = opts_to_select[0] # select first match
                              # (Maybe you also want to raise an error if
                              # there is more than one match.)

And select it:

if not my_elem.is_selected():
    my_elem.click()

Source: Select at selenium-python documentation


问:
How can a C program restart itself once using execve?
I'm trying to write a C program that restarts itself once. My approach was to fork and in the child process call execve. I thought I would see Hello twice printed. This here prints main twice, but even so if I comment out execve, so I assume I'm not correctly using execve here. The binary is called "restartOnce".

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>

int main(int argc, char *argv[]) {
    pid_t pid = fork();
    printf("Main.\n");
    if (pid == 0) {
        char *argv = "hello"; // To silence gcc compiler warning.
        char *env  = "world"; // To silence gcc compiler warning.
        execve("restartOnce", &argv, &env);
    } else {
        wait(NULL);
        printf("Done.\n");
    }
    return 0;
}
</code>```

答:
I'm not completely sure what you're trying to accomplish, but I see two things to attend to. We have to get the execve() call right, plus we have to avoid a fork bomb, and this code should do it.

There are lots of ways to avoid a fork bomb, but I chose to set something in the environment, and when the child sees this environment variable, it will know not to continue.

So execve() requires its own argv, which is an array of pointers to individual strings (with a NULL pointer at the end), and it's entirely legit to pass the same parameter you got from main.

The third parameter is like argv, but it's a list of environment variables instead of command line arguments. It has things like TERM=vt100, PATH=/bin/..., and many others.  Though you can fetch environment variables individually with getenv("PATH"), Unix/Linux systems provide an argv-like variable environ.

This variable is declared in <unistd.h> but requires the _GNU_SOURCE macro to be defined to expose it.

This done, you can call safely call execve this way:

```<code>#define _GNU_SOURCE
#include <unistd.h>

    ...
    execve("restartOnce", argv, environ);
</code>```

To avoid a fork bomb, one of the first thing the program does is look for the environment variable FORKBOMB - if this is set, we're in the child process and should stop forking other children, perhaps doing something else instead (the real work of the program?)

But if we're in the parent - no variable seen - we actively set the variable by putting it in our own environment that's seen by the child processes: putenv("FORKBOMB=no");

A minor addition: the very first thing the program does is report that it's started up, and it provides its own process ID just so you know what it's doing.

Maybe I misunderstand the problem, but this is how I'd solve what I imagine you're asking:

#define _GNU_SOURCE // for "environ"

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>

int main(int argc, char *argv[])
{
    printf("Main in pid %d.\n", getpid() );

    if (getenv("FORKBOMB") != 0)
    {
        printf("**We're in the second child, no more forking\n");
        exit(0);
    }

    putenv("FORKBOMB=no");

    pid_t pid = fork();

    if (pid == 0) {
        execve("restartOnce", argv, environ);
    } else {
        wait(NULL);
        printf("Done.\n");
    }
    return 0;
}
```

There are quite a few other ways to avoid the fork bomb, but this is as good as any to get the idea across, and others might chime in with their favorites.

EDIT But as I think about this, I'm pretty sure this should not be necessary no matter what you're trying to accomplish unless this is just a learning exercise.

The two things I can imagine are:

1) You need to detach from the parent process so you can run in the background, like a daemon process. In that case, you don't have to exec, just do the daemon work in the child process.

2) If the program has altered itself - perhaps downloaded an updated version of itself, then it does have to call exec to get the new executable, but a fork() would not be required.

So I'm not sure we (or at least I) know what you're trying to accomplish.

Body:
I'm trying to write a C program that restarts itself once. My approach was to fork and in the child process call execve. I thought I would see Hello twice printed. This here prints main twice, but even so if I comment out execve, so I assume I'm not correctly using execve here. The binary is called "restartOnce".

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>

int main(int argc, char *argv[]) {
    pid_t pid = fork();
    printf("Main.\n");
    if (pid == 0) {
        char *argv = "hello"; // To silence gcc compiler warning.
        char *env  = "world"; // To silence gcc compiler warning.
        execve("restartOnce", &argv, &env);
    } else {
        wait(NULL);
        printf("Done.\n");
    }
    return 0;
}

Body:
I'm not completely sure what you're trying to accomplish, but I see two things to attend to. We have to get the execve() call right, plus we have to avoid a fork bomb, and this code should do it.

There are lots of ways to avoid a fork bomb, but I chose to set something in the environment, and when the child sees this environment variable, it will know not to continue.

So execve() requires its own argv, which is an array of pointers to individual strings (with a NULL pointer at the end), and it's entirely legit to pass the same parameter you got from main.

The third parameter is like argv, but it's a list of environment variables instead of command line arguments. It has things like TERM=vt100, PATH=/bin/..., and many others.  Though you can fetch environment variables individually with getenv("PATH"), Unix/Linux systems provide an argv-like variable environ.

This variable is declared in <unistd.h> but requires the _GNU_SOURCE macro to be defined to expose it.

This done, you can call safely call execve this way:

#define _GNU_SOURCE
#include <unistd.h>

    ...
    execve("restartOnce", argv, environ);

To avoid a fork bomb, one of the first thing the program does is look for the environment variable FORKBOMB - if this is set, we're in the child process and should stop forking other children, perhaps doing something else instead (the real work of the program?)

But if we're in the parent - no variable seen - we actively set the variable by putting it in our own environment that's seen by the child processes: putenv("FORKBOMB=no");

A minor addition: the very first thing the program does is report that it's started up, and it provides its own process ID just so you know what it's doing.

Maybe I misunderstand the problem, but this is how I'd solve what I imagine you're asking:

#define _GNU_SOURCE // for "environ"

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>

int main(int argc, char *argv[])
{
    printf("Main in pid %d.\n", getpid() );

    if (getenv("FORKBOMB") != 0)
    {
        printf("**We're in the second child, no more forking\n");
        exit(0);
    }

    putenv("FORKBOMB=no");

    pid_t pid = fork();

    if (pid == 0) {
        execve("restartOnce", argv, environ);
    } else {
        wait(NULL);
        printf("Done.\n");
    }
    return 0;
}

There are quite a few other ways to avoid the fork bomb, but this is as good as any to get the idea across, and others might chime in with their favorites.

EDIT But as I think about this, I'm pretty sure this should not be necessary no matter what you're trying to accomplish unless this is just a learning exercise.

The two things I can imagine are:

1) You need to detach from the parent process so you can run in the background, like a daemon process. In that case, you don't have to exec, just do the daemon work in the child process.

2) If the program has altered itself - perhaps downloaded an updated version of itself, then it does have to call exec to get the new executable, but a fork() would not be required.

So I'm not sure we (or at least I) know what you're trying to accomplish.


问:
How can I see the formulas of an excel spreadsheet in pandas / python?
I would like to read in an excel spreadsheet to python / pandas, but have the formulae instead of the cell results.

For example, if cell A1 is 25, and cell B1 is =A1, I would like my dataframe to show:

```<code>25    =A1
</code>```

Right now it shows:

```<code>25    25
</code>```

How can I do so?

答:
Yes, it is possible. I recently found a package that solves this issue in a quite sophisticated way. It is called portable-spreadsheet (available via pip install portable-spreadsheet). It basically encapsulates xlsxwriter. Here is a simple example:

```<code>import portable_spreadsheet as ps
sheet = ps.Spreadsheet.create_new_sheet(5, 5)
# Set values
sheet.iloc[0, 0] = 25  # Set A1
sheet.iloc[1, 0] = sheet.iloc[0, 0]  # reference to A1
# Export to Excel
sheet.to_excel('output/sample.xlsx')
</code>```

It works in a similar way as Pandas Dataframe.

ContentLicense: CC BY-SA 3.0

Body:
I would like to read in an excel spreadsheet to python / pandas, but have the formulae instead of the cell results.

For example, if cell A1 is 25, and cell B1 is =A1, I would like my dataframe to show:

25    =A1

Right now it shows:

25    25

How can I do so?

Body:
Yes, it is possible. I recently found a package that solves this issue in a quite sophisticated way. It is called portable-spreadsheet (available via pip install portable-spreadsheet). It basically encapsulates xlsxwriter. Here is a simple example:

import portable_spreadsheet as ps
sheet = ps.Spreadsheet.create_new_sheet(5, 5)
# Set values
sheet.iloc[0, 0] = 25  # Set A1
sheet.iloc[1, 0] = sheet.iloc[0, 0]  # reference to A1
# Export to Excel
sheet.to_excel('output/sample.xlsx')

It works in a similar way as Pandas Dataframe.


问:
How to customize laravel passport error on login?
public function render($request, Throwable $exception)
    {

```<code>    if ($request->expectsJson()) {

        if ($exception instanceof ValidationException) {

            return response()->json([
                'message' => $exception -> getMessage(),
                'errors' => $exception -> validator -> errors()
            ],422);
        }
    }

    return parent::render($request, $exception);
}

protected function unauthenticated($request, AuthenticationException  $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error'=>'Unauthenticated'],401);
    }
    return redirect()->guest(route('login'));
</code>```

the error in login request
{
    "error": "invalid_grant",
    "error_description": "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.",
    "hint": "",
    "message": "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client."
}

```<code>login controller

class LoginController extends Controller
{
    use IssueTokenTrait;

    private $client;

    public function __construct()
    {
        $this->client = Client::find(2);
    }

    public function login(Request $request)
    {
        $this->validate($request,[
            'username' => 'required',
            'password' => 'required'
        ]);

        return $this->issueToken($request,'password');
    }

    public function refresh(Request $request)
    {
        $this->validate($request,[
            'refresh_token' => 'required'
        ]);

        return $this->issueToken($request,'refresh_token');
    }

    public function logout(Request $request)
    {
        # code...
        $accessToken = Auth::user()->token();

        DB::table('oauth_refresh_tokens')
            ->where('access_token_id', $accessToken->id)
            ->update(['revoked' => true]);

        $accessToken->revoke();

        return response()->json([], 204);
    }
}

</code>```

答:
You can customize the error messages like this:

$messages = [
    'required' => 'The :attribute field is required.',
];

$validator = Validator::make($input, $rules, $messages);
```

More on that: https://laravel.com/docs/7.x/validation#custom-error-messages

Body:
public function render($request, Throwable $exception)
    {

    if ($request->expectsJson()) {

        if ($exception instanceof ValidationException) {

            return response()->json([
                'message' => $exception -> getMessage(),
                'errors' => $exception -> validator -> errors()
            ],422);
        }
    }

    return parent::render($request, $exception);
}

protected function unauthenticated($request, AuthenticationException  $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error'=>'Unauthenticated'],401);
    }
    return redirect()->guest(route('login'));

the error in login request
{
    "error": "invalid_grant",
    "error_description": "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.",
    "hint": "",
    "message": "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client."
}

login controller

class LoginController extends Controller
{
    use IssueTokenTrait;

    private $client;

    public function __construct()
    {
        $this->client = Client::find(2);
    }

    public function login(Request $request)
    {
        $this->validate($request,[
            'username' => 'required',
            'password' => 'required'
        ]);

        return $this->issueToken($request,'password');
    }

    public function refresh(Request $request)
    {
        $this->validate($request,[
            'refresh_token' => 'required'
        ]);

        return $this->issueToken($request,'refresh_token');
    }

    public function logout(Request $request)
    {
        # code...
        $accessToken = Auth::user()->token();

        DB::table('oauth_refresh_tokens')
            ->where('access_token_id', $accessToken->id)
            ->update(['revoked' => true]);

        $accessToken->revoke();

        return response()->json([], 204);
    }
}

Body:
You can customize the error messages like this:

$messages = [
    'required' => 'The :attribute field is required.',
];

$validator = Validator::make($input, $rules, $messages);

More on that: https://laravel.com/docs/7.x/validation#custom-error-messages


问:
How to copy an event listener in plain Javascript
So I am making some overrides on a Wordpress plugin. I need to copy the event listener on an element and then replace the element and add it back. The event listener is generated by the plugin.

I thought getEventListeners() would work but I have read that it only works in console. If that is this case I'm really astounded. We're in freaking 2020 and I am not finding an obvious solution to this.

What is the solution here people?

Below is the code I was trying to implement having assumed getEventListeners wasn't just a console function.

```<code>  // Edit Affirm
  (function replaceAffirm() {
    if (document.querySelector(".affirm-modal-trigger")) {
      const learnMore = document.querySelector("#learn-more");
      const modalTrigger = document.querySelector(".affirm-modal-trigger");
      const clickHandler = getEventListeners(modalTrigger).click[0].listener;
      const substr = learnMore.innerHTML
        .toString()
        .substring(
          learnMore.innerHTML.indexOf("h") + 2,
          learnMore.innerHTML.length
        );
      learnMore.innerHTML = "Easy Financing with " + substr;
      modalTrigger.addEventListener("click", clickHandler);
    } else {
      setTimeout(function () {
        replaceAffirm();
      }, 250);
    }
  })();
</code>```

HTML

```<code><p id="learn-more" class="affirm-as-low-as" data-amount="20000" data-affirm-color="white" data-learnmore-show="true" data-page-type="product">
   Starting at
   <span class="affirm-ala-price">$68</span>
   /mo with
   <span class="__affirm-logo __affirm-logo-white __ligature__affirm_full_logo__ __processed">Affirm</span>.
   <a class="affirm-modal-trigger" aria-label="Prequalify Now (opens in modal)" href="javascript:void(0)">Prequalify now</a>
</p>
</code>```

答:
You can't copy event listeners, but it seems because of the structure of your HTML it's more likely that you shouldn't need to re-add it. Instead of editing the HTML and removing the event listener by doing so, the best bet would be to edit around it.

If you want to remove the text nodes you can iterate through childNodes and separate out what should be removed.

Then to rebuild the appropriate text where you want it you can use insertAdjacentText

if (document.querySelector(".affirm-modal-trigger")) {
  const learnMore = document.querySelector("#learn-more");
  const modalTrigger = document.querySelector(".affirm-modal-trigger");
  const children = Array.from(learnMore.childNodes);

  children.forEach(child => {
    if (child.nodeType === Node.TEXT_NODE || child.matches(".affirm-ala-price")) {
      if (learnMore.contains(child)) {
        learnMore.removeChild(child);
      }
    }
  });

  learnMore.insertAdjacentText("afterBegin", "Easy Financing With ");
  modalTrigger.insertAdjacentText("beforeBegin", " ");
} else {
  setTimeout(function() {
    replaceAffirm();
  }, 250);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="learn-more" class="affirm-as-low-as" data-amount="20000" data-affirm-color="white" data-learnmore-show="true" data-page-type="product">
  Starting at
  <span class="affirm-ala-price">$68</span> /mo with
  <span class="__affirm-logo __affirm-logo-white __ligature__affirm_full_logo__ __processed">Affirm</span>.
  Prequalify now
</p></code>```

Body:
So I am making some overrides on a Wordpress plugin. I need to copy the event listener on an element and then replace the element and add it back. The event listener is generated by the plugin.

I thought getEventListeners() would work but I have read that it only works in console. If that is this case I'm really astounded. We're in freaking 2020 and I am not finding an obvious solution to this.

What is the solution here people?

Below is the code I was trying to implement having assumed getEventListeners wasn't just a console function.

  // Edit Affirm
  (function replaceAffirm() {
    if (document.querySelector(".affirm-modal-trigger")) {
      const learnMore = document.querySelector("#learn-more");
      const modalTrigger = document.querySelector(".affirm-modal-trigger");
      const clickHandler = getEventListeners(modalTrigger).click[0].listener;
      const substr = learnMore.innerHTML
        .toString()
        .substring(
          learnMore.innerHTML.indexOf("h") + 2,
          learnMore.innerHTML.length
        );
      learnMore.innerHTML = "Easy Financing with " + substr;
      modalTrigger.addEventListener("click", clickHandler);
    } else {
      setTimeout(function () {
        replaceAffirm();
      }, 250);
    }
  })();

HTML

   Starting at
   $68
   /mo with
   Affirm.
   Prequalify now

Body:
You can't copy event listeners, but it seems because of the structure of your HTML it's more likely that you shouldn't need to re-add it. Instead of editing the HTML and removing the event listener by doing so, the best bet would be to edit around it.

If you want to remove the text nodes you can iterate through childNodes and separate out what should be removed.

Then to rebuild the appropriate text where you want it you can use insertAdjacentText

if (document.querySelector(".affirm-modal-trigger")) {
  const learnMore = document.querySelector("#learn-more");
  const modalTrigger = document.querySelector(".affirm-modal-trigger");
  const children = Array.from(learnMore.childNodes);

  children.forEach(child => {
    if (child.nodeType === Node.TEXT_NODE || child.matches(".affirm-ala-price")) {
      if (learnMore.contains(child)) {
        learnMore.removeChild(child);
      }
    }
  });

  learnMore.insertAdjacentText("afterBegin", "Easy Financing With ");
  modalTrigger.insertAdjacentText("beforeBegin", " ");
} else {
  setTimeout(function() {
    replaceAffirm();
  }, 250);
}

<p id="learn-more" class="affirm-as-low-as" data-amount="20000" data-affirm-color="white" data-learnmore-show="true" data-page-type="product">
  Starting at
  <span class="affirm-ala-price">$68</span> /mo with
  <span class="__affirm-logo __affirm-logo-white __ligature__affirm_full_logo__ __processed">Affirm</span>.
  <a class="affirm-modal-trigger" aria-label="Prequalify Now (opens in modal)" href="javascript:void(0)">Prequalify now</a>
</p>


问:
Accessing member variables with getters C++
If I have this private map of scenes in my header file

```<code>std::map<std::string, Scene> scenes;
</code>```

Should my public getter be like so?

```<code>std::map<std::string, Scene>* getScenes() { return &scenes; }
</code>```

Still getting my head around pointers in c++ so apologies if it seems like a dumb question

答:
Unless you need to, returning a pointer to a member that isn't stored as a pointer isn't a great idea. Passing pointers around can get messy e.g. if the original object goes out of scope you'll end up with a dangling pointer. Returning by const reference should be your first port of call:

```<code>const std::map<std::string, Scene>& getScenes() const { return scenes; }
</code>```

This will avoid a copy while preserving const correctness. This obviously isn't a one size fits all approach, but quite often if you want a getter for a non-primitive type, you will want to return by const reference.

Body:
If I have this private map of scenes in my header file

std::map<std::string, Scene> scenes;

Should my public getter be like so?

std::map<std::string, Scene>* getScenes() { return &scenes; }

Still getting my head around pointers in c++ so apologies if it seems like a dumb question

Body:
Unless you need to, returning a pointer to a member that isn't stored as a pointer isn't a great idea. Passing pointers around can get messy e.g. if the original object goes out of scope you'll end up with a dangling pointer. Returning by const reference should be your first port of call:

const std::map<std::string, Scene>& getScenes() const { return scenes; }

This will avoid a copy while preserving const correctness. This obviously isn't a one size fits all approach, but quite often if you want a getter for a non-primitive type, you will want to return by const reference.


问:
How to apply the correct syntax for IF condition with HTML for Swiftmailer?
I needed to upgrade my PHP online form from 5.3 to 7.2.  Decided to use Swiftmailer and have it setup to send emails.  Now I need to reproduce the same email as I had it.  When I copy over PHP code from the older version, I am running into some syntax errors that I don't understand.  Here is the code:</p>

```<code><?php

// Varibles for the general information section
$company_name = $_REQUEST['company_name'];
$contact = $_REQUEST['contact'];
$delivery_date = $_REQUEST['delivery_date'];
$delivery_time = $_REQUEST['delivery_time'];
$delivery_address = $_REQUEST['delivery_address'];
$phone = $_REQUEST['phone'];
$special_instruction = $_REQUEST['special_instruction'];
$email = $_REQUEST['email'];
$payment = $_REQUEST['payment'];

require_once '[localhosting_service]/phpmailer/vendor/autoload.php';

// Create the Transport
$transport = (new Swift_SmtpTransport('********.com', ***, 'ssl'))
->setUsername('******@********.com')
->setPassword('[password]')
;

// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);

// Create a message
$message = (new Swift_Message('Wonderful Subject'))
->setFrom(['******@*******.com' => '!!! Online Order !!!'])
->setTo(['********@*****.com' => 'Jake'])
->setCc(['********@*****.com' => 'Jay'])

->setSubject('Online order from A COMPANY')

->setBody('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<body>
<p>You have an order from a visitor (<strong>'.$company_name.'</strong>) on your website:</p>
<p> </p>
<p><strong>*** General Information ***</strong></p>
<p>
<strong>Company Name:</strong> <span style="color:red;">'.$company_name.'</span><br />';
if (!empty($contact))
  {
    $message->setBody .= '<strong>Contact:</strong> <span style="color:red;">'.$contact.'</span><br />';
  }
$message->setBody .= '<strong>Delivery Date:</strong> <span style="color:red;">'.$delivery_date.'</span><br />
<strong>Delivery Time:</strong> <span style="color:red;">'.$delivery_time.'</span><br />
<strong>Delivery Address:</strong> <span style="color:red;">'.$delivery_address.'</span><br />
<strong>Phone:</strong> <span style="color:red;">'.$phone.'</span><br />';
if (!empty($special_instruction))
  {
    $message->setBody .= '<strong>Special Instruction:</strong> <span style="color:red;">'.$special_instruction.'</span><br />';
  }
$message->setBody .= '<strong>Email:</strong> <span style="color:red;">'.$email.'</span><br />
<strong>Type of Payment:</strong> <span style="color:red;">'.$payment.'</span><br />
</p>
</body>
</html>')
;

// Send the message
$result = $mailer->send($message);

?>
</code>```

答:
You can achieve this by defining the $body email outside its setter method. "Build it" before, and once you have it defined, then pass it as an argument to the setBody() method.

Look at this example:

// ...
$body = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

You have an order from a visitor (' . $company_name . ') on your website:

*** General Information ***

Company Name: ' . $company_name . '
';
if (!empty($contact)) {
    $body.='Contact: ' . $contact . '
';
}
$body.='Delivery Date: ' . $delivery_date . '

Delivery Time: ' . $delivery_time . '

Delivery Address: ' . $delivery_address . '

Phone: ' . $phone . '
';
if (!empty($special_instruction)) {
    $body.='Special Instruction: ' . $special_instruction . '
';
}
$body.='Email: ' . $email . '

Type of Payment: ' . $payment . '

';

$message = (new \Swift_Message('Wonderful Subject'))
    ->setFrom(['******@*******.com' => '!!! Online Order !!!'])
    ->setTo(['********@*****.com' => 'Jake'])
    ->setCc(['********@*****.com' => 'Jay'])
    ->setSubject('Online order from A COMPANY')
    ->setBody($body);

$result = $mailer->send($message);
```

That said, I recommend you to use the new Symfony Mailer component. It's super easy to create messages and use them with different mailers! :)

Body:
I needed to upgrade my PHP online form from 5.3 to 7.2.  Decided to use Swiftmailer and have it setup to send emails.  Now I need to reproduce the same email as I had it.  When I copy over PHP code from the older version, I am running into some syntax errors that I don't understand.  Here is the code:

<?php

// Varibles for the general information section
$company_name = $_REQUEST['company_name'];
$contact = $_REQUEST['contact'];
$delivery_date = $_REQUEST['delivery_date'];
$delivery_time = $_REQUEST['delivery_time'];
$delivery_address = $_REQUEST['delivery_address'];
$phone = $_REQUEST['phone'];
$special_instruction = $_REQUEST['special_instruction'];
$email = $_REQUEST['email'];
$payment = $_REQUEST['payment'];

require_once '[localhosting_service]/phpmailer/vendor/autoload.php';

// Create the Transport
$transport = (new Swift_SmtpTransport('********.com', ***, 'ssl'))
->setUsername('******@********.com')
->setPassword('[password]')
;

// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);

// Create a message
$message = (new Swift_Message('Wonderful Subject'))
->setFrom(['******@*******.com' => '!!! Online Order !!!'])
->setTo(['********@*****.com' => 'Jake'])
->setCc(['********@*****.com' => 'Jay'])

->setSubject('Online order from A COMPANY')

->setBody('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

You have an order from a visitor ('.$company_name.') on your website:

*** General Information ***

Company Name: '.$company_name.'
';
if (!empty($contact))
  {
    $message->setBody .= 'Contact: '.$contact.'
';
  }
$message->setBody .= 'Delivery Date: '.$delivery_date.'

Delivery Time: '.$delivery_time.'

Delivery Address: '.$delivery_address.'

Phone: '.$phone.'
';
if (!empty($special_instruction))
  {
    $message->setBody .= 'Special Instruction: '.$special_instruction.'
';
  }
$message->setBody .= 'Email: '.$email.'

Type of Payment: '.$payment.'

')
;

// Send the message
$result = $mailer->send($message);

?>

Body:
You can achieve this by defining the $body email outside its setter method. "Build it" before, and once you have it defined, then pass it as an argument to the setBody() method.

Look at this example:

// ...
$body = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<body>
<p>You have an order from a visitor (<strong>' . $company_name . '</strong>) on your website:</p>
<p>&nbsp;</p>
<p><strong>*** General Information ***</strong></p>
<p>
<strong>Company Name:</strong> <span style="color:red;">' . $company_name . '</span><br />';
if (!empty($contact)) {
    $body.='<strong>Contact:</strong> <span style="color:red;">' . $contact . '</span><br />';
}
$body.='<strong>Delivery Date:</strong> <span style="color:red;">' . $delivery_date . '</span><br />
<strong>Delivery Time:</strong> <span style="color:red;">' . $delivery_time . '</span><br />
<strong>Delivery Address:</strong> <span style="color:red;">' . $delivery_address . '</span><br />
<strong>Phone:</strong> <span style="color:red;">' . $phone . '</span><br />';
if (!empty($special_instruction)) {
    $body.='<strong>Special Instruction:</strong> <span style="color:red;">' . $special_instruction . '</span><br />';
}
$body.='<strong>Email:</strong> <span style="color:red;">' . $email . '</span><br />
<strong>Type of Payment:</strong> <span style="color:red;">' . $payment . '</span><br />
</p>
</body>
</html>';

$message = (new \Swift_Message('Wonderful Subject'))
    ->setFrom(['******@*******.com' => '!!! Online Order !!!'])
    ->setTo(['********@*****.com' => 'Jake'])
    ->setCc(['********@*****.com' => 'Jay'])
    ->setSubject('Online order from A COMPANY')
    ->setBody($body);

$result = $mailer->send($message);

That said, I recommend you to use the new Symfony Mailer component. It's super easy to create messages and use them with different mailers! :)


问:
How does one Display a Hyperlink in React Native App?
How do I display a hyperlink in a React Native app? </p>

<p>e.g. </p>

```<code><a href="https://google.com>Google</a>
</code>```

答:
Another helpful note to add to the above responses is to add some flexbox styling.
This will keep the text on one line and will make sure the text doesn't overlap the screen.</p>

```<code> <View style={{ display: "flex", flexDirection: "row", flex: 1, flexWrap: 'wrap', margin: 10 }}>
  <Text>Add your </Text>
  <TouchableOpacity>
    <Text style={{ color: 'blue' }} onpress={() => Linking.openURL('https://www.google.com')} >
         link
    </Text>
   </TouchableOpacity>
   <Text>here.
   </Text>
 </View>
</code>```

Body:
How do I display a hyperlink in a React Native app?

e.g.

Google

Body:
Another helpful note to add to the above responses is to add some flexbox styling.
This will keep the text on one line and will make sure the text doesn't overlap the screen.

 <View style={{ display: "flex", flexDirection: "row", flex: 1, flexWrap: 'wrap', margin: 10 }}>
  <Text>Add your </Text>
  <TouchableOpacity>
    <Text style={{ color: 'blue' }} onpress={() => Linking.openURL('https://www.google.com')} >
         link
    </Text>
   </TouchableOpacity>
   <Text>here.
   </Text>
 </View>


问:
Make Right Answers Green and Wrong Answers Red for JS Quiz
I have a quiz system that is created in JS. I am using input elements to display each quiz option. I am trying to make it so when you click submit, it will loop through each input element and set the styling of the input text to green if it is a correct answer and red if it an incorrect answer. I am having trouble actually getting the text that is next to the input value however.

Below is a picture of the quiz:
https://gyazo.com/1ba5245de2c5c6f96bd728e31aeb0899

HTML:

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

<link href ="style.css" rel ="stylesheet">
<!-- <link href="https://fonts.googleapis.com/css?family=OpenSans" rel="stylesheet"> -->
<script src = "main.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<body>
<h1>Chapter 1 Quiz</h1>

<form id = "quiz" name = "quiz">
<p class = "questions">What is the capital of Rhode Island?</p>
<input id = "textbox" type = "text" name = "question1">

<p class = "questions">What is the capital of Connecticut?</p>
<input type = "radio" id = "mc" name = "question2" value = "Hartford"> Hartford<br>

<input type = "radio" id = "mc" name = "question2" value = "Heartford"> Heartford<br>

<p class = "questions">What is the capital of New York?</p>
<input type = "radio" id = "mc" name = "question3" value = "Albany"> Albany<br>
<input type = "radio" id = "mc" name = "question3" value = "All Benny's"> All Benny's<br>

<input id = "button" type = "button" value = "Finish" onclick = "check();">
</form>

<div id = "after_submit">
<p id = "number_correct"></p>
<p id = "message"></p>
</div>
</html>

</body>

</code>```

JAVASCRIPT:

```<code>
function check(){

    var question1 = document.quiz.question1.value;
    var question2 = document.quiz.question2.value;
    var question3 = document.quiz.question3.value;
    var correct = 0;
    var total_questions = 3;

    if (question1 == "Providence") {
        correct++;
}
    if (question2 == "Hartford") {
        correct++;
}
    if (question3 == "Albany") {
        correct++;
    }

    var score;

    if (correct == 0) {
        score = 2;
    }

    if (correct > 0 && correct < total_questions) {
        score = 1;
    }

    if (correct == total_questions) {
        score = 0;
    }

    $( "input" ).each(function( index ) {
        console.log( index + ": " + $( this ).val() );
        // CHANGE THE STYLING HERE. VAL DOES NOT GET THE TEXT OF INPUT AND NIETHER DOES .text()
    });

    document.getElementById("after_submit").style.visibility = "visible";

    document.getElementById("message").innerHTML = "Correct Answers:";
    document.getElementById("number_correct").innerHTML = "Score: " + correct + " / " + total_questions + " (" + Math.trunc((correct / total_questions)*100) + "%)";

    }

</code>```

I was thinking I could store the correct answers in the array and if the input has the value then change the styling of the text to green otherwise change it to red.

答:
This code is not good. I decided to rewrite it with the correct answers in one place. Also I added labels to each input element so that I can manipulate the CSS better.

Here is the JS:

```<code>
function check(){

    var correct = 0;
    var total_questions = 3;
    var correct_answers = ["Providence", "Hartford", "Albany"];

    $( "label" ).each(function( index ) {
        console.log( index + ": " + $( this ).text() );
        if (correct_answers.includes($( this ).text())) {
            this.style.color = 'green'
            correct++
        } else {
            this.style.color = 'red'

        }
    });

    document.getElementById("after_submit").style.visibility = "visible";

    document.getElementById("message").innerHTML = "Correct Answers:";
    document.getElementById("number_correct").innerHTML = "Score: " + correct + " / " + total_questions + " (" + Math.trunc((correct / total_questions)*100) + "%)";

    }

</code>```

Body:
I have a quiz system that is created in JS. I am using input elements to display each quiz option. I am trying to make it so when you click submit, it will loop through each input element and set the styling of the input text to green if it is a correct answer and red if it an incorrect answer. I am having trouble actually getting the text that is next to the input value however.

Below is a picture of the quiz:
https://gyazo.com/1ba5245de2c5c6f96bd728e31aeb0899

HTML:

<!DOCTYPE html>

<link href ="style.css" rel ="stylesheet">

Chapter 1 Quiz

<form id = "quiz" name = "quiz">

What is the capital of Rhode Island?

<input id = "textbox" type = "text" name = "question1">

What is the capital of Connecticut?

<input type = "radio" id = "mc" name = "question2" value = "Hartford"> Hartford

<input type = "radio" id = "mc" name = "question2" value = "Heartford"> Heartford

What is the capital of New York?

<input type = "radio" id = "mc" name = "question3" value = "Albany"> Albany

<input type = "radio" id = "mc" name = "question3" value = "All Benny's"> All Benny's

<input id = "button" type = "button" value = "Finish" onclick = "check();">
</form>

JAVASCRIPT:

function check(){

    var question1 = document.quiz.question1.value;
    var question2 = document.quiz.question2.value;
    var question3 = document.quiz.question3.value;
    var correct = 0;
    var total_questions = 3;

    if (question1 == "Providence") {
        correct++;
}
    if (question2 == "Hartford") {
        correct++;
}
    if (question3 == "Albany") {
        correct++;
    }

    var score;

    if (correct == 0) {
        score = 2;
    }

    if (correct > 0 && correct < total_questions) {
        score = 1;
    }

    if (correct == total_questions) {
        score = 0;
    }

    $( "input" ).each(function( index ) {
        console.log( index + ": " + $( this ).val() );
        // CHANGE THE STYLING HERE. VAL DOES NOT GET THE TEXT OF INPUT AND NIETHER DOES .text()
    });

    document.getElementById("after_submit").style.visibility = "visible";

    document.getElementById("message").innerHTML = "Correct Answers:";
    document.getElementById("number_correct").innerHTML = "Score: " + correct + " / " + total_questions + " (" + Math.trunc((correct / total_questions)*100) + "%)";

    }

I was thinking I could store the correct answers in the array and if the input has the value then change the styling of the text to green otherwise change it to red.

Body:
This code is not good. I decided to rewrite it with the correct answers in one place. Also I added labels to each input element so that I can manipulate the CSS better.

Here is the JS:

function check(){

    var correct = 0;
    var total_questions = 3;
    var correct_answers = ["Providence", "Hartford", "Albany"];

    $( "label" ).each(function( index ) {
        console.log( index + ": " + $( this ).text() );
        if (correct_answers.includes($( this ).text())) {
            this.style.color = 'green'
            correct++
        } else {
            this.style.color = 'red'

        }
    });

    document.getElementById("after_submit").style.visibility = "visible";

    document.getElementById("message").innerHTML = "Correct Answers:";
    document.getElementById("number_correct").innerHTML = "Score: " + correct + " / " + total_questions + " (" + Math.trunc((correct / total_questions)*100) + "%)";

    }


问:
Template operator overload is not picked up by linker
I have this minimal working example (I deliberately use cstdio here to keep nm output readable):

```<code>// main.cpp
#include "cstdio"
#include "foo.hpp"

int main() {
    Foo<int> foo{42};
    Foo<int> bar{42};

    bool b = foo == bar;
    printf("%d\n", b);

    return 0;
}
</code>```

```<code>// foo.hpp
#pragma once

template<typename T>
struct Foo {
    Foo(T foo_) : foo{foo_} {}

    T foo;

    friend bool operator==(const Foo<T> &lhs, const Foo<T> &rhs);
};
</code>```

```<code>// foo.cpp
#include "foo.hpp"

template<typename T>
bool operator==(const Foo<T> &lhs, const Foo<T> &rhs) {
    return false;
}

template struct Foo<int>;
template bool operator==(const Foo<int> &lhs, const Foo<int> &rhs);
</code>```

And I build it like this:

```<code>clang --std=c++2a -lstdc++ main.cpp foo.cpp
</code>```

It fails with

```<code>Undefined symbols for architecture x86_64:
  "operator==(Foo<int> const&, Foo<int> const&)", referenced from:
      _main in main-3d7fff.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

despite I explicitly instantiated operator== template.

I have rebuilt each file separately:

```<code>clang --std=c++2a -c main.cpp
clang --std=c++2a -c foo.cpp
</code>```

And explored both with nm:

```<code>main.o: 0000000000000060 T Foo<int>::Foo(int)
main.o: 0000000000000090 T Foo<int>::Foo(int)
main.o:                  U operator==(Foo<int> const&, Foo<int> const&)
main.o: 0000000000000000 T _main
main.o:                  U _printf
foo.o: 0000000000000020 T Foo<int>::Foo(int)
foo.o: 0000000000000000 T Foo<int>::Foo(int)
foo.o: 0000000000000050 T bool operator==<int>(Foo<int> const&, Foo<int> const&)
</code>```

And despite that two signatures look compatible to me, when I try to link this, it fails:

```<code>$ ld -lc foo.o main.o 2>&1 | c++filt
Undefined symbols for architecture x86_64:
  "operator==(Foo<int> const&, Foo<int> const&)", referenced from:
      _main in main.o
ld: symbol(short) not found for architecture x86_64
</code>```

Why? How can I fix this?

答:
Ok, asking the question had rubber duck effect. Compiler complaints, because it expects friend bool operator== to be a plain, non-template function, which it isn't — this can be seen by main.o expecting operator==, while foo.o exports operator==<int>.

In order to tell compiler that operator is a template on its own (implemented somewhere else), I had to change my foo.hpp as follows:

```<code>#pragma once

// forward declaration of Foo to use in forward declaration of operator== template
template<typename T> struct Foo;
// forward declaration of operator== template
template<typename T> bool operator==(const Foo<T> &lhs, const Foo<T> &rhs);

template<typename T>
struct Foo {
    Foo(T foo_) : foo{foo_} {}

    T foo;

    // indicate operator== is some template
    friend bool operator==<>(const Foo<T> &lhs, const Foo<T> &rhs);
};
</code>```

Now, nm produces expected output:

```<code>foo.o: 0000000000000050 T bool operator==<int>(Foo<int> const&, Foo<int> const&)
main.o:                  U bool operator==<int>(Foo<int> const&, Foo<int> const&)
</code>```

Which makes it all link properly.

Body:
I have this minimal working example (I deliberately use cstdio here to keep nm output readable):

// main.cpp
#include "cstdio"
#include "foo.hpp"

int main() {
    Foo<int> foo{42};
    Foo<int> bar{42};

    bool b = foo == bar;
    printf("%d\n", b);

    return 0;
}

// foo.hpp
#pragma once

template<typename T>
struct Foo {
    Foo(T foo_) : foo{foo_} {}

    T foo;

    friend bool operator==(const Foo<T> &lhs, const Foo<T> &rhs);
};

// foo.cpp
#include "foo.hpp"

template<typename T>
bool operator==(const Foo<T> &lhs, const Foo<T> &rhs) {
    return false;
}

template struct Foo<int>;
template bool operator==(const Foo<int> &lhs, const Foo<int> &rhs);

And I build it like this:

clang --std=c++2a -lstdc++ main.cpp foo.cpp

It fails with

Undefined symbols for architecture x86_64:
  "operator==(Foo<int> const&, Foo<int> const&)", referenced from:
      _main in main-3d7fff.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

despite I explicitly instantiated operator== template.

I have rebuilt each file separately:

clang --std=c++2a -c main.cpp
clang --std=c++2a -c foo.cpp

And explored both with nm:

main.o: 0000000000000060 T Foo<int>::Foo(int)
main.o: 0000000000000090 T Foo<int>::Foo(int)
main.o:                  U operator==(Foo<int> const&, Foo<int> const&)
main.o: 0000000000000000 T _main
main.o:                  U _printf
foo.o: 0000000000000020 T Foo<int>::Foo(int)
foo.o: 0000000000000000 T Foo<int>::Foo(int)
foo.o: 0000000000000050 T bool operator==<int>(Foo<int> const&, Foo<int> const&)

And despite that two signatures look compatible to me, when I try to link this, it fails:

$ ld -lc foo.o main.o 2>&1 | c++filt
Undefined symbols for architecture x86_64:
  "operator==(Foo<int> const&, Foo<int> const&)", referenced from:
      _main in main.o
ld: symbol(short) not found for architecture x86_64

Why? How can I fix this?

Body:
Ok, asking the question had rubber duck effect. Compiler complaints, because it expects friend bool operator== to be a plain, non-template function, which it isn't — this can be seen by main.o expecting operator==, while foo.o exports operator==<int>.

In order to tell compiler that operator is a template on its own (implemented somewhere else), I had to change my foo.hpp as follows:

#pragma once

// forward declaration of Foo to use in forward declaration of operator== template
template<typename T> struct Foo;
// forward declaration of operator== template
template<typename T> bool operator==(const Foo<T> &lhs, const Foo<T> &rhs);

template<typename T>
struct Foo {
    Foo(T foo_) : foo{foo_} {}

    T foo;

    // indicate operator== is some template
    friend bool operator==<>(const Foo<T> &lhs, const Foo<T> &rhs);
};

Now, nm produces expected output:

foo.o: 0000000000000050 T bool operator==<int>(Foo<int> const&, Foo<int> const&)
main.o:                  U bool operator==<int>(Foo<int> const&, Foo<int> const&)

Which makes it all link properly.


问:
Conversion from int to char failed and console prints weird symbol
I am having a weird issue and I don't know how to explain it. When I run this code it prints this symbol -> .
This is my code:

```<code>#include <iostream>

int main() {
     int num = 1;
     char number = num;

     std::cout<<number<<std::endl;

     system("PAUSE");
     return 0;
}
</code>```

I don't understand why. Normally it should convert the integer to char. I am using Dev C++ and my language standard is ISO C++11. I am programming for 4 years now and this is the first time I get something like this. I hope I explained my issue and if someone can help me I will be grateful.

答:
Then, since 4 years you seem to misunderstand what char is. It's not directly a character, but a number. It's the encoding that turns that number into a readable character.

Essentially, char i=1 is not the same as char i='1' (ascii table).

Body:
I am having a weird issue and I don't know how to explain it. When I run this code it prints this symbol -> .
This is my code:

#include <iostream>

int main() {
     int num = 1;
     char number = num;

     std::cout<<number<<std::endl;

     system("PAUSE");
     return 0;
}

I don't understand why. Normally it should convert the integer to char. I am using Dev C++ and my language standard is ISO C++11. I am programming for 4 years now and this is the first time I get something like this. I hope I explained my issue and if someone can help me I will be grateful.


问:
Getting rid of repeating parts of code in Activities
I'm new to Android, so at some point I realized that I have 20 Activities with same parts in them.

The whole;e structure of app is the following:
Activity1 -> Activity2 -> TaskActivity1 -> Activity3 -> Activity4 -> TaskActivity2 -> ...

So, there 2 types of repeating code: for simple Activities and for task Activities.

Providing code for simple Activities:

```<code>class Activity2 : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_2)
}

fun nextClick(view: View, ID: Int) {
    val intent3 = Intent(this, Activity3::class.java)
    startActivity(intent3)
    this.finish()
}

fun backClick(view: View){
    val intent1 = Intent(this, Activity1::class.java)
    startActivity(intent1)
    this.finish()
}
</code>```

}

With tasks, only 3 more buttons (for answers) are added (so, there 5 of them: next, ans1, ans2, ans3, back). Also, some of simple Activities do not have back button in layout.

So, obviously I have about 15 activities with the same code (and it looks awful).

I tried:

1) Creating a class for activities:

```<code>open class everyActivity(imageId: Int, nextActivity: Activity, prevActivity: Activity): AppCompatActivity() {

val imageId = imageId
val nextActivity = nextActivity
val prevActivity = prevActivity

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(imageId)
}

fun nextClick(view: View) {
    val intentNext = Intent(this, nextActivity::class.java)
    startActivity(intentNext)
    this.finish()
}

fun backClick(view: View){
    val intentPrev = Intent(this, prevActivity::class.java)
    startActivity(intentPrev)
    this.finish()
}
</code>```

}

And then in Activity:

```<code>class Kadr1Activity : KadrActivity(R.layout.activity_kadr01, Kadr2Activity(), Kadr0InfoActivity()) {
}
</code>```

It does not work, the app shows white screen.

2) Extracting functions for Clicks:

It's impossible to pass Activity variable in onClick, so Extracting functions doesn't help.

3) Sticking to 1 Activity:

I do not want to just change ImageView picture with every click. As I've already mentioned, some Activities look differently (with no back button), so keeping track of changing buttons depending on the current image is not convenient.

4) Single Activity Architecture

I want to have animation between activities and with fragments it is too complicated (according to the information I've found).

So, is it possible to get rid of repeating code in my app?

Would be grateful for any possible help, have no idea how to solve this

答:
If I couldn't just swap fragments and had to do separate Activities, I would make a single Activity class and open multiple instances of it, using Intent extras to determine the slight differences in behavior, like this:

```<code>class MyActivity: AppCompatActivity()

    private val screen by lazy {
        Screen.valueOf(intent.getStringExtra(SCREEN_KEY) ?: Screen.SCREEN_ONE.name)
        // The Elvis operator is to specifiy the default for when the activity
        // is the first instance from when the app was launched.
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.my_activity)
        imageView.setImageResource(screen.imageID)

        prepareButton(previousButton, Screen[screen.prevScreen])
        prepareButton(nextButton, Screen[screen.nextScreen])
    }

    private fun prepareButton(button: Button, targetScreen: Screen?) {
        if (targetScreen == null) {
            button.visibility = View.INVISIBLE
        } else {
            button.setOnClickListener {
                val intent = Intent(this, MyActivity::class.java)
                intent.putExtra(SCREEN_KEY, targetScreen.name)
                startActivity(intent)
                finish()
           }
        }
    }
}

private const SCREEN_KEY = "SCREEN"

enum class Screen(val imageID: Int, val prevScreen: String?, val nextScreen: String?) {
    SCREEN_ONE(R.drawable.screenOneImg, null, "SCREEN_TWO"),
    SCREEN_TWO(R.drawable.screenTwoImg, "SCREEN_ONE", "SCREEN_THREE"),
    SCREEN_THREE(R.drawable.screenThreeImg, "SCREEN_TWO", null)

    companion object {
        operator fun get(name: String?) = name?.let { Screen.valueOf(it) }
    }
}
</code>```

Note for simplicity the above sample code is written as if you're using synthetic view properties. If you're not, you would be using findViewById or view binding to get the view references.

Edit:

Here's a more beginner-friendly way to do it without an enum or lazy property:

```<code>class MyActivity: AppCompatActivity()

    companion object {
        private const SCREEN_KEY = "SCREEN"
        private const lastScreenIndex = 2 // if there are three screens (counting starts at 0)
    }

    private var screen: Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.my_activity)

        screen = intent.getStringExtra(SCREEN_KEY) ?: 0 // 0 is default screen number
        val screenImageResource = when (screen) {
            0 -> R.drawable.screen_0_image
            1 -> R.drawable.screen_1_image
            else -> R.drawable.screen_2_image
        }
        imageView.setImageResource(screenImageResource )

        prepareScreen(previousButton, screen - 1)
        prepareScreen(nextButton, screen + 1)
    }

    private fun prepareButton(button: Button, targetScreen: Int) {
        if ((0..lastScreenIndex).contains(targetScreen)) {
            button.setOnClickListener {
                val intent = Intent(this, MyActivity::class.java)
                intent.putExtra(SCREEN_KEY, targetScreen)
                startActivity(intent)
                finish()
           }
        } else {
            button.visibility = View.INVISIBLE
        }
    }
}
</code>```

Body:
I'm new to Android, so at some point I realized that I have 20 Activities with same parts in them.

The whole;e structure of app is the following:
Activity1 -> Activity2 -> TaskActivity1 -> Activity3 -> Activity4 -> TaskActivity2 -> ...

So, there 2 types of repeating code: for simple Activities and for task Activities.

Providing code for simple Activities:

class Activity2 : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_2)
}

fun nextClick(view: View, ID: Int) {
    val intent3 = Intent(this, Activity3::class.java)
    startActivity(intent3)
    this.finish()
}

fun backClick(view: View){
    val intent1 = Intent(this, Activity1::class.java)
    startActivity(intent1)
    this.finish()
}

}

With tasks, only 3 more buttons (for answers) are added (so, there 5 of them: next, ans1, ans2, ans3, back). Also, some of simple Activities do not have back button in layout.

So, obviously I have about 15 activities with the same code (and it looks awful).

I tried:

1) Creating a class for activities:

open class everyActivity(imageId: Int, nextActivity: Activity, prevActivity: Activity): AppCompatActivity() {

val imageId = imageId
val nextActivity = nextActivity
val prevActivity = prevActivity

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(imageId)
}

fun nextClick(view: View) {
    val intentNext = Intent(this, nextActivity::class.java)
    startActivity(intentNext)
    this.finish()
}

fun backClick(view: View){
    val intentPrev = Intent(this, prevActivity::class.java)
    startActivity(intentPrev)
    this.finish()
}

}

And then in Activity:

class Kadr1Activity : KadrActivity(R.layout.activity_kadr01, Kadr2Activity(), Kadr0InfoActivity()) {
}

It does not work, the app shows white screen.

2) Extracting functions for Clicks:

It's impossible to pass Activity variable in onClick, so Extracting functions doesn't help.

3) Sticking to 1 Activity:

I do not want to just change ImageView picture with every click. As I've already mentioned, some Activities look differently (with no back button), so keeping track of changing buttons depending on the current image is not convenient.

4) Single Activity Architecture

I want to have animation between activities and with fragments it is too complicated (according to the information I've found).

So, is it possible to get rid of repeating code in my app?

Would be grateful for any possible help, have no idea how to solve this

Body:
If I couldn't just swap fragments and had to do separate Activities, I would make a single Activity class and open multiple instances of it, using Intent extras to determine the slight differences in behavior, like this:

class MyActivity: AppCompatActivity()

    private val screen by lazy {
        Screen.valueOf(intent.getStringExtra(SCREEN_KEY) ?: Screen.SCREEN_ONE.name)
        // The Elvis operator is to specifiy the default for when the activity
        // is the first instance from when the app was launched.
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.my_activity)
        imageView.setImageResource(screen.imageID)

        prepareButton(previousButton, Screen[screen.prevScreen])
        prepareButton(nextButton, Screen[screen.nextScreen])
    }

    private fun prepareButton(button: Button, targetScreen: Screen?) {
        if (targetScreen == null) {
            button.visibility = View.INVISIBLE
        } else {
            button.setOnClickListener {
                val intent = Intent(this, MyActivity::class.java)
                intent.putExtra(SCREEN_KEY, targetScreen.name)
                startActivity(intent)
                finish()
           }
        }
    }
}

private const SCREEN_KEY = "SCREEN"

enum class Screen(val imageID: Int, val prevScreen: String?, val nextScreen: String?) {
    SCREEN_ONE(R.drawable.screenOneImg, null, "SCREEN_TWO"),
    SCREEN_TWO(R.drawable.screenTwoImg, "SCREEN_ONE", "SCREEN_THREE"),
    SCREEN_THREE(R.drawable.screenThreeImg, "SCREEN_TWO", null)

    companion object {
        operator fun get(name: String?) = name?.let { Screen.valueOf(it) }
    }
}

Note for simplicity the above sample code is written as if you're using synthetic view properties. If you're not, you would be using findViewById or view binding to get the view references.

Edit:

Here's a more beginner-friendly way to do it without an enum or lazy property:

class MyActivity: AppCompatActivity()

    companion object {
        private const SCREEN_KEY = "SCREEN"
        private const lastScreenIndex = 2 // if there are three screens (counting starts at 0)
    }

    private var screen: Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.my_activity)

        screen = intent.getStringExtra(SCREEN_KEY) ?: 0 // 0 is default screen number
        val screenImageResource = when (screen) {
            0 -> R.drawable.screen_0_image
            1 -> R.drawable.screen_1_image
            else -> R.drawable.screen_2_image
        }
        imageView.setImageResource(screenImageResource )

        prepareScreen(previousButton, screen - 1)
        prepareScreen(nextButton, screen + 1)
    }

    private fun prepareButton(button: Button, targetScreen: Int) {
        if ((0..lastScreenIndex).contains(targetScreen)) {
            button.setOnClickListener {
                val intent = Intent(this, MyActivity::class.java)
                intent.putExtra(SCREEN_KEY, targetScreen)
                startActivity(intent)
                finish()
           }
        } else {
            button.visibility = View.INVISIBLE
        }
    }
}


问:
Spring WebClient Post method Body
i'm trying to send a POST request with body data as described here: https://scrapyrt.readthedocs.io/en/stable/api.html#post.

Here's what i've tried to do but it gives me HTTP code 500

```<code>String uri = "http://localhost:3000";

WebClient webClient = WebClient.builder()
            .baseUrl(uri)
            .build();
LinkedMultiValueMap map = new LinkedMultiValueMap();

        String q = "\"url\": \"https://blog.trendmicro.com/trendlabs-security-intelligence\",\"meta\":{\"latestDate\" : \"18-05-2020\"}}";
        map.add("request", q);
        map.add("spider_name", "blog");

        BodyInserter<MultiValueMap<String, Object>, ClientHttpRequest> inserter2
         = BodyInserters.fromMultipartData(map);

        Mono<ItemsList> result = webClient.post()
                                          .uri(uriBuilder -> uriBuilder
                                                           .path("/crawl.json")
                                                           .build())
                                          .body(inserter2)
                                          .retrieve()
                                          .bodyToMono(ItemsList.class);

        ItemsList tempItems = result.block();
</code>```

答:
Here's what i've tried to do but it gives me HTTP code 500

Most likely because you're sending the wrong data in a mixture of wrong formats with the wrong type:

You're using multipart form data, not JSON

You're then setting the request parameter as a JSON string (q)

The JSON string you're using in q isn't even valid (it's at least missing an opening curly brace) - and handwriting JSON is almost universally a bad idea, leverage a framework to do it for you instead.

Instead, the normal thing to do would be to create a POJO structure that maps to your request, so:

```<code>public class CrawlRequest {

    private CrawlInnerRequest request;
    @JsonProperty("spider_name")
    private String spiderName;

    //....add the getters / setters
}

public class CrawlInnerRequest {

    private String url;
    private String callback;
    @JsonProperty("dont_filter")
    private String dontFilter;

    //....add the getters / setters
}
</code>```

...then simply create a CrawlRequest, set the values as you wish, then in your post call use:

```<code>.body(BodyInserters.fromValue(crawlRequest))
</code>```

This is a rather fundamental, basic part of using a WebClient. I'd suggest reading around more widely to give yourself a better understanding of the fundamentals, it will help tremendously in the long run.

Title: Spring WebClient Post method Body

Body:
i'm trying to send a POST request with body data as described here: https://scrapyrt.readthedocs.io/en/stable/api.html#post.

Here's what i've tried to do but it gives me HTTP code 500

String uri = "http://localhost:3000";

WebClient webClient = WebClient.builder()
            .baseUrl(uri)
            .build();
LinkedMultiValueMap map = new LinkedMultiValueMap();

        String q = "\"url\": \"https://blog.trendmicro.com/trendlabs-security-intelligence\",\"meta\":{\"latestDate\" : \"18-05-2020\"}}";
        map.add("request", q);
        map.add("spider_name", "blog");

        BodyInserter<MultiValueMap<String, Object>, ClientHttpRequest> inserter2
         = BodyInserters.fromMultipartData(map);

        Mono<ItemsList> result = webClient.post()
                                          .uri(uriBuilder -> uriBuilder
                                                           .path("/crawl.json")
                                                           .build())
                                          .body(inserter2)
                                          .retrieve()
                                          .bodyToMono(ItemsList.class);

        ItemsList tempItems = result.block();

Body:
Here's what i've tried to do but it gives me HTTP code 500

Most likely because you're sending the wrong data in a mixture of wrong formats with the wrong type:

You're using multipart form data, not JSON

You're then setting the request parameter as a JSON string (q)

The JSON string you're using in q isn't even valid (it's at least missing an opening curly brace) - and handwriting JSON is almost universally a bad idea, leverage a framework to do it for you instead.

Instead, the normal thing to do would be to create a POJO structure that maps to your request, so:

public class CrawlRequest {

    private CrawlInnerRequest request;
    @JsonProperty("spider_name")
    private String spiderName;

    //....add the getters / setters
}

public class CrawlInnerRequest {

    private String url;
    private String callback;
    @JsonProperty("dont_filter")
    private String dontFilter;

    //....add the getters / setters
}

...then simply create a CrawlRequest, set the values as you wish, then in your post call use:

.body(BodyInserters.fromValue(crawlRequest))

This is a rather fundamental, basic part of using a WebClient. I'd suggest reading around more widely to give yourself a better understanding of the fundamentals, it will help tremendously in the long run.


问:
selenium - Chromedriver- extension - Python / crx to crx3
since google updated chrome  , i can not add crx extension to the chromedriver in selenium , it throws an error

```<code>selenium.common.exceptions.SessionNotCreatedException: Message: session not created: cannot process extension #1
from unknown error: CRX verification failed to parse extension header. Chrome supports only CRX3 format. Does the extension need to be updated?
</code>```

does anyone know how to convert crx extension to crx3 ? i searched everywhere in Internet but no solution . Thanks alot

my search results without success >
WebDriverException: Message: unknown error: cannot process extension #1 from unknown error: CRX verification failed: 3

答:
-Go to chrome://extensions/
 -At the top right, turn on Developer mode.
 -Click Load unpacked.

Should be able to do this with selenium.

Alternatively, get an older version of chromedriver?
https://sites.google.com/a/chromium.org/chromedriver/downloads

Body:
since google updated chrome  , i can not add crx extension to the chromedriver in selenium , it throws an error

selenium.common.exceptions.SessionNotCreatedException: Message: session not created: cannot process extension #1
from unknown error: CRX verification failed to parse extension header. Chrome supports only CRX3 format. Does the extension need to be updated?

does anyone know how to convert crx extension to crx3 ? i searched everywhere in Internet but no solution . Thanks alot

my search results without success >
WebDriverException: Message: unknown error: cannot process extension #1 from unknown error: CRX verification failed: 3


问:
Why isn't .equals recognizing my variable as the same string that I'm passing it?
So this little function is supposed to check if parentheses and brackets are matched next to each other. I feel like it should work and I've tried it a few different ways but I can't figure out how to check if my next char is what I expect it to be.

```<code>class Parenths {
    public boolean isValid(String s) {
        char[] parens = s.toCharArray();
        if (parens.length == 0) return true;
        for (int i = 0; i < parens.length; i+=2) {
            String curr= String.valueOf(parens[i]);
            String next = String.valueOf(parens[i+1]);
            // System.out.println(next.equals(")");      --------> false
            // System.out.println(Object.equals(next, ")")); ----> error
            switch (curr) {
                case "(": if (!next.equals(")")) return false;
                case "{": if (!next.equals("}")) return false;
                case "[": if (!next.equals("]")) return false;
            }
        }
        return true;
    }
}
</code>```

You can see the lines I printed to debug and it seems that .equals is not the right thing to use here? Can anyone explain why this isn't working?

PS. I realize I don't have to convert the string to a char array to compare elements, so unless that's the only fix, please don't point that out to me.

答:
First , you have to add break; after the cases its important to stop seeing the cases

```<code> switch (curr) {
            case "(": if (!next.equals(")")) return false;
            break;
            case "{": if (!next.equals("}")) return false;
            break;
            case "[": if (!next.equals("]")) return false;
            break;
        }
</code>```

Secondly , your code doesnt support the confrotation of a closing patenthesis at first , you have to add a default case

```<code>           switch (curr) {
                case "(": if (!next.equals(")")) return false;
                break;
                case "{": if (!next.equals("}")) return false;
                break;
                case "[": if (!next.equals("]")) return false;
                break;
                default :
                    break;
            }
            return true;
</code>```

Also , you have to make sure the next element is not null before comparing to it , and dont increment with 2 , you give a String with a one element and that's why you get the error

```<code>public static boolean isValid(String s) {
        char[] parens = s.toCharArray();
        if (parens.length == 0) return true;
        for (int i = 0; i < parens.length; i++) {
            String curr= String.valueOf(parens[i]);
            String next = "";
            try {
            next = String.valueOf(parens[i+1]);

            switch (curr) {
                case "(": if (!next.equals(")")) return false;
                break;
                case "{": if (!next.equals("}")) return false;
                break;
                case "[": if (!next.equals("]")) return false;
                break;
                default :
                    break;
            }
            return true;
        }catch(Exception e) {}
            }
        return false;
    }
</code>```

Test :

```<code>  System.out.println(isValid("()"));
  // Output : true
  System.out.println(isValid("("));
  // Output : false
</code>```

Body:
So this little function is supposed to check if parentheses and brackets are matched next to each other. I feel like it should work and I've tried it a few different ways but I can't figure out how to check if my next char is what I expect it to be.

class Parenths {
    public boolean isValid(String s) {
        char[] parens = s.toCharArray();
        if (parens.length == 0) return true;
        for (int i = 0; i < parens.length; i+=2) {
            String curr= String.valueOf(parens[i]);
            String next = String.valueOf(parens[i+1]);
            // System.out.println(next.equals(")");      --------> false
            // System.out.println(Object.equals(next, ")")); ----> error
            switch (curr) {
                case "(": if (!next.equals(")")) return false;
                case "{": if (!next.equals("}")) return false;
                case "[": if (!next.equals("]")) return false;
            }
        }
        return true;
    }
}

You can see the lines I printed to debug and it seems that .equals is not the right thing to use here? Can anyone explain why this isn't working?

PS. I realize I don't have to convert the string to a char array to compare elements, so unless that's the only fix, please don't point that out to me.

Body:
First , you have to add break; after the cases its important to stop seeing the cases

 switch (curr) {
            case "(": if (!next.equals(")")) return false;
            break;
            case "{": if (!next.equals("}")) return false;
            break;
            case "[": if (!next.equals("]")) return false;
            break;
        }

Secondly , your code doesnt support the confrotation of a closing patenthesis at first , you have to add a default case

           switch (curr) {
                case "(": if (!next.equals(")")) return false;
                break;
                case "{": if (!next.equals("}")) return false;
                break;
                case "[": if (!next.equals("]")) return false;
                break;
                default :
                    break;
            }
            return true;

Also , you have to make sure the next element is not null before comparing to it , and dont increment with 2 , you give a String with a one element and that's why you get the error

public static boolean isValid(String s) {
        char[] parens = s.toCharArray();
        if (parens.length == 0) return true;
        for (int i = 0; i < parens.length; i++) {
            String curr= String.valueOf(parens[i]);
            String next = "";
            try {
            next = String.valueOf(parens[i+1]);

            switch (curr) {
                case "(": if (!next.equals(")")) return false;
                break;
                case "{": if (!next.equals("}")) return false;
                break;
                case "[": if (!next.equals("]")) return false;
                break;
                default :
                    break;
            }
            return true;
        }catch(Exception e) {}
            }
        return false;
    }

Test :

  System.out.println(isValid("()"));
  // Output : true
  System.out.println(isValid("("));
  // Output : false


问:
MySQL - Multiple Queries or Single Query
So I have a table that contains votes. The relevant columns for this issue being user and timestamp.

I need to grab the user's total vote count, and also their votes this month.

I know the queries - I'm not asking for those. I use these at the same time:

Votes this month / Total votes:

```<code>SELECT COUNT( 0 ) FROM votes WHERE ( timestamp BETWEEN DATE_FORMAT( NOW( ) ,'%Y-%m-01' ) AND NOW( ) ) AND user = ?;

SELECT COUNT( 0 ) FROM votes WHERE user = ?;
</code>```

At the moment, my database isn't large enough (or even queried enough) to where performance is an issue. However, that's expected to change shortly. Should I keep the queries separate, or should I:

```<code>SELECT COUNT( 0 ) AS totalVotes,
       SUM( IF( timestamp BETWEEN DATE_FORMAT( NOW( ) ,'%Y-%m-01' )
                              AND NOW( ), 1, 0 ) ) AS votesThisMonth
    FROM votes WHERE user = ?;
</code>```

What is the best practice? Are there any tips for querying multiple bits of information from the same table to prevent having to search it twice? Is my combined query even what I should be using?

Thanks!

答:
Slightly different, not necessarily faster than other suggestions:

```<code>SELECT COUNT(*) AS total,
       SUM(LEFT(timestamp, 7) = LEFT(NOW(), 7)) AS this_month
    FROM tbl
    WHERE user_id = ?
</code>```

And have

```<code>INDEX(user_id, timestamp) -- in this order.  ("Covering")
</code>```

Back to the question of 1 vs 2 queries:

My combined query makes one scan over all rows for the user.

The 'total' query also needs one scan over all rows for the user.

The 'this month' query, if using BETWEEN or >= makes a scan over just the rows for the user this month.  (Mine fails to do that, but it does not matter.)

Body:
So I have a table that contains votes. The relevant columns for this issue being user and timestamp.

I need to grab the user's total vote count, and also their votes this month.

I know the queries - I'm not asking for those. I use these at the same time:

Votes this month / Total votes:

SELECT COUNT( 0 ) FROM votes WHERE ( timestamp BETWEEN DATE_FORMAT( NOW( ) ,'%Y-%m-01' ) AND NOW( ) ) AND user = ?;

SELECT COUNT( 0 ) FROM votes WHERE user = ?;

At the moment, my database isn't large enough (or even queried enough) to where performance is an issue. However, that's expected to change shortly. Should I keep the queries separate, or should I:

SELECT COUNT( 0 ) AS totalVotes,
       SUM( IF( timestamp BETWEEN DATE_FORMAT( NOW( ) ,'%Y-%m-01' )
                              AND NOW( ), 1, 0 ) ) AS votesThisMonth
    FROM votes WHERE user = ?;

What is the best practice? Are there any tips for querying multiple bits of information from the same table to prevent having to search it twice? Is my combined query even what I should be using?

Thanks!

Body:
Slightly different, not necessarily faster than other suggestions:

SELECT COUNT(*) AS total,
       SUM(LEFT(timestamp, 7) = LEFT(NOW(), 7)) AS this_month
    FROM tbl
    WHERE user_id = ?

And have

INDEX(user_id, timestamp) -- in this order.  ("Covering")

Back to the question of 1 vs 2 queries:

My combined query makes one scan over all rows for the user.

The 'total' query also needs one scan over all rows for the user.

The 'this month' query, if using BETWEEN or >= makes a scan over just the rows for the user this month.  (Mine fails to do that, but it does not matter.)


问:
Django wont start with Docker
Docker starts my django server and says its up at 0.0.0.0:8000, but i cant reach it in my browser, neither 0.0.0.0:8000 nor 127.0.0.1:8000 work

```<code>web_1  | You have unapplied migrations; your app may not work properly until
they are applied.
web_1  | Run 'python manage.py migrate' to apply them.
web_1  | April 30, 2017 - 03:36:35
web_1  | Django version 1.8.5, using settings 'my_project.settings'
web_1  | Starting development server at http://0.0.0.0:8000/
web_1  | Quit the server with CONTROL-C.
</code>```

Dockerfile

```<code>version: '2'
services:
  db:
    image: postgres
  web:
    build: .
    command: python3 manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db
</code>```

答:
If you are using the legacy Docker Toolbox then, in that case, you need to find the IP of the VM that's running your Docker engine. If you run docker-machine ls, it should show the IP of your active engine. Then, go to port 8000 of that for your container.
for e.g- http://192.168.99.100:8000/
Here, 192.168.99.100 is the IP address of VM that's running my Docker engine.

Also, you have to add VM's IP in your ALLOWED_HOST in setting.py file

Title: Django wont start with Docker

Body:
Docker starts my django server and says its up at 0.0.0.0:8000, but i cant reach it in my browser, neither 0.0.0.0:8000 nor 127.0.0.1:8000 work

web_1  | You have unapplied migrations; your app may not work properly until
they are applied.
web_1  | Run 'python manage.py migrate' to apply them.
web_1  | April 30, 2017 - 03:36:35
web_1  | Django version 1.8.5, using settings 'my_project.settings'
web_1  | Starting development server at http://0.0.0.0:8000/
web_1  | Quit the server with CONTROL-C.

Dockerfile

version: '2'
services:
  db:
    image: postgres
  web:
    build: .
    command: python3 manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db