问:
is there an easy way to bring a dictionary into a function?
The goal is to play craps with this.

I created a dictionary "all_dice" and I end up passing it through 3 functions before it is used.

There must be an easier way to access the dictionary without just passing it over and over again like this.

```<code>import random
from random import randint

x = 0
the_dice_chosen = ""

##this is the dictionary

all_dice = {"six":
        [["_____",],
        ["0   0",],
        ["0   0",],
        ["0   0",],
        ["_____",],],
        "five":
        [["_____",],
        ["0   0",],
        ["  0  ",],
        ["0   0",],
        ["_____",],],
        "four":
        [["_____",],
        ["0   0",],
        ["     ",],
        ["0   0",],
        ["_____",],],
        "three":
        [["_____",],
        ["0    ",],
        ["  0  ",],
        ["    0",],
        ["_____",],],
        "two":
        [["_____",],
        ["0    ",],
        ["    ",],
        ["    0",],
        ["_____",],],
        "one":
        [["_____",],
        ["     ",],
        ["  0  ",],
        ["     ",],
        ["_____",],],}

## This prints the dictionary of the numbers chosen side by side.
## Again "all_dice" is passed as "ad" and is used.

def dice_print(ndy,ndz,ad):
    x = 0
    nday = ad[ndy]
    ndaz = ad[ndz]
    for i in nday:
        print(nday[x], ndaz[x])
        x = x + 1

##This creates the random dice numbers.

def dice_roller():
    x = randint(1, 6)
    y = randint(1, 6)
    return(x, y)

## This converts the numbers into selections in the dictionary. E.G. 6 into "six" "all_dice" is ad
## and it will from now on be passed as "ad".

def dice_maker(ad,):
    master = {1 : "one",
              2 : "two",
              3 : "three",
              4 : "four",
              5 : "five",
              6 : "six",}
    for i in range(1,2):
        x = dice_roller()
        y = int(x[0])
        z = int(x[1])
        new_die_y = (master[y])
        new_die_z = (master[z])
        dice_print(new_die_y,new_die_z,ad)

##This calls the script to action and passing the dictionary "all_dice"

dice_maker(all_dice)```
```

答:
You can totally discard it as a parameter.

A python module behaves very much like a singleton class. A module, like a class, is an object. all_dice is an attribute of the module and hence accessible to the functions scoped to the same module.

import random
from random import randint

x = 0
the_dice_chosen = ""

##this is the dictionary

all_dice = {"six":
        [["_____",],
        ["0   0",],
        ["0   0",],
        ["0   0",],
        ["_____",],],
        "five":
        [["_____",],
        ["0   0",],
        ["  0  ",],
        ["0   0",],
        ["_____",],],
        "four":
        [["_____",],
        ["0   0",],
        ["     ",],
        ["0   0",],
        ["_____",],],
        "three":
        [["_____",],
        ["0    ",],
        ["  0  ",],
        ["    0",],
        ["_____",],],
        "two":
        [["_____",],
        ["0    ",],
        ["    ",],
        ["    0",],
        ["_____",],],
        "one":
        [["_____",],
        ["     ",],
        ["  0  ",],
        ["     ",],
        ["_____",],],}

## This prints the dictionary of the numbers chosen side by side.
## Again "all_dice" is passed as "ad" and is used.

def dice_print(ndy,ndz):
    x = 0
    nday = all_dice[ndy]
    ndaz = all_dice[ndz]
    for i in nday:
        print(nday[x], ndaz[x])
        x = x + 1

##This creates the random dice numbers.

def dice_roller():
    x = randint(1, 6)
    y = randint(1, 6)
    return(x, y)

## This converts the numbers into selections in the dictionary. E.G. 6 into "six" "all_dice" is ad
## and it will from now on be passed as "ad".

def dice_maker():
    master = {1 : "one",
              2 : "two",
              3 : "three",
              4 : "four",
              5 : "five",
              6 : "six",}
    for i in range(1,2):
        x = dice_roller()
        y = int(x[0])
        z = int(x[1])
        new_die_y = (master[y])
        new_die_z = (master[z])
        dice_print(new_die_y,new_die_z)

##This calls the script to action and passing the dictionary "all_dice"

dice_maker()
```

<h1>The <code>global</code> keyword</h1>

<p>If you require to reassign <code>all_dice</code> in a function. You must add <code>global all_dice</code> to the function.</p>

<pre class="lang-py prettyprint-override"><code>all_dice = None

def set_all_dice(value):
    global all_dice
    all_dice = value

def _set_all_dice(value):
    all_dice = value       ## all_dice here is scoped to the function
</code>```

Body:
The goal is to play craps with this.

I created a dictionary "all_dice" and I end up passing it through 3 functions before it is used.

There must be an easier way to access the dictionary without just passing it over and over again like this.

import random
from random import randint

x = 0
the_dice_chosen = ""

##this is the dictionary

all_dice = {"six":
        [["_____",],
        ["0   0",],
        ["0   0",],
        ["0   0",],
        ["_____",],],
        "five":
        [["_____",],
        ["0   0",],
        ["  0  ",],
        ["0   0",],
        ["_____",],],
        "four":
        [["_____",],
        ["0   0",],
        ["     ",],
        ["0   0",],
        ["_____",],],
        "three":
        [["_____",],
        ["0    ",],
        ["  0  ",],
        ["    0",],
        ["_____",],],
        "two":
        [["_____",],
        ["0    ",],
        ["    ",],
        ["    0",],
        ["_____",],],
        "one":
        [["_____",],
        ["     ",],
        ["  0  ",],
        ["     ",],
        ["_____",],],}

## This prints the dictionary of the numbers chosen side by side.
## Again "all_dice" is passed as "ad" and is used.

def dice_print(ndy,ndz,ad):
    x = 0
    nday = ad[ndy]
    ndaz = ad[ndz]
    for i in nday:
        print(nday[x], ndaz[x])
        x = x + 1

##This creates the random dice numbers.

def dice_roller():
    x = randint(1, 6)
    y = randint(1, 6)
    return(x, y)

## This converts the numbers into selections in the dictionary. E.G. 6 into "six" "all_dice" is ad
## and it will from now on be passed as "ad".

def dice_maker(ad,):
    master = {1 : "one",
              2 : "two",
              3 : "three",
              4 : "four",
              5 : "five",
              6 : "six",}
    for i in range(1,2):
        x = dice_roller()
        y = int(x[0])
        z = int(x[1])
        new_die_y = (master[y])
        new_die_z = (master[z])
        dice_print(new_die_y,new_die_z,ad)

##This calls the script to action and passing the dictionary "all_dice"

dice_maker(all_dice)```

Body:
You can totally discard it as a parameter.

A python module behaves very much like a singleton class. A module, like a class, is an object. all_dice is an attribute of the module and hence accessible to the functions scoped to the same module.

import random
from random import randint

x = 0
the_dice_chosen = ""

##this is the dictionary

all_dice = {"six":
        [["_____",],
        ["0   0",],
        ["0   0",],
        ["0   0",],
        ["_____",],],
        "five":
        [["_____",],
        ["0   0",],
        ["  0  ",],
        ["0   0",],
        ["_____",],],
        "four":
        [["_____",],
        ["0   0",],
        ["     ",],
        ["0   0",],
        ["_____",],],
        "three":
        [["_____",],
        ["0    ",],
        ["  0  ",],
        ["    0",],
        ["_____",],],
        "two":
        [["_____",],
        ["0    ",],
        ["    ",],
        ["    0",],
        ["_____",],],
        "one":
        [["_____",],
        ["     ",],
        ["  0  ",],
        ["     ",],
        ["_____",],],}

## This prints the dictionary of the numbers chosen side by side.
## Again "all_dice" is passed as "ad" and is used.

def dice_print(ndy,ndz):
    x = 0
    nday = all_dice[ndy]
    ndaz = all_dice[ndz]
    for i in nday:
        print(nday[x], ndaz[x])
        x = x + 1

##This creates the random dice numbers.

def dice_roller():
    x = randint(1, 6)
    y = randint(1, 6)
    return(x, y)

## This converts the numbers into selections in the dictionary. E.G. 6 into "six" "all_dice" is ad
## and it will from now on be passed as "ad".

def dice_maker():
    master = {1 : "one",
              2 : "two",
              3 : "three",
              4 : "four",
              5 : "five",
              6 : "six",}
    for i in range(1,2):
        x = dice_roller()
        y = int(x[0])
        z = int(x[1])
        new_die_y = (master[y])
        new_die_z = (master[z])
        dice_print(new_die_y,new_die_z)

##This calls the script to action and passing the dictionary "all_dice"

dice_maker()

The global keyword

If you require to reassign all_dice in a function. You must add global all_dice to the function.

all_dice = None

def set_all_dice(value):
    global all_dice
    all_dice = value

def _set_all_dice(value):
    all_dice = value       ## all_dice here is scoped to the function


来源: stackexchange

问:
access class property using a variable name that user input
so basically I have a class that similar to the following but much longer

```<code>Public Class inventory
    Public Property id As Integer
    Public Property name As String
End Class
</code>```

and in other class I have a list of called order of class inventory
so when I loop over the list I can do as

```<code>For Each i In orders
        Console.WriteLine(i.name)
Next
</code>```

but I want a variable to be in the spot .
so like

```<code>Dim rrr As String = Console.ReadLine()
For Each i In orders
     Console.WriteLine(i.rrr)
Next
</code>```

however I get error as rrr is not a member in inventory!
so please any one know how to solve that and be able to access the class from a variable let me know
Thanks

答:
An answer is provided at Get property value from string using reflection in C# but it is C#. Following is vb.net translation.

Public Class inventory
    Public Property id As Integer
    Public Property name As String
    'I added a custom constructor to make filling a list easier for me
    Public Sub New(i As Integer, n As String)
        id = i
        name = n
    End Sub
    'add back default constructor
    Public Sub New()

    End Sub
End Class

Private orders As New List(Of inventory) From {New inventory(1, "Apples"), New inventory(2, "Oranges"), New inventory(3, "Pears")}

Private Sub OPCode()
    Dim rrr As String = "name" 'Console.ReadLine() as if user typed in name
    For Each i In orders
        Console.WriteLine(GetPropertyValue(i, rrr))
    Next
End Sub

Private Function GetPropertyValue(src As Object, PropName As String) As Object
    Return src.GetType().GetProperty(PropName).GetValue(src, Nothing)
End Function
```

Output:

Apples

Oranges

Pears

ContentLicense: CC BY-SA 4.0

Body:
so basically I have a class that similar to the following but much longer

Public Class inventory
    Public Property id As Integer
    Public Property name As String
End Class

and in other class I have a list of called order of class inventory
so when I loop over the list I can do as

For Each i In orders
        Console.WriteLine(i.name)
Next

but I want a variable to be in the spot .
so like

Dim rrr As String = Console.ReadLine()
For Each i In orders
     Console.WriteLine(i.rrr)
Next

however I get error as rrr is not a member in inventory!
so please any one know how to solve that and be able to access the class from a variable let me know
Thanks

Body:
An answer is provided at Get property value from string using reflection in C# but it is C#. Following is vb.net translation.

Public Class inventory
    Public Property id As Integer
    Public Property name As String
    'I added a custom constructor to make filling a list easier for me
    Public Sub New(i As Integer, n As String)
        id = i
        name = n
    End Sub
    'add back default constructor
    Public Sub New()

    End Sub
End Class

Private orders As New List(Of inventory) From {New inventory(1, "Apples"), New inventory(2, "Oranges"), New inventory(3, "Pears")}

Private Sub OPCode()
    Dim rrr As String = "name" 'Console.ReadLine() as if user typed in name
    For Each i In orders
        Console.WriteLine(GetPropertyValue(i, rrr))
    Next
End Sub

Private Function GetPropertyValue(src As Object, PropName As String) As Object
    Return src.GetType().GetProperty(PropName).GetValue(src, Nothing)
End Function

Output:

Apples

Oranges

Pears


问:
DNS - Firebase connect to Namecheap still says Needs setup?
Ok, it has been less than 24 hrs but more than 10, and I find it odd that I am still getting a status of Needs setup in Firebase just trying to redirect to a custom domain, bought with Namecheap. I don't know what Im doing wrong but I still get the "insecure connection" error trying to access my site.

Here are the records specified in Firebase to be added to my Namecheap records:

Namecheap is in accordance:

I used @ for the same host as specified by Namecheap - is something wrong? How long should this take if not?

答:
Yes, as stated on firebase docs

https://firebase.google.com/docs/hosting/custom-domain#dns-records-namecheap

ContentLicense: CC BY-SA 3.0


问:
Composer not installing on windows machine
I am very new to web development and mostly following tutorials so, I am learning laravel and I want to install composer. I downloaded the setup from the composer website and manually added the PHP path in environment variable I am using xampp. when I run the installer I get this error

"The Composer installer script did not run correctly because composer.phar was not downloaded."

error screenshot

答:
2 ways you could fix it,

Run the following command in the cmd:

php -r "eval('?>'.file_get_contents('http://getcomposer.org/installer'));"

Uninstall and then re-install and run as administrator(run the .exe if you're on windows)

The first one fixed mine once.


问:
Use COUNTIFS with two criteria?
I am stuck please help me,
basically I want use a formula which counts data within the day range that ı have defined and also counts just the name I describe.
Likes data which is in photo enter image description here

I want to learn just Anthony's done works number but just in first month like in 1/1/2019-1/30/2019

Sample Data

```<code>NAME       DATE        IS THERE ANY DONE WORK IN THIS DATE
anthony    1/1/2019    YES
jacob      1/25/2019   YES
anthony    1/30/2019   YES
justin     2/1/2019    YES
marc       2/5/2019    YES
anthony    3/1/2019    YES
jacob      3/1/2019    YES
</code>```

答: ı changed the data image.Can you look again ? ı want count the data whıch i said and see in other sheet page like images and also want when ı change name from list it should changed datas.    1: https://i.stack.imgur.com/bRWtW.png    2: https://i.stack.imgur.com/sJAAN.png    3: https://i.stack.imgur.com/NKT97.png</p>

Title: Use COUNTIFS with two criteria?

Body:
I am stuck please help me,
basically I want use a formula which counts data within the day range that ı have defined and also counts just the name I describe.
Likes data which is in photo enter image description here

I want to learn just Anthony's done works number but just in first month like in 1/1/2019-1/30/2019

Sample Data

NAME       DATE        IS THERE ANY DONE WORK IN THIS DATE
anthony    1/1/2019    YES
jacob      1/25/2019   YES
anthony    1/30/2019   YES
justin     2/1/2019    YES
marc       2/5/2019    YES
anthony    3/1/2019    YES
jacob      3/1/2019    YES


问:
Select all values with the same key in a dict
I am using an API to get some financial data from companies.

API https://financialmodelingprep.com/api/v3/financials/income-statement/TD

How can I select all values for the key revenue?

```<code>import urllib.request
import json

income_statement = ('https://financialmodelingprep.com/api/v3/financials/income-statement/TD')

response = urllib.request.urlopen(income_statement)
parseResponse = json.loads(response.read())

test = (parseResponse['financials'][0]['Revenue'])
</code>```

This will give me the number, but not for all key = Revenue.

答:
You will need to loop through the financials array and stored all the revenues inside another array. Something like

```<code>all_revenue = [item['Revenue'] for item in parseResponse['financials']]
</code>```

Body:
I am using an API to get some financial data from companies.

API https://financialmodelingprep.com/api/v3/financials/income-statement/TD

How can I select all values for the key revenue?

import urllib.request
import json

income_statement = ('https://financialmodelingprep.com/api/v3/financials/income-statement/TD')

response = urllib.request.urlopen(income_statement)
parseResponse = json.loads(response.read())

test = (parseResponse['financials'][0]['Revenue'])

This will give me the number, but not for all key = Revenue.

Body:
You will need to loop through the financials array and stored all the revenues inside another array. Something like

all_revenue = [item['Revenue'] for item in parseResponse['financials']]


问:
C#/Java portability
What mainstream frameworks, patterns, and tools would you choose to develop two projects in parallel, one in C#, one in Java, in order to minimize the total effort. (Disregard the obvious cases of interchangeable or equivalent tools, like SCC, Unit Testing, etc. Also assume generic broad RDBMS support.)

"Mainstream" means the market in general won't disregard the result because it uses something untested they've never heard of, or arcane skills are required to implement and support it.

Assume a broadly applicable tactical business appication.

答:
Why would you want to develop for Java and C# in parallel?

You could just use Java and J#. The only problem is, that J# is stuck at Java 1.4 level, so you have two choices:

don't use this fancy stuff like enums, generics, for-each

use a tool like retroweaver to convert 1.5 back to 1.4

I've just finished building a mid-size application (about 80 classes / 30.000 lines) that runs nicely on Java and .NET this way.

As far as I know, the Java Classes compiled by J# are .NET-bytecode that is like any other .NET-bytecode, and can be used in C#. But you don't have to code your core classes twice.

OwnerDisplayName: doofledorfer

ContentLicense: CC BY-SA 2.5

Title: C#/Java portability

OwnerDisplayName: Brian Schimmel


问:
How can I extract three characters at a time from a Python string?
I want to write a function that takes a long string of characters (a protein sequence like 'UGGUGUUAUUAAUGGUUU') and extracts three characters at a time from it (i.e. the codons). It can either return each set of three characters one after another, or a list containing all the sets of three characters. Either way would work. But I'm having some trouble figuring out exactly how to do this cleanly.

Here's what I have so far:

```<code>def get_codon_list(codon_string):
    codon_start = 0
    codon_length = 3
    codon_end = 3
    codon_list = []
    for x in range(len(codon_string) // codon_length):
        codon_list.append(codon_string[codon_start:codon_end])
        codon_start += codon_length
        codon_end += codon_length
    return codon_list
</code>```

It works to return a list of the codons, but it seems very inefficient. I don't like using hard-coded numbers and incrementing variables like that if there is a better way. I also don't like using for loops that don't actually use the variable in the loop. It doesn't seem like a proper use of it.

Any suggestions for how to improve this, either with a specific function/module, or just a better Pythonic technique?

Thanks!

答: You might want to use a while loop here and increment the index by 3 each iteration, printing the next three letters, and exiting when the inedex is within 3 of the length</p>

Body:
I want to write a function that takes a long string of characters (a protein sequence like 'UGGUGUUAUUAAUGGUUU') and extracts three characters at a time from it (i.e. the codons). It can either return each set of three characters one after another, or a list containing all the sets of three characters. Either way would work. But I'm having some trouble figuring out exactly how to do this cleanly.

Here's what I have so far:

def get_codon_list(codon_string):
    codon_start = 0
    codon_length = 3
    codon_end = 3
    codon_list = []
    for x in range(len(codon_string) // codon_length):
        codon_list.append(codon_string[codon_start:codon_end])
        codon_start += codon_length
        codon_end += codon_length
    return codon_list

It works to return a list of the codons, but it seems very inefficient. I don't like using hard-coded numbers and incrementing variables like that if there is a better way. I also don't like using for loops that don't actually use the variable in the loop. It doesn't seem like a proper use of it.

Any suggestions for how to improve this, either with a specific function/module, or just a better Pythonic technique?

Thanks!


问:
Import ReactJS component from another file?
I'm new to React. Want to develop an app using little components in separate files and import them to my App.js

I tried but not be able to figure out what I'm doing wrong.

Here is my html:

```<code><!DOCTYPE html>
<html>
<head>
    <title>App</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <script src="https://unpkg.com/react@15.3.2/dist/react.js"></script>
    <script src="https://unpkg.com/react-dom@15.3.2/dist/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
</head>
<body>

<script type="text/babel" src="js/App.js"></script>

</body>
</html>
</code>```

This is my App.js: (From js/ directory)

```<code>import MyComp from 'components/MyComp';

class App extends React.Component {
    render() {
        return (
            <MyComp />
        )
    }
}

ReactDOM.render(
    <App />,
    document.body
);
</code>```

And this is my MyComp.js (From js/components/ directory)

```<code>class MyComp extends React.Component{

    render() {
        return (
            <div>
                Hello World!
            </div>
        )
    }

}

export default MyComp;
</code>```

If I try this way I see nothing. Whereas if I create MyComp class in App.js it works like a charm.

Any suggestion what am I doing wrong?

答:
Try with

./components/MyComp

if you are using visual studio code, you could explore your components from any .js file by start typing ./ like this:

Body:
I'm new to React. Want to develop an app using little components in separate files and import them to my App.js

I tried but not be able to figure out what I'm doing wrong.

Here is my html:

<!DOCTYPE html>

    <title>App</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">

This is my App.js: (From js/ directory)

import MyComp from 'components/MyComp';

class App extends React.Component {
    render() {
        return (
            <MyComp />
        )
    }
}

ReactDOM.render(
    <App />,
    document.body
);

And this is my MyComp.js (From js/components/ directory)

class MyComp extends React.Component{

    render() {
        return (

                Hello World!

        )
    }

}

export default MyComp;

If I try this way I see nothing. Whereas if I create MyComp class in App.js it works like a charm.

Any suggestion what am I doing wrong?


问:
Filter specific value from Tshark JSON output
I would like to extract the "tls.handshake.certificate_raw" values, but without success so far. The big JSON is killing me.

Here's my JSON file: Download

Thanks in advance!

答:
Since the JSON has objects with duplicate keys, an approach that does not use jq's normal object semantics is warranted.

jq's streaming parser (invoked with the --stream option) allows one to handle objects with duplicate keys:

```<code>jq --stream -c '(.[0]|index("tls.handshake.certificate_raw")) as $ix
                | select($ix) | .[0] |= .[$ix+1:]' Tshark.json |
    jq -nc 'fromstream(inputs)'

</code>```

This produces 503 entities, the first of which is:

```<code>["[encoded data, 4550 characters]",109,2275,0,30]

</code>```

Explanation

The first invocation of jq uses jq's streaming parser to extract the [path, atomicValue] pairs of interest. The second invocation reconstructs the relevant entities.

Resources

Here are the main stats from a run using /usr/bin/time -lp on a Mac Mini:

```<code>real         5.35
user         5.31
sys          0.05
  13279232  maximum resident set size
</code>```

Body:
Since the JSON has objects with duplicate keys, an approach that does not use jq's normal object semantics is warranted.

jq's streaming parser (invoked with the --stream option) allows one to handle objects with duplicate keys:

jq --stream -c '(.[0]|index("tls.handshake.certificate_raw")) as $ix
                | select($ix) | .[0] |= .[$ix+1:]' Tshark.json |
    jq -nc 'fromstream(inputs)'

This produces 503 entities, the first of which is:

["[encoded data, 4550 characters]",109,2275,0,30]

Explanation

The first invocation of jq uses jq's streaming parser to extract the [path, atomicValue] pairs of interest. The second invocation reconstructs the relevant entities.

Resources

Here are the main stats from a run using /usr/bin/time -lp on a Mac Mini:

real         5.35
user         5.31
sys          0.05
  13279232  maximum resident set size


问:
How to delete multiple occurrences of multiple variables in a linked list in c
I am a beginner in c programming and i have been trying for several days to solve the following question:

how to remove numbers that appear at least 3 times in the following list:

3→3→1→2→4→3→5→3→5→4

which makes the result:

1→2→4→5→5→4.

Now i know how to delete multiple occurrences of "one" key in a linked list, for example deleting all occurrences of "1" in the linked list, but can't seem to understand how to delete multiple occurrences of multiple variables. It's just killing me. I would really appreciate it if anyone could help. thanks in advance.

答:
It seems nobody hurries to help you.:)

It is simpler to write the function if to pass the pointer head to the function by reference.

Here is a demonstrative program that shows how the function can be implemented.

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

struct Node
{
    int data;
    struct Node *next;
};

int insert( struct Node **head, int data )
{
    struct Node *node = malloc( sizeof( struct Node ) );
    int success = node != NULL;

    if ( success )
    {
        node->data = data;
        node->next = *head;
        *head = node;
    }

    return success;
}

void out( struct Node *head )
{
    for ( ; head != NULL; head = head->next )
    {
        printf( "%d -> ", head->data );
    }
    puts( "null" );
}

void remove_repetitive( struct Node **head )
{
    const size_t LIMIT = 3;

    while ( *head != NULL )
    {
        size_t count = 1;

        int data = ( *head )->data;

        for ( struct Node *node = ( *head )->next;
              count < LIMIT && node != NULL; node = node->next )
        {
            if ( node->data == data ) ++count;
        }

        if ( count == LIMIT )
        {
            for ( struct Node **node = head; *node != NULL; )
            {
                if ( ( *node )->data == data )
                {
                    struct Node *tmp = *node;
                    *node = ( *node )->next;
                    free( tmp );
                }
                else
                {
                    node = &( *node )->next;
                }
            }
        }
        else
        {
            head = &( *head )->next;
        }
    }
}

int main(void)
{
    struct Node *head = NULL;
    int a[] = { 4, 5, 3, 5, 3, 4, 2, 1, 3, 3 };

    const size_t N = sizeof( a ) / sizeof( *a );

    for ( size_t i = 0; i < N; i++ )
    {
        insert( &head, a[i] );
    }

    out( head );

    remove_repetitive( &head );

    out( head );

    return 0;
}
</code>```

The program output is

```<code>3 -> 3 -> 1 -> 2 -> 4 -> 3 -> 5 -> 3 -> 5 -> 4 -> null
1 -> 2 -> 4 -> 5 -> 5 -> 4 -> null
</code>```

The function remove_repetitive can be splitted out into two functions as it is shown below.

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

struct Node
{
    int data;
    struct Node *next;
};

int insert( struct Node **head, int data )
{
    struct Node *node = malloc( sizeof( struct Node ) );
    int success = node != NULL;

    if ( success )
    {
        node->data = data;
        node->next = *head;
        *head = node;
    }

    return success;
}

void out( struct Node *head )
{
    for ( ; head != NULL; head = head->next )
    {
        printf( "%d -> ", head->data );
    }
    puts( "null" );
}

void remove_all( struct Node **head, int data )
{
    while ( *head != NULL )
    {
        if ( ( *head )->data == data )
        {
            struct Node *tmp = *head;
            *head = ( *head )->next;
            free( tmp );
        }
        else
        {
            head = &( *head )->next;
        }
    }
}

void remove_repetitive( struct Node **head )
{
    const size_t LIMIT = 3;

    while ( *head != NULL )
    {
        size_t count = 1;

        int data = ( *head )->data;

        for ( struct Node *node = ( *head )->next;
              count < LIMIT && node != NULL; node = node->next )
        {
            if ( node->data == data ) ++count;
        }

        if ( count == LIMIT )
        {
            remove_all( head, data );
        }
        else
        {
            head = &( *head )->next;
        }
    }
}

int main(void)
{
    struct Node *head = NULL;
    int a[] = { 4, 5, 3, 5, 3, 4, 2, 1, 3, 3 };

    const size_t N = sizeof( a ) / sizeof( *a );

    for ( size_t i = 0; i < N; i++ )
    {
        insert( &head, a[i] );
    }

    out( head );

    remove_repetitive( &head );

    out( head );

    return 0;
}
</code>```

The program output is the same as shown above.

Body:
It seems nobody hurries to help you.:)

It is simpler to write the function if to pass the pointer head to the function by reference.

Here is a demonstrative program that shows how the function can be implemented.

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

struct Node
{
    int data;
    struct Node *next;
};

int insert( struct Node **head, int data )
{
    struct Node *node = malloc( sizeof( struct Node ) );
    int success = node != NULL;

    if ( success )
    {
        node->data = data;
        node->next = *head;
        *head = node;
    }

    return success;
}

void out( struct Node *head )
{
    for ( ; head != NULL; head = head->next )
    {
        printf( "%d -> ", head->data );
    }
    puts( "null" );
}

void remove_repetitive( struct Node **head )
{
    const size_t LIMIT = 3;

    while ( *head != NULL )
    {
        size_t count = 1;

        int data = ( *head )->data;

        for ( struct Node *node = ( *head )->next;
              count < LIMIT && node != NULL; node = node->next )
        {
            if ( node->data == data ) ++count;
        }

        if ( count == LIMIT )
        {
            for ( struct Node **node = head; *node != NULL; )
            {
                if ( ( *node )->data == data )
                {
                    struct Node *tmp = *node;
                    *node = ( *node )->next;
                    free( tmp );
                }
                else
                {
                    node = &( *node )->next;
                }
            }
        }
        else
        {
            head = &( *head )->next;
        }
    }
}

int main(void)
{
    struct Node *head = NULL;
    int a[] = { 4, 5, 3, 5, 3, 4, 2, 1, 3, 3 };

    const size_t N = sizeof( a ) / sizeof( *a );

    for ( size_t i = 0; i < N; i++ )
    {
        insert( &head, a[i] );
    }

    out( head );

    remove_repetitive( &head );

    out( head );

    return 0;
}

The program output is

3 -> 3 -> 1 -> 2 -> 4 -> 3 -> 5 -> 3 -> 5 -> 4 -> null
1 -> 2 -> 4 -> 5 -> 5 -> 4 -> null

The function remove_repetitive can be splitted out into two functions as it is shown below.

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

struct Node
{
    int data;
    struct Node *next;
};

int insert( struct Node **head, int data )
{
    struct Node *node = malloc( sizeof( struct Node ) );
    int success = node != NULL;

    if ( success )
    {
        node->data = data;
        node->next = *head;
        *head = node;
    }

    return success;
}

void out( struct Node *head )
{
    for ( ; head != NULL; head = head->next )
    {
        printf( "%d -> ", head->data );
    }
    puts( "null" );
}

void remove_all( struct Node **head, int data )
{
    while ( *head != NULL )
    {
        if ( ( *head )->data == data )
        {
            struct Node *tmp = *head;
            *head = ( *head )->next;
            free( tmp );
        }
        else
        {
            head = &( *head )->next;
        }
    }
}

void remove_repetitive( struct Node **head )
{
    const size_t LIMIT = 3;

    while ( *head != NULL )
    {
        size_t count = 1;

        int data = ( *head )->data;

        for ( struct Node *node = ( *head )->next;
              count < LIMIT && node != NULL; node = node->next )
        {
            if ( node->data == data ) ++count;
        }

        if ( count == LIMIT )
        {
            remove_all( head, data );
        }
        else
        {
            head = &( *head )->next;
        }
    }
}

int main(void)
{
    struct Node *head = NULL;
    int a[] = { 4, 5, 3, 5, 3, 4, 2, 1, 3, 3 };

    const size_t N = sizeof( a ) / sizeof( *a );

    for ( size_t i = 0; i < N; i++ )
    {
        insert( &head, a[i] );
    }

    out( head );

    remove_repetitive( &head );

    out( head );

    return 0;
}

The program output is the same as shown above.


问:
Find the number of previous consecutive occurences of value different than current row value in pandas dataframe
Assume that we have the following pandas dataframe:

```<code>df = pd.DataFrame({'x':[0,0,1,0,0,0,0],'y':[1,1,1,1,1,1,0],'z':[0,1,1,1,0,0,1]})

   x  y  z
0  0  1  0
1  0  1  1
2  1  1  1
3  0  1  1
4  0  1  0
5  0  1  0
6  0  0  1
</code>```

All dataframe is filled either by 1 or 0. Looking at each column separately, if current row value is different than previous value I need to count number of previous consecutive values:

```<code>   x  y  z
0
1        1
2  2
3  1
4        3
5
6     6  2
</code>```

I tried to write a lambda function and apply it to entire dataframe, but I failed. Any idea?

答:
You can try the following, where you identify the "runs" first, get the "runs" lengths. You will only entry at where it switches, so it is the lengths of the runs except the last one.

```<code>import pandas as pd
import numpy as np

def func(x,missing=np.NaN):
        runs = np.cumsum(np.append(0,np.diff(x)!=0))
        switches = np.where(np.diff(x!=0))[0] + 1
        out = np.repeat(missing,len(x))
        out[switches] = np.bincount(runs)[:-1]
        # thanks to Scott see comments below
        ##out[switches] = pd.value_counts(runs,sort=False)[:-1]
        return(out)

df.apply(func)

    x   y   z
0   NaN NaN NaN
1   NaN NaN 1.0
2   2.0 NaN NaN
3   1.0 NaN NaN
4   NaN NaN 3.0
5   NaN NaN NaN
6   NaN 6.0 2.0
</code>```

It might be faster with a good implementation of run length encoding.. but I am not too familiar with it in python..

Body:
Assume that we have the following pandas dataframe:

df = pd.DataFrame({'x':[0,0,1,0,0,0,0],'y':[1,1,1,1,1,1,0],'z':[0,1,1,1,0,0,1]})

   x  y  z
0  0  1  0
1  0  1  1
2  1  1  1
3  0  1  1
4  0  1  0
5  0  1  0
6  0  0  1

All dataframe is filled either by 1 or 0. Looking at each column separately, if current row value is different than previous value I need to count number of previous consecutive values:

   x  y  z
0
1        1
2  2
3  1
4        3
5
6     6  2

I tried to write a lambda function and apply it to entire dataframe, but I failed. Any idea?

Body:
You can try the following, where you identify the "runs" first, get the "runs" lengths. You will only entry at where it switches, so it is the lengths of the runs except the last one.

import pandas as pd
import numpy as np

def func(x,missing=np.NaN):
        runs = np.cumsum(np.append(0,np.diff(x)!=0))
        switches = np.where(np.diff(x!=0))[0] + 1
        out = np.repeat(missing,len(x))
        out[switches] = np.bincount(runs)[:-1]
        # thanks to Scott see comments below
        ##out[switches] = pd.value_counts(runs,sort=False)[:-1]
        return(out)

df.apply(func)

    x   y   z
0   NaN NaN NaN
1   NaN NaN 1.0
2   2.0 NaN NaN
3   1.0 NaN NaN
4   NaN NaN 3.0
5   NaN NaN NaN
6   NaN 6.0 2.0

It might be faster with a good implementation of run length encoding.. but I am not too familiar with it in python..


问:
Ignoring method calls in Mockito
With Mockito, is it possible to ignore a method call to a mock?

E.g. for the mock rugger created with mock(MyRugger.class):

```<code>class Pepe {

  public void runner() {
    rugger.doIt();
    rugger.flushIt();
    rugger.boilIt();
  }
}
</code>```

I need only test runner() but avoid the method flushIt().

答:
Mockito is nice and will not verify calls unless you ask it to.  So if you don't want to verify flush() just verify the methods you care about:

```<code>verify(rugger).doIt();
verify(rugger).boilIt();
</code>```

If you want to verify that flush() was NOT called, use:

```<code>verify(rugger, never()).flush();
</code>```

Title: Ignoring method calls in Mockito

Body:
With Mockito, is it possible to ignore a method call to a mock?

E.g. for the mock rugger created with mock(MyRugger.class):

class Pepe {

  public void runner() {
    rugger.doIt();
    rugger.flushIt();
    rugger.boilIt();
  }
}

I need only test runner() but avoid the method flushIt().

Body:
Mockito is nice and will not verify calls unless you ask it to.  So if you don't want to verify flush() just verify the methods you care about:

verify(rugger).doIt();
verify(rugger).boilIt();

If you want to verify that flush() was NOT called, use:

verify(rugger, never()).flush();


问:
Store Data in TPM using CNG NCryptOpenStorageProvider in Windows
I am trying to store the key in TPM using CNG NCryptOpenStorageProvide "MS_PLATFORM_CRYPTO_PROVIDER".

Please any one help on How to use CNG functions for accessing TPM read and Write.

答:
Assuming by "store a key in TPM" you mean "create a persisted key in the TPM":

```<code>NCRYPT_PROV_HANDLE hProv = NULL;
NCRYPT_KEY_HANDLE hKey = NULL;
PCWSTR keyName = L"MyKey";

NCryptOpenStorageProvider(
        &hProv,
        MS_PLATFORM_CRYPTO_PROVIDER,
        0);
NCryptCreatePersistedKey(
        hProv,
        &hKey,
        BCRYPT_RSA_ALGORITHM,
        keyName,
        0,
        NCRYPT_OVERWRITE_KEY_FLAG);
NCryptFinalizeKey(hKey, 0);
</code>```

Obviously you should check the return code of each invoked function.

Body:
Assuming by "store a key in TPM" you mean "create a persisted key in the TPM":

NCRYPT_PROV_HANDLE hProv = NULL;
NCRYPT_KEY_HANDLE hKey = NULL;
PCWSTR keyName = L"MyKey";

NCryptOpenStorageProvider(
        &hProv,
        MS_PLATFORM_CRYPTO_PROVIDER,
        0);
NCryptCreatePersistedKey(
        hProv,
        &hKey,
        BCRYPT_RSA_ALGORITHM,
        keyName,
        0,
        NCRYPT_OVERWRITE_KEY_FLAG);
NCryptFinalizeKey(hKey, 0);

Obviously you should check the return code of each invoked function.


问:
How to pass the in-line editable mat-table data into the service using angular8?
I have prepared the editable dynamic column/rows Mat-Table. I have entered the data into the each cell. After Click on submit button how to get/iterate formArray/formgroup data (like json) and construct json object to send to the service. I am unalbe to get this,Could you please help on this?

Link:https://stackblitz.com/edit/angular-zazofh

答: In your "onSaveClick()" method if you use "this.myformArray.value" it will return an array of objects. Which is pretty versatile for making a post request or sending the data elsewhere. You can also use methods JSON.parse() and JSON.stringify() to get the formatted JSON data.</p>


问:
R: Dynamically Splitting A Data Frame
I have a one column data frame.  The length varies between 60,000 and 500,000 rows.

I would like to split the data frame into smaller data frames with 45,000 rows plus an additional data frame with any remaining rows.  For example, if my starting data frame has 90,100 rows, the result should be 3 data frames - 2 with 45000 rows and 1 with 100 rows.

I would like to be able to subsequently process each of the resulting data frames in a for loop.

Is there a way to do this in R?

答:
We can use split to create a list of data.frame by splitting on a grouping index created with gl

```<code>lst1 <- split(df1,  as.integer(gl(nrow(df1), 45000, nrow(df1))))
length(lst1)
#[1] 3
sapply(lst1, nrow)
#     1     2     3
# 45000 45000   100
</code>```

data

```<code>set.seed(24)
df1 <- data.frame(col1 = rnorm(90100), col2 = runif(90100), id = 1:90100)
</code>```

Title: R: Dynamically Splitting A Data Frame

Body:
We can use split to create a list of data.frame by splitting on a grouping index created with gl

lst1 <- split(df1,  as.integer(gl(nrow(df1), 45000, nrow(df1))))
length(lst1)
#[1] 3
sapply(lst1, nrow)
#     1     2     3
# 45000 45000   100

data

set.seed(24)
df1 <- data.frame(col1 = rnorm(90100), col2 = runif(90100), id = 1:90100)


问:
I wrote a function for a math formula, may I ask you please check my code?
For my research, I needed to calculate some formula. I create a function for it. This is the very first time for me to write a function and also the first time to write a math formula in Matlab language. May I please ask you to check if where I do wrong?

Here is formula

And here is the function I wrote (P is x and P^ is y):

```<code>function biass = BIASS(x,y)
%This function calculates biass error
%   Detailed explanation goes here
H = sum(y-x)/sum(y)
biass = H * 100
end
</code>```

I'm not sure about results because I believe they are not reasonable.

答:
A slightly more efficient way to compute this is

```<code>100 * (sum(y) / sum(x) - 1)
</code>```

since your expression can be simplified.

Body:
For my research, I needed to calculate some formula. I create a function for it. This is the very first time for me to write a function and also the first time to write a math formula in Matlab language. May I please ask you to check if where I do wrong?

Here is formula

And here is the function I wrote (P is x and P^ is y):

function biass = BIASS(x,y)
%This function calculates biass error
%   Detailed explanation goes here
H = sum(y-x)/sum(y)
biass = H * 100
end

I'm not sure about results because I believe they are not reasonable.

Body:
A slightly more efficient way to compute this is

100 * (sum(y) / sum(x) - 1)

since your expression can be simplified.


问:
Is there a way to log printk's somewhere from cabbage plugins inside DAWs?
Is there a way to log the printk's from a Cabbage plugin somewhere when it's running inside a DAW? Unlike the classic CsoundVST, with Cabbage you don't get a default log window in the plugin itself, but only in its Cabbage host (the Cabbage "IDE" if you like).

So, when running a Cabbage plugin inside a DAW, is there a simple enough way to get logging from the plugin logging somewhere, e.g. to a file? (I guess I could make a scroll box and write in it, but it seem a bit much work for a simple function).

答:
I feel pretty dumb right now, as there's a Cabbage widget just for this although its name was not 100% obvious when I was scanning the list of widgets... csoundoutput.

Csoundoutput will display Csound output messages within your instrument`s GUI. This widget can be very useful when working in plugin mode and can be invaluable when it comes to de-slugging Cabbage instruments.

Funnily I found it when I looking for a built-in VU meter widget, which also exists, but oddly it doesn't show up n the documentation index on the website at the moment.


问:
Managing theme from firefox extension
Is there a way to change themes dynamically from an add-on based on some criteria?
Or at least change the header picture.

Thanks in advance,

答:
For Firefox before version 4:

If the extensions.dss.enabled preference is set, set the general.skins.selectedSkin preference to the theme's internal name. Otherwise set the extensions.lastSelectedSkin preference to the theme's internal name and restart Firefox. Note: This is for standard themes, I don't know whether this applies to Personas.

For Firefox 4 and later:

Obtain a reference to the theme object from the Add-on Manager and set its userDisabled property to false. If it is a Persona, then it will apply instantly, and its isActive property will become true. Otherwise you will need to restart Firefox.

Title: Managing theme from firefox extension


问:
How to write aggregate function of mongo for the following condition
I have a collection in mongo, which consists of approx half a million documents, and from that i want a sum of a specific field with specific ids.

For example :

a single document has a field of meter_id and total power.
So i want to seperate documents having same meter ids and then calculate the total power for each collection having same meter id.

example document:

```<code>_id:5e444fc1c5e86c84d1044aeb
meter_id:"jhk"
date:2017-06-17T18:39:28.795+00:00
activePower:Object
unit:"kwh"
Active Power L1:"0"
Active Power L2:"0"
Active Power L3:"0"
Total Active Power:"5"
reactivePower:Object
apparentPower:Object
frequency:Object
thd:Object
</code>```

now i have to group by meter ids and want the total of total active power field which is a key-value for active power object

expected output:

```<code>{ _id: 'jhk', total: 69236, totalAmount:  }
</code>```

答:
Try this :

Query :

```<code>db.collection.aggregate([{$group :{_id : '$meter_id', total : {$sum : { $toInt : '$activePower.TotalActivePower'}}}}])
</code>```

Test : MongoDB-Playground

Note : It seems like your $activePower.TotalActivePower field is a string, if it is then we need to use $toInt to convert it into number in order to calculate the sum across all documents matching to an _id criteria.

Body:
I have a collection in mongo, which consists of approx half a million documents, and from that i want a sum of a specific field with specific ids.

For example :

a single document has a field of meter_id and total power.
So i want to seperate documents having same meter ids and then calculate the total power for each collection having same meter id.

example document:

_id:5e444fc1c5e86c84d1044aeb
meter_id:"jhk"
date:2017-06-17T18:39:28.795+00:00
activePower:Object
unit:"kwh"
Active Power L1:"0"
Active Power L2:"0"
Active Power L3:"0"
Total Active Power:"5"
reactivePower:Object
apparentPower:Object
frequency:Object
thd:Object

now i have to group by meter ids and want the total of total active power field which is a key-value for active power object

expected output:

{ _id: 'jhk', total: 69236, totalAmount:  }

Body:
Try this :

Query :

db.collection.aggregate([{$group :{_id : '$meter_id', total : {$sum : { $toInt : '$activePower.TotalActivePower'}}}}])

Test : MongoDB-Playground

Note : It seems like your $activePower.TotalActivePower field is a string, if it is then we need to use $toInt to convert it into number in order to calculate the sum across all documents matching to an _id criteria.


问:
Why react `useRef` hook stores the objects in `current` property? Why cant it store directly in the ref object?
Why does the object returned by the useRef hook stores whatever value it's supposed to hold in current property? Why can't we assign something directly into the ref object as shown below:

```<code>const sampleRef = useRef([]);

/** why can't we do this... */
sampleRef.push('1');

/** ...instead of this? Why an extra `current` object? */
sampleRef.current.pus('1');
</code>```

What is the purpose of useRef returning the argument wrapped inside another object with current property?

答:
I'm trying to answer the root cause of your question, which I interpret to be something like: "It seems that we should not need an intermediate object with a .current property." You're correct. We don't. Whatever the actual reason regarding useRef, I have noticed it is possible to instead do something like the following, which has the kind of syntax you were asking for in your question (the elimination of .current). Please note this is an advanced usage that actually creates a component local cache like useRef, but that doesn't talk to the DOM.:

```<code>//note foo is in array brackets by itself
const [foo /*no setFoo here*/] = useState({bar:"baz"});
...
foo.bar="hello"
</code>```

or

```<code>//note foo in brackets by itself
const [foo /*no setFoo here*/] = useState([]);
...
foo.push(1);
</code>```

This lets us directly mutate foo's properties without using .current. As long as we never call setFoo, mutating foo's properties will not cause a rerender on its own. The value of foo itself is never changed, since it always points to the same object or array.

However, it is possible, just as with any other variables including useRef ones, to cause a useEffect hook to rerun after a rerender if a changed property like foo.bar appears in the 2nd argument array of the useEffect.

I haven't tried let [foo]= useState("whatever") yet. In that case, we'd be altering the actual value of foo, and depending on React to give that altered value back to us on subsequent rerenders, even though we never notified React of the change. Seems sketchy.

Body:
Why does the object returned by the useRef hook stores whatever value it's supposed to hold in current property? Why can't we assign something directly into the ref object as shown below:

const sampleRef = useRef([]);

/** why can't we do this... */
sampleRef.push('1');

/** ...instead of this? Why an extra `current` object? */
sampleRef.current.pus('1');

What is the purpose of useRef returning the argument wrapped inside another object with current property?

Body:
I'm trying to answer the root cause of your question, which I interpret to be something like: "It seems that we should not need an intermediate object with a .current property." You're correct. We don't. Whatever the actual reason regarding useRef, I have noticed it is possible to instead do something like the following, which has the kind of syntax you were asking for in your question (the elimination of .current). Please note this is an advanced usage that actually creates a component local cache like useRef, but that doesn't talk to the DOM.:

//note foo is in array brackets by itself
const [foo /*no setFoo here*/] = useState({bar:"baz"});
...
foo.bar="hello"

or

//note foo in brackets by itself
const [foo /*no setFoo here*/] = useState([]);
...
foo.push(1);

This lets us directly mutate foo's properties without using .current. As long as we never call setFoo, mutating foo's properties will not cause a rerender on its own. The value of foo itself is never changed, since it always points to the same object or array.

However, it is possible, just as with any other variables including useRef ones, to cause a useEffect hook to rerun after a rerender if a changed property like foo.bar appears in the 2nd argument array of the useEffect.

I haven't tried let [foo]= useState("whatever") yet. In that case, we'd be altering the actual value of foo, and depending on React to give that altered value back to us on subsequent rerenders, even though we never notified React of the change. Seems sketchy.


问:
Angular Bitbucket Pipeline unable to run ng build
i have created a pipeline to deploy my angular app to my ftp server through bitbucket pipeline. I have created therefore this pipeline.yml file:

```<code> image: node:6.9.4 # we need node image to run our angular application in
  clone: # help to clone our source here
  depth: full
 pipelines: # We set up all the pipeline or actions beneath
default: # here most always trigger before any other pipeline
  - step:
      script:
        - echo "This script runs on all branches that don't have any specific pipeline assigned in 'branches'."

branches: # This is branch specific configuration, we can set for different branches and different actions when we push codes
  master:
    - step:
        script:
          - npm install -g @angular/cli
          - npm install
          - ng build --prod
          - echo "Let's go in to our dist/ and initialize there with git"
          - cd dist/
          - git config --global user.email "account@clate.de"
          - git config --global user.name "clate"
          - git init
          - git add -A && git commit -m "base url updated for prod deployment"
          - git clone https://github.com/git-ftp/git-ftp.git
          - cd git-ftp
          - git checkout 1.3.4
          - make install
          - echo "Done with installation of git-ftp"
          - cd ../
          - rm -rf git-ftp
          - git config git-ftp.url "ftp://188.40.30.32/test"
          - git config git-ftp.user $FTP_USERNAME
          - git config git-ftp.password $FTP_PASSWORD
          - git ftp push --auto-init
</code>```

Unfortunately i'm receiving an error while trying to run command ng build --prod It is showing this error:

```<code>+ ng build --prod
/usr/local/lib/node_modules/@angular/cli/bin/ng:23
 );
 ^
SyntaxError: Unexpected token )
  at Object.exports.runInThisContext (vm.js:76:16)
  at Module._compile (module.js:542:28)
  at Object.Module._extensions..js (module.js:579:10)
  at Module.load (module.js:487:32)
  at tryModuleLoad (module.js:446:12)
  at Function.Module._load (module.js:438:3)
  at Module.runMain (module.js:604:10)
  at run (bootstrap_node.js:394:7)
  at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
</code>```

i haved tried to run it locally and it works without any problems.

答:
you have angular cli installed in your project, the better and faster way would be to use local ng installation to build your project. just add an npm script and call build through npm like this:</p>

```<code>//package.json
"scripts": {
 "build:prod": "ng build --prod",
...
}

pipeline.yml

       - npm install -g @angular/cli <---THIS IS NO LONGER NEEDED
       - npm install
       - npm run build:prod
....
</code>```

Body:
i have created a pipeline to deploy my angular app to my ftp server through bitbucket pipeline. I have created therefore this pipeline.yml file:

 image: node:6.9.4 # we need node image to run our angular application in
  clone: # help to clone our source here
  depth: full
 pipelines: # We set up all the pipeline or actions beneath
default: # here most always trigger before any other pipeline
  - step:
      script:
        - echo "This script runs on all branches that don't have any specific pipeline assigned in 'branches'."

branches: # This is branch specific configuration, we can set for different branches and different actions when we push codes
  master:
    - step:
        script:
          - npm install -g @angular/cli
          - npm install
          - ng build --prod
          - echo "Let's go in to our dist/ and initialize there with git"
          - cd dist/
          - git config --global user.email "account@clate.de"
          - git config --global user.name "clate"
          - git init
          - git add -A && git commit -m "base url updated for prod deployment"
          - git clone https://github.com/git-ftp/git-ftp.git
          - cd git-ftp
          - git checkout 1.3.4
          - make install
          - echo "Done with installation of git-ftp"
          - cd ../
          - rm -rf git-ftp
          - git config git-ftp.url "ftp://188.40.30.32/test"
          - git config git-ftp.user $FTP_USERNAME
          - git config git-ftp.password $FTP_PASSWORD
          - git ftp push --auto-init

Unfortunately i'm receiving an error while trying to run command ng build --prod It is showing this error:

+ ng build --prod
/usr/local/lib/node_modules/@angular/cli/bin/ng:23
 );
 ^
SyntaxError: Unexpected token )
  at Object.exports.runInThisContext (vm.js:76:16)
  at Module._compile (module.js:542:28)
  at Object.Module._extensions..js (module.js:579:10)
  at Module.load (module.js:487:32)
  at tryModuleLoad (module.js:446:12)
  at Function.Module._load (module.js:438:3)
  at Module.runMain (module.js:604:10)
  at run (bootstrap_node.js:394:7)
  at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3

i haved tried to run it locally and it works without any problems.

Body:
you have angular cli installed in your project, the better and faster way would be to use local ng installation to build your project. just add an npm script and call build through npm like this:

//package.json
"scripts": {
 "build:prod": "ng build --prod",
...
}

pipeline.yml

       - npm install -g @angular/cli <---THIS IS NO LONGER NEEDED
       - npm install
       - npm run build:prod
....


问:
Edit JSON file while keeping it properly formatted (e.g. indentation)
I have a JSON file with the format below and I would like a method to easily edit the data in the two datasets.

By having the tables to insert (2 columns each) in a .txt or .xls file how can I easily replace the two data tables [x,x].

I tried to do it with jsondecode and jsonencode funcions in MATLAB but when I rewrite to a .json file all the identation and line changes are lost. How (and with which software) can I do it to keep it properly formatted?

{
  "Compounds" :
      [ "frutafresca" ],
  "Property 1" :
      {
      "Scheme" : "Test1"  ,
      "StdValue"  : 0.01                 ,
      "Data":
          [
            [     353.15  ,   108320   ],
            [   503.15  ,   5120000  ],
            [   513.15  ,   6071400  ]
          ]
      },
  "Property 2" :
      {
      "Scheme" : "Test 1"  ,
      "StdValue"  : 0.01                 ,
      "Data":
          [
            [     273.15  ,   806.25 ],
            [   283.15  ,   797.92 ],
            [   293.15  ,   789.39 ],
            [   453.15  ,   598.39 ],
            [   463.15  ,   578.21 ],
            [   473.15  ,   556.79 ]
          ]
      }
}
```

答:
Is there a reason not to use the standard lib json module?

json module

From the docs:

json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

If indent is a non-negative integer or string, then JSON array
  elements and object members will be pretty-printed with that indent
  level. An indent level of 0, negative, or "" will only insert
  newlines. None (the default) selects the most compact representation.
  Using a positive integer indent indents that many spaces per level. If
  indent is a string (such as "\t"), that string is used to indent each
  level.

import json

data = None
with open('data.json', 'r') as _file:
    data = json.load(_file)
assert data is not None

## do your changes to data dict

with open('data.json', 'w') as _file:
    json.dump(data, _file, indent=2)    ## indent output with 2 spaces per level

```


答:
Let's try this:

```<code>def f(col):
    x = (col != col.shift().bfill())
    s = x.cumsum()
    return s.groupby(s).transform('count').shift().where(x)

df.apply(f).fillna('')
</code>```

Output:

```<code>   x  y  z
0
1        1
2  2
3  1
4        3
5
6     6  2
</code>```

Details:

Use apply, to apply a custom function on each column of the dataframe.
Find the difference spots in the column then use cumsum to create groups of consecutive values, then groupby and transform to create a count for each record, then mask the values in the column using where for the difference spots.

Title: Find the number of previous consecutive occurences of value different than current row value in pandas dataframe

Body:
Let's try this:

def f(col):
    x = (col != col.shift().bfill())
    s = x.cumsum()
    return s.groupby(s).transform('count').shift().where(x)

df.apply(f).fillna('')

Output:

   x  y  z
0
1        1
2  2
3  1
4        3
5
6     6  2

Details:

Use apply, to apply a custom function on each column of the dataframe.
Find the difference spots in the column then use cumsum to create groups of consecutive values, then groupby and transform to create a count for each record, then mask the values in the column using where for the difference spots.


问:
How to calculate percentage with a SQL statement
I have a SQL Server table that contains users & their grades. For simplicity's sake, lets just say there are 2 columns - name & grade. So a typical row would be Name: "John Doe", Grade:"A".

I'm looking for one SQL statement that will find the percentages of all possible answers. (A, B, C, etc...) Also, is there a way to do this without defining all possible answers (open text field - users could enter 'pass/fail', 'none', etc...)

The final output I'm looking for is A: 5%, B: 15%, C: 40%, etc...

答:
I had a similar issue to this. you should be able to get the correct result multiplying by 1.0 instead of 100.See example Image attached

Select Grade, (Count(Grade)* 1.0 / (Select Count(*) From MyTable)) as Score From MyTable Group By Grade


问:
Add custom combobox scrollbar style wpf
I know that I can find this on http://mark-dot-net.blogspot.com/2008/06/styling-listbox-with-silverlight-2-beta_21.html but I would like to be able to just do something like this:

```<code><ComboBox Width="163" Height="30">
     <ComboBox.Style>
          <Style>
              <Setter Property="ScrollViewer" Value="{StaticResource Custom}"/>
          </Style>
     </ComboBox.Style>
</ComboBox>
</code>```

But because of the ScrollViewer is not available, I tried doing something like this:

```<code><ComboBox Width="163" Height="30">
     <Style>
         <Setter Property="ScrollViewer.Style" Value="{StaticResource Custom}"/>
     </Style>
</ComboBox>
</code>```

But it does not work and if I keep in the Combobox.Style it gives me the error Style object is not allowed to affect the Style property of the object to which it applies to. I have also tried doing ScrollViewer.Template but my computer crashes when I do this /: Is there a way to do this without using the method in the link I provided earlier? My style xaml is:

```<code><ControlTemplate x:Key="VerticalScrollBar" TargetType="{x:Type ScrollBar}">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition MaxHeight="0"/>
                <RowDefinition Height="0.00001*"/>
                <RowDefinition MaxHeight="0"/>
            </Grid.RowDefinitions>
            <Border Grid.RowSpan="3" CornerRadius="2" Background="Transparent" />
            <RepeatButton Grid.Row="0" Style="{StaticResource ScrollBarLineButton}" Height="18" Command="ScrollBar.LineUpCommand" Content="M 0 4 L 8 4 L 4 0 Z" />
            <Track Name="PART_Track" Grid.Row="1" IsDirectionReversed="true">
                <Track.DecreaseRepeatButton>
                    <RepeatButton Style="{StaticResource ScrollBarPageButton}" Command="ScrollBar.PageUpCommand" />
                </Track.DecreaseRepeatButton>
                <Track.Thumb>
                    <Thumb Style="{StaticResource ScrollBarThumb}" Margin="1,0,1,0" Background="#E43D47" BorderBrush="{StaticResource HorizontalNormalBorderBrush}" />
                </Track.Thumb>
                <Track.IncreaseRepeatButton>
                    <RepeatButton Style="{StaticResource ScrollBarPageButton}" Command="ScrollBar.PageDownCommand" />
                </Track.IncreaseRepeatButton>
            </Track>
            <RepeatButton Grid.Row="3" Style="{StaticResource ScrollBarLineButton}" Height="18" Command="ScrollBar.LineDownCommand" Content="M 0 0 L 4 4 L 8 0 Z"/>
        </Grid>
    </ControlTemplate>
</code>```

答:
Just declare a ScrollViewer style in the ComboBox's Resources block:</p>

```<code><ComboBox ItemsSource="{Binding Items}">
    <ComboBox.Resources>
        <Style TargetType="ScrollViewer">
            <Setter Property="Background" Value="Green" />
            <Setter Property="Padding" Value="20" />
        </Style>
    </ComboBox.Resources>
</ComboBox>
</code>```

Title: Add custom combobox scrollbar style wpf

Body:
I know that I can find this on http://mark-dot-net.blogspot.com/2008/06/styling-listbox-with-silverlight-2-beta_21.html but I would like to be able to just do something like this:

<ComboBox Width="163" Height="30">
     <ComboBox.Style>

     </ComboBox.Style>
</ComboBox>

But because of the ScrollViewer is not available, I tried doing something like this:

<ComboBox Width="163" Height="30">

</ComboBox>

But it does not work and if I keep in the Combobox.Style it gives me the error Style object is not allowed to affect the Style property of the object to which it applies to. I have also tried doing ScrollViewer.Template but my computer crashes when I do this /: Is there a way to do this without using the method in the link I provided earlier? My style xaml is:

<ControlTemplate x:Key="VerticalScrollBar" TargetType="{x:Type ScrollBar}">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition MaxHeight="0"/>
                <RowDefinition Height="0.00001*"/>
                <RowDefinition MaxHeight="0"/>
            </Grid.RowDefinitions>
            <Border Grid.RowSpan="3" CornerRadius="2" Background="Transparent" />
            <RepeatButton Grid.Row="0" Style="{StaticResource ScrollBarLineButton}" Height="18" Command="ScrollBar.LineUpCommand" Content="M 0 4 L 8 4 L 4 0 Z" />
            <Track Name="PART_Track" Grid.Row="1" IsDirectionReversed="true">
                <Track.DecreaseRepeatButton>
                    <RepeatButton Style="{StaticResource ScrollBarPageButton}" Command="ScrollBar.PageUpCommand" />
                </Track.DecreaseRepeatButton>
                <Track.Thumb>
                    <Thumb Style="{StaticResource ScrollBarThumb}" Margin="1,0,1,0" Background="#E43D47" BorderBrush="{StaticResource HorizontalNormalBorderBrush}" />
                </Track.Thumb>
                <Track.IncreaseRepeatButton>
                    <RepeatButton Style="{StaticResource ScrollBarPageButton}" Command="ScrollBar.PageDownCommand" />
                </Track.IncreaseRepeatButton>
            </Track>
            <RepeatButton Grid.Row="3" Style="{StaticResource ScrollBarLineButton}" Height="18" Command="ScrollBar.LineDownCommand" Content="M 0 0 L 4 4 L 8 0 Z"/>
        </Grid>
    </ControlTemplate>

Body:
Just declare a ScrollViewer style in the ComboBox's Resources block:

<ComboBox ItemsSource="{Binding Items}">
    <ComboBox.Resources>
        <Style TargetType="ScrollViewer">
            <Setter Property="Background" Value="Green" />
            <Setter Property="Padding" Value="20" />
        </Style>
    </ComboBox.Resources>
</ComboBox>


问:
How to fix the issue:Your PHP installation appears to be missing the MySQL extension
Environment:os and apache and php and mariadb version.

```<code>uname -a
Linux MiWiFi-R3-srv 4.9.0-11-amd64 #1 SMP Debian 4.9.189-3+deb9u2 (2019-11-11) x86_64 GNU/Linux

sudo apachectl -v
Server version: Apache/2.4.25 (Debian)
Server built:   2019-10-13T15:43:54

php -v
PHP 7.0.33-0+deb9u6 (cli) (built: Oct 24 2019 18:50:20) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.0.33-0+deb9u6, Copyright (c) 1999-2017, by Zend Technologies
</code>```

Login mariadb with password and input status:

```<code>Server:         MariaDB
Server version:     10.1.41-MariaDB-0+deb9u1 Debian 9.9
</code>```

Check php-mysql:

```<code>sudo dpkg -l php-mysql
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name           Version      Architecture Description
+++-==============-============-============-=================================
ii  php-mysql      1:7.0+49     all          MySQL module for PHP [default]
</code>```

Get the mysql.so library:

```<code>sudo find  /  -name  "*mysql.so"
/usr/lib/php/20151012/pdo_mysql.so
</code>```

Chekc all modules which contain mysql:

```<code>php -m |grep  mysql
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php/20151012/php_pdo_mysql.so' - /usr/lib/php/20151012/php_pdo_mysql.so: cannot open shared object file: No such file or directory in Unknown on line 0
mysqli
mysqlnd
pdo_mysql

sudo vim  /etc/php/7.0/fpm/php.ini
</code>```

Rewrite

```<code>; ... or under UNIX:
;
;extension=mysql.so
</code>```

as

```<code>extension=mysqli.so
</code>```

or

```<code>extension=mysqlnd.so
</code>```

or

```<code>extension=pdo_mysql.so
</code>```

Restart apache2 and mariadb database,the issue remains ,none of the three format can work,how to fix then?

答:
pdo_mysql is not the same as mysql.so. The old mysql extension was removed in PHP 7.0. The supported extension is now only mysqli.

From there on it depends on what the software is expecting to find - if it needs the old mysql library, then you're going to have to use a shim or an older PHP version (i.e. anything before PHP 7, such as PHP 5.6).

You can use the php7-mysql-shim library or the mysql-shim library (be aware, this might incur a small performance penalty) to make a transparent mapping available that dispatches any calls to the old mysql library to the still supported mysqli library. As long as you've installed php7-mysql-shim through composer and your project uses composer, it should be loaded automagically.

A third option is to run the original code through the mysql-to-mysqli rector configuration, but if this is not your own code, that will be hard to maintain in the future.

The .so file that can't be loaded might be because of permission issue. Make sure to ls -al that file and correct any ownership or permission issues (chmod og+r <filename>, probably).

Body:
Environment:os and apache and php and mariadb version.

uname -a
Linux MiWiFi-R3-srv 4.9.0-11-amd64 #1 SMP Debian 4.9.189-3+deb9u2 (2019-11-11) x86_64 GNU/Linux

sudo apachectl -v
Server version: Apache/2.4.25 (Debian)
Server built:   2019-10-13T15:43:54

php -v
PHP 7.0.33-0+deb9u6 (cli) (built: Oct 24 2019 18:50:20) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.0.33-0+deb9u6, Copyright (c) 1999-2017, by Zend Technologies

Login mariadb with password and input status:

Server:         MariaDB
Server version:     10.1.41-MariaDB-0+deb9u1 Debian 9.9

Check php-mysql:

sudo dpkg -l php-mysql
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name           Version      Architecture Description
+++-==============-============-============-=================================
ii  php-mysql      1:7.0+49     all          MySQL module for PHP [default]

Get the mysql.so library:

sudo find  /  -name  "*mysql.so"
/usr/lib/php/20151012/pdo_mysql.so

Chekc all modules which contain mysql:

php -m |grep  mysql
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php/20151012/php_pdo_mysql.so' - /usr/lib/php/20151012/php_pdo_mysql.so: cannot open shared object file: No such file or directory in Unknown on line 0
mysqli
mysqlnd
pdo_mysql

sudo vim  /etc/php/7.0/fpm/php.ini

Rewrite

; ... or under UNIX:
;
;extension=mysql.so

as

extension=mysqli.so

or

extension=mysqlnd.so

or

extension=pdo_mysql.so

Restart apache2 and mariadb database,the issue remains ,none of the three format can work,how to fix then?


问:
Windows run two VPN client at the same time
I have successfully ran 2 openvpn client (VPN-A, VPN-B) in my windows pc.

I firstly ran VPN-A, then ran VPN-B.

But found out the VPN-A works fine, but the route requests to VPN-B were all timeout.

Anyone can help me? thanks.

答: So you have two OpenVPN TAP Adapters in Windows with different names?  Is IPv4 set to Obtain an IP address automatically for both?  You the client should be getting an IP address from the server.  Each server should be using a different subnet than each other too.  </p>


问:
In shell how do I get stdout & stderr combined in output order and stderr separate too?
For the reason of build logging I want to have a shell script
combining stderr and stdout of a command but also saving stderr only separately so I can show stderr prominently in the beginning. But also have them combined to probably further analyze including the stdout messages if necessary.

Tried a lot around with tee and file descriptors but I do not get this
stuff to work.

I already found that for zsh this should be working cmd &> all.txt and 2> out.txt but does unfortunately not on sh.

I also managed to have them together in one file once but, it was not in order, I got all errors followed by the stdout or other way round.

if you try something it should be sh.

That is my test script:

```<code>>&2 echo "error0"
echo "out0"
>&2 echo "error1"
echo "out1"
>&2 echo "error2"
echo "out2"
</code>```

Outputs should be:

```<code>error0
out0
error1
out1
error2
out2
</code>```

and:

```<code>error0
error1
error2
</code>```

答:
```<code>#!/bin/sh
mkfifo logpipe errpipe
tee -a errlog >logpipe <errpipe&
cat logpipe >log&
{ echo foo; echo bar >&2; } >logpipe 2>errpipe
rm logpipe errpipe
</code>```

Best results I could get in dash so far (see the buffering discussion in the comments):

```<code>stdbuf -e0 -o0 test.sh 2>&1 >>log | tee -a log >errlog
</code>```

With test.sh:

```<code>#!/bin/sh
for i in `seq 10`; do
  echo "error$i" >&2
  echo "out$i"
done
</code>```

I get results like:

```<code>$ cat log
out1
out2
error1
out3
error2
error3
out4
error4
out5
error5
out6
error6
out7
error7
out8
error8
out9
error9
out10
error10
$ cat errlog
error1
error2
error3
error4
error5
error6
error7
error8
error9
error10
</code>```

Sometimes it's better, sometimes it's worse.

Body:
For the reason of build logging I want to have a shell script
combining stderr and stdout of a command but also saving stderr only separately so I can show stderr prominently in the beginning. But also have them combined to probably further analyze including the stdout messages if necessary.

Tried a lot around with tee and file descriptors but I do not get this
stuff to work.

I already found that for zsh this should be working cmd &> all.txt and 2> out.txt but does unfortunately not on sh.

I also managed to have them together in one file once but, it was not in order, I got all errors followed by the stdout or other way round.

if you try something it should be sh.

That is my test script:

>&2 echo "error0"
echo "out0"
>&2 echo "error1"
echo "out1"
>&2 echo "error2"
echo "out2"

Outputs should be:

error0
out0
error1
out1
error2
out2

and:

error0
error1
error2

Body:
#!/bin/sh
mkfifo logpipe errpipe
tee -a errlog >logpipe <errpipe&
cat logpipe >log&
{ echo foo; echo bar >&2; } >logpipe 2>errpipe
rm logpipe errpipe

Best results I could get in dash so far (see the buffering discussion in the comments):

stdbuf -e0 -o0 test.sh 2>&1 >>log | tee -a log >errlog

With test.sh:

#!/bin/sh
for i in `seq 10`; do
  echo "error$i" >&2
  echo "out$i"
done

I get results like:

$ cat log
out1
out2
error1
out3
error2
error3
out4
error4
out5
error5
out6
error6
out7
error7
out8
error8
out9
error9
out10
error10
$ cat errlog
error1
error2
error3
error4
error5
error6
error7
error8
error9
error10

Sometimes it's better, sometimes it's worse.


问:
Pass required argument plus variable length arguments to function
I have a function that has one required parameter and a variable number of parameters.  I'm passing an array of blobs to the functions.  A simplified version of the function looks like this:

```<code>function test(directory, blob0, blob1) {
  for (var argumentIndex = 1; argumentIndex < arguments.length; argumentIndex++) {
    var bytes = arguments[argumentIndex].getBytes();
    //do some things
  }
}
</code>```

I'm using the rhino runtime so I can't use the spread operator.  The closest I've come to making it work is by using the apply function, but I'm not sure how to also pass the required parameter (directory) in the test function above.

```<code>var blobs = [];
blobs[0] = getBlob();
blobs[1] = getBlob();
blobs[2] = getBlob();

test.apply(null,blobs)  //doesn't set required parameter (directory)
</code>```

答:
Use the unshift() function, it adds an element to the begining of an array

```<code>var blobs = [];
blobs[0] = getBlob();
blobs[1] = getBlob();
blobs[2] = getBlob();

blobs.unshift(directory)

test.apply(null,blobs)
</code>```

Body:
I have a function that has one required parameter and a variable number of parameters.  I'm passing an array of blobs to the functions.  A simplified version of the function looks like this:

function test(directory, blob0, blob1) {
  for (var argumentIndex = 1; argumentIndex < arguments.length; argumentIndex++) {
    var bytes = arguments[argumentIndex].getBytes();
    //do some things
  }
}

I'm using the rhino runtime so I can't use the spread operator.  The closest I've come to making it work is by using the apply function, but I'm not sure how to also pass the required parameter (directory) in the test function above.

var blobs = [];
blobs[0] = getBlob();
blobs[1] = getBlob();
blobs[2] = getBlob();

test.apply(null,blobs)  //doesn't set required parameter (directory)

Body:
Use the unshift() function, it adds an element to the begining of an array

var blobs = [];
blobs[0] = getBlob();
blobs[1] = getBlob();
blobs[2] = getBlob();

blobs.unshift(directory)

test.apply(null,blobs)


问:
Unable to trup external signal in bash
I'm trying to write a script that will mostly stay idle waiting for a predefined amount of time using regular system sleep. The problem emerges when I try to kill it externally (with start-stop-daemon for example). The main process will be killed, but the child sleep will remain in the system until it will run out. I decided to make a sanity trap and kill active sleep from the script itself. This is how it is done:

```<code>cleanup()
{
        local PIDS=$(jobs -p)
        echo $PIDS
        [ -n "$PIDS" ] && kill $PIDS
        exit 0
}
trap "cleanup" SIGINT SIGTERM

sleep 1h
</code>```

When I hit Ctrl-C (send SIGINT) while the script is in foreground, the cleanup() procedure will fire up, but if I'm trying to kill (send default SIGTERM) the running script from other console nothing happens. No the cleanup() is executed, neither script terminates. The script will continue to run just like nothing happens.
Can anybody explain what is going on and how to trap external SIGTERM and execute the desired procedure?

答:
As Philippe mentions in a comment above, the Bash Reference Manual § 3.7.6 "Signals" states in part:

If Bash is waiting for a command to complete and receives a signal for which a trap has been set, the trap will not be executed until the command completes.

This is actually true of SIGINT as well as SIGTERM; the reason that your approach seems to work for Ctrl-C is that Ctrl-C sends SIGINT to every process in the foreground process group, including the sleep process, so sleep exits immediately and then its parent script exits.

The most explicit way to fix this is offered by the rest of the paragraph I just quoted from:

When Bash is waiting for an asynchronous command via the wait builtin, the reception of a signal for which a trap has been set will cause the wait builtin to return immediately with an exit status greater than 128, immediately after which the trap is executed.

In other words, you can replace sleep 1h with sleep 1h & wait (where sleep 1h & and wait can be on separate lines or on the same line, as you prefer) to have your trap called immediately (so it can kill the sleep process).

Alternatively, you can eliminate the trap setup and replace sleep 1h with something that won't continue running so long after the script exits; for example:

a loop that repeatedly sleeps only briefly (e.g. sleep 1s) until an hour has passed.

read -t 3600, which waits up to 3600 seconds (one hour) for text to appear on standard input. (N.B. this approach only works if there is not, in fact, any text on standard input.)

(These rely on the fact that the loop (in the former case) or the read call (in the latter case) are part of the Bash process itself, rather than a forked child process.)

Title: Unable to trup external signal in bash

Body:
I'm trying to write a script that will mostly stay idle waiting for a predefined amount of time using regular system sleep. The problem emerges when I try to kill it externally (with start-stop-daemon for example). The main process will be killed, but the child sleep will remain in the system until it will run out. I decided to make a sanity trap and kill active sleep from the script itself. This is how it is done:

cleanup()
{
        local PIDS=$(jobs -p)
        echo $PIDS
        [ -n "$PIDS" ] && kill $PIDS
        exit 0
}
trap "cleanup" SIGINT SIGTERM

sleep 1h

When I hit Ctrl-C (send SIGINT) while the script is in foreground, the cleanup() procedure will fire up, but if I'm trying to kill (send default SIGTERM) the running script from other console nothing happens. No the cleanup() is executed, neither script terminates. The script will continue to run just like nothing happens.
Can anybody explain what is going on and how to trap external SIGTERM and execute the desired procedure?


问:
Solving dangling if, elsif, and else in Bison without associativity declarations
I am implementing a parser for a language that has if-elsif-else statements and can't seem to make my grammar unambiguous. Our compilers class was given a handout on solving the dangling else problem for if-else statements using a match/unmatched approaches as follows:

```<code>%token IF EXP ELSE XX

stmts: stmts stmt ';'
     | stmt ';'
     ;

stmt : matched
     | unmatched
     ;

matched: IF '(' EXP ')' matched ELSE matched
      | XX
      ;

unmatched : IF '(' EXP ')' matched
      | IF '(' EXP ')' unmatched
      | IF '(' EXP ')' matched ELSE unmatched
      ;
</code>```

The grammar documentation provided for our language is defined to have productions involving if - elsif- else where:

```<code>selectionStmt → IF simpleExpression THEN statement elsifList
      | IF simpleExpression THEN statement elsifList ELSE statement

elsifList → elsifList ELSIF simpleExpression THEN statement
      | *empty*
</code>```

where the lowercase words are productions and the uppercase are terminals.

These provided productions are ambiguous and have to be solved in the grammar implementation in bison. Here is the progress I've made on actually implementing it into Bison:

```<code>statement: stmtMatched
     | selectionStmtUnmatched

elsifList: elsifList ELSIF simpleExpression THEN statement
     | %empty

stmtMatched: IF simpleExpression THEN stmtMatched elsifList ELSE
stmtMatched
       | otherStatement

selectionStmtUnmatched: IF simpleExpression THEN statement elsifList
       | IF simpleExpression THEN stmtMatched elsifList ELSE
selectionStmtUnmatched

otherStatement: expressionStmt
          | compoundStmt
          | iterationStmt
          | returnStmt
          | breakStmt
</code>```

Any suggestions on changing the grammar to accommodate the elsif productions similarly to using matched and unmatched statements to solving the dangling if-else problem and get rid of any shift/reduce and reduce/reduce errors?

Edit 1:
I've made more progress on a simpler version of the grammar to ensure that elsifLists can only follow matched statements:

```<code>stmt: matched
| unmatched

matched: IF '(' EXP ')' THEN matched elsifList ELSE matched
   | %empty

unmatched: IF '(' EXP ')' THEN matched elsifList
     | IF '(' EXP ')' THEN unmatched
     | IF '(' EXP ')' THEN matched elsifList ELSE unmatched

elsifList: elsifList ELSIF EXP THEN stmt
     | %empty
</code>```

But I am still getting shift/reduce conflicts:

```<code>State 12

    3 matched: IF '(' EXP ')' THEN matched elsifList . ELSE matched
    5 unmatched: IF '(' EXP ')' THEN matched elsifList .
    7          | IF '(' EXP ')' THEN matched elsifList . ELSE unmatched
    8 elsifList: elsifList . ELSIF EXP THEN stmt

    ELSE   shift, and go to state 13
    ELSIF  shift, and go to state 14

    ELSE      [reduce using rule 5 (unmatched)]
    ELSIF     [reduce using rule 5 (unmatched)]
    $default  reduce using rule 5 (unmatched)
</code>```

Edit 2:
I've made enough progress with the simple grammar to ensure that elsif statements are preceeded by matched statements. The resulting grammar is:

```<code>stmt: matched
    | unmatched

matched: IF '(' EXP ')' THEN matched elsifList ELSE matched
       | %empty

unmatched: IF '(' EXP ')' THEN matched elsifList
         | IF '(' EXP ')' THEN unmatched
         | IF '(' EXP ')' THEN matched elsifList ELSE unmatched

elsifList: elsifList ELSIF EXP THEN matched
         | %empty
</code>```

I've updated the actual grammar for the parser for the actual language to ensure that unmatched statements can not be followed by an elsifList and that elsifLists can only be followed by matched statements:

```<code>statement :     stmtMatched |
                selectionStmtUnmatched
                ;

otherStatement : expressionStmt
                | compoundStmt
                | iterationStmt
                | returnStmt
                | breakStmt
                ;

elsifList :     elsifList ELSIF simpleExpression THEN stmtMatched
                | %empty
                ;

stmtMatched : IF simpleExpression THEN stmtMatched elsifList ELSE stmtMatched
            | otherStatement
            ;

selectionStmtUnmatched : IF simpleExpression THEN stmtMatched elsifList
                | IF simpleExpression THEN selectionStmtUnmatched
                | IF simpleExpression THEN stmtMatched elsifList ELSE selectionStmtUnmatched
</code>```

The resulting grammar is still giving me 2 shift/reduce conflicts though:

```<code>State 164

   44 elsifList: elsifList . ELSIF simpleExpression THEN stmtMatched
   46 stmtMatched: IF simpleExpression THEN stmtMatched elsifList . ELSE stmtMatched
   48 selectionStmtUnmatched: IF simpleExpression THEN stmtMatched elsifList .
   50                       | IF simpleExpression THEN stmtMatched elsifList . ELSE selectionStmtUnmatched

   ELSIF  shift, and go to state 167
   ELSE   shift, and go to state 168

   ELSIF     [reduce using rule 48 (selectionStmtUnmatched)]
   ELSE      [reduce using rule 48 (selectionStmtUnmatched)]
   $default  reduce using rule 48 (selectionStmtUnmatched)
</code>```

答:
The grammar in your handout does not allow an unmatched statement before an else. Why is that?

It's because the else must bind to the closest not-yet-matched if. You might want to try doing a few parse trees by hand to understand how this works. The essential point is that inside the unmatched statement, there is an unmatched if which the else should bind to. So the ambiguity can be removed by removing the possibility of skipping over that unmatched if.

Now, what changes when we add elsif? Not much. Both elsif and else must bind to the closest not-yet-matched if or elsif. And the way of guaranteeing that is exactly the same as the simple case. We need to ensure that the statement before the elsif is matched.

But your grammar only requires that the statement before the first elsif be matched. So ambiguities remain.

As a hint: the fix is very simple. You just need to do the grouping differently.

Body:
I am implementing a parser for a language that has if-elsif-else statements and can't seem to make my grammar unambiguous. Our compilers class was given a handout on solving the dangling else problem for if-else statements using a match/unmatched approaches as follows:

%token IF EXP ELSE XX

stmts: stmts stmt ';'
     | stmt ';'
     ;

stmt : matched
     | unmatched
     ;

matched: IF '(' EXP ')' matched ELSE matched
      | XX
      ;

unmatched : IF '(' EXP ')' matched
      | IF '(' EXP ')' unmatched
      | IF '(' EXP ')' matched ELSE unmatched
      ;

The grammar documentation provided for our language is defined to have productions involving if - elsif- else where:

selectionStmt → IF simpleExpression THEN statement elsifList
      | IF simpleExpression THEN statement elsifList ELSE statement

elsifList → elsifList ELSIF simpleExpression THEN statement
      | *empty*

where the lowercase words are productions and the uppercase are terminals.

These provided productions are ambiguous and have to be solved in the grammar implementation in bison. Here is the progress I've made on actually implementing it into Bison:

statement: stmtMatched
     | selectionStmtUnmatched

elsifList: elsifList ELSIF simpleExpression THEN statement
     | %empty

stmtMatched: IF simpleExpression THEN stmtMatched elsifList ELSE
stmtMatched
       | otherStatement

selectionStmtUnmatched: IF simpleExpression THEN statement elsifList
       | IF simpleExpression THEN stmtMatched elsifList ELSE
selectionStmtUnmatched

otherStatement: expressionStmt
          | compoundStmt
          | iterationStmt
          | returnStmt
          | breakStmt

Any suggestions on changing the grammar to accommodate the elsif productions similarly to using matched and unmatched statements to solving the dangling if-else problem and get rid of any shift/reduce and reduce/reduce errors?

Edit 1:
I've made more progress on a simpler version of the grammar to ensure that elsifLists can only follow matched statements:

stmt: matched
| unmatched

matched: IF '(' EXP ')' THEN matched elsifList ELSE matched
   | %empty

unmatched: IF '(' EXP ')' THEN matched elsifList
     | IF '(' EXP ')' THEN unmatched
     | IF '(' EXP ')' THEN matched elsifList ELSE unmatched

elsifList: elsifList ELSIF EXP THEN stmt
     | %empty

But I am still getting shift/reduce conflicts:

State 12

    3 matched: IF '(' EXP ')' THEN matched elsifList . ELSE matched
    5 unmatched: IF '(' EXP ')' THEN matched elsifList .
    7          | IF '(' EXP ')' THEN matched elsifList . ELSE unmatched
    8 elsifList: elsifList . ELSIF EXP THEN stmt

    ELSE   shift, and go to state 13
    ELSIF  shift, and go to state 14

    ELSE      [reduce using rule 5 (unmatched)]
    ELSIF     [reduce using rule 5 (unmatched)]
    $default  reduce using rule 5 (unmatched)

Edit 2:
I've made enough progress with the simple grammar to ensure that elsif statements are preceeded by matched statements. The resulting grammar is:

stmt: matched
    | unmatched

matched: IF '(' EXP ')' THEN matched elsifList ELSE matched
       | %empty

unmatched: IF '(' EXP ')' THEN matched elsifList
         | IF '(' EXP ')' THEN unmatched
         | IF '(' EXP ')' THEN matched elsifList ELSE unmatched

elsifList: elsifList ELSIF EXP THEN matched
         | %empty

I've updated the actual grammar for the parser for the actual language to ensure that unmatched statements can not be followed by an elsifList and that elsifLists can only be followed by matched statements:

statement :     stmtMatched |
                selectionStmtUnmatched
                ;

otherStatement : expressionStmt
                | compoundStmt
                | iterationStmt
                | returnStmt
                | breakStmt
                ;

elsifList :     elsifList ELSIF simpleExpression THEN stmtMatched
                | %empty
                ;

stmtMatched : IF simpleExpression THEN stmtMatched elsifList ELSE stmtMatched
            | otherStatement
            ;

selectionStmtUnmatched : IF simpleExpression THEN stmtMatched elsifList
                | IF simpleExpression THEN selectionStmtUnmatched
                | IF simpleExpression THEN stmtMatched elsifList ELSE selectionStmtUnmatched

The resulting grammar is still giving me 2 shift/reduce conflicts though:

State 164

   44 elsifList: elsifList . ELSIF simpleExpression THEN stmtMatched
   46 stmtMatched: IF simpleExpression THEN stmtMatched elsifList . ELSE stmtMatched
   48 selectionStmtUnmatched: IF simpleExpression THEN stmtMatched elsifList .
   50                       | IF simpleExpression THEN stmtMatched elsifList . ELSE selectionStmtUnmatched

   ELSIF  shift, and go to state 167
   ELSE   shift, and go to state 168

   ELSIF     [reduce using rule 48 (selectionStmtUnmatched)]
   ELSE      [reduce using rule 48 (selectionStmtUnmatched)]
   $default  reduce using rule 48 (selectionStmtUnmatched)


问:
mysql: implement function into query
i'm having a database which is storing geo-data like countries, cities.
i would like to use modrewrite with links like:
mysite.com/europe/austria/vienna

now the problem: in german, some countries contain umlauts like austria = österreich
(i can't use umlauts in urls)

so my question:
is there a way to create a function inside the database which replaces all special characters when querying like "where validUrl(country)='oesterreich' ?
which would replace ö->oe

my only idea so far is adding an extra database field for modrewrite which would hold "oesterreich"

any ideas? thanks

答:
You can create a function in MySQL like so

```<code>DELIMITER $$

CREATE FUNCTION UmlautRaus(input varchar) RETURNS varchar
BEGIN
  declare output varchar;

  SET output = REPLACE(input,'ü','ue');
  SET output = REPLACE(output,.....
  ....
  RETURN output;
END $$

DELIMITER ;
</code>```

However as @GolezTrol said, this is not a great idea because of diacritics in other languages.

Link: http://dev.mysql.com/doc/refman/5.1/en/string-functions.html

Title: mysql: implement function into query

Body:
You can create a function in MySQL like so

DELIMITER $$

CREATE FUNCTION UmlautRaus(input varchar) RETURNS varchar
BEGIN
  declare output varchar;

  SET output = REPLACE(input,'ü','ue');
  SET output = REPLACE(output,.....
  ....
  RETURN output;
END $$

DELIMITER ;

However as @GolezTrol said, this is not a great idea because of diacritics in other languages.

Link: http://dev.mysql.com/doc/refman/5.1/en/string-functions.html


问:
Pine backtesting, doesn't open a new trade if there is one already opened
The titles says it all, here is my code.

```<code>strategy.entry("Short", strategy.short, comment="InsBarSE")
        strategy.exit("Short", loss=200, profit=200, when=exit_long)

strategy.entry("Long", strategy.long, comment="InsBarLE")
        strategy.exit("Long", loss=200, profit=200, when=exit_short)
</code>```

a lot of times the short trade closes the long trade automatically, and I don't want that to happen, I want them to go until it hits profit or loss, help please.

答:
You're not using the from_entry= parameter for your strategy.exit() calls, so they are exiting any open trade. See the refman for details. Your code should look like:

```<code>strategy.entry("Short", strategy.short, comment="InsBarSE")
        strategy.exit("Exit Short", "Short", loss=200, profit=200, when=exit_long)

strategy.entry("Long", strategy.long, comment="InsBarLE")
        strategy.exit("Exit Long", "Long", loss=200, profit=200, when=exit_short)
</code>```

Body:
The titles says it all, here is my code.

strategy.entry("Short", strategy.short, comment="InsBarSE")
        strategy.exit("Short", loss=200, profit=200, when=exit_long)

strategy.entry("Long", strategy.long, comment="InsBarLE")
        strategy.exit("Long", loss=200, profit=200, when=exit_short)

a lot of times the short trade closes the long trade automatically, and I don't want that to happen, I want them to go until it hits profit or loss, help please.

Body:
You're not using the from_entry= parameter for your strategy.exit() calls, so they are exiting any open trade. See the refman for details. Your code should look like:

strategy.entry("Short", strategy.short, comment="InsBarSE")
        strategy.exit("Exit Short", "Short", loss=200, profit=200, when=exit_long)

strategy.entry("Long", strategy.long, comment="InsBarLE")
        strategy.exit("Exit Long", "Long", loss=200, profit=200, when=exit_short)


问:
change culture programmatically at runtime (ASP.NET MVC)
How do I programmatically change (override) the current culture (set in web.config) ?
sounds simple but tried different code for hours without any result.  Let start with this :
option 1

```<code>   @Html.ActionLink("French", "SetFrenchCulture", "Culture")
      @Html.ActionLink("English", "SetEnglishCulture", "Culture")
...
      public class CultureController : Controller
        {
            public ActionResult SetEnglishCulture()
            {
                HttpContext.Session["culture"] = "en-US";
                return RedirectToAction("Index", "Home");
            }

            public ActionResult SetFrenchCulture()
            {
                HttpContext.Session["culture"] = "fr-FR";
                return RedirectToAction("Index", "Home");
            }
        }
</code>```

Option 2

```<code>  public void SetLanguage(string lang)
        {
            try
            {

                var cultureInfo = new CultureInfo(lang);
                Thread.CurrentThread.CurrentUICulture = cultureInfo;
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);
                HttpCookie langCookie = new HttpCookie("culture", lang);
                langCookie.Expires = DateTime.Now.AddYears(1);
                HttpContext.Current.Response.Cookies.Add(langCookie);
            }
            catch (Exception) { }
        }
</code>```

Switching with web.config works perfectly.   Thanks

答:
The answer is here :

https://afana.me/archive/2011/01/14/aspnet-mvc-internationalization.aspx/

works pefectly!!  culture in mvc is extremely particular.

Body:
How do I programmatically change (override) the current culture (set in web.config) ?
sounds simple but tried different code for hours without any result.  Let start with this :
option 1

   @Html.ActionLink("French", "SetFrenchCulture", "Culture")
      @Html.ActionLink("English", "SetEnglishCulture", "Culture")
...
      public class CultureController : Controller
        {
            public ActionResult SetEnglishCulture()
            {
                HttpContext.Session["culture"] = "en-US";
                return RedirectToAction("Index", "Home");
            }

            public ActionResult SetFrenchCulture()
            {
                HttpContext.Session["culture"] = "fr-FR";
                return RedirectToAction("Index", "Home");
            }
        }

Option 2

  public void SetLanguage(string lang)
        {
            try
            {

                var cultureInfo = new CultureInfo(lang);
                Thread.CurrentThread.CurrentUICulture = cultureInfo;
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);
                HttpCookie langCookie = new HttpCookie("culture", lang);
                langCookie.Expires = DateTime.Now.AddYears(1);
                HttpContext.Current.Response.Cookies.Add(langCookie);
            }
            catch (Exception) { }
        }

Switching with web.config works perfectly.   Thanks