问:
How to clear all bits above a certain bit position in Javascript
I have a bit manipulation question in Javascript.

I have a number that I need to clear some upper bits from. Which exact bits need to be cleared is determined programmatically and as a result of some calculation, I have two pieces of information, a bit position and a mask for that particular bit position.  What I want to do is to clear all the bits above that bit position (not include that bit) in my value.

So, if my value is:

```<code> 0b11111111
</code>```

And, a calculation has yielded bit position 3 and a mask for that bit position:

```<code> 0b00000100
</code>```

I want to mask out or clear the bits above that bit position 3 in my value and end up with:

```<code> 0b00000111
</code>```

As a reminder, the bit position that I want to clear above is programmatically determined and could be any bit position so I can't just code a pre-defined mask.  How would I do that?  Programming environment is Javascript in node.js.

答:
```<code> value & ((mask << 1) - 1)
</code>```

In the example given, 100 leftshifted by 1 will be 1000 (8) minus one will be 111 (7). value & 111 will clear all bits except the last three. Might not work with more than 30 bits. If 31 bits are needed, one could also use a very similar formula:

```<code>value & (mask * 2 - 1)
</code>```

The logic is pretty much the same, but as the multiplication gets performed on a 52 bit mantissa, you get one bit more.

Body:
I have a bit manipulation question in Javascript.

I have a number that I need to clear some upper bits from. Which exact bits need to be cleared is determined programmatically and as a result of some calculation, I have two pieces of information, a bit position and a mask for that particular bit position.  What I want to do is to clear all the bits above that bit position (not include that bit) in my value.

So, if my value is:

 0b11111111

And, a calculation has yielded bit position 3 and a mask for that bit position:

 0b00000100

I want to mask out or clear the bits above that bit position 3 in my value and end up with:

 0b00000111

As a reminder, the bit position that I want to clear above is programmatically determined and could be any bit position so I can't just code a pre-defined mask.  How would I do that?  Programming environment is Javascript in node.js.

Body:
 value & ((mask << 1) - 1)

In the example given, 100 leftshifted by 1 will be 1000 (8) minus one will be 111 (7). value & 111 will clear all bits except the last three. Might not work with more than 30 bits. If 31 bits are needed, one could also use a very similar formula:

value & (mask * 2 - 1)

The logic is pretty much the same, but as the multiplication gets performed on a 52 bit mantissa, you get one bit more.


来源: stackexchange

问:
Python why does my variable leap_counter return the UnboundLocalError error message?
I have the following function to simulate a biochemical system over time. The idea behind the code is to sample time steps then add them to current time.

I have a globally defined start time: tao = 0.0

and the following function:

```<code>def gillespie_tau_leaping(propensity_calc, popul_num, popul_num_all, tao_all, rxn_vector, tao, epsi):
    t = simulation_timer()
    t.start()
    while tao < tmax:
        evaluate_propensity = propensity_calc(LHS, popul_num, stoch_rate)
        a0 = (sum(propensity))  # a0 is a numpy.float64
        if a0 == 0.0:
            break
        if popul_num.any() < 0: # This isnt working
            print("Number of molecules {} is too small for reaction to fire".format(popul_num))
            break
        # code equation 26 here!
        for x in range(len(popul_num)):
            # equation 22:
            expctd_net_change = a0*state_change_array[x]
            # equation 24:
            part_diff = derivative(evaluate_propensity, popul_num[x])
            # find the partial derivative of propensity with respect to popul_num (number of discrete molecules)
        # need to find a a way to SELECT delta_t before I can code it!
        # equation 26:
        t_step = epsi*a0 / sum(expctd_net_change*part_diff)
        delta_t = optimize.fmin(t_step, 0.00012)
        print (delta_t)
        lam = (evaluate_propensity*delta_t)
        rxn_vector = np.random.poisson(lam) # probability of a reaction firing in the given time period
        if tao + delta_t > tmax:
            break
        tao = tao + delta_t
        leap_counter = tao / delta_t
        if tao >= 2/a0:     # if tao is big enough
            for j in range(len(rxn_vector)):
                state_change_lambda = np.squeeze(np.asarray(state_change_array[j])*rxn_vector[j])
                #new_propensity = evaluate_propensity
                propensity_check = evaluate_propensity.copy()
                propensity_check[0] += state_change_lambda[0]
                propensity_check[1:] += state_change_lambda
                for n in range(len(propensity_check)):
                    if propensity_check[n] - evaluate_propensity[n] >= epsi*a0:
                        print("The value of delta_t {} choosen is too large".format(delta_t))
                        break
                    else:
                        popul_num = popul_num + state_change_lambda
                        popul_num_all.append(popul_num)
                        tao_all.append(tao)
        else:
            t = np.random.exponential(1/a0)
            rxn_probability = evaluate_propensity / a0
            num_rxn = np.arange(rxn_probability.size)
            if tao + t > tmax:
                tao = tmax
                break
            j = stats.rv_discrete(values=(num_rxn, rxn_probability)).rvs()
            tao = tao + t
            popul_num = popul_num + np.squeeze(np.asarray(state_change_array[j]))
            popul_num_all.append(popul_num)
            tao_all.append(tao)
    print("tao:\n", tao)
    print("Molecule numbers:\n", popul_num)
    print("Number of leaps taken:\n", leap_counter)
    t.stop()
    return popul_num_all.append(popul_num), tao_all.append(tao)
</code>```

print(gillespie_tau_leaping(propensity_calc, popul_num, popul_num_all, tao_all, rxn_vector, tao, epsi))

Only I get the error: UnboundLocalError: local variable 'leap_counter' referenced before assignment
When trying to print, or return the number of time steps taken during the simulation, saved in the variable leap_counter and I don't know why. I've tried to change the indentation a bit but that doesn't work. Whats going on and how do I fix it?

EDIT: The following code specifies the value of delta_t in the global environment. I've tried to update it above so I calculate the value of delta_t on each iteration. But then I ran into the problem with the leap counter.

```<code>def gillespie_tau_leaping(propensity_calc, popul_num, popul_num_all, tao_all, rxn_vector, tao, delta_t, epsi):
    t = simulation_timer()
    t.start()
    while tao < tmax:
        propensity = propensity_calc(LHS, popul_num, stoch_rate)
        print("propensity:\n", type(propensity))
        a0 = (sum(propensity))
        if a0 == 0.0:
            break
        # if reaction cannot fire corresponding element in rxn_vector should be zero --> tau leaping method
        if popul_num.any() < 0:
            print("Number of molecules {} is too small for reaction to fire".format(popul_num))
            break
        lam = (propensity_calc(LHS, popul_num, stoch_rate)*delta_t)
        rxn_vector = np.random.poisson(lam)
        if tao + delta_t > tmax:
            break
        tao += delta_t
        print("tao:\n", tao)
        print("Molecule numbers:\n", popul_num)
        # divide tao by delta_t to calculate number of leaps
        leap_counter = tao / delta_t
        if tao >= 2/a0:
            for j in range(len(rxn_vector)):
                state_change_lambda = np.squeeze(np.asarray(state_change_array[j])*rxn_vector[j])
                popul_num = popul_num + state_change_lambda
                new_propensity = propensity_calc(LHS, popul_num, stoch_rate)
            for n in range(len(new_propensity)):
                propensity_check = propensity + state_change_lambda
                if propensity_check[n] - new_propensity[n] >= epsi*a0:
                    print("The value of delta_t {} choosen is too large".format(delta_t))
                    break
                else:
                    popul_num = popul_num + state_change_lambda
                    popul_num_all.append(popul_num)
                    tao_all.append(tao)
        else:
            next_t = np.random.exponential(1/a0)
            rxn_probability = propensity / a0
            num_rxn = np.arange(rxn_probability.size)
            if tao + next_t > tmax:
                tao = tmax
                break
            j = stats.rv_discrete(values=(num_rxn, rxn_probability)).rvs()
            tao = tao + next_t
            popul_num = popul_num + np.squeeze(np.asarray(state_change_array[j]))
    t.stop()
    return popul_num_all.append(popul_num), tao_all.append(tao), leap_counter
</code>```

This code works exactly as I want it to, and what i cant understand is the first function all of a sudden doesnt

Cheers

答: leap_counter is visible (and thus accessible) only inside while loop, try creating it outside the loop (with a reasonable default, preferably).

ContentLicense: CC BY-SA 4.0

Body:
I have the following function to simulate a biochemical system over time. The idea behind the code is to sample time steps then add them to current time.

I have a globally defined start time: tao = 0.0

and the following function:

def gillespie_tau_leaping(propensity_calc, popul_num, popul_num_all, tao_all, rxn_vector, tao, epsi):
    t = simulation_timer()
    t.start()
    while tao < tmax:
        evaluate_propensity = propensity_calc(LHS, popul_num, stoch_rate)
        a0 = (sum(propensity))  # a0 is a numpy.float64
        if a0 == 0.0:
            break
        if popul_num.any() < 0: # This isnt working
            print("Number of molecules {} is too small for reaction to fire".format(popul_num))
            break
        # code equation 26 here!
        for x in range(len(popul_num)):
            # equation 22:
            expctd_net_change = a0*state_change_array[x]
            # equation 24:
            part_diff = derivative(evaluate_propensity, popul_num[x])
            # find the partial derivative of propensity with respect to popul_num (number of discrete molecules)
        # need to find a a way to SELECT delta_t before I can code it!
        # equation 26:
        t_step = epsi*a0 / sum(expctd_net_change*part_diff)
        delta_t = optimize.fmin(t_step, 0.00012)
        print (delta_t)
        lam = (evaluate_propensity*delta_t)
        rxn_vector = np.random.poisson(lam) # probability of a reaction firing in the given time period
        if tao + delta_t > tmax:
            break
        tao = tao + delta_t
        leap_counter = tao / delta_t
        if tao >= 2/a0:     # if tao is big enough
            for j in range(len(rxn_vector)):
                state_change_lambda = np.squeeze(np.asarray(state_change_array[j])*rxn_vector[j])
                #new_propensity = evaluate_propensity
                propensity_check = evaluate_propensity.copy()
                propensity_check[0] += state_change_lambda[0]
                propensity_check[1:] += state_change_lambda
                for n in range(len(propensity_check)):
                    if propensity_check[n] - evaluate_propensity[n] >= epsi*a0:
                        print("The value of delta_t {} choosen is too large".format(delta_t))
                        break
                    else:
                        popul_num = popul_num + state_change_lambda
                        popul_num_all.append(popul_num)
                        tao_all.append(tao)
        else:
            t = np.random.exponential(1/a0)
            rxn_probability = evaluate_propensity / a0
            num_rxn = np.arange(rxn_probability.size)
            if tao + t > tmax:
                tao = tmax
                break
            j = stats.rv_discrete(values=(num_rxn, rxn_probability)).rvs()
            tao = tao + t
            popul_num = popul_num + np.squeeze(np.asarray(state_change_array[j]))
            popul_num_all.append(popul_num)
            tao_all.append(tao)
    print("tao:\n", tao)
    print("Molecule numbers:\n", popul_num)
    print("Number of leaps taken:\n", leap_counter)
    t.stop()
    return popul_num_all.append(popul_num), tao_all.append(tao)

print(gillespie_tau_leaping(propensity_calc, popul_num, popul_num_all, tao_all, rxn_vector, tao, epsi))

Only I get the error: UnboundLocalError: local variable 'leap_counter' referenced before assignment
When trying to print, or return the number of time steps taken during the simulation, saved in the variable leap_counter and I don't know why. I've tried to change the indentation a bit but that doesn't work. Whats going on and how do I fix it?

EDIT: The following code specifies the value of delta_t in the global environment. I've tried to update it above so I calculate the value of delta_t on each iteration. But then I ran into the problem with the leap counter.

def gillespie_tau_leaping(propensity_calc, popul_num, popul_num_all, tao_all, rxn_vector, tao, delta_t, epsi):
    t = simulation_timer()
    t.start()
    while tao < tmax:
        propensity = propensity_calc(LHS, popul_num, stoch_rate)
        print("propensity:\n", type(propensity))
        a0 = (sum(propensity))
        if a0 == 0.0:
            break
        # if reaction cannot fire corresponding element in rxn_vector should be zero --> tau leaping method
        if popul_num.any() < 0:
            print("Number of molecules {} is too small for reaction to fire".format(popul_num))
            break
        lam = (propensity_calc(LHS, popul_num, stoch_rate)*delta_t)
        rxn_vector = np.random.poisson(lam)
        if tao + delta_t > tmax:
            break
        tao += delta_t
        print("tao:\n", tao)
        print("Molecule numbers:\n", popul_num)
        # divide tao by delta_t to calculate number of leaps
        leap_counter = tao / delta_t
        if tao >= 2/a0:
            for j in range(len(rxn_vector)):
                state_change_lambda = np.squeeze(np.asarray(state_change_array[j])*rxn_vector[j])
                popul_num = popul_num + state_change_lambda
                new_propensity = propensity_calc(LHS, popul_num, stoch_rate)
            for n in range(len(new_propensity)):
                propensity_check = propensity + state_change_lambda
                if propensity_check[n] - new_propensity[n] >= epsi*a0:
                    print("The value of delta_t {} choosen is too large".format(delta_t))
                    break
                else:
                    popul_num = popul_num + state_change_lambda
                    popul_num_all.append(popul_num)
                    tao_all.append(tao)
        else:
            next_t = np.random.exponential(1/a0)
            rxn_probability = propensity / a0
            num_rxn = np.arange(rxn_probability.size)
            if tao + next_t > tmax:
                tao = tmax
                break
            j = stats.rv_discrete(values=(num_rxn, rxn_probability)).rvs()
            tao = tao + next_t
            popul_num = popul_num + np.squeeze(np.asarray(state_change_array[j]))
    t.stop()
    return popul_num_all.append(popul_num), tao_all.append(tao), leap_counter

This code works exactly as I want it to, and what i cant understand is the first function all of a sudden doesnt

Cheers


问:
Node.JS Pyshell crashes on second message to Python, [ERR_STREAM_WRITE_AFTER_END]: write after end
I have a Node.JS server that sends messages to a Python script using Pyshell.send

When Pyshell returns a message using print Node.JS recieves it using pyshell.on and then reads out the returned message.

When this is then done again with a second message it crashes with the error:

```<code>Error [ERR_STREAM_WRITE_AFTER_END]: write after end
    at writeAfterEnd (_stream_writable.js:243:12)
    at Socket.Writable.write (_stream_writable.js:291:5)
    at PythonShell.send (/Users/maxkenney/Desktop/nodeLanguageProcessing/node_modules/python-shell/index.js:285:20)
    at Namespace.<anonymous> (/Users/maxkenney/Desktop/nodeLanguageProcessing/app.js:87:10)
    at Namespace.emit (events.js:189:13)
    at Namespace.emit (/Users/maxkenney/Desktop/nodeLanguageProcessing/node_modules/socket.io/lib/namespace.js:213:10)
    at /Users/maxkenney/Desktop/nodeLanguageProcessing/node_modules/socket.io/lib/namespace.js:181:14
    at process._tickCallback (internal/process/next_tick.js:61:11)
Emitted 'error' event at:
    at writeAfterEnd (_stream_writable.js:245:10)
    at Socket.Writable.write (_stream_writable.js:291:5)
    [... lines matching original stack trace ...]
    at process._tickCallback (internal/process/next_tick.js:61:11)
</code>```

I believe it could possibly be because the Python shell is closed after one message but I am unsure. Any help would be greatly appreciated!

Node.JS Script (relevant parts)

```<code>
let pyshell = new PythonShell('my_script.py');

pyshell.on('message', function(message){
    console.log("python said: " + message);
});

pyshell.send("This is a test entry").end(function(err){
        if(err) handleError(err);
});

</code>```

That last pyshell.send is repeated later on and it crashes.

Python Script:

```<code>
import sys
import spacy
import nltk

nlp = spacy.load("en_core_web_sm");

def convertGeneratorObjectToListOfString(generatorObject):
    list = []

    for item in generatorObject:
        list.append(str(item))

    return list

def main():

    #doc = nlp(sys.argv[1])
    doc = nlp(sys.stdin.readline())

    # Return the printed message to Node
    jsonObjectToReturn = {}

    for token in doc:
        dependents = token.children
        listOfChildrenTag = []

        for d in dependents:
            listOfChildrenTag.append(d.dep_)
        jsonObjectToReturn[token.text] = {
            "text": token.text,
            "lemma": token.lemma_,
            "tag": token.tag_,
            "dep": token.dep_,
            "dependencies": convertGeneratorObjectToListOfString(token.children),
            "dependenciesTag": listOfChildrenTag
        }

    print(jsonObjectToReturn)

if __name__ == '__main__':
    main()
</code>```

I have included all python code here as I am unsure but I believe the issue could also be caused by the fact that the Python script closes once the main finishes. Apologies I am unfamiliar with running constant python scripts.

答:
When you call .end() you close the stream so it cannot be used any more. So, don't call .end() until you're done with the stream.   You can call .send() without calling .end().

if you also need to monitor when the python script ends, you can use the childProcess property of the pyshell object.

```<code>let pyshell = new PythonShell('my_script.py');
pyshell.childProcess.on('exit', (code) => {
    console.log(`python program ended with exit code: ${code}`);
});
</code>```

Body:
I have a Node.JS server that sends messages to a Python script using Pyshell.send

When Pyshell returns a message using print Node.JS recieves it using pyshell.on and then reads out the returned message.

When this is then done again with a second message it crashes with the error:

Error [ERR_STREAM_WRITE_AFTER_END]: write after end
    at writeAfterEnd (_stream_writable.js:243:12)
    at Socket.Writable.write (_stream_writable.js:291:5)
    at PythonShell.send (/Users/maxkenney/Desktop/nodeLanguageProcessing/node_modules/python-shell/index.js:285:20)
    at Namespace.<anonymous> (/Users/maxkenney/Desktop/nodeLanguageProcessing/app.js:87:10)
    at Namespace.emit (events.js:189:13)
    at Namespace.emit (/Users/maxkenney/Desktop/nodeLanguageProcessing/node_modules/socket.io/lib/namespace.js:213:10)
    at /Users/maxkenney/Desktop/nodeLanguageProcessing/node_modules/socket.io/lib/namespace.js:181:14
    at process._tickCallback (internal/process/next_tick.js:61:11)
Emitted 'error' event at:
    at writeAfterEnd (_stream_writable.js:245:10)
    at Socket.Writable.write (_stream_writable.js:291:5)
    [... lines matching original stack trace ...]
    at process._tickCallback (internal/process/next_tick.js:61:11)

I believe it could possibly be because the Python shell is closed after one message but I am unsure. Any help would be greatly appreciated!

Node.JS Script (relevant parts)

let pyshell = new PythonShell('my_script.py');

pyshell.on('message', function(message){
    console.log("python said: " + message);
});

pyshell.send("This is a test entry").end(function(err){
        if(err) handleError(err);
});

That last pyshell.send is repeated later on and it crashes.

Python Script:

import sys
import spacy
import nltk

nlp = spacy.load("en_core_web_sm");

def convertGeneratorObjectToListOfString(generatorObject):
    list = []

    for item in generatorObject:
        list.append(str(item))

    return list

def main():

    #doc = nlp(sys.argv[1])
    doc = nlp(sys.stdin.readline())

    # Return the printed message to Node
    jsonObjectToReturn = {}

    for token in doc:
        dependents = token.children
        listOfChildrenTag = []

        for d in dependents:
            listOfChildrenTag.append(d.dep_)
        jsonObjectToReturn[token.text] = {
            "text": token.text,
            "lemma": token.lemma_,
            "tag": token.tag_,
            "dep": token.dep_,
            "dependencies": convertGeneratorObjectToListOfString(token.children),
            "dependenciesTag": listOfChildrenTag
        }

    print(jsonObjectToReturn)

if __name__ == '__main__':
    main()

I have included all python code here as I am unsure but I believe the issue could also be caused by the fact that the Python script closes once the main finishes. Apologies I am unfamiliar with running constant python scripts.

Body:
When you call .end() you close the stream so it cannot be used any more. So, don't call .end() until you're done with the stream.   You can call .send() without calling .end().

if you also need to monitor when the python script ends, you can use the childProcess property of the pyshell object.

let pyshell = new PythonShell('my_script.py');
pyshell.childProcess.on('exit', (code) => {
    console.log(`python program ended with exit code: ${code}`);
});


问:
Find unused CSS rule and js script in a web project?
HI..
My project has many CSS roles and JavaScript scripts that are not used in my project. How can I find these unused files?</p>

答:
There is a nice little firefox plugin called Dust Me Selectors, which scans a page for CSS which isn't being used.

It's a very good tool for spotting things in your stylesheets which are redundant.

However, you still need to be careful with it, as it is quite possible for a stylesheet to be unused when you run the program, but still necessary for your site - ie it could be used for dynamic content, or for other pages which share the same stylesheet code, etc.

[EDIT]

I've removed my previous edit where I noted that this project might have been abandoned, because in fact it looks like it's back in active development. Good news all round.

ContentLicense: CC BY-SA 3.0


问:
Stop the 'Ding' when pressing Enter
I have a very simple Windows Forms Application. And, in Windows (or, atleast Windows Forms Applications), when you press Enter while inside a Single-line TextBox Control, you hear a Ding. It's an unpleasent sound, that indicated you cannot enter a newline, because it is a single-line TextBox.

This is all fine. However, in my Form, I have 1 TextBox, and a Search Button. And I am allowing the user to Perform a search by pressing Enter after they've finished typing, so they don't have to use the mouse to click the Search Button.

But this Ding sound occurs. It's very annoying.

How can we make it so just that sound doesn't play at all in my Form?

@David H - Here's how I'm detecting the enter pressing:

```<code>private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        // Perform search now.
    }
}
</code>```

答: i changed the textbox properties for an multiline textbox and it works for me.</p>

Title: Stop the 'Ding' when pressing Enter

Body:
I have a very simple Windows Forms Application. And, in Windows (or, atleast Windows Forms Applications), when you press Enter while inside a Single-line TextBox Control, you hear a Ding. It's an unpleasent sound, that indicated you cannot enter a newline, because it is a single-line TextBox.

This is all fine. However, in my Form, I have 1 TextBox, and a Search Button. And I am allowing the user to Perform a search by pressing Enter after they've finished typing, so they don't have to use the mouse to click the Search Button.

But this Ding sound occurs. It's very annoying.

How can we make it so just that sound doesn't play at all in my Form?

@David H - Here's how I'm detecting the enter pressing:

private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        // Perform search now.
    }
}


问:
How to flip two words in a string, Java
So say I have a string called x that = "Hello world". I want to somehow make it so that it will flip those two words and instead display "world Hello". I am not very good with loops or arrays and obviously am a beginner. Could I accomplish this somehow by splitting my string? If so, how? If not, how could I do this? Help would be appreciated, thanks!</p>

答:
Just use this method, call it and pass the string that you want to split out </p>

```<code>static String reverseWords(String str) {

    // Specifying the pattern to be searched
    Pattern pattern = Pattern.compile("\\s");

    // splitting String str with a pattern
    // (i.e )splitting the string whenever their
    //  is whitespace and store in temp array.
    String[] temp = pattern.split(str);
    String result = "";

    // Iterate over the temp array and store
    // the string in reverse order.
    for (int i = 0; i < temp.length; i++) {
        if (i == temp.length - 1) {
            result = temp[i] + result;
        } else {
            result = " " + temp[i] + result;
        }
    }
    return result;
}
</code>```

Title: How to flip two words in a string, Java

Body:
Just use this method, call it and pass the string that you want to split out

static String reverseWords(String str) {

    // Specifying the pattern to be searched
    Pattern pattern = Pattern.compile("\\s");

    // splitting String str with a pattern
    // (i.e )splitting the string whenever their
    //  is whitespace and store in temp array.
    String[] temp = pattern.split(str);
    String result = "";

    // Iterate over the temp array and store
    // the string in reverse order.
    for (int i = 0; i < temp.length; i++) {
        if (i == temp.length - 1) {
            result = temp[i] + result;
        } else {
            result = " " + temp[i] + result;
        }
    }
    return result;
}


问:
An existing connection was forcibly closed by the remote host - Error on client computer
I upgraded the environment for a client app which was developed on windows xp 32 bits to windows 10 with 64 bits.

The app is a client for a remote sql server, and it is based on wpf services. The server computer was also upgraded recently to Windows 7 with 64 bits system.

The app seems to work fine, but upon sending data to the server, I get the error:

Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host.
       Inner exception: An existing connection was forcibly closed by the remote host.

Stack Trace

at System.Net.Sockets.NetworkStream.BeginWrite(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state).`

I tried installing different versions of dotnet framework, enabling tcp connections on the client computer, enabling connection on the firewall of the server and more.
What else can possibly cause this error?

答:
This must be a TLS issue. Add this line before you send data to an external server to force TLS version that must be used for the connection</p>

```<code>System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
</code>```

Body:
This must be a TLS issue. Add this line before you send data to an external server to force TLS version that must be used for the connection

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;


问:
How to add validation rules to Antd Form.List
I have a form which contains a Form.List. It will be used to add songs to an album.

I want to make sure that an album contains at least one song, but Form.List only has the props name and children.

How can I validate this?

Thanks

答:
make a condition to see if the album contains at least one song.
If not, Do not render the form.list
If yes, render the form.list</p>


问:
Learning about DB2 triggers
Hi I am trying to figure out the syntax for triggers. I have two tables one called tagged_in and the other notification. So I want to make a trigger where when an insert is called in tagged_in I want to insert a tuple in notification.</p>

答:
Something like this</p>

```<code>CREATE TRIGGER TEST_TRIGGER
     AFTER INSERT ON TAGGED_IN
     REFERENCING NEW AS NEW_TAG
     FOR EACH ROW
     BEGIN ATOMIC
       INSERT INTO NOTIFICATION
         VALUES (NEW_TAG.FIELD1,NEW_TAG.FIELD2);
     END
</code>```

Title: Learning about DB2 triggers

Body:
Something like this

CREATE TRIGGER TEST_TRIGGER
     AFTER INSERT ON TAGGED_IN
     REFERENCING NEW AS NEW_TAG
     FOR EACH ROW
     BEGIN ATOMIC
       INSERT INTO NOTIFICATION
         VALUES (NEW_TAG.FIELD1,NEW_TAG.FIELD2);
     END


问:
How to add an additional endpoint to the AWS Amplify Express Server?
I've generated an REST express server with Amplify.

I tried adding to more endpoints to it:

```<code>// using serverless express
app.post('/myendpoint', function(req, res) {
  console.log('body: ', req.body)
  res.json(req.body)
});

// using serverless express
app.get('/myendpoint', function(req, res) {
  res.json({success: 'get call to my endpoint succeed!', url: req.url});
});

</code>```

After running amplify push I don't see these endpoints in the console, and I can't make requests to them via amplify.

The endpoints that were generated as part of the initial configuration work.

What is the correct way to add more REST endpoints?  I have a feeling that I'm missing some additional configuration step.

答:
As Kevin Le stated running "amplify update api" will allow you to add another "root" path such as "/items" or "/customers", but I have been running into problems adding nested paths such as "/customer/addAddress" after the initial api creation.

What I have tried:

I can add them during the initial creation of the API, but not during an update

I can change the cloud formation template to include them in the API gateway, but any calls to the nested path are picked up by the root paths proxy.

I can add them in the express lambda function ( defeats the purpose of API Gateway )

They need to add a few enhancements to amplify rest API so we can take advantage of the API Gateway.  It's not truly serverless until we can separate functions for GET, POST, PUT, etc.

UPDATE:  I wanted to follow up after futher investigation.  A solution I found is to remove the "root" path's {proxy} endpoint in the cloud formation file for the API gateway.  The file should be located at:  "project root"/amplify/backend/api/"api name"/"api name"-cloudformation-template.json.  Then remove the path located at Resources->"api name"->Properties->Body->paths->"api name"/{proxy+}.

FURTHER INVESTIGATION:  I have not tried this yet, but the order of the path's in the cloud formation file might have an affect on how the requests are processed, so if you move the "root" proxy to the last path, you might not have to remove it.  Also thanks to Piotr for fixing my poor grammar!

Body:
I've generated an REST express server with Amplify.

I tried adding to more endpoints to it:

// using serverless express
app.post('/myendpoint', function(req, res) {
  console.log('body: ', req.body)
  res.json(req.body)
});

// using serverless express
app.get('/myendpoint', function(req, res) {
  res.json({success: 'get call to my endpoint succeed!', url: req.url});
});

After running amplify push I don't see these endpoints in the console, and I can't make requests to them via amplify.

The endpoints that were generated as part of the initial configuration work.

What is the correct way to add more REST endpoints?  I have a feeling that I'm missing some additional configuration step.


问:
converting object to int of a large dataframe
how can I convert a large dataframe of a column from object to int.

Dataframe :

```<code>user
1101110110100
1111222555555
1112223365556
1113656560005
asaseee"
tdyhhdy"

dtype: object
</code>```

expected:

```<code>user
1101110110100
1111222555555
1112223365556
1113656560005

dtype: int64
</code>```

I have used the below codes.

```<code>df['user'].astype(int)
df['user'].astype(str).astpe(int)
</code>```

答:
```<code>df['user'] = pd.to_numeric(df['user'], errors='coerce').fillna(0)
</code>```

This is working fine.. I have tried for one problem which I have faced
it's convert object into float

Body:
how can I convert a large dataframe of a column from object to int.

Dataframe :

user
1101110110100
1111222555555
1112223365556
1113656560005
asaseee"
tdyhhdy"

dtype: object

expected:

user
1101110110100
1111222555555
1112223365556
1113656560005

dtype: int64

I have used the below codes.

df['user'].astype(int)
df['user'].astype(str).astpe(int)

Body:
df['user'] = pd.to_numeric(df['user'], errors='coerce').fillna(0)

This is working fine.. I have tried for one problem which I have faced
it's convert object into float


问:
SB Admin Laravel 5 line chart data
Am using the following package. There is a chart displayed in resources/views/mcharts.blade.php. The code is the following;

```<code>@section ('cchart1_panel_title','Line Chart')
            @section ('cchart1_panel_body')
            @include('widgets.charts.clinechart')
            @endsection
            @include('widgets.panel', array('header'=>true, 'as'=>'cchart1'))
</code>```

So this code refers to widgets.charts.clinechart. Looking into that file, the code is as follows:

This prints out a nice line chart:

Where does it get this date from to draw the lines. I would expect this to come from the controller, but I can't seem to find it. What is the correct way to provide the linechart with data coming from my application

答:
In laravel 5.4, Run the following command for install composer for create charts

```<code>composer require "consoletvs/charts:5.*"
</code>```

then, add the following in your config/app.php file providers

```<code>ConsoleTVs\Charts\ChartsServiceProvider::class,
</code>```

then, add the following in your config/app.php file aliases

```<code>'Charts' => ConsoleTVs\Charts\Facades\Charts::class,
</code>```

then, use the following codes in your controller file

```<code>use Charts;
public function index()
{

    $chart= Charts::multi('areaspline', 'highcharts')
    ->title('My nice chart')
    ->colors(['#ff0000', '#ffffff'])
    ->labels(['January', 'February', 'March', 'April', 'May','June', 'July'])
    ->dataset('John', [3, 4, 3, 5, 4, 10, 12])
    ->dataset('Jane',  [1, 3, 4, 3, 3, 5, 4]);

    return view('User.chart',['chart'=>$chart]);
}
</code>```

In your blade file called User/chart.blade.php add the following codes

```<code><head>
{!! Charts::assets() !!}
</head>
<body>
    {!! $chart->render() !!}
</body>
</code>```

Click here for demo

Title: SB Admin Laravel 5 line chart data

Body:
Am using the following package. There is a chart displayed in resources/views/mcharts.blade.php. The code is the following;

@section ('cchart1_panel_title','Line Chart')
            @section ('cchart1_panel_body')
            @include('widgets.charts.clinechart')
            @endsection
            @include('widgets.panel', array('header'=>true, 'as'=>'cchart1'))

So this code refers to widgets.charts.clinechart. Looking into that file, the code is as follows:

This prints out a nice line chart:

Where does it get this date from to draw the lines. I would expect this to come from the controller, but I can't seem to find it. What is the correct way to provide the linechart with data coming from my application

Body:
In laravel 5.4, Run the following command for install composer for create charts

composer require "consoletvs/charts:5.*"

then, add the following in your config/app.php file providers

ConsoleTVs\Charts\ChartsServiceProvider::class,

then, add the following in your config/app.php file aliases

'Charts' => ConsoleTVs\Charts\Facades\Charts::class,

then, use the following codes in your controller file

use Charts;
public function index()
{

    $chart= Charts::multi('areaspline', 'highcharts')
    ->title('My nice chart')
    ->colors(['#ff0000', '#ffffff'])
    ->labels(['January', 'February', 'March', 'April', 'May','June', 'July'])
    ->dataset('John', [3, 4, 3, 5, 4, 10, 12])
    ->dataset('Jane',  [1, 3, 4, 3, 3, 5, 4]);

    return view('User.chart',['chart'=>$chart]);
}

In your blade file called User/chart.blade.php add the following codes

<head>
{!! Charts::assets() !!}
</head>
<body>
    {!! $chart->render() !!}
</body>

Click here for demo


问:
dplyr use n() within summarize to get row count of different grouping
My data frame includes region, date (by day), and general response data for a survey. I have grouped and summarized by region and date, so that I have a daily count of completed surveys (looking at a boolean Finished variable). If I use n(), I get a total for a region on that date (since I grouped the data frame by both of these).

I would like to add the total based on only region, across all dates. Is this possible using the dplyr methods? I have currently calculated the region totals, and after summarizing my table, have manually added a column using case_when to add the region totals. The goal is to make cumulative completion percentages per region in ggplot.

Is my approach the only way, or is it possible to use dplyr methods to remove a grouping level when calculating n()?

Example below. DailyCompeted is the sum of boolean Finished, and total is giving the total count for that day in that region. My goal is for total to be the sum of that column (92), per region in every row.

```<code>x %>% group_by(Region, EndDate) %>% summarize(DailyCompleted=sum(Finished), total=n())

Region EndDate    DailyCompleted total
   <fct>  <date>              <int> <int>
 1 AMER   2019-04-29              0     1
 2 AMER   2019-04-30              0     1
 3 AMER   2019-05-02              1     1
 4 AMER   2019-05-03              1     1
 5 AMER   2019-05-06             40    54
 6 AMER   2019-05-07             12    17
 7 AMER   2019-05-08              4     7
 8 AMER   2019-05-09              3     5
 9 AMER   2019-05-10              3     4
10 AMER   2019-05-12              1     1
</code>```

答:
We can reaggregate the summarized data by Region, and then join it bak to the data frame that has been aggregated by EndDate.

```<code>textFile <- "Region EndDate    DailyCompleted total
 AMER   2019-04-29              0     1
 AMER   2019-04-30              0     1
 AMER   2019-05-02              1     1
 AMER   2019-05-03              1     1
 AMER   2019-05-06             40    54
 AMER   2019-05-07             12    17
 AMER   2019-05-08              4     7
 AMER   2019-05-09              3     5
 AMER   2019-05-10              3     4
AMER   2019-05-12              1     1"

regionDay <- read.table(text = textFile,header = TRUE)

library(dplyr)
regionDay %>% group_by(Region) %>%
     summarise(regionDay,region_total = sum(total)) %>%
     inner_join(regionDay,.)
region_tot
</code>```

...and the output is:

```<code>   Region    EndDate DailyCompleted total region_total
1    AMER 2019-04-29              0     1           92
2    AMER 2019-04-30              0     1           92
3    AMER 2019-05-02              1     1           92
4    AMER 2019-05-03              1     1           92
5    AMER 2019-05-06             40    54           92
6    AMER 2019-05-07             12    17           92
7    AMER 2019-05-08              4     7           92
8    AMER 2019-05-09              3     5           92
9    AMER 2019-05-10              3     4           92
10   AMER 2019-05-12              1     1           92
>
</code>```

Body:
My data frame includes region, date (by day), and general response data for a survey. I have grouped and summarized by region and date, so that I have a daily count of completed surveys (looking at a boolean Finished variable). If I use n(), I get a total for a region on that date (since I grouped the data frame by both of these).

I would like to add the total based on only region, across all dates. Is this possible using the dplyr methods? I have currently calculated the region totals, and after summarizing my table, have manually added a column using case_when to add the region totals. The goal is to make cumulative completion percentages per region in ggplot.

Is my approach the only way, or is it possible to use dplyr methods to remove a grouping level when calculating n()?

Example below. DailyCompeted is the sum of boolean Finished, and total is giving the total count for that day in that region. My goal is for total to be the sum of that column (92), per region in every row.

x %>% group_by(Region, EndDate) %>% summarize(DailyCompleted=sum(Finished), total=n())

Region EndDate    DailyCompleted total
   <fct>  <date>              <int> <int>
 1 AMER   2019-04-29              0     1
 2 AMER   2019-04-30              0     1
 3 AMER   2019-05-02              1     1
 4 AMER   2019-05-03              1     1
 5 AMER   2019-05-06             40    54
 6 AMER   2019-05-07             12    17
 7 AMER   2019-05-08              4     7
 8 AMER   2019-05-09              3     5
 9 AMER   2019-05-10              3     4
10 AMER   2019-05-12              1     1

Body:
We can reaggregate the summarized data by Region, and then join it bak to the data frame that has been aggregated by EndDate.

textFile <- "Region EndDate    DailyCompleted total
 AMER   2019-04-29              0     1
 AMER   2019-04-30              0     1
 AMER   2019-05-02              1     1
 AMER   2019-05-03              1     1
 AMER   2019-05-06             40    54
 AMER   2019-05-07             12    17
 AMER   2019-05-08              4     7
 AMER   2019-05-09              3     5
 AMER   2019-05-10              3     4
AMER   2019-05-12              1     1"

regionDay <- read.table(text = textFile,header = TRUE)

library(dplyr)
regionDay %>% group_by(Region) %>%
     summarise(regionDay,region_total = sum(total)) %>%
     inner_join(regionDay,.)
region_tot

...and the output is:

   Region    EndDate DailyCompleted total region_total
1    AMER 2019-04-29              0     1           92
2    AMER 2019-04-30              0     1           92
3    AMER 2019-05-02              1     1           92
4    AMER 2019-05-03              1     1           92
5    AMER 2019-05-06             40    54           92
6    AMER 2019-05-07             12    17           92
7    AMER 2019-05-08              4     7           92
8    AMER 2019-05-09              3     5           92
9    AMER 2019-05-10              3     4           92
10   AMER 2019-05-12              1     1           92
>


问:
What's the better-practice way to rotate a string by one character in Python?
I'm doing a codecademy task and was wondering which of the following set of code is considered best practice:

The task is to create a function, given a string username , that shifts all letters one to the right.
For example the username : AbeSimp would become pAbeSim, this becomes the password and is stored in the string password.

Here is my code:

```<code>def password_generator(username):
    password = ""
    password = username[-1] + username[:-1]
    return password
</code>```

The Solution code is :

```<code>def password_generator(username):
    password = ""
    for i in range(0, len(user_name)):
       password += user_name[i-1]
    return password
</code>```

Any explanation is appreciated - thanks!

答: Your code is fine. I am wondering where would you get that solution, which doesn't seem to be correct in terms of efficiency or syntactically. As there additional complexity of for-loop involved.</p>

Body:
I'm doing a codecademy task and was wondering which of the following set of code is considered best practice:

The task is to create a function, given a string username , that shifts all letters one to the right.
For example the username : AbeSimp would become pAbeSim, this becomes the password and is stored in the string password.

Here is my code:

def password_generator(username):
    password = ""
    password = username[-1] + username[:-1]
    return password

The Solution code is :

def password_generator(username):
    password = ""
    for i in range(0, len(user_name)):
       password += user_name[i-1]
    return password

Any explanation is appreciated - thanks!


问:
Javascript issue- Uncaught TypeError: Cannot read property 'incart' of undefined
I am trying to increase or decrease quantity but for some reason the increase , decrease and remove products buttons are not working. whenever I click on the icons I am seeing a error "Uncaught TypeError: Cannot read property 'inCart' of undefined in console.log. I have spend a lot of time but did not find the error.
     let carts = document.querySelectorAll('.add-cart');

```<code> let products = [

  {

    name:'Natural Straight',
    tag: 'naturalStraight',
    price: 95,
    incart:0
},

{

    name:'Natural Wavy',
    tag: 'naturalWavy',
    price: 200,
    incart:0
},

{

    name:'Clip in Bangs',
    tag: 'Bangs',
    price: 50,
    incart:0
},

{

    name:'Bronde Balayage',
    tag: 'brondeBalayage',
    price: 350,
    incart:0
},
</code>```

]

```<code>for (let i=0; i < carts.length; i++){

carts[i].addEventListener('click',() =>{
    cartNumbers(products[i]);
    totalCost(products[i]);
})
</code>```

}

```<code> function onLoadCartNumbers()
 {
 let productNumbers = localStorage.getItem('cartNumbers');

if(productNumbers){
document.querySelector('.cart span').textContent = productNumbers;

}

}
 function cartNumbers(product)
 {

let productNumbers = localStorage.getItem('cartNumbers');
productNumbers = parseInt(productNumbers);

 if(productNumbers) {
localStorage.setItem('cartNumbers', productNumbers + 1);
 document.querySelector('.cart,span').textContent=productNumbers + 1;
 }else {

    localStorage.setItem('cartNumbers',1);
    document.querySelector('.cart,span').textContent =1;
 }

 setIteams(product);
}

function setIteams(product){

     let cartItems = localStorage.getItem('productsInCart');
    cartItems = JSON.parse(cartItems);

    if(cartItems != null){

        if(cartItems[product.tag] == undefined){

            cartItems ={

                ...cartItems,
                [product.tag]: product
            }
        }
        cartItems[product.tag].incart += 1;
        }else {
        product.incart =1;
     cartItems = {
        [product.tag]: product
    }

    }

    localStorage.setItem("productsInCart", JSON.stringify(cartItems));
}

  function totalCost(product){

//  console.log("te product price is", product.price);

let cartCost = localStorage.getItem('totalCost');
console.log("My cartCost is", cartCost);
console.log(typeof cartCost);

if(cartCost !=null){
    cartCost = parseInt(cartCost);
    localStorage.setItem("totalCost", cartCost + product.price);

}else{

localStorage.setItem("totalCost", product.price);
}

}
 function displayCart() {
let cartItems = localStorage.getItem('productsInCart');
cartItems = JSON.parse(cartItems);

let productContainer = document.querySelector(".products");
let cartCost = localStorage.getItem('totalCost');

if(cartItems && productContainer) {
    productContainer.innerHTML ='';
    Object.values(cartItems).map(item => {
    productContainer.innerHTML +=
        ` <div class="product">
         <ion-icon name="close-circle-outline"></ion-icon>
         <img src="./images/${item.tag}.jpg">
          <span>${item.name}</span>
    <div class="price">$${item.price},00</div>
    <div class="quantity">
    <ion-icon class="decrease" name="caret-back-circle-outline"></ion-
  icon>
        <span>${item.incart}</span>
<ion-icon class="increase" name="caret-forward-circle-outline"></ion-icon>
    </div>
    <div class="total">$${item.incart * item.price},00 </div>
     </div>
        `;
    });

}
    manageQuantity();
   }

 function manageQuantity() {

    let decreaseButton = document.querySelectorAll('.decrease');
    let increaseButton = document.querySelectorAll('.increase');

    let cartItems = localStorage.getItem('productsInCart') //Grab all the
     cartItems from localstorage
    let currentQuantity = 0;
                               is 0 when we get started
    let currentProduct = " ";
    cartItems = JSON.parse(cartItems);
    console.log(cartItems);

   // whenever we click on them the addEventListner does some action
   for (let i=0; i < decreaseButton.length; i++) {
      decreaseButton[i].addEventListener('click', () => {

      // whenever I click on decrease button I want to know the current
        quantity
        currentQuantity =
        decreaseButton[i].parentElement.querySelector('span').textContent;
        console.log(currentQuantity);

        //replace(//g,'') -to remove place between words,g is for globally
        everywhere on textcontent.
        currentProduct =
        decreaseButton[i].parentElement.previousElementSibling

       .previousElementSibling.textContent.toLowerCase().replace(/ /g,
       '');
        console.log(currentProduct);

        //checking cartItems and selecting the one with name and accessing
        incart from cartItems.
   cartItems[currentProduct].incart = cartItems[currentProduct].incart -1;
    });
    }

 }
</code>```

答:
The error means that you are trying to access the value of a property from an Object that is not defined.

In your case the cartItems[currentProduct] Object is not defined and that is the reason you are getting the error.

This can happen because of the following things:

cartItems does not contain currenProduct

currentProduct is undefined

cartItems itself is undefined.

But from your code it is clear that you have assigned a value for cartItems.
So the problem is most likely that cartItems does not contain currentProduct or currentProduct is undefined.

Check these and your code should work properly.

Body:
I am trying to increase or decrease quantity but for some reason the increase , decrease and remove products buttons are not working. whenever I click on the icons I am seeing a error "Uncaught TypeError: Cannot read property 'inCart' of undefined in console.log. I have spend a lot of time but did not find the error.
     let carts = document.querySelectorAll('.add-cart');

 let products = [

  {

    name:'Natural Straight',
    tag: 'naturalStraight',
    price: 95,
    incart:0
},

{

    name:'Natural Wavy',
    tag: 'naturalWavy',
    price: 200,
    incart:0
},

{

    name:'Clip in Bangs',
    tag: 'Bangs',
    price: 50,
    incart:0
},

{

    name:'Bronde Balayage',
    tag: 'brondeBalayage',
    price: 350,
    incart:0
},

]

for (let i=0; i < carts.length; i++){

carts[i].addEventListener('click',() =>{
    cartNumbers(products[i]);
    totalCost(products[i]);
})

}

 function onLoadCartNumbers()
 {
 let productNumbers = localStorage.getItem('cartNumbers');

if(productNumbers){
document.querySelector('.cart span').textContent = productNumbers;

}

}
 function cartNumbers(product)
 {

let productNumbers = localStorage.getItem('cartNumbers');
productNumbers = parseInt(productNumbers);

 if(productNumbers) {
localStorage.setItem('cartNumbers', productNumbers + 1);
 document.querySelector('.cart,span').textContent=productNumbers + 1;
 }else {

    localStorage.setItem('cartNumbers',1);
    document.querySelector('.cart,span').textContent =1;
 }

 setIteams(product);
}

function setIteams(product){

     let cartItems = localStorage.getItem('productsInCart');
    cartItems = JSON.parse(cartItems);

    if(cartItems != null){

        if(cartItems[product.tag] == undefined){

            cartItems ={

                ...cartItems,
                [product.tag]: product
            }
        }
        cartItems[product.tag].incart += 1;
        }else {
        product.incart =1;
     cartItems = {
        [product.tag]: product
    }

    }

    localStorage.setItem("productsInCart", JSON.stringify(cartItems));
}

  function totalCost(product){

//  console.log("te product price is", product.price);

let cartCost = localStorage.getItem('totalCost');
console.log("My cartCost is", cartCost);
console.log(typeof cartCost);

if(cartCost !=null){
    cartCost = parseInt(cartCost);
    localStorage.setItem("totalCost", cartCost + product.price);

}else{

localStorage.setItem("totalCost", product.price);
}

}
 function displayCart() {
let cartItems = localStorage.getItem('productsInCart');
cartItems = JSON.parse(cartItems);

let productContainer = document.querySelector(".products");
let cartCost = localStorage.getItem('totalCost');

if(cartItems && productContainer) {
    productContainer.innerHTML ='';
    Object.values(cartItems).map(item => {
    productContainer.innerHTML +=
        `

         <ion-icon name="close-circle-outline"></ion-icon>

          ${item.name}

$${item.price},00

    <ion-icon class="decrease" name="caret-back-circle-outline"></ion-
  icon>
        ${item.incart}
<ion-icon class="increase" name="caret-forward-circle-outline"></ion-icon>

$${item.incart * item.price},00

        `;
    });

}
    manageQuantity();
   }

 function manageQuantity() {

    let decreaseButton = document.querySelectorAll('.decrease');
    let increaseButton = document.querySelectorAll('.increase');

    let cartItems = localStorage.getItem('productsInCart') //Grab all the
     cartItems from localstorage
    let currentQuantity = 0;
                               is 0 when we get started
    let currentProduct = " ";
    cartItems = JSON.parse(cartItems);
    console.log(cartItems);

   // whenever we click on them the addEventListner does some action
   for (let i=0; i < decreaseButton.length; i++) {
      decreaseButton[i].addEventListener('click', () => {

      // whenever I click on decrease button I want to know the current
        quantity
        currentQuantity =
        decreaseButton[i].parentElement.querySelector('span').textContent;
        console.log(currentQuantity);

        //replace(//g,'') -to remove place between words,g is for globally
        everywhere on textcontent.
        currentProduct =
        decreaseButton[i].parentElement.previousElementSibling

       .previousElementSibling.textContent.toLowerCase().replace(/ /g,
       '');
        console.log(currentProduct);

        //checking cartItems and selecting the one with name and accessing
        incart from cartItems.
   cartItems[currentProduct].incart = cartItems[currentProduct].incart -1;
    });
    }

 }


问:
Vector invalid subscript. SFML
I'm trying to make a snake game and maybe this error is one of possible. So when I'm debugging and stepping over then I getting link to exception in header file of vector and in exception code wrote that vector has invalid subscript. (Error cause can called by vector bodyPart). The compiler message:

Unhandled exception at 0x00007FFA227EA799 in snake.exe: Microsoft C++ exception: std::out_of_range at memory location 0x00000052FA7CDFD0.

```<code>Snake::Snake(RenderWindow& window)
{
    bodyPart.setPosition(window.getSize().x / 4, window.getSize().y / 4);
    bodyPart.setSize(Vector2f(20.f, 20.f));
    bodyPart.setFillColor(Color(0, 0, 0));
    body.push_back(bodyPart);
}
//Sets default parameters
void Game::restart(RenderWindow& window)
{
    for (int i = 0; i < snake.body.size() - 1; i++)
    {
        snake.body.pop_back();
    }
    snake.bodyPart.setPosition(window.getSize().x / 4, window.getSize().y / 4);
    snake.body.push_back(snake.bodyPart);
}
//Updates game
void Game::tick(RenderWindow& window)
{
    if (snake.body.at(0).getPosition().x == fruit.fruitX && snake.body.at(0).getPosition().y == fruit.fruitY)
    {
        fruit.fruitX = fieldLCorn + rand() % fieldX * fieldY;
        fruit.fruitY = fieldLCorn + rand() % fieldY * fieldX;
        ui.score++;
        snake.body.reserve(1);
        snake.body.push_back(snake.bodyPart);
    }
}
void Game::moveSnake()
{
    switch(dir)
    {
    case 1:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(0, snake.body.at(0).getPosition().y + 10);
        snake.body.pop_back();
    case 2:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(0, snake.body.at(0).getPosition().y - 10);
        snake.body.pop_back();
    case 3:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(snake.body.at(0).getPosition().x + 10, 0);
        snake.body.pop_back();
    case 4:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(snake.body.at(0).getPosition().x - 10, 0);
        snake.body.pop_back();
    }
}
void Game::countCollision(RenderWindow& window)
{
    //Is snake met border
    if (snake.body.at(0).getPosition().x > 300) restart(window);
    if (snake.body.at(0).getPosition().y > 300) restart(window);
    if (snake.body.at(0).getPosition().x < -300) restart(window);
    if (snake.body.at(0).getPosition().y < -300) restart(window);
    //If snake eats itself
    for (int k = 0; k < snake.body.size() - 1; k++)
    {
        if (snake.body.at(0).getPosition().x == snake.body.at(k).getPosition().y && snake.body.at(0).getPosition().y == snake.body.at(k).getPosition().y)
        {
            restart(window);
        }
    }
}
void Game::render(RenderWindow& window)
{
    for (int i = 0; i < snake.body.size() - 1; i++)
    {
        window.draw(snake.body.at(i));
    }
}
</code>```

答:
For what I can see here, the problem might be the

```<code>snake.body.at(0)
</code>```

That you are using inside your code a lot of times, when maybe the body has no elements, and so there is no 0's element

Title: Vector invalid subscript. SFML

Body:
I'm trying to make a snake game and maybe this error is one of possible. So when I'm debugging and stepping over then I getting link to exception in header file of vector and in exception code wrote that vector has invalid subscript. (Error cause can called by vector bodyPart). The compiler message:

Unhandled exception at 0x00007FFA227EA799 in snake.exe: Microsoft C++ exception: std::out_of_range at memory location 0x00000052FA7CDFD0.

Snake::Snake(RenderWindow& window)
{
    bodyPart.setPosition(window.getSize().x / 4, window.getSize().y / 4);
    bodyPart.setSize(Vector2f(20.f, 20.f));
    bodyPart.setFillColor(Color(0, 0, 0));
    body.push_back(bodyPart);
}
//Sets default parameters
void Game::restart(RenderWindow& window)
{
    for (int i = 0; i < snake.body.size() - 1; i++)
    {
        snake.body.pop_back();
    }
    snake.bodyPart.setPosition(window.getSize().x / 4, window.getSize().y / 4);
    snake.body.push_back(snake.bodyPart);
}
//Updates game
void Game::tick(RenderWindow& window)
{
    if (snake.body.at(0).getPosition().x == fruit.fruitX && snake.body.at(0).getPosition().y == fruit.fruitY)
    {
        fruit.fruitX = fieldLCorn + rand() % fieldX * fieldY;
        fruit.fruitY = fieldLCorn + rand() % fieldY * fieldX;
        ui.score++;
        snake.body.reserve(1);
        snake.body.push_back(snake.bodyPart);
    }
}
void Game::moveSnake()
{
    switch(dir)
    {
    case 1:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(0, snake.body.at(0).getPosition().y + 10);
        snake.body.pop_back();
    case 2:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(0, snake.body.at(0).getPosition().y - 10);
        snake.body.pop_back();
    case 3:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(snake.body.at(0).getPosition().x + 10, 0);
        snake.body.pop_back();
    case 4:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(snake.body.at(0).getPosition().x - 10, 0);
        snake.body.pop_back();
    }
}
void Game::countCollision(RenderWindow& window)
{
    //Is snake met border
    if (snake.body.at(0).getPosition().x > 300) restart(window);
    if (snake.body.at(0).getPosition().y > 300) restart(window);
    if (snake.body.at(0).getPosition().x < -300) restart(window);
    if (snake.body.at(0).getPosition().y < -300) restart(window);
    //If snake eats itself
    for (int k = 0; k < snake.body.size() - 1; k++)
    {
        if (snake.body.at(0).getPosition().x == snake.body.at(k).getPosition().y && snake.body.at(0).getPosition().y == snake.body.at(k).getPosition().y)
        {
            restart(window);
        }
    }
}
void Game::render(RenderWindow& window)
{
    for (int i = 0; i < snake.body.size() - 1; i++)
    {
        window.draw(snake.body.at(i));
    }
}

Body:
For what I can see here, the problem might be the

snake.body.at(0)

That you are using inside your code a lot of times, when maybe the body has no elements, and so there is no 0's element


问:
How do i get a service worker detected & registered in web2py?
I am trying to create a web2py progressive app but so far in all I have done Chrome Developer Tools keeps showing a warning message that says :

"No matching service worker detected. You may need to reload page or check that the scope of the service worker for the current page encloses the scope of the start URL from the manifest."

I have placed the service worker and the main.js file in {{=URL('static','js/')}} directory.

In my research I came across some information saying that I have to place the service worker in a root directory but I dont know where to locate the root directory in this framework!

Please assist me in figuring this out.

答:
Make sure you have registered your service worker correctly and your main.js include in index.html

For better answer post service worker register code and index.html so it will be better to understand.

Thanks


问:
Log wrapper in makefile?
I m trying to write a simple log wrapper in makefile as shown below

```<code>define do_log
ifeq ($(1),1)
  $(info ---------- $(shell date +%H:%M:%S) $(2))
else ifeq ($(1),2)
  $(warning ^^^^^^^^^^ $(shell date +%H:%M:%S) $(2))
else ifeq ($(1),3)
  $(error !!!!!!!!!! $(shell date +%H:%M:%S) $(2))
endif
endef
</code>```

But every-time i call this function

```<code>$(call do_log,1,"hello")
</code>```

All statements are getting executed

```<code>$ make
---------- 18:22:45 "hello"
Makefile:16: ^^^^^^^^^^ 18:22:45 "hello"
Makefile:16: *** !!!!!!!!!! 18:22:45 "hello".  Stop.
</code>```

Can someone please help me understand, on what am i doing wrong ?

答:
This can be achieved with eval :

```<code>define do_log
ifeq ($(1),1)
  $$(info ---------- $(shell date +%H:%M:%S) $(2))
else ifeq ($(1),2)
  $$(warning ^^^^^^^^^^ $(shell date +%H:%M:%S) $(2))
else ifeq ($(1),3)
  $$(error !!!!!!!!!! $(shell date +%H:%M:%S) $(2))
endif
endef

$(eval $(call do_log,3,"hello"))
</code>```

Title: Log wrapper in makefile?

Body:
I m trying to write a simple log wrapper in makefile as shown below

define do_log
ifeq ($(1),1)
  $(info ---------- $(shell date +%H:%M:%S) $(2))
else ifeq ($(1),2)
  $(warning ^^^^^^^^^^ $(shell date +%H:%M:%S) $(2))
else ifeq ($(1),3)
  $(error !!!!!!!!!! $(shell date +%H:%M:%S) $(2))
endif
endef

But every-time i call this function

$(call do_log,1,"hello")

All statements are getting executed

$ make
---------- 18:22:45 "hello"
Makefile:16: ^^^^^^^^^^ 18:22:45 "hello"
Makefile:16: *** !!!!!!!!!! 18:22:45 "hello".  Stop.

Can someone please help me understand, on what am i doing wrong ?

Body:
This can be achieved with eval :

define do_log
ifeq ($(1),1)
  $$(info ---------- $(shell date +%H:%M:%S) $(2))
else ifeq ($(1),2)
  $$(warning ^^^^^^^^^^ $(shell date +%H:%M:%S) $(2))
else ifeq ($(1),3)
  $$(error !!!!!!!!!! $(shell date +%H:%M:%S) $(2))
endif
endef

$(eval $(call do_log,3,"hello"))


答:
You are currently doing it wrong. Just follow the official example here and you can do something like this. You need to create a 2-dimensional mesh grid of x and y points for each of your bar. Moreover, to create the meshgrids, you have to use numbers and later reset the tick labels to your original strings

```<code>x = np.arange(len(xx))
y = np.arange(len(yy))

_xx, _yy = np.meshgrid(x, y)
XX, YY = _xx.ravel(), _yy.ravel()

bottom = np.zeros_like(zz)
dx = np.ones(len(XX))
dy = np.ones(len(YY))

ax.bar3d(XX, YY, bottom, dx, dy, zz, shade=True)

ax.set_xticks(range(0, 36, 2))
ax.set_xticklabels(xx[::2])

ax.set_yticks(np.arange(4) + 0.5)
ax.set_yticklabels(yy);
</code>```

Title: 3D bar plot with dates, strings and numbers in 3 axes with matplotlib in python

Body:
I have three lists as mentioned below.

xx =  ['TT', 'AN', 'AP', 'AR', 'AS', 'BR', 'CH', 'CT', 'DN', 'DD', 'DL', 'GA', 'GJ', 'HR', 'HP', 'JK', 'JH', 'KA', 'KL', 'LA', 'LD', 'MP', 'MH', 'MN', 'ML', 'MZ', 'NL', 'OR', 'PY', 'PB', 'RJ', 'SK', 'TN', 'TG', 'TR', 'UP', 'UT', 'WB']
yy = [datetime.date(2020, 5, 27), datetime.date(2020, 5, 28), datetime.date(2020, 5, 29), datetime.date(2020, 5, 30)]
zz = [7246, 0, 134, 0, 101, 68, 1, 4, 0, 0, 792, 1, 376, 76, 26, 162, 7, 135, 40, 1, 0, 237, 2190, 5, 0, 0, 5, 76, 0, 33, 280, 0, 817, 107, 10, 267, 69, 183, 7254, 0, 128, 1, 97, 149, 10, 34, 0, 0, 1024, 1, 367, 123, 8, 115, 6, 115, 85, 20, 0, 192, 2598, 11, 1, 0, 9, 67, 4, 19, 251, 0, 827, 117, 2, 179, 31, 344, 8138, 0, 85, 0, 177, 174, 0, 17, 0, 0, 1105, 0, 372, 217, 14, 128, 82, 248, 62, 0, 0, 192, 2682, 4, 6, 0, 7, 63, 4, 39, 298, 0, 874, 169, 10, 275, 216, 277, 8304, 0, 131, 1, 128, 206, 0, 32, 0, 0, 1163, 1, 412, 202, 18, 177, 42, 141, 58, 3, 0, 246, 2940, 3, 0, 0, 11, 96, 0, 36, 252, 0, 938, 74, 17, 256, 33, 317]

I want to plot bar3d plot using matplotlib in python such that x axis will be xx, y axis will be yy to plot **zz*, i.e. date wise plotting. Following tutorials, I tried

dx = np.ones(len(xx))
dy = np.ones(len(yy))
dz = np.ones(len(zz))   # doubt
ax.bar3d(xx, yy, zz, dx, dy, dz, shade=True)

Obviously, I got errors

  ax.bar3d(xx, yy, zz, dx=dx, dy=dy, dz=dz, shade=True)
File "/home/vega/anaconda3/envs/tf01/lib/python3.7/sitepackages/mpl_toolkits/mplot3d/axes3d.py", line 2365, in bar3d
  np.atleast_1d(x), y, z, dx, dy, dz)
File "<__array_function__ internals>", line 6, in broadcast_arrays
File "/home/vega/anaconda3/envs/tf01/lib/python3.7/sitepackages/numpy/lib/stride_tricks.py", line 264, in broadcast_arrays
  shape = _broadcast_shape(*args)
File "/home/vega/anaconda3/envs/tf01/lib/python3.7/sitepackages/numpy/lib/stride_tricks.py", line 191, in _broadcast_shape
  b = np.broadcast(*args[:32])
ValueError: shape mismatch: objects cannot be broadcast to a single shape

I think I did not understand proper formulation of tuples for bar3D plot. I request any handle to resolve. I scanned earlier questions and hence I believe it is not a repeat question.

Body:
You are currently doing it wrong. Just follow the official example here and you can do something like this. You need to create a 2-dimensional mesh grid of x and y points for each of your bar. Moreover, to create the meshgrids, you have to use numbers and later reset the tick labels to your original strings

x = np.arange(len(xx))
y = np.arange(len(yy))

_xx, _yy = np.meshgrid(x, y)
XX, YY = _xx.ravel(), _yy.ravel()

bottom = np.zeros_like(zz)
dx = np.ones(len(XX))
dy = np.ones(len(YY))

ax.bar3d(XX, YY, bottom, dx, dy, zz, shade=True)

ax.set_xticks(range(0, 36, 2))
ax.set_xticklabels(xx[::2])

ax.set_yticks(np.arange(4) + 0.5)
ax.set_yticklabels(yy);


问:
How to stub a service with Sinon in an integration test?
I'm trying to do some integration tests for my api in express.

My API's structure is something like:

```<code>app -> routes -> controllers -> services
</code>```

Because I already have unit tests, my idea is only test that all that components are connected in the correct way.

So my idea was created an stub with Sinon for the service, and only check the responses of the controller with supertest.

When I run a single test everything is ok. The problem is when I run more than one unit test for different controllers, the stub doesn't work in the second run.

I think it's  because the app is already saved in cache as a module, so sinon can't stub the service.

Some examples of my code:

controller.js

```<code>const httpStatus = require('http-status');
const { service } = require('../services/croupier');

/**
 * Execute lambda tasks for candidates
 * @public
 */
exports.task = async (req, res, next) => {
  try {
    const result = await service({
      body: req.body,
      authorizer: req.authorizer
    });
    console.log('res', result);

    res.status(httpStatus.OK).json(result);
  } catch (error) {
    next(error);
  }
};
</code>```

foo.integration.test.js

```<code>const request = require('supertest');
const httpStatus = require('http-status');
const sinon = require('sinon');
const mongoose = require('../../../database');

const deleteModule = module => delete require.cache[require.resolve(module)];

const requireUncached = module => {
  deleteModule(module);
  return require(module);
};

describe('Foo - Integration Test', async () => {
  describe('POST /v1/foo', () => {
    const fooService = require('../../services/foo');
    const stub = sinon.stub(fooService, 'service');
    let db;
    before(async () => {
      db = await mongoose.connect();
    });

    afterEach(async () => {
      sinon.restore();
    });

    after(async () => {
      await db.close();
    });

    it('the api should response successfully', async () => {
      stub.returns({});
      const payload = { task: 'task', payload: [{ pathParameters: {}, body: {} }] };
      const app = requireUncached('../../../app');
      await request(app)
        .post('/api/foo')
        .send(payload)
        .expect(httpStatus.OK);
    });

    it('the api should response with an error', async () => {
      stub.throwsException();
      const payload = { task: 'task', payload: [{ pathParameters: {}, body: {} }] };
      const app = requireUncached('../../../app');
      await request(app)
        .post('/api/foo')
        .send(payload)
        .expect(httpStatus.INTERNAL_SERVER_ERROR);
    });
  });
});
</code>```

The other integration tests have the same structure. I've also tried using proxyquire but didn't work.

Also I tried deleting cache of de app.js with any success.

Any ideas?

答:
Context: integration test.

I agree with your idea: "test that all that components are connected in the correct way". Then what you need is spy, not stub. When there is a case / condition, you need to setup preconfigured/dummy data (up mongodb with specific data), turn on HTTP server, call HTTP request with specific data (post / get with specific query), and check the HTTP response for correct status, etc. The spy needed to check/validate/verify whether your service get called with correct parameter and response with correct result. This test validate you have correctly configured route - controller to a service for specific HTTP request.

You must have question: How to test negative scenario? For example: 404, 500. Then you need to know which specific scenario do what, which result negative condition. For example: if request come with unknown ID query, then response will be 404. Or if express not connected to database, then response will be 500. You need to know the real scenario, and again provide the require setup to produce the negative response.

For problem: "When I run a single test everything is ok. The problem is when I run more than one unit test for different controllers, the stub doesn't work in the second run.". There are several possible solutions, the main point is: you must make sure that the conditions for specific scenario/case are correctly prepared.

You can do:

create sandbox, to make sure no other stub service run between test cases.

start up fresh http (and or db) server before and shut down the server after the test run for each services, (for example: start the app and use real http client - as alternative to supertest)

run on debug mode to find out why the second stub not run or not get called or not work,

change implementation from stub to spy, you have already had a unit test, you just need to check whether the service get called or not, and then check the overall response.

Hope this helps.

Body:
I'm trying to do some integration tests for my api in express.

My API's structure is something like:

app -> routes -> controllers -> services

Because I already have unit tests, my idea is only test that all that components are connected in the correct way.

So my idea was created an stub with Sinon for the service, and only check the responses of the controller with supertest.

When I run a single test everything is ok. The problem is when I run more than one unit test for different controllers, the stub doesn't work in the second run.

I think it's  because the app is already saved in cache as a module, so sinon can't stub the service.

Some examples of my code:

controller.js

const httpStatus = require('http-status');
const { service } = require('../services/croupier');

/**
 * Execute lambda tasks for candidates
 * @public
 */
exports.task = async (req, res, next) => {
  try {
    const result = await service({
      body: req.body,
      authorizer: req.authorizer
    });
    console.log('res', result);

    res.status(httpStatus.OK).json(result);
  } catch (error) {
    next(error);
  }
};

foo.integration.test.js

const request = require('supertest');
const httpStatus = require('http-status');
const sinon = require('sinon');
const mongoose = require('../../../database');

const deleteModule = module => delete require.cache[require.resolve(module)];

const requireUncached = module => {
  deleteModule(module);
  return require(module);
};

describe('Foo - Integration Test', async () => {
  describe('POST /v1/foo', () => {
    const fooService = require('../../services/foo');
    const stub = sinon.stub(fooService, 'service');
    let db;
    before(async () => {
      db = await mongoose.connect();
    });

    afterEach(async () => {
      sinon.restore();
    });

    after(async () => {
      await db.close();
    });

    it('the api should response successfully', async () => {
      stub.returns({});
      const payload = { task: 'task', payload: [{ pathParameters: {}, body: {} }] };
      const app = requireUncached('../../../app');
      await request(app)
        .post('/api/foo')
        .send(payload)
        .expect(httpStatus.OK);
    });

    it('the api should response with an error', async () => {
      stub.throwsException();
      const payload = { task: 'task', payload: [{ pathParameters: {}, body: {} }] };
      const app = requireUncached('../../../app');
      await request(app)
        .post('/api/foo')
        .send(payload)
        .expect(httpStatus.INTERNAL_SERVER_ERROR);
    });
  });
});

The other integration tests have the same structure. I've also tried using proxyquire but didn't work.

Also I tried deleting cache of de app.js with any success.

Any ideas?


问:
java.lang.ClassNotFoundException: org.springframework.core.ErrorCoded
I am using below dependencies in my spring boot shell application.

```<code><dependencies>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
      <version>2.0.0.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework.shell</groupId>
      <artifactId>spring-shell-starter</artifactId>
      <version>2.0.0.RELEASE</version>
    </dependency>

  </dependencies>
</code>```

But When I am trying to run the application, I am getting error like 'ClassNotFoundException: org.springframework.core.ErrorCoded'

```<code>Caused by: java.lang.ClassNotFoundException: org.springframework.core.ErrorCoded
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    ... 57 common frames omitted
</code>```

答:
I solved this problem with these dependencies.</p>

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.sample.app</groupId>
  <artifactId>hello-world</artifactId>
  <packaging>jar</packaging>
  <version>1</version>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>

    <dependency>
      <groupId>org.springframework.shell</groupId>
      <artifactId>spring-shell-starter</artifactId>
      <version>2.0.1.BUILD-SNAPSHOT</version>
    </dependency>

  </dependencies>

  <repositories>
    <repository>
      <id>spring-snapshots</id>
      <name>Spring Snapshots</name>
      <url>https://repo.spring.io/libs-snapshot</url>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </repository>
  </repositories>

</project>
</code>```

Body:
I am using below dependencies in my spring boot shell application.

<dependencies>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
      <version>2.0.0.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework.shell</groupId>
      <artifactId>spring-shell-starter</artifactId>
      <version>2.0.0.RELEASE</version>
    </dependency>

  </dependencies>

But When I am trying to run the application, I am getting error like 'ClassNotFoundException: org.springframework.core.ErrorCoded'

Caused by: java.lang.ClassNotFoundException: org.springframework.core.ErrorCoded
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    ... 57 common frames omitted

Body:
I solved this problem with these dependencies.

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.sample.app</groupId>
  <artifactId>hello-world</artifactId>
  <packaging>jar</packaging>
  <version>1</version>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>

    <dependency>
      <groupId>org.springframework.shell</groupId>
      <artifactId>spring-shell-starter</artifactId>
      <version>2.0.1.BUILD-SNAPSHOT</version>
    </dependency>

  </dependencies>

  <repositories>
    <repository>
      <id>spring-snapshots</id>
      <name>Spring Snapshots</name>
      <url>https://repo.spring.io/libs-snapshot</url>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </repository>
  </repositories>

</project>


问:
Xcode fails to install watchOS app onto Apple Watch device
Xcode "Run" operation fails to install a watchOS app on a real Apple Watch device with error description:

The host is not paired with the device.

Context:

First time ever trying to install a watchOS app from Xcode onto an Apple Watch device for testing/debugging

The watchOS app is an official Apple SwiftUI tutorial example

Assume latest versions of MacOS, Xcode, watchOS, Watch device, etc.

The selected scheme is the watchOS app target

The selected device is "[my Apple Watch name] via [my iPhone name]"

The Apple Watch is in fact paired with the companion iPhone, despite what the Xcode error says

答:
What needs to be done is restarting both devices, iPhone and paired Apple Watch, connect iPhone to computer with cable. When the trust/don't trust notification appears on the Apple Watch or iPhone obviously choose 'trust'. Then the app will install again.

What it stops from running on your watch sometimes is if you have a simulator debug session open still. It says it can't install because there is another debug session running (but not on your watch..)! Closing this simulator session will allow you to install on your watch.

Other times xCode is building fine and thinks it's running the app on your watch, but it runs an old version and you don't see any changes made. Then you have to delete the app from your Apple Watch.

What also sometimes stops it from running on the Apple Watch are in Xcode the Preferences->Accounts->Profiles. Installing them manually will help in that case.

If nothing works uncouple your apple watch from your iPhone and recouple again.

Why isn't this still been resolved? I see people complaining about it for several of years now. Is this bug only related to standalone apps?


问:
Swift foundation vs standard library?
Question
- What is the difference between Swift Foundation and standard library?

I know they are not in the same repository. Swift standard library and Swift Foundation.

My understanding is that Swift standard library is low level library that are support for core data types, array, etc... written in swift. And Swift Foundation is for higher level which are already included common utilities codes written in swift language. But my confusion is that why are the objective-c classes like NSArray are included in Foundation library? Can you explain me with more details?

答:
To understand what's going on here, first distinguish three things:

Swift library is the Swift native types, like String and Array.

Foundation is the Cocoa Objective-C basic set of types, like NSString and NSArray and NSDate and NSData.

Swift also contains an overlay library that shadows (without obscuring) types in the Foundation. For example, Date shadows NSDate, and Data shadows NSData. This makes the Cocoa Foundation a lot easier to use in Swift.

Note that there are two very different relations in which a Swift type can stand with respect to a Cocoa Objective-C type.

String and Array are completely independent native Swift types. They are bridged to NSString and NSArray respectively, but they exist without Foundation.

Data and Date are merely facades for NSData and NSDate respectively. If you import Swift but not Foundation, Data and Date are not even present.

Okay, so far so good. But this situation presents a quandary, because one would like to use Data and Date without the need for Foundation, in places like Linux that do not have it in the first place. Therefore, the project you have pointed to, https://github.com/apple/swift-corelibs-foundation, provides a backing for Data and Date (and so on) independent of Foundation.
But if you are developing for iOS or MacOS you would never use it, because the real Foundation is present.

Title: Swift foundation vs standard library?


问:
How do I SORT only the fields ($project) returned from Mongodb aggregation, while also using $match, $lookup AND $filter
I am VERY close to getting what I want out of this query... but now I want to sort on a notification field

NOTE: This is a refinement : I am now asking how to return SORT on notification fields, while my similar question asks how to return the data between a start and end date and my other similar question asks how to return only certain fields.

Register Schema

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const RegisterSchema = new Schema({
    userId: {type: Schema.Types.ObjectId, required: true},
    accessToken: {type:String, required: true, default: null},
})
module.exports = Register = mongoose.model( 'register', RegisterSchema)
```

<p>Here is some register data</p>

<pre class="lang-js prettyprint-override"><code>[
  {
    "_id": "Reg_1",
    "userId": "User_1",
    "accessToken": "a_1"
  },
  {
    "_id": "Reg_2",
    "userId": "User_2",
    "accessToken": "a_2"
  }
]
</code>```

The next document contains data that is related to the Register schema via the accessToken

Notifications

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const NotificationSchema = new Schema({
    accessToken: {type:String, required: true},
    summaryId: {type:Number, required: true},
    dateCreated: {type: Date, default: Date.now},

    // I don't want these returned in the final results
    dontWantThis1: {type:Number, required: true},
    dontWantThis2: {type:Number, required: true},
})
module.exports = Notification = mongoose.model( 'notification', NotificationSchema)
```

<p>Here is some notification data</p>

<pre class="lang-js prettyprint-override"><code>[{
    "_id": "N1_1",
    "accessToken": "a_1",
    "summaryId": 1111,
    "dontWantThis1": 61,
    "dontWantThis2": 62,
    "dateCreated": "2020-04-17T00:00:00.000+00:00" },
  {
    "_id": "N2_1",
    "accessToken": "a_2",
    "summaryId": 2221,
    "dontWantThis1": 71,
    "dontWantThis2": 72,
    "dateCreated": "2020-04-18T00:00:00.000+00:00" },
  {
    "_id": "N1_2",
    "accessToken": "a_1",
    "summaryId": 1112,
    "dontWantThis1": 611,
    "dontWantThis2": 622,
    "dateCreated": "2020-05-25T00:00:00.000+00:00" },
  {
    "_id": "N2_2",
    "accessToken": "a_2",
    "summaryId": 2222,
    "dontWantThis1": 711,
    "dontWantThis2": 722,
    "dateCreated": "2020-05-26T00:00:00.000+00:00" }
]
</code>```

Starting with this

This code returns everything I want... but doesn't sort the notifications by dateCreated showing the newest dates first.

        // make sure the input dates are REALLY date objects
        // I only want to see notifications for the month of May (in this example)
        var dateStart = new Date('2020-01-01T00:00:00.000+00:00');
        var dateEnd = new Date('2020-05-30T00:00:00.000+00:00');

        var match = {$match: { userId: mongoose.Types.ObjectId(userId) } };

        var lookup ={
            $lookup:
            {
                from: "my_Notifications",
                localField: "accessToken",
                foreignField: "accessToken",
                as: "notifications"
            }
        };

        var dateCondition = { $and: [
            { $gte: [ "$$item.dateCreated", dateStart ] },
            { $lte: [ "$$item.dateCreated", dateEnd ] }
          ]}

        var project = {
            $project: {
                notifications: {
                    $filter: {
                    input: "$notifications",
                    as: "item",
                    cond: dateCondition
                    } } }
        };

        var project2 = {
            $project: {
                "_id": 1,
                "userId": 1,
                "accessToken":1,
                "count":{$size:"$notifications"},
                "notifications._id":1,
                "notifications.summaryId": 1,
                "notifications.dateCreated":1,
                "notifications.dateProcessed":1,
            }
        };

        var agg = [
            match,
            lookup,
            project,
            project2,
        ];

        Register.aggregate(agg)
        .then( ..... )
```

<h2>Expected Results</h2>

<p>I would like to have the notifications sorted by latest date to earliest date</p>

<p><strong>NOTE</strong>: It doesn't matter which "accessToken" is the first record... just that the dates of the notifications <em>in EACH accessToken record</em> are latest to earliest AND all of the data is present :</p>

<pre class="lang-js prettyprint-override"><code>[
  {
    "_id": "Reg_1",
    "accessToken": "a_1",
    "userId": "User_1",
    "count": 2,
    "notifications": [
      {
        "_id": "N1_2",
        "dateCreated": ISODate("2020-05-25T00:00:00Z"),
        "summaryId": 1112
      },
      {
        "_id": "N1_1",
        "dateCreated": ISODate("2020-04-17T00:00:00Z"),
        "summaryId": 1111
      }
    ]
  },
  {
    "_id": "Reg_2",
    "accessToken": "a_2",
    "userId": "User_2",
    "count": 2,
    "notifications": [
      {
        "_id": "N2_2",
        "dateCreated": ISODate("2020-05-26T00:00:00Z"),
        "summaryId": 2222
      },
      {
        "_id": "N2_1",
        "dateCreated": ISODate("2020-04-18T00:00:00Z"),
        "summaryId": 2221
      }
    ]
  }
]
</code>```

previous tries removed for brevity

Try 6

I am getting closer with this playground attempt, but

Try 6 close... but no cigar

I am getting this... instead of the expected results

[
  {
    "_id": {
      "accessToken": "a_2",
      "userId": "User_2"
    },
    "notifications": [
      {
        "_id": "N2_2",
        "dateCreated": "2020-05-26T00:00:00.000+00:00",
        "summaryId": 2222
      },
      {
        "_id": "N2_1",
        "dateCreated": "2020-04-18T00:00:00.000+00:00",
        "summaryId": 2221
      }
    ],
    "notifications_count": 2
  },
  {
    "_id": {
      "accessToken": "a_1",
      "userId": "User_1"
    },
    "notifications": [
      {
        "_id": "N1_2",
        "dateCreated": "2020-05-25T00:00:00.000+00:00",
        "summaryId": 1112
      },
      {
        "_id": "N1_1",
        "dateCreated": "2020-04-17T00:00:00.000+00:00",
        "summaryId": 1111
      }
    ],
    "notifications_count": 2
  }
]
```

Thanks!!

答:
OK.. after much playing around in mongodb and a dozen google searches.

Here is the answer to make the output the same as the expected results

  {
    $group: {
      "_id": "$_id",
      "accessToken": {
        "$first": "$accessToken"
      },
      "userId": {
        "$first": "$userId"
      },
      "n_count": {
        $sum: 1
      },
      "notifications": {
        $push: "$notifications"
      }
    }
  }
```

https://mongoplayground.net/p/8XaIOW7gKAg

Body:
I am VERY close to getting what I want out of this query... but now I want to sort on a notification field

NOTE: This is a refinement : I am now asking how to return SORT on notification fields, while my similar question asks how to return the data between a start and end date and my other similar question asks how to return only certain fields.

Register Schema

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const RegisterSchema = new Schema({
    userId: {type: Schema.Types.ObjectId, required: true},
    accessToken: {type:String, required: true, default: null},
})
module.exports = Register = mongoose.model( 'register', RegisterSchema)

Here is some register data

[
  {
    "_id": "Reg_1",
    "userId": "User_1",
    "accessToken": "a_1"
  },
  {
    "_id": "Reg_2",
    "userId": "User_2",
    "accessToken": "a_2"
  }
]

The next document contains data that is related to the Register schema via the accessToken

Notifications

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const NotificationSchema = new Schema({
    accessToken: {type:String, required: true},
    summaryId: {type:Number, required: true},
    dateCreated: {type: Date, default: Date.now},

    // I don't want these returned in the final results
    dontWantThis1: {type:Number, required: true},
    dontWantThis2: {type:Number, required: true},
})
module.exports = Notification = mongoose.model( 'notification', NotificationSchema)

Here is some notification data

[{
    "_id": "N1_1",
    "accessToken": "a_1",
    "summaryId": 1111,
    "dontWantThis1": 61,
    "dontWantThis2": 62,
    "dateCreated": "2020-04-17T00:00:00.000+00:00" },
  {
    "_id": "N2_1",
    "accessToken": "a_2",
    "summaryId": 2221,
    "dontWantThis1": 71,
    "dontWantThis2": 72,
    "dateCreated": "2020-04-18T00:00:00.000+00:00" },
  {
    "_id": "N1_2",
    "accessToken": "a_1",
    "summaryId": 1112,
    "dontWantThis1": 611,
    "dontWantThis2": 622,
    "dateCreated": "2020-05-25T00:00:00.000+00:00" },
  {
    "_id": "N2_2",
    "accessToken": "a_2",
    "summaryId": 2222,
    "dontWantThis1": 711,
    "dontWantThis2": 722,
    "dateCreated": "2020-05-26T00:00:00.000+00:00" }
]

Starting with this

This code returns everything I want... but doesn't sort the notifications by dateCreated showing the newest dates first.

        // make sure the input dates are REALLY date objects
        // I only want to see notifications for the month of May (in this example)
        var dateStart = new Date('2020-01-01T00:00:00.000+00:00');
        var dateEnd = new Date('2020-05-30T00:00:00.000+00:00');

        var match = {$match: { userId: mongoose.Types.ObjectId(userId) } };

        var lookup ={
            $lookup:
            {
                from: "my_Notifications",
                localField: "accessToken",
                foreignField: "accessToken",
                as: "notifications"
            }
        };

        var dateCondition = { $and: [
            { $gte: [ "$$item.dateCreated", dateStart ] },
            { $lte: [ "$$item.dateCreated", dateEnd ] }
          ]}

        var project = {
            $project: {
                notifications: {
                    $filter: {
                    input: "$notifications",
                    as: "item",
                    cond: dateCondition
                    } } }
        };

        var project2 = {
            $project: {
                "_id": 1,
                "userId": 1,
                "accessToken":1,
                "count":{$size:"$notifications"},
                "notifications._id":1,
                "notifications.summaryId": 1,
                "notifications.dateCreated":1,
                "notifications.dateProcessed":1,
            }
        };

        var agg = [
            match,
            lookup,
            project,
            project2,
        ];

        Register.aggregate(agg)
        .then( ..... )

Expected Results

I would like to have the notifications sorted by latest date to earliest date

NOTE: It doesn't matter which "accessToken" is the first record... just that the dates of the notifications in EACH accessToken record are latest to earliest AND all of the data is present :

[
  {
    "_id": "Reg_1",
    "accessToken": "a_1",
    "userId": "User_1",
    "count": 2,
    "notifications": [
      {
        "_id": "N1_2",
        "dateCreated": ISODate("2020-05-25T00:00:00Z"),
        "summaryId": 1112
      },
      {
        "_id": "N1_1",
        "dateCreated": ISODate("2020-04-17T00:00:00Z"),
        "summaryId": 1111
      }
    ]
  },
  {
    "_id": "Reg_2",
    "accessToken": "a_2",
    "userId": "User_2",
    "count": 2,
    "notifications": [
      {
        "_id": "N2_2",
        "dateCreated": ISODate("2020-05-26T00:00:00Z"),
        "summaryId": 2222
      },
      {
        "_id": "N2_1",
        "dateCreated": ISODate("2020-04-18T00:00:00Z"),
        "summaryId": 2221
      }
    ]
  }
]

previous tries removed for brevity

Try 6

I am getting closer with this playground attempt, but

Try 6 close... but no cigar

I am getting this... instead of the expected results

[
  {
    "_id": {
      "accessToken": "a_2",
      "userId": "User_2"
    },
    "notifications": [
      {
        "_id": "N2_2",
        "dateCreated": "2020-05-26T00:00:00.000+00:00",
        "summaryId": 2222
      },
      {
        "_id": "N2_1",
        "dateCreated": "2020-04-18T00:00:00.000+00:00",
        "summaryId": 2221
      }
    ],
    "notifications_count": 2
  },
  {
    "_id": {
      "accessToken": "a_1",
      "userId": "User_1"
    },
    "notifications": [
      {
        "_id": "N1_2",
        "dateCreated": "2020-05-25T00:00:00.000+00:00",
        "summaryId": 1112
      },
      {
        "_id": "N1_1",
        "dateCreated": "2020-04-17T00:00:00.000+00:00",
        "summaryId": 1111
      }
    ],
    "notifications_count": 2
  }
]

Thanks!!

Body:
OK.. after much playing around in mongodb and a dozen google searches.

Here is the answer to make the output the same as the expected results

  {
    $group: {
      "_id": "$_id",
      "accessToken": {
        "$first": "$accessToken"
      },
      "userId": {
        "$first": "$userId"
      },
      "n_count": {
        $sum: 1
      },
      "notifications": {
        $push: "$notifications"
      }
    }
  }

https://mongoplayground.net/p/8XaIOW7gKAg


问:
Jest with globalsetup doesn't see tests
Say I have the following test:

```<code>describe('foo', () => {
    it('bar', () => {
        expect(1).toBe(2)
    })
})
</code>```

in a file named foo.application.test.ts

And the following command in my package.json:

```<code>jest --testRegex '.*.application.test.ts'"
</code>```

Running these tests fails, as you would expect. However, changing my command to:

```<code>jest --globalSetup ./tests/support/instantiateApplicationTests.ts --testRegex '.*.application.test.ts'"
</code>```

Results in no tests being run at all ( the global setup file does exist), with the following log:

```<code>yarn run v1.22.4
$ jest --globalSetup ./tests/support/instantiateApplicationTests.ts --testRegex '.*.application.test.ts'
✨  Done in 0.81s.
</code>```

How am I misusing globalsetup here?

答: In my case the code in my globalSetup was throwing silently. For anybody who runs across this, try adding console logs inside your global setup file to ascertain if it's running at all. If so, debug it using your favorite approach (node debuggers, logging, whatever). Once I fixed my globalSetup script, my problem went away.</p>

Title: Jest with globalsetup doesn't see tests

Body:
Say I have the following test:

describe('foo', () => {
    it('bar', () => {
        expect(1).toBe(2)
    })
})

in a file named foo.application.test.ts

And the following command in my package.json:

jest --testRegex '.*.application.test.ts'"

Running these tests fails, as you would expect. However, changing my command to:

jest --globalSetup ./tests/support/instantiateApplicationTests.ts --testRegex '.*.application.test.ts'"

Results in no tests being run at all ( the global setup file does exist), with the following log:

yarn run v1.22.4
$ jest --globalSetup ./tests/support/instantiateApplicationTests.ts --testRegex '.*.application.test.ts'
✨  Done in 0.81s.

How am I misusing globalsetup here?