问:
Warning: session_start() [function.session-start]: The session id contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,'
I noticed this in my PHP error log:

Warning: session_start() [function.session-start]: The session id contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,'

I don't know what's wrong. The session names are called PHPSESSID (default). and have values like: f11m9p7r18pau9s7j9dsk8f1h6.

I am baffled, I don't know what it is trying to tell me, sessions are handled by PHP. I am on shared hosting, but have my sessions stored outside document root so nobody can access them.

答:
Don't mind, somebody could simply manipulate the URL like:

```<code>http://domain.org/?PHPSESSID=this~won't_work
</code>```

PHP will see the PHPSESSID-parameter and tries to restore the session using the value(what will fail)

If you like to avoid these errors, use the @-operator on session_start()

Body:
Don't mind, somebody could simply manipulate the URL like:

http://domain.org/?PHPSESSID=this~won't_work

PHP will see the PHPSESSID-parameter and tries to restore the session using the value(what will fail)

If you like to avoid these errors, use the @-operator on session_start()


来源: stackexchange

问:
java.lang.NoSuchMethodError: org.mockito.internal.runners.RunnerFactory.createStrict(Ljava/lang/Class;)Lorg/mockito/internal/runners/InternalRunner;
I am writing my Junit test cases for Groovy using Mockito jar, but it is giving me following exception:

```<code>java.lang.NoSuchMethodError: org.mockito.internal.runners.RunnerFactory.createStrict(Ljava/lang/Class;)Lorg/mockito/internal/runners/InternalRunner;
at org.mockito.junit.MockitoJUnitRunner.<init>(MockitoJUnitRunner.java:152)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:84)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:70)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:43)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
</code>```

Below is the jar list that I have:

```<code>cglib-nodep-2.2.2
javassist-3.19.0-GA
junit-4.12
mockito-all-1.10.19
objenesis-2.5
powermock-mockito-1.6.2-full
</code>```

Below is my code. I have added necessary imports:

```<code>package test.service
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
class SyncImplTest {

    @InjectMocks
    SyncThreatImpl  fixture;

    @Mock
    RpcConfigurationLoader rpcConfigurationLoader

    @Test
    public void testRpcConfig(){
        RpcApiInfo rpcApiInfo =  new RpcApiInfo();
        when(rpcConfigurationLoader.loadConfiguration()).thenReturn(rpcApiInfo)
    }

}
</code>```

答:
For some reason, your test suite, tries to load the MockitoJunitRunner from the  org.mockito.junit contained in the Mockito versions >= 2. O. In that version, the line:

```<code>at org.mockito.junit.MockitoJUnitRunner.<init>(MockitoJUnitRunner.java:152)
</code>```

is doing this:

```<code>public MockitoJUnitRunner(Class<?> klass) throws InvocationTargetException {
        //by default, StrictRunner is used. We can change that potentially based on feedback from users
        this(new StrictRunner(new RunnerFactory().createStrict(klass), klass));
    }
</code>```

and the RunnerFactory that is loaded here is from version 1.x as createStrict has been introduced in Mockito 2.x.

So go through the pom dependency tree and to find what artifact implicitly add the Mockito 2.x dependency to your project and exclude it.

Alternatively.. as a workaround, instead of the @RunWith(MockitoJUnitRunner.class) you can use:

```<code>@Before
public void init() {
    MockitoAnnotations.initMocks(this);
}
</code>```

You can also check out this Mockito cheat sheet to keep all the standards at hand.

ContentLicense: CC BY-SA 3.0

Body:
I am writing my Junit test cases for Groovy using Mockito jar, but it is giving me following exception:

java.lang.NoSuchMethodError: org.mockito.internal.runners.RunnerFactory.createStrict(Ljava/lang/Class;)Lorg/mockito/internal/runners/InternalRunner;
at org.mockito.junit.MockitoJUnitRunner.<init>(MockitoJUnitRunner.java:152)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:84)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:70)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:43)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Below is the jar list that I have:

cglib-nodep-2.2.2
javassist-3.19.0-GA
junit-4.12
mockito-all-1.10.19
objenesis-2.5
powermock-mockito-1.6.2-full

Below is my code. I have added necessary imports:

package test.service
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
class SyncImplTest {

    @InjectMocks
    SyncThreatImpl  fixture;

    @Mock
    RpcConfigurationLoader rpcConfigurationLoader

    @Test
    public void testRpcConfig(){
        RpcApiInfo rpcApiInfo =  new RpcApiInfo();
        when(rpcConfigurationLoader.loadConfiguration()).thenReturn(rpcApiInfo)
    }

}

Body:
For some reason, your test suite, tries to load the MockitoJunitRunner from the  org.mockito.junit contained in the Mockito versions >= 2. O. In that version, the line:

at org.mockito.junit.MockitoJUnitRunner.<init>(MockitoJUnitRunner.java:152)

is doing this:

public MockitoJUnitRunner(Class<?> klass) throws InvocationTargetException {
        //by default, StrictRunner is used. We can change that potentially based on feedback from users
        this(new StrictRunner(new RunnerFactory().createStrict(klass), klass));
    }

and the RunnerFactory that is loaded here is from version 1.x as createStrict has been introduced in Mockito 2.x.

So go through the pom dependency tree and to find what artifact implicitly add the Mockito 2.x dependency to your project and exclude it.

Alternatively.. as a workaround, instead of the @RunWith(MockitoJUnitRunner.class) you can use:

@Before
public void init() {
    MockitoAnnotations.initMocks(this);
}

You can also check out this Mockito cheat sheet to keep all the standards at hand.

ContentLicense: CC BY-SA 4.0


问:
Firebase Firestore multiple queries

Hi, I'm trying to add a filter on top of a query, however, it's not working. It's causing useless repetition in the code. Can someone help me?

Is there a way to add more .whereField to an existant Ref?

Thanks!
William

```<code>        var usersRef:Query

    if (DAgeMin == DAgeMax) {
        if (DGender == "Both") {
            usersRef = Firestore.firestore().collection("users")
                .whereField("AccountCompleted", isEqualTo: true)
                .whereField("Banned", isEqualTo: 0)
                .whereField("Age", isEqualTo: DAgeMin as Any)
            // usersRef.limit(to: 1)
        } else {
            usersRef = Firestore.firestore().collection("users")
                .whereField("AccountCompleted", isEqualTo: true)
                .whereField("Banned", isEqualTo: 0)
                .whereField("Gender", isEqualTo: DGender as Any)
                .whereField("Age", isEqualTo: DAgeMin as Any)
            // usersRef.limit(to: 1)
        }
    } else {
        if (DGender == "Both") {

            usersRef = Firestore.firestore().collection("users")
            // Not working, filters aren't being applied
                usersRef
                .whereField("AccountCompleted", isEqualTo: true)
                .whereField("Banned", isEqualTo: 0)
                .whereField("Age", isGreaterThanOrEqualTo: DAgeMin as Any)
                .whereField("Age", isLessThanOrEqualTo: DAgeMax as Any)

            // usersRef.limit(to: 1)
        } else {
            usersRef = Firestore.firestore().collection("users")
                .whereField("AccountCompleted", isEqualTo: true)
                .whereField("Banned", isEqualTo: 0)
                .whereField("Gender", isEqualTo: DGender as Any)
                .whereField("Age", isGreaterThanOrEqualTo: DAgeMin as Any)
                .whereField("Age", isLessThanOrEqualTo: DAgeMax as Any)
            // usersRef.limit(to: 1)

        }
    }
    // How can I apply this filter to all the usersRef, without putting it after each "block"
    usersRef.limit(to: 1)

    usersRef.getDocuments() { (querySnapshot, err) in
</code>```

答: you must set the common 'whereField' outside your 'ifs', and inside your 'ifs' you must set the particular 'whereField'</p>

Title: Firebase Firestore multiple queries

Body:
Hi, I'm trying to add a filter on top of a query, however, it's not working. It's causing useless repetition in the code. Can someone help me?

Is there a way to add more .whereField to an existant Ref?

Thanks!
William

        var usersRef:Query

    if (DAgeMin == DAgeMax) {
        if (DGender == "Both") {
            usersRef = Firestore.firestore().collection("users")
                .whereField("AccountCompleted", isEqualTo: true)
                .whereField("Banned", isEqualTo: 0)
                .whereField("Age", isEqualTo: DAgeMin as Any)
            // usersRef.limit(to: 1)
        } else {
            usersRef = Firestore.firestore().collection("users")
                .whereField("AccountCompleted", isEqualTo: true)
                .whereField("Banned", isEqualTo: 0)
                .whereField("Gender", isEqualTo: DGender as Any)
                .whereField("Age", isEqualTo: DAgeMin as Any)
            // usersRef.limit(to: 1)
        }
    } else {
        if (DGender == "Both") {

            usersRef = Firestore.firestore().collection("users")
            // Not working, filters aren't being applied
                usersRef
                .whereField("AccountCompleted", isEqualTo: true)
                .whereField("Banned", isEqualTo: 0)
                .whereField("Age", isGreaterThanOrEqualTo: DAgeMin as Any)
                .whereField("Age", isLessThanOrEqualTo: DAgeMax as Any)

            // usersRef.limit(to: 1)
        } else {
            usersRef = Firestore.firestore().collection("users")
                .whereField("AccountCompleted", isEqualTo: true)
                .whereField("Banned", isEqualTo: 0)
                .whereField("Gender", isEqualTo: DGender as Any)
                .whereField("Age", isGreaterThanOrEqualTo: DAgeMin as Any)
                .whereField("Age", isLessThanOrEqualTo: DAgeMax as Any)
            // usersRef.limit(to: 1)

        }
    }
    // How can I apply this filter to all the usersRef, without putting it after each "block"
    usersRef.limit(to: 1)

    usersRef.getDocuments() { (querySnapshot, err) in


问:
WampServer : Your Port 80 is actually used by Microsoft-HTTPAPI/2.0
I've uninstalled my WampServer 2.5 and installed version 3.0
But apache service isn't running and tray icon is orange...
Clicking on test port 80 gave me the following cmd output :

```<code>***** Test which uses port 80 *****
===== Tested by command netstat filtered on port 80 =====
Test for TCP
Your port 80 is used by a processus with PID = 4
The processus of PID 4 is 'System' Session: Services
The service of PID 4 for 'System' is 'N/A'
*** ERROR *** This service IS NOT from Wampserver - Should be: 'wampapache'
Test for TCPv6
Your port 80 is used by a processus with PID = 4
The processus of PID 4 is 'System' Session: Services
The service of PID 4 for 'System' is 'N/A'
*** ERROR *** This service IS NOT from Wampserver - Should be: 'wampapache'
===== Tested by attempting to open a socket on port 80 =====
Your port 80 is actually used by :
Server: Microsoft-HTTPAPI/2.0

Press Enter to exit...
</code>```

ISS Service has been disabled before and the Activation Windows service process too by the wampserver forum.

What is the problem then ??

答:
There is more than one service that could be causing this. Try opening cmd or PowerShell (remember about administrator rights) and run:

```<code>NET stop HTTP
</code>```

It will stop service that is running on port 80 and will display every service that was disabled to achieve that, simply disable that services for future and that should solve your issue.

Body:
I've uninstalled my WampServer 2.5 and installed version 3.0
But apache service isn't running and tray icon is orange...
Clicking on test port 80 gave me the following cmd output :

***** Test which uses port 80 *****
===== Tested by command netstat filtered on port 80 =====
Test for TCP
Your port 80 is used by a processus with PID = 4
The processus of PID 4 is 'System' Session: Services
The service of PID 4 for 'System' is 'N/A'
*** ERROR *** This service IS NOT from Wampserver - Should be: 'wampapache'
Test for TCPv6
Your port 80 is used by a processus with PID = 4
The processus of PID 4 is 'System' Session: Services
The service of PID 4 for 'System' is 'N/A'
*** ERROR *** This service IS NOT from Wampserver - Should be: 'wampapache'
===== Tested by attempting to open a socket on port 80 =====
Your port 80 is actually used by :
Server: Microsoft-HTTPAPI/2.0

Press Enter to exit...

ISS Service has been disabled before and the Activation Windows service process too by the wampserver forum.

What is the problem then ??

Body:
There is more than one service that could be causing this. Try opening cmd or PowerShell (remember about administrator rights) and run:

NET stop HTTP

It will stop service that is running on port 80 and will display every service that was disabled to achieve that, simply disable that services for future and that should solve your issue.


问:
Xamarin, Android: Timer to animate Text stops after 1 second
in my app, I have a simple TextView that is supposed to count numbers down animated. Since the animator class doenst have anything that would do that, I created my own animation using a timer. Basically, whenever the timer is elapsed (every .01 second), the integer that is displayed on my textviews subtracts 10 of itself and then displays it on the textview again. This looks like this:

```<code>    private void CountHOFNumbers()
    {

        int intHofNumber = 999999;

        System.Timers.Timer timer = new System.Timers.Timer();

        timer.Interval = 10;
        timer.Elapsed += delegate
        {
            intHofNumber -= 10;
            txtHof.Text = "# " + formatAp(intHofNumber);
        };
        timer.Enabled = true;
        timer.Start();

    }
</code>```

It does work, but after just a secnd the timer stops. The app doenst crash, it just doesnt count down anymore. Also, it is never the exact same number that it stops on - sometimes it is at 999,913 - then it is as 999,324 and so on. But it never runs for longer than about 1.5 seconds. This is really bothering me. Also, my phone is vibrating from another thread. The timer seems to stops always when the vibration is on. Is there a chance that they correlate? Or am I just doing it all wrong? I'd love some help! Thanks!

答:
And here is the solution:

```<code>RunOnUiThread(() => txtHof.Text = "# " + formatAp(intHofStartNumber));
</code>```

I'ts weired though, that it started and then stopps. It shouldn't have started to begin with, but anyway - this fixes my issue :)

Body:
in my app, I have a simple TextView that is supposed to count numbers down animated. Since the animator class doenst have anything that would do that, I created my own animation using a timer. Basically, whenever the timer is elapsed (every .01 second), the integer that is displayed on my textviews subtracts 10 of itself and then displays it on the textview again. This looks like this:

    private void CountHOFNumbers()
    {

        int intHofNumber = 999999;

        System.Timers.Timer timer = new System.Timers.Timer();

        timer.Interval = 10;
        timer.Elapsed += delegate
        {
            intHofNumber -= 10;
            txtHof.Text = "# " + formatAp(intHofNumber);
        };
        timer.Enabled = true;
        timer.Start();

    }

It does work, but after just a secnd the timer stops. The app doenst crash, it just doesnt count down anymore. Also, it is never the exact same number that it stops on - sometimes it is at 999,913 - then it is as 999,324 and so on. But it never runs for longer than about 1.5 seconds. This is really bothering me. Also, my phone is vibrating from another thread. The timer seems to stops always when the vibration is on. Is there a chance that they correlate? Or am I just doing it all wrong? I'd love some help! Thanks!

Body:
And here is the solution:

RunOnUiThread(() => txtHof.Text = "# " + formatAp(intHofStartNumber));

I'ts weired though, that it started and then stopps. It shouldn't have started to begin with, but anyway - this fixes my issue :)


问:
Covert scala to c++ - list to vector
I have the following code in scala

```<code>type Pos = (Int, Int)
def legal_moves(dim: Int, path: Path, x: Pos): List[Pos] =
{
 List((x._1 + 1, x._2 + 2),
    (x._1 + 2, x._2 + 1),
    (x._1 + 2, x._2 - 1),
    (x._1 + 1, x._2 - 2),
    (x._1 - 1, x._2 - 2),
    (x._1 - 2, x._2 - 1),
    (x._1 - 2, x._2 + 1),
    (x._1 - 1, x._2 + 2))
}
</code>```

I want to convert it to c++, I have tried to do the following:

```<code>typedef vector<pair<int,int> > Path;

Path move(const pair<int,int> & passed_Pair)
{

    Path allMoves =
    (
        ( (get<0>(passed_Pair))+1, (get<1>(passed_Pair))+2),
        ( (get<0>(passed_Pair))+2, (get<1>(passed_Pair))+1),
        ( (get<0>(passed_Pair))+2, (get<1>(passed_Pair))-1),
        ( (get<0>(passed_Pair))+1, (get<1>(passed_Pair))-2),

        ( (get<0>(passed_Pair))-1, (get<1>(passed_Pair))-2),
        ( (get<0>(passed_Pair))-2, (get<1>(passed_Pair))-1),
        ( (get<0>(passed_Pair))-2, (get<1>(passed_Pair))+1),
        ( (get<0>(passed_Pair))-1, (get<1>(passed_Pair))+2)
    );

    return allMoves;
}
</code>```

and I am getting this error message:

conversion from ‘int’ to non-scalar type ‘Path {aka
  std::vector >}’ requested

and I get all the allMoves in red.

If I did it like this

```<code>Path allMoves = { // as above }
</code>```

I get this error message:

```<code>> error: could not convert ‘{(((void)(((int)std::get<0ul, int, int>((* &
> passed_Pair))) + 1)), (((int)std::get<1ul, int, int>((* &
> passed_Pair))) + 2)), (((void)(((int)std::get<0ul, int, int>((* &
> passed_Pair))) + 2)), (((int)std::get<1ul, int, int>((* &
> passed_Pair))) + 1)), (((void)(((int)std::get<0ul, int, int>((* &
> passed_Pair))) + 2)), (((int)std::get<1ul, int, int>((* &
> passed_Pair))) - 1)), (((void)(((int)std::get<0ul, int, int>((* &
> passed_Pair))) + 1)), (((int)std::get<1ul, int, int>((* &
> passed_Pair))) - 2)), (((void)(((int)std::get<0ul, int, int>((* &
> passed_Pair))) - 1)), (((int)std::get<1ul, int, int>((* &
> passed_Pair))) - 2)), (((void)(((int)std::get<0ul, int, int>((* &
> passed_Pair))) - 2)), (((int)std::get<1ul, int, int>((* &
> passed_Pair))) - 1)), (((void)(((int)std::get<0ul, int, int>((* &
> passed_Pair))) - 2)), (((int)std::get<1ul, int, int>((* &
> passed_Pair))) + 1)), (((void)(((int)std::get<0ul, int, int>((* &
> passed_Pair))) - 1)), (((int)std::get<1ul, int, int>((* &
> passed_Pair))) + 2))}’ from ‘<brace-enclosed initializer list>’ to
> ‘Path {aka std::vector<std::pair<int, int> >}’   };
</code>```

Thanks for your time

答:
You're C++ syntax is just wrong. You need to learn the syntax to construct objects on the stack and how to use the initializer_list constructor of your vector (http://en.cppreference.com/w/cpp/utility/initializer_list)</p>

```<code>#include <vector>
#include <utility>

typedef std::vector<std::pair<int,int> > Path;

Path move(const std::pair<int,int>& passed_Pair)
{
    using std::get;
    Path allMoves
    {
        { get<0>(passed_Pair)+1, get<1>(passed_Pair)+2},
        { get<0>(passed_Pair)+2, get<1>(passed_Pair)+1},
        { get<0>(passed_Pair)+2, get<1>(passed_Pair)-1},
        { get<0>(passed_Pair)+1, get<1>(passed_Pair)-2},

        { get<0>(passed_Pair)-1, get<1>(passed_Pair)-2},
        { get<0>(passed_Pair)-2, get<1>(passed_Pair)-1},
        { get<0>(passed_Pair)-2, get<1>(passed_Pair)+1},
        { get<0>(passed_Pair)-1, get<1>(passed_Pair)+2}
    };

    return allMoves;
}
</code>```

Title: Covert scala to c++ - list to vector

Body:
I have the following code in scala

type Pos = (Int, Int)
def legal_moves(dim: Int, path: Path, x: Pos): List[Pos] =
{
 List((x._1 + 1, x._2 + 2),
    (x._1 + 2, x._2 + 1),
    (x._1 + 2, x._2 - 1),
    (x._1 + 1, x._2 - 2),
    (x._1 - 1, x._2 - 2),
    (x._1 - 2, x._2 - 1),
    (x._1 - 2, x._2 + 1),
    (x._1 - 1, x._2 + 2))
}

I want to convert it to c++, I have tried to do the following:

typedef vector<pair<int,int> > Path;

Path move(const pair<int,int> & passed_Pair)
{

    Path allMoves =
    (
        ( (get<0>(passed_Pair))+1, (get<1>(passed_Pair))+2),
        ( (get<0>(passed_Pair))+2, (get<1>(passed_Pair))+1),
        ( (get<0>(passed_Pair))+2, (get<1>(passed_Pair))-1),
        ( (get<0>(passed_Pair))+1, (get<1>(passed_Pair))-2),

        ( (get<0>(passed_Pair))-1, (get<1>(passed_Pair))-2),
        ( (get<0>(passed_Pair))-2, (get<1>(passed_Pair))-1),
        ( (get<0>(passed_Pair))-2, (get<1>(passed_Pair))+1),
        ( (get<0>(passed_Pair))-1, (get<1>(passed_Pair))+2)
    );

    return allMoves;
}

and I am getting this error message:

conversion from ‘int’ to non-scalar type ‘Path {aka
  std::vector >}’ requested

and I get all the allMoves in red.

If I did it like this

Path allMoves = { // as above }

I get this error message:

> error: could not convert ‘{(((void)(((int)std::get<0ul, int, int>((* &
> passed_Pair))) + 1)), (((int)std::get<1ul, int, int>((* &
> passed_Pair))) + 2)), (((void)(((int)std::get<0ul, int, int>((* &
> passed_Pair))) + 2)), (((int)std::get<1ul, int, int>((* &
> passed_Pair))) + 1)), (((void)(((int)std::get<0ul, int, int>((* &
> passed_Pair))) + 2)), (((int)std::get<1ul, int, int>((* &
> passed_Pair))) - 1)), (((void)(((int)std::get<0ul, int, int>((* &
> passed_Pair))) + 1)), (((int)std::get<1ul, int, int>((* &
> passed_Pair))) - 2)), (((void)(((int)std::get<0ul, int, int>((* &
> passed_Pair))) - 1)), (((int)std::get<1ul, int, int>((* &
> passed_Pair))) - 2)), (((void)(((int)std::get<0ul, int, int>((* &
> passed_Pair))) - 2)), (((int)std::get<1ul, int, int>((* &
> passed_Pair))) - 1)), (((void)(((int)std::get<0ul, int, int>((* &
> passed_Pair))) - 2)), (((int)std::get<1ul, int, int>((* &
> passed_Pair))) + 1)), (((void)(((int)std::get<0ul, int, int>((* &
> passed_Pair))) - 1)), (((int)std::get<1ul, int, int>((* &
> passed_Pair))) + 2))}’ from ‘<brace-enclosed initializer list>’ to
> ‘Path {aka std::vector<std::pair<int, int> >}’   };

Thanks for your time

Body:
You're C++ syntax is just wrong. You need to learn the syntax to construct objects on the stack and how to use the initializer_list constructor of your vector (http://en.cppreference.com/w/cpp/utility/initializer_list)

#include <vector>
#include <utility>

typedef std::vector<std::pair<int,int> > Path;

Path move(const std::pair<int,int>& passed_Pair)
{
    using std::get;
    Path allMoves
    {
        { get<0>(passed_Pair)+1, get<1>(passed_Pair)+2},
        { get<0>(passed_Pair)+2, get<1>(passed_Pair)+1},
        { get<0>(passed_Pair)+2, get<1>(passed_Pair)-1},
        { get<0>(passed_Pair)+1, get<1>(passed_Pair)-2},

        { get<0>(passed_Pair)-1, get<1>(passed_Pair)-2},
        { get<0>(passed_Pair)-2, get<1>(passed_Pair)-1},
        { get<0>(passed_Pair)-2, get<1>(passed_Pair)+1},
        { get<0>(passed_Pair)-1, get<1>(passed_Pair)+2}
    };

    return allMoves;
}


问:
Any way to have double->float conversion regarded as "widening"?
Is there any way to tell vb.net (2010) to allow expressions of type Double to be passed to parameters expecting Float, without having to use an explicit CSng() calls, other than by turning off all complaints related to narrowing conversions?  Given that a Double->Single conversion will never throw an exception, and given that precision loss does not seem to be a criterion for regarding a conversion as "Narrowing" (Long->Double is considered "Widening" despite the fact that it involves an inexact conversion from an "exact-value" type to an "approximate-value" type; a Double->Single conversion merely goes from an "approximate-value" type to a "somewhat-more-approximate-value" type, so it is in some sense less lossy).

I know turning off Option Strict would eliminate squawks about Double->Single conversion, but that is incredibly massively overkill.  Is there any way to stifle all complaints about Double->Single, without stifling other possibly-useful squawks?

Edit

If Microsoft isn't going to allow code to be written in the most logical fashion, would it be preferable to litter the code with CSng() every time I call graphics methods, or define NewRectF and NewPointF methods which accept doubles and then use the RectF/PointF overloads for the graphics methods, or would something else be better still?

答:
no, it's not possible

you have to convert it

or convert your code to use only double or only float(single)

ContentLicense: CC BY-SA 2.5


问:
How to optimize this method in Scala?
Suppose I've got class A with method foo:

```<code>class A(x: Int) { def foo(): Option[Int] = if (x > 0) Some(x) else None }
</code>```

Now I am writing function bar like this:

```<code>def bar(as: List[A]): Option[(A,  Int)] = for {
  a <- as.view.find(_.foo.nonEmpty)
  foo <- a.foo
} yield (a, foo)
</code>```

The code above works fine but what it invokes the foo method twice for the found A instance. How to re-write bar to invoke method foo only once for the found A instance ?

答:
```<code> as.iterator.flatMap { a => a.foo.map { a -> _ } }.find(_ => true)
</code>```

Title: How to optimize this method in Scala?

Body:
Suppose I've got class A with method foo:

class A(x: Int) { def foo(): Option[Int] = if (x > 0) Some(x) else None }

Now I am writing function bar like this:

def bar(as: List[A]): Option[(A,  Int)] = for {
  a <- as.view.find(_.foo.nonEmpty)
  foo <- a.foo
} yield (a, foo)

The code above works fine but what it invokes the foo method twice for the found A instance. How to re-write bar to invoke method foo only once for the found A instance ?


问:
Determine when a socket is destroyed NodeJS
When the user closes the window, how can I tell if a socket is destroyed?

In my code:

```<code>io.on('connection', function (socket) {...})
</code>```

is there a io.on('disconnect', function(socket) or something? I want io.emit that a particular socket has closed or finished.

答:
Socket.IO have a disconnect event: https://socket.io/docs/server-api/ look for "Event: 'disconnect'"

Just make sure it's inside you 'connect' block

```<code>socket.on('disconnect', function () {
    //do something
});
</code>```

Body:
When the user closes the window, how can I tell if a socket is destroyed?

In my code:

io.on('connection', function (socket) {...})

is there a io.on('disconnect', function(socket) or something? I want io.emit that a particular socket has closed or finished.

Body:
Socket.IO have a disconnect event: https://socket.io/docs/server-api/ look for "Event: 'disconnect'"

Just make sure it's inside you 'connect' block

socket.on('disconnect', function () {
    //do something
});


问:
IDENTITY_INSERT is set to OFF(can't find where is the error)
I am trying to run my program in Visual Studio 2015. I created a .mdf database and a table in it. When I try to run it, I get this the following error:

```<code>cannot insert explicit value for identity column in table tblinfo when IDENTITY_INSERT is set to OFF".
</code>```

Hope someone can help me. Thanks.

答:
Scope for "SET IDENTITY_INSERT" is based on the connection only. For the new connection, it will be reset.

Here, if you want to insert the data into the identity column, you have to set the  SET IDENTITY_INSERT ON in the stored procedure first before insert statement. Once data is inserted again set it to ON. SET IDENTITY_INSERT OFF after the insert statement.

Body:
I am trying to run my program in Visual Studio 2015. I created a .mdf database and a table in it. When I try to run it, I get this the following error:

cannot insert explicit value for identity column in table tblinfo when IDENTITY_INSERT is set to OFF".

Hope someone can help me. Thanks.


答:
Listen to the particular socket object's disconnect event:

```<code>io.on('connection', socket => {
  socket.on('disconnect', () => {
    // socket has been disconnected
  })
})
</code>```

Title: Determine when a socket is destroyed NodeJS

Body:
Listen to the particular socket object's disconnect event:

io.on('connection', socket => {
  socket.on('disconnect', () => {
    // socket has been disconnected
  })
})


问:
Take the sum of 3 adc data for 3 sampling

Hi everyone,

I am a newbie in programming FPGA by verilog language. At the present, I am trying to design the firmware to calculate the sum of adc data at 3 sampling. Firstly, I will explain about one adc at one sampling in my code. When you look at the code, you can see that with rising-edge of clkr clock and adcIfEnb == 1, the adc_data will get the value from adcIfData and this is the data for one sampling. In the next rising-edge of clkr clock and adcIfEnb == 1, this data is stored in iradcTrg. Finally, I will have the 3 data of adc_data for 3 sampling which are stored in iradcTrg and then I summarize 3 these data.

```<code>wire adcIfData[79:0];
reg
always @(posedge clkr) begin
if(adcIfEnb) begin
adc_data[9:0] <= adcIfData[9:0];
end
end
reg [29:0] iradcTrg;
reg [9:0]  adcTrg;
always @(posedge clkr) begin
if (adcIfEnb) begin
iradcTrg[29:0] <= {adc_trg[19:10],adc_trg[9:0],adc_data[9:0]};
adcTrg[9:0] <= adc_trg[29:20] + adc_trg[19:10] + adc_trg[9:0];
end
end
</code>```

However, there are 2 problems which I do not know how to solve.

Firstly, at the beginning time, when the first data of adc_data is stored at iradcTrg and adcTrg also take the sum. It means that adcTrg = 0 + 0 + first_adc_data but this sum need to be avoided.

Secondly, according to my design, I see that adc_data is serialized into iradcTrg. It means that the adc_data will be stored like this:

[1 2 3] 4 5 6 => 1 [2 3 4] 5 6=> 1 2 [3 4 5] 6

But in my case, I would like that the adc_data will be stored like this to get the sum

[1 2 3] 4 5 6 => 1 2 3 [4 5 6]

Therefore, how should I repair my code to get the result that I expected or are there any documents can help me in this case ?

答:
Your job will be much easier if you use a state machine. Here's a small (and incomplete) example of a state machine.</p>

```<code>parameter FIRST_DATA=0, SECOND_DATA=1, THIRD_DATA=2, OUTPUT=3;
reg [2:0] current_state = FIRST_DATA;

reg [9:0] adc_data1;
reg [9:0] adc_data2;
reg [9:0] adc_data3;
reg [11:0] adc_data_sum;

always @ (posedge clk)
begin
// TODO: use proper reset
case (current_state):
FIRST_DATA:
    if(adcIfEnb):
        current_state <= SECOND_DATA;
SECOND_DATA:
    if(adcIfEnb):
        current_state <= THIRD_DATA;
THIRD_DATA:
    if(adcIfEnb):
        current_state <= OUTPUT;
OUTPUT:
    if(adcIfEnb):
        current_state <= FIRST_DATA;
endcase
end

always @ (negedge clk)
begin
    if (current_state == FIRST_DATA && adcIfEnb)
        adc_data1 <= adcIfData;
end

always @ (negedge clk)
begin
    if (current_state == SECOND_DATA && adcIfEnb)
        adc_data2 <= adcIfData;
end

always @ (negedge clk)
begin
    if (current_state == THIRD_DATA && adcIfEnb)
        adc_data3 <= adcIfData;
end

always @ (negedge clk)
begin
    if (current_state == OUTPUT)
         adc_data_sum <= adc_data1 + adc_data2 + adc_data3;
end
</code>```

Body:
Hi everyone,

I am a newbie in programming FPGA by verilog language. At the present, I am trying to design the firmware to calculate the sum of adc data at 3 sampling. Firstly, I will explain about one adc at one sampling in my code. When you look at the code, you can see that with rising-edge of clkr clock and adcIfEnb == 1, the adc_data will get the value from adcIfData and this is the data for one sampling. In the next rising-edge of clkr clock and adcIfEnb == 1, this data is stored in iradcTrg. Finally, I will have the 3 data of adc_data for 3 sampling which are stored in iradcTrg and then I summarize 3 these data.

wire adcIfData[79:0];
reg
always @(posedge clkr) begin
if(adcIfEnb) begin
adc_data[9:0] <= adcIfData[9:0];
end
end
reg [29:0] iradcTrg;
reg [9:0]  adcTrg;
always @(posedge clkr) begin
if (adcIfEnb) begin
iradcTrg[29:0] <= {adc_trg[19:10],adc_trg[9:0],adc_data[9:0]};
adcTrg[9:0] <= adc_trg[29:20] + adc_trg[19:10] + adc_trg[9:0];
end
end

However, there are 2 problems which I do not know how to solve.

Firstly, at the beginning time, when the first data of adc_data is stored at iradcTrg and adcTrg also take the sum. It means that adcTrg = 0 + 0 + first_adc_data but this sum need to be avoided.

Secondly, according to my design, I see that adc_data is serialized into iradcTrg. It means that the adc_data will be stored like this:

[1 2 3] 4 5 6 => 1 [2 3 4] 5 6=> 1 2 [3 4 5] 6

But in my case, I would like that the adc_data will be stored like this to get the sum

[1 2 3] 4 5 6 => 1 2 3 [4 5 6]

Therefore, how should I repair my code to get the result that I expected or are there any documents can help me in this case ?

Body:
Your job will be much easier if you use a state machine. Here's a small (and incomplete) example of a state machine.

parameter FIRST_DATA=0, SECOND_DATA=1, THIRD_DATA=2, OUTPUT=3;
reg [2:0] current_state = FIRST_DATA;

reg [9:0] adc_data1;
reg [9:0] adc_data2;
reg [9:0] adc_data3;
reg [11:0] adc_data_sum;

always @ (posedge clk)
begin
// TODO: use proper reset
case (current_state):
FIRST_DATA:
    if(adcIfEnb):
        current_state <= SECOND_DATA;
SECOND_DATA:
    if(adcIfEnb):
        current_state <= THIRD_DATA;
THIRD_DATA:
    if(adcIfEnb):
        current_state <= OUTPUT;
OUTPUT:
    if(adcIfEnb):
        current_state <= FIRST_DATA;
endcase
end

always @ (negedge clk)
begin
    if (current_state == FIRST_DATA && adcIfEnb)
        adc_data1 <= adcIfData;
end

always @ (negedge clk)
begin
    if (current_state == SECOND_DATA && adcIfEnb)
        adc_data2 <= adcIfData;
end

always @ (negedge clk)
begin
    if (current_state == THIRD_DATA && adcIfEnb)
        adc_data3 <= adcIfData;
end

always @ (negedge clk)
begin
    if (current_state == OUTPUT)
         adc_data_sum <= adc_data1 + adc_data2 + adc_data3;
end


问:
Bivariate Poisson Regression in R?
I found a package 'bivpois' for R which evaluates a model for two related poisson processes (for example, the number of goals by the home and the away team in a soccer game).  However, this package seems to no longer be useable in newer versions of R.

Is there a reasonable way to modify the glm() function to do a similar process, or run this older package on my new version of R?  I have found very little literature on these sorts of processes and have found very little in terms of easy implementation in other statistical packages like STATA.

Any suggestions would be much appreciated.

答: You can feel free to refer to odds modelling and testing inefficiency of sports-bookmakersas I had modified the relevant functions inside bivpois package.

Title: Bivariate Poisson Regression in R?


问:
Merging table depending on the same key
I want to merge two PHP arrays to third one and I want to depend them on the same key data. I've got data key in two arrays and I want stay with this. I want be depend on First array. I mean I load first array to final_array(), next I adding third key as ESTYMACJA from second array but to the same data from already loaded data key in final_array(). If there is no data key in final_array(), algorithm should add this key to final_array(), add WYKONANIA and copy ESTYMACJA. If it possible I would have also copied ESTYMACJA to the rest of data keys. I will show what I mean in final_array() expectation.

1st array:

```<code>$my_array=[
    ['data'=>'2017-11-27','ESTYMACJA'=>5000],
    ['data'=>'2017-11-30','ESTYMACJA'=>9000]
];
</code>```

2nd array:

```<code>$new_array=[
    ['data'=>'2017-11-01','WYKONANIA'=>3],
    ['data'=>'2017-11-02','WYKONANIA'=>10],
    ['data'=>'2017-11-03','WYKONANIA'=>303],
    ['data'=>'2017-11-04','WYKONANIA'=>327],
    ['data'=>'2017-11-05','WYKONANIA'=>652],
    ['data'=>'2017-11-06','WYKONANIA'=>812],
    ['data'=>'2017-11-07','WYKONANIA'=>817],
    ['data'=>'2017-11-08','WYKONANIA'=>870],
    ['data'=>'2017-11-09','WYKONANIA'=>1070],
    ['data'=>'2017-11-10','WYKONANIA'=>1199],
    ['data'=>'2017-11-11','WYKONANIA'=>1206],
    ['data'=>'2017-11-12','WYKONANIA'=>1220],
    ['data'=>'2017-11-13','WYKONANIA'=>1421],
    ['data'=>'2017-11-14','WYKONANIA'=>1440],
    ['data'=>'2017-11-15','WYKONANIA'=>1904],
    ['data'=>'2017-11-16','WYKONANIA'=>1910],
    ['data'=>'2017-11-17','WYKONANIA'=>1962],
    ['data'=>'2017-11-18','WYKONANIA'=>2234],
    ['data'=>'2017-11-19','WYKONANIA'=>2305],
    ['data'=>'2017-11-20','WYKONANIA'=>2325],
    ['data'=>'2017-11-21','WYKONANIA'=>2250],
    ['data'=>'2017-11-22','WYKONANIA'=>2263],
    ['data'=>'2017-11-23','WYKONANIA'=>2821],
    ['data'=>'2017-11-24','WYKONANIA'=>2890],
    ['data'=>'2017-11-25','WYKONANIA'=>3411],
    ['data'=>'2017-11-26','WYKONANIA'=>3443],
    ['data'=>'2017-11-27','WYKONANIA'=>3501],
    ['data'=>'2017-11-28','WYKONANIA'=>4032]
];
</code>```

final_array() expectation:

```<code>Array
(
    [0] => Array
        (
            [data] => 2017-11-01
            [WYKONANIA] => 3
            [ESTYMACJA] => 5000
        )

    [1] => Array
        (
            [data] => 2017-11-02
            [WYKONANIA] => 10
            [ESTYMACJA] => 5000
        )

    [2] => Array
        (
            [data] => 2017-11-03
            [WYKONANIA] => 303
            [ESTYMACJA] => 5000
        )

    [3] => Array
        (
            [data] => 2017-11-04
            [WYKONANIA] => 327
            [ESTYMACJA] => 5000
        )

    [4] => Array
        (
            [data] => 2017-11-05
            [WYKONANIA] => 652
            [ESTYMACJA] => 5000
        )

    [5] => Array
        (
            [data] => 2017-11-06
            [WYKONANIA] => 812
            [ESTYMACJA] => 5000
        )

    [6] => Array
        (
            [data] => 2017-11-07
            [WYKONANIA] => 817
            [ESTYMACJA] => 5000
        )

    [7] => Array
        (
            [data] => 2017-11-08
            [WYKONANIA] => 870
            [ESTYMACJA] => 5000
        )

    [8] => Array
        (
            [data] => 2017-11-09
            [WYKONANIA] => 1070
            [ESTYMACJA] => 5000
        )

    [9] => Array
        (
            [data] => 2017-11-10
            [WYKONANIA] => 1199
            [ESTYMACJA] => 5000
        )

    [10] => Array
        (
            [data] => 2017-11-11
            [WYKONANIA] => 1206
            [ESTYMACJA] => 5000
        )

    [11] => Array
        (
            [data] => 2017-11-12
            [WYKONANIA] => 1220
            [ESTYMACJA] => 5000
        )

    [12] => Array
        (
            [data] => 2017-11-13
            [WYKONANIA] => 1421
            [ESTYMACJA] => 5000
        )

    [13] => Array
        (
            [data] => 2017-11-14
            [WYKONANIA] => 1440
            [ESTYMACJA] => 5000
        )

    [14] => Array
        (
            [data] => 2017-11-15
            [WYKONANIA] => 1904
            [ESTYMACJA] => 5000
        )

    [15] => Array
        (
            [data] => 2017-11-16
            [WYKONANIA] => 1910
            [ESTYMACJA] => 5000
        )

    [16] => Array
        (
            [data] => 2017-11-17
            [WYKONANIA] => 1962
            [ESTYMACJA] => 5000
        )

    [17] => Array
        (
            [data] => 2017-11-18
            [WYKONANIA] => 2234
            [ESTYMACJA] => 5000
        )

    [18] => Array
        (
            [data] => 2017-11-19
            [WYKONANIA] => 2305
            [ESTYMACJA] => 5000
        )

    [19] => Array
        (
            [data] => 2017-11-20
            [WYKONANIA] => 2325
            [ESTYMACJA] => 5000
        )

    [20] => Array
        (
            [data] => 2017-11-21
            [WYKONANIA] => 2250
            [ESTYMACJA] => 5000
        )

    [21] => Array
        (
            [data] => 2017-11-22
            [WYKONANIA] => 2263
            [ESTYMACJA] => 5000
        )

    [22] => Array
        (
            [data] => 2017-11-23
            [WYKONANIA] => 2821
            [ESTYMACJA] => 5000
        )

    [23] => Array
        (
            [data] => 2017-11-24
            [WYKONANIA] => 2890
            [ESTYMACJA] => 5000
        )

    [24] => Array
        (
            [data] => 2017-11-25
            [WYKONANIA] => 3411
            [ESTYMACJA] => 5000
        )

    [25] => Array
        (
            [data] => 2017-11-26
            [WYKONANIA] => 3443
            [ESTYMACJA] => 5000
        )

    [26] => Array
        (
            [data] => 2017-11-27
            [WYKONANIA] => 3501
            **[ESTYMACJA] => 5000**
        )

    [27] => Array
        (
            [data] => 2017-11-28
            [WYKONANIA] => 4032
            [ESTYMACJA] => 5000

        )

    *[28] => Array
        (
            [data] => 2017-11-30
            [WYKONANIA] => 4032
            [ESTYMACJA] => 9000

        )
</code>```

This code is already what i've done but im stuck right now.

```<code>$x = 0;
while ($x<count($final_array))
{
    if ($new_array == null) {
    break;
    }
    else {
        for ($i = 0; $i < count($new_array); $i++) {
            if ($final_array[$x]['data'] == ($new_array[$i]['data']) {
                $final_array[$x]['WYKONANIA'] = $new_array['WYKONANIA'];
            }
            else {
                array_push($final_array, "data", $new_array[$i]['data']);
                array_push($final_array, "WYKONANIA", $new_array[$i]['WYKONANIA']);
                array_push($final_array, "ESTYMACJA", $final_array[$x]['ESTYMACJA']);
            }
        }
    }
    $x++;
}

$myArray - first array
$new_array - second array
$final_array - final array.
</code>```

答:
This will help</p>

```<code>function merge_by_keys(){
    $arr = func_get_args();
    $num = func_num_args();

    $keys = array();
    $i = 0;
    for ($i=0; $i<$num; ++$i){
        $keys = array_merge($keys, array_keys($arr[$i]));
    }
    $keys = array_unique($keys);

    $merged = array();

    foreach ($keys as $key){
        $merged[$key] = array();
        for($i=0; $i<$num; ++$i){
            $merged[$key][] = isset($arr[$i][$key]) ? $arr[$i][$key] : null;
        }
    }
    return $merged;
}
</code>```

Title: Merging table depending on the same key

Body:
I want to merge two PHP arrays to third one and I want to depend them on the same key data. I've got data key in two arrays and I want stay with this. I want be depend on First array. I mean I load first array to final_array(), next I adding third key as ESTYMACJA from second array but to the same data from already loaded data key in final_array(). If there is no data key in final_array(), algorithm should add this key to final_array(), add WYKONANIA and copy ESTYMACJA. If it possible I would have also copied ESTYMACJA to the rest of data keys. I will show what I mean in final_array() expectation.

1st array:

$my_array=[
    ['data'=>'2017-11-27','ESTYMACJA'=>5000],
    ['data'=>'2017-11-30','ESTYMACJA'=>9000]
];

2nd array:

$new_array=[
    ['data'=>'2017-11-01','WYKONANIA'=>3],
    ['data'=>'2017-11-02','WYKONANIA'=>10],
    ['data'=>'2017-11-03','WYKONANIA'=>303],
    ['data'=>'2017-11-04','WYKONANIA'=>327],
    ['data'=>'2017-11-05','WYKONANIA'=>652],
    ['data'=>'2017-11-06','WYKONANIA'=>812],
    ['data'=>'2017-11-07','WYKONANIA'=>817],
    ['data'=>'2017-11-08','WYKONANIA'=>870],
    ['data'=>'2017-11-09','WYKONANIA'=>1070],
    ['data'=>'2017-11-10','WYKONANIA'=>1199],
    ['data'=>'2017-11-11','WYKONANIA'=>1206],
    ['data'=>'2017-11-12','WYKONANIA'=>1220],
    ['data'=>'2017-11-13','WYKONANIA'=>1421],
    ['data'=>'2017-11-14','WYKONANIA'=>1440],
    ['data'=>'2017-11-15','WYKONANIA'=>1904],
    ['data'=>'2017-11-16','WYKONANIA'=>1910],
    ['data'=>'2017-11-17','WYKONANIA'=>1962],
    ['data'=>'2017-11-18','WYKONANIA'=>2234],
    ['data'=>'2017-11-19','WYKONANIA'=>2305],
    ['data'=>'2017-11-20','WYKONANIA'=>2325],
    ['data'=>'2017-11-21','WYKONANIA'=>2250],
    ['data'=>'2017-11-22','WYKONANIA'=>2263],
    ['data'=>'2017-11-23','WYKONANIA'=>2821],
    ['data'=>'2017-11-24','WYKONANIA'=>2890],
    ['data'=>'2017-11-25','WYKONANIA'=>3411],
    ['data'=>'2017-11-26','WYKONANIA'=>3443],
    ['data'=>'2017-11-27','WYKONANIA'=>3501],
    ['data'=>'2017-11-28','WYKONANIA'=>4032]
];

final_array() expectation:

Array
(
    [0] => Array
        (
            [data] => 2017-11-01
            [WYKONANIA] => 3
            [ESTYMACJA] => 5000
        )

    [1] => Array
        (
            [data] => 2017-11-02
            [WYKONANIA] => 10
            [ESTYMACJA] => 5000
        )

    [2] => Array
        (
            [data] => 2017-11-03
            [WYKONANIA] => 303
            [ESTYMACJA] => 5000
        )

    [3] => Array
        (
            [data] => 2017-11-04
            [WYKONANIA] => 327
            [ESTYMACJA] => 5000
        )

    [4] => Array
        (
            [data] => 2017-11-05
            [WYKONANIA] => 652
            [ESTYMACJA] => 5000
        )

    [5] => Array
        (
            [data] => 2017-11-06
            [WYKONANIA] => 812
            [ESTYMACJA] => 5000
        )

    [6] => Array
        (
            [data] => 2017-11-07
            [WYKONANIA] => 817
            [ESTYMACJA] => 5000
        )

    [7] => Array
        (
            [data] => 2017-11-08
            [WYKONANIA] => 870
            [ESTYMACJA] => 5000
        )

    [8] => Array
        (
            [data] => 2017-11-09
            [WYKONANIA] => 1070
            [ESTYMACJA] => 5000
        )

    [9] => Array
        (
            [data] => 2017-11-10
            [WYKONANIA] => 1199
            [ESTYMACJA] => 5000
        )

    [10] => Array
        (
            [data] => 2017-11-11
            [WYKONANIA] => 1206
            [ESTYMACJA] => 5000
        )

    [11] => Array
        (
            [data] => 2017-11-12
            [WYKONANIA] => 1220
            [ESTYMACJA] => 5000
        )

    [12] => Array
        (
            [data] => 2017-11-13
            [WYKONANIA] => 1421
            [ESTYMACJA] => 5000
        )

    [13] => Array
        (
            [data] => 2017-11-14
            [WYKONANIA] => 1440
            [ESTYMACJA] => 5000
        )

    [14] => Array
        (
            [data] => 2017-11-15
            [WYKONANIA] => 1904
            [ESTYMACJA] => 5000
        )

    [15] => Array
        (
            [data] => 2017-11-16
            [WYKONANIA] => 1910
            [ESTYMACJA] => 5000
        )

    [16] => Array
        (
            [data] => 2017-11-17
            [WYKONANIA] => 1962
            [ESTYMACJA] => 5000
        )

    [17] => Array
        (
            [data] => 2017-11-18
            [WYKONANIA] => 2234
            [ESTYMACJA] => 5000
        )

    [18] => Array
        (
            [data] => 2017-11-19
            [WYKONANIA] => 2305
            [ESTYMACJA] => 5000
        )

    [19] => Array
        (
            [data] => 2017-11-20
            [WYKONANIA] => 2325
            [ESTYMACJA] => 5000
        )

    [20] => Array
        (
            [data] => 2017-11-21
            [WYKONANIA] => 2250
            [ESTYMACJA] => 5000
        )

    [21] => Array
        (
            [data] => 2017-11-22
            [WYKONANIA] => 2263
            [ESTYMACJA] => 5000
        )

    [22] => Array
        (
            [data] => 2017-11-23
            [WYKONANIA] => 2821
            [ESTYMACJA] => 5000
        )

    [23] => Array
        (
            [data] => 2017-11-24
            [WYKONANIA] => 2890
            [ESTYMACJA] => 5000
        )

    [24] => Array
        (
            [data] => 2017-11-25
            [WYKONANIA] => 3411
            [ESTYMACJA] => 5000
        )

    [25] => Array
        (
            [data] => 2017-11-26
            [WYKONANIA] => 3443
            [ESTYMACJA] => 5000
        )

    [26] => Array
        (
            [data] => 2017-11-27
            [WYKONANIA] => 3501
            **[ESTYMACJA] => 5000**
        )

    [27] => Array
        (
            [data] => 2017-11-28
            [WYKONANIA] => 4032
            [ESTYMACJA] => 5000

        )

    *[28] => Array
        (
            [data] => 2017-11-30
            [WYKONANIA] => 4032
            [ESTYMACJA] => 9000

        )

This code is already what i've done but im stuck right now.

$x = 0;
while ($x<count($final_array))
{
    if ($new_array == null) {
    break;
    }
    else {
        for ($i = 0; $i < count($new_array); $i++) {
            if ($final_array[$x]['data'] == ($new_array[$i]['data']) {
                $final_array[$x]['WYKONANIA'] = $new_array['WYKONANIA'];
            }
            else {
                array_push($final_array, "data", $new_array[$i]['data']);
                array_push($final_array, "WYKONANIA", $new_array[$i]['WYKONANIA']);
                array_push($final_array, "ESTYMACJA", $final_array[$x]['ESTYMACJA']);
            }
        }
    }
    $x++;
}

$myArray - first array
$new_array - second array
$final_array - final array.

Body:
This will help

function merge_by_keys(){
    $arr = func_get_args();
    $num = func_num_args();

    $keys = array();
    $i = 0;
    for ($i=0; $i<$num; ++$i){
        $keys = array_merge($keys, array_keys($arr[$i]));
    }
    $keys = array_unique($keys);

    $merged = array();

    foreach ($keys as $key){
        $merged[$key] = array();
        for($i=0; $i<$num; ++$i){
            $merged[$key][] = isset($arr[$i][$key]) ? $arr[$i][$key] : null;
        }
    }
    return $merged;
}


问:
Issue with JavaScript recursive function
I have an object with nested objects. I need to get all the keys and values from all the sub objects into one array.

So I'm trying to do it with a recursive function, but I guess I'm doing something wrong...

The object :

```<code>var jsonobj = {

  "gender": "male",
  "country": "us",
  "phone": "06 12 34 56 78",
  "enterprise": {
    "parameters": {
      "company": "foo",
      "companyID": "12345678912345",
      "address": "adress principale",
     }
   },
  "contacts": [],
   "requirements": []
 }
</code>```

Here is the function :

```<code>  function check(arr){
      var val = '';
      $.each(arr, function(k, v) {
          if (typeof v == "object" && v.length !== 0) {
              val = check(v);
          }
      });

      return val;
 }
</code>```

And this is the function using it :

```<code>function rec_res(obj_res) {
    var foo=[];
    $.each(jsonobj, function(k, v) {
        if (typeof v == "object" && v.length !== 0) {
            g = check(jsonobj); // calling the function
            foo.push(g);
        } else {
            foo.push(v);
        }
    });
    console.log(foo);
};
</code>```

Expected output:

```<code> [foo:{
  "gender": "male",
  "country": "us",
  "phone": "06 12 34 56 78",
  "company": "foo",
  "companyID": "12345678912345",
  "address": "adress principale",
 }]
</code>```

Fiddle

答:
```<code>var jsonobj = {
  "gender": "male",
  "country": "us",
  "phone": "06 12 34 56 78",
  "enterprise": {
    "parameters": {
      "company": "foo",
      "companyID": "12345678912345",
      "address": "adress principale",
    }
  },
  "contacts": [],
  "requirements": []
}
var result=[];
function rec_res(obj_res) {
var foo=[];
  $.each(Object.keys(obj_res), function(k, v) {
    if (typeof obj_res[v] == "object") {

     var data = rec_res(obj_res[v]);
     if(data!=undefined && data.length!=0){
     data.map(function(d){
     result.push(d);
     });
     }
  }  else {
result.push({[v]:obj_res[v]});
foo.push({[v]:obj_res[v]});
  }
  return foo;
  });
//console.log(foo);
};
rec_res(jsonobj);
alert(JSON.stringify(result));
</code>```

Body:
I have an object with nested objects. I need to get all the keys and values from all the sub objects into one array.

So I'm trying to do it with a recursive function, but I guess I'm doing something wrong...

The object :

var jsonobj = {

  "gender": "male",
  "country": "us",
  "phone": "06 12 34 56 78",
  "enterprise": {
    "parameters": {
      "company": "foo",
      "companyID": "12345678912345",
      "address": "adress principale",
     }
   },
  "contacts": [],
   "requirements": []
 }

Here is the function :

  function check(arr){
      var val = '';
      $.each(arr, function(k, v) {
          if (typeof v == "object" && v.length !== 0) {
              val = check(v);
          }
      });

      return val;
 }

And this is the function using it :

function rec_res(obj_res) {
    var foo=[];
    $.each(jsonobj, function(k, v) {
        if (typeof v == "object" && v.length !== 0) {
            g = check(jsonobj); // calling the function
            foo.push(g);
        } else {
            foo.push(v);
        }
    });
    console.log(foo);
};

Expected output:

 [foo:{
  "gender": "male",
  "country": "us",
  "phone": "06 12 34 56 78",
  "company": "foo",
  "companyID": "12345678912345",
  "address": "adress principale",
 }]

Fiddle


问:
Microsoft Bot Framework State Management
we are updating our MBF bot to have its state managed in Azure Table Store. We changed code according to documentation to register our Table store provider:

```<code>protected void Application_Start()
{
        GlobalConfiguration.Configure(WebApiConfig.Register);
        var builder = new ContainerBuilder();
        var store = new TableBotDataStore("...");

        builder.Register(c => store)
            .Keyed<IBotDataStore<BotData>>(AzureModule.Key_DataStore)
            .AsSelf()
            .SingleInstance();

        builder.Register(c => new CachingBotDataStore(store,
                CachingBotDataStoreConsistencyPolicy
                .ETagBasedConsistency))
                .As<IBotDataStore<BotData>>()
                .AsSelf()
                .InstancePerLifetimeScope();

        var config = GlobalConfiguration.Configuration;

        var container = builder.Build();
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}
</code>```

Now, in the dialog we use following to store and load user data:

```<code>context.PrivateConversationData.SetValue<UserData>(UserDataRepositoryKey, userData);
</code>```

Interesting thing is that dialog state seems to be maintained, but we see nothing is our Azure table and I really doubt any calls are getting to that storage. The documentation is super unclear on how to use state in the right way.

Question:

Does our container registration looks correct? Should it be at the app_start or should we register it for every request?

Are we using right method to store state during the conversation?

答:
It seems that you are not updating the Conversation container. You need to use the Conversation.UpdateContainer method for that.

```<code>Conversation.UpdateContainer(
           builder =>
           {
               builder.Register(c => store)
                         .Keyed<IBotDataStore<BotData>>(AzureModule.Key_DataStore)
                         .AsSelf()
                         .SingleInstance();

               builder.Register(c => new CachingBotDataStore(store,
                          CachingBotDataStoreConsistencyPolicy
                          .ETagBasedConsistency))
                          .As<IBotDataStore<BotData>>()
                          .AsSelf()
                          .InstancePerLifetimeScope();

           });
</code>```

Docs around the topic can be found at https://learn.microsoft.com/en-us/bot-framework/dotnet/bot-builder-dotnet-state-azure-table-storage and a sample at https://github.com/Microsoft/BotBuilder-Azure/tree/master/CSharp/Samples/AzureTable.

Body:
we are updating our MBF bot to have its state managed in Azure Table Store. We changed code according to documentation to register our Table store provider:

protected void Application_Start()
{
        GlobalConfiguration.Configure(WebApiConfig.Register);
        var builder = new ContainerBuilder();
        var store = new TableBotDataStore("...");

        builder.Register(c => store)
            .Keyed<IBotDataStore<BotData>>(AzureModule.Key_DataStore)
            .AsSelf()
            .SingleInstance();

        builder.Register(c => new CachingBotDataStore(store,
                CachingBotDataStoreConsistencyPolicy
                .ETagBasedConsistency))
                .As<IBotDataStore<BotData>>()
                .AsSelf()
                .InstancePerLifetimeScope();

        var config = GlobalConfiguration.Configuration;

        var container = builder.Build();
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}

Now, in the dialog we use following to store and load user data:

context.PrivateConversationData.SetValue<UserData>(UserDataRepositoryKey, userData);

Interesting thing is that dialog state seems to be maintained, but we see nothing is our Azure table and I really doubt any calls are getting to that storage. The documentation is super unclear on how to use state in the right way.

Question:

Does our container registration looks correct? Should it be at the app_start or should we register it for every request?

Are we using right method to store state during the conversation?

Body:
It seems that you are not updating the Conversation container. You need to use the Conversation.UpdateContainer method for that.

Conversation.UpdateContainer(
           builder =>
           {
               builder.Register(c => store)
                         .Keyed<IBotDataStore<BotData>>(AzureModule.Key_DataStore)
                         .AsSelf()
                         .SingleInstance();

               builder.Register(c => new CachingBotDataStore(store,
                          CachingBotDataStoreConsistencyPolicy
                          .ETagBasedConsistency))
                          .As<IBotDataStore<BotData>>()
                          .AsSelf()
                          .InstancePerLifetimeScope();

           });

Docs around the topic can be found at https://learn.microsoft.com/en-us/bot-framework/dotnet/bot-builder-dotnet-state-azure-table-storage and a sample at https://github.com/Microsoft/BotBuilder-Azure/tree/master/CSharp/Samples/AzureTable.


问:
Destroy and recreate a jQuery Datatables
I have two jQuery datatables with server side processing. I have a checkbox where I hide and show the two tables. I would like to destroy the none displayed and create another table. How would I do this?

This is what I tried but ajax.reload does not fire.

if ($('#mode').is(':checked')) {
    Table2.ajax.reload();
    Table1.clear();
    Table1.destroy();
} else {
    Table1.ajax.reload();
    Table2.clear();
    Table2.destroy()
}

var Table1 = $('#timesheet-table').DataTable({})
var Table2 = $('#timesheet-table-2').DataTable({})
```

答:
```<code>if ($('#mode').is(':checked')) {
    Table2.ajax.reload();
    Table1.clear();
    Table1.destroy();
} else {
    Table1.ajax.reload();
    Table2.clear();
    Table2.destroy()
}

var Table1 = $('#timesheet-table').DataTable({
    ajax: "data.json";
})
var Table2 = $('#timesheet-table-2').DataTable({
    ajax: "data.json";
})
</code>```

You need to provide ajax url in order to use table.ajax.reload() method

Body:
if ($('#mode').is(':checked')) {
    Table2.ajax.reload();
    Table1.clear();
    Table1.destroy();
} else {
    Table1.ajax.reload();
    Table2.clear();
    Table2.destroy()
}

var Table1 = $('#timesheet-table').DataTable({
    ajax: "data.json";
})
var Table2 = $('#timesheet-table-2').DataTable({
    ajax: "data.json";
})

You need to provide ajax url in order to use table.ajax.reload() method


问:
How to click on specific element out of the webelements in selenium webdriver in java
If the date from the list of dates is matching with the given date which is string format then it should click on that element from that list of dates which when fetched is converted to string only.
I have list of dates like below when converted to string:

```<code>2017-10-13
2017-09-29
2017-09-22
2017-09-15
2017-09-08
2017-09-01
2017-08-25
2017-08-18
</code>```

So now if the input which is "2017-Sep-29" which when parsed to another format gives 2017-09-29 matches with the second date from the list then it should be clicked but it is throwing an error.

Below is my java code with comments :

```<code>WebDriver driver;
List<WebElement> stageListOfFilters;
String finalSnapshot = "", finalSnapshot1 = "";

@Test
public void getDateAndclick()
{
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
    try {
        Date varDate = dateFormat.parse("18-Aug-2017");
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        finalSnapshot1 = dateFormat.format(varDate).toString();
        System.out.println("Date: " + finalSnapshot1); // Prints 2017-08-18
        driver.findElement(By.xpath(config.getsnapshotFilter())).click();
        Thread.sleep(2000);
        finalSnap = finalSnapshot1.substring(5, 10);
        System.out.println("Date for final Comparison: " + finalSnap); // Prints 08-18 since i want to click on 18th august date
        stageListOfFilters = driver.findElements(By.xpath(".//*[@class='QvFrame DS']")); // This collects the list
                                                                                // of dates which is
                                                                                // fetched later on in
                                                                                // for loop
        Thread.sleep(2000);
        for (int i = 0; i < stageListOfFilters.size(); i++) {
            System.out.println(stageListOfFilters.get(i).getText());
            Thread.sleep(2000);
            if (finalSnap.contains(stageListOfFilters.get(i).getText())) {
                driver.findElement(By.xpath(".//*[@class='QvFrame DS']/div/div/div[1]/div[2]/div[" + i + "]"))
                        .click();// If it matches at that index then it should click on element present at that index
                Thread.sleep(2000);
            }
        }
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
</code>```

So now it should click on the last element since date which is being passed is 18th August but it still clicks on 2017-09-29. I figured out that I am not getting value using get(i).getText() in if loop which is under for loop. Why is it so ?

Code for getAttribute("title") data :

```<code>stageListOfFilters = driver.findElements(By.xpath(".//*[@id='DS']")); // This collects the list
                                                                                // of dates which is
                                                                                // fetched later on in
                                                                                // for loop

            for (WebElement element : stageListOfFilters) {
                System.out.println("Dates are: " + element.getAttribute("title"));
            }
</code>```

答:
If you are fetching the date value correctly using the elements then I believe the problem could be in your "if" condition. I believe the finalSnap value is "08-18" and whereas "stageListOfFilters.get(i).getText()" is fetching the date as "2017-08-18". The below "If" condition inside the for loop will be always false since you are checking if "08-18" contains "2017-08-18" or not.

```<code>if (finalSnap.contains(stageListOfFilters.get(i).getText())) { //this condition check is false

     //ur code
}
</code>```

You should be comparing "2017-08-18" with "08-18" and not the reverse way.

Body:
If the date from the list of dates is matching with the given date which is string format then it should click on that element from that list of dates which when fetched is converted to string only.
I have list of dates like below when converted to string:

2017-10-13
2017-09-29
2017-09-22
2017-09-15
2017-09-08
2017-09-01
2017-08-25
2017-08-18

So now if the input which is "2017-Sep-29" which when parsed to another format gives 2017-09-29 matches with the second date from the list then it should be clicked but it is throwing an error.

Below is my java code with comments :

WebDriver driver;
List<WebElement> stageListOfFilters;
String finalSnapshot = "", finalSnapshot1 = "";

@Test
public void getDateAndclick()
{
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
    try {
        Date varDate = dateFormat.parse("18-Aug-2017");
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        finalSnapshot1 = dateFormat.format(varDate).toString();
        System.out.println("Date: " + finalSnapshot1); // Prints 2017-08-18
        driver.findElement(By.xpath(config.getsnapshotFilter())).click();
        Thread.sleep(2000);
        finalSnap = finalSnapshot1.substring(5, 10);
        System.out.println("Date for final Comparison: " + finalSnap); // Prints 08-18 since i want to click on 18th august date
        stageListOfFilters = driver.findElements(By.xpath(".//*[@class='QvFrame DS']")); // This collects the list
                                                                                // of dates which is
                                                                                // fetched later on in
                                                                                // for loop
        Thread.sleep(2000);
        for (int i = 0; i < stageListOfFilters.size(); i++) {
            System.out.println(stageListOfFilters.get(i).getText());
            Thread.sleep(2000);
            if (finalSnap.contains(stageListOfFilters.get(i).getText())) {
                driver.findElement(By.xpath(".//*[@class='QvFrame DS']/div/div/div[1]/div[2]/div[" + i + "]"))
                        .click();// If it matches at that index then it should click on element present at that index
                Thread.sleep(2000);
            }
        }
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }

So now it should click on the last element since date which is being passed is 18th August but it still clicks on 2017-09-29. I figured out that I am not getting value using get(i).getText() in if loop which is under for loop. Why is it so ?

Code for getAttribute("title") data :

stageListOfFilters = driver.findElements(By.xpath(".//*[@id='DS']")); // This collects the list
                                                                                // of dates which is
                                                                                // fetched later on in
                                                                                // for loop

            for (WebElement element : stageListOfFilters) {
                System.out.println("Dates are: " + element.getAttribute("title"));
            }

Body:
If you are fetching the date value correctly using the elements then I believe the problem could be in your "if" condition. I believe the finalSnap value is "08-18" and whereas "stageListOfFilters.get(i).getText()" is fetching the date as "2017-08-18". The below "If" condition inside the for loop will be always false since you are checking if "08-18" contains "2017-08-18" or not.

if (finalSnap.contains(stageListOfFilters.get(i).getText())) { //this condition check is false

     //ur code
}

You should be comparing "2017-08-18" with "08-18" and not the reverse way.


问:
How to make string to json with javascript? (like A//a1,A//a2,A//a3//a31 ..)
How to convert a string to JSON with javascript or jQuery? I've been thinking all day, but I do not get a good idea.

This task is to dynamically create the treeview in the client side (ASP.Net). My idea is to convert the string to an object and convert to JSON type. (String -> object -> JSON) I tried, but the day is gone. It is difficult to construct 2 more depth like A->a3->a31.

String is

```<code>var sString = "A//a1,A//a2,A//a3//a31,A//a3//a32,B,C//c1,C//c2";
</code>```

and JSON format is

{
  "title": "A",
  "key": "1",
  "folder": true,
  "children": [{
      "title": "a1",
      "key": "2"
    }, {
      "title": "a2",
      "key": "3"
    }, {
      "title": "a3",
      "key": "4",
      "folder": true,
      "children": [{
          "title": "a31",
          "key": "5"
        }...
      }]
  }```

(This is fancytreeview plugin)

‘//‘ is depth and ‘,’ is split.

Please help me..

Edit)
I want to turn ‘sString’ to JSON format.. but It’s ok just JSON type string.

Please understand that my sentence is strange because my native language is not English.

Edit2)
oh.. I want to convert the string to an object and then convert it back to JSON format. I do not have the confidence to convert that string into JSON format right away. Because there are more than 8000 variants. If It’s can, let me know how.

答:
I believe this can be done without recursion:

var string = "A//a1,A//a2,A//a3//a31,A//a3//a32,B,C//c1,C//c2";

// Take all the roots
var roots = string.split(',');

// We will attach it to every node and keep it incrementing
var key = 1;

// The final result will be in this object
var result = [];

// Loop through to found roots
roots.forEach(function(root) {
  // Take all the children
  var items = root.split('//');
  var parent = result;

  // Loop through the available children
  items.forEach(function(item, i) {
    // Find if the current item exists in the tree
    var child = getChild(parent, item);

    if (!child) {
     child = {
        title: item,
        key: key++
      }

      // This will ensure that the current node is a folder only
      // if there are more children
      if (i < items.length - 1) {
       child.folder = true;
        child.children = [];
      }

      // Attach this node to parent
      parent.push(child);
    }

    parent = child.children;
  });
});

console.log(result);

// Utility function to find a node in a collection of nodes by title
function getChild(parent, title) {
  for (var i = 0; i < parent.length; i++) {
    if (parent[i].title === title) {
      return parent[i];
    }
  }
}```

This is the draft code which came in my mind at first. I believe it can be improved further in terms of complexity.

Body:
How to convert a string to JSON with javascript or jQuery? I've been thinking all day, but I do not get a good idea.

This task is to dynamically create the treeview in the client side (ASP.Net). My idea is to convert the string to an object and convert to JSON type. (String -> object -> JSON) I tried, but the day is gone. It is difficult to construct 2 more depth like A->a3->a31.

String is

var sString = "A//a1,A//a2,A//a3//a31,A//a3//a32,B,C//c1,C//c2";

and JSON format is

{
  "title": "A",
  "key": "1",
  "folder": true,
  "children": [{
      "title": "a1",
      "key": "2"
    }, {
      "title": "a2",
      "key": "3"
    }, {
      "title": "a3",
      "key": "4",
      "folder": true,
      "children": [{
          "title": "a31",
          "key": "5"
        }...
      }]
  }

(This is fancytreeview plugin)

‘//‘ is depth and ‘,’ is split.

Please help me..

Edit)
I want to turn ‘sString’ to JSON format.. but It’s ok just JSON type string.

Please understand that my sentence is strange because my native language is not English.

Edit2)
oh.. I want to convert the string to an object and then convert it back to JSON format. I do not have the confidence to convert that string into JSON format right away. Because there are more than 8000 variants. If It’s can, let me know how.

Body:
I believe this can be done without recursion:

var string = "A//a1,A//a2,A//a3//a31,A//a3//a32,B,C//c1,C//c2";

// Take all the roots
var roots = string.split(',');

// We will attach it to every node and keep it incrementing
var key = 1;

// The final result will be in this object
var result = [];

// Loop through to found roots
roots.forEach(function(root) {
  // Take all the children
  var items = root.split('//');
  var parent = result;

  // Loop through the available children
  items.forEach(function(item, i) {
    // Find if the current item exists in the tree
    var child = getChild(parent, item);

    if (!child) {
     child = {
        title: item,
        key: key++
      }

      // This will ensure that the current node is a folder only
      // if there are more children
      if (i < items.length - 1) {
       child.folder = true;
        child.children = [];
      }

      // Attach this node to parent
      parent.push(child);
    }

    parent = child.children;
  });
});

console.log(result);

// Utility function to find a node in a collection of nodes by title
function getChild(parent, title) {
  for (var i = 0; i < parent.length; i++) {
    if (parent[i].title === title) {
      return parent[i];
    }
  }
}

This is the draft code which came in my mind at first. I believe it can be improved further in terms of complexity.


问:
How to create a home button on Tkinter
I would like to create a home button that can be used on every window and direct me back to home, in Python without OOP.</p>

答:
This could work:</p>

```<code>import Tkinter as tk
win1 = tk.Tk()
win2 = tk.Tk()
win3 = tk.Tk()
win4 = tk.Tk()
def home_button():
    print("Home Button Pressed.")
tk.Button(win1, text="home", command=home_button).pack()
tk.Button(win2, text="home", command=home_button).pack()
tk.Button(win3, text="home", command=home_button).pack()
tk.Button(win4, text="home", command=home_button).pack()
win1.mainloop()
win2.mainloop()
win3.mainloop()
win4.mainloop()
</code>```

Title: How to create a home button on Tkinter

Body:
This could work:

import Tkinter as tk
win1 = tk.Tk()
win2 = tk.Tk()
win3 = tk.Tk()
win4 = tk.Tk()
def home_button():
    print("Home Button Pressed.")
tk.Button(win1, text="home", command=home_button).pack()
tk.Button(win2, text="home", command=home_button).pack()
tk.Button(win3, text="home", command=home_button).pack()
tk.Button(win4, text="home", command=home_button).pack()
win1.mainloop()
win2.mainloop()
win3.mainloop()
win4.mainloop()


问:
[mysql][php] Problematic join results from two tables and filtering in php
I am looking for a way to get data about the production process.
I have two tables:

production: stores product information

timeline: there are details of the employee and when he made the production step

production:

```<code>--------------------------
internal | type of closing
--------------------------
123      | close
122      | open

timeline:
------------------------------------------------
id | internal | employee | date        | step
------------------------------------------------
1  | 123      | E01      | 2017-11-11  | diag
2  | 123      | E03      | 2017-11-12  | rep
3  | 122      | E06      | 2017-11-05  | diag
</code>```

Steps from the column steps are predetermined (diag,rep,test)

I would like to get a result:

```<code>----------------------------------------------------------------------------------------
internal | diag | date_diag  | rep  | date_rep   | test  | date_test  | type of closing
----------------------------------------------------------------------------------------
123      | E01  | 2017-11-11 | E03  | 2017-11-12 | NULL  | NULL       | close
122      | E06  | 2017-11-05 | NULL | NULL       | NULL  | NULL       | open
</code>```

To filter this result later by date_rep(or)date_test(or)date_diag and type of closing (close/open).
How can this be done using Mysql and PHP? With the best performance, because the base is huge.

答:
You should use different aliases on the same table, joining the table in a way like this:

```<code>SELECT T1.internal,
       T1.employee,
       T1.date as date_diag,
       T2.employee as rep,
       T2.date as date_rep,
       NULL,
       NULL,
       P.description
FROM timeline T1
INNER JOIN production P ON T1.internal = P.internal
LEFT JOIN timeline T2 ON T1.internal = T1.internal and T2.step = 'rep'
WHERE T1.step ='diag'
</code>```

This is a starting point close enough to the solution.

Body:
I am looking for a way to get data about the production process.
I have two tables:

production: stores product information

timeline: there are details of the employee and when he made the production step

production:

--------------------------
internal | type of closing
--------------------------
123      | close
122      | open

timeline:
------------------------------------------------
id | internal | employee | date        | step
------------------------------------------------
1  | 123      | E01      | 2017-11-11  | diag
2  | 123      | E03      | 2017-11-12  | rep
3  | 122      | E06      | 2017-11-05  | diag

Steps from the column steps are predetermined (diag,rep,test)

I would like to get a result:

----------------------------------------------------------------------------------------
internal | diag | date_diag  | rep  | date_rep   | test  | date_test  | type of closing
----------------------------------------------------------------------------------------
123      | E01  | 2017-11-11 | E03  | 2017-11-12 | NULL  | NULL       | close
122      | E06  | 2017-11-05 | NULL | NULL       | NULL  | NULL       | open

To filter this result later by date_rep(or)date_test(or)date_diag and type of closing (close/open).
How can this be done using Mysql and PHP? With the best performance, because the base is huge.

Body:
You should use different aliases on the same table, joining the table in a way like this:

SELECT T1.internal,
       T1.employee,
       T1.date as date_diag,
       T2.employee as rep,
       T2.date as date_rep,
       NULL,
       NULL,
       P.description
FROM timeline T1
INNER JOIN production P ON T1.internal = P.internal
LEFT JOIN timeline T2 ON T1.internal = T1.internal and T2.step = 'rep'
WHERE T1.step ='diag'

This is a starting point close enough to the solution.


问:
How to match a regexp with receive in Erlang?
There is the following block:

```<code>receive
...
  {raw, Text} ->
      send(Socket, Text),
      master(State);
...
end.
</code>```

I am wondering if it is possible to match a regexp in Text and have a simple clause if the Text matches.

答:
You cannot use use regular expressions at all in patterns, at least not as regular expressions. Patterns have exactly the same structure as data constructors. This means that unless the regular expression is very simple and can be expressed as a pattern as in @archaelus example then there is no way to test the message without first removing it from the message queue. Then you can use the regular expression module to test the string and extract fields from it.

I don't see this changing in the foreseeable future.

Body:
There is the following block:

receive
...
  {raw, Text} ->
      send(Socket, Text),
      master(State);
...
end.

I am wondering if it is possible to match a regexp in Text and have a simple clause if the Text matches.


问:
Limiting the results by sql query
I have a ranking system, and when I pass the player_ID it will return 2 values above and below my player_id. But the problem is if the above or below player rankings are same it's returning all the values, But I need exactly five values.

My Code:

```<code> SET @rank = 1, @seq = 1, @last = null;

select ranks.rank , ranks.id, ranks.scores from (
SELECT *, @rank := if(@last = scores, @rank, @seq) AS rank, @seq := @seq + 1, @last := scores FROM testingleaderboard ORDER BY scores DESC) as ranks JOIN (

  -- find the rank of the user we want similarly
  SELECT @sd:=COUNT(id) rank
  FROM   testingleaderboard JOIN (
    -- our user's highest score
    SELECT MAX(scores) maxscore FROM testingleaderboard WHERE id = 46818
  ) userscore ON testingleaderboard.scores > userscore.maxscore

-- filter for only those who are within given range from our user's rank
) userrank ON ranks.rank BETWEEN  userrank.rank - 2  AND  userrank.rank + 3

-- sort the results
ORDER BY ranks.rank
</code>```

INPUT :

```<code>id = 46818
</code>```

RECEIVED OUTPUT:

```<code>"rank"  "id"    "scores"

"426688"    "1032909"   "6138"
"426688"    "1094298"   "6138"
"426688"    "1081638"   "6138"
"426688"    "1016393"   "6138"
"426688"    "1016503"   "6138"
"426688"    "1020950"   "6138"
"426688"    "39479" "6138"
**"426688"  "46818" "6138"**
"426688"    "29181" "6138"
"426688"    "31458" "6138"
"426688"    "33779" "6138"
"426688"    "23640" "6138"
"426688"    "4852"  "6138"
</code>```

REQUIRED OUTPUT:

```<code>"426688"    "1020950"   "6138"
"426688"    "39479" "6138"
**"426688"  "46818" "6138"**
"426688"    "29181" "6138"
"426688"    "31458" "6138"
</code>```

答:
Is this what you want?

```<code>(select tlb.*
 from testingleaderboard tlb
 where tlb.score <= (select tlb2.score from testingleaderboard tlb2 where tlb2.id = @id)
 order by (tlb.id = @id) desc, score desc
 limit 3
) union all
(select tlb.*
 from testingleaderboard tlb
 where tlb.score > (select tlb2.score from testingleaderboard tlb2 where tlb2.id = @id)
 order by score asc
 limit 2
);
</code>```

This returns two rows with a smaller or equal score, the row with the id, and two rows with a larger score.  There are some situations where this might miss rows with equal scores.  It can be tricky to figure out how to handle that situation.

Title: Limiting the results by sql query

Body:
I have a ranking system, and when I pass the player_ID it will return 2 values above and below my player_id. But the problem is if the above or below player rankings are same it's returning all the values, But I need exactly five values.

My Code:

 SET @rank = 1, @seq = 1, @last = null;

select ranks.rank , ranks.id, ranks.scores from (
SELECT *, @rank := if(@last = scores, @rank, @seq) AS rank, @seq := @seq + 1, @last := scores FROM testingleaderboard ORDER BY scores DESC) as ranks JOIN (

  -- find the rank of the user we want similarly
  SELECT @sd:=COUNT(id) rank
  FROM   testingleaderboard JOIN (
    -- our user's highest score
    SELECT MAX(scores) maxscore FROM testingleaderboard WHERE id = 46818
  ) userscore ON testingleaderboard.scores > userscore.maxscore

-- filter for only those who are within given range from our user's rank
) userrank ON ranks.rank BETWEEN  userrank.rank - 2  AND  userrank.rank + 3

-- sort the results
ORDER BY ranks.rank

INPUT :

id = 46818

RECEIVED OUTPUT:

"rank"  "id"    "scores"

"426688"    "1032909"   "6138"
"426688"    "1094298"   "6138"
"426688"    "1081638"   "6138"
"426688"    "1016393"   "6138"
"426688"    "1016503"   "6138"
"426688"    "1020950"   "6138"
"426688"    "39479" "6138"
**"426688"  "46818" "6138"**
"426688"    "29181" "6138"
"426688"    "31458" "6138"
"426688"    "33779" "6138"
"426688"    "23640" "6138"
"426688"    "4852"  "6138"

REQUIRED OUTPUT:

"426688"    "1020950"   "6138"
"426688"    "39479" "6138"
**"426688"  "46818" "6138"**
"426688"    "29181" "6138"
"426688"    "31458" "6138"

Body:
Is this what you want?

(select tlb.*
 from testingleaderboard tlb
 where tlb.score <= (select tlb2.score from testingleaderboard tlb2 where tlb2.id = @id)
 order by (tlb.id = @id) desc, score desc
 limit 3
) union all
(select tlb.*
 from testingleaderboard tlb
 where tlb.score > (select tlb2.score from testingleaderboard tlb2 where tlb2.id = @id)
 order by score asc
 limit 2
);

This returns two rows with a smaller or equal score, the row with the id, and two rows with a larger score.  There are some situations where this might miss rows with equal scores.  It can be tricky to figure out how to handle that situation.


问:
SQL Server: how to change the default value of the ONLINE property for an index?
I need to change the default value for the ONLINE option of almost all of the indexes to ON so that rebuilding an indexes with this script:

```<code>ALTER INDEX [Index1]|ALL ON [Table1] REBUILD;
</code>```

will do the same as:

```<code>ALTER INDEX [Index1]|ALL ON [Table1] REBUILD WITH (ONLINE = ON);
</code>```

I have to do it without recreating the indexes.

However, it is strange that creating an index with this script:

```<code>CREATE NONCLUSTERED INDEX [Index1] ON [Table1]
(
  [Column1] ASC
)
WITH (ONLINE = ON)
</code>```

results in an index with the ONLINE option set on OFF :-??

The fix:

Figured out that this cannot be done. The ONLINE option is not saved anywhere, it affects only the current statement that creates or rebuilds the index, even though some of the options are saved in sys.indexes table.
Not specifying ONLINE option runs the script with the default value OFF.
The fix is to update all rebuild index scripts with explicitly ONLINE option on ON and to make sure it will run on a SQL Server version that supports this (Enterprise and Developer editions) and that will rebuild online only allowed indexes.
The indexes that cannot be rebuild online are:

Disabled clustered index

Disabled indexed view

Image, ntext, text, varchar(max), nvarchar(max), varbinary(max), XML index

Columnstore index

Index on a local temp table

答:
Try this

```<code>USE [DATABASE_NAME];
GO
EXEC sp_MSforeachtable @command1="print 'rebuilding indexes in table: ?'", @command2="ALTER INDEX ALL ON ?
REBUILD WITH (ONLINE=ON)";
GO
</code>```

Note: The above script assumes that your current edition of SQL
Server supports online index rebuild. In a different case you can
modify the script to perform the index rebuild offline.

Body:
I need to change the default value for the ONLINE option of almost all of the indexes to ON so that rebuilding an indexes with this script:

ALTER INDEX [Index1]|ALL ON [Table1] REBUILD;

will do the same as:

ALTER INDEX [Index1]|ALL ON [Table1] REBUILD WITH (ONLINE = ON);

I have to do it without recreating the indexes.

However, it is strange that creating an index with this script:

CREATE NONCLUSTERED INDEX [Index1] ON [Table1]
(
  [Column1] ASC
)
WITH (ONLINE = ON)

results in an index with the ONLINE option set on OFF :-??

The fix:

Figured out that this cannot be done. The ONLINE option is not saved anywhere, it affects only the current statement that creates or rebuilds the index, even though some of the options are saved in sys.indexes table.
Not specifying ONLINE option runs the script with the default value OFF.
The fix is to update all rebuild index scripts with explicitly ONLINE option on ON and to make sure it will run on a SQL Server version that supports this (Enterprise and Developer editions) and that will rebuild online only allowed indexes.
The indexes that cannot be rebuild online are:

Disabled clustered index

Disabled indexed view

Image, ntext, text, varchar(max), nvarchar(max), varbinary(max), XML index

Columnstore index

Index on a local temp table

Body:
Try this

USE [DATABASE_NAME];
GO
EXEC sp_MSforeachtable @command1="print 'rebuilding indexes in table: ?'", @command2="ALTER INDEX ALL ON ?
REBUILD WITH (ONLINE=ON)";
GO

Note: The above script assumes that your current edition of SQL
Server supports online index rebuild. In a different case you can
modify the script to perform the index rebuild offline.


问:
In phpDoc, how do I write a class I don't know yet will be returned?
The following is code for Base.php and the class Base

```<code>/**
 * @return ?
 */
public static function withId($id, $class = __CLASS__)
{
    $instance = new $class($id);
    if ($instance->getId() == self::ID_OF_UNKNOWN_USER) {
        $instance = null;
    }
    return $instance;
}
</code>```

Other classes will extend this class. I'm using late static binding to figure out who should be created prior to calling withId() and passing the class name as $class.

The returned class could be Base or any of its children. How do I mark that in phpDoc?

答:
The returned class could be Base or any of its children. How do I mark that in phpDoc?

Straight forward.

```<code>/**
 * @return Base
 */
</code>```

Body:
The following is code for Base.php and the class Base

/**
 * @return ?
 */
public static function withId($id, $class = __CLASS__)
{
    $instance = new $class($id);
    if ($instance->getId() == self::ID_OF_UNKNOWN_USER) {
        $instance = null;
    }
    return $instance;
}

Other classes will extend this class. I'm using late static binding to figure out who should be created prior to calling withId() and passing the class name as $class.

The returned class could be Base or any of its children. How do I mark that in phpDoc?

Body:
The returned class could be Base or any of its children. How do I mark that in phpDoc?

Straight forward.

/**
 * @return Base
 */


问:
How to publish Amazon Lex Chatbot as webservice
I am able to create Amazon lex chat bot. I am also able to publish the same in Facebook messenger. Also I found sdk's for iOS and Android.

What I want is to publish lex bot as a webservice which can be called from any rest client, so that it can be integrated to any user interface with rest calls.

I heard of Javascript sdk's for publishing lex bots as service, but I am not able to find any proper documentation on this.

答:
You can use AWS API Gateway which will get the requests from your Rest Client and forward it to Lex.

Your architecture will be like:

Chat client <==> AWS API Gateway <==> AWS Lex

Check this link for details.


问:
Error when running ionic cordova run ios - seems to be related to push notification

I am trying to test cordova-plugin-firebase in my ionic v1 project.

I am getting an error when running

```<code>ionic cordova run ios
</code>```

If I run the command

```<code>ionic cordova build ios
</code>```

I don't get any error message.  Also, if I open the project in Xcode and try to run the app in a simulator(iphone 8), it successfully runs but running the app in xcode with a device (iphone 4s) connected also shows the same error when running

```<code>ionic cordova run ios.
</code>```

The error I am getting is "Automatic signing is unable to resolve an issue with the "nativeApp" target's entitlements. Automatic signing can't add the aps-environment entitlement to your provisioning profile"

I saw that one of the solution to this problem is to enable push notification under your "target > capabilities".  But I can't seem to find this option in Xcode when I'm in the project navigator.  I am currently using XCode 9.1

答:
try this both :-

Under Code Signing Identity, change iPhone Distribution to iPhone Developer for Debug section.
 push notifications :- go Target-> Capabillities and turned on push notifications.

Body:
I am trying to test cordova-plugin-firebase in my ionic v1 project.

I am getting an error when running

ionic cordova run ios

If I run the command

ionic cordova build ios

I don't get any error message.  Also, if I open the project in Xcode and try to run the app in a simulator(iphone 8), it successfully runs but running the app in xcode with a device (iphone 4s) connected also shows the same error when running

ionic cordova run ios.

The error I am getting is "Automatic signing is unable to resolve an issue with the "nativeApp" target's entitlements. Automatic signing can't add the aps-environment entitlement to your provisioning profile"

I saw that one of the solution to this problem is to enable push notification under your "target > capabilities".  But I can't seem to find this option in Xcode when I'm in the project navigator.  I am currently using XCode 9.1


问:
Can I have jQuery load a page after finishing a slide toggle?
I have a button linking to a separate page, which is inside of a panel that uses jQuery to slide open and closed. On clicking the button, I want the panel to slide closed, then have the linked page load in the main window.

Here's the code:

```<code>$("a.appLink").click(function(){
    closePanel();
});

var closePanel = function(){
    if ($(".panel").is(":visible")) {
        $(".panel").slideToggle("medium",plusMinus)
    }}
</code>```

The "plusMinus" callback is just another function that toggles a little image to indicate whether the panel can be expanded or not.

The problem is that when I click on the link, the new page loading will interrupt the panel closing animation, only allowing it to partly close before the page reloads. Is there a way to have the linked page load as a callback function after "closePanel" instead of just a regular HTML link, so the panel can have an opportunity to close completely?

Thanks a lot for any help.

答:
You'll need to cancel the click, and then change the location directly in the callback on slideToggle. Something like:

```<code>$("a.appLink").click(function(){
    closePanel(this.href); // <== Pass the `href` of the link
    return false;          // <== Cancel the click
});

var closePanel = function(href){
    if ($(".panel").is(":visible")) {
        $(".panel").slideToggle("medium",function() {
            plusMinus();
            location = href; // <== Navigate to the link
        });
    }
    else {
        location = href;     // <== If it makes sense to do the navigation anyway
    }
};
...
</code>```

Somewhat off-topic, but: Note that by doing this, you'll be breaking Shift+Click, Ctrl+Click, etc., because you'll be cancelling the action they activate, and replacing it with your own action instead. You have to ask yourself whether the user experience you provide is appropriate and worth doing that.

Body:
I have a button linking to a separate page, which is inside of a panel that uses jQuery to slide open and closed. On clicking the button, I want the panel to slide closed, then have the linked page load in the main window.

Here's the code:

$("a.appLink").click(function(){
    closePanel();
});

var closePanel = function(){
    if ($(".panel").is(":visible")) {
        $(".panel").slideToggle("medium",plusMinus)
    }}

The "plusMinus" callback is just another function that toggles a little image to indicate whether the panel can be expanded or not.

The problem is that when I click on the link, the new page loading will interrupt the panel closing animation, only allowing it to partly close before the page reloads. Is there a way to have the linked page load as a callback function after "closePanel" instead of just a regular HTML link, so the panel can have an opportunity to close completely?

Thanks a lot for any help.

Body:
You'll need to cancel the click, and then change the location directly in the callback on slideToggle. Something like:

$("a.appLink").click(function(){
    closePanel(this.href); // <== Pass the `href` of the link
    return false;          // <== Cancel the click
});

var closePanel = function(href){
    if ($(".panel").is(":visible")) {
        $(".panel").slideToggle("medium",function() {
            plusMinus();
            location = href; // <== Navigate to the link
        });
    }
    else {
        location = href;     // <== If it makes sense to do the navigation anyway
    }
};
...

Somewhat off-topic, but: Note that by doing this, you'll be breaking Shift+Click, Ctrl+Click, etc., because you'll be cancelling the action they activate, and replacing it with your own action instead. You have to ask yourself whether the user experience you provide is appropriate and worth doing that.