问:
gradle package org.springframework.test.context does not exist
I'm trying to use the dependency "testCompile group: 'org.springframework', name: 'spring-test', version: '4.3.18.RELEASE'" buy when I run gradle clean build it shows

error: package org.springframework.test.context does not exist
import org.springframework.test.context.ContextConfiguration;

This is my build.gradle

```<code>/*
 * This build file was auto generated by running the Gradle 'init' task
 * by 'diego.virguez' at '5/22/19 10:16 AM' with Gradle 2.14.1-rc-1
 *
 * This generated file contains a sample Java project to get you started.
 * For more details take a look at the Java Quickstart chapter in the Gradle
 * user guide available at https://docs.gradle.org/2.14.1-rc-1/userguide/tutorial_java_projects.html
 */

// Apply the java plugin to add support for Java
apply plugin: 'java'

// In this section you declare where to find the dependencies of your project
repositories {
    // Use 'jcenter' for resolving your dependencies.
    // You can declare any Maven/Ivy/file repository here.
    jcenter()
    mavenLocal()
    mavenCentral()

}

// In this section you declare the dependencies for your production and test code
dependencies {
    // The production code uses the SLF4J logging API at compile time
    compile 'org.slf4j:slf4j-api:1.7.21'
    compile 'org.springframework:spring-webmvc:4.1.6.RELEASE'
    compile 'junit:junit:4.12'
    compile 'javax.servlet:jstl:1.2'

    // Declare the dependency for your favourite test framework you want to use in your tests.
    // TestNG is also supported by the Gradle Test task. Just change the
    // testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add
    // 'test.useTestNG()' to your build script.
    testCompile 'junit:junit:4.12'
    testCompile group: 'org.springframework', name: 'spring-test', version: '4.3.18.RELEASE'
    //testCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1-b09'
    compile group: 'org.springframework', name: 'spring-tx', version: '5.1.2.RELEASE'

}
</code>```

and this is the error:

Task :compileJava FAILED
  D:\projects\personal\wiring-beans\src\main\java\soundsystem\CDPlayerTest.java:8:
  error: package org.springframework.test.context does not exist import
  org.springframework.test.context.ContextConfiguration;
                                         ^ D:\projects\personal\wiring-beans\src\main\java\soundsystem\CDPlayerTest.java:9:
  error: package org.springframework.test.context.junit4 does not exist
  import
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
                                                ^ D:\projects\personal\wiring-beans\src\main\java\soundsystem\CDPlayerTest.java:12:
  error: cannot find symbol @ContextConfiguration(classes =
  CDPlayerConfig.class)  ^   symbol: class ContextConfiguration
  D:\projects\personal\wiring-beans\src\main\java\soundsystem\CDPlayerTest.java:11:
  error: cannot find symbol @RunWith(SpringJUnit4ClassRunner.class)
           ^   symbol: class SpringJUnit4ClassRunner 4 errors

答:
I have found that the easiest, most failsafe way to create a Spring project is to use Spring's handy-dandy project intializer.

Just select „Gradle Project“, „Java“, „2.25“ (the stable version of Spring Boot), fill in the values for your project's „Group“ and „Artifact“.

In the „Search dependencies to add“ field, you would enter  „web“ and select what's presented. Then just click the green „Generate Project“ button.

After you download the generated starter project, build it. It's pretty much guaranteed to build successfully right out the gate. Because all of the required dependencies and transitive dependencies have been taken care of for you by Spring.

Even if you decide not to base your own project off that starter project (which I would advise against), you at least will be able to see what a correctly-configured Spring project should look like.

Body:
I'm trying to use the dependency "testCompile group: 'org.springframework', name: 'spring-test', version: '4.3.18.RELEASE'" buy when I run gradle clean build it shows

error: package org.springframework.test.context does not exist
import org.springframework.test.context.ContextConfiguration;

This is my build.gradle

/*
 * This build file was auto generated by running the Gradle 'init' task
 * by 'diego.virguez' at '5/22/19 10:16 AM' with Gradle 2.14.1-rc-1
 *
 * This generated file contains a sample Java project to get you started.
 * For more details take a look at the Java Quickstart chapter in the Gradle
 * user guide available at https://docs.gradle.org/2.14.1-rc-1/userguide/tutorial_java_projects.html
 */

// Apply the java plugin to add support for Java
apply plugin: 'java'

// In this section you declare where to find the dependencies of your project
repositories {
    // Use 'jcenter' for resolving your dependencies.
    // You can declare any Maven/Ivy/file repository here.
    jcenter()
    mavenLocal()
    mavenCentral()

}

// In this section you declare the dependencies for your production and test code
dependencies {
    // The production code uses the SLF4J logging API at compile time
    compile 'org.slf4j:slf4j-api:1.7.21'
    compile 'org.springframework:spring-webmvc:4.1.6.RELEASE'
    compile 'junit:junit:4.12'
    compile 'javax.servlet:jstl:1.2'

    // Declare the dependency for your favourite test framework you want to use in your tests.
    // TestNG is also supported by the Gradle Test task. Just change the
    // testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add
    // 'test.useTestNG()' to your build script.
    testCompile 'junit:junit:4.12'
    testCompile group: 'org.springframework', name: 'spring-test', version: '4.3.18.RELEASE'
    //testCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1-b09'
    compile group: 'org.springframework', name: 'spring-tx', version: '5.1.2.RELEASE'

}

and this is the error:

Task :compileJava FAILED
  D:\projects\personal\wiring-beans\src\main\java\soundsystem\CDPlayerTest.java:8:
  error: package org.springframework.test.context does not exist import
  org.springframework.test.context.ContextConfiguration;
                                         ^ D:\projects\personal\wiring-beans\src\main\java\soundsystem\CDPlayerTest.java:9:
  error: package org.springframework.test.context.junit4 does not exist
  import
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
                                                ^ D:\projects\personal\wiring-beans\src\main\java\soundsystem\CDPlayerTest.java:12:
  error: cannot find symbol @ContextConfiguration(classes =
  CDPlayerConfig.class)  ^   symbol: class ContextConfiguration
  D:\projects\personal\wiring-beans\src\main\java\soundsystem\CDPlayerTest.java:11:
  error: cannot find symbol @RunWith(SpringJUnit4ClassRunner.class)
           ^   symbol: class SpringJUnit4ClassRunner 4 errors


来源: stackexchange

问:
How does findstr "^" equate to an empty directory?
Batch files in Windows can be confusing at the best of times. How does

```<code>  findstr "^"
</code>```

equate to finding an empty folder, when ^ means the start of the line?

```<code>for /d /r %1 %%A in (.) do (
  dir /ad /b "%%~fA" 2>nul | findstr "^" >nul || echo %%~fA
)
</code>```

taken from dbenham's answer

Unless I'm reading this wrong and it's

```<code>dir /ad /b "%%~fA" 2>nul
</code>```

that finds empty folders.

答:
This script will get a list of directories (and their subdirectories), loop through each directory to check for subdirectories, then list only the directory names that did not contain a subdirectory. The original script in the link provided works similarly except that it will only list completely empty directories (not containing subdirectories or files). Here is a breakdown of each section of code:

The for /d in your example is getting a recursive list of directories:

```<code>for /d /r %1 %%A in (.) do ( )
</code>```

for /d loops through the specified set of directories

for /d /r tells the for loop to recurse into subdirectories

%1 is an optional file path specified from the command-line

%%A will return the current directory in each loop

in (SET) specifies the directory set to loop through

Specifying "in (.)" tells for to loop through all directories

The code inside your for loop then checks each directory to see if it's empty*:

```<code>  dir /ad /b "%%~fA" 2>nul | findstr "^" >nul || echo %%~fA
</code>```

dir /ad /b "PATH" gets a list of subdirectories in the specified path*

"%%~fA" expands the current directory name to its full path

2>nul hides any dir errors by redirecting STDERR to nul

| pipes the list of subdirectories found by dir into findstr

findstr "^" then checks for a non-empty list of subdirectories

>nul hides the findstr results by redirecting all output to nul

|| runs a command if the previous command failed (no findstr results)

echo %%~fA returns the directory name if no sub-directories were found*

*Please Note: as mentioned by LotPings, the code you provided will produce different results than in the example you linked to. dir /a /b lists all files and directories while dir /ad /b lists directories only. This means that your script will list all directories not containing a subdirectory (but that may still contain files). If this was the expected behavior, please disregard this note.

Edit: further broke down the above list of commands as suggested by Ben Voigt.

ContentLicense: CC BY-SA 4.0

Body:
Batch files in Windows can be confusing at the best of times. How does

  findstr "^"

equate to finding an empty folder, when ^ means the start of the line?

for /d /r %1 %%A in (.) do (
  dir /ad /b "%%~fA" 2>nul | findstr "^" >nul || echo %%~fA
)

taken from dbenham's answer

Unless I'm reading this wrong and it's

dir /ad /b "%%~fA" 2>nul

that finds empty folders.

Body:
This script will get a list of directories (and their subdirectories), loop through each directory to check for subdirectories, then list only the directory names that did not contain a subdirectory. The original script in the link provided works similarly except that it will only list completely empty directories (not containing subdirectories or files). Here is a breakdown of each section of code:

The for /d in your example is getting a recursive list of directories:

for /d /r %1 %%A in (.) do ( )

for /d loops through the specified set of directories

for /d /r tells the for loop to recurse into subdirectories

%1 is an optional file path specified from the command-line

%%A will return the current directory in each loop

in (SET) specifies the directory set to loop through

Specifying "in (.)" tells for to loop through all directories

The code inside your for loop then checks each directory to see if it's empty*:

  dir /ad /b "%%~fA" 2>nul | findstr "^" >nul || echo %%~fA

dir /ad /b "PATH" gets a list of subdirectories in the specified path*

"%%~fA" expands the current directory name to its full path

2>nul hides any dir errors by redirecting STDERR to nul

| pipes the list of subdirectories found by dir into findstr

findstr "^" then checks for a non-empty list of subdirectories

>nul hides the findstr results by redirecting all output to nul

|| runs a command if the previous command failed (no findstr results)

echo %%~fA returns the directory name if no sub-directories were found*

*Please Note: as mentioned by LotPings, the code you provided will produce different results than in the example you linked to. dir /a /b lists all files and directories while dir /ad /b lists directories only. This means that your script will list all directories not containing a subdirectory (but that may still contain files). If this was the expected behavior, please disregard this note.

Edit: further broke down the above list of commands as suggested by Ben Voigt.


问:
Docker. Error: Cannot start container: port has already been allocated
I am working with Docker and when I first created a container, I managed to work with it properly. Today I rebooted my computer and set myself to work with the Docker container again.

I tried to "activate" the container like this:

```<code>docker run -it --rm -p 5000:5000 -v `pwd`:/app myproject
</code>```

And this is the message that I get back:

```<code>WARNING: Local (127.0.0.1) DNS resolver found in resolv.conf and containers can't use it. Using default external servers : [8.8.8.8 8.8.4.4]
2014/07/28 12:34:32 Error: Cannot start container a152dd9040ab4be0f20ace96ba4a9b0a3c50fa89034512c2b9fcb986db912027: port has already been allocated
</code>```

So I tried to find out what process is listening on port 5000 and kill it. Just like this:

```<code># netstat -tulpn | grep :5000
tcp6       0      0 :::5000                 :::*                    LISTEN    3992/docker.io
# kill -9 3992
</code>```

I also tried restarting the docker service, like this:

```<code>sudo service docker.io restart
</code>```

But none of these things have worked out. I am still getting the same error message when trying to activate my container:

```<code># docker run -it --rm -p 5000:5000 -v `pwd`:/app myproj
WARNING: Local (127.0.0.1) DNS resolver found in resolv.conf and containers can't use it. Using default external servers : [8.8.8.8 8.8.4.4]
2014/07/28 12:34:14 Error: Cannot start container b28ac5c4a425068ac1827bade6dd89e95be32f3e94c982300eba006822971ab1: port has already been allocated
</code>```

Googling for a solution I found that this seems to be a known issue, but maybe you can help me find a way out of this issue.

UPDATE:

Just as requested by @Marcus Hughes , this is the output of docker ps:

```<code>$ sudo docker ps
CONTAINER ID        IMAGE               COMMAND                CREATED             STATUS              PORTS                    NAMES
3fdfc9ecf30f        7e0ca0814a33        /bin/sh -c composer    4 hours ago         Up About an hour    0.0.0.0:5000->5000/tcp   naughty_galileo
</code>```

And if I do docker ps -a, this is what I get:

```<code>$ sudo docker ps -a
CONTAINER ID        IMAGE                        COMMAND                CREATED              STATUS              PORTS                    NAMES
69400a0e21f5        stenocaption-server:latest   /bin/sh -c composer    About a minute ago   Exit 0                                       agitated_feynman
a3c352d48ab5        stenocaption-server:latest   /bin/sh -c composer    6 minutes ago        Exit 0                                       grave_shockley
4c3c823bda55        stenocaption-server:latest   /bin/sh -c composer    2 hours ago          Exit 0                                       condescending_heisenberg
b9083a0af2cd        7e0ca0814a33                 /bin/sh -c composer    2 hours ago          Exit 0                                       kickass_lumiere
0d51ea8c4377        7e0ca0814a33                 /bin/sh -c composer    2 hours ago          Exit 0                                       sick_ritchie
a152dd9040ab        7e0ca0814a33                 /bin/sh -c composer    2 hours ago          Exit 0                                       happy_thompson
b28ac5c4a425        7e0ca0814a33                 /bin/sh -c composer    2 hours ago          Exit 0                                       cocky_franklin
d449f40487ca        7e0ca0814a33                 /bin/sh -c composer    2 hours ago          Exit 0                                       evil_torvalds
b485da98ca6d        7e0ca0814a33                 /bin/sh -c composer    2 hours ago          Exit 0                                       tender_nobel6
8b73b154c8aa        7e0ca0814a33                 /bin/sh -c composer    2 hours ago          Exit 0                                       dreamy_ptolemy
10d327c46d95        7e0ca0814a33                 /bin/sh -c composer    2 hours ago          Exit 0                                       boring_morse
a3397c0c4dfb        7e0ca0814a33                 /bin/sh -c composer    2 hours ago          Exit 0                                       thirsty_engelbart
e6440629fac1        7e0ca0814a33                 /bin/sh -c composer    3 hours ago          Exit 0                                       distracted_bohr
cb718204384e        7e0ca0814a33                 /bin/sh -c composer    3 hours ago          Exit 0                                       nostalgic_mclean
ca62ccc30227        7e0ca0814a33                 /bin/sh -c composer    3 hours ago          Exit 0                                       evil_heisenberg
83ed0727883f        7e0ca0814a33                 /bin/sh -c composer    3 hours ago          Exit 0                                       nostalgic_curie
1100e926ef29        7e0ca0814a33                 /bin/sh -c composer    3 hours ago          Exit 0                                       tender_nobel
1ed76e31d8f5        7e0ca0814a33                 /bin/sh -c composer    3 hours ago          Exit 0                                       grave_hawking
ad429a4ab116        7e0ca0814a33                 /bin/sh -c composer    3 hours ago          Exit 0                                       condescending_nobel
5790e0e9c21f        7e0ca0814a33                 /bin/sh -c composer    4 hours ago          Exit 0                                       boring_curie
3fdfc9ecf30f        7e0ca0814a33                 /bin/sh -c composer    4 hours ago          Up About an hour    0.0.0.0:5000->5000/tcp   naughty_galileo
7372b8327065        b0d5a13e5ea7                 /bin/sh -c apt-get-i   40 hours ago         Exit 127                                     high_torvalds
d4482ca96df9        10aac624035d                 /bin/sh -c apt-get i   40 hours ago         Exit 0                                       sad_pare
0ae7489bd53e        6edd40908159                 /bin/sh -c apt-get i   41 hours ago         Exit 0                                       dreamy_davinci
13c1a8670908        ubuntu:14.04                 /bin/sh -c apt-get u   41 hours ago         Exit 0                                       loving_babbage
18e20ff7f4ec        ubuntu:14.04                 /bin/sh -c apt-get u   41 hours ago         Exit 1                                       stupefied_poincare
0965776b2ee9        ubuntu:14.04                 /bin/sh -c apt-get u   41 hours ago         Exit 1                                       goofy_davinci
aa3d871f6d1c        ubuntu:14.04                 /bin/sh -c apt-get u   41 hours ago         Exit 1                                       insane_pasteur
cb266936771d        ubuntu:14.04                 /bin/sh -c apt-get u   41 hours ago         Exit 1                                       distracted_turing
10d25a9c965b        ubuntu:14.04                 /bin/sh -c apt-get u   41 hours ago         Exit 1                                       kickass_ptolemy
729afe65b3f5        ubuntu:14.04                 /bin/sh -c apt-get u   42 hours ago         Exit 1                                       dreamy_tesla
a53c5707e667        ubuntu:14.04                 /bin/sh -c apt-get u   42 hours ago         Exit 1                                       ecstatic_bohr
ec97aaae1bda        ubuntu:14.04                 /bin/sh -c apt-get u   42 hours ago         Exit 1                                       romantic_bell
13fe8539439c        ubuntu:14.04                 /bin/sh -c apt-get u   42 hours ago         Exit 1                                       romantic_shockley
deaff10c2ed3        ubuntu:14.04                 /bin/sh -c apt-get u   42 hours ago         Exit 1                                       trusting_shockley
c49494c24595        ubuntu:14.04                 /bin/sh -c apt-get u   42 hours ago         Exit 1                                       loving_bell
3972c67fbd92        ubuntu:14.04                 /bin/sh -c apt-get u   42 hours ago         Exit 1                                       stupefied_euclid
</code>```

答:
For Windows users, quoting from the Docker documentation:

On Windows systems, CTRL+C does not stop the container. So, first type CTRL+C to get the prompt back (or open another shell), then type docker container ls to list the running containers, followed by docker container stop <Container NAME or ID> to stop the container. Otherwise, you get an error response from the daemon when you try to re-run the container.

Additionally, this command stops all running containers:

```<code>docker stop $(docker ps -q)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am working with Docker and when I first created a container, I managed to work with it properly. Today I rebooted my computer and set myself to work with the Docker container again.

I tried to "activate" the container like this:

docker run -it --rm -p 5000:5000 -v `pwd`:/app myproject

And this is the message that I get back:

WARNING: Local (127.0.0.1) DNS resolver found in resolv.conf and containers can't use it. Using default external servers : [8.8.8.8 8.8.4.4]
2014/07/28 12:34:32 Error: Cannot start container a152dd9040ab4be0f20ace96ba4a9b0a3c50fa89034512c2b9fcb986db912027: port has already been allocated

So I tried to find out what process is listening on port 5000 and kill it. Just like this:

# netstat -tulpn | grep :5000
tcp6       0      0 :::5000                 :::*                    LISTEN    3992/docker.io
# kill -9 3992

I also tried restarting the docker service, like this:

sudo service docker.io restart

But none of these things have worked out. I am still getting the same error message when trying to activate my container:

# docker run -it --rm -p 5000:5000 -v `pwd`:/app myproj
WARNING: Local (127.0.0.1) DNS resolver found in resolv.conf and containers can't use it. Using default external servers : [8.8.8.8 8.8.4.4]
2014/07/28 12:34:14 Error: Cannot start container b28ac5c4a425068ac1827bade6dd89e95be32f3e94c982300eba006822971ab1: port has already been allocated

Googling for a solution I found that this seems to be a known issue, but maybe you can help me find a way out of this issue.

UPDATE:

Just as requested by @Marcus Hughes , this is the output of docker ps:

$ sudo docker ps
CONTAINER ID        IMAGE               COMMAND                CREATED             STATUS              PORTS                    NAMES
3fdfc9ecf30f        7e0ca0814a33        /bin/sh -c composer    4 hours ago         Up About an hour    0.0.0.0:5000->5000/tcp   naughty_galileo

And if I do docker ps -a, this is what I get:

$ sudo docker ps -a
CONTAINER ID        IMAGE                        COMMAND                CREATED              STATUS              PORTS                    NAMES
69400a0e21f5        stenocaption-server:latest   /bin/sh -c composer    About a minute ago   Exit 0                                       agitated_feynman
a3c352d48ab5        stenocaption-server:latest   /bin/sh -c composer    6 minutes ago        Exit 0                                       grave_shockley
4c3c823bda55        stenocaption-server:latest   /bin/sh -c composer    2 hours ago          Exit 0                                       condescending_heisenberg
b9083a0af2cd        7e0ca0814a33                 /bin/sh -c composer    2 hours ago          Exit 0                                       kickass_lumiere
0d51ea8c4377        7e0ca0814a33                 /bin/sh -c composer    2 hours ago          Exit 0                                       sick_ritchie
a152dd9040ab        7e0ca0814a33                 /bin/sh -c composer    2 hours ago          Exit 0                                       happy_thompson
b28ac5c4a425        7e0ca0814a33                 /bin/sh -c composer    2 hours ago          Exit 0                                       cocky_franklin
d449f40487ca        7e0ca0814a33                 /bin/sh -c composer    2 hours ago          Exit 0                                       evil_torvalds
b485da98ca6d        7e0ca0814a33                 /bin/sh -c composer    2 hours ago          Exit 0                                       tender_nobel6
8b73b154c8aa        7e0ca0814a33                 /bin/sh -c composer    2 hours ago          Exit 0                                       dreamy_ptolemy
10d327c46d95        7e0ca0814a33                 /bin/sh -c composer    2 hours ago          Exit 0                                       boring_morse
a3397c0c4dfb        7e0ca0814a33                 /bin/sh -c composer    2 hours ago          Exit 0                                       thirsty_engelbart
e6440629fac1        7e0ca0814a33                 /bin/sh -c composer    3 hours ago          Exit 0                                       distracted_bohr
cb718204384e        7e0ca0814a33                 /bin/sh -c composer    3 hours ago          Exit 0                                       nostalgic_mclean
ca62ccc30227        7e0ca0814a33                 /bin/sh -c composer    3 hours ago          Exit 0                                       evil_heisenberg
83ed0727883f        7e0ca0814a33                 /bin/sh -c composer    3 hours ago          Exit 0                                       nostalgic_curie
1100e926ef29        7e0ca0814a33                 /bin/sh -c composer    3 hours ago          Exit 0                                       tender_nobel
1ed76e31d8f5        7e0ca0814a33                 /bin/sh -c composer    3 hours ago          Exit 0                                       grave_hawking
ad429a4ab116        7e0ca0814a33                 /bin/sh -c composer    3 hours ago          Exit 0                                       condescending_nobel
5790e0e9c21f        7e0ca0814a33                 /bin/sh -c composer    4 hours ago          Exit 0                                       boring_curie
3fdfc9ecf30f        7e0ca0814a33                 /bin/sh -c composer    4 hours ago          Up About an hour    0.0.0.0:5000->5000/tcp   naughty_galileo
7372b8327065        b0d5a13e5ea7                 /bin/sh -c apt-get-i   40 hours ago         Exit 127                                     high_torvalds
d4482ca96df9        10aac624035d                 /bin/sh -c apt-get i   40 hours ago         Exit 0                                       sad_pare
0ae7489bd53e        6edd40908159                 /bin/sh -c apt-get i   41 hours ago         Exit 0                                       dreamy_davinci
13c1a8670908        ubuntu:14.04                 /bin/sh -c apt-get u   41 hours ago         Exit 0                                       loving_babbage
18e20ff7f4ec        ubuntu:14.04                 /bin/sh -c apt-get u   41 hours ago         Exit 1                                       stupefied_poincare
0965776b2ee9        ubuntu:14.04                 /bin/sh -c apt-get u   41 hours ago         Exit 1                                       goofy_davinci
aa3d871f6d1c        ubuntu:14.04                 /bin/sh -c apt-get u   41 hours ago         Exit 1                                       insane_pasteur
cb266936771d        ubuntu:14.04                 /bin/sh -c apt-get u   41 hours ago         Exit 1                                       distracted_turing
10d25a9c965b        ubuntu:14.04                 /bin/sh -c apt-get u   41 hours ago         Exit 1                                       kickass_ptolemy
729afe65b3f5        ubuntu:14.04                 /bin/sh -c apt-get u   42 hours ago         Exit 1                                       dreamy_tesla
a53c5707e667        ubuntu:14.04                 /bin/sh -c apt-get u   42 hours ago         Exit 1                                       ecstatic_bohr
ec97aaae1bda        ubuntu:14.04                 /bin/sh -c apt-get u   42 hours ago         Exit 1                                       romantic_bell
13fe8539439c        ubuntu:14.04                 /bin/sh -c apt-get u   42 hours ago         Exit 1                                       romantic_shockley
deaff10c2ed3        ubuntu:14.04                 /bin/sh -c apt-get u   42 hours ago         Exit 1                                       trusting_shockley
c49494c24595        ubuntu:14.04                 /bin/sh -c apt-get u   42 hours ago         Exit 1                                       loving_bell
3972c67fbd92        ubuntu:14.04                 /bin/sh -c apt-get u   42 hours ago         Exit 1                                       stupefied_euclid

Body:
For Windows users, quoting from the Docker documentation:

On Windows systems, CTRL+C does not stop the container. So, first type CTRL+C to get the prompt back (or open another shell), then type docker container ls to list the running containers, followed by docker container stop <Container NAME or ID> to stop the container. Otherwise, you get an error response from the daemon when you try to re-run the container.

Additionally, this command stops all running containers:

docker stop $(docker ps -q)


问:
Canvas HTML - Smoothness between lineTo and Bezier curve
Maybe this is more a math question but lets see:

I'm using HTML5 Canvas to draw a line chart.
The chart is basically Position X Time.
Each line represents a vehicle in a position (Y) in a given time (X).
I only have information about when a vehicle passed through determined points in the road. So if a vehicle stops between two points I don't have the information that it actually stoped, but when it passes through the next point I will be able to draw a line that will be almost horizontal, because the average speed, i.e. the line slope, will be really small.

In these scenarios we have defined that if a vehicle moved below 10Km/h I should consider that it made a stop and should draw a horizontal smooth line.

Basically I have to transform this:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.lineWidth = 5;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';

ctx.beginPath();
ctx.moveTo(0, 30);
ctx.lineTo(20, 50);
ctx.lineTo(220, 70);
ctx.lineTo(240, 110);
ctx.stroke();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas></code>```

Into this:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.lineWidth = 5;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';

ctx.beginPath();
ctx.moveTo(0, 30);
ctx.lineTo(20, 50);

ctx.bezierCurveTo(
  50, 70,
  210, 50,
  220, 70
)

ctx.lineTo(240, 110);
ctx.stroke();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas></code>```

The problem is: how do I chose good values for the bezier points?
In the above example I have done it experimentally. I cannot find a way to programatically pick good point values so my lines don't look bad like these:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.lineWidth = 5;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';

ctx.beginPath();
ctx.moveTo(0, 30);
ctx.lineTo(20, 50);

ctx.bezierCurveTo(
  20, 70,
  180, 50,
  220, 70
)

ctx.lineTo(240, 110);
ctx.stroke();

ctx.beginPath();
ctx.moveTo(0, 80);
ctx.lineTo(20, 100);

ctx.bezierCurveTo(
  20, 120,
  220, 100,
  220, 120
)

ctx.lineTo(280, 150);
ctx.stroke();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="myCanvas" width="300" height="170" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas></code>```

I'm looking for a computationally simple solution because this is redrawn everytime with a lot of lines, so I don't want this melting down my performance.

Thanks for any tips!

答:
I found a good solution for my problem: Using line interpolation.

Having the following segments and imagine I want to smooth things between B and C, how can I choose some bezier points that would garantee a smooth curve instead of broken one?

First I interpolate the segment AB and find the point B', which is the point the line AB would touch the Y coordinate for C. Then I use the same process to find C':

The points B' and C' make good points for the bezier in order to smooth things up to a horizontal line:

This is also being computationally simple enough since finding the a line equation is rather simple.

Body:
Maybe this is more a math question but lets see:

I'm using HTML5 Canvas to draw a line chart.
The chart is basically Position X Time.
Each line represents a vehicle in a position (Y) in a given time (X).
I only have information about when a vehicle passed through determined points in the road. So if a vehicle stops between two points I don't have the information that it actually stoped, but when it passes through the next point I will be able to draw a line that will be almost horizontal, because the average speed, i.e. the line slope, will be really small.

In these scenarios we have defined that if a vehicle moved below 10Km/h I should consider that it made a stop and should draw a horizontal smooth line.

Basically I have to transform this:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.lineWidth = 5;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';

ctx.beginPath();
ctx.moveTo(0, 30);
ctx.lineTo(20, 50);
ctx.lineTo(220, 70);
ctx.lineTo(240, 110);
ctx.stroke();

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

Into this:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.lineWidth = 5;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';

ctx.beginPath();
ctx.moveTo(0, 30);
ctx.lineTo(20, 50);

ctx.bezierCurveTo(
  50, 70,
  210, 50,
  220, 70
)

ctx.lineTo(240, 110);
ctx.stroke();

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

The problem is: how do I chose good values for the bezier points?
In the above example I have done it experimentally. I cannot find a way to programatically pick good point values so my lines don't look bad like these:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.lineWidth = 5;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';

ctx.beginPath();
ctx.moveTo(0, 30);
ctx.lineTo(20, 50);

ctx.bezierCurveTo(
  20, 70,
  180, 50,
  220, 70
)

ctx.lineTo(240, 110);
ctx.stroke();

ctx.beginPath();
ctx.moveTo(0, 80);
ctx.lineTo(20, 100);

ctx.bezierCurveTo(
  20, 120,
  220, 100,
  220, 120
)

ctx.lineTo(280, 150);
ctx.stroke();

<canvas id="myCanvas" width="300" height="170" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

I'm looking for a computationally simple solution because this is redrawn everytime with a lot of lines, so I don't want this melting down my performance.

Thanks for any tips!


问:
How to access individual strings in Python?
I am trying to access two strings which are coupled together. I do not know how to access them individually, as subscription does not work.

I tried printing the variable b in the following example, and I get two strings. However using b[0] does not give me the first string separately.

```<code>import numpy as np
import json
import requests
from datetime import datetime

resp = requests.get("https://api.mfapi.in/mf/130503")
data = resp.json()

x = data['data']

for i in range(1):
    for a,b in x[i].items():
        print(b)
</code>```

答:
Your variable x is a list of dictionaries

Depending on if you want to access date or nav in the dictionaries, in your for loop you can just use x[i]['date'] or x[i]['nav']

Body:
I am trying to access two strings which are coupled together. I do not know how to access them individually, as subscription does not work.

I tried printing the variable b in the following example, and I get two strings. However using b[0] does not give me the first string separately.

import numpy as np
import json
import requests
from datetime import datetime

resp = requests.get("https://api.mfapi.in/mf/130503")
data = resp.json()

x = data['data']

for i in range(1):
    for a,b in x[i].items():
        print(b)


问:
Minimalist Programming Tools
What tools go well with or help minimalist programming? Examples would be libraries with tight, clean interface and very small size in it's genre.

Techniques, functions or concepts that result in smaller and/or more efficient apps would be great. If you know of any other relevant tools this would help as well.

答: See colorFORTH - minimal and strange ... best of both worlds :)

ContentLicense: CC BY-SA 2.5

Title: Minimalist Programming Tools


问:
Angular bootstrap Modal component not working?
I am trying to add Modals from bootstrap for angular, but it seems like it's not working : https://ng-bootstrap.github.io/#/components/modal/examples

I copy/pasted the last modal 'Global configuration of modals'

Of course I imported it and placed it in my declarations variables + in the constructor.

答: Adding NgbModule.forRoot() in my imports solves the problem</p>


问:
Jupyter ImportError: cannot import name 'create_prompt_application' ubuntu 18.04
I have installed jupypter on Ubuntu 18.04. when I try to open .ipynb file it says trying to connect to server and fails eventaully.
When I looked at the console I saw the following error :

ImportError: cannot import name 'create_prompt_application'
 as follows

```<code>[I 14:37:41.311 NotebookApp] KernelRestarter: restarting kernel (4/5), new random ports
Traceback (most recent call last):
  File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py", line 15, in <module>
    from ipykernel import kernelapp as app
  File "/usr/local/lib/python3.6/dist-packages/ipykernel/__init__.py", line 2, in <module>
    from .connect import *
  File "/usr/local/lib/python3.6/dist-packages/ipykernel/connect.py", line 13, in <module>
    from IPython.core.profiledir import ProfileDir
  File "/usr/lib/python3/dist-packages/IPython/__init__.py", line 49, in <module>
    from .terminal.embed import embed
  File "/usr/lib/python3/dist-packages/IPython/terminal/embed.py", line 18, in <module>
    from IPython.terminal.interactiveshell import TerminalInteractiveShell
  File "/usr/lib/python3/dist-packages/IPython/terminal/interactiveshell.py", line 20, in <module>
    from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop, create_prompt_layout, create_output
ImportError: cannot import name 'create_prompt_application'
[W 14:37:44.322 NotebookApp] KernelRestarter: restart failed
</code>```

Some posts related to IPyton are suggesting that prompt-toolkit should be downgraded. I run deptree to get dependency tree as follows, which shows that prompt-toolkit 2.0.9 is installed and required version for jupyter-console should be between 2.0.0 and 2.0.1

```<code>- jupyter-console [required: Any, installed: 6.0.0]
    - ipykernel [required: Any, installed: 5.1.0]
      - ipython [required: >=5.0.0, installed: 5.5.0]
        - pexpect [required: Any, installed: 4.2.1]
      - jupyter-client [required: Any, installed: 5.2.4]
        - jupyter-core [required: Any, installed: 4.4.0]
          - traitlets [required: Any, installed: 4.3.2]
        - python-dateutil [required: >=2.1, installed: 2.6.1]
        - pyzmq [required: >=13, installed: 18.0.1]
        - tornado [required: >=4.1, installed: 6.0.1]
        - traitlets [required: Any, installed: 4.3.2]
      - tornado [required: >=4.2, installed: 6.0.1]
      - traitlets [required: >=4.1.0, installed: 4.3.2]
    - ipython [required: Any, installed: 5.5.0]
      - pexpect [required: Any, installed: 4.2.1]
    - jupyter-client [required: Any, installed: 5.2.4]
      - jupyter-core [required: Any, installed: 4.4.0]
        - traitlets [required: Any, installed: 4.3.2]
      - python-dateutil [required: >=2.1, installed: 2.6.1]
      - pyzmq [required: >=13, installed: 18.0.1]
      - tornado [required: >=4.1, installed: 6.0.1]
      - traitlets [required: Any, installed: 4.3.2]
    - prompt-toolkit [required: >=2.0.0,<2.1.0, installed: 2.0.9]
</code>```

Any thoughts on what could be wrong and what should I do?
Thanks

答:
sudo pip3 uninstall ipython

sudo pip3 install ipython

the error solved for me Try it out.

sudo pip3 install 'prompt-toolkit<2.1.0,>=2.0.0' --force-reinstall

Body:
I have installed jupypter on Ubuntu 18.04. when I try to open .ipynb file it says trying to connect to server and fails eventaully.
When I looked at the console I saw the following error :

ImportError: cannot import name 'create_prompt_application'
 as follows

[I 14:37:41.311 NotebookApp] KernelRestarter: restarting kernel (4/5), new random ports
Traceback (most recent call last):
  File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py", line 15, in <module>
    from ipykernel import kernelapp as app
  File "/usr/local/lib/python3.6/dist-packages/ipykernel/__init__.py", line 2, in <module>
    from .connect import *
  File "/usr/local/lib/python3.6/dist-packages/ipykernel/connect.py", line 13, in <module>
    from IPython.core.profiledir import ProfileDir
  File "/usr/lib/python3/dist-packages/IPython/__init__.py", line 49, in <module>
    from .terminal.embed import embed
  File "/usr/lib/python3/dist-packages/IPython/terminal/embed.py", line 18, in <module>
    from IPython.terminal.interactiveshell import TerminalInteractiveShell
  File "/usr/lib/python3/dist-packages/IPython/terminal/interactiveshell.py", line 20, in <module>
    from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop, create_prompt_layout, create_output
ImportError: cannot import name 'create_prompt_application'
[W 14:37:44.322 NotebookApp] KernelRestarter: restart failed

Some posts related to IPyton are suggesting that prompt-toolkit should be downgraded. I run deptree to get dependency tree as follows, which shows that prompt-toolkit 2.0.9 is installed and required version for jupyter-console should be between 2.0.0 and 2.0.1

- jupyter-console [required: Any, installed: 6.0.0]
    - ipykernel [required: Any, installed: 5.1.0]
      - ipython [required: >=5.0.0, installed: 5.5.0]
        - pexpect [required: Any, installed: 4.2.1]
      - jupyter-client [required: Any, installed: 5.2.4]
        - jupyter-core [required: Any, installed: 4.4.0]
          - traitlets [required: Any, installed: 4.3.2]
        - python-dateutil [required: >=2.1, installed: 2.6.1]
        - pyzmq [required: >=13, installed: 18.0.1]
        - tornado [required: >=4.1, installed: 6.0.1]
        - traitlets [required: Any, installed: 4.3.2]
      - tornado [required: >=4.2, installed: 6.0.1]
      - traitlets [required: >=4.1.0, installed: 4.3.2]
    - ipython [required: Any, installed: 5.5.0]
      - pexpect [required: Any, installed: 4.2.1]
    - jupyter-client [required: Any, installed: 5.2.4]
      - jupyter-core [required: Any, installed: 4.4.0]
        - traitlets [required: Any, installed: 4.3.2]
      - python-dateutil [required: >=2.1, installed: 2.6.1]
      - pyzmq [required: >=13, installed: 18.0.1]
      - tornado [required: >=4.1, installed: 6.0.1]
      - traitlets [required: Any, installed: 4.3.2]
    - prompt-toolkit [required: >=2.0.0,<2.1.0, installed: 2.0.9]

Any thoughts on what could be wrong and what should I do?
Thanks


问:
$push an object to a nested array
I am looking for a way to $push an object to a nested array which the route keys come from variables.

```<code>{
    "_id": {
        "$oid": "5ce9964cd0e7df57eb0c8a99"
    },
    "history": {
        "2019": {
            "jan": {
                "1": [],
                "2": [],
                "3": []
            },
            "feb": {
                "1": [],
                "2": [],
                "3": []
            }
        }
    }
}
</code>```

def add_tx():
    body = request.get_json()
    users = mongo.db.date
    users.find_one_and_update({
        "username": session['username']
    }, {
        '$push': {
            'history'[str(body['year'])][months[body['month']]][str(
                body['day'])]: {body['title']: body['value']}
        }
    })
```

So the route in the "history" object comes from the body:

body['year'], body['month'], body['day']

and I want to append to the array an object with:

{body['title']: body['value']}

答:
got it, for someone else that could be looking for the answer;

the trick is to set a variable with the wanted path using the variables and the wanted value then push only that final variable.

    # Setting the variable with the complete path in the DB using the variables from the POST BODY
    query = {}
    query['history.' + str(body['year']) + "." + months[body['month']] +
          "." + str(body['day'])] = {body['title']: float(body['value'])}
    # Pushing the created variable to the DB
    users.find_one_and_update({
        "username": session['username']
    }, {
        '$push': query
    })

```

Title: $push an object to a nested array

Body:
I am looking for a way to $push an object to a nested array which the route keys come from variables.

{
    "_id": {
        "$oid": "5ce9964cd0e7df57eb0c8a99"
    },
    "history": {
        "2019": {
            "jan": {
                "1": [],
                "2": [],
                "3": []
            },
            "feb": {
                "1": [],
                "2": [],
                "3": []
            }
        }
    }
}

def add_tx():
    body = request.get_json()
    users = mongo.db.date
    users.find_one_and_update({
        "username": session['username']
    }, {
        '$push': {
            'history'[str(body['year'])][months[body['month']]][str(
                body['day'])]: {body['title']: body['value']}
        }
    })

So the route in the "history" object comes from the body:

body['year'], body['month'], body['day']

and I want to append to the array an object with:

{body['title']: body['value']}


问:
Jquery hide and show in one line
I need to build function that show or hide element following a boolean flag.
flag==false: hide
flag==true: show
the function should contain only single line that will starts with: $element.

I need to complete:

```<code>function willItShow($element, flag){
    $element
}
</code>```

please help me with it.
thank you all!!

答:
Add a class to the element you want to show hide.

On button click use toggleclass to show or hide

Description: Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument.

version added: 1.0.toggleClass( className )

$("#action").click(willItShow)

function willItShow(e) {
  $("span").toggleClass("show hide")
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide {
  display: none
}

.show {
  display: block
}</code>```

Shown

<input type="button" id='action' value="Click ME">```

Title: Jquery hide and show in one line

Body:
I need to build function that show or hide element following a boolean flag.
flag==false: hide
flag==true: show
the function should contain only single line that will starts with: $element.

I need to complete:

function willItShow($element, flag){
    $element
}

please help me with it.
thank you all!!

Body:
Add a class to the element you want to show hide.

On button click use toggleclass to show or hide

Description: Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument.

version added: 1.0.toggleClass( className )

$("#action").click(willItShow)

function willItShow(e) {
  $("span").toggleClass("show hide")
}

.hide {
  display: none
}

.show {
  display: block
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class='show'>Shown</span>

<input type="button" id='action' value="Click ME">


问:
How can you open a directory/entire folder in Visual Studio Code using command line?
Is there a way to open a folder/directory from git bash/shell emulator? I know you can use 'start' then the file name to open one file, but is there a way to open the entire folder?

Edit: If you're trying to open an entire folder with Visual Studio Code (which is what I was trying to do), follow these steps:

Navigate inside the folder in git bash.

Then run the command: code . --new-window

Your project with all files in that folder should open in a new Visual Studio Code window.

答:
I use this alias in my ~/.bashrc to mirror the open functionality I miss from OSX:

```<code>function open() {
    # if argument != '.', open full-path to argument
    [ "$@" = '.' ] && dir_path="." || dir_path=$(realpath "$@")
    start $dir_path
}
</code>```

You can use it to open relative paths to directories: open /relativeDirectory

Here's the same code in an easier to read manner:

```<code>function open() {
    arg="$@"
    dir_path=$(realpath $arg)
    if [ "$arg" = '.' ]; then
      dir_path="."
    fi
    start $dir_path
}
</code>```

Body:
I use this alias in my ~/.bashrc to mirror the open functionality I miss from OSX:

function open() {
    # if argument != '.', open full-path to argument
    [ "$@" = '.' ] && dir_path="." || dir_path=$(realpath "$@")
    start $dir_path
}

You can use it to open relative paths to directories: open /relativeDirectory

Here's the same code in an easier to read manner:

function open() {
    arg="$@"
    dir_path=$(realpath $arg)
    if [ "$arg" = '.' ]; then
      dir_path="."
    fi
    start $dir_path
}


问:
How to make a webpage unresponsive?
I'm looking to make my webpage unresponsive in the sense to where upon a window resize, rather than elements changing properties & using media queries, I want the entire page to just scale down proportionally and all elements keep their ratio. How is this done? with pure css or with the aid of JS?</p>

答: I found a solution on this page. I'm not sure if it will work exactly the same but it looks similar. There is a link to the demo on the site.</p>

Title: How to make a webpage unresponsive?


问:
Exporting data to XML - unserialize array fails due to error
I'd like to export the woocommerce array "redq_day_ranges_cost" into XML format with WP All Export. If I try to unserialize the array I run into this PHP Error: unserialize(): Error at offset...

I tried the things mentioned here: How to repair a serialized string which has been corrupted by an incorrect byte count length?

The problem is, that WP All Export already fails on saving an export template due to that error, so I feel a little lost here.

This is the data to be exported:

```<code>a:7:{
i:0;a:4
{s:8:"min_days";s:1:"1";s:8:"max_days";s:1:"1";s:10:"range_cost";s:2:"340";s:15:"cost_applicable";s:5:"fixed";}
i:1;a:4:
{s:8:"min_days";s:1:"2";s:8:"max_days";s:1:"2";s:10:"range_cost";s:2:"450";s:15:"cost_applicable";s:5:"fixed";}
i:2;a:4:
{s:8:"min_days";s:1:"3";s:8:"max_days";s:1:"3";s:10:"range_cost";s:2:"570";s:15:"cost_applicable";s:5:"fixed";}}
</code>```

the plan is to export it something like

```<code><min_days>1</min_days>
<max_days>1</max_days>
<range_cost>340</range_cost>
<cost_applicable>fixed</cost_applicable>
</code>```

So far, if I call unserialize in the function editor the result is the named error. If I call it inline within the XML Editor it results in 3 rows of

<redq_day_ranges_cost>Array</redq_day_ranges_cost>

答:
You have two issues with your data, the first is that it has newlines in it which need to be removed, and the second is that some of your string variables have mismatched lengths. The former can be corrected with a simple str_replace; the latter can be corrected using the code in this answer. This code will work to convert your string back to an array:

```<code>$data = str_replace("\n", "", $data);
$fixed_data = preg_replace_callback ( '!s:(\d+):"(.*?)";!', function($match) {
    return ($match[1] == strlen($match[2])) ? $match[0] : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
}, $data );

print_r(unserialize($fixed_data));
</code>```

Output:

```<code>Array (
  [0] => Array (
    [min_days] => 1
    [max_days] => 1
    [range_cost] => 340
    [cost_applicable] => fixed
  )
  [1] => Array (
    [min_days] => 2
    [max_days] => 2
    [range_cost] => 450
    [cost_applicable] => fixed
  )
  [2] => Array (
    [min_days] => 3
    [max_days] => 3
    [range_cost] => 570
    [cost_applicable] => fixed
  )
)
</code>```

Demo on 3v4l.org

Body:
I'd like to export the woocommerce array "redq_day_ranges_cost" into XML format with WP All Export. If I try to unserialize the array I run into this PHP Error: unserialize(): Error at offset...

I tried the things mentioned here: How to repair a serialized string which has been corrupted by an incorrect byte count length?

The problem is, that WP All Export already fails on saving an export template due to that error, so I feel a little lost here.

This is the data to be exported:

a:7:{
i:0;a:4
{s:8:"min_days";s:1:"1";s:8:"max_days";s:1:"1";s:10:"range_cost";s:2:"340";s:15:"cost_applicable";s:5:"fixed";}
i:1;a:4:
{s:8:"min_days";s:1:"2";s:8:"max_days";s:1:"2";s:10:"range_cost";s:2:"450";s:15:"cost_applicable";s:5:"fixed";}
i:2;a:4:
{s:8:"min_days";s:1:"3";s:8:"max_days";s:1:"3";s:10:"range_cost";s:2:"570";s:15:"cost_applicable";s:5:"fixed";}}

the plan is to export it something like

<min_days>1</min_days>
<max_days>1</max_days>
<range_cost>340</range_cost>
<cost_applicable>fixed</cost_applicable>

So far, if I call unserialize in the function editor the result is the named error. If I call it inline within the XML Editor it results in 3 rows of

<redq_day_ranges_cost>Array</redq_day_ranges_cost>

Body:
You have two issues with your data, the first is that it has newlines in it which need to be removed, and the second is that some of your string variables have mismatched lengths. The former can be corrected with a simple str_replace; the latter can be corrected using the code in this answer. This code will work to convert your string back to an array:

$data = str_replace("\n", "", $data);
$fixed_data = preg_replace_callback ( '!s:(\d+):"(.*?)";!', function($match) {
    return ($match[1] == strlen($match[2])) ? $match[0] : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
}, $data );

print_r(unserialize($fixed_data));

Output:

Array (
  [0] => Array (
    [min_days] => 1
    [max_days] => 1
    [range_cost] => 340
    [cost_applicable] => fixed
  )
  [1] => Array (
    [min_days] => 2
    [max_days] => 2
    [range_cost] => 450
    [cost_applicable] => fixed
  )
  [2] => Array (
    [min_days] => 3
    [max_days] => 3
    [range_cost] => 570
    [cost_applicable] => fixed
  )
)

Demo on 3v4l.org


问:
Google Maps marker clicks do not work on iPad when using Sencha Touch
Has anyone been able to get map marker clicks working on iPad? I have tried the following, which worked nicely on Google Chrome, but not on the iPad.</p>

```<code>// Marker
var marker = new google.maps.Marker({
    position: location,
    title: 'Title',
    map: map,
    icon: '/images/marker.gif'
});

// Click listener
google.maps.event.addListener(marker, 'click', function() {

    ...

});
</code>```

答: The problem was that I was listening on "click" events when I should have been listening on "mousedown" events.</p>

Body:
Has anyone been able to get map marker clicks working on iPad? I have tried the following, which worked nicely on Google Chrome, but not on the iPad.

// Marker
var marker = new google.maps.Marker({
    position: location,
    title: 'Title',
    map: map,
    icon: '/images/marker.gif'
});

// Click listener
google.maps.event.addListener(marker, 'click', function() {

    ...

});


问:
how to create endpoints and send messages in amazon pinpoint
im trying to use boto3 to send messages with pinpoint to, but the functions for update_endpoint and send_messages keeps return me Resource not found

```<code>client = boto3.client('pinpoint', region_name="us-east-1", aws_access_key_id="xxx", aws_secret_access_key="xxx")

client.update_endpoint(ApplicationId="xxx",EndpointId='+573163781068',EndpointRequest={'Address': '+573163781068','ChannelType': 'SMS','Location': {'Country': 'CO'}})

client.send_messages(ApplicationId="xxx", MessageRequest={'Addresses': {'+573163781068': {'ChannelType': 'SMS'}}, 'MessageConfiguration': {'SMSMessage': {'Body': 'hola desde libreria', 'MessageType': 'TRANSACTIONAL'}}})
</code>```

the error that returns me is:

```<code>Traceback (most recent call last):
 File "<console>", line 1, in <module>
 File "/Applications/MAMP/htdocs/enviroment/kleanapp/lib/python3.7/site-packages/botocore/client.py", line 357, in _api_call
return self._make_api_call(operation_name, kwargs)
 File "/Applications/MAMP/htdocs/enviroment/kleanapp/lib/python3.7/site-packages/botocore/client.py", line 661, in _make_api_call
  raise error_class(parsed_response, operation_name)
botocore.errorfactory.NotFoundException: An error occurred (NotFoundException) when calling the SendMessages operation: Resource not found
</code>```

in advance thanks for your help

答:
You don't need an endpoint to send a message.  Just remove the update_endpoint line.

The NotFoundException can come from the Application ID not being found.  Please make sure you are specifying the correct application ID value in the correct region.

You can find a list of valid applications and their IDs for a particular region using the following command:

```<code>aws --region us-east-1 pinpoint get-apps
</code>```

Body:
im trying to use boto3 to send messages with pinpoint to, but the functions for update_endpoint and send_messages keeps return me Resource not found

client = boto3.client('pinpoint', region_name="us-east-1", aws_access_key_id="xxx", aws_secret_access_key="xxx")

client.update_endpoint(ApplicationId="xxx",EndpointId='+573163781068',EndpointRequest={'Address': '+573163781068','ChannelType': 'SMS','Location': {'Country': 'CO'}})

client.send_messages(ApplicationId="xxx", MessageRequest={'Addresses': {'+573163781068': {'ChannelType': 'SMS'}}, 'MessageConfiguration': {'SMSMessage': {'Body': 'hola desde libreria', 'MessageType': 'TRANSACTIONAL'}}})

the error that returns me is:

Traceback (most recent call last):
 File "<console>", line 1, in <module>
 File "/Applications/MAMP/htdocs/enviroment/kleanapp/lib/python3.7/site-packages/botocore/client.py", line 357, in _api_call
return self._make_api_call(operation_name, kwargs)
 File "/Applications/MAMP/htdocs/enviroment/kleanapp/lib/python3.7/site-packages/botocore/client.py", line 661, in _make_api_call
  raise error_class(parsed_response, operation_name)
botocore.errorfactory.NotFoundException: An error occurred (NotFoundException) when calling the SendMessages operation: Resource not found

in advance thanks for your help

Body:
You don't need an endpoint to send a message.  Just remove the update_endpoint line.

The NotFoundException can come from the Application ID not being found.  Please make sure you are specifying the correct application ID value in the correct region.

You can find a list of valid applications and their IDs for a particular region using the following command:

aws --region us-east-1 pinpoint get-apps


问:
Join two dataframes with inner join
Say I have these two datasets:

```<code>Data frame 1:
X |  date
a |  1/1/2018
a |  1/2/2018
...
b |  1/1/2018
</code>```

And df 2:

```<code>Holiday
1/1/2018
5/1/2018
</code>```

What would be a elegant way to add a new column in the first dataset, with a 1 when the date has a match with second dataset?

Thank you very much!

Title: Join two dataframes with inner join

Body:
Say I have these two datasets:

Data frame 1:
X |  date
a |  1/1/2018
a |  1/2/2018
...
b |  1/1/2018

And df 2:

Holiday
1/1/2018
5/1/2018

What would be a elegant way to add a new column in the first dataset, with a 1 when the date has a match with second dataset?

Thank you very much!

Body:
This gets there with the isin() method.

df1 = pd.DataFrame({'date': ['1/1/2018', '1/2/2018', '1/1/2018']})
df2 = pd.DataFrame({'Holiday': ['1/1/2018', '5/1/2018']})
df1
#        date
# 0  1/1/2018
# 1  1/2/2018
# 2  1/1/2018
df2
#     Holiday
# 0  1/1/2018
# 1  5/1/2018

df1['is_holiday'] = df1.date.isin(df2.Holiday).astype(int)

df1
#        date  is_holiday
# 0  1/1/2018           1
# 1  1/2/2018           0
# 2  1/1/2018           1


问:
String index out of range: -5
I have a problem when i test runQuery, the problem is String index out of range: -5 and i can't find the solution

```<code>@Test
void testRunQuery() throws FileNotFoundException, IOException, InterruptedException {
    final Answer answer = new Answer();
    String[] args = new String[5];

    final String year = "yyyy ";
    final String month = "mm ";
    final String day = "dd ";
    final String limit = "limit ";
    args[0] = year.substring(5);
    args[1] = month.substring(3);
    args[2] = day.substring(3);
    args[3] = null;
    args[4] = limit.substring(6);

    Job result = answer.runQuery(args);
    assertNotNull(result);

}
</code>```

And this is runQuery where i make the query

```<code>public  Job runQuery(final String[] args) throws InterruptedException {
    // Use standard SQL syntax for queries.
    // See: https://cloud.google.com/bigquery/sql-reference/
    // Variabili per le query
    final Integer yyyy=Integer.valueOf(args[ZERO].substring(FIVE)),
            mm=Integer.valueOf(args[ONE].substring(THREE)),
            dd=Integer.valueOf(args[TWO].substring(THREE)),
            limit=Integer.valueOf(args[FOUR].substring(SIX));

final QueryJobConfiguration queryConfig = QueryJobConfiguration.newBuilder(
    "SELECT DISTINCT owner_user_id "
    + "FROM `bigquery-public-data.stackoverflow.posts_answers` "
    + "WHERE extract(year from creation_date) = @yyyy "
    + "AND extract(month from creation_date) = @mm "
    + "AND extract(day from creation_date) = @dd "
    + "AND owner_user_id is not null "
    + "AND owner_user_id > 0 "
    + "ORDER BY owner_user_id ASC LIMIT @limit ")
    .addNamedParameter("yyyy", QueryParameterValue.int64(yyyy))
    .addNamedParameter("mm", QueryParameterValue.int64(mm))
    .addNamedParameter("dd", QueryParameterValue.int64(dd))
    .addNamedParameter("limit", QueryParameterValue.int64(limit))
    .setUseLegacySql(false).build();

        // Create a job ID so that we can safely retry.
final JobId jobId = JobId.of(UUID.randomUUID().toString());
Job queryJob=bigquery.create(JobInfo.newBuilder(queryConfig).setJobId(jobId).build());

// Wait for the query to complete.
queryJob = queryJob.waitFor();

        // Check for errors
        if (queryJob == null) {
            throw new RuntimeException("Job no longer exists");
        } else if (queryJob.getStatus().getError() != null) {
            // You can also look at queryJob.getStatus().getExecutionErrors() for all
            // errors, not just the latest one.
            throw new RuntimeException(queryJob.getStatus().getError().toString());
        }
        return queryJob;
    }
</code>```

```<code>String index out of range: -5 at the line 93 of runQuery; this is the line:
final Integer yyyy=Integer.valueOf(args[ZERO].substring(FIVE))
</code>```

答:
You first define a variable

```<code> final String year = "yyyy ";
</code>```

then you use subString

```<code>args[0] = year.substring(5);
</code>```

args[0] is now a String value of nothing( args[0] equals "")

then you are trying to subString it again.

```<code>final Integer yyyy=Integer.valueOf(args[ZERO].substring(FIVE)),
</code>```

this won't work because args[0] is an empty String.

You should only use substring once, either inside the function or before calling the function.

Title: String index out of range: -5

Body:
I have a problem when i test runQuery, the problem is String index out of range: -5 and i can't find the solution

@Test
void testRunQuery() throws FileNotFoundException, IOException, InterruptedException {
    final Answer answer = new Answer();
    String[] args = new String[5];

    final String year = "yyyy ";
    final String month = "mm ";
    final String day = "dd ";
    final String limit = "limit ";
    args[0] = year.substring(5);
    args[1] = month.substring(3);
    args[2] = day.substring(3);
    args[3] = null;
    args[4] = limit.substring(6);

    Job result = answer.runQuery(args);
    assertNotNull(result);

}

And this is runQuery where i make the query

public  Job runQuery(final String[] args) throws InterruptedException {
    // Use standard SQL syntax for queries.
    // See: https://cloud.google.com/bigquery/sql-reference/
    // Variabili per le query
    final Integer yyyy=Integer.valueOf(args[ZERO].substring(FIVE)),
            mm=Integer.valueOf(args[ONE].substring(THREE)),
            dd=Integer.valueOf(args[TWO].substring(THREE)),
            limit=Integer.valueOf(args[FOUR].substring(SIX));

final QueryJobConfiguration queryConfig = QueryJobConfiguration.newBuilder(
    "SELECT DISTINCT owner_user_id "
    + "FROM `bigquery-public-data.stackoverflow.posts_answers` "
    + "WHERE extract(year from creation_date) = @yyyy "
    + "AND extract(month from creation_date) = @mm "
    + "AND extract(day from creation_date) = @dd "
    + "AND owner_user_id is not null "
    + "AND owner_user_id > 0 "
    + "ORDER BY owner_user_id ASC LIMIT @limit ")
    .addNamedParameter("yyyy", QueryParameterValue.int64(yyyy))
    .addNamedParameter("mm", QueryParameterValue.int64(mm))
    .addNamedParameter("dd", QueryParameterValue.int64(dd))
    .addNamedParameter("limit", QueryParameterValue.int64(limit))
    .setUseLegacySql(false).build();

        // Create a job ID so that we can safely retry.
final JobId jobId = JobId.of(UUID.randomUUID().toString());
Job queryJob=bigquery.create(JobInfo.newBuilder(queryConfig).setJobId(jobId).build());

// Wait for the query to complete.
queryJob = queryJob.waitFor();

        // Check for errors
        if (queryJob == null) {
            throw new RuntimeException("Job no longer exists");
        } else if (queryJob.getStatus().getError() != null) {
            // You can also look at queryJob.getStatus().getExecutionErrors() for all
            // errors, not just the latest one.
            throw new RuntimeException(queryJob.getStatus().getError().toString());
        }
        return queryJob;
    }

String index out of range: -5 at the line 93 of runQuery; this is the line:
final Integer yyyy=Integer.valueOf(args[ZERO].substring(FIVE))

Body:
You first define a variable

 final String year = "yyyy ";

then you use subString

args[0] = year.substring(5);

args[0] is now a String value of nothing( args[0] equals "")

then you are trying to subString it again.

final Integer yyyy=Integer.valueOf(args[ZERO].substring(FIVE)),

this won't work because args[0] is an empty String.

You should only use substring once, either inside the function or before calling the function.


问:
React: Run handler, only at select renders, useCallback or useEffect?
I would like to run a function only when the variable phone (see below) changes.

Note: useMediaQuery works as intended, it initiates re-render whenever the screen size changes above / below 768, and returns true / false.

```<code>const phone = !useMediaQuery('(min-width:768px)'); // 768 and down: Smartphones

console.log('phone', phone);
useCallback(() => {
  console.log('useCallback fired');
  if (!phone) handleDrawerClose();
}, [phone])();
</code>```

My above code fires the callback in useCallback on every re-render. Regardless if phone changed. I tried useEffect and it partially works.

Why does not useCallback work as intended?

What is the best approach here?

答:
useCallback returns a memoized function, which you then call. As you call it, it gets executed.

What is the best approach here?

useEffect

Body:
I would like to run a function only when the variable phone (see below) changes.

Note: useMediaQuery works as intended, it initiates re-render whenever the screen size changes above / below 768, and returns true / false.

const phone = !useMediaQuery('(min-width:768px)'); // 768 and down: Smartphones

console.log('phone', phone);
useCallback(() => {
  console.log('useCallback fired');
  if (!phone) handleDrawerClose();
}, [phone])();

My above code fires the callback in useCallback on every re-render. Regardless if phone changed. I tried useEffect and it partially works.

Why does not useCallback work as intended?

What is the best approach here?


问:
Reading Excel files from C#
Is there a free or open source library to read Excel files (.xls) directly from a C# program?

It does not need to be too fancy, just to select a worksheet and read the data as strings. So far, I've been using Export to Unicode text function of Excel, and parsing the resulting (tab-delimited) file, but I'd like to eliminate the manual step.

答:
The .NET component Excel Reader .NET may satisfy your requirement. It's good enought for reading XLSX and XLS files. So try it from:

http://www.devtriogroup.com/ExcelReader

OwnerDisplayName: dbkk

Title: Reading Excel files from C#

LastEditorDisplayName: Chris


问:
Nearest Point to N Lines in D dimensional Space
I want to calculate a point/vector with the least Euclidian distance to a given set of N lines (e.g. given by a point and a vector for the direction) in a D dimensional space (for example by least squares)

Since I use Python for my project, I was wondering, whether there are already appropriate implementations for this general problem in some standard library like numpy, but I have not found any.

There are already related questions like:

Finding the centre of multiple lines using least squares approach in Python

nearest intersection point to many lines in python

However, these questions did not consider a dimension larger than 3 and in my case, I would like to adapt the problem to dimensions like 100.

I also found this resource for Matlab, which does not seem to be used that much, but it deals with the same problem:
https://de.mathworks.com/matlabcentral/fileexchange/59805-line-line-intersection-n-lines-d-space?s_tid=FX_rc1_behav

答:
If each line with index i is given by a unit vector column

```<code>vi = {
       v1i,
       v2i,
       v3i,
       ...
       vDi
      }
</code>```

pointing along the line i, and a point given by a vector column

```<code>pi = {
       p1i,
       p2i,
       p3i,
       ...
       pDi
      }
</code>```

, where i = 1...N, then the point x  you seek, given as a column, is given by the equation

```<code>x = inverse( sum(i=1:N, I - vi * transposed(vi)) ) * sum(i=1:N, (I - vi * transposed(vi)) * pi);
</code>```

Here I is the D-dimensional identity square matrix.

If each line is given by two points pi and qi then you can calculate

vi = (qi - pi) / sqrt(transposed(qi - pi) * (qi - pi))

Body:
If each line with index i is given by a unit vector column

vi = {
       v1i,
       v2i,
       v3i,
       ...
       vDi
      }

pointing along the line i, and a point given by a vector column

pi = {
       p1i,
       p2i,
       p3i,
       ...
       pDi
      }

, where i = 1...N, then the point x  you seek, given as a column, is given by the equation

x = inverse( sum(i=1:N, I - vi * transposed(vi)) ) * sum(i=1:N, (I - vi * transposed(vi)) * pi);

Here I is the D-dimensional identity square matrix.

If each line is given by two points pi and qi then you can calculate

vi = (qi - pi) / sqrt(transposed(qi - pi) * (qi - pi))


问:
how to count how many squares with different sizes in a grid with size n*m?
is there a formula to count each distinct square or rectangle within a rectangle for e.g if we have rectangle of size 105119*753919 , and we want to know how many 54705*91121 in it or how many 2*2 in it , is there a general formula that we can use to get the count ?</p>

答:
In an nm grid, how many ij rectangles?

Answer: as many as places you can put the upper left corner. That is:

```<code>(n-i+1)*(m-j+1)
</code>```

Body:
In an nm grid, how many ij rectangles?

Answer: as many as places you can put the upper left corner. That is:

(n-i+1)*(m-j+1)


问:
Add comma from print json_encode
How to add commas to a json print?

```<code>$result = curl($url);
$result = json_decode($result , true);

$resultdata = $result ['data'];
foreach($resultdata as $data){
$print= array(
"id" => $data['id'],
"username" => $data['username'],
"text" => $data['text']
);
print json_encode($print);
}
</code>```

this is the response from my code

```<code>{
    "id": "17996292388215089",
    "username": "hanikfadhilah",
    "text": "Loh kapan ini huuu pengen"
}
{
    "id": "17877856039348099",
    "username": "titan_kdk",
    "text": "Mntb"
}
{
    "id": "17860767967398064",
    "username": "explorecentraljava",
    "text": "Terbaik fotonya lur"
}
</code>```

I want to have a comma for each json result

```<code>{
    "id": "17996292388215089",
    "username": "hanikfadhilah",
    "text": "Loh kapan ini huuu pengen"
},{
    "id": "17877856039348099",
    "username": "titan_kdk",
    "text": "Mntb"
},{
    "id": "17860767967398064",
    "username": "explorecentraljava",
    "text": "Terbaik fotonya lur"
}
</code>```

答:
What you actually need to do is produce an array of results, which you can do by pushing values into an array in the loop, and then json_encode the array after the loop:</p>

```<code>$print = array();
foreach($resultdata as $data){
    $print[]= array(
        "id" => $data['id'],
        "username" => $data['username'],
        "text" => $data['text']
    );
}
print json_encode($print);
</code>```

Title: Add comma from print json_encode

Body:
How to add commas to a json print?

$result = curl($url);
$result = json_decode($result , true);

$resultdata = $result ['data'];
foreach($resultdata as $data){
$print= array(
"id" => $data['id'],
"username" => $data['username'],
"text" => $data['text']
);
print json_encode($print);
}

this is the response from my code

{
    "id": "17996292388215089",
    "username": "hanikfadhilah",
    "text": "Loh kapan ini huuu pengen"
}
{
    "id": "17877856039348099",
    "username": "titan_kdk",
    "text": "Mntb"
}
{
    "id": "17860767967398064",
    "username": "explorecentraljava",
    "text": "Terbaik fotonya lur"
}

I want to have a comma for each json result

{
    "id": "17996292388215089",
    "username": "hanikfadhilah",
    "text": "Loh kapan ini huuu pengen"
},{
    "id": "17877856039348099",
    "username": "titan_kdk",
    "text": "Mntb"
},{
    "id": "17860767967398064",
    "username": "explorecentraljava",
    "text": "Terbaik fotonya lur"
}

Body:
What you actually need to do is produce an array of results, which you can do by pushing values into an array in the loop, and then json_encode the array after the loop:

$print = array();
foreach($resultdata as $data){
    $print[]= array(
        "id" => $data['id'],
        "username" => $data['username'],
        "text" => $data['text']
    );
}
print json_encode($print);


答:
The isin method of @Mike suffices for your answer, but just for your convenience, you can extend your dataframe with more information about the matches by using merge with an indicator:

```<code>df1.merge(df2, left_on='date', right_on='Holiday', how='left', indicator=True)

   X      date   Holiday     _merge
0  a  1/1/2018  1/1/2018       both
1  a  1/2/2018       NaN  left_only
2  b  1/1/2018  1/1/2018       both
</code>```

Here we see our _merge column which indicates if the matches were in both or in left only.

Title: Join two dataframes with inner join

Body:
The isin method of @Mike suffices for your answer, but just for your convenience, you can extend your dataframe with more information about the matches by using merge with an indicator:

df1.merge(df2, left_on='date', right_on='Holiday', how='left', indicator=True)

   X      date   Holiday     _merge
0  a  1/1/2018  1/1/2018       both
1  a  1/2/2018       NaN  left_only
2  b  1/1/2018  1/1/2018       both

Here we see our _merge column which indicates if the matches were in both or in left only.


问:
C# Dll Invoke String Encoding Problem
```<code>    StringBuilder codeline = new StringBuilder(100);

    protected virtual int OnCodeLine(int code, int docId, ref StringBuilder codeline)
            {
////
}
</code>```

This is what i get with *ref StringBuilder*

ĞĞÑĞÒĞÓĞÔĞÕĞÖĞ×ĞØĞÙĞÚĞÛĞÜĞİĞŞĞßĞàĞáĞâĞãĞäĞåĞæĞçĞèĞéĞêĞëĞìĞíĞîĞïĞğĞñĞòĞóĞôĞõĞöĞ÷ĞøĞùĞúĞûĞüĞıĞşĞÿĞÑÑÑÑÑÑÑ Ñ
    ÑÑÑ

ÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑ

and only with StringBuilder i only get 3

This is what its suppose to return

300 078 9059431

By the way this the MICR Code from Cheques

```<code> [DllImport("mflib.dll")]
    public static extern int mfScanFeeder(int mode, int font, int timeout);

 [UnmanagedFunctionPointer(CallingConvention.StdCall)]
 public delegate int MFS100_CodeLineDelegate(int code, int docId, ref StringBuilder codeline);
 public event MFS100_CodeLineDelegate MFS100_CodeLine;
 private static  MFS100_CodeLineDelegate cache_CodeLine;
</code>```

Update : Here is the Original Code that works in vb6

```<code>    Public Function MFS100_OnCodeline(ByVal code As Long, ByVal docId As Long, ByVal codeline As String) As Long
  Dim i As Integer

  WriteEvent "OnCodeline:"
  WriteEvent "  code = " & code
  WriteEvent "  docId = " & docId
  WriteEvent "  codeline = " & codeline

  MFS100_OnCodeline = -1        ' -1 means: sorting will be done by mfSort()

  g_codeline = codeline

  CScannerForm.TmrSort.enabled = True
End Function
</code>```

Update 2

```<code>  mfSetEvent((int)EventEnum.E_EVENT_CODELINE, cache_CodeLine);

[DllImport("mflib.dll")]
        private static extern int mfSetEvent(int eventID, Delegate callsback);
</code>```

When i use StringBuilder with ref i get a string  that have
32361 length. Without ref i get
only the first value of the
string.

OnCodeLine is for the callback
from the scanner device. What is the
problem ?

答:
I don't understand what are you trying to achieve, but if you want to collect a string generated inside OnCodeLine, you don't need to pass the StringBuilder by reference, as it is a reference type.

Just pass the StringBuilder without ref, populate it, and when you return you'll have the desired string in it.

Regarding what you get after calling the OnCodeLine, can you provide some info regarding the implementation?

Sorry, I didn't notice the PInvoke was involved!! :(

Title: C# Dll Invoke String Encoding Problem

Body:
    StringBuilder codeline = new StringBuilder(100);

    protected virtual int OnCodeLine(int code, int docId, ref StringBuilder codeline)
            {
////
}

This is what i get with *ref StringBuilder*

ĞĞÑĞÒĞÓĞÔĞÕĞÖĞ×ĞØĞÙĞÚĞÛĞÜĞİĞŞĞßĞàĞáĞâĞãĞäĞåĞæĞçĞèĞéĞêĞëĞìĞíĞîĞïĞğĞñĞòĞóĞôĞõĞöĞ÷ĞøĞùĞúĞûĞüĞıĞşĞÿĞÑÑÑÑÑÑÑ Ñ
    ÑÑÑ

ÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑ

and only with StringBuilder i only get 3

This is what its suppose to return

300 078 9059431

By the way this the MICR Code from Cheques

 [DllImport("mflib.dll")]
    public static extern int mfScanFeeder(int mode, int font, int timeout);

 [UnmanagedFunctionPointer(CallingConvention.StdCall)]
 public delegate int MFS100_CodeLineDelegate(int code, int docId, ref StringBuilder codeline);
 public event MFS100_CodeLineDelegate MFS100_CodeLine;
 private static  MFS100_CodeLineDelegate cache_CodeLine;

Update : Here is the Original Code that works in vb6

    Public Function MFS100_OnCodeline(ByVal code As Long, ByVal docId As Long, ByVal codeline As String) As Long
  Dim i As Integer

  WriteEvent "OnCodeline:"
  WriteEvent "  code = " & code
  WriteEvent "  docId = " & docId
  WriteEvent "  codeline = " & codeline

  MFS100_OnCodeline = -1        ' -1 means: sorting will be done by mfSort()

  g_codeline = codeline

  CScannerForm.TmrSort.enabled = True
End Function

Update 2

  mfSetEvent((int)EventEnum.E_EVENT_CODELINE, cache_CodeLine);

[DllImport("mflib.dll")]
        private static extern int mfSetEvent(int eventID, Delegate callsback);

When i use StringBuilder with ref i get a string  that have
32361 length. Without ref i get
only the first value of the
string.

OnCodeLine is for the callback
from the scanner device. What is the
problem ?


问:
Change Bootstraps column order for mobile while inside a loop
Trying to change Bootstraps column order for mobile, .col-order doesn't work cause its in a loop. Have $loop->iteration set for displaying different backgrounds on column 1, 4 or 5 for desktop, but for mobile i need some way of displaying them stacked as odds or evens, thanks.

```<code><div class="row no-gutters bg-light">
     @foreach ($products as $product)
     <div class="col-12 col-xl-6 div-wo-bg @if($loop->iteration === 1 || $loop->iteration === 4 || $loop->iteration === 5) div-w-bg @endif">
</code>```

Have tried an if statement:

```<code><div class="row no-gutters bg-light">
     @foreach ($products as $product)
         @if ('className' == 'col-12')
            <div class="col-12 col-xl-6 div-wo-bg @if($loop->iteration === 1 || $loop->iteration === 4 || $loop->iteration === 5) div-w-bg @endif">
         @elseif ('className' == 'col-xl-6')
            <div class="col-12 col-xl-6 div-wo-bg @if($loop->odd) div-w-bg @endif">
         @endif
</code>```

This just throws all the column display out of wack (for both mobile and desktop).

答:
```<code><!-- Latest Products Showcase Section

         - The showcase design calls for columns to be side by side for desktop, but stacked for mobile. There are 2 differently styled   bg's repeated throughout the layout of the columns.

         - Because these columns are layed out differently, they both require 2 different $loop extensions to retrieve the bg's. So       from within an if statement we use $loop->iteration for desktop but $loop->odd for mobile -->

    <!-- Desktop Layout -->
        <div class="container-fluid p-0">
            <div class="row showcase-shop-products no-gutters bg-light">
                @foreach ($products as $product)
                    <div class="col-6 d-none d-lg-flex div-wo-bg @if($loop->iteration === 1 || $loop->iteration === 4 || $loop->iteration === 5) div-w-bg @endif">
                        <div class="container-fluid">
                            <div class="row">

                                <!-- Column a (Text) -->
                                <div class="col-6 showcase-col">
                                    <div class="overlay"></div>
                                    <div class="showcase-hero">
                                        <h2 class="card-title mb-4"><a href="{{ route("shop.show", $product->slug) }}">{{ $product->name }}</a></h2>
                                        <h3 class="card-subtitle text-muted">{{ $product->details }}</h3>
                                        <h4 class="mb-3">{{ $product->presentPrice() }}</h4>
                                        <p class="card-text mb-4 d-lg-none d-xxl-block">Lorem ipsum dolor sit amet consectetur adipisicing elit. At dicta accusamus quia aliquid minima animi alias.</p>
                                        <a href="#" class="btn btn-primary rounded" role="button">Add to Cart</a>
                                    </div>
                                </div>

                                <!-- Column b (Image) -->
                                <div class="col-6 showcase-col">
                                    <a href="{{ route("shop.show", $product->slug) }}" class="text-center showcase-hero"><img class="card-img-top products-img img-fluid" src="{{ asset("img/shop/products/".$product->slug.".png") }}" alt="Random product item"></a>
                                    <div class="overlay"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                @endforeach
            </div>
        </div>

    <!-- Mobile Layout -->
        <div class="container-fluid p-0">
            <div class="row showcase-shop-products no-gutters bg-light">
                @foreach ($products as $product)
                    <div class="col-12 d-flex d-lg-none div-wo-bg @if($loop->odd) div-w-bg @endif">
                        <div class="container-fluid">
                            <div class="row">

                                <!-- Top Column (Image) -->
                                <div class="col-12 showcase-col">
                                    <a href="{{ route("shop.show", $product->slug) }}" class="text-center showcase-hero pt-3"><img class="card-img-top products-img img-fluid" src="{{ asset("img/shop/products/".$product->slug.".png") }}" alt="Random product item"></a>
                                    <div class="overlay"></div>
                                </div>

                                <!-- Bottom Column (Text) -->
                                <div class="col-12 showcase-col">
                                    <div class="overlay"></div>
                                    <div class="showcase-hero text-center pb-5">
                                        <h2 class="card-title mb-4"><a href="{{ route("shop.show", $product->slug) }}">{{ $product->name }}</a></h2>
                                        <h3 class="card-subtitle text-muted">{{ $product->details }}</h3>
                                        <h4 class="mb-3">{{ $product->presentPrice() }}</h4>
                                        <p class="card-text mb-4 d-none xl-block">Lorem ipsum dolor sit amet consectetur adipisicing elit. At dicta accusamus quia aliquid minima animi alias.</p>
                                        <a href="#" class="btn btn-primary rounded btn-width" role="button">Add to Cart</a>
                                    </div>
                                </div>

                            </div>
                        </div>
                    </div>
                @endforeach
            </div>
        </div>
</code>```

Works perfectly now.

Body:
Trying to change Bootstraps column order for mobile, .col-order doesn't work cause its in a loop. Have $loop->iteration set for displaying different backgrounds on column 1, 4 or 5 for desktop, but for mobile i need some way of displaying them stacked as odds or evens, thanks.

     @foreach ($products as $product)

iteration === 1 || $loop->iteration === 4 || $loop->iteration === 5) div-w-bg @endif">

Have tried an if statement:

     @foreach ($products as $product)
         @if ('className' == 'col-12')

iteration === 1 || $loop->iteration === 4 || $loop->iteration === 5) div-w-bg @endif">
         @elseif ('className' == 'col-xl-6')

odd) div-w-bg @endif">
         @endif

This just throws all the column display out of wack (for both mobile and desktop).

Body:
<!-- Latest Products Showcase Section

         - The showcase design calls for columns to be side by side for desktop, but stacked for mobile. There are 2 differently styled   bg's repeated throughout the layout of the columns.

         - Because these columns are layed out differently, they both require 2 different $loop extensions to retrieve the bg's. So       from within an if statement we use $loop->iteration for desktop but $loop->odd for mobile -->

    <!-- Desktop Layout -->
        <div class="container-fluid p-0">
            <div class="row showcase-shop-products no-gutters bg-light">
                @foreach ($products as $product)
                    <div class="col-6 d-none d-lg-flex div-wo-bg @if($loop->iteration === 1 || $loop->iteration === 4 || $loop->iteration === 5) div-w-bg @endif">
                        <div class="container-fluid">
                            <div class="row">

                                <!-- Column a (Text) -->
                                <div class="col-6 showcase-col">
                                    <div class="overlay"></div>
                                    <div class="showcase-hero">
                                        <h2 class="card-title mb-4"><a href="{{ route("shop.show", $product->slug) }}">{{ $product->name }}</a></h2>
                                        <h3 class="card-subtitle text-muted">{{ $product->details }}</h3>
                                        <h4 class="mb-3">{{ $product->presentPrice() }}</h4>
                                        <p class="card-text mb-4 d-lg-none d-xxl-block">Lorem ipsum dolor sit amet consectetur adipisicing elit. At dicta accusamus quia aliquid minima animi alias.</p>
                                        <a href="#" class="btn btn-primary rounded" role="button">Add to Cart</a>
                                    </div>
                                </div>

                                <!-- Column b (Image) -->
                                <div class="col-6 showcase-col">
                                    <a href="{{ route("shop.show", $product->slug) }}" class="text-center showcase-hero"><img class="card-img-top products-img img-fluid" src="{{ asset("img/shop/products/".$product->slug.".png") }}" alt="Random product item"></a>
                                    <div class="overlay"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                @endforeach
            </div>
        </div>

    <!-- Mobile Layout -->
        <div class="container-fluid p-0">
            <div class="row showcase-shop-products no-gutters bg-light">
                @foreach ($products as $product)
                    <div class="col-12 d-flex d-lg-none div-wo-bg @if($loop->odd) div-w-bg @endif">
                        <div class="container-fluid">
                            <div class="row">

                                <!-- Top Column (Image) -->
                                <div class="col-12 showcase-col">
                                    <a href="{{ route("shop.show", $product->slug) }}" class="text-center showcase-hero pt-3"><img class="card-img-top products-img img-fluid" src="{{ asset("img/shop/products/".$product->slug.".png") }}" alt="Random product item"></a>
                                    <div class="overlay"></div>
                                </div>

                                <!-- Bottom Column (Text) -->
                                <div class="col-12 showcase-col">
                                    <div class="overlay"></div>
                                    <div class="showcase-hero text-center pb-5">
                                        <h2 class="card-title mb-4"><a href="{{ route("shop.show", $product->slug) }}">{{ $product->name }}</a></h2>
                                        <h3 class="card-subtitle text-muted">{{ $product->details }}</h3>
                                        <h4 class="mb-3">{{ $product->presentPrice() }}</h4>
                                        <p class="card-text mb-4 d-none xl-block">Lorem ipsum dolor sit amet consectetur adipisicing elit. At dicta accusamus quia aliquid minima animi alias.</p>
                                        <a href="#" class="btn btn-primary rounded btn-width" role="button">Add to Cart</a>
                                    </div>
                                </div>

                            </div>
                        </div>
                    </div>
                @endforeach
            </div>
        </div>

Works perfectly now.


问:
e.target.value in button returns undefined sometimes. Why this happens?
I have defined four buttons and those buttons will call same method in onClick event.

Method

```<code>   changeFilterForButtons(e){
    let filter = e.target.value;
    console.log("----------------------------"  + filter);
    this.props.handleData(filter);
    this.props.filterData();
}
</code>```

Render()

```<code> render() {
    return (
        <div className='audit-menu' style={{backgroundColor: '#fff'}}>
            <div className='row align-items-center'>
                <div className="col text-left ml-2 font-weight-bold">
                    Invoice audit
                </div>
                <div className="col-6 ">
                    <div class="btn-group btn-group w-100">
                        <button class="w-25 btn menu-btn" value='inbox' onClick={this.changeFilterForButtons.bind(this)}><i className="icon-upload pr-3">
                        </i>Inbox
                        </button>
                        <button class="w-25 btn menu-btn" value='rejected'  onClick={this.changeFilterForButtons.bind(this)}><i className="icon-search pr-3">
                        </i>Rejected
                        </button>
                        <button class="w-25 btn menu-btn" value='accepted' onClick={this.changeFilterForButtons.bind(this)}><i className="icon-search pr-3">
                        </i>Accepted
                        </button>
                        <button class="w-25 btn menu-btn" value='archive' onClick={this.changeFilterForButtons.bind(this)}><i className="icon-search pr-3">
                        </i>Archive
                        </button>
                    </div>

                </div>
                <div className="col">
                    <li className="nav-item dropdown d-none d-lg-block">
                        <a aria-expanded="true" className="nav-link dropdown-toggle select-company-dropdown"
                           data-toggle="dropdown" href="#" id="selectLanguage">Select company</a>
                    </li>
                </div>
            </div>
        </div>
    );
}
</code>```

When buttons are clicked most of the times e.target.value is taken by above function. But sometimes it returns undefined. Why this is happening ?. Console.log output is added below.

答:
I had the same trouble. When I read the second comment I saw where to find the solution.

CSS solution:

```<code>button > * {
  pointer-events: none;
}
</code>```

Source

Body:
I have defined four buttons and those buttons will call same method in onClick event.

Method

   changeFilterForButtons(e){
    let filter = e.target.value;
    console.log("----------------------------"  + filter);
    this.props.handleData(filter);
    this.props.filterData();
}

Render()

 render() {
    return (

                    Invoice audit

                        <button class="w-25 btn menu-btn" value='inbox' onClick={this.changeFilterForButtons.bind(this)}>
                        Inbox
                        </button>
                        <button class="w-25 btn menu-btn" value='rejected'  onClick={this.changeFilterForButtons.bind(this)}>
                        Rejected
                        </button>
                        <button class="w-25 btn menu-btn" value='accepted' onClick={this.changeFilterForButtons.bind(this)}>
                        Accepted
                        </button>
                        <button class="w-25 btn menu-btn" value='archive' onClick={this.changeFilterForButtons.bind(this)}>
                        Archive
                        </button>

                        Select company

    );
}

When buttons are clicked most of the times e.target.value is taken by above function. But sometimes it returns undefined. Why this is happening ?. Console.log output is added below.

Body:
I had the same trouble. When I read the second comment I saw where to find the solution.

CSS solution:

button > * {
  pointer-events: none;
}

Source


问:
cumulative sum by ID with lag
I want to create a cumulative sum by id. But, it should not sum the value that belongs to the row where is being calculated.

I've already tried with cumsum. However, I do not know how to add a statement which specifies to do not add the amount of the row where the sum is made. The result column I am looking for is the third column called: "sum".

For example, for id 1, the first row is sum=0, because should not add this row. But, for id 1 and row 2 sum=100 because the amount of id 1 previous to the row 2 was 100 and so on.

```<code>   id amount sum
1:  1    100   0
2:  1     20 100
3:  1    150 120
4:  2     60   0
5:  2    100  60
6:  1     30 270
7:  2     40 160
</code>```

This is what I've tried:

```<code>  df[,sum:=cumsum(amount),
      by ="id"]

  data: df <- data.table(id = c(1, 1, 1, 2, 2,1,2), amount = c(100, 20,
  150,60,100,30,40),sum=c(0,100,120,0,60,270,160) ,stringsAsFactors =
  FALSE)
</code>```

答:
With dplyr -

```<code>df %>%
  group_by(id) %>%
  mutate(sum = lag(cumsum(amount), default = 0)) %>%
  ungroup()

# A tibble: 7 x 3
     id amount   sum
  <dbl>  <dbl> <dbl>
1     1    100     0
2     1     20   100
3     1    150   120
4     2     60     0
5     2    100    60
6     1     30   270
7     2     40   160
</code>```

Thanks to @thelatemail here's the data.table version -

```<code>df[, sum := cumsum(shift(amount, fill=0)), by=id]
</code>```

Title: cumulative sum by ID with lag

Body:
I want to create a cumulative sum by id. But, it should not sum the value that belongs to the row where is being calculated.

I've already tried with cumsum. However, I do not know how to add a statement which specifies to do not add the amount of the row where the sum is made. The result column I am looking for is the third column called: "sum".

For example, for id 1, the first row is sum=0, because should not add this row. But, for id 1 and row 2 sum=100 because the amount of id 1 previous to the row 2 was 100 and so on.

   id amount sum
1:  1    100   0
2:  1     20 100
3:  1    150 120
4:  2     60   0
5:  2    100  60
6:  1     30 270
7:  2     40 160

This is what I've tried:

  df[,sum:=cumsum(amount),
      by ="id"]

  data: df <- data.table(id = c(1, 1, 1, 2, 2,1,2), amount = c(100, 20,
  150,60,100,30,40),sum=c(0,100,120,0,60,270,160) ,stringsAsFactors =
  FALSE)

Body:
With dplyr -

df %>%
  group_by(id) %>%
  mutate(sum = lag(cumsum(amount), default = 0)) %>%
  ungroup()

# A tibble: 7 x 3
     id amount   sum
  <dbl>  <dbl> <dbl>
1     1    100     0
2     1     20   100
3     1    150   120
4     2     60     0
5     2    100    60
6     1     30   270
7     2     40   160

Thanks to @thelatemail here's the data.table version -

df[, sum := cumsum(shift(amount, fill=0)), by=id]