问:
A succinct binary tree of sums, array construction and addressing
Using 'sum' as a short hand for some arbitrary computation. I have a process that computes a single sum from a list of values by recursively summing pairs of values. Un-paired values are promoted up the tree unaltered until they can be paired.

Given this computation, I'm in search of the best way to balance computation (i.e. number of operation required to access array elements/nodes), and the most succinct encoding of all nodes in a 1 dimensional array (i.e. no gaps, nil values, or repeated values), and preferably without an additional index array that cannot be easily derived from the succinct encoding so that it would have to be saved along with the array.

Although the following are simple examples, in reality the number of values in the initial list can be extraordinarily large (2^47 or more).

For example, given the list [1, 2, 3, 4], the array is trivial: [10, 3, 7, 1, 2, 3, 4], and split nicely into rows that are easy to address by node, or as a reference to the entire row.

But for a 5 item list the tree looks like this:

Tree 1

```<code>         15
        /  \
       /    \
      /      \
     /        \
    10          5
  /   \       /   \
 3     7     5     -
/ \   / \   / \   / \
1  2  3  4 5   - -   -
</code>```

The standard mapping left = i*2+1, right = i*2+2 gives us this array:

Array 1

```<code>[ 15, 10,  5,  3,   7,   5,  nil,   1,   2,   3,   4,   5,   nil,   nil, nil]
</code>```

This array has 4 nil values, and the last element in the list '5' is repeated 2 times.

To improve this we can imply the repetition of the 5, and remove the nil values:

Array 2

```<code>[15, 10, 3, 7, 1, 2, 3, 4, 5]
</code>```

Which is much more compact. This tree is the same, but conceptually looks a bit like:

Tree 2

```<code>       15
      / \
     /   \
    10    \
  /   \    \
 3     7    \
/ \   / \    \
1  2  3  4    5
</code>```

In the Array 2 encoding I have 4 rows:

```<code>1. [1, 2, 3, 4]
2. [3, 7]
3. [10, 5]
4. [15]
</code>```

Rows 1, 2 and 4 can simply be references into Array 2 allowing me to compute results 'in-place' with no allocations or copies. Very fast. Row 3 however, contains values in two non-contiguous cells. I have to break the simple logic used for the other rows, and possibly add copy, indexing or storage for a map.

I can construct complete/balanced sub trees (such as indexes 1-7, the tree for 1, 2, 3, 4), but it seems like they will not always be so nicely aligned when the odd number of items appears at different rows depending on input length.  For example consider a tree with an initial list of 6 elements.

答:
Let's assume your tree has N nodes on the final (most numerous) row.

If you do store the nodes that are only propagated upwards, your tree has between 2*N-1 and 2*N-1+log2(N) nodes, total. The exact total number of nodes is given by OEIS A120511. Of these, at most floor(2 + log2(N-1)) are copied/propagated nodes.

The tree has floor(2 + log2(N-1)) rows. The number of rows as a function of  N (the number of elements on the final row) is OEIS A070941.

The number of rows in such trees is quite low. For example, if you have 240 ≈ 1,000,000,000,000 nodes in the final row, you only have 42 rows in the tree. For 264 nodes, you have just 66. Therefore, if you need some operation per row, it is not a high overhead.

A simple logarithmic-time function can compute the number of rows and the total number of nodes, given the number of nodes in the final row N:

```<code># Account for the root node
rows = 1
total = 1

curr_left = N
While (curr_left > 1):
    rows = rows + 1
    total = total + curr_left
    curr_left = (curr_left + 1) / 2
End While
</code>```

where / denotes integer division, i.e. any fractional part is discarded/truncated/rounded towards zero. Again, for 264 nodes in the final row, the above loops only 65 times.

When we know the total number of nodes in the tree, and the number of rows, we can use another logarithmic-time loop to compute the offset of the first element on each row of the tree, and the number of nodes on that row:

```<code>first_offset = []
nodes = []

curr_row = rows - 1
curr_offset = total - N
curr_left = N

While (curr_left > 1):
    nodes[curr_row] = curr_left
    first_offset[curr_row] = curr_offset
    curr_row = curr_row - 1
    curr_left = (curr_left + 1) / 2
    curr_offset = curr_offset - curr_left
}

first_offset[0] = 0
nodes[0] = 1
</code>```

As before, for 264 nodes in the final row, the above loops only 65 times.

All elements on a row are consecutive in memory, and if we use zero-based indexing, and N is the number of nodes on the final row, and we apply the above, then

rows is the number of rows in the tree

total is the total number of nodes in the tree

There are nodes[r] nodes on row r, if r >= 0 and r < rows

Array index for node on row r, column c is first_offset[r] + c

Node on row r, column c, with r > 0, has a parent on row r-1, column c/2, at array index first_offset[r-1] + c/2

Node on row r, column c, with r < rows - 1, has a left child on row r+1, column 2*c, at array index first_offset[r+1] + 2*c

Node on row r, column c, with r < rows - 1 and c < nodes[r] - 1, has a right child on row r+1, column 2*c+1, at array index first_offset[r+1] + 2*c + 1

Node on row r, column c, with r < rows - 1 and c < nodes[r] - 1, has both a left and a right child

This array is compact, and other than the nodes that get propagated upwards (so, maybe a few dozen nodes for a terabyte-sized dataset), wastes no storage.

If the number of nodes in the final row is stored with the array (for example, as an extra uint64_t following the array data), all readers can recover total, rows, first_offset[], and nodes[], and easily navigate the tree. (However, note that instead of just the array index, you use the "column" and "row" instead, and derive the array index using those.)

Because first_offset[] and nodes[] arrays have at most a few dozen entries, they should stay hot in caches, and using them should not harm performance.

Note that not all tree sizes are valid for the rules stated in the second paragraph above. For example, a tree with two nodes makes no sense: why would you duplicate the root node?

If you do know that the tree size (total) is valid, you can find N based on total in O(log2(total)*log2log2(total)) time complexity using a binary search, or in O((log2(total))²) if you use a simple loop. Remember, total is between 2*N-1 and 2*N-1+log2(N). Conversely, N cannot be greater than (N + 1)/2, or smaller than (N + 1)/2 - log2(total), because total is greater than N, and therefore log2(N) is less than log2(total). So, a binary search could be implemented as

```<code>Function Find_N(total):
    Nmax = (total + 1) / 2
    Nmin = Nmax - log2(total)

    t = Total(Nmin)
    If t == total:
        Return Nmin
    Else if t < total:
        Return "Bug!"
    End if

    t = Total(Nmax)
    if t == total:
        Return Nmax
    Else if t > total:
        Return "Bug!"
    End if

    Loop:

        N = (Nmin + Nmax) / 2
        If N == Nmin:
            Return "Invalid tree size!"
        End If

        t = Total(N)
        If t > total:
            Nmax = N
        Else if t < total:
            Nmin = N
        Else:
            return N
        End If
    End Loop
End Function
</code>```

Keep in mind that even with 264 nodes in the tree, the above function makes at most 1 + log2(64) = 6 calls to Total, a function implementing the first pseudocode snippet in this answer. Since you typically need this only once per program invocation, the overhead is truly irrelevant.

You can calculate log2(x) using log(x)/log(2), using the log2() function from <math.h> since C99 (but since double has less precision than uint64_t, I would add +1 to the result, or round it towards positive infinity using ceil(), just to be sure), or even using a simple loop:

```<code>Function ulog2(value):
    result = 0
    While (value > 0):
        result = result + 1
        value = value / 2
    End While
    Return result
End Function
</code>```

where once again, / denotes integer division.

Body:
Using 'sum' as a short hand for some arbitrary computation. I have a process that computes a single sum from a list of values by recursively summing pairs of values. Un-paired values are promoted up the tree unaltered until they can be paired.

Given this computation, I'm in search of the best way to balance computation (i.e. number of operation required to access array elements/nodes), and the most succinct encoding of all nodes in a 1 dimensional array (i.e. no gaps, nil values, or repeated values), and preferably without an additional index array that cannot be easily derived from the succinct encoding so that it would have to be saved along with the array.

Although the following are simple examples, in reality the number of values in the initial list can be extraordinarily large (2^47 or more).

For example, given the list [1, 2, 3, 4], the array is trivial: [10, 3, 7, 1, 2, 3, 4], and split nicely into rows that are easy to address by node, or as a reference to the entire row.

But for a 5 item list the tree looks like this:

Tree 1

         15
        /  \
       /    \
      /      \
     /        \
    10          5
  /   \       /   \
 3     7     5     -
/ \   / \   / \   / \
1  2  3  4 5   - -   -

The standard mapping left = i*2+1, right = i*2+2 gives us this array:

Array 1

[ 15, 10,  5,  3,   7,   5,  nil,   1,   2,   3,   4,   5,   nil,   nil, nil]

This array has 4 nil values, and the last element in the list '5' is repeated 2 times.

To improve this we can imply the repetition of the 5, and remove the nil values:

Array 2

[15, 10, 3, 7, 1, 2, 3, 4, 5]

Which is much more compact. This tree is the same, but conceptually looks a bit like:

Tree 2

       15
      / \
     /   \
    10    \
  /   \    \
 3     7    \
/ \   / \    \
1  2  3  4    5

In the Array 2 encoding I have 4 rows:

1. [1, 2, 3, 4]
2. [3, 7]
3. [10, 5]
4. [15]

Rows 1, 2 and 4 can simply be references into Array 2 allowing me to compute results 'in-place' with no allocations or copies. Very fast. Row 3 however, contains values in two non-contiguous cells. I have to break the simple logic used for the other rows, and possibly add copy, indexing or storage for a map.

I can construct complete/balanced sub trees (such as indexes 1-7, the tree for 1, 2, 3, 4), but it seems like they will not always be so nicely aligned when the odd number of items appears at different rows depending on input length.  For example consider a tree with an initial list of 6 elements.

Body:
Let's assume your tree has N nodes on the final (most numerous) row.

If you do store the nodes that are only propagated upwards, your tree has between 2*N-1 and 2*N-1+log2(N) nodes, total. The exact total number of nodes is given by OEIS A120511. Of these, at most floor(2 + log2(N-1)) are copied/propagated nodes.

The tree has floor(2 + log2(N-1)) rows. The number of rows as a function of  N (the number of elements on the final row) is OEIS A070941.

The number of rows in such trees is quite low. For example, if you have 240 ≈ 1,000,000,000,000 nodes in the final row, you only have 42 rows in the tree. For 264 nodes, you have just 66. Therefore, if you need some operation per row, it is not a high overhead.

A simple logarithmic-time function can compute the number of rows and the total number of nodes, given the number of nodes in the final row N:

# Account for the root node
rows = 1
total = 1

curr_left = N
While (curr_left > 1):
    rows = rows + 1
    total = total + curr_left
    curr_left = (curr_left + 1) / 2
End While

where / denotes integer division, i.e. any fractional part is discarded/truncated/rounded towards zero. Again, for 264 nodes in the final row, the above loops only 65 times.

When we know the total number of nodes in the tree, and the number of rows, we can use another logarithmic-time loop to compute the offset of the first element on each row of the tree, and the number of nodes on that row:

first_offset = []
nodes = []

curr_row = rows - 1
curr_offset = total - N
curr_left = N

While (curr_left > 1):
    nodes[curr_row] = curr_left
    first_offset[curr_row] = curr_offset
    curr_row = curr_row - 1
    curr_left = (curr_left + 1) / 2
    curr_offset = curr_offset - curr_left
}

first_offset[0] = 0
nodes[0] = 1

As before, for 264 nodes in the final row, the above loops only 65 times.

All elements on a row are consecutive in memory, and if we use zero-based indexing, and N is the number of nodes on the final row, and we apply the above, then

rows is the number of rows in the tree

total is the total number of nodes in the tree

There are nodes[r] nodes on row r, if r >= 0 and r < rows

Array index for node on row r, column c is first_offset[r] + c

Node on row r, column c, with r > 0, has a parent on row r-1, column c/2, at array index first_offset[r-1] + c/2

Node on row r, column c, with r < rows - 1, has a left child on row r+1, column 2*c, at array index first_offset[r+1] + 2*c

Node on row r, column c, with r < rows - 1 and c < nodes[r] - 1, has a right child on row r+1, column 2*c+1, at array index first_offset[r+1] + 2*c + 1

Node on row r, column c, with r < rows - 1 and c < nodes[r] - 1, has both a left and a right child

This array is compact, and other than the nodes that get propagated upwards (so, maybe a few dozen nodes for a terabyte-sized dataset), wastes no storage.

If the number of nodes in the final row is stored with the array (for example, as an extra uint64_t following the array data), all readers can recover total, rows, first_offset[], and nodes[], and easily navigate the tree. (However, note that instead of just the array index, you use the "column" and "row" instead, and derive the array index using those.)

Because first_offset[] and nodes[] arrays have at most a few dozen entries, they should stay hot in caches, and using them should not harm performance.

Note that not all tree sizes are valid for the rules stated in the second paragraph above. For example, a tree with two nodes makes no sense: why would you duplicate the root node?

If you do know that the tree size (total) is valid, you can find N based on total in O(log2(total)*log2log2(total)) time complexity using a binary search, or in O((log2(total))²) if you use a simple loop. Remember, total is between 2*N-1 and 2*N-1+log2(N). Conversely, N cannot be greater than (N + 1)/2, or smaller than (N + 1)/2 - log2(total), because total is greater than N, and therefore log2(N) is less than log2(total). So, a binary search could be implemented as

Function Find_N(total):
    Nmax = (total + 1) / 2
    Nmin = Nmax - log2(total)

    t = Total(Nmin)
    If t == total:
        Return Nmin
    Else if t < total:
        Return "Bug!"
    End if

    t = Total(Nmax)
    if t == total:
        Return Nmax
    Else if t > total:
        Return "Bug!"
    End if

    Loop:

        N = (Nmin + Nmax) / 2
        If N == Nmin:
            Return "Invalid tree size!"
        End If

        t = Total(N)
        If t > total:
            Nmax = N
        Else if t < total:
            Nmin = N
        Else:
            return N
        End If
    End Loop
End Function

Keep in mind that even with 264 nodes in the tree, the above function makes at most 1 + log2(64) = 6 calls to Total, a function implementing the first pseudocode snippet in this answer. Since you typically need this only once per program invocation, the overhead is truly irrelevant.

You can calculate log2(x) using log(x)/log(2), using the log2() function from <math.h> since C99 (but since double has less precision than uint64_t, I would add +1 to the result, or round it towards positive infinity using ceil(), just to be sure), or even using a simple loop:

Function ulog2(value):
    result = 0
    While (value > 0):
        result = result + 1
        value = value / 2
    End While
    Return result
End Function

where once again, / denotes integer division.


来源: stackexchange

问:
PHPExcel Writer Excel2007 error
I recently encountered this error in my report.

```<code>PHP Fatal error:  Allowed memory size of 1073741824 bytes exhausted (tried to allocate 3022731 bytes)
</code>```

I cant seem to resolved the problem, i already added:

```<code>set_time_limit(0);
ini_set('memory_limit', -1);
</code>```

in my script but it seems the issue is still persistent, by the way im using

```<code>PHPExcel ver 1.7.6
</code>```

My excel file output contains 55 headers and multiple worksheets (closely 45 - increasing) and each sheet contains about 150 to 500 records

I would like to seek for your help and advises to resolve my remedy T_T

Thanks!

答: I would suggest to import the Excel File into an Access Database and then query the database via ODBC from PHP.</p>

ContentLicense: CC BY-SA 3.0

Title: PHPExcel Writer Excel2007 error

Body:
I recently encountered this error in my report.

PHP Fatal error:  Allowed memory size of 1073741824 bytes exhausted (tried to allocate 3022731 bytes)

I cant seem to resolved the problem, i already added:

set_time_limit(0);
ini_set('memory_limit', -1);

in my script but it seems the issue is still persistent, by the way im using

PHPExcel ver 1.7.6

My excel file output contains 55 headers and multiple worksheets (closely 45 - increasing) and each sheet contains about 150 to 500 records

I would like to seek for your help and advises to resolve my remedy T_T

Thanks!


问:
PHP and C# SHA256 Hashes returning different strings
So, I found a question just like this with an accepted answer, so I hopped off and tried to implement the necessary changes. For some reason though, I am still getting two different strings, and I don't know what it is I'm doing wrong. I tried to comment on the accepted answer to find help, but I lack the reputation to do so. So, I figured I'd ask the question again (that question was 2 years old, too).

Let me explain what I'm doing.

In php...

```<code>$intermediatesalt = md5(uniqid(rand(), true));
$salt = substr($intermediatesalt, 0, 8);
$hashpassword = base64_encode(
hash('sha256', $salt . hash('sha256', $password), true)
);
</code>```

The line that says $hashpassword was taken from the accepted answer from this question. I didn't write any of this php, my friend did. I only know enough about programming to alter the code, but I couldn't create anything in php, let alone HTML.

After the hash has been created, both the hash and the salt are stored on a database.

The C# method I'm using is also from the answer I found here.

```<code>    public static string ComputeHash(string plainText, string salt)
    {
        // Convert plain text into a byte array.
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        byte[] saltBytes = Encoding.UTF8.GetBytes(salt);

        SHA256Managed hash = new SHA256Managed();

        // Compute hash value of salt.
        byte[] plainHash = hash.ComputeHash(plainTextBytes);

        byte[] concat = new byte[plainHash.Length + saltBytes.Length];

        System.Buffer.BlockCopy(saltBytes, 0, concat, 0, saltBytes.Length);
        System.Buffer.BlockCopy(plainHash, 0, concat, saltBytes.Length, plainHash.Length);

        byte[] tHashBytes = hash.ComputeHash(concat);

        // Convert result into a base64-encoded string.
        string hashValue = Convert.ToBase64String(tHashBytes);

        // Return the result.
        return hashValue;
    }
</code>```

But for some bizarre reason, even though the person who asked the question got what s/he wanted, I am still getting an undesired result.

This is the block of code that loads player data then compares the the php generated hashed password with the c# generated hashed password.

```<code>        // load the player based on the given email
        PlayerStructure.Player newPlayer = MySQL.loadPlayer(email);

        // compute a hash based on the given password and the retrieved salt
        // then, compare it to the hashed password on the database
        string hPassword = Program.ComputeHash(password, newPlayer.salt);

        if (newPlayer.password != hPassword)
        {
            sendStatusMsg(index, "Invalid password.");
            sendStatusMsg(index, "1: " + hPassword);
            sendStatusMsg(index, "2: " + newPlayer.password);

            return;
        }
</code>```

MySQL.loadPlayer loads the hash string and the salt string from the database, and I had to use those sendStatusMessage methods to print strings as this is for a server application that takes up to 15 minutes to load data from the database in debug mode. So I run the debug exe instead, ergo no Console.WriteLine calls. newPlayer.password is the hashed password stored on the database (the password created with php). hPassword is the computed hash using the C# method I borrowed.

The salt is e0071fa9 and the plain-text password is 'test'.

This is the result I get with the sendStatusMsg methods:

```<code>Invalid password.
1: 3QQyVEfmBN4kJJHsRQ307TCDYxNMpc4k3r3udBaVz8Y=
2: moHRVv9C0JvpdTk28xGm3uvPPuhatK2rAHXd5he4ZJI=
</code>```

Any ideas as to what I might be doing incorrectly? As I've stated before, I literally just used the answer on here (borrowing the code almost verbatim) and I'm still not getting my desired result. This is the question I referenced: Why isn't my PHP SHA256 hash equivalent to C# SHA256Managed hash

答:
Please on PHP avoid using your own hashing mechanism, unless you are a security / crypto expert and (more important, know what you are doing).

Have a good look on how password_hash works in PHP (and if using a PHP version that doesn't support it - please upgrade it), you can always use Anthony Ferrara compatibility library for good effect:

https://github.com/ircmaxell/password_compat

If you follow his blog, you will get some hints about the issues at stake:

http://blog.ircmaxell.com/search/label/Security

:)

Body:
So, I found a question just like this with an accepted answer, so I hopped off and tried to implement the necessary changes. For some reason though, I am still getting two different strings, and I don't know what it is I'm doing wrong. I tried to comment on the accepted answer to find help, but I lack the reputation to do so. So, I figured I'd ask the question again (that question was 2 years old, too).

Let me explain what I'm doing.

In php...

$intermediatesalt = md5(uniqid(rand(), true));
$salt = substr($intermediatesalt, 0, 8);
$hashpassword = base64_encode(
hash('sha256', $salt . hash('sha256', $password), true)
);

The line that says $hashpassword was taken from the accepted answer from this question. I didn't write any of this php, my friend did. I only know enough about programming to alter the code, but I couldn't create anything in php, let alone HTML.

After the hash has been created, both the hash and the salt are stored on a database.

The C# method I'm using is also from the answer I found here.

    public static string ComputeHash(string plainText, string salt)
    {
        // Convert plain text into a byte array.
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        byte[] saltBytes = Encoding.UTF8.GetBytes(salt);

        SHA256Managed hash = new SHA256Managed();

        // Compute hash value of salt.
        byte[] plainHash = hash.ComputeHash(plainTextBytes);

        byte[] concat = new byte[plainHash.Length + saltBytes.Length];

        System.Buffer.BlockCopy(saltBytes, 0, concat, 0, saltBytes.Length);
        System.Buffer.BlockCopy(plainHash, 0, concat, saltBytes.Length, plainHash.Length);

        byte[] tHashBytes = hash.ComputeHash(concat);

        // Convert result into a base64-encoded string.
        string hashValue = Convert.ToBase64String(tHashBytes);

        // Return the result.
        return hashValue;
    }

But for some bizarre reason, even though the person who asked the question got what s/he wanted, I am still getting an undesired result.

This is the block of code that loads player data then compares the the php generated hashed password with the c# generated hashed password.

        // load the player based on the given email
        PlayerStructure.Player newPlayer = MySQL.loadPlayer(email);

        // compute a hash based on the given password and the retrieved salt
        // then, compare it to the hashed password on the database
        string hPassword = Program.ComputeHash(password, newPlayer.salt);

        if (newPlayer.password != hPassword)
        {
            sendStatusMsg(index, "Invalid password.");
            sendStatusMsg(index, "1: " + hPassword);
            sendStatusMsg(index, "2: " + newPlayer.password);

            return;
        }

MySQL.loadPlayer loads the hash string and the salt string from the database, and I had to use those sendStatusMessage methods to print strings as this is for a server application that takes up to 15 minutes to load data from the database in debug mode. So I run the debug exe instead, ergo no Console.WriteLine calls. newPlayer.password is the hashed password stored on the database (the password created with php). hPassword is the computed hash using the C# method I borrowed.

The salt is e0071fa9 and the plain-text password is 'test'.

This is the result I get with the sendStatusMsg methods:

Invalid password.
1: 3QQyVEfmBN4kJJHsRQ307TCDYxNMpc4k3r3udBaVz8Y=
2: moHRVv9C0JvpdTk28xGm3uvPPuhatK2rAHXd5he4ZJI=

Any ideas as to what I might be doing incorrectly? As I've stated before, I literally just used the answer on here (borrowing the code almost verbatim) and I'm still not getting my desired result. This is the question I referenced: Why isn't my PHP SHA256 hash equivalent to C# SHA256Managed hash


问:
Java 8 method reference does not start thread?
Why does a method reference not start a thread in this example?

```<code>package example;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ESMethodReference {
    int i1, i2, result = 0;

    ESMethodReference(int i1, int i2){
        this.i1 =i1;
        this.i2 = i2;
    }

    public Runnable calculate(){
        System.out.print("In calculate()");
        return new Runnable() {
            @Override
            public void run() {
                result += i1 + i2;
                System.out.print(" creating result");
            }
        };
    }

    public static void main(String[] args) throws InterruptedException{
        ESMethodReference es = new ESMethodReference(1, 1);

        ExecutorService executorService = Executors.newSingleThreadExecutor();

        for (int i = 0; i < 2; i++){
            executorService.submit(es.calculate());
            Thread.sleep(100);  // Allow new thread to run
            System.out.println("\tes.calculate() result incremented " + es.result );

            executorService.submit(es::calculate);
            Thread.sleep(100);  // Allow new thread to run
            System.out.println("\tes::calculate result NOT incremented " + es.result );
        }

        executorService.shutdown();
    }
}
</code>```

Output:

In calculate() creating result  es.calculate() result incremented 2

In calculate()  es::calculate result NOT incremented 2

In calculate() creating result  es.calculate() result incremented 4

In calculate()  es::calculate result NOT incremented 4

答:
When you call es.calculate() it returns a Runnable with the code

```<code>public void run() {
    result += i1 + i2;
    System.out.print(" creating result");
}
</code>```

When you pass a method reference es::calculate, the code run will be

```<code>System.out.print("In calculate()");
return new Runnable() {
    @Override
    public void run() {
        result += i1 + i2;
        System.out.print(" creating result");
    }
};
</code>```

There's a difference between executing the return value of a method, and executing a method itself through a method reference.

Body:
Why does a method reference not start a thread in this example?

package example;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ESMethodReference {
    int i1, i2, result = 0;

    ESMethodReference(int i1, int i2){
        this.i1 =i1;
        this.i2 = i2;
    }

    public Runnable calculate(){
        System.out.print("In calculate()");
        return new Runnable() {
            @Override
            public void run() {
                result += i1 + i2;
                System.out.print(" creating result");
            }
        };
    }

    public static void main(String[] args) throws InterruptedException{
        ESMethodReference es = new ESMethodReference(1, 1);

        ExecutorService executorService = Executors.newSingleThreadExecutor();

        for (int i = 0; i < 2; i++){
            executorService.submit(es.calculate());
            Thread.sleep(100);  // Allow new thread to run
            System.out.println("\tes.calculate() result incremented " + es.result );

            executorService.submit(es::calculate);
            Thread.sleep(100);  // Allow new thread to run
            System.out.println("\tes::calculate result NOT incremented " + es.result );
        }

        executorService.shutdown();
    }
}

Output:

In calculate() creating result  es.calculate() result incremented 2

In calculate()  es::calculate result NOT incremented 2

In calculate() creating result  es.calculate() result incremented 4

In calculate()  es::calculate result NOT incremented 4

Body:
When you call es.calculate() it returns a Runnable with the code

public void run() {
    result += i1 + i2;
    System.out.print(" creating result");
}

When you pass a method reference es::calculate, the code run will be

System.out.print("In calculate()");
return new Runnable() {
    @Override
    public void run() {
        result += i1 + i2;
        System.out.print(" creating result");
    }
};

There's a difference between executing the return value of a method, and executing a method itself through a method reference.


问:
Completing Source[ByteString, _] in Akka-Http
I wanted to use Alpakka for handling S3 upload and download with Akka Steams. However, I got stuck with using Source produced by S3Client within Akka Http routes. The error message I get is:

```<code>[error]  found   : akka.stream.scaladsl.Source[akka.util.ByteString,_$1] where type _$1
[error]  required: akka.http.scaladsl.marshalling.ToResponseMarshallable
[error]     complete(source)
</code>```

I assume that it is some annoying trivial thing, like missing implicit import, but I was not able to pinpoint what I am missing.

I've created some minimal example to illustrate the issue:

```<code>import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Source
import akka.util.ByteString

import scala.concurrent.ExecutionContext

class Test {

  implicit val actorSystem: ActorSystem = ActorSystem()
  implicit val materializer: ActorMaterializer = ActorMaterializer()
  implicit val executionContext: ExecutionContext = actorSystem.dispatcher

  val route = (path("test") & get) {
    def source: Source[ByteString, _] = ??? // just assume that I am able to get that value
    complete(source) // here error happens
  }

  Http().bindAndHandle(route, "localhost", 8000)
}
</code>```

Do you have some suggestions, what can I try? I am using

```<code>libraryDependencies += "com.typesafe.akka"%% "akka-http" % "10.0.5"
</code>```

答:
You need to create an HttpEntity from the source, and give it a content-type.

```<code>complete(HttpEntity(ContentTypes.`application/json`, source))
</code>```

Body:
I wanted to use Alpakka for handling S3 upload and download with Akka Steams. However, I got stuck with using Source produced by S3Client within Akka Http routes. The error message I get is:

[error]  found   : akka.stream.scaladsl.Source[akka.util.ByteString,_$1] where type _$1
[error]  required: akka.http.scaladsl.marshalling.ToResponseMarshallable
[error]     complete(source)

I assume that it is some annoying trivial thing, like missing implicit import, but I was not able to pinpoint what I am missing.

I've created some minimal example to illustrate the issue:

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Source
import akka.util.ByteString

import scala.concurrent.ExecutionContext

class Test {

  implicit val actorSystem: ActorSystem = ActorSystem()
  implicit val materializer: ActorMaterializer = ActorMaterializer()
  implicit val executionContext: ExecutionContext = actorSystem.dispatcher

  val route = (path("test") & get) {
    def source: Source[ByteString, _] = ??? // just assume that I am able to get that value
    complete(source) // here error happens
  }

  Http().bindAndHandle(route, "localhost", 8000)
}

Do you have some suggestions, what can I try? I am using

libraryDependencies += "com.typesafe.akka"%% "akka-http" % "10.0.5"

Body:
You need to create an HttpEntity from the source, and give it a content-type.

complete(HttpEntity(ContentTypes.`application/json`, source))


问:
Bukkit PlayerDeathEvent
why isn't this working? I don't get any response if I've been killed! So as you can see I have tested multiple ways. But no one is working. </p>

```<code>package net.gameforce.testing;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.plugin.java.JavaPlugin;

public class Main extends JavaPlugin implements Listener {

@Override
public void onEnable() {
    getServer().getPluginManager().registerEvents(this,this);
    getLogger().info("Testing Plugin Started");
}

public void onDisable() {}

@EventHandler
public void onPlayerInteract(PlayerInteractEvent event){
    Bukkit.broadcastMessage("test");
    event.getPlayer().setExp(100);
}
public void onPlayerDeath (PlayerDeathEvent event){
    Bukkit.broadcastMessage("send");
    event.getEntity().getPlayer().setExp(1000);
}

public boolean onDeath (PlayerDeathEvent event) {
    Player Player = event.getEntity();
    Bukkit.broadcastMessage(Player.getKiller().getDisplayName() + ", has killed you!");
    if (Player.getKiller() != null) {
        Bukkit.broadcastMessage("No Player");
    }
    else {
        Bukkit.broadcastMessage("IDK");
    }

    return true;
}
}
</code>```

<p>Have I done something wrong?  </p>

答:
Quotation from http://bukkit.gamepedia.com/Event_API_Reference#.40EventHandler

"Before this method can be invoked by Bukkit when the "Event" is fired, we need to annotate it. We do this with EventHandlers."

You've added this annotation to your onPlayerInteract method, but none of your others, such as your onDeath method. If your listener is setup correctly, adding the @EventHandler annotation to these methods will allow bukkit to correctly invoke them, like so:

```<code>@EventHandler
public void onPlayerDeath (PlayerDeathEvent event){
    Bukkit.broadcastMessage("send");
    event.getEntity().getPlayer().setExp(1000);
}
</code>```

Title: Bukkit PlayerDeathEvent

Body:
why isn't this working? I don't get any response if I've been killed! So as you can see I have tested multiple ways. But no one is working.

package net.gameforce.testing;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.plugin.java.JavaPlugin;

public class Main extends JavaPlugin implements Listener {

@Override
public void onEnable() {
    getServer().getPluginManager().registerEvents(this,this);
    getLogger().info("Testing Plugin Started");
}

public void onDisable() {}

@EventHandler
public void onPlayerInteract(PlayerInteractEvent event){
    Bukkit.broadcastMessage("test");
    event.getPlayer().setExp(100);
}
public void onPlayerDeath (PlayerDeathEvent event){
    Bukkit.broadcastMessage("send");
    event.getEntity().getPlayer().setExp(1000);
}

public boolean onDeath (PlayerDeathEvent event) {
    Player Player = event.getEntity();
    Bukkit.broadcastMessage(Player.getKiller().getDisplayName() + ", has killed you!");
    if (Player.getKiller() != null) {
        Bukkit.broadcastMessage("No Player");
    }
    else {
        Bukkit.broadcastMessage("IDK");
    }

    return true;
}
}

Have I done something wrong?

Body:
Quotation from http://bukkit.gamepedia.com/Event_API_Reference#.40EventHandler

"Before this method can be invoked by Bukkit when the "Event" is fired, we need to annotate it. We do this with EventHandlers."

You've added this annotation to your onPlayerInteract method, but none of your others, such as your onDeath method. If your listener is setup correctly, adding the @EventHandler annotation to these methods will allow bukkit to correctly invoke them, like so:

@EventHandler
public void onPlayerDeath (PlayerDeathEvent event){
    Bukkit.broadcastMessage("send");
    event.getEntity().getPlayer().setExp(1000);
}


问:
Adding a dynamic servlet using servlet 3.0 throws exception
I need to create add servlets at runtime. When I run the following code.

```<code>protected void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
    {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            out.println("<html>");
            out.println("<head>");
            out.println("<title> URI out</title>");
            out.println("</head>");
            out.println("<body>");
            Integer generatedKey = Math.abs(randomiser.nextInt());
            out.print(generatedKey);

            createServlet(Integer.toString(generatedKey),request.getServletContext());

        } finally {
            out.println("</body>");
            out.println("</html>");
            out.close();
        }
    }

    private void createServlet(String generatedKey, ServletContext servletContext) {
        String servletMapping = "/"+generatedKey;

 ServletRegistration sr = servletContext.addServlet(generatedKey, "com.path.lbs.servlets.testDynamic");

        sr.setInitParameter("keyname", generatedKey);
        sr.addMapping(servletMapping);

    }
</code>```

I get the following error.

java.lang.IllegalStateException:
  PWC1422: Unable to configure mapping
  for servlet 1114600676 of servlet
  context /123-LBS, because this servlet
  context has already been initialized

Is it impossible to add new servlets at runtime i.e. after the Servlet Context is initialised or am I doing something wrong?

答:
Is it impossible to add new servlets at runtime i.e. after the Servlet Context is initialised?

That's correct. You need to do it in ServletContextListener#contextInitialized().

```<code>@WebListener
public class Config implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent event) {
        // Do it here.
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        // ...
    }
}
</code>```

However, for your particular functional requirement, a single controller servlet in combination with command pattern is much better suited. You could then add commands (actions) during runtime and intercept on it based on the request URI. See also my answer on Design Patterns web based applications for a kickoff.

ContentLicense: CC BY-SA 2.5

Body:
I need to create add servlets at runtime. When I run the following code.

protected void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
    {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            out.println("");
            out.println("");
            out.println("<title> URI out</title>");
            out.println("");
            out.println("");
            Integer generatedKey = Math.abs(randomiser.nextInt());
            out.print(generatedKey);

            createServlet(Integer.toString(generatedKey),request.getServletContext());

        } finally {
            out.println("");
            out.println("");
            out.close();
        }
    }

    private void createServlet(String generatedKey, ServletContext servletContext) {
        String servletMapping = "/"+generatedKey;

 ServletRegistration sr = servletContext.addServlet(generatedKey, "com.path.lbs.servlets.testDynamic");

        sr.setInitParameter("keyname", generatedKey);
        sr.addMapping(servletMapping);

    }

I get the following error.

java.lang.IllegalStateException:
  PWC1422: Unable to configure mapping
  for servlet 1114600676 of servlet
  context /123-LBS, because this servlet
  context has already been initialized

Is it impossible to add new servlets at runtime i.e. after the Servlet Context is initialised or am I doing something wrong?

Body:
Is it impossible to add new servlets at runtime i.e. after the Servlet Context is initialised?

That's correct. You need to do it in ServletContextListener#contextInitialized().

@WebListener
public class Config implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent event) {
        // Do it here.
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        // ...
    }
}

However, for your particular functional requirement, a single controller servlet in combination with command pattern is much better suited. You could then add commands (actions) during runtime and intercept on it based on the request URI. See also my answer on Design Patterns web based applications for a kickoff.


问:
Modifying a subset of rows in a pandas dataframe
Assume I have a pandas DataFrame with two columns, A and B. I'd like to modify this DataFrame (or create a copy) so that B is always NaN whenever A is 0. How would I achieve that?

I tried the following

```<code>df['A'==0]['B'] = np.nan
</code>```

and

```<code>df['A'==0]['B'].values.fill(np.nan)
</code>```

without success.

答:
Starting from pandas 0.20 ix is deprecated. The right way is to use df.loc

here is a working example

```<code>>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame({"A":[0,1,0], "B":[2,0,5]}, columns=list('AB'))
>>> df.loc[df.A == 0, 'B'] = np.nan
>>> df
   A   B
0  0 NaN
1  1   0
2  0 NaN
>>>
</code>```

Explanation:

As explained in the doc here, .loc is primarily label based, but may also be used with a boolean array.

So, what we are doing above is applying df.loc[row_index, column_index] by:

Exploiting the fact that loc can take a boolean array as a mask that tells pandas which subset of rows we want to change in row_index

Exploiting the fact loc is also label based to select the column using the label 'B' in the column_index

We can use logical, condition or  any operation that returns a series of booleans to construct the array of booleans.  In the above example, we want any rows that contain a 0, for that we can use df.A == 0, as you can see in the example below, this returns a series of booleans.

```<code>>>> df = pd.DataFrame({"A":[0,1,0], "B":[2,0,5]}, columns=list('AB'))
>>> df
   A  B
0  0  2
1  1  0
2  0  5
>>> df.A == 0
0     True
1    False
2     True
Name: A, dtype: bool
>>>
</code>```

Then, we use the above array of booleans to select and modify the necessary rows:

```<code>>>> df.loc[df.A == 0, 'B'] = np.nan
>>> df
   A   B
0  0 NaN
1  1   0
2  0 NaN
</code>```

For more information check the advanced indexing documentation here.

Body:
Assume I have a pandas DataFrame with two columns, A and B. I'd like to modify this DataFrame (or create a copy) so that B is always NaN whenever A is 0. How would I achieve that?

I tried the following

df['A'==0]['B'] = np.nan

and

df['A'==0]['B'].values.fill(np.nan)

without success.

Body:
Starting from pandas 0.20 ix is deprecated. The right way is to use df.loc

here is a working example

>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame({"A":[0,1,0], "B":[2,0,5]}, columns=list('AB'))
>>> df.loc[df.A == 0, 'B'] = np.nan
>>> df
   A   B
0  0 NaN
1  1   0
2  0 NaN
>>>

Explanation:

As explained in the doc here, .loc is primarily label based, but may also be used with a boolean array.

So, what we are doing above is applying df.loc[row_index, column_index] by:

Exploiting the fact that loc can take a boolean array as a mask that tells pandas which subset of rows we want to change in row_index

Exploiting the fact loc is also label based to select the column using the label 'B' in the column_index

We can use logical, condition or  any operation that returns a series of booleans to construct the array of booleans.  In the above example, we want any rows that contain a 0, for that we can use df.A == 0, as you can see in the example below, this returns a series of booleans.

>>> df = pd.DataFrame({"A":[0,1,0], "B":[2,0,5]}, columns=list('AB'))
>>> df
   A  B
0  0  2
1  1  0
2  0  5
>>> df.A == 0
0     True
1    False
2     True
Name: A, dtype: bool
>>>

Then, we use the above array of booleans to select and modify the necessary rows:

>>> df.loc[df.A == 0, 'B'] = np.nan
>>> df
   A   B
0  0 NaN
1  1   0
2  0 NaN

For more information check the advanced indexing documentation here.

ContentLicense: CC BY-SA 4.0


问:
Slugfy in filter sqlalchemy
I'm trying slug some data, i use some lower and replace to change the special caracters i need:

my query is like this:

```<code>return Person.query.get(person_id).name.filter(func.lower(func.replace(Person.name, "ç", "c"))
</code>```

works well,  but if i recive a other character like á or other special character, it's dosen't work.

Someone can tell me the best way to handle that, make a list of all special characters, or a sqlalchemy has a func to slug?

答:
You wouldn't be using lower and replace to slugify.
Try a library like: un33k/python-slugify (github).
In order to get the desired result, you can write something like:

```<code>from slugify import slugify
return Person.query.get(person_id).name.filter(slugify(Person.name))
</code>```

I'm not so sure that your query is going to work, I only replaced the slug part and I recommend you to check it first.

Title: Slugfy in filter sqlalchemy

Body:
I'm trying slug some data, i use some lower and replace to change the special caracters i need:

my query is like this:

return Person.query.get(person_id).name.filter(func.lower(func.replace(Person.name, "ç", "c"))

works well,  but if i recive a other character like á or other special character, it's dosen't work.

Someone can tell me the best way to handle that, make a list of all special characters, or a sqlalchemy has a func to slug?

Body:
You wouldn't be using lower and replace to slugify.
Try a library like: un33k/python-slugify (github).
In order to get the desired result, you can write something like:

from slugify import slugify
return Person.query.get(person_id).name.filter(slugify(Person.name))

I'm not so sure that your query is going to work, I only replaced the slug part and I recommend you to check it first.


问:
Variable modified in loop does not persist outside the loop
```<code>{% set title_org = nav_item.title.split(" ") %}
{% set title_mod = "" %}
{% for i in title_org %}
  {% if loop.index > 3 %}
    {% set title_mod = title_mod + ' ' + i %}
  {% endif %}
{% endfor %}
<a href="{{ nav_item.url }}" id="{{ id }}">{{ title_mod }}</a>
</code>```

{{ title_mod }} is an empty string despite concatenated within the loop. How can I retrieve the updated {{ title_mod }} outside the for loop?

答:
You should use array/dictionary like

```<code><p style="display:none;">
{% set title_data = {'org': nav_item.title.split(" "), 'mod' : ""} %}
{% for i in title_data.org %}
  {% if loop.index > 3 %}
    {{ title_data.update({'mod' : title_data.mod + ' ' + i}) }}
  {% endif %}
{% endfor %}
</p>
<a href="{{ nav_item.url }}" id="{{ id }}">{{ title_data.mod }}</a>
</code>```

Looks like a dupe

Body:
{% set title_org = nav_item.title.split(" ") %}
{% set title_mod = "" %}
{% for i in title_org %}
  {% if loop.index > 3 %}
    {% set title_mod = title_mod + ' ' + i %}
  {% endif %}
{% endfor %}
{{ title_mod }}

{{ title_mod }} is an empty string despite concatenated within the loop. How can I retrieve the updated {{ title_mod }} outside the for loop?

Body:
You should use array/dictionary like

<p style="display:none;">
{% set title_data = {'org': nav_item.title.split(" "), 'mod' : ""} %}
{% for i in title_data.org %}
  {% if loop.index > 3 %}
    {{ title_data.update({'mod' : title_data.mod + ' ' + i}) }}
  {% endif %}
{% endfor %}
</p>
<a href="{{ nav_item.url }}" id="{{ id }}">{{ title_data.mod }}</a>

Looks like a dupe


问:
build maven project with propriatery libraries included
How to create maven pom, which will make project buildable, can I include propriatery jars with my project directly without having to take them from repository? anyone did this before ?

EDIT :

I don't want to make it runnable by building assembly with dependencies jar, I want it to be buildable. So anyone having this project is able to build it, even if jars are nowhere to be found at any repository.

答:
You could either add the jar to your project and mess around with the maven-assembly-plugin, or  add the jar to your local repository:</p>

```<code>mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> -DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging> -DgeneratePom=true

Where: <path-to-file>  the path to the file to load
       <group-id>      the group that the file should be registered under
       <artifact-id>   the artifact name for the file
       <version>       the version of the file
       <packaging>     the packaging of the file e.g. jar
</code>```

Body:
You could either add the jar to your project and mess around with the maven-assembly-plugin, or  add the jar to your local repository:

mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> -DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging> -DgeneratePom=true

Where: <path-to-file>  the path to the file to load
       <group-id>      the group that the file should be registered under
       <artifact-id>   the artifact name for the file
       <version>       the version of the file
       <packaging>     the packaging of the file e.g. jar


问:
How do you configure Github Desktop to run from the command line in OSX?
I used to be able to do this with the Github GUI app like so:

```<code>$ github .
</code>```

which would open the current directory in the GUI, but need a new alias or such for "Github Desktop" which is the new GUI app as of Aug 12, 2015.

答: on Mac I solved this by uninstalling the beta version and installing a previous official release</p>

Body:
I used to be able to do this with the Github GUI app like so:

$ github .

which would open the current directory in the GUI, but need a new alias or such for "Github Desktop" which is the new GUI app as of Aug 12, 2015.


问:
Run Time Error Ballerina
Why I'm getting Runtime error in ballerina.

Error:- "You must set the JAVA_HOME variable before running Ballerina."

答:
Locate the Java installation directory (if you did not change the directory when the installation,it'll be something like this.  C:\Program Files\Java\jdk1.8.0_65)

Windows 8 or 10 – Go to Control Panel > System > Advanced System Settings

Click the Environment Variables

Under System Variables, click New

In the Variable Name field, enter either: JAVA_HOME if you installed the JDK (Java Development Kit) or JRE_HOME if you installed the JRE (Java Runtime Environment)

In the Variable Value field, enter your JDK or JRE installation path

Click OK

Title: Run Time Error Ballerina


问:
Android long drawable list
I have this list in an android Java file:

```<code>int[] imagelist = new int[]{R.drawable.n0d,R.drawable.n1d,R.drawable.n2d};
</code>```

How can I make this list longer with a loop? In the end I'd like something like this:

```<code>int[] imagelist = new int[]{R.drawable.n0d,R.drawable.n1d,...,R.drawable.n85d};
</code>```

Later I'd like to use it in a for loop, to display images in ImageViews:

```<code>int lenght = 3; //I'd like it to be: int lenght = 85;
for (int i=0;i<lenght;i++){
        imageViews[i] = new ImageView(this);
        imageViews[i].setImageResource(imagelist[i]);
        imageViews[i].setLayoutParams(LayoutParamsview);
        linearlayout.addView(imageViews[i]);
}
</code>```

答:
I've found the answer..!
I used getIdentifier.</p>

```<code>for (int i=0;i<lenght;i++){
    imagelist[i] = getResources().getIdentifier("n"+(i)+"d","drawable",getPackageName());
}
</code>```

Title: Android long drawable list

Body:
I have this list in an android Java file:

int[] imagelist = new int[]{R.drawable.n0d,R.drawable.n1d,R.drawable.n2d};

How can I make this list longer with a loop? In the end I'd like something like this:

int[] imagelist = new int[]{R.drawable.n0d,R.drawable.n1d,...,R.drawable.n85d};

Later I'd like to use it in a for loop, to display images in ImageViews:

int lenght = 3; //I'd like it to be: int lenght = 85;
for (int i=0;i<lenght;i++){
        imageViews[i] = new ImageView(this);
        imageViews[i].setImageResource(imagelist[i]);
        imageViews[i].setLayoutParams(LayoutParamsview);
        linearlayout.addView(imageViews[i]);
}

Body:
I've found the answer..!
I used getIdentifier.

for (int i=0;i<lenght;i++){
    imagelist[i] = getResources().getIdentifier("n"+(i)+"d","drawable",getPackageName());
}


问:
PHP Roomba Serial Port Communication
I am trying to communicate with an iRobot Roomba through the serial port using the PHP class developed by Remy Sanchez. I am sure it is sending the data as the iRobot USB cable is receiving the data and lighting up, however, the Roomba doesn't seem to be acknowledging the commands as defined in the Roomba Serial Command Interface (SCI) Specification manual. Is there a possible reason for this? Does the class distort the data in some way or does the Roomba require a certain data type to be sent to it that PHP doesn't support?

Additional Information (I'm not sure if this is relevant)

Using RealTerm, I can communicate with the Roomba directly using the Send Numbers function (if I try to communicate any other way, it sends every keypress). Using PuTTY, the Roomba doesn't accept my commands, even though I can force local echo + line editing on. It receives the commands, but doesn't do anything with them even though the baud rate is configured correctly.

Code

```<code>require("php_serial.class.php");
$serial = new phpSerial();
$serial->deviceSet("COM1");

$serial->confBaudRate(115200); //Baud rate: 115200
$serial->confParity("none");  //Parity (this is the "N" in "8-N-1")
$serial->confCharacterLength(8); //Character length (this is the "8" in "8-N-1")
$serial->confStopBits(1);  //Stop bits (this is the "1" in "8-N-1")
$serial->confFlowControl("none"); //Device does not support flow control

$serial->deviceOpen();

$start = sprintf("%c",128);
$power = sprintf("%c",133);

$serial->sendMessage("$start");

$time_start = microtime(true);
// Sleep for a while
usleep(1000000);
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did nothing in $time seconds <br>";

$serial->sendMessage("$power");
$serial->deviceClose();
</code>```

答:
While using Putty your OS is Linux, right? So COM1 might be wrong.
Try something like $serial->deviceSet("/dev/ttyAMA0");
And make sure your web-user (www-data?) is within the 'dialout' group.

But first of all get it working from the commandline (Bash):

Correct configuration of the serial port: sudo stty 115200 -F /dev/ttyAMA0 cs8 cread clocal

Send some testdata from bash (start passive mode): sudo echo -n -e "\x80" > /dev/ttyAMA0

Let the roomba clean: sudo echo -n -e "\x87" > /dev/ttyAMA0

Title: PHP Roomba Serial Port Communication

Body:
I am trying to communicate with an iRobot Roomba through the serial port using the PHP class developed by Remy Sanchez. I am sure it is sending the data as the iRobot USB cable is receiving the data and lighting up, however, the Roomba doesn't seem to be acknowledging the commands as defined in the Roomba Serial Command Interface (SCI) Specification manual. Is there a possible reason for this? Does the class distort the data in some way or does the Roomba require a certain data type to be sent to it that PHP doesn't support?

Additional Information (I'm not sure if this is relevant)

Using RealTerm, I can communicate with the Roomba directly using the Send Numbers function (if I try to communicate any other way, it sends every keypress). Using PuTTY, the Roomba doesn't accept my commands, even though I can force local echo + line editing on. It receives the commands, but doesn't do anything with them even though the baud rate is configured correctly.

Code

require("php_serial.class.php");
$serial = new phpSerial();
$serial->deviceSet("COM1");

$serial->confBaudRate(115200); //Baud rate: 115200
$serial->confParity("none");  //Parity (this is the "N" in "8-N-1")
$serial->confCharacterLength(8); //Character length (this is the "8" in "8-N-1")
$serial->confStopBits(1);  //Stop bits (this is the "1" in "8-N-1")
$serial->confFlowControl("none"); //Device does not support flow control

$serial->deviceOpen();

$start = sprintf("%c",128);
$power = sprintf("%c",133);

$serial->sendMessage("$start");

$time_start = microtime(true);
// Sleep for a while
usleep(1000000);
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did nothing in $time seconds
";

$serial->sendMessage("$power");
$serial->deviceClose();


问:
Dropdown Not Working with id="<?php echo $post->ID ?>"
My drop down menus aren't working, can someone spot the problem and suggest a fix?

```<code><div><ul><li><p class="more-info">
<a onclick="myFunction()" class="dropbtn">Dropdown</a></ul></li>
<div id="<?php echo $post->ID ?>" class="dropdown-content">
<?php echo $dropdown ?>
</div>
</div>

<script>
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("<?php echo $post->ID ?>").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {

var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
  var openDropdown = dropdowns[i];
  if (openDropdown.classList.contains('show')) {
    openDropdown.classList.remove('show');
  }
}
}
}
</script>
</div>
</code>```

Ive got a live version here - http://www.enjoycompare.com/test-2/

My Style.css

```<code>.product-box .dropbtn{border:none;cursor:pointer;margin-bottom:5px;}
.product-box .dropdown{position:relative;display:inline-block;}
.product-box .dropdown-content{width:auto;position:relative;margin:0px 20px 0px 20px;}
.product-box .dropdown-content ul{overflow:hidden;margin-left:-18px;margin-bottom:20px;}
.product-box .dropdown-content ul li{width:675px;float:left;margin:0 0 0 18px;padding:2px 0 10px 27px;background:url(img/icons/tick-bullet.png) top left no-repeat;}
.product-box .dropdown-content a {font-family:'Nunito', sans-serif;font-weight:700;padding:10px;color:#222;text-decoration:none;}
.product-box div.dropdown-content:not(.show) { display: none!important; }
</code>```

答:
You have plenty of HTML errors in your page, I guess that at least one (or more) of them effects on your script. Anyway, It should work this way (Your PHP is valid):

Demo (Note: PHP tags has been removed)

/* When the user clicks on the button,
   toggle between hiding and showing the dropdown content */
function myFunction() {
    document.getElementById("<?php echo $post->ID; ?>").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
    if (!event.target.matches('.dropbtn')) {
        var dropdowns = document.getElementsByClassName("dropdown-content");
        var i;
        for (i = 0; i < dropdowns.length; i++) {
            var openDropdown = dropdowns[i];
            if (openDropdown.classList.contains('show')) {
                openDropdown.classList.remove('show');
            }
        }
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.dropdown-content:not(.show) {
    display: none;
}</code>```

                    Dropdown

    <div id="<?php echo $post->ID; ?>" class="dropdown-content">
        <?php echo $dropdown; ?>

```
</div>
</div>
</p>

<p><strong>UPDATE</strong> In continuation of our discussion at the comments below, You're experiencing the problem because you've placed the script everytime the loop is running, and that's why the script isn't working as expected.</p>

<p>Follow the Instructions below:</p>

<p>1) Move the <code>script</code> tag out of the loop, to the bottom of the page (just before the body ending <code></body></code>)</p>

<p>2) <strong>DO NOT USE PREDEFINED VALUE</strong>: that means, You have the following code:</p>

```
```

<p>As you can see, You've defined that <code><?php echo $post->ID; ?></code> will produce the desired element. It could be good, if it was only one element. but you're dealing with multiple elements, and this value override every other possible value.</p>

<p>3) So Instead, do this:</p>

```
```

<p><code>dropdown_id</code> will be accessible for you to modify (and re-modify) specifically for each iteration. I mean, all you have to do is simply update your html to:</p>

```

                <a onclick="myFunction('<?php echo $post->ID; ?>')" class="dropbtn">
                    Dropdown

    <div id="<?php echo $post->ID; ?>" class="dropdown-content">
        <?php echo $dropdown; ?>

```

Just move the PHP from the JavaScript and it will be fixed.

Hope it was helpful and please let me know if something went wrong (and, of course, if it worked as expected).

Body:
My drop down menus aren't working, can someone spot the problem and suggest a fix?

Dropdown

<div id="<?php echo $post->ID ?>" class="dropdown-content">
<?php echo $dropdown ?>

Ive got a live version here - http://www.enjoycompare.com/test-2/

My Style.css

.product-box .dropbtn{border:none;cursor:pointer;margin-bottom:5px;}
.product-box .dropdown{position:relative;display:inline-block;}
.product-box .dropdown-content{width:auto;position:relative;margin:0px 20px 0px 20px;}
.product-box .dropdown-content ul{overflow:hidden;margin-left:-18px;margin-bottom:20px;}
.product-box .dropdown-content ul li{width:675px;float:left;margin:0 0 0 18px;padding:2px 0 10px 27px;background:url(img/icons/tick-bullet.png) top left no-repeat;}
.product-box .dropdown-content a {font-family:'Nunito', sans-serif;font-weight:700;padding:10px;color:#222;text-decoration:none;}
.product-box div.dropdown-content:not(.show) { display: none!important; }

Body:
You have plenty of HTML errors in your page, I guess that at least one (or more) of them effects on your script. Anyway, It should work this way (Your PHP is valid):

Demo (Note: PHP tags has been removed)

/* When the user clicks on the button,
   toggle between hiding and showing the dropdown content */
function myFunction() {
    document.getElementById("<?php echo $post->ID; ?>").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
    if (!event.target.matches('.dropbtn')) {
        var dropdowns = document.getElementsByClassName("dropdown-content");
        var i;
        for (i = 0; i < dropdowns.length; i++) {
            var openDropdown = dropdowns[i];
            if (openDropdown.classList.contains('show')) {
                openDropdown.classList.remove('show');
            }
        }
    }
}

div.dropdown-content:not(.show) {
    display: none;
}

<div>
    <ul>
        <li>
            <p class="more-info">
                <a onclick="myFunction()" class="dropbtn">
                    Dropdown
                </a>
            </p>
        </li>
    </ul>
    <div id="<?php echo $post->ID; ?>" class="dropdown-content">
        <?php echo $dropdown; ?>
    </div>
</div>

UPDATE In continuation of our discussion at the comments below, You're experiencing the problem because you've placed the script everytime the loop is running, and that's why the script isn't working as expected.

Follow the Instructions below:

1) Move the script tag out of the loop, to the bottom of the page (just before the body ending </body>)

2) DO NOT USE PREDEFINED VALUE: that means, You have the following code:

<script>
/* When the user clicks on the button,
   toggle between hiding and showing the dropdown content */
function myFunction() {
    document.getElementById("<?php echo $post->ID; ?>").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
    if (!event.target.matches('.dropbtn')) {
        var dropdowns = document.getElementsByClassName("dropdown-content");
        var i;
        for (i = 0; i < dropdowns.length; i++) {
            var openDropdown = dropdowns[i];
            if (openDropdown.classList.contains('show')) {
                openDropdown.classList.remove('show');
            }
        }
    }
}
</script>

As you can see, You've defined that <?php echo $post->ID; ?> will produce the desired element. It could be good, if it was only one element. but you're dealing with multiple elements, and this value override every other possible value.

3) So Instead, do this:

<script>
/* When the user clicks on the button,
   toggle between hiding and showing the dropdown content */
function myFunction(dropdown_id) {
    document.getElementById(dropdown_id).classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
    if (!event.target.matches('.dropbtn')) {
        var dropdowns = document.getElementsByClassName("dropdown-content");
        var i;
        for (i = 0; i < dropdowns.length; i++) {
            var openDropdown = dropdowns[i];
            if (openDropdown.classList.contains('show')) {
                openDropdown.classList.remove('show');
            }
        }
    }
}
</script>

dropdown_id will be accessible for you to modify (and re-modify) specifically for each iteration. I mean, all you have to do is simply update your html to:

<div>
    <ul>
        <li>
            <p class="more-info">
                <a onclick="myFunction('<?php echo $post->ID; ?>')" class="dropbtn">
                    Dropdown
                </a>
            </p>
        </li>
    </ul>
    <div id="<?php echo $post->ID; ?>" class="dropdown-content">
        <?php echo $dropdown; ?>
    </div>
</div>

Just move the PHP from the JavaScript and it will be fixed.

Hope it was helpful and please let me know if something went wrong (and, of course, if it worked as expected).


问:
UI issues with bootstrap 3.3.7
I'm facing some UI problems in my project and i don't know if it's because JavaScript files i import or not? and I'm using angular JS 1.6.3 and bootstrap 3.3.7

here is the head of the html page i run :

```<code><head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<link rel="stylesheet" type="text/css" href="bootstrap-3.3.7-dist/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="bootstrap-3.3.7-dist/css/bootstrap-theme.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/cat.js"></script>
<script type="text/javascript" src="angular/angular.js"></script>
<script type="text/javascript" src="angular/angular-messages.js"></script>
<script type="text/javascript" src="angular/angular.min.js"></script>
<script type="text/javascript" src="angular/angular-sanitize.min.js"></script>
<script type="text/javascript" src="js/ui-bootstrap-tpls-2.5.0.min.js"></script>
<script type="text/javascript" src="js/dialogs.min.js" type="text/javascript"></script>

</head>
<body data-ng-controller="CategoryController">
<div class="col-md-8 col-sm-8 col-xs-8" style="position: absolute;top:0;bottom: 0;left: 0;right: 0;margin: auto;">
<div class="panel panel-info spacer">
<div class="panel-heading">
  <input type="checkbox" data-ng-model="checked" aria-label="Toggle ngHide" onchange="hideAndShow()"/><b> Category Form</b>
</div>
<div class="panel-body" class="check-element animate-show-hide" data-ng-hide="checked">
  <div class="alert alert-success" role="alert" data-ng-if="successMessage1" id="success-alert1">
    <strong>Success!</strong> {{successMessage1}}
  </div>
  <div class="alert alert-danger" role="alert" data-ng-if="errorMessage1" id="error-alert1">
    <strong>Error!</strong> {{errorMessage1}}
  </div>
  <form class="form-horizontal" name="catForm1" novalidate>
  <div class="form-group">
    <label class="control-label col-md-3 col-sm-3 col-xs-3" for="idCategory">Category ID</label>
    <div class="col-md-5 col-sm-5 col-xs-5">
      <input type="text" class="form-control" placeholder="Category ID" disabled="disabled">
    </div>
  </div>
  <div class="form-group">
    <label class="control-label col-md-3 col-sm-3 col-xs-3" for="nameCategory">Category Name</label>
    <div class="col-md-5 col-sm-5 col-xs-5" data-ng-class="{ 'has-error': catForm1.nameCategory.$touched && catForm1.nameCategory.name.$invalid}">
      <input type="text" class="form-control" data-ng-model="category.nameCategory" name="nameCategory" placeholder="Enter Category Name"
             data-ng-minlength="6"
             data-ng-maxlength="20"
             required/>
      <div class="help-block" data-ng-messages="catForm1.nameCategory.$error" data-ng-if="catForm1.nameCategory.$touched">
        <div data-ng-messages-include="messages.html"></div>
      </div>
    </div>
  </div>
  <div class="col-md-3 col-sm-3 col-xs-3 right">
    <div class="form-actions">
      <button data-ng-click="catForm1.$valid && saveCategory()" class="btn btn-primary btn-sm">Submit</button>
      <button data-ng-click="reset()" class="btn btn-default btn-sm" type="reset">Reset</button>
    </div></div><br><br></form></div></div>
<div class="panel panel-info spacer">
<div class="panel-heading"><b>Category List</b></div>
<div class="panel-body">
<form class="form-horizontal">
  <div class="col-md-4 col-sm-4 col-xs-4 right">
    <div class="input-group">
      <input type="text" class="form-control" data-ng-model="keyword" placeholder="Search">
      <div class="input-group-btn">
        <button data-ng-click="search()" class="btn btn-primary"><i class="glyphicon glyphicon-search"></i></button>
      </div></div></div></form><br><br>
<div class="alert alert-success" role="alert" data-ng-if="successMessage2" id="success-alert2">
  <strong>Success!</strong> {{successMessage2}}
</div>
<div class="alert alert-danger" role="alert" data-ng-if="errorMessage2" id="error-alert2">
  <strong>Danger!</strong> {{errorMessage2}}
</div>
<div id="categoryList">
  <div class="row" style="margin-right: 10px;margin-left: 10px;">
    <div class="col-xs-3"><b>CATEGORY ID</b></div>
    <div class="col-xs-6"><b>CATEGORY NAME</b></div>
    <div class="col-xs-1"></div>
    <div class="col-xs-1"></div>
  </div>
  <hr style="border-color: #cccccc;margin-bottom:5px !important; margin-top:5px !important;margin-right: 10px;margin-left: 10px;" />
  <div class="row" data-ng-repeat-start="c in categories.content" data-ng-class-odd="'alt'" style="margin-right: 10px;margin-left: 10px;">
    <div class="col-xs-3">{{c.idCategory}}</div>
    <div class="col-xs-6">{{c.nameCategory}}</div>
    <div class="col-xs-1 text-right"><button type="button" data-ng-mouseover="showEditRow(c)" class="btn btn-primary btn-sm">Edit</button></div>
    <div class="col-xs-1"><button type="button" data-ng-click="removeCategory(c.idCategory)" class="btn btn-danger btn-sm">Remove</button></div>
    </div>
    <div class="row" data-ng-repeat-end="" data-ng-show="active==c" data-ng-class-odd="'alt'" style="margin-right: 10px;margin-left: 10px;">
      <div class="col-xs-3"></div>
      <form name="catForm2" novalidate>
      <div class="col-xs-6" data-ng-class="{ 'has-error': catForm2.nameCategory2.$touched && catForm2.nameCategory2.$invalid}">
        <input class="form-control input-sm" data-ng-model="category.nameCategory2" name="nameCategory2"
             data-ng-minlength="6"
             data-ng-maxlength="20"
             required/>
        <div class="row" class="help-block" data-ng-messages="catForm2.nameCategory2.$error" data-ng-if="catForm2.nameCategory2.$touched">
          <div data-ng-messages-include="messages.html"></div>
        </div>
      </div>
      <div class="col-xs-1"><button type="button" data-ng-click="updateCategory()" class="btn btn-default btn-sm">Save</button></div>
      <div class="col-xs-1"></div>
      </form>
    </div>
  </div>
  <br>
  <div class="col-md-8 col-sm-8 col-xs-8">
    <ul class="nav nav-pills">
      <li class="clickable" data-ng-repeat="p in pages track by $index" data-ng-class= "{active:$index==currentPage}" >
        <a data-ng-click="goToPage($index)">{{$index}}</a>
      </li>
    </ul>
  </div></div></div></div></body></html>
</code>```

and here it is the javascript file :

```<code>var app=angular.module('crm',['ngMessages']);
app.controller('CategoryController', function($scope,$http,$document,$q){

$scope.categories=[];
$scope.keyword=null;
$scope.currentPage=0;
$scope.category={nameCategory:null};
$scope.successMessage1 = '';
$scope.errorMessage1 = '';
$scope.done = false;
$scope.successMessage2 = '';
$scope.errorMessage2='';

//show and hide a DIV
$scope.hideAndShow=function(){
    $scope.checkbox = element(by.model('checked'));
    $scope.checkElem = element(by.css('.check-element'));
    expect($scope.checkElem.isDisplayed()).toBe(true);
    $scope.checkbox.click();
    expect($scope.checkElem.isDisplayed()).toBe(false);
};

//find a category by a keyword
$scope.search=function(){
    $http.get("/catByKW?kw="+$scope.keyword+"&page="+$scope.currentPage)
    .then(function(response){
        $scope.categories=response.data;
        $scope.pages=new Array(response.data.totalPages);
    });
};

//index of category list
$scope.goToPage=function(p){
    $scope.currentPage=p;
    $scope.search();
};

//reset catForm1
$scope.reset1=function(){
    $scope.successMessage1='';
    $scope.errorMessage1='';
    $scope.category={};
    $scope.catForm1.$setPristine(); //reset Form
};

//save a new category
$scope.saveCategory=function(){
    $http({
          method  : 'GET',
          url     : '/saveCat?nameCategory='+$scope.category.nameCategory,
          headers : {'Content-Type':'application/x-wwww-form-urlencoded'}
    })
    .then(
          function successCallback(response){

              //var x = document.forms['catForm']['nameCategory'].value;
              //x='';
              document.forms['catForm1'].reset1();
              console.log('Category created successfully');
              $scope.successMessage1 = 'Category created successfully';
              $scope.errorMessage1='';
              $scope.done = true;
              setTimeout(function() {
                    $("#success-alert1").fadeIn(2000).fadeOut(4000);
              });
              //$scope.category={};
              //$scope.catForm.$setPristine();

          },
          function errorCallback(errResponse){
              console.error('Error while creating Category : Duplicate entry!');
              $scope.errorMessage1 = 'Error while creating Category: Duplicate entry!  ' + errResponse.data.object;
              $scope.successMessage1='';
              setTimeout(function() {
                $("#error-alert1").fadeIn(2000).fadeOut(4000);
              });
          }
     );
};
//show a row for updating a category
$scope.showEditRow=function(r){
  if($scope.active != r){
    $scope.active = r;
  }
  else{
    $scope.active = null;
  }
};

//remove a category
$scope.removeCategory=function(catID) {
    $http.delete('/deleteCat?catId='+catID)
        .then(
            function successCallback(response){
                $scope.search();
                $scope.successMessage2 = 'Category deleted successfully';
                $scope.errorMessage2='';
                setTimeout(function() {
                    $("#success-alert2").fadeIn(2000).fadeOut(4000);
                });
            },
            function errorCallback(errResponse) {
                console.error('Error while removing Category with id :'+catID);
                $scope.errorMessage2 = 'Error while deleting Category: ' + errResponse.data;
                $scope.successMessage2='';
                setTimeout(function() {
                    $("#error-alert2").fadeIn(2000).fadeOut(4000);
                });
            }
        )
};

});
</code>```

and here is what i got
and this is i got on the console

console

答:
You are added two angular.js dependencies on your page. Please use either angular.js or angular.min.js and try

And also cat.js contains angular code please put that script after angular.js
Hope this helps

Title: UI issues with bootstrap 3.3.7

Body:
I'm facing some UI problems in my project and i don't know if it's because JavaScript files i import or not? and I'm using angular JS 1.6.3 and bootstrap 3.3.7

here is the head of the html page i run :

<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<link rel="stylesheet" type="text/css" href="bootstrap-3.3.7-dist/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="bootstrap-3.3.7-dist/css/bootstrap-theme.min.css" rel="stylesheet"/>

  <input type="checkbox" data-ng-model="checked" aria-label="Toggle ngHide" onchange="hideAndShow()"/> Category Form

    Success! {{successMessage1}}

    Error! {{errorMessage1}}

  <form class="form-horizontal" name="catForm1" novalidate>

    Category ID

      <input type="text" class="form-control" placeholder="Category ID" disabled="disabled">

    Category Name

      <input type="text" class="form-control" data-ng-model="category.nameCategory" name="nameCategory" placeholder="Enter Category Name"
             data-ng-minlength="6"
             data-ng-maxlength="20"
             required/>

      <button data-ng-click="catForm1.$valid && saveCategory()" class="btn btn-primary btn-sm">Submit</button>
      <button data-ng-click="reset()" class="btn btn-default btn-sm" type="reset">Reset</button>

</form>

Category List

<form class="form-horizontal">

      <input type="text" class="form-control" data-ng-model="keyword" placeholder="Search">

        <button data-ng-click="search()" class="btn btn-primary"></button>

</form>

  Success! {{successMessage2}}

  Danger! {{errorMessage2}}

CATEGORY ID

CATEGORY NAME

{{c.idCategory}}

{{c.nameCategory}}

<button type="button" data-ng-mouseover="showEditRow(c)" class="btn btn-primary btn-sm">Edit</button>

<button type="button" data-ng-click="removeCategory(c.idCategory)" class="btn btn-danger btn-sm">Remove</button>

      <form name="catForm2" novalidate>

        <input class="form-control input-sm" data-ng-model="category.nameCategory2" name="nameCategory2"
             data-ng-minlength="6"
             data-ng-maxlength="20"
             required/>

<button type="button" data-ng-click="updateCategory()" class="btn btn-default btn-sm">Save</button>

      </form>

        {{$index}}

and here it is the javascript file :

var app=angular.module('crm',['ngMessages']);
app.controller('CategoryController', function($scope,$http,$document,$q){

$scope.categories=[];
$scope.keyword=null;
$scope.currentPage=0;
$scope.category={nameCategory:null};
$scope.successMessage1 = '';
$scope.errorMessage1 = '';
$scope.done = false;
$scope.successMessage2 = '';
$scope.errorMessage2='';

//show and hide a DIV
$scope.hideAndShow=function(){
    $scope.checkbox = element(by.model('checked'));
    $scope.checkElem = element(by.css('.check-element'));
    expect($scope.checkElem.isDisplayed()).toBe(true);
    $scope.checkbox.click();
    expect($scope.checkElem.isDisplayed()).toBe(false);
};

//find a category by a keyword
$scope.search=function(){
    $http.get("/catByKW?kw="+$scope.keyword+"&page="+$scope.currentPage)
    .then(function(response){
        $scope.categories=response.data;
        $scope.pages=new Array(response.data.totalPages);
    });
};

//index of category list
$scope.goToPage=function(p){
    $scope.currentPage=p;
    $scope.search();
};

//reset catForm1
$scope.reset1=function(){
    $scope.successMessage1='';
    $scope.errorMessage1='';
    $scope.category={};
    $scope.catForm1.$setPristine(); //reset Form
};

//save a new category
$scope.saveCategory=function(){
    $http({
          method  : 'GET',
          url     : '/saveCat?nameCategory='+$scope.category.nameCategory,
          headers : {'Content-Type':'application/x-wwww-form-urlencoded'}
    })
    .then(
          function successCallback(response){

              //var x = document.forms['catForm']['nameCategory'].value;
              //x='';
              document.forms['catForm1'].reset1();
              console.log('Category created successfully');
              $scope.successMessage1 = 'Category created successfully';
              $scope.errorMessage1='';
              $scope.done = true;
              setTimeout(function() {
                    $("#success-alert1").fadeIn(2000).fadeOut(4000);
              });
              //$scope.category={};
              //$scope.catForm.$setPristine();

          },
          function errorCallback(errResponse){
              console.error('Error while creating Category : Duplicate entry!');
              $scope.errorMessage1 = 'Error while creating Category: Duplicate entry!  ' + errResponse.data.object;
              $scope.successMessage1='';
              setTimeout(function() {
                $("#error-alert1").fadeIn(2000).fadeOut(4000);
              });
          }
     );
};
//show a row for updating a category
$scope.showEditRow=function(r){
  if($scope.active != r){
    $scope.active = r;
  }
  else{
    $scope.active = null;
  }
};

//remove a category
$scope.removeCategory=function(catID) {
    $http.delete('/deleteCat?catId='+catID)
        .then(
            function successCallback(response){
                $scope.search();
                $scope.successMessage2 = 'Category deleted successfully';
                $scope.errorMessage2='';
                setTimeout(function() {
                    $("#success-alert2").fadeIn(2000).fadeOut(4000);
                });
            },
            function errorCallback(errResponse) {
                console.error('Error while removing Category with id :'+catID);
                $scope.errorMessage2 = 'Error while deleting Category: ' + errResponse.data;
                $scope.successMessage2='';
                setTimeout(function() {
                    $("#error-alert2").fadeIn(2000).fadeOut(4000);
                });
            }
        )
};

});

and here is what i got
and this is i got on the console

console


问:
PyYaml "include file" and yaml aliases (anchors/references)
I had a large YAML file with a massive use of YAML anchors and references, for example:

```<code>warehouse:
  obj1: &obj1
    key1: 1
    key2: 2
specific:
  spec1:
    <<: *obj1
  spec2:
    <<: *obj1
    key1: 10
</code>```

The file got too large, so I looked for a solution that will allow me split to 2 files: warehouse.yaml and specific.yaml, and to include the warehouse.yaml inside the specific.yaml. I read this simple article, which describes how I can use PyYAML to achieve that, but it also says that the merge key(<<) is not supported.

I really got an error:

yaml.composer.ComposerError: found undefined alias 'obj1

when I tried to go like that.

So, I started looking for alternative way and I got confused because I don't really know much about PyYAML.

Can I get the desired merge key support? Any other solutions for my problem?

答:
Crucial for the handling of anchors and aliases in PyYAML is the dict anchors that is part of the Composer. It maps anchor to nodes so that aliases can be looked up. It existence is limited  by the existence of the Composer, which is a composite element of the Loader that you use.

That Loader class only exists during the time of the call to yaml.load() so there is no trivial way to extract this afterwards: first you would have to make the instance of the Loader() persist and then make sure that the  normal compose_document() method is not called (which among other things does self.anchors = {}, to be clean for the next document (in a single stream)).

To further complicate things if you would have warehouse.yaml:

```<code>warehouse:
  obj1: &obj1
    key1: 1
    key2: 2
</code>```

and specific.yaml:

```<code>warehouse: !include warehouse.yaml
specific:
  spec1:
    <<: *obj1
  spec2:
    <<: *obj1
    key1: 10
</code>```

you would never get this to work with your snippet, even if you could preserve, extract and pass on the anchor information because the composer handling specific.yaml will much earlier encountering a non-defined alias than the tag !include gets used for construction (and filling anchors).

What you can do to circumvent this problem is to include specific.yaml

```<code>specific:
  spec1:
    <<: *obj1
  spec2:
    <<: *obj1
    key1: 10
</code>```

from warehouse.yaml:

```<code>warehouse:
  obj1: &obj1
    key1: 1
    key2: 2
specific: !include specific.yaml
</code>```

, or include both in a third file. Please note that the key specific is in both files.

With those two files run:

```<code>import sys
from ruamel import yaml

def my_compose_document(self):
    self.get_event()
    node = self.compose_node(None, None)
    self.get_event()
    # self.anchors = {}    # <<<< commented out
    return node

yaml.SafeLoader.compose_document = my_compose_document

# adapted from http://code.activestate.com/recipes/577613-yaml-include-support/
def yaml_include(loader, node):
    with open(node.value) as inputfile:
        return list(my_safe_load(inputfile, master=loader).values())[0]
#              leave out the [0] if your include file drops the key ^^^

yaml.add_constructor("!include", yaml_include, Loader=yaml.SafeLoader)

def my_safe_load(stream, Loader=yaml.SafeLoader, master=None):
    loader = Loader(stream)
    if master is not None:
        loader.anchors = master.anchors
    try:
        return loader.get_single_data()
    finally:
        loader.dispose()

with open('warehouse.yaml') as fp:
    data = my_safe_load(fp)
yaml.safe_dump(data, sys.stdout, default_flow_style=False)
</code>```

which gives:

```<code>specific:
  spec1:
    key1: 1
    key2: 2
  spec2:
    key1: 10
    key2: 2
warehouse:
  obj1:
    key1: 1
    key2: 2
</code>```

If your specific.yaml would not have the top-level key specific:

```<code>spec1:
  <<: *obj1
spec2:
  <<: *obj1
  key1: 10
</code>```

then replace the last line of yaml_include() with:

```<code>return my_safe_load(inputfile, master=loader)
</code>```

The above was done with ruamel.yaml (disclaimer: I am the author of that package) and tested on Python 2.7 and 3.6. By changing the import it will work with PyYAML as well.

With the new ruamel.yaml API the above can be much simplified, because the loader handed to the yaml_include() constructor knows about the YAML instance, but of course you still need an adapted compose_document that doesn't destroy anchors. Assuming the specific.yaml without top-level key specific, the following gives the same output as before.

```<code>import sys
from ruamel.std.pathlib import Path
from ruamel.yaml import YAML, version_info

yaml = YAML(typ='safe', pure=True)
yaml.default_flow_style = False

def my_compose_document(self):
    self.parser.get_event()
    node = self.compose_node(None, None)
    self.parser.get_event()
    # self.anchors = {}    # <<<< commented out
    return node

yaml.Composer.compose_document = my_compose_document

# adapted from http://code.activestate.com/recipes/577613-yaml-include-support/
def yaml_include(loader, node):
    y = loader.loader
    yaml = YAML(typ=y.typ, pure=y.pure)  # same values as including YAML
    yaml.composer.anchors = loader.composer.anchors
    return yaml.load(Path(node.value))

yaml.Constructor.add_constructor("!include", yaml_include)

data = yaml.load(Path('warehouse.yaml'))
yaml.dump(data, sys.stdout)
</code>```

Body:
I had a large YAML file with a massive use of YAML anchors and references, for example:

warehouse:
  obj1: &obj1
    key1: 1
    key2: 2
specific:
  spec1:
    <<: *obj1
  spec2:
    <<: *obj1
    key1: 10

The file got too large, so I looked for a solution that will allow me split to 2 files: warehouse.yaml and specific.yaml, and to include the warehouse.yaml inside the specific.yaml. I read this simple article, which describes how I can use PyYAML to achieve that, but it also says that the merge key(<<) is not supported.

I really got an error:

yaml.composer.ComposerError: found undefined alias 'obj1

when I tried to go like that.

So, I started looking for alternative way and I got confused because I don't really know much about PyYAML.

Can I get the desired merge key support? Any other solutions for my problem?

Body:
Crucial for the handling of anchors and aliases in PyYAML is the dict anchors that is part of the Composer. It maps anchor to nodes so that aliases can be looked up. It existence is limited  by the existence of the Composer, which is a composite element of the Loader that you use.

That Loader class only exists during the time of the call to yaml.load() so there is no trivial way to extract this afterwards: first you would have to make the instance of the Loader() persist and then make sure that the  normal compose_document() method is not called (which among other things does self.anchors = {}, to be clean for the next document (in a single stream)).

To further complicate things if you would have warehouse.yaml:

warehouse:
  obj1: &obj1
    key1: 1
    key2: 2

and specific.yaml:

warehouse: !include warehouse.yaml
specific:
  spec1:
    <<: *obj1
  spec2:
    <<: *obj1
    key1: 10

you would never get this to work with your snippet, even if you could preserve, extract and pass on the anchor information because the composer handling specific.yaml will much earlier encountering a non-defined alias than the tag !include gets used for construction (and filling anchors).

What you can do to circumvent this problem is to include specific.yaml

specific:
  spec1:
    <<: *obj1
  spec2:
    <<: *obj1
    key1: 10

from warehouse.yaml:

warehouse:
  obj1: &obj1
    key1: 1
    key2: 2
specific: !include specific.yaml

, or include both in a third file. Please note that the key specific is in both files.

With those two files run:

import sys
from ruamel import yaml

def my_compose_document(self):
    self.get_event()
    node = self.compose_node(None, None)
    self.get_event()
    # self.anchors = {}    # <<<< commented out
    return node

yaml.SafeLoader.compose_document = my_compose_document

# adapted from http://code.activestate.com/recipes/577613-yaml-include-support/
def yaml_include(loader, node):
    with open(node.value) as inputfile:
        return list(my_safe_load(inputfile, master=loader).values())[0]
#              leave out the [0] if your include file drops the key ^^^

yaml.add_constructor("!include", yaml_include, Loader=yaml.SafeLoader)

def my_safe_load(stream, Loader=yaml.SafeLoader, master=None):
    loader = Loader(stream)
    if master is not None:
        loader.anchors = master.anchors
    try:
        return loader.get_single_data()
    finally:
        loader.dispose()

with open('warehouse.yaml') as fp:
    data = my_safe_load(fp)
yaml.safe_dump(data, sys.stdout, default_flow_style=False)

which gives:

specific:
  spec1:
    key1: 1
    key2: 2
  spec2:
    key1: 10
    key2: 2
warehouse:
  obj1:
    key1: 1
    key2: 2

If your specific.yaml would not have the top-level key specific:

spec1:
  <<: *obj1
spec2:
  <<: *obj1
  key1: 10

then replace the last line of yaml_include() with:

return my_safe_load(inputfile, master=loader)

The above was done with ruamel.yaml (disclaimer: I am the author of that package) and tested on Python 2.7 and 3.6. By changing the import it will work with PyYAML as well.

With the new ruamel.yaml API the above can be much simplified, because the loader handed to the yaml_include() constructor knows about the YAML instance, but of course you still need an adapted compose_document that doesn't destroy anchors. Assuming the specific.yaml without top-level key specific, the following gives the same output as before.

import sys
from ruamel.std.pathlib import Path
from ruamel.yaml import YAML, version_info

yaml = YAML(typ='safe', pure=True)
yaml.default_flow_style = False

def my_compose_document(self):
    self.parser.get_event()
    node = self.compose_node(None, None)
    self.parser.get_event()
    # self.anchors = {}    # <<<< commented out
    return node

yaml.Composer.compose_document = my_compose_document

# adapted from http://code.activestate.com/recipes/577613-yaml-include-support/
def yaml_include(loader, node):
    y = loader.loader
    yaml = YAML(typ=y.typ, pure=y.pure)  # same values as including YAML
    yaml.composer.anchors = loader.composer.anchors
    return yaml.load(Path(node.value))

yaml.Constructor.add_constructor("!include", yaml_include)

data = yaml.load(Path('warehouse.yaml'))
yaml.dump(data, sys.stdout)


问:
How to access application URL hosted in docker container?
I hosted our application inside a docker container. When I run docker ps command, it gave info like below.

```<code>CONTAINER ID        IMAGE                      COMMAND             CREATED             STATUS              PORTS                                                                                NAMES
6405daf98246        rdarukumalli/testapp-master   "/bin/bash"         4 hours ago         Up 4 hours          0.0.0.0:32797->443/tcp, 0.0.0.0:32796->8000/tcp, 0.0.0.0:32795->8080/tcp, 0.0.0.0:32794->8443/tcp, 0.0.0.0:32793->9997/tcp   insane_poincare
</code>```

I am trying to access this application from my machine with the following URLs. Nothing worked so far.

```<code>0.0.0.0:32795/testapp/login.jsp
0.0.0.0:8080/testapp/login.jsp
localhost:8080/testapp/login.jsp
localhost:32795/testapp/login.jsp
</code>```

However, if i give the command "curl http://localhost:8080/testapp/login.jsp" inside bash of docker container,
I can login page html is coming.

Can some one help me in understanding these URL mappings and what URL i need to use to access this login page outside docker container?

答:
Try curl http://localhost:32795/testapp/login.jsp.

Your docker ps shows that container's port 8080 is bound to external port 32795 : [...] 0.0.0.0:32795->8080/tcp [...]

Body:
I hosted our application inside a docker container. When I run docker ps command, it gave info like below.

CONTAINER ID        IMAGE                      COMMAND             CREATED             STATUS              PORTS                                                                                NAMES
6405daf98246        rdarukumalli/testapp-master   "/bin/bash"         4 hours ago         Up 4 hours          0.0.0.0:32797->443/tcp, 0.0.0.0:32796->8000/tcp, 0.0.0.0:32795->8080/tcp, 0.0.0.0:32794->8443/tcp, 0.0.0.0:32793->9997/tcp   insane_poincare

I am trying to access this application from my machine with the following URLs. Nothing worked so far.

0.0.0.0:32795/testapp/login.jsp
0.0.0.0:8080/testapp/login.jsp
localhost:8080/testapp/login.jsp
localhost:32795/testapp/login.jsp

However, if i give the command "curl http://localhost:8080/testapp/login.jsp" inside bash of docker container,
I can login page html is coming.

Can some one help me in understanding these URL mappings and what URL i need to use to access this login page outside docker container?