问:
How to find specific string within a group of like-named elements
For the XML below, how would I find which Election, with the latest date if there are multiple elections elected, each employee has chosen. A default value of 'Bronze' would be used if all elections say 'Waive' or when there are no elections for that employee.

Example XML:

```<code><Data>
    <Employee>
            <First_Name>Homer</First_Name>
            <Last_Name>Simpson</<Last_Name>
            <Elections>
                <Election type="Homer Simpson on 01/01/2020 (Gold Membership) (Waive)"/>
            </Elections>
            <Elections>
                <Election type="Homer Simpson on 01/01/2020 (Silver Membership) (Waive)"/>
            </Elections>
    </Employee>
    <Employee>
            <First_Name>Marge</First_Name>
            <Last_Name>Simpson</<Last_Name>
            <Elections>
                <Election type="Marge Simpson on 01/01/2020 (Gold Membership) (Waive)"/>
            </Elections>
            <Elections>
                <Election type="Marge Simpson on 01/03/2020 (Gold Membership) (Elect)"/>
            </Elections>
            <Elections>
                <Election type="Marge Simpson on 01/03/2020 (Silver Membership) (Waive)"/>
            </Elections>
    </Employee>
    <Employee>
            <First_Name>Lisa</First_Name>
            <Last_Name>Simpson</<Last_Name>
            <Elections>
                <Election type="Lisa Simpson on 01/01/2020 (Gold Membership) (Elect)"/>
            </Elections>
            <Elections>
                <Election type="Lisa Simpson on 01/01/2020 (Silver Membership) (Waive)"/>
            </Elections>
    </Employee>
    <Employee>
            <First_Name>Bart</First_Name>
            <Last_Name>Simpson</<Last_Name>
            <Elections>
                <Election type="Bart Simpson on 01/01/2020 (Gold Membership) (Waive)"/>
            </Elections>
            <Elections>
                <Election type="Bart Simpson on 01/01/2020 (Silver Membership) (Waive)"/>
            </Elections>
            <Elections>
                <Election type="Bart Simpson on 01/01/2020 (Bronze Membership) (Elect)"/>
            </Elections>
    </Employee>
    <Employee>
            <First_Name>Maggie</First_Name>
            <Last_Name>Simpson</<Last_Name>
            <Elections>
                <Election type="Lisa Simpson on 01/01/2020 (Silver Membership) (Elect)"/>
            </Elections>
            <Elections>
                <Election type="Lisa Simpson on 01/01/2020 (Gold Membership) (Waive)"/>
            </Elections>
    </Employee>
    <Employee>
            <First_Name>Grandpa</First_Name>
            <Last_Name>Simpson</<Last_Name>
    </Employee>
</Data>
</code>```

I tried a few things such as a for-each over the Elections/Election tag looking for the string "(Gold Membership) (Elect)" and "(Silver Membership) (Elect)" and setting a variable if it was found but that didn't work.

The desired output would be:

Homer, Simpson, Bronze

Marge, Simpson, Gold

Lisa, Simpson, Gold

Bart, Simpson, Bronze

Grandpa, Simpson, Silver

答:
This is a lot of work.

It would have been considerably simpler if each employee had only one election marked as Elect. But you say there can be more than one, and that only the latest one needs to be considered. And to make it even worse, you're using a date format that cannot be used for sorting as is.

Try something like the following:

XSLT 2.0

```<code><xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>

<xsl:template match="/Data">
    <xsl:for-each select="Employee">
        <!-- names -->
        <xsl:value-of select="First_Name" />
        <xsl:text>,</xsl:text>
        <xsl:value-of select="Last_Name" />
        <xsl:text>,</xsl:text>
        <!-- membership -->
        <xsl:variable name="valid-elections" select="Elections/Election[contains(@type, '(Elect)')]"/>
        <xsl:choose>
            <xsl:when test="$valid-elections">
                <xsl:variable name="memberships" as="element()*">
                    <xsl:perform-sort>
                        <!-- sort by reformatted date -->
                        <xsl:sort select="replace(@type, '.*(\d{2})/(\d{2})/(\d{4}).*', '$3$1$2')" order="descending"/>
                        <xsl:sequence select="$valid-elections"/>
                    </xsl:perform-sort>
                </xsl:variable>
                <!-- extract type from latest membership -->
                <xsl:value-of select="replace($memberships[1]/@type, '.*\((Gold|Silver|Bronze) Membership\).*', '$1')" />
            </xsl:when>
            <xsl:otherwise>Bronze</xsl:otherwise>
        </xsl:choose>
        <xsl:text>
</xsl:text>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>
</code>```

Demo: https://xsltfiddle.liberty-development.net/gWEaSvj

Body:
For the XML below, how would I find which Election, with the latest date if there are multiple elections elected, each employee has chosen. A default value of 'Bronze' would be used if all elections say 'Waive' or when there are no elections for that employee.

Example XML:

<Data>
    <Employee>
            <First_Name>Homer</First_Name>
            <Last_Name>Simpson</<Last_Name>
            <Elections>
                <Election type="Homer Simpson on 01/01/2020 (Gold Membership) (Waive)"/>
            </Elections>
            <Elections>
                <Election type="Homer Simpson on 01/01/2020 (Silver Membership) (Waive)"/>
            </Elections>
    </Employee>
    <Employee>
            <First_Name>Marge</First_Name>
            <Last_Name>Simpson</<Last_Name>
            <Elections>
                <Election type="Marge Simpson on 01/01/2020 (Gold Membership) (Waive)"/>
            </Elections>
            <Elections>
                <Election type="Marge Simpson on 01/03/2020 (Gold Membership) (Elect)"/>
            </Elections>
            <Elections>
                <Election type="Marge Simpson on 01/03/2020 (Silver Membership) (Waive)"/>
            </Elections>
    </Employee>
    <Employee>
            <First_Name>Lisa</First_Name>
            <Last_Name>Simpson</<Last_Name>
            <Elections>
                <Election type="Lisa Simpson on 01/01/2020 (Gold Membership) (Elect)"/>
            </Elections>
            <Elections>
                <Election type="Lisa Simpson on 01/01/2020 (Silver Membership) (Waive)"/>
            </Elections>
    </Employee>
    <Employee>
            <First_Name>Bart</First_Name>
            <Last_Name>Simpson</<Last_Name>
            <Elections>
                <Election type="Bart Simpson on 01/01/2020 (Gold Membership) (Waive)"/>
            </Elections>
            <Elections>
                <Election type="Bart Simpson on 01/01/2020 (Silver Membership) (Waive)"/>
            </Elections>
            <Elections>
                <Election type="Bart Simpson on 01/01/2020 (Bronze Membership) (Elect)"/>
            </Elections>
    </Employee>
    <Employee>
            <First_Name>Maggie</First_Name>
            <Last_Name>Simpson</<Last_Name>
            <Elections>
                <Election type="Lisa Simpson on 01/01/2020 (Silver Membership) (Elect)"/>
            </Elections>
            <Elections>
                <Election type="Lisa Simpson on 01/01/2020 (Gold Membership) (Waive)"/>
            </Elections>
    </Employee>
    <Employee>
            <First_Name>Grandpa</First_Name>
            <Last_Name>Simpson</<Last_Name>
    </Employee>
</Data>

I tried a few things such as a for-each over the Elections/Election tag looking for the string "(Gold Membership) (Elect)" and "(Silver Membership) (Elect)" and setting a variable if it was found but that didn't work.

The desired output would be:

Homer, Simpson, Bronze

Marge, Simpson, Gold

Lisa, Simpson, Gold

Bart, Simpson, Bronze

Grandpa, Simpson, Silver

Body:
This is a lot of work.

It would have been considerably simpler if each employee had only one election marked as Elect. But you say there can be more than one, and that only the latest one needs to be considered. And to make it even worse, you're using a date format that cannot be used for sorting as is.

Try something like the following:

XSLT 2.0

<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>

<xsl:template match="/Data">
    <xsl:for-each select="Employee">
        <!-- names -->
        <xsl:value-of select="First_Name" />
        <xsl:text>,</xsl:text>
        <xsl:value-of select="Last_Name" />
        <xsl:text>,</xsl:text>
        <!-- membership -->
        <xsl:variable name="valid-elections" select="Elections/Election[contains(@type, '(Elect)')]"/>
        <xsl:choose>
            <xsl:when test="$valid-elections">
                <xsl:variable name="memberships" as="element()*">
                    <xsl:perform-sort>
                        <!-- sort by reformatted date -->
                        <xsl:sort select="replace(@type, '.*(\d{2})/(\d{2})/(\d{4}).*', '$3$1$2')" order="descending"/>
                        <xsl:sequence select="$valid-elections"/>
                    </xsl:perform-sort>
                </xsl:variable>
                <!-- extract type from latest membership -->
                <xsl:value-of select="replace($memberships[1]/@type, '.*\((Gold|Silver|Bronze) Membership\).*', '$1')" />
            </xsl:when>
            <xsl:otherwise>Bronze</xsl:otherwise>
        </xsl:choose>
        <xsl:text>&#10;</xsl:text>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Demo: https://xsltfiddle.liberty-development.net/gWEaSvj


来源: stackexchange

问:
Swagger UI - " TypeError: Failed to fetch" on valid response
I've just pulled down the latest Swagger from the Git repo (3.0.19) using: https://github.com/swagger-api/swagger-ui.git and updated my API to use the new version.

Ran git describe --tags to confirm and my version is currently: v3.0.19-6-gaab1403

The problem I'm having is one described here, whereby my response is a 403 (I can see this in the inspector on the browser) and although I have a reponse for error 403, I still get the TypeError: Failed to fetch message.

Here's a snippet from my definition regarding the 403 response:

```<code>                    "403": {
                    "description": "Forbidden",
                    "headers": {
                        "Access-Control-Allow-Origin": {
                            "type": "string"
                        }
                    }
                },
</code>```

I've also noticed it reported here however, I know it's not a CORS issue as I have tested the endpoints and the OPTIONS are returning correct, as are the endpoints if called with valid information (I force this 403).

Could anyone point me in the right direction please?

Update: I have since tested on a 401 response, with the same response.

And that a 400 is working as expected:

答:
It's because some times your IIS Binding's HTTPS SSL Certificate will automatically goes to Not Selected. So again you haveThere was a similar question raised and there are few good answers Please refer this link to manually selectget the SSL Certificates to1 IIS Express Development Certificate1. Below I have mention how to doanswer:

Open IIS Click Default web sites.
In the right side corner you will see a some setting click "Bindings", you will get a Site Binding window.
Then you will get http and https details.
In that Click "https" and click edit, then you will get another window Edit Site Bindings.
In that window check SSL Certificates.
If SSL Certificate = Not Selected select IIS Express Development Certificate.
Then stop and Start the IIS.
Issue will be solved.

ContentLicense: CC BY-SA 3.0

Body:
I've just pulled down the latest Swagger from the Git repo (3.0.19) using: https://github.com/swagger-api/swagger-ui.git and updated my API to use the new version.

Ran git describe --tags to confirm and my version is currently: v3.0.19-6-gaab1403

The problem I'm having is one described here, whereby my response is a 403 (I can see this in the inspector on the browser) and although I have a reponse for error 403, I still get the TypeError: Failed to fetch message.

Here's a snippet from my definition regarding the 403 response:

                    "403": {
                    "description": "Forbidden",
                    "headers": {
                        "Access-Control-Allow-Origin": {
                            "type": "string"
                        }
                    }
                },

I've also noticed it reported here however, I know it's not a CORS issue as I have tested the endpoints and the OPTIONS are returning correct, as are the endpoints if called with valid information (I force this 403).

Could anyone point me in the right direction please?

Update: I have since tested on a 401 response, with the same response.

And that a 400 is working as expected:

ContentLicense: CC BY-SA 4.0


问:
How do I create a For-Loop for these vectors?
This is my current code (I'm a greenhorn!). Although it does the job, but I'm curious to find a more efficient code.

```<code>day1_av <- tapply(day1$lots_available, day1$hour, mean) %>% data.frame()
day2_av <- tapply(day2$lots_available, day2$hour, mean) %>% data.frame()
day3_av <- tapply(day3$lots_available, day3$hour, mean) %>% data.frame()
day4_av <- tapply(day4$lots_available, day4$hour, mean) %>% data.frame()
day5_av <- tapply(day5$lots_available, day5$hour, mean) %>% data.frame()
day6_av <- tapply(day6$lots_available, day6$hour, mean) %>% data.frame()
day7_av <- tapply(day7$lots_available, day7$hour, mean) %>% data.frame()
day_av <- cbind(day1_av, day2_av, day3_av, day4_av, day5_av, day6_av, day7_av)
day_av
</code>```

Is there a way to make a for-loop and create a data frame day_av out of this in R? I tried this:

```<code>day_av <- data.frame()
for(i in c(1:7)){
day[i]_av <- tapply(day[i]$lots_available, day[i]$hour, mean) %>% data.frame()
day_av <- rbind(day_av, day[i]_av)
</code>```

but the square brackets don't seem to send the message across. Appreciate any help, thank you~

答:
You could put all the dataframe in a list and then use tapply over them

```<code>output <- do.call(cbind, lapply(mget(paste0('day', 1:7)) function(x)
                         tapply(x$lots_available, x$hour, mean)))
</code>```

Body:
This is my current code (I'm a greenhorn!). Although it does the job, but I'm curious to find a more efficient code.

day1_av <- tapply(day1$lots_available, day1$hour, mean) %>% data.frame()
day2_av <- tapply(day2$lots_available, day2$hour, mean) %>% data.frame()
day3_av <- tapply(day3$lots_available, day3$hour, mean) %>% data.frame()
day4_av <- tapply(day4$lots_available, day4$hour, mean) %>% data.frame()
day5_av <- tapply(day5$lots_available, day5$hour, mean) %>% data.frame()
day6_av <- tapply(day6$lots_available, day6$hour, mean) %>% data.frame()
day7_av <- tapply(day7$lots_available, day7$hour, mean) %>% data.frame()
day_av <- cbind(day1_av, day2_av, day3_av, day4_av, day5_av, day6_av, day7_av)
day_av

Is there a way to make a for-loop and create a data frame day_av out of this in R? I tried this:

day_av <- data.frame()
for(i in c(1:7)){
day[i]_av <- tapply(day[i]$lots_available, day[i]$hour, mean) %>% data.frame()
day_av <- rbind(day_av, day[i]_av)

but the square brackets don't seem to send the message across. Appreciate any help, thank you~

Body:
You could put all the dataframe in a list and then use tapply over them

output <- do.call(cbind, lapply(mget(paste0('day', 1:7)) function(x)
                         tapply(x$lots_available, x$hour, mean)))


问:
Generate a random integer array with repeating values in J
I want to generate a random array with repeating values. Something like this:

```<code>4 11 6 3 5 4 16 11 26 5 4
</code>```

I know that the statement 12 ? 50 will generate a random integer array with 12 unique values in the range 0 to 49. How would I allow repeating values?

Also can J create random floating point arrays?

答:
NuVoc tells you in ?'s documentation under 'Use These Combinations':

```<code>   5 ?@$ 10
3 3 7 7 0
   5 ?@$ 10
6 7 6 6 9
</code>```

This has the same effect but is more performant than

```<code>   ? 5 $ 10
6 1 1 8 9
   ? 5 $ 10
5 9 7 2 9
</code>```

Which of course builds an array of five 10s and then applies ? to each of them to get a random number from 0..9, independently of the other results.

And can J create floating point arrays.

Totally missed this question. Yes, you'd do this the same way as with any other kind of array.

```<code>   datatype 1 2 3
integer
   datatype 1.1 2.2 3.3
floating
</code>```

Body:
I want to generate a random array with repeating values. Something like this:

4 11 6 3 5 4 16 11 26 5 4

I know that the statement 12 ? 50 will generate a random integer array with 12 unique values in the range 0 to 49. How would I allow repeating values?

Also can J create random floating point arrays?

Body:
NuVoc tells you in ?'s documentation under 'Use These Combinations':

   5 ?@$ 10
3 3 7 7 0
   5 ?@$ 10
6 7 6 6 9

This has the same effect but is more performant than

   ? 5 $ 10
6 1 1 8 9
   ? 5 $ 10
5 9 7 2 9

Which of course builds an array of five 10s and then applies ? to each of them to get a random number from 0..9, independently of the other results.

And can J create floating point arrays.

Totally missed this question. Yes, you'd do this the same way as with any other kind of array.

   datatype 1 2 3
integer
   datatype 1.1 2.2 3.3
floating


问:
How to convert a `const char *` to simply `char *`?
I'm using the pdCurses library and am aiming to only really use strings in my C++ console game but the curses mvinstr() function or any insert function requires a non-const char * as a parameter.

My solution at first to this problem was simply entering in string.c_str(), but that returns a const char * which apparently doesn't work with the function.

Next I put (char *)string.c_str() but this only causes an unhandled exception.

Finally I just tried char *test = string.c_str() but that's not compatible with const either.

What do I do to solve this?

K i just tried const_cast() and i still get an exception thrown and break....
I don't know why PDcurses only takes non-const char pointers.... =(

alright making a char* buffer didn't work when i used this code (time_s is the sting):

```<code>size_t length;
    char buffer[12];
    length=time_s.copy(buffer,5,0);
    buffer[length]='\0';
mvinstr(time_loc_y, time_loc_x, buffer);
</code>```

i even put a stop before mvinstr() and checked the buffer's contents which was "00   /0"
EXACTLY WHAT I WANTED.

but i get an access violation point to "xutility"....

答:
How about

```<code>char* buffer = &str[0];
int fetched_len = mvinnstr(time_loc_y, time_loc_x, buffer, str.size());
str.resize(fetched_len);
</code>```

In general, though, you should make a writable buffer instead of removing const from a pointer that has it.  e.g.

```<code>vector<char> charvec(MAX_LENGTH);
str = string(&charvec[0], mvinnstr(time_loc_y, time_loc_x, &charvec[0], charvec.size());
</code>```

Body:
I'm using the pdCurses library and am aiming to only really use strings in my C++ console game but the curses mvinstr() function or any insert function requires a non-const char * as a parameter.

My solution at first to this problem was simply entering in string.c_str(), but that returns a const char * which apparently doesn't work with the function.

Next I put (char *)string.c_str() but this only causes an unhandled exception.

Finally I just tried char *test = string.c_str() but that's not compatible with const either.

What do I do to solve this?

K i just tried const_cast() and i still get an exception thrown and break....
I don't know why PDcurses only takes non-const char pointers.... =(

alright making a char* buffer didn't work when i used this code (time_s is the sting):

size_t length;
    char buffer[12];
    length=time_s.copy(buffer,5,0);
    buffer[length]='\0';
mvinstr(time_loc_y, time_loc_x, buffer);

i even put a stop before mvinstr() and checked the buffer's contents which was "00   /0"
EXACTLY WHAT I WANTED.

but i get an access violation point to "xutility"....

Body:
How about

char* buffer = &str[0];
int fetched_len = mvinnstr(time_loc_y, time_loc_x, buffer, str.size());
str.resize(fetched_len);

In general, though, you should make a writable buffer instead of removing const from a pointer that has it.  e.g.

vector<char> charvec(MAX_LENGTH);
str = string(&charvec[0], mvinnstr(time_loc_y, time_loc_x, &charvec[0], charvec.size());


问:
How to debug a nodemon project in VSCode
I have a NodeJs project and I run it using nodemon,

I wish to run it in debug mode for development tasks, but I am unable to do so.

I found that I'll need to add the right configuration to the launch.json file under .vscode folder,

I have a app.js file which is the main app file.

And the application runs on node version 4.6.2 and on Port 8080.

In usual case I run the App using npm run dev command.

Following is my launch.json file -

```<code>{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "MyApp",
            "program": "${workspaceFolder}/app.js",
            "runtimeVersion": "4.6.2",
            "protocol": "legacy",
            "port": 8080
            //"runtimeExecutable": "/home/user/.nvm/versions/node/v4.6.2/bin/node"
        },
        {
            "type": "node",
            "request": "launch",
            "name": "nodemon",
            "runtimeExecutable": "nodemon",
            "program": "${workspaceRoot}/app.js",
            "restart": true,
            "console": "integratedTerminal",
            "internalConsoleOptions": "neverOpen",
            "runtimeVersion": "4.6.2",
            "protocol": "legacy",
            "port": 8080
        },
        {
            "type": "node",
            "request": "launch",
            "name": "DEBUG",
            "runtimeExecutable": "nodemon",
            "program": "${workspaceFolder}/app.js",
            "restart": true,
            "console": "integratedTerminal",
            "internalConsoleOptions": "neverOpen",
            "runtimeVersion": "4.6.2",
            "protocol": "legacy",
            "port": 8080
        }
    ]
}
</code>```

The package.json is as follows -

```<code>{
  "name": "myapp",
  "description": "myapp",
  "version": "1.35.0",
  "private": true,
  "scripts": {
    "dev": "nodemon app.js",
    "debug": "nodemon app.js"
  },
  "dependencies": {
    "async": "1.3.0",
    "aws-sdk": "2.7.20",
    "aws-xray-sdk": "^2.1.0",
    "aws-xray-sdk-restify": "^1.3.0-beta",
    "bcrypt": "0.8.5",
    "body-parser": "1.12.3",
    "compression": "^1.7.0",
    "connect-flash": "0.1.1",
    "cookie-parser": "1.3.4",
    "cron": "1.0.9",
    "csurf": "^1.9.0",
    "csvtojson": "^1.1.2",
    "date-utils": "1.2.16",
    "dotenv": "4.0.0",
    "email-templates": "1.2.1",
    "express": "4.12.3",
    "express-handlebars": "2.0.0",
    "express-jwt": "^5.1.0",
    "express-mailer": "0.2.4",
    "express-session": "1.11.1",
    "express-validator": "3.1.3",
    "handlebars": "^3.0.3",
    "helmet": "^3.5.0",
    "html-pdf": "1.4.0",
    "json-2-csv": "2.0.12",
    "jsonwebtoken": "^7.3.0",
    "multer": "^0.1.8",
    "mysql": "2.6.2",
    "newrelic": "1.25.0",
    "node-schedule": "^1.3.0",
    "nodemailer": "^1.3.4",
    "nodemailer-ses-transport": "1.2.0",
    "passport": "0.2.1",
    "passport-local": "1.0.0",
    "path": "0.11.14",
    "promise": "7.0.0",
    "qs": "^2.4.1",
    "replaceall": "0.1.6",
    "request": "2.55.0",
    "run-parallel": "1.1.0",
    "validator": "^7.0.0",
    "winston": "^2.3.1",
    "winston-daily-rotate-file": "^1.7.0",
    "xlsx": "0.8.8"
  },
  "devDependencies": {
    "nodemon": "^1.17.3"
  }
}
</code>```

The App gets launched when I run the DEBUG and nodemon configurations,

But the code is not getting paused on the breakpoints I put on the app.js file.

Reference links -

1. https://github.com/Microsoft/vscode-recipes/tree/master/nodemon

2. https://github.com/bdspen/nodemon_vscode

3. Can Visual Studio Code be configured to launch with nodemon

4. Cannot debug in VSCode by attaching to Chrome

5. https://code.visualstudio.com/docs/editor/debugging

What changes are required in package.json, or any corrections in Launch configuration - launch.json, that would help me to debug the application in VSCode for my usecase?

答:
You can launch and attach nodemon with F5, however it will require a little more setup.

We will have to first pre-launch nodemon via VS Code task and then attach.

I'm using remote debugger to attach since it does not require additional clicks to select the process to attach, and VS Code process picker is currently broken in WSL2, which is my main development environment.

tasks.json (from this answer):

```<code>{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "npm dev",
      "type": "npm",
      "script": "dev",
      "isBackground": true,

      // This task is run before some debug tasks.
      // Problem is, it's a watch script, and since it never exits, VSCode
      // complains. All this is needed so VSCode just lets it run.
      "problemMatcher": [
        {
          "pattern": [
            {
              "regexp": ".",
              "file": 1,
              "location": 2,
              "message": 3
            }
          ],
          "background": {
            "activeOnStart": true,
            "beginsPattern": ".",
            "endsPattern": "."
          }
        }
      ]
    }
  ]
}
</code>```

launch.json:

```<code>{
  "type": "node",
  "request": "attach",
  "name": "Launch & Attach",
  "restart": true,
  "localRoot": "${workspaceRoot}",
  "remoteRoot": "${workspaceRoot}",
  "preLaunchTask": "npm dev"
}
</code>```

And in npm dev script (for node >= 6.9):

```<code>nodemon --watch src -e js --exec node --inspect .
</code>```

Note - this approach won't work if your process takes more than 10 seconds to start.
In that case you will have to figure out how to signal VS Code when the pre-launch task has finished. This probably can be achieved by playing with beginsPattern / endPattern regex, though I haven't tried it.

Body:
I have a NodeJs project and I run it using nodemon,

I wish to run it in debug mode for development tasks, but I am unable to do so.

I found that I'll need to add the right configuration to the launch.json file under .vscode folder,

I have a app.js file which is the main app file.

And the application runs on node version 4.6.2 and on Port 8080.

In usual case I run the App using npm run dev command.

Following is my launch.json file -

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "MyApp",
            "program": "${workspaceFolder}/app.js",
            "runtimeVersion": "4.6.2",
            "protocol": "legacy",
            "port": 8080
            //"runtimeExecutable": "/home/user/.nvm/versions/node/v4.6.2/bin/node"
        },
        {
            "type": "node",
            "request": "launch",
            "name": "nodemon",
            "runtimeExecutable": "nodemon",
            "program": "${workspaceRoot}/app.js",
            "restart": true,
            "console": "integratedTerminal",
            "internalConsoleOptions": "neverOpen",
            "runtimeVersion": "4.6.2",
            "protocol": "legacy",
            "port": 8080
        },
        {
            "type": "node",
            "request": "launch",
            "name": "DEBUG",
            "runtimeExecutable": "nodemon",
            "program": "${workspaceFolder}/app.js",
            "restart": true,
            "console": "integratedTerminal",
            "internalConsoleOptions": "neverOpen",
            "runtimeVersion": "4.6.2",
            "protocol": "legacy",
            "port": 8080
        }
    ]
}

The package.json is as follows -

{
  "name": "myapp",
  "description": "myapp",
  "version": "1.35.0",
  "private": true,
  "scripts": {
    "dev": "nodemon app.js",
    "debug": "nodemon app.js"
  },
  "dependencies": {
    "async": "1.3.0",
    "aws-sdk": "2.7.20",
    "aws-xray-sdk": "^2.1.0",
    "aws-xray-sdk-restify": "^1.3.0-beta",
    "bcrypt": "0.8.5",
    "body-parser": "1.12.3",
    "compression": "^1.7.0",
    "connect-flash": "0.1.1",
    "cookie-parser": "1.3.4",
    "cron": "1.0.9",
    "csurf": "^1.9.0",
    "csvtojson": "^1.1.2",
    "date-utils": "1.2.16",
    "dotenv": "4.0.0",
    "email-templates": "1.2.1",
    "express": "4.12.3",
    "express-handlebars": "2.0.0",
    "express-jwt": "^5.1.0",
    "express-mailer": "0.2.4",
    "express-session": "1.11.1",
    "express-validator": "3.1.3",
    "handlebars": "^3.0.3",
    "helmet": "^3.5.0",
    "html-pdf": "1.4.0",
    "json-2-csv": "2.0.12",
    "jsonwebtoken": "^7.3.0",
    "multer": "^0.1.8",
    "mysql": "2.6.2",
    "newrelic": "1.25.0",
    "node-schedule": "^1.3.0",
    "nodemailer": "^1.3.4",
    "nodemailer-ses-transport": "1.2.0",
    "passport": "0.2.1",
    "passport-local": "1.0.0",
    "path": "0.11.14",
    "promise": "7.0.0",
    "qs": "^2.4.1",
    "replaceall": "0.1.6",
    "request": "2.55.0",
    "run-parallel": "1.1.0",
    "validator": "^7.0.0",
    "winston": "^2.3.1",
    "winston-daily-rotate-file": "^1.7.0",
    "xlsx": "0.8.8"
  },
  "devDependencies": {
    "nodemon": "^1.17.3"
  }
}

The App gets launched when I run the DEBUG and nodemon configurations,

But the code is not getting paused on the breakpoints I put on the app.js file.

Reference links -

1. https://github.com/Microsoft/vscode-recipes/tree/master/nodemon

2. https://github.com/bdspen/nodemon_vscode

3. Can Visual Studio Code be configured to launch with nodemon

4. Cannot debug in VSCode by attaching to Chrome

5. https://code.visualstudio.com/docs/editor/debugging

What changes are required in package.json, or any corrections in Launch configuration - launch.json, that would help me to debug the application in VSCode for my usecase?

Body:
You can launch and attach nodemon with F5, however it will require a little more setup.

We will have to first pre-launch nodemon via VS Code task and then attach.

I'm using remote debugger to attach since it does not require additional clicks to select the process to attach, and VS Code process picker is currently broken in WSL2, which is my main development environment.

tasks.json (from this answer):

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "npm dev",
      "type": "npm",
      "script": "dev",
      "isBackground": true,

      // This task is run before some debug tasks.
      // Problem is, it's a watch script, and since it never exits, VSCode
      // complains. All this is needed so VSCode just lets it run.
      "problemMatcher": [
        {
          "pattern": [
            {
              "regexp": ".",
              "file": 1,
              "location": 2,
              "message": 3
            }
          ],
          "background": {
            "activeOnStart": true,
            "beginsPattern": ".",
            "endsPattern": "."
          }
        }
      ]
    }
  ]
}

launch.json:

{
  "type": "node",
  "request": "attach",
  "name": "Launch & Attach",
  "restart": true,
  "localRoot": "${workspaceRoot}",
  "remoteRoot": "${workspaceRoot}",
  "preLaunchTask": "npm dev"
}

And in npm dev script (for node >= 6.9):

nodemon --watch src -e js --exec node --inspect .

Note - this approach won't work if your process takes more than 10 seconds to start.
In that case you will have to figure out how to signal VS Code when the pre-launch task has finished. This probably can be achieved by playing with beginsPattern / endPattern regex, though I haven't tried it.


问:
Handling firebase auth with react-router
I am building a React + Redux + Firebase app with webpack and am trying to figure out the best way to handle protected routes and redirects. I have tried using onEnter() with setTimeout() like many examples show, but it still ended up flashing the alternate component before redirecting.

Here is what I currently have, and I am trying to come up with a more elegant solution. This mostly works, but an example of when it fails is if I am on /profile and navigate to / in the browser. It seems that because firebase.auth() needs to initialize again, I get a flash of the HomePage component before it switches to Profile.

Firebase is initialized in firebaseClientConfig and I am passing firebase.auth() in to routes.

```<code>import { auth } from './firebaseClientConfig';

...

export default (
<Route path="/" component={App}>
 <IndexRoute
  getComponent={(nextState, cb) => {
    auth.onAuthStateChanged((user) => {
      if (!user) {
        return require.ensure([], require => {
          cb(null, require('./components/HomePage').default);
        });
      } else {
        return require.ensure([], require => {
          cb(null, require('./modules/Profile/Profile').default);
        });
      }
    });
  }}
/>
<Route
  path="/profile"
  getComponent={(nextState, cb) => {
    auth.onAuthStateChanged((user) => {
      if (user) {
        return require.ensure([], require => {
          cb(null, require('./modules/Profile/Profile').default);
        });
      } else {
        return require.ensure([], require => {
          cb(null, require('./modules/Login/Login').default);
        });
      }
    });
  }}
/>
</Route>
);
</code>```

Does anyone have a better way of doing this?

答:
if you are managing authentication using local state instead of redux then you need to create two states to hold progress of your authentication.

state={"loading=true",
"loggedin=false"}```

i.e. redner Loading component initialy when loading is true and when i receive current user state from firebase function i will use setState() to set loading to flase and further render the component i intend to render according to the user state.

For better understanding have look react firebase authentication

Body:
I am building a React + Redux + Firebase app with webpack and am trying to figure out the best way to handle protected routes and redirects. I have tried using onEnter() with setTimeout() like many examples show, but it still ended up flashing the alternate component before redirecting.

Here is what I currently have, and I am trying to come up with a more elegant solution. This mostly works, but an example of when it fails is if I am on /profile and navigate to / in the browser. It seems that because firebase.auth() needs to initialize again, I get a flash of the HomePage component before it switches to Profile.

Firebase is initialized in firebaseClientConfig and I am passing firebase.auth() in to routes.

import { auth } from './firebaseClientConfig';

...

export default (
<Route path="/" component={App}>
 <IndexRoute
  getComponent={(nextState, cb) => {
    auth.onAuthStateChanged((user) => {
      if (!user) {
        return require.ensure([], require => {
          cb(null, require('./components/HomePage').default);
        });
      } else {
        return require.ensure([], require => {
          cb(null, require('./modules/Profile/Profile').default);
        });
      }
    });
  }}
/>
<Route
  path="/profile"
  getComponent={(nextState, cb) => {
    auth.onAuthStateChanged((user) => {
      if (user) {
        return require.ensure([], require => {
          cb(null, require('./modules/Profile/Profile').default);
        });
      } else {
        return require.ensure([], require => {
          cb(null, require('./modules/Login/Login').default);
        });
      }
    });
  }}
/>
</Route>
);

Does anyone have a better way of doing this?

Body:
if you are managing authentication using local state instead of redux then you need to create two states to hold progress of your authentication.

state={"loading=true",
"loggedin=false"}

i.e. redner Loading component initialy when loading is true and when i receive current user state from firebase function i will use setState() to set loading to flase and further render the component i intend to render according to the user state.

For better understanding have look react firebase authentication


问:
Stringify a recursive `std::vector<std::vector<...>>` without using partial template function specialization
I seek (for example) to stringify a vector of vectors of ... (with arbitrarily deep nesting).

I tried the following:

```<code>#include <iostream>
#include <sstream>
#include <vector>

template<typename E>
std::string toString(const E& element) {
    std::ostringstream oss;
    oss << element;
    return oss.str();
}

template<typename E>
std::string toString<std::vector<E>>(const std::vector<E>& set) {
    std::ostringstream oss;
    oss << "{";
    bool started = false;
    for (const auto& el : set) {
        if (started) {
            oss << ",";
        }
        else {
            started = true;
        }
        oss << toString(el);
    }
    oss << "}";
    return oss.str();
}

int main()
{
  std::vector<std::vector<int>> v{{1},{2,3}};
  std::cout << toString(v) << std::endl; // want to output "{{1},{2,3}}"
  return 0;
}
</code>```

but it generates a compiler error since partial template function specialization is apparently not allowed. How am I supposed to do this kind of thing then?

答:
What you want here is not template specialization but function overloading.

Use this instead of your template specialization method.

```<code>template <typename E>
std::string toString(const std::vector<E>& set) {
    std::ostringstream oss;
    oss << "{";
    bool started = false;
    for (const auto& el : set) {
        if (started) {
            oss << ",";
        }
        else {
            started = true;
        }
        oss << toString(el);
    }
    oss << "}";
    return oss.str();
}
</code>```

Your code also has a typo: oss << toSring(el).

Body:
I seek (for example) to stringify a vector of vectors of ... (with arbitrarily deep nesting).

I tried the following:

#include <iostream>
#include <sstream>
#include <vector>

template<typename E>
std::string toString(const E& element) {
    std::ostringstream oss;
    oss << element;
    return oss.str();
}

template<typename E>
std::string toString<std::vector<E>>(const std::vector<E>& set) {
    std::ostringstream oss;
    oss << "{";
    bool started = false;
    for (const auto& el : set) {
        if (started) {
            oss << ",";
        }
        else {
            started = true;
        }
        oss << toString(el);
    }
    oss << "}";
    return oss.str();
}

int main()
{
  std::vector<std::vector<int>> v{{1},{2,3}};
  std::cout << toString(v) << std::endl; // want to output "{{1},{2,3}}"
  return 0;
}

but it generates a compiler error since partial template function specialization is apparently not allowed. How am I supposed to do this kind of thing then?

Body:
What you want here is not template specialization but function overloading.

Use this instead of your template specialization method.

template <typename E>
std::string toString(const std::vector<E>& set) {
    std::ostringstream oss;
    oss << "{";
    bool started = false;
    for (const auto& el : set) {
        if (started) {
            oss << ",";
        }
        else {
            started = true;
        }
        oss << toString(el);
    }
    oss << "}";
    return oss.str();
}

Your code also has a typo: oss << toSring(el).


问:
ADB Devices not showing phone, og droid
Hey Everyone,
I have had this working before, but all of the sudden it stopped working, I have reinstalled the drivers, restarted the adb server, restarted the phone and computer a few times, and it just won't work. The thing that is weird about it is that I had it working before, and it just stopped working, if I never had it working before, then I would assume I just didn't have something installed correctly, but it must be if it worked before. Any ideas for anything I can do to fix this, I am getting tired of using the crappy emulator :p

Thanks,
WWaldo

Edit: Editing the edit, because I am dumb and forgot I had the copy mode on...no new info on the issue then :(

答:
It can be many things:

bad device drivers: try removing all usb drivers for the device and start from scratch

bad mb drivers preventing the recognition of any usb: look into the device manager for trouble

as EboMike said, bad cable: do you hear the sound when the device is plugged in?

phone not in debug mode: adb requires usb debug mode. Check the phone settings

bad ROM: you mention "the rom I am running": flash another one and check

Title: ADB Devices not showing phone, og droid


问:
How to use the Directory.GetFiles() method to choose between today's date and another date?
I am trying to find files using XML Reader which meet some conditions including if the File Age is Younger than a certain number. I am getting an error for CreationTime but I do not understand how to get through it. d1 is the current date and d2 is the date range for the youngest file

Error   CS1061  'string' does not contain a definition for 'CreationTime' and no accessible extension method 'CreationTime' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)

```<code> public int FileAgeYounger
            {
                get
                {
                    return FileAgeYounger;
                }
                set
                {
                    DateTime d1 = DateTime.Now;
                    d2 = d1.AddDays(FileAgeYounger);

                    if (subfolders == true & FileExtension != null & Fileprefix != null & FileUseRelativeAgeYounger == true)
                    {
                        FolderLocation2 = Directory.GetFiles(FolderLocation, Fileprefix + FileExtension, SearchOption.AllDirectories).Where(f => f.CreationTime >= d2 && f.CreationTime <= d1));
                    }
                }
</code>```

答:
Directory.GetFiles returns only the name of the file.
You can use DirectoryInfo instead.

```<code>FileInfo[] fileInfos = new DirectoryInfo(FolderLocation).GetFiles();
IEnumerable<FileInfo> files = fileInfos.Where((f) => f.Extension.Equals(FileExtension)
            && f.Name.StartsWith(Fileprefix)
            && f.CreationTime >= d2
            && f.CreationTime <= d1);
</code>```

Body:
I am trying to find files using XML Reader which meet some conditions including if the File Age is Younger than a certain number. I am getting an error for CreationTime but I do not understand how to get through it. d1 is the current date and d2 is the date range for the youngest file

Error   CS1061  'string' does not contain a definition for 'CreationTime' and no accessible extension method 'CreationTime' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)

 public int FileAgeYounger
            {
                get
                {
                    return FileAgeYounger;
                }
                set
                {
                    DateTime d1 = DateTime.Now;
                    d2 = d1.AddDays(FileAgeYounger);

                    if (subfolders == true & FileExtension != null & Fileprefix != null & FileUseRelativeAgeYounger == true)
                    {
                        FolderLocation2 = Directory.GetFiles(FolderLocation, Fileprefix + FileExtension, SearchOption.AllDirectories).Where(f => f.CreationTime >= d2 && f.CreationTime <= d1));
                    }
                }

Body:
Directory.GetFiles returns only the name of the file.
You can use DirectoryInfo instead.

FileInfo[] fileInfos = new DirectoryInfo(FolderLocation).GetFiles();
IEnumerable<FileInfo> files = fileInfos.Where((f) => f.Extension.Equals(FileExtension)
            && f.Name.StartsWith(Fileprefix)
            && f.CreationTime >= d2
            && f.CreationTime <= d1);


问:
How to set the ServicePort in launchsettings.json for docker
So recently docker-integration in VS2017 has removed the docker project and simply works from launchsettings.json and a Dockerfile.

In my launchsettings.json I have the following:

```<code>"Docker": {
      "commandName": "Docker",
      "launchBrowser": true,
      "launchUrl": "{Scheme}://localhost:{ServicePort}/swagger"
    }
</code>```

Whenever I debug the application a random port is assigned.

If I include a valid sslPort in the iisExpress settings it takes the correct http and https ports from there, however my application is not currently using https so I'd rather not bind an unused port.

The below iisExpress settings seem to influence the docker settings. While below gives me what I want (a consistent binding from 81:80, host:container) I would prefer that port 444 was not also bound, or that the settings within another profile influence a different profile.

```<code>"iisExpress": {
      "applicationUrl": "http://localhost:81/",
      "sslPort": 444 (takes a random port if set to 0)
    }
</code>```

Any ideas? I would just like to be able to set the ServicePort / default port to a known value.

答:
The Docker section in launchsettings.json supports now httpPort and sslPort settings:

```<code>"Docker": {
      ...
    "httpPort": 8080
}
</code>```

Body:
So recently docker-integration in VS2017 has removed the docker project and simply works from launchsettings.json and a Dockerfile.

In my launchsettings.json I have the following:

"Docker": {
      "commandName": "Docker",
      "launchBrowser": true,
      "launchUrl": "{Scheme}://localhost:{ServicePort}/swagger"
    }

Whenever I debug the application a random port is assigned.

If I include a valid sslPort in the iisExpress settings it takes the correct http and https ports from there, however my application is not currently using https so I'd rather not bind an unused port.

The below iisExpress settings seem to influence the docker settings. While below gives me what I want (a consistent binding from 81:80, host:container) I would prefer that port 444 was not also bound, or that the settings within another profile influence a different profile.

"iisExpress": {
      "applicationUrl": "http://localhost:81/",
      "sslPort": 444 (takes a random port if set to 0)
    }

Any ideas? I would just like to be able to set the ServicePort / default port to a known value.

Body:
The Docker section in launchsettings.json supports now httpPort and sslPort settings:

"Docker": {
      ...
    "httpPort": 8080
}


问:
In Tkinter, How I disable Entry?
How I disable Entry in Tkinter.

```<code>def com():
       ....

entryy=Entry()
entryy.pack()

button=Button(text="Enter!", command=com, font=(24))
button.pack(expand="yes", anchor="center")
</code>```

As I said How I disable Entry in com function?

答:
if we want to change again and again data in entry box we will have to first convert into Normal state after changing data we will convert in to disable state</p>

```<code>import tkinter as tk
count = 0

def func(en):
    en.configure(state=tk.NORMAL)
    global count
    count += 1
    count=str(count)
    en.delete(0, tk.END)
    text = str(count)
    en.insert(0, text)
    en.configure(state=tk.DISABLED)
    count=int(count)

root = tk.Tk()

e = tk.Entry(root)
e.pack()

b = tk.Button(root, text='Click', command=lambda: func(e))
b.pack()

root.mainloop()
</code>```

Title: In Tkinter, How I disable Entry?

Body:
How I disable Entry in Tkinter.

def com():
       ....

entryy=Entry()
entryy.pack()

button=Button(text="Enter!", command=com, font=(24))
button.pack(expand="yes", anchor="center")

As I said How I disable Entry in com function?

Body:
if we want to change again and again data in entry box we will have to first convert into Normal state after changing data we will convert in to disable state

import tkinter as tk
count = 0

def func(en):
    en.configure(state=tk.NORMAL)
    global count
    count += 1
    count=str(count)
    en.delete(0, tk.END)
    text = str(count)
    en.insert(0, text)
    en.configure(state=tk.DISABLED)
    count=int(count)

root = tk.Tk()

e = tk.Entry(root)
e.pack()

b = tk.Button(root, text='Click', command=lambda: func(e))
b.pack()

root.mainloop()


问:
Exception handing in Spring Boot Rest API ResponseStatusException

While running the program saying remove the catch clause.

```<code>@RestController @RequestMapping(value = "/api/")
public class EmployeeController {

private EmployeeService employeeService;

@Autowired
public EmployeeController(EmployeeService employeeService) {
    this.employeeService = employeeService;
}

@GetMapping(value = "employee")
public List<Employee> getAllEmployee() {
    try {
        return employeeService.findAllEmployees();
    } catch (MyResourceNotFoundException ex) {
        throw new ResponseStatusException(
          HttpStatus.NOT_FOUND, "Employee not Found", ex);
    }
}
</code>```

}

This is the exception Class

```<code>@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Employee Not Found")
public class MyResourceNotFoundException extends Exception {
private static final long serialVersionUID = 1L;

public MyResourceNotFoundException(String errorMessage) {
    super(errorMessage);
}
}
</code>```

Kindly find below screenshot. This is the exception which is being thrown while running the application.

答:
I think there is a logical error in getAllEmployee method. Because, if in employeeService.findAllEmployees() there will be no employee, then by the logic of code it should return list of Employee with size 0. So, I think your code should look like this:

```<code>@GetMapping(value = "employee")
public List<Employee> getAllEmployee() throws MyResourceNotFoundException {
    List<Employee> employees = employeeService.findAllEmployees();

    if (employees.size() > 0) return employees;
    else throw new MyResourceNotFoundException("Employee not Found");
}
</code>```

Body:
While running the program saying remove the catch clause.

@RestController @RequestMapping(value = "/api/")
public class EmployeeController {

private EmployeeService employeeService;

@Autowired
public EmployeeController(EmployeeService employeeService) {
    this.employeeService = employeeService;
}

@GetMapping(value = "employee")
public List<Employee> getAllEmployee() {
    try {
        return employeeService.findAllEmployees();
    } catch (MyResourceNotFoundException ex) {
        throw new ResponseStatusException(
          HttpStatus.NOT_FOUND, "Employee not Found", ex);
    }
}

}

This is the exception Class

@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Employee Not Found")
public class MyResourceNotFoundException extends Exception {
private static final long serialVersionUID = 1L;

public MyResourceNotFoundException(String errorMessage) {
    super(errorMessage);
}
}

Kindly find below screenshot. This is the exception which is being thrown while running the application.

Body:
I think there is a logical error in getAllEmployee method. Because, if in employeeService.findAllEmployees() there will be no employee, then by the logic of code it should return list of Employee with size 0. So, I think your code should look like this:

@GetMapping(value = "employee")
public List<Employee> getAllEmployee() throws MyResourceNotFoundException {
    List<Employee> employees = employeeService.findAllEmployees();

    if (employees.size() > 0) return employees;
    else throw new MyResourceNotFoundException("Employee not Found");
}


问:
How to echo multidimension array define() function in php?
Below is the multidimensional array with define function. How would I echo so that the output value would show 5 from array 'a' => array 'apple'?

I tried echo Hello[0][2], but it doesn't show anything in the output.

```<code>define('Hello',
  array(
    'a' => array(
      'apple' => array(1,3,5),
      'orange' => array(543,345,345345),
      'grapes' => array(64,576,353)
      ),
    'b' => array(
      'apple' => array(1,3,5),
      'orange' => array(523,342,34645),
      'grapes' => array(66,76,33)
      )
    )
);
</code>```

Body:
Below is the multidimensional array with define function. How would I echo so that the output value would show 5 from array 'a' => array 'apple'?

I tried echo Hello[0][2], but it doesn't show anything in the output.

define('Hello',
  array(
    'a' => array(
      'apple' => array(1,3,5),
      'orange' => array(543,345,345345),
      'grapes' => array(64,576,353)
      ),
    'b' => array(
      'apple' => array(1,3,5),
      'orange' => array(523,342,34645),
      'grapes' => array(66,76,33)
      )
    )
);

Body:
I think are accessing by wrong indexes as print_r(Hello); shows

Array
(
    [a] => Array
        (
            [apple] => Array
                (
                    [0] => 1
                    [1] => 3
                    [2] => 5
                )

            [orange] => Array
                (
                    [0] => 543
                    [1] => 345
                    [2] => 345345
                )

            [grapes] => Array
                (
                    [0] => 64
                    [1] => 576
                    [2] => 353
                )

        )

    [b] => Array
        (
            [apple] => Array
                (
                    [0] => 1
                    [1] => 3
                    [2] => 5
                )

            [orange] => Array
                (
                    [0] => 523
                    [1] => 342
                    [2] => 34645
                )

            [grapes] => Array
                (
                    [0] => 66
                    [1] => 76
                    [2] => 33
                )

        )

)

so you need to access

Hello['a']['apple'][0];
Hello['b']['orange'][2];

which will give you 1 and 34645


问:
Trying to group an array of objects under same keys resulting in a new array of objects
I have an array of messages consisting of objects, where each object represents a single message and the created_at key representing the date of the message. I am receiving this data from the API. Here is the structure that I get:

```<code>let messages = [
  {text: "A", status: 'r', created_at: "2020-02-06"},
  {text: "B", status: 's', created_at: "2020-02-06"},
  {text: "C", status: 'r', created_at: "2020-02-06"},
  {text: "D", status: 's', created_at: "2020-02-07"},
  {text: "E", status: 's', created_at: "2020-02-07"},
  {text: "F", status: 'r', created_at: "2020-02-09"},
  {text: "G", status: 's', created_at: "2020-02-09"},
  {text: "H", status: 's', created_at: "2020-02-10"}
]
</code>```

I am using vuejs to render these messages in a chat application (similar to WhatsApp), where I want to display the date on top and the messages under that date in chronological order, just like WhatsApp. I am receiving the messages from the API in chronological order like the messages array I pasted above.
I would like to have the following output, so that I can use v-for directive in vuejs to loop through the messages and render them according to the date they were created:

```<code>  output:
    [
      {
        dt: "2020-02-06",
        arr: [
            {text: "A", status: 'r', created_at: "2020-02-06"},
            {text: "B", status: 's', created_at: "2020-02-06"},
            {text: "C", status: 'r', created_at: "2020-02-06"},
        ]
      },
      {
        dt: "2020-02-07",
        arr: [
            {text: "D", status: 's', created_at: "2020-02-06"},
            {text: "E", status: 's', created_at: "2020-02-06"},
        ]
      },
      {
        dt: "2020-02-09",
        arr: [
            {text: "F", status: 'r', created_at: "2020-02-09"},
            {text: "G", status: 's', created_at: "2020-02-09"},
        ]
      },
        {
        dt: "2020-02-10",
        arr: [
           {text: "H", status: 's', created_at: "2020-02-10"}
        ]
      },
    ]
</code>```

Is there a library in lodash that can achieve this directly?

What I have tried so far:

I was able to group the dates in an array without the dates repeating, like so:

```<code>let dates = messages.map((item => {
    return item.created_at
}))
let uniq = [...new Set(dates)];
console.log(uniq)
</code>```

...which gives the following output:

```<code>uniq = ["2020-02-06", "2020-02-07", "2020-02-09", "2020-02-10"]
</code>```

I am not able to move ahead of this.

Thanks in advance!

答:
There's no need to require a big library if you don't have to - iterate over the array and organize it into an object, where the keys are the dates and values are arrays for each date. Then map the object's entries to turn it into an array of objects:

let messages = [
  {text: "A", status: 'r', created_at: "2020-02-06"},
  {text: "B", status: 's', created_at: "2020-02-06"},
  {text: "C", status: 'r', created_at: "2020-02-06"},
  {text: "D", status: 's', created_at: "2020-02-07"},
  {text: "E", status: 's', created_at: "2020-02-07"},
  {text: "F", status: 'r', created_at: "2020-02-09"},
  {text: "G", status: 's', created_at: "2020-02-09"},
  {text: "H", status: 's', created_at: "2020-02-10"}
];
const messagesByDate = {};
for (const message of messages) {
  if (!messagesByDate[message.created_at]) {
    messagesByDate[message.created_at] = [];
  }
  messagesByDate[message.created_at].push(message);
}
const output = Object.entries(messagesByDate).map(([dt, arr]) => ({ dt, arr }));
console.log(output);```

Body:
I have an array of messages consisting of objects, where each object represents a single message and the created_at key representing the date of the message. I am receiving this data from the API. Here is the structure that I get:

let messages = [
  {text: "A", status: 'r', created_at: "2020-02-06"},
  {text: "B", status: 's', created_at: "2020-02-06"},
  {text: "C", status: 'r', created_at: "2020-02-06"},
  {text: "D", status: 's', created_at: "2020-02-07"},
  {text: "E", status: 's', created_at: "2020-02-07"},
  {text: "F", status: 'r', created_at: "2020-02-09"},
  {text: "G", status: 's', created_at: "2020-02-09"},
  {text: "H", status: 's', created_at: "2020-02-10"}
]

I am using vuejs to render these messages in a chat application (similar to WhatsApp), where I want to display the date on top and the messages under that date in chronological order, just like WhatsApp. I am receiving the messages from the API in chronological order like the messages array I pasted above.
I would like to have the following output, so that I can use v-for directive in vuejs to loop through the messages and render them according to the date they were created:

  output:
    [
      {
        dt: "2020-02-06",
        arr: [
            {text: "A", status: 'r', created_at: "2020-02-06"},
            {text: "B", status: 's', created_at: "2020-02-06"},
            {text: "C", status: 'r', created_at: "2020-02-06"},
        ]
      },
      {
        dt: "2020-02-07",
        arr: [
            {text: "D", status: 's', created_at: "2020-02-06"},
            {text: "E", status: 's', created_at: "2020-02-06"},
        ]
      },
      {
        dt: "2020-02-09",
        arr: [
            {text: "F", status: 'r', created_at: "2020-02-09"},
            {text: "G", status: 's', created_at: "2020-02-09"},
        ]
      },
        {
        dt: "2020-02-10",
        arr: [
           {text: "H", status: 's', created_at: "2020-02-10"}
        ]
      },
    ]

Is there a library in lodash that can achieve this directly?

What I have tried so far:

I was able to group the dates in an array without the dates repeating, like so:

let dates = messages.map((item => {
    return item.created_at
}))
let uniq = [...new Set(dates)];
console.log(uniq)

...which gives the following output:

uniq = ["2020-02-06", "2020-02-07", "2020-02-09", "2020-02-10"]

I am not able to move ahead of this.

Thanks in advance!


答:
Just by using this:</p>

```<code>echo Hello['a']['apple'][2];
</code>```

Title: How to echo multidimension array define() function in php?

Body:
Just by using this:

echo Hello['a']['apple'][2];


问:
How to get data from my axios request without using a setTimeout?
I am having a problem, I believe many of you have faced it somehow, so I am using axios to get my data :

```<code> let data = axios.get(
    "http://localhost:8080/api/taskExecution?&search=&page=1&size=8"
  ).then(response => {
    if (response.status !== 200) {
      console.log("LOADING");
    } else {
      return response.data;
    }
  });
  let tasks = [];

  data.then(response => {
    tasks = response;
  });

  console.log(tasks);

  return tasks;
</code>```

Something like this, response data returns array of 8 items, but tasks is still empty which is normal because the axios request takes some time, I can use setTimeout for 100ms and inside it, I put console.log(tasks); and it will work but is not a proper solution, because what if the server takes 5s to returns the data?

This code is in my reducer, so I have to get my tasks and return them so I can display them, and show a loader when the request is executed.

This is my reducer :

```<code>import update from "immutability-helper";
import Axios from "axios";

export default function getTasksReducer(state = [], action) {
  switch (action.type) {
    case "GET_TASKS":
      let data = Axios.get(
        "http://localhost:8080/api/taskExecution?&search=&page=1&size=8"
      ).then(response => {
        if (response.status !== 200) {
          console.log("LOADING");
        } else {
          return response.data;
        }
      });
      let tasks = [];

      data.then(response => {
        tasks = response;
      });

      console.log(tasks);

      return tasks;
    default:
      return state;
  }
}
</code>```

I need some help in this code and also in the conception of it, I mean where should I change my loader state and so forth.

答:
Alright buddy, so there're a few things I want to raise up:

First, you should always use your reducers only return new state to Redux, and that's it. You just merge new data that comes from actions, with your old state and return it back. And you can't use Promise or async/await in there because Redux doesn't and won't support that behavior.

Second, all the business logic should be placed in your actions. Data fetching(like in your case), computations and that kind of stuff needs be in actions. And now, you've come to the point where you, most likely, should start using libraries like redux-thunk or redux-saga to handle asynchronous operations within your actions. redux-thunk is less complicated than redux-saga, but redux-saga empowers you with a lot of cool features yet it could a bit complicated.

You can go big or start small with these libs, either way, they will force you to move you data fetching into your action. If you want support loading of data, then just dispatch actions that tell Redux: "I'm loading data" or "I got an error while loading data" or "I've loaded data". And when that action comes in, update your store, show loader, data or an error if you need. You can take a look on this or that  example of using redux-thunk for data fetching, there's everything you need to get started with async actions.

Hope it helps <3

Body:
I am having a problem, I believe many of you have faced it somehow, so I am using axios to get my data :

 let data = axios.get(
    "http://localhost:8080/api/taskExecution?&search=&page=1&size=8"
  ).then(response => {
    if (response.status !== 200) {
      console.log("LOADING");
    } else {
      return response.data;
    }
  });
  let tasks = [];

  data.then(response => {
    tasks = response;
  });

  console.log(tasks);

  return tasks;

Something like this, response data returns array of 8 items, but tasks is still empty which is normal because the axios request takes some time, I can use setTimeout for 100ms and inside it, I put console.log(tasks); and it will work but is not a proper solution, because what if the server takes 5s to returns the data?

This code is in my reducer, so I have to get my tasks and return them so I can display them, and show a loader when the request is executed.

This is my reducer :

import update from "immutability-helper";
import Axios from "axios";

export default function getTasksReducer(state = [], action) {
  switch (action.type) {
    case "GET_TASKS":
      let data = Axios.get(
        "http://localhost:8080/api/taskExecution?&search=&page=1&size=8"
      ).then(response => {
        if (response.status !== 200) {
          console.log("LOADING");
        } else {
          return response.data;
        }
      });
      let tasks = [];

      data.then(response => {
        tasks = response;
      });

      console.log(tasks);

      return tasks;
    default:
      return state;
  }
}

I need some help in this code and also in the conception of it, I mean where should I change my loader state and so forth.


问:
Spaces replaced by =20 after extracting text from email
I tried to get the text of a received gmail, using the email and imaplib modules in python. After decoding with utf-8 and after getting the payload of the message, all the spaces are still replaced by =20. Can I use another decoding step in order to fix this?

The code is the following: (I got it from a youtube tutorial - https://youtu.be/Jt8LizzxkPU )

``

```<code>import email
import imaplib

username = "abc"
password = "123"

mail = imaplib.IMAP4_SSL("imap.gmail.com")
mail.login(username,password)

mail.select("inbox")

result, data = mail.uid("search", None,"ALL")

inbox_item_list = data[0].split()

for item in inbox_item_list:
    #most_recent = inbox_item_list[-1]
    #oldest = inbox_item_list[0]

    result2, email_data = mail.uid('fetch',item,'(RFC822)')

    raw_email = email_data[0][1].decode("utf-8")

    email_message = email.message_from_string(raw_email)

    to_ = email_message['To']
    from_ = email_message['From']
    subject_ = email_message['Subject']

    counter = 1
    for part in email_message.walk():
        if part.get_content_maintype() == "multipart":
            continue
        filename = part.get_filename()
        if not filename:
            ext = ".html"
            filename = "msg-part-%08d%s" %(counter, ext)
        counter += 1

    #save file
    content_type = part.get_content_type()
    print(subject_)
    print (content_type)
    if "plain" in content_type:
        print(part.get_payload())
    elif "html" in content_type:
        print("do some beautiful soup")
    else:
        print(content_type)
</code>```

``

答:
Here's a complete code example of how a simple email (that contains both a literal =20 as well as =20 sequence that should be replaced by a space) could be decoded:

```<code>#!/usr/bin/env python3
import email.policy

email_text = """Subject: =?UTF-8?B?dGVzdCDwn5OnID0yMA==?=
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable

loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo=
oooooooooooooooooooooooooooooong=20word
=3D20
^ line starts with =3D20
emoji: <=F0=9F=93=A7>"""
msg = email.message_from_string(
    email_text, policy=email.policy.default
)
print("Subject: <{subject}>".format_map(msg))
assert not msg.is_multipart()
print(msg.get_content())
</code>```

Output

```<code>Subject: <test  =20>
loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong word
=20
^ line starts with =20
emoji: <>
</code>```

msg.walk(), part.get_payload(decode=True) could be used to traverse more complex EmailMessage objects. See email Examples.

Body:
I tried to get the text of a received gmail, using the email and imaplib modules in python. After decoding with utf-8 and after getting the payload of the message, all the spaces are still replaced by =20. Can I use another decoding step in order to fix this?

The code is the following: (I got it from a youtube tutorial - https://youtu.be/Jt8LizzxkPU )

``

import email
import imaplib

username = "abc"
password = "123"

mail = imaplib.IMAP4_SSL("imap.gmail.com")
mail.login(username,password)

mail.select("inbox")

result, data = mail.uid("search", None,"ALL")

inbox_item_list = data[0].split()

for item in inbox_item_list:
    #most_recent = inbox_item_list[-1]
    #oldest = inbox_item_list[0]

    result2, email_data = mail.uid('fetch',item,'(RFC822)')

    raw_email = email_data[0][1].decode("utf-8")

    email_message = email.message_from_string(raw_email)

    to_ = email_message['To']
    from_ = email_message['From']
    subject_ = email_message['Subject']

    counter = 1
    for part in email_message.walk():
        if part.get_content_maintype() == "multipart":
            continue
        filename = part.get_filename()
        if not filename:
            ext = ".html"
            filename = "msg-part-%08d%s" %(counter, ext)
        counter += 1

    #save file
    content_type = part.get_content_type()
    print(subject_)
    print (content_type)
    if "plain" in content_type:
        print(part.get_payload())
    elif "html" in content_type:
        print("do some beautiful soup")
    else:
        print(content_type)

``

Body:
Here's a complete code example of how a simple email (that contains both a literal =20 as well as =20 sequence that should be replaced by a space) could be decoded:

#!/usr/bin/env python3
import email.policy

email_text = """Subject: =?UTF-8?B?dGVzdCDwn5OnID0yMA==?=
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable

loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo=
oooooooooooooooooooooooooooooong=20word
=3D20
^ line starts with =3D20
emoji: <=F0=9F=93=A7>"""
msg = email.message_from_string(
    email_text, policy=email.policy.default
)
print("Subject: <{subject}>".format_map(msg))
assert not msg.is_multipart()
print(msg.get_content())

Output

Subject: <test  =20>
loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong word
=20
^ line starts with =20
emoji: <>

msg.walk(), part.get_payload(decode=True) could be used to traverse more complex EmailMessage objects. See email Examples.


问:
Trying to show the product of two EditTexts as a TextView in another activity
I am having a ton of trouble passing the product of two EditTexts to a TextView in another activity. Here is my code for MainActivity.

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

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

        val button1: Button = findViewById(R.id.button1)
        val editText1: EditText = findViewById(R.id.editText1)
        val editText2: EditText = findViewById(R.id.editText2)
        val firstNumber = editText1.toString().toInt()
        val secondNumber = editText2.toString().toInt()
        val product = firstNumber * secondNumber

        button1.setOnClickListener{

            val intent = Intent(this, Activity2::class.java)
            intent.putExtra("RESULT_PRODUCT", product)
            startActivity(intent)
        }
    }
}
</code>```

Here is my code for Activity2:

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

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

        val product = intent.getIntExtra("RESULT_SUM", 0)
        textView1.text = product.toString()
    }
}
</code>```

I am relatively new to Kotlin and Android Studio but this has caused crashes left and right.

答:
First of all, You have to calculate the product inside OnClickListener to get correct result.

```<code>button1.setOnClickListener{

    val firstNumber = editText1.text.toString().trim()
    val secondNumber = editText2.text.toString().trim()

    if(!(firstNumber.isEmpty() or secondNumber.isEmpty())) {
        val product = firstNumber.toInt() * secondNumber.toInt()

        val intent = Intent(this, Activity2::class.java)
        intent.putExtra("RESULT_PRODUCT", product)
        startActivity(intent)
    } else {
        //Show messages
    }
}
</code>```

And then you have to use the exact key RESULT_PRODUCT that you use in your activity to pass data through intent

```<code>val product = intent.getIntExtra("RESULT_PRODUCT", 0)
</code>```

Body:
I am having a ton of trouble passing the product of two EditTexts to a TextView in another activity. Here is my code for MainActivity.

class MainActivity : AppCompatActivity() {

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

        val button1: Button = findViewById(R.id.button1)
        val editText1: EditText = findViewById(R.id.editText1)
        val editText2: EditText = findViewById(R.id.editText2)
        val firstNumber = editText1.toString().toInt()
        val secondNumber = editText2.toString().toInt()
        val product = firstNumber * secondNumber

        button1.setOnClickListener{

            val intent = Intent(this, Activity2::class.java)
            intent.putExtra("RESULT_PRODUCT", product)
            startActivity(intent)
        }
    }
}

Here is my code for Activity2:

class Activity2 : AppCompatActivity() {

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

        val product = intent.getIntExtra("RESULT_SUM", 0)
        textView1.text = product.toString()
    }
}

I am relatively new to Kotlin and Android Studio but this has caused crashes left and right.

Body:
First of all, You have to calculate the product inside OnClickListener to get correct result.

button1.setOnClickListener{

    val firstNumber = editText1.text.toString().trim()
    val secondNumber = editText2.text.toString().trim()

    if(!(firstNumber.isEmpty() or secondNumber.isEmpty())) {
        val product = firstNumber.toInt() * secondNumber.toInt()

        val intent = Intent(this, Activity2::class.java)
        intent.putExtra("RESULT_PRODUCT", product)
        startActivity(intent)
    } else {
        //Show messages
    }
}

And then you have to use the exact key RESULT_PRODUCT that you use in your activity to pass data through intent

val product = intent.getIntExtra("RESULT_PRODUCT", 0)


问:
Cannot read a public array item inside chained AXIO transactions in VUE
I have a chained AXIOS call that is being called from an array.  I need to have the second call finish before the first one makes another API request and the process works fine.  My only problem is that I can't reference anything from inside the response of the second chain.  I need to update either the calling array(arr) a public array this.excelData.results or even a deep copy of the original array.  Every time I get an error saying:

```<code> err = TypeError: Cannot read property 'ORCID' of undefined at eval (webpack-
    internal:///./node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-
     loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-
    loader/lib/index.js?!./src/views/examples/ExcelWorksheet.vue?vue&type=script&lang=js&:410:49) at
    NodeList.forEach (<anonymous>) at eval (webpack-internal:///./node_modules/cache-
   loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-
   loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/views/examples/ExcelWorksheet.vue?
   vue&type=script&lang=js&:381:28) at NodeList.forEach (<anonymous>) at eval (webpack-
    internal:///./node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-
    loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-
    loader/lib/index.js?!./src/views/examples/ExcelWorksheet.vue?vue&type=script&lang=js&:378:33)
</code>```

I have tried adding this or self but nothing seems to help.  As I debug in a browser I can see all of the elements of the array but I can't read them in code or change them.  Is there something special that I need to do so that I can use the data from the second AXIOS call in the original array?

```<code>    lookUpORCID(){
   this.pubmedArticles=[];
   this.makeRequestsFromArray(this.excelData.results);
       },
          makeRequestsFromArray(arr) {

   var self = this
   let index = 0;
  function request() {

  let authorName =  arr[index]["Last_Name"]

  let linkGetIdList = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?';
  linkGetIdList += 'tool=biosketch&db=pubmed&retmode=json&retmax=200&';
  linkGetIdList += 'term=' + authorName +'[AU] ';

    return axios.get(linkGetIdList).then((res) => {
         index++;
         let idlist = res.data.esearchresult.idlist
         const passID = idlist.join(',')
        if (idlist.length > 0) {
          var getXmlLink = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?';
          getXmlLink += 'db=pubmed&retmode=xml&id=${passID}';
          return axios.get(getXmlLink).then((response) => {
             // parse document
              const parser = new DOMParser()
              const xmlDoc = parser.parseFromString(response.data, 'text/xml') // Get ALL XML content
              // Do Stuff

              **This is the spot that I need to change value in array**
              let xyz = arr[index]["ORCID"]

              return request();
          })
          }

        if (index >= arr.length) {
            return 'done'
        }
    });

}
return request();
</code>```

},

答:
You are able to access the arr or the error would have been: cannot read property index of undefined.

You have incremented index after the first request & the arr has the value undefined at the incremented index, so the error says Cannot read property 'ORCID' of undefined.

You can try console.log(arr[index]) before let xyz = arr[index]["ORCID"] to verify above.

Body:
I have a chained AXIOS call that is being called from an array.  I need to have the second call finish before the first one makes another API request and the process works fine.  My only problem is that I can't reference anything from inside the response of the second chain.  I need to update either the calling array(arr) a public array this.excelData.results or even a deep copy of the original array.  Every time I get an error saying:

 err = TypeError: Cannot read property 'ORCID' of undefined at eval (webpack-
    internal:///./node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-
     loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-
    loader/lib/index.js?!./src/views/examples/ExcelWorksheet.vue?vue&type=script&lang=js&:410:49) at
    NodeList.forEach (<anonymous>) at eval (webpack-internal:///./node_modules/cache-
   loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-
   loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/views/examples/ExcelWorksheet.vue?
   vue&type=script&lang=js&:381:28) at NodeList.forEach (<anonymous>) at eval (webpack-
    internal:///./node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-
    loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-
    loader/lib/index.js?!./src/views/examples/ExcelWorksheet.vue?vue&type=script&lang=js&:378:33)

I have tried adding this or self but nothing seems to help.  As I debug in a browser I can see all of the elements of the array but I can't read them in code or change them.  Is there something special that I need to do so that I can use the data from the second AXIOS call in the original array?

    lookUpORCID(){
   this.pubmedArticles=[];
   this.makeRequestsFromArray(this.excelData.results);
       },
          makeRequestsFromArray(arr) {

   var self = this
   let index = 0;
  function request() {

  let authorName =  arr[index]["Last_Name"]

  let linkGetIdList = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?';
  linkGetIdList += 'tool=biosketch&db=pubmed&retmode=json&retmax=200&';
  linkGetIdList += 'term=' + authorName +'[AU] ';

    return axios.get(linkGetIdList).then((res) => {
         index++;
         let idlist = res.data.esearchresult.idlist
         const passID = idlist.join(',')
        if (idlist.length > 0) {
          var getXmlLink = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?';
          getXmlLink += 'db=pubmed&retmode=xml&id=${passID}';
          return axios.get(getXmlLink).then((response) => {
             // parse document
              const parser = new DOMParser()
              const xmlDoc = parser.parseFromString(response.data, 'text/xml') // Get ALL XML content
              // Do Stuff

              **This is the spot that I need to change value in array**
              let xyz = arr[index]["ORCID"]

              return request();
          })
          }

        if (index >= arr.length) {
            return 'done'
        }
    });

}
return request();

},


问:
Difficulty with useState and useEffect with custom hook
Hello I'm having trouble with a custom hook

right when rendering the component everything is normal creates the key in storage, but when I try to click on the switch theme, my setTheme always goes as light and never as dark

i don't know where i am wrong ..:

code:

```<code>export default function App() {
  const [theme, setTheme] = usePersistedState('theme', { type: 'light' });
  const toggleTheme = () => {
    setTheme(theme.type === 'light' ? { type: 'dark' } : { type: 'light' });
  };
  console.log(theme.type, 'aa');
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />
      <div className="App">
        <button
          css={css`
            background: red;
            width: 100px;
            height: 50px;
            border-radius: 10px;
          `}
          onClick={toggleTheme}
        >
          a
        </button>
      </div>
    </ThemeProvider>
  );
}
</code>```

custom hook:

```<code>function usePersistedState(key, type) {
  console.log(key, type, 'xf');
  const [state, setState] = useState(() => {
    console.log('first');
    const storageValue = JSON.parse(localStorage.getItem(key));
    switch (storageValue) {
      case 'dark':
        return darkTheme;
      case 'light':
        return lightTheme;
      default:
        return lightTheme;
    }
  });

  useEffect(() => {
    const storageValue = JSON.parse(localStorage.getItem(key));
    if (storageValue !== state.type) {
      localStorage.setItem(key, JSON.stringify(state.type));
    }
  }, [key, state]);
  return [state, setState];
}
</code>```

example:

https://codesandbox.io/s/vigorous-goodall-x7x7d

gif:

答:
in App.js

```<code>setTheme(theme.type === "light" ? darkTheme : lightTheme);
</code>```

will solve your problem !!

Body:
Hello I'm having trouble with a custom hook

right when rendering the component everything is normal creates the key in storage, but when I try to click on the switch theme, my setTheme always goes as light and never as dark

i don't know where i am wrong ..:

code:

export default function App() {
  const [theme, setTheme] = usePersistedState('theme', { type: 'light' });
  const toggleTheme = () => {
    setTheme(theme.type === 'light' ? { type: 'dark' } : { type: 'light' });
  };
  console.log(theme.type, 'aa');
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />

        <button
          css={css`
            background: red;
            width: 100px;
            height: 50px;
            border-radius: 10px;
          `}
          onClick={toggleTheme}
        >
          a
        </button>

    </ThemeProvider>
  );
}

custom hook:

function usePersistedState(key, type) {
  console.log(key, type, 'xf');
  const [state, setState] = useState(() => {
    console.log('first');
    const storageValue = JSON.parse(localStorage.getItem(key));
    switch (storageValue) {
      case 'dark':
        return darkTheme;
      case 'light':
        return lightTheme;
      default:
        return lightTheme;
    }
  });

  useEffect(() => {
    const storageValue = JSON.parse(localStorage.getItem(key));
    if (storageValue !== state.type) {
      localStorage.setItem(key, JSON.stringify(state.type));
    }
  }, [key, state]);
  return [state, setState];
}

example:

https://codesandbox.io/s/vigorous-goodall-x7x7d

gif:

Body:
in App.js

setTheme(theme.type === "light" ? darkTheme : lightTheme);

will solve your problem !!


问:
Making an object listen to Activity lifecycle events?
One of the classes I've written needs to react when the following Activity events occur:

onStart()

onPause()

onResume()

onStop()

I can react to those on the Activity itself:

```<code>public class Activity extends ApplicationContext
{
    protected void onCreate(Bundle savedInstanceState);

    protected void onStart();

    protected void onRestart();

    protected void onResume();

    protected void onPause();

    protected void onStop();

    protected void onDestroy();
}
</code>```

From the Activity I could tell the object in question that a certain event has occurred, but I don't like this idea: it requires the developer to implement the logic outside my object/class. Ideally I would like the object to be responsible for registering these events and set itself as a listener, independent of the Activity.

Any ideas? Thanks in advance.

答:
Leverage ActivityLifecycleCallbacks that has been introduced since API level 14.

This is what the interface looks like now.

```<code>public interface ActivityLifecycleCallbacks {
    void onActivityCreated(Activity activity, Bundle savedInstanceState);
    void onActivityStarted(Activity activity);
    void onActivityResumed(Activity activity);
    void onActivityPaused(Activity activity);
    void onActivityStopped(Activity activity);
    void onActivitySaveInstanceState(Activity activity, Bundle outState);
    void onActivityDestroyed(Activity activity);
}
</code>```

What you need to do is simply to implement the interface methods and register it on your application.

```<code>public class MyApplication extends Application implements ActivityLifecycleCallbacks {
    @Override
    public void onCreate() {
         super.onCreate();
         this.registerActivityLifecycleCallbacks(this);
    }

    //implement call back methods.
}
</code>```

Body:
One of the classes I've written needs to react when the following Activity events occur:

onStart()

onPause()

onResume()

onStop()

I can react to those on the Activity itself:

public class Activity extends ApplicationContext
{
    protected void onCreate(Bundle savedInstanceState);

    protected void onStart();

    protected void onRestart();

    protected void onResume();

    protected void onPause();

    protected void onStop();

    protected void onDestroy();
}

From the Activity I could tell the object in question that a certain event has occurred, but I don't like this idea: it requires the developer to implement the logic outside my object/class. Ideally I would like the object to be responsible for registering these events and set itself as a listener, independent of the Activity.

Any ideas? Thanks in advance.

Body:
Leverage ActivityLifecycleCallbacks that has been introduced since API level 14.

This is what the interface looks like now.

public interface ActivityLifecycleCallbacks {
    void onActivityCreated(Activity activity, Bundle savedInstanceState);
    void onActivityStarted(Activity activity);
    void onActivityResumed(Activity activity);
    void onActivityPaused(Activity activity);
    void onActivityStopped(Activity activity);
    void onActivitySaveInstanceState(Activity activity, Bundle outState);
    void onActivityDestroyed(Activity activity);
}

What you need to do is simply to implement the interface methods and register it on your application.

public class MyApplication extends Application implements ActivityLifecycleCallbacks {
    @Override
    public void onCreate() {
         super.onCreate();
         this.registerActivityLifecycleCallbacks(this);
    }

    //implement call back methods.
}


问:
Javascript, jQuery, Do function after another function
I have this javascript function.

```<code><script type="text/javascript">
  $(document).ready(function () {
  $('#load').html('<img style="display:block; margin:10px auto;background-color: #EEE;" src="<?echo $site["url"];?>images/icons/loading.gif"/>');
  $('#loaded').fadeIn(1500);
     $('#load').fadeOut(2000);
  });
</script>
</code>```

As you may see it simply runs a loading image for a tot of seconds, then shows the div and hide the loading image.
This is not good for me. I need a function that will work in this way. The logic of the code would be:

```<code>As soon as $('#load').html('<img style="display:block; margin:10px auto;background-color: #EEE;" src="<?echo $site["url"];?>images/icons/loading.gif"/>'); is running, then wait 4 seconds, and then show the #loaded DIV.
</code>```

In this way the #loaded DIV will be fully loaded and it will work fine, since it is an heavy one.

In few words I must to be sure that #loaded has been fully loaded by the browser before showing it.
How can I create a function that will do that?

On document ready show the loading DIV. Then WAIT for 3-4 seconds, then make the loading disappear and the loaded DIV visible.

Is this possible?

答:
You could bind a handler to the load event on the #loaded div:

```<code>$(document).ready(function() {
    $('#loaded').load(function() {
        $('#loaded').fadeIn(500);
        $('#load').fadeOut(500);
    });
});
</code>```

See http://api.jquery.com/load-event/

Body:
I have this javascript function.

As you may see it simply runs a loading image for a tot of seconds, then shows the div and hide the loading image.
This is not good for me. I need a function that will work in this way. The logic of the code would be:

As soon as $('#load').html('<img style="display:block; margin:10px auto;background-color: #EEE;" src="<?echo $site["url"];?>images/icons/loading.gif"/>'); is running, then wait 4 seconds, and then show the #loaded DIV.

In this way the #loaded DIV will be fully loaded and it will work fine, since it is an heavy one.

In few words I must to be sure that #loaded has been fully loaded by the browser before showing it.
How can I create a function that will do that?

On document ready show the loading DIV. Then WAIT for 3-4 seconds, then make the loading disappear and the loaded DIV visible.

Is this possible?

Body:
You could bind a handler to the load event on the #loaded div:

$(document).ready(function() {
    $('#loaded').load(function() {
        $('#loaded').fadeIn(500);
        $('#load').fadeOut(500);
    });
});

See http://api.jquery.com/load-event/