问:
While loop stuck at random points on the code
i need help, i had my friend to help me debug this code, and we found that the code stops at random points on the code, sometimes on first loop, sometimes on last loop and so on.
the code is just to make a 9x9 sudoku board with all the rules applied. when i tested each block separately it worked and printed a well done sudoku board, but the problem here is that is gets stuck somehow.
help will be appreciated.</p>

```<code>int[,] helpblock = new int[10, 10];
int[,] helplines = new int[10, 10];
int[,] helpcols = new int[10, 10];
for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
        helplines[i, j] = 0;
        helpcols[i, j] = 0;
        helpblock[i, j] = 0;
    }
}

Random rnf = new Random();
int help1;
for (int i = 0; i < 9; i++) {
    for (int j = 0; j < 9; j++) {
        help1 = rnf.Next(1, 10);
        if (i == 0 || i == 1 || i == 2) {
            if (j == 0 || j == 1 || j == 2) {
                if (helplines[i, help1] != 0 || helpblock[0, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[0, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }
                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[0, help1]++;
            } else if (j == 3 || j == 4 || j == 5) {
                if (helplines[i, help1] != 0 || helpblock[1, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[1, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }
                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[1, help1]++;
            } else if (j == 6 || j == 7 || j == 8) {
                if (helplines[i, help1] != 0 || helpblock[2, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[2, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }
                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[2, help1]++;
            }
        } else if (i == 3 || i == 4 || i == 5) {
            if (j == 0 || j == 1 || j == 2) {
                if (helplines[i, help1] != 0 || helpblock[3, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[3, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }
                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[3, help1]++;
            } else if (j == 3 || j == 4 || j == 5) {
                if (helplines[i, help1] != 0 || helpblock[4, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[4, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }

                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[4, help1]++;
            } else if (j == 6 || j == 7 || j == 8) {
                if (helplines[i, help1] != 0 || helpblock[5, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[5, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }

                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[5, help1]++;

            }
        } else if (i == 6 || i == 7 || i == 8) {
            if (j == 0 || j == 1 || j == 2) {
                if (helplines[i, help1] != 0 || helpblock[6, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[6, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }

                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[6, help1]++;
            } else if (j == 3 || j == 4 || j == 5) {
                if (helplines[i, help1] != 0 || helpblock[7, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[7, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }

                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[7, help1]++;
            } else if (j == 6 || j == 7 || j == 8) {
                if (helplines[i, help1] != 0 || helpblock[8, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[8, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }

                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[8, help1]++;
            }
        }
    }
}

PrintSudoku(map);
</code>```

答:
This is not really an answer, but hopefully it will help you debug the program. Inside your for loops you have a whole bunch of if statements that look something like:

```<code>if (i == 0 || i == 1 || i == 2) {
    if (j == 0 || j == 1 || j == 2) {
</code>```

It looks like you are using this logic to determine which block you're in, because that's the one array that you are using a hard-coded value for the first index.

Instead of doing it this way, consider calculating the block using a formula based on the current row and column value.

Your grid currently looks something like this:

```<code>  | 0 1 2 | 3 4 5 | 6 7 8 |
--+-------+-------+--------
0 |       |       |       |
1 |  [0]  |  [1]  |  [2]  |
2 |       |       |       |
--+-------+-------+--------
3 |       |       |       |
4 |  [3]  |  [4]  |  [5]  |
5 |       |       |       |
--+-------+-------+--------
6 |       |       |       |
7 |  [6]  |  [7]  |  [8]  |
8 |       |       |       |
---------------------------
</code>```

What you might notice is that if you take the row number and do an integer division by 3, you will get the Block row number (0, 1, or 2). Multiplying this number by 3 gives you the first block in each row (0, 3, and 6). Now, if we take the current column and integer-divide that by 3, we will get the current block column (0, 1, or 2). Adding the "block row" to the "block column" then will give us the block index:

```<code>int block = ((row / 3) * 3) + (column / 3);
</code>```

(Note that it looks like you could simplify this since row is being divided by three and then multiplied by three, but remember that integer division rounds down, so 2 / 3 == 0, not .6667)

By calculating the block this way, you can drastically reduce the number of lines you have to walk through.

Also, using some more meaningful variable names will help with the readability.

I simplified your code to something that I believe does the exact same thing. Maybe it will help your analysis:

```<code>int[,] blocks = new int[10, 10];
int[,] rows = new int[10, 10];
int[,] columns = new int[10, 10];

for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 10; j++)
    {
        rows[i, j] = 0;
        columns[i, j] = 0;
        blocks[i, j] = 0;
    }
}

Random rnd = new Random();
int randomNumber;

for (int row = 0; row < 9; row++)
{
    for (int column = 0; column < 9; column++)
    {
        int block = ((row / 3) * 3) + (column / 3);
        randomNumber = rnd.Next(1, 10);

        while (rows[row, randomNumber] != 0 ||
            blocks[block, randomNumber] != 0 ||
            columns[column, randomNumber] != 0)
        {
            System.Threading.Thread.Sleep(1);
            randomNumber = rnd.Next(1, 10);
        }

        map[row, column] = randomNumber;
        rows[row, randomNumber]++;
        columns[column, randomNumber]++;
        blocks[block, randomNumber]++;
    }
}
</code>```

After playing with this, of course, I got interested in the problem. Below is what I came up with to solve it, which is pretty much a brute-force method:

Start with numbers 1-9 available for each row, column, and block

From the list of available numbers for a cell, assign one of them at random, one cell at a time

Remove that number from the available numbers for that row, column, and block

If we run into the case where there is no valid number available for the cell, reset everything and try again.

Notice there is potential that this will run and never finish, but in my testing it usually finds a solution in less than 400 tries (which is relatively fast from a user's point of view).

What I did differently was, instead of using arrays to store the row/column/block information, I decided to use a Dictionary<int, List<int>>, which stores the row/column/block index as the key, and the value for each key is a List of available numbers for that index.

Then in our loop, I just put the intersection of the available numbers left for the current row, column, and block into a List. Then I pick a random index in that list and assign that value to the cell (and remove it from the available items in that row, column, and block).

I also added some logging to find out how many times it failed before finding a solution.

Here's the code, which also prints the solution at the end:

```<code>static void Main()
{
    int[,] map = new int[9, 9];
    var blocks = new Dictionary<int, List<int>>();
    var rows = new Dictionary<int, List<int>>();
    var columns = new Dictionary<int, List<int>>();

    // initialize lists of available numbers
    for (int i = 0; i < 9; i++)
    {
        blocks.Add(i, new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
        rows.Add(i, new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
        columns.Add(i, new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
    }

    Random rnd = new Random();
    int failCount = 0;

    // For each row
    for (int row = 0; row < 9; row++)
    {
        // For each column in this row
        for (int column = 0; column < 9; column++)
        {
            // Calculate block based on current row and column
            int block = ((row / 3) * 3) + (column / 3);

            // Get set of available numbers for this cell by getting the intersection
            // of available numbers for the row, column, and block
            var availableItems =
                rows[row].Intersect(
                    columns[column].Intersect(
                        blocks[block])).ToList();

            // If we reach a point where there are no availableItems, then this is
            // not a valid Sudoku pattern. Reset everything and try again
            if (availableItems.Count == 0)
            {
                failCount++;
                Console.WriteLine($"Failed {failCount} times. Trying again...");

                // Reset to the first cell
                row = 0;
                column = 0;
                block = 0;

                // Initialize data
                for (int i = 0; i < 9; i++)
                {
                    blocks[i] = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                    rows[i] = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                    columns[i] = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                }
                availableItems = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            }

            // Grab a number from the available numbers by choosing a random index
            var randomNumber = availableItems[rnd.Next(0, availableItems.Count)];

            // Update our map with this item
            map[row, column] = randomNumber;

            // Remove this item from our lists
            rows[row].Remove(randomNumber);
            columns[column].Remove(randomNumber);
            blocks[block].Remove(randomNumber);
        }
    }

    // Print our Sudoku map:
    Console.WriteLine(new string('-', 25));

    for(int i = 0; i < 9; i++)
    {
        Console.Write("|");

        for (int j = 0; j < 9; j++)
        {
            Console.Write($" {map[i, j]}");
            if ((j + 1) % 3 == 0) Console.Write(" |");
        }

        Console.WriteLine();

        if ((i + 1) % 3 == 0) Console.WriteLine(new string('-', 25));
    }

    Console.Write("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}
</code>```

Ouput:

Body:
i need help, i had my friend to help me debug this code, and we found that the code stops at random points on the code, sometimes on first loop, sometimes on last loop and so on.
the code is just to make a 9x9 sudoku board with all the rules applied. when i tested each block separately it worked and printed a well done sudoku board, but the problem here is that is gets stuck somehow.
help will be appreciated.

int[,] helpblock = new int[10, 10];
int[,] helplines = new int[10, 10];
int[,] helpcols = new int[10, 10];
for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
        helplines[i, j] = 0;
        helpcols[i, j] = 0;
        helpblock[i, j] = 0;
    }
}

Random rnf = new Random();
int help1;
for (int i = 0; i < 9; i++) {
    for (int j = 0; j < 9; j++) {
        help1 = rnf.Next(1, 10);
        if (i == 0 || i == 1 || i == 2) {
            if (j == 0 || j == 1 || j == 2) {
                if (helplines[i, help1] != 0 || helpblock[0, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[0, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }
                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[0, help1]++;
            } else if (j == 3 || j == 4 || j == 5) {
                if (helplines[i, help1] != 0 || helpblock[1, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[1, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }
                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[1, help1]++;
            } else if (j == 6 || j == 7 || j == 8) {
                if (helplines[i, help1] != 0 || helpblock[2, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[2, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }
                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[2, help1]++;
            }
        } else if (i == 3 || i == 4 || i == 5) {
            if (j == 0 || j == 1 || j == 2) {
                if (helplines[i, help1] != 0 || helpblock[3, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[3, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }
                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[3, help1]++;
            } else if (j == 3 || j == 4 || j == 5) {
                if (helplines[i, help1] != 0 || helpblock[4, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[4, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }

                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[4, help1]++;
            } else if (j == 6 || j == 7 || j == 8) {
                if (helplines[i, help1] != 0 || helpblock[5, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[5, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }

                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[5, help1]++;

            }
        } else if (i == 6 || i == 7 || i == 8) {
            if (j == 0 || j == 1 || j == 2) {
                if (helplines[i, help1] != 0 || helpblock[6, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[6, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }

                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[6, help1]++;
            } else if (j == 3 || j == 4 || j == 5) {
                if (helplines[i, help1] != 0 || helpblock[7, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[7, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }

                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[7, help1]++;
            } else if (j == 6 || j == 7 || j == 8) {
                if (helplines[i, help1] != 0 || helpblock[8, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[8, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }

                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[8, help1]++;
            }
        }
    }
}

PrintSudoku(map);

Body:
This is not really an answer, but hopefully it will help you debug the program. Inside your for loops you have a whole bunch of if statements that look something like:

if (i == 0 || i == 1 || i == 2) {
    if (j == 0 || j == 1 || j == 2) {

It looks like you are using this logic to determine which block you're in, because that's the one array that you are using a hard-coded value for the first index.

Instead of doing it this way, consider calculating the block using a formula based on the current row and column value.

Your grid currently looks something like this:

  | 0 1 2 | 3 4 5 | 6 7 8 |
--+-------+-------+--------
0 |       |       |       |
1 |  [0]  |  [1]  |  [2]  |
2 |       |       |       |
--+-------+-------+--------
3 |       |       |       |
4 |  [3]  |  [4]  |  [5]  |
5 |       |       |       |
--+-------+-------+--------
6 |       |       |       |
7 |  [6]  |  [7]  |  [8]  |
8 |       |       |       |
---------------------------

What you might notice is that if you take the row number and do an integer division by 3, you will get the Block row number (0, 1, or 2). Multiplying this number by 3 gives you the first block in each row (0, 3, and 6). Now, if we take the current column and integer-divide that by 3, we will get the current block column (0, 1, or 2). Adding the "block row" to the "block column" then will give us the block index:

int block = ((row / 3) * 3) + (column / 3);

(Note that it looks like you could simplify this since row is being divided by three and then multiplied by three, but remember that integer division rounds down, so 2 / 3 == 0, not .6667)

By calculating the block this way, you can drastically reduce the number of lines you have to walk through.

Also, using some more meaningful variable names will help with the readability.

I simplified your code to something that I believe does the exact same thing. Maybe it will help your analysis:

int[,] blocks = new int[10, 10];
int[,] rows = new int[10, 10];
int[,] columns = new int[10, 10];

for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 10; j++)
    {
        rows[i, j] = 0;
        columns[i, j] = 0;
        blocks[i, j] = 0;
    }
}

Random rnd = new Random();
int randomNumber;

for (int row = 0; row < 9; row++)
{
    for (int column = 0; column < 9; column++)
    {
        int block = ((row / 3) * 3) + (column / 3);
        randomNumber = rnd.Next(1, 10);

        while (rows[row, randomNumber] != 0 ||
            blocks[block, randomNumber] != 0 ||
            columns[column, randomNumber] != 0)
        {
            System.Threading.Thread.Sleep(1);
            randomNumber = rnd.Next(1, 10);
        }

        map[row, column] = randomNumber;
        rows[row, randomNumber]++;
        columns[column, randomNumber]++;
        blocks[block, randomNumber]++;
    }
}

After playing with this, of course, I got interested in the problem. Below is what I came up with to solve it, which is pretty much a brute-force method:

Start with numbers 1-9 available for each row, column, and block

From the list of available numbers for a cell, assign one of them at random, one cell at a time

Remove that number from the available numbers for that row, column, and block

If we run into the case where there is no valid number available for the cell, reset everything and try again.

Notice there is potential that this will run and never finish, but in my testing it usually finds a solution in less than 400 tries (which is relatively fast from a user's point of view).

What I did differently was, instead of using arrays to store the row/column/block information, I decided to use a Dictionary<int, List<int>>, which stores the row/column/block index as the key, and the value for each key is a List of available numbers for that index.

Then in our loop, I just put the intersection of the available numbers left for the current row, column, and block into a List. Then I pick a random index in that list and assign that value to the cell (and remove it from the available items in that row, column, and block).

I also added some logging to find out how many times it failed before finding a solution.

Here's the code, which also prints the solution at the end:

static void Main()
{
    int[,] map = new int[9, 9];
    var blocks = new Dictionary<int, List<int>>();
    var rows = new Dictionary<int, List<int>>();
    var columns = new Dictionary<int, List<int>>();

    // initialize lists of available numbers
    for (int i = 0; i < 9; i++)
    {
        blocks.Add(i, new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
        rows.Add(i, new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
        columns.Add(i, new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
    }

    Random rnd = new Random();
    int failCount = 0;

    // For each row
    for (int row = 0; row < 9; row++)
    {
        // For each column in this row
        for (int column = 0; column < 9; column++)
        {
            // Calculate block based on current row and column
            int block = ((row / 3) * 3) + (column / 3);

            // Get set of available numbers for this cell by getting the intersection
            // of available numbers for the row, column, and block
            var availableItems =
                rows[row].Intersect(
                    columns[column].Intersect(
                        blocks[block])).ToList();

            // If we reach a point where there are no availableItems, then this is
            // not a valid Sudoku pattern. Reset everything and try again
            if (availableItems.Count == 0)
            {
                failCount++;
                Console.WriteLine($"Failed {failCount} times. Trying again...");

                // Reset to the first cell
                row = 0;
                column = 0;
                block = 0;

                // Initialize data
                for (int i = 0; i < 9; i++)
                {
                    blocks[i] = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                    rows[i] = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                    columns[i] = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                }
                availableItems = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            }

            // Grab a number from the available numbers by choosing a random index
            var randomNumber = availableItems[rnd.Next(0, availableItems.Count)];

            // Update our map with this item
            map[row, column] = randomNumber;

            // Remove this item from our lists
            rows[row].Remove(randomNumber);
            columns[column].Remove(randomNumber);
            blocks[block].Remove(randomNumber);
        }
    }

    // Print our Sudoku map:
    Console.WriteLine(new string('-', 25));

    for(int i = 0; i < 9; i++)
    {
        Console.Write("|");

        for (int j = 0; j < 9; j++)
        {
            Console.Write($" {map[i, j]}");
            if ((j + 1) % 3 == 0) Console.Write(" |");
        }

        Console.WriteLine();

        if ((i + 1) % 3 == 0) Console.WriteLine(new string('-', 25));
    }

    Console.Write("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}

Ouput:


来源: stackexchange

问:
Downloading table from website into R
I've been trying to download this table into R without success.

The code I'm using is this one

```<code>library(XML)
web_banrep <- "http://obieebr.banrep.gov.co/analytics/saw.dll?Go&Action=prompt&lang=es&NQUser=publico&NQPassword=publico&path=%2Fshared%2fSeries%20Estad%C3%ADsticas%2F1.%20Empleo%20y%20desempleo%2F1.1%20Serie%20hist%C3%B3rica%2F1.1.1.EMP_Total%20nacional&Options=rdf"
desemp     <-  readHTMLTable(web_banrep, header=T, which=1,stringsAsFactors=F)
</code>```

I'd appreciate any help.

答:
If you just want that one table, a very handy tool for this kind of JS-reliant websites is:

Chrome Pipe (Plugin, Github)

With it you can get data from your currently rendered dom as you see it in your chrome-browser. I normally use

```<code>selectorgadget | text | pbcopy
</code>```

which copies the Data to your clipboard

An alternativ is:

```<code>selectorgadget | text | gist
</code>```

which gives you the link to a gist with your data. Here is yours:

https://gist.github.com/anonymous/3772146382b500195a22ba2b10962ffa

From there click on raw to get the url of your data.
You can then parse it using R as follows:

```<code>gist_raw <- "https://gist.githubusercontent.com/anonymous/3772146382b500195a22ba2b10962ffa/raw/218b07739f6c146ec4ff15ec78657adc26455c95/data.txt"
raw <- read.table(gist_raw)

col <- seq(1, nrow(raw), by = 3)
data.frame(col1 = raw[col,], col2 = raw[col + 1,], col3 = raw[col + 2,])
</code>```

This gives you:

```<code>     col1  col2  col3
1 2017-02 57,25 10,50
2 2017-01 56,34 11,73
3 2016-12 58,98  8,74
4 2016-11 60,35  7,51
5 2016-10 60,77  8,29
6 2016-09 58,71  8,51
...
</code>```

The parsing of the columns i leave to you.

ContentLicense: CC BY-SA 3.0

Title: Downloading table from website into R

Body:
I've been trying to download this table into R without success.

The code I'm using is this one

library(XML)
web_banrep <- "http://obieebr.banrep.gov.co/analytics/saw.dll?Go&Action=prompt&lang=es&NQUser=publico&NQPassword=publico&path=%2Fshared%2fSeries%20Estad%C3%ADsticas%2F1.%20Empleo%20y%20desempleo%2F1.1%20Serie%20hist%C3%B3rica%2F1.1.1.EMP_Total%20nacional&Options=rdf"
desemp     <-  readHTMLTable(web_banrep, header=T, which=1,stringsAsFactors=F)

I'd appreciate any help.

Body:
If you just want that one table, a very handy tool for this kind of JS-reliant websites is:

Chrome Pipe (Plugin, Github)

With it you can get data from your currently rendered dom as you see it in your chrome-browser. I normally use

selectorgadget | text | pbcopy

which copies the Data to your clipboard

An alternativ is:

selectorgadget | text | gist

which gives you the link to a gist with your data. Here is yours:

https://gist.github.com/anonymous/3772146382b500195a22ba2b10962ffa

From there click on raw to get the url of your data.
You can then parse it using R as follows:

gist_raw <- "https://gist.githubusercontent.com/anonymous/3772146382b500195a22ba2b10962ffa/raw/218b07739f6c146ec4ff15ec78657adc26455c95/data.txt"
raw <- read.table(gist_raw)

col <- seq(1, nrow(raw), by = 3)
data.frame(col1 = raw[col,], col2 = raw[col + 1,], col3 = raw[col + 2,])

This gives you:

     col1  col2  col3
1 2017-02 57,25 10,50
2 2017-01 56,34 11,73
3 2016-12 58,98  8,74
4 2016-11 60,35  7,51
5 2016-10 60,77  8,29
6 2016-09 58,71  8,51
...

The parsing of the columns i leave to you.


问:
Get Alfresco NodeRef by path
I want to get the NodeRef of a document (or space) stored in Alfresco.

My code is in Java, running within Alfresco (for instance in an AMP).

How to do?

答: Path queries and not the fastest, though, especially if you're on Lucene. You should think of an alternative ways to find what you're looking for.</p>

ContentLicense: CC BY-SA 4.0

Title: Get Alfresco NodeRef by path


问:
MySQL autogenerated id vs custom autogenerated id
I have to say that this is my first question here. Currently I have a table ´journals´ in a MySQL server with an ID autogenerate with autoincrement:

```<code>´id´ int(10) NOT NULL AUTO_INCREMENT,
-- more columns
PRIMARY KEY (´id´)
</code>```

I'm thinking about modify this ID for a custom one because the client would like to generate the id in the following way:

ABC0000001, where ´ABC´ is the acronym of a department and ´0000001´ would be autoincrement. We already have different acronyms for different deparments.

I can get this ID with a trigger (a similar example: How to make MySQL table primary key auto increment with some prefix) but I have doubts about perfomance and efficiency because I could get the same "result" with the initial solution and another column to store the department´s acronym. In the backend I would create a method to unified both columns before returning the result to the frontend and another method to split the search into the table.

Does anybody have faced a similar situation that could guide me on this issue in terms of perfomance or efficiency? Thanks in advance.

答:
Creating custom-generated ids is fun, but masochistic.  What is your subconscious goal?

AUTO_INCREMENT is well optimized; anything else is somewhere between slightly and seriously less efficient.  For example, a Trigger, might double the cost of an INSERT, but if INSERTs are not a performance problem, then "so what".

Semi-related:  UUIDs are terribly inefficient for huge tables -- due to their randomness.

Body:
I have to say that this is my first question here. Currently I have a table ´journals´ in a MySQL server with an ID autogenerate with autoincrement:

´id´ int(10) NOT NULL AUTO_INCREMENT,
-- more columns
PRIMARY KEY (´id´)

I'm thinking about modify this ID for a custom one because the client would like to generate the id in the following way:

ABC0000001, where ´ABC´ is the acronym of a department and ´0000001´ would be autoincrement. We already have different acronyms for different deparments.

I can get this ID with a trigger (a similar example: How to make MySQL table primary key auto increment with some prefix) but I have doubts about perfomance and efficiency because I could get the same "result" with the initial solution and another column to store the department´s acronym. In the backend I would create a method to unified both columns before returning the result to the frontend and another method to split the search into the table.

Does anybody have faced a similar situation that could guide me on this issue in terms of perfomance or efficiency? Thanks in advance.


问:
Swift: Convert string to hex color code
I have generated user Ids (with a format like ""XzSYoKJaqKYREkdB2dgwt0fLOPP2"") from a database that I would like to use to create an UIColor.

I found several solutions on how to crate an UIColor with a color hex code, but I don't quite know how I would generate a color hex code (#ffffff) from a string like the one above. Any help would be appreciated, thanks.

答:
There are far too many user ids to get a unique color for every possible user id. Your best option would be to find a way to narrow down each user id to one of the possible available colors and accept the fact that two users may have the same color.

One possible solution is would be to get the hashValue of the user id string and then reduce that Int down to one of the possible 16,777,216 colors.

```<code>let userId = "XzSYoKJaqKYREkdB2dgwt0fLOPP2" // or whatever the id is
let hash = abs(userId.hashValue)
let colorNum = hash % (256*256*256)
</code>```

At this point colorNum is the range 0 - 0xFFFFFF

You can now create a color from colorNum.

```<code>let red = colorNum >> 16
let green = (colorNum & 0x00FF00) >> 8
let blue = (colorNum & 0x0000FF)
let userColor = UIColor(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: 1.0)
</code>```

You will want to store this color in the user's profile since the hashValue isn't guaranteed to be the same each time your app runs.

Title: Swift: Convert string to hex color code

Body:
There are far too many user ids to get a unique color for every possible user id. Your best option would be to find a way to narrow down each user id to one of the possible available colors and accept the fact that two users may have the same color.

One possible solution is would be to get the hashValue of the user id string and then reduce that Int down to one of the possible 16,777,216 colors.

let userId = "XzSYoKJaqKYREkdB2dgwt0fLOPP2" // or whatever the id is
let hash = abs(userId.hashValue)
let colorNum = hash % (256*256*256)

At this point colorNum is the range 0 - 0xFFFFFF

You can now create a color from colorNum.

let red = colorNum >> 16
let green = (colorNum & 0x00FF00) >> 8
let blue = (colorNum & 0x0000FF)
let userColor = UIColor(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: 1.0)

You will want to store this color in the user's profile since the hashValue isn't guaranteed to be the same each time your app runs.


问:
Advanced Method Call Hierarchy generation for Java?
I have some large corporate Spring project unknown for me and I need to perform this kind of task above it:

"I have method A and method B. During the execution of method A, can
  method B be called?"

Well I found there is function Method Call Hierarchy in IntelliJ Idea. I can perform this function on method B and generate call hierarchy, where I can perform serarch for method A. Unfortunatelly, IntelliJ freeze during computing of this hierarchy becouse its so large and crashed after 5 hours of working.

I need Method Call Hierarchy utility with better performance than IntelliJ Idea have but I failed to find it. Can you help me?

答: Consider using AOP functionality for method interception and execution path modification. Spring AOP support may be enough for this. this and this questions may help</p>


问:
Using CAMediaTimingFunction to calculate value at time (t)
In Cocoa/Touch, CAMediaTimingFunction represents four control points that specify a cubic bezier curve of a timing function. For an application I am writing I would like to be able to extract the result of said bezier curve at an arbitrary time t (0 -> 1). What is confusing me is that when I look up how to do this, the result is supposed to be a point as well, not a scalar:

However, Apple's implementation results in a scalar value (you can see on this graph they plot x(t) vs t: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Animation_Types_Timing/Articles/Timing.html#//apple_ref/doc/uid/TP40006670-SW1 )

So does Apple simply ignore the y coordinate of the result and only deal with the x? This seems strange because then you wouldn't need to pass in control points but rather control scalars as the y's wouldn't influence the result at all.

答:
It's unfortunate, but Core Animation doesn't expose its internal computational model for its animation timing. However, what has worked really well for me is to use Core Animation to do the work!

Create a CALayer to serve as an evaluator

Set its frame to ((0.0, 0.0), (1.0, 1.0))

Set isHidden to true

Set speed to 0.0

Add this layer to some container layer

When you want to evaluate any CAMediaTimingFunction, create a reference animation:

```<code>let basicAnimation = CABasicAnimation(keyPath: "bounds.origin.x")
basicAnimation.duration = 1.0
basicAnimation.timingFunction = timingFunction
basicAnimation.fromValue = 0.0
basicAnimation.toValue = containerLayer.bounds.width

referenceLayer.add(basicAnimation, forKey: "evaluatorAnimation")
</code>```

Set the reference layer's timeOffset to whatever normalized input value (i.e., between 0.0 and 1.0) you want to evaluate:

```<code>referenceLayer.timeOffset = 0.3    // 30% into the animation
</code>```

Ask for the reference layer's presentation layer, and get its current bounds origin x value:

```<code>if let presentationLayer = referenceLayer.presentation() as CALayer? {
    let evaluatedValue = presentationLayer.bounds.origin.x / containerLayer.bounds.width
}
</code>```

Basically, you're using Core Animation to run an animation for an invisible layer. But the layer's speed is 0.0, so it won't progress the animation at all. Using timeOffset, we can manually adjust the current position of the animation then get its presentation layer's x position. This represents the current perceived value of that property as driven by the animation.

It's a little unconventional, but there's nothing hacky about it. It's as faithful a representation of the output value of a CAMediaTimingFunction as you can get because Core Animation is actually using it.

The only thing to be aware of is that presentation layers are close approximations of the values presented on screen. Core Animation makes no guarantees as to their accuracy, but in all my years of using Core Animation, I've never seen it be inaccurate. Still, if your application requires absolute accuracy, it's possible this technique might not be the best.

Body:
It's unfortunate, but Core Animation doesn't expose its internal computational model for its animation timing. However, what has worked really well for me is to use Core Animation to do the work!

Create a CALayer to serve as an evaluator

Set its frame to ((0.0, 0.0), (1.0, 1.0))

Set isHidden to true

Set speed to 0.0

Add this layer to some container layer

When you want to evaluate any CAMediaTimingFunction, create a reference animation:

let basicAnimation = CABasicAnimation(keyPath: "bounds.origin.x")
basicAnimation.duration = 1.0
basicAnimation.timingFunction = timingFunction
basicAnimation.fromValue = 0.0
basicAnimation.toValue = containerLayer.bounds.width

referenceLayer.add(basicAnimation, forKey: "evaluatorAnimation")

Set the reference layer's timeOffset to whatever normalized input value (i.e., between 0.0 and 1.0) you want to evaluate:

referenceLayer.timeOffset = 0.3    // 30% into the animation

Ask for the reference layer's presentation layer, and get its current bounds origin x value:

if let presentationLayer = referenceLayer.presentation() as CALayer? {
    let evaluatedValue = presentationLayer.bounds.origin.x / containerLayer.bounds.width
}

Basically, you're using Core Animation to run an animation for an invisible layer. But the layer's speed is 0.0, so it won't progress the animation at all. Using timeOffset, we can manually adjust the current position of the animation then get its presentation layer's x position. This represents the current perceived value of that property as driven by the animation.

It's a little unconventional, but there's nothing hacky about it. It's as faithful a representation of the output value of a CAMediaTimingFunction as you can get because Core Animation is actually using it.

The only thing to be aware of is that presentation layers are close approximations of the values presented on screen. Core Animation makes no guarantees as to their accuracy, but in all my years of using Core Animation, I've never seen it be inaccurate. Still, if your application requires absolute accuracy, it's possible this technique might not be the best.


问:
How to check if C++ abstract method is defined at runtime
How to check if C++ abstract method is defined at runtime

```<code>class ABase{
public:
 virtual void do1() = 0;
};

class BBase: public ABase{
public:
 virtual void do1(){}
};

class CBase: public ABase{
public:
};

ABase * base = rand() % 2 ? new BBase() : new CBase();
if(&(base->do1) != 0)
  base->do1();
</code>```

This gives error.

Thanks,
Max

答:
CBase is abstract because it does not override ABase::do1(). Therefore, you cannot instantiate it. Or rather, that's what would happen if you had declared do1() as virtual. But for now, it just won't compile.

Would be nice to know why you want to do this, though.

ContentLicense: CC BY-SA 2.5

Body:
How to check if C++ abstract method is defined at runtime

class ABase{
public:
 virtual void do1() = 0;
};

class BBase: public ABase{
public:
 virtual void do1(){}
};

class CBase: public ABase{
public:
};

ABase * base = rand() % 2 ? new BBase() : new CBase();
if(&(base->do1) != 0)
  base->do1();

This gives error.

Thanks,
Max


问:
Foreign key name for `many_to_many` association in Ecto
Here is a question for many_to_many association. The error I’m getting is

```<code>INSERT INTO "qbinders" ("title","typecode","inserted_at","updated_at","id") VALUES ($1,$2,$3,$4,$5) ["Math", "Jim1000", {{2017, 4, 1}, {15, 4, 47, 827009}}, {{2017, 4, 1}, {15, 4, 47, 843348}}, <<68, 1
49, 156, 219, 153, 214, 65, 63, 179, 141, 252, 147, 221, 247, 41, 143>>]
[debug] QUERY OK db=0.9ms
commit []
** (Postgrex.Error) ERROR 42703 (undefined_column): column q2.qbinders_id does not exist
</code>```

in running

```<code>qbinder_map = %{ title: "Math", typecode: "Jim1000"}
changeset = Qbinders.changeset(%Qbinders{}, qbinder_map)
qbinder = Repo.insert!(changeset) |> Repo.preload(:qbooks)

qbook_list =
  %Qbooks{ title: "Algebra1"}
qbook = Repo.insert!(qbook_list) |> Repo.preload(:qbinders)

changeset = Ecto.Changeset.change(qbinder)
            |> Ecto.Changeset.put_assoc(:qbooks, [qbook_list])
Repo.update!(changeset)
</code>```

In postgres, the join table looks like

```<code>CREATE TABLE qbook2qbinder
(
  qbook_id uuid,
  qbinder_id uuid,
  qbook_order integer,
  inserted_at timestamp without time zone NOT NULL,
  updated_at timestamp without time zone NOT NULL,
  CONSTRAINT qbook2qbinder_qbinder_id_fkey FOREIGN KEY (qbinder_id)
      REFERENCES qbinders (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT qbook2qbinder_qbook_id_fkey FOREIGN KEY (qbook_id)
      REFERENCES qbooks (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)
</code>```

And the model is

```<code>defmodule Project.Qbinders do
  use Project.Web, :model

  @primary_key {:id, :binary_id, autogenerate: true}

  schema "qbinders" do

        field :title, :string
        field :reward, :string

        many_to_many :qbooks, Project.Qbooks, join_through: "qbook2qbinder"
    timestamps
  end
</code>```

Why does Ecto look for qbinders_id instead of qbinder_id? How do I set it to qbinder_id?

答:
This is easily customisable by options argument of Ecto.Schema.many_to_many/3.

The column names can be configured with option join_keys, and should be used like:

```<code>many_to_many :qbooks, Project.Qbooks, join_through: "qbook2qbinder",
                                      join_keys: [{qbook_id: :id, qbinder_id: :id}]
</code>```

Body:
Here is a question for many_to_many association. The error I’m getting is

INSERT INTO "qbinders" ("title","typecode","inserted_at","updated_at","id") VALUES ($1,$2,$3,$4,$5) ["Math", "Jim1000", {{2017, 4, 1}, {15, 4, 47, 827009}}, {{2017, 4, 1}, {15, 4, 47, 843348}}, <<68, 1
49, 156, 219, 153, 214, 65, 63, 179, 141, 252, 147, 221, 247, 41, 143>>]
[debug] QUERY OK db=0.9ms
commit []
** (Postgrex.Error) ERROR 42703 (undefined_column): column q2.qbinders_id does not exist

in running

qbinder_map = %{ title: "Math", typecode: "Jim1000"}
changeset = Qbinders.changeset(%Qbinders{}, qbinder_map)
qbinder = Repo.insert!(changeset) |> Repo.preload(:qbooks)

qbook_list =
  %Qbooks{ title: "Algebra1"}
qbook = Repo.insert!(qbook_list) |> Repo.preload(:qbinders)

changeset = Ecto.Changeset.change(qbinder)
            |> Ecto.Changeset.put_assoc(:qbooks, [qbook_list])
Repo.update!(changeset)

In postgres, the join table looks like

CREATE TABLE qbook2qbinder
(
  qbook_id uuid,
  qbinder_id uuid,
  qbook_order integer,
  inserted_at timestamp without time zone NOT NULL,
  updated_at timestamp without time zone NOT NULL,
  CONSTRAINT qbook2qbinder_qbinder_id_fkey FOREIGN KEY (qbinder_id)
      REFERENCES qbinders (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT qbook2qbinder_qbook_id_fkey FOREIGN KEY (qbook_id)
      REFERENCES qbooks (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)

And the model is

defmodule Project.Qbinders do
  use Project.Web, :model

  @primary_key {:id, :binary_id, autogenerate: true}

  schema "qbinders" do

        field :title, :string
        field :reward, :string

        many_to_many :qbooks, Project.Qbooks, join_through: "qbook2qbinder"
    timestamps
  end

Why does Ecto look for qbinders_id instead of qbinder_id? How do I set it to qbinder_id?

Body:
This is easily customisable by options argument of Ecto.Schema.many_to_many/3.

The column names can be configured with option join_keys, and should be used like:

many_to_many :qbooks, Project.Qbooks, join_through: "qbook2qbinder",
                                      join_keys: [{qbook_id: :id, qbinder_id: :id}]


问:
why does getdate returns 1\1\1900
i have the following code which does backward scheduling if Saturday or Sunday to move the date to Friday but why it returns 1900-01-06 00:00:00.000 rather 2017-03-31 13:18:12.300 i tried it getdate()-1 works fine which is Friday works great. I wounder why i doesn't work if Saturday or Sunday?

```<code>set datefirst 7 --Sunday

declare @ACUTBY datetime = getdate()

select
case datepart(WEEKDAY, @ACUTBY)
    when 1 then 5
    when 7 then 5
    else  @ACUTBY
end as [A-CUT BY]
</code>```

the above code 1900-01-06 00:00:00.000

---- getdate()-1------

```<code>set datefirst 7 --Sunday

declare @ACUTBY datetime = getdate()-1

select
case datepart(WEEKDAY, @ACUTBY)
    when 1 then 2
    when 7 then 5
    else  @ACUTBY
end as [A-CUT BY]
</code>```

the above code return 2017-03-31 13:18:12.300

答:
Try select Cast( 5 as DateTime ).

You are mixing data types, e.g. an integer 5 and a datetime @ACUTBY, and the result of the case must be a single data type. Hence the numbers get converted to a DateTime. Since the base date for a DateTime is January 1st, 1900, adding 5 results in January 6th.

You might want something like:

```<code>declare @Samples as Table ( Sample Date );
insert into @Samples ( Sample ) values
  ( '20170402' ), ( '20170403' ), ( '20170404' ),
  ( '20170405' ), ( '20170406' ), ( '20170407' ), ( '20170408' );

select Sample, DatePart( dw, Sample ) as DoW,
  case DatePart( dw, Sample )
    when 1 then DateAdd( day, -2, Sample )
    when 7 then DateAdd( day, -1, Sample )
    else Sample end as WeekDay
  from @Samples;
</code>```

Title: why does getdate returns 1\1\1900

Body:
i have the following code which does backward scheduling if Saturday or Sunday to move the date to Friday but why it returns 1900-01-06 00:00:00.000 rather 2017-03-31 13:18:12.300 i tried it getdate()-1 works fine which is Friday works great. I wounder why i doesn't work if Saturday or Sunday?

set datefirst 7 --Sunday

declare @ACUTBY datetime = getdate()

select
case datepart(WEEKDAY, @ACUTBY)
    when 1 then 5
    when 7 then 5
    else  @ACUTBY
end as [A-CUT BY]

the above code 1900-01-06 00:00:00.000

---- getdate()-1------

set datefirst 7 --Sunday

declare @ACUTBY datetime = getdate()-1

select
case datepart(WEEKDAY, @ACUTBY)
    when 1 then 2
    when 7 then 5
    else  @ACUTBY
end as [A-CUT BY]

the above code return 2017-03-31 13:18:12.300

Body:
Try select Cast( 5 as DateTime ).

You are mixing data types, e.g. an integer 5 and a datetime @ACUTBY, and the result of the case must be a single data type. Hence the numbers get converted to a DateTime. Since the base date for a DateTime is January 1st, 1900, adding 5 results in January 6th.

You might want something like:

declare @Samples as Table ( Sample Date );
insert into @Samples ( Sample ) values
  ( '20170402' ), ( '20170403' ), ( '20170404' ),
  ( '20170405' ), ( '20170406' ), ( '20170407' ), ( '20170408' );

select Sample, DatePart( dw, Sample ) as DoW,
  case DatePart( dw, Sample )
    when 1 then DateAdd( day, -2, Sample )
    when 7 then DateAdd( day, -1, Sample )
    else Sample end as WeekDay
  from @Samples;


问:
SQL Summing digits of a number
i'm using presto. I have an ID field which is numeric. I want a column that adds up the digits within the id. So if ID=1234, I want a column that outputs 10 i.e 1+2+3+4.

I could use substring to extract each digit and sum it but is there a function I can use or simpler way?

答:
You can combine regexp_extract_all from @akuhn's answer with lambda support recently added to Presto. That way you don't need to unnest. The code would be really self explanatory if not the need for cast to and from varchar:

```<code>presto> select
    reduce(
        regexp_extract_all(cast(x as varchar), '\d'), -- split into digits array
        0, -- initial reduction element
        (s, x) -> s + cast(x as integer), -- reduction function
        s -> s -- finalization
    ) sum_of_digits
from (values 1234) t(x);

 sum_of_digits
---------------
            10
(1 row)
</code>```

Title: SQL Summing digits of a number

Body:
You can combine regexp_extract_all from @akuhn's answer with lambda support recently added to Presto. That way you don't need to unnest. The code would be really self explanatory if not the need for cast to and from varchar:

presto> select
    reduce(
        regexp_extract_all(cast(x as varchar), '\d'), -- split into digits array
        0, -- initial reduction element
        (s, x) -> s + cast(x as integer), -- reduction function
        s -> s -- finalization
    ) sum_of_digits
from (values 1234) t(x);

 sum_of_digits
---------------
            10
(1 row)


问:
How to use Arrays.sort
If I have following code:

```<code>    Arrays.sort(sums, new Comparator<Pair>() {
       public int compare(Pair a, Pair b) {
           return a.sum - b.sum;
       }
    });
</code>```

Is it sorting my values from small to large or from large to small? Also other than Comparator, is there anything else I can use to defind my sorter?

答:
```<code>Arrays.sort(sums, new Comparator<Pair>() {
       public int compare(Pair a, Pair b) {
           return a.sum - b.sum;
       }
    });
</code>```

Walking through this code it simply compares each element one by one of sums.

Return statement result is definitive here. So it basically has 3 outputs.

If it returns a negative then the second one which is b in your case so it's smaller than a; put it on the head. Then it keeps comparing next element.

If it returns a positive then the first one is bigger then the second one. So it puts the a after b.

If it returns 0 then two of the elements compared are equal for the comparison property.

So as a result, if had a list of elements let's say.     [3, 5, 2, 8] it will become --> [2, 3, 5, 8]

It's totally up to you to compare against any property you want.
I hope this explains things better.

Title: How to use Arrays.sort

Body:
If I have following code:

    Arrays.sort(sums, new Comparator<Pair>() {
       public int compare(Pair a, Pair b) {
           return a.sum - b.sum;
       }
    });

Is it sorting my values from small to large or from large to small? Also other than Comparator, is there anything else I can use to defind my sorter?

Body:
Arrays.sort(sums, new Comparator<Pair>() {
       public int compare(Pair a, Pair b) {
           return a.sum - b.sum;
       }
    });

Walking through this code it simply compares each element one by one of sums.

Return statement result is definitive here. So it basically has 3 outputs.

If it returns a negative then the second one which is b in your case so it's smaller than a; put it on the head. Then it keeps comparing next element.

If it returns a positive then the first one is bigger then the second one. So it puts the a after b.

If it returns 0 then two of the elements compared are equal for the comparison property.

So as a result, if had a list of elements let's say.     [3, 5, 2, 8] it will become --> [2, 3, 5, 8]

It's totally up to you to compare against any property you want.
I hope this explains things better.


问:
Getting Game Score (Sub String) From String C#
What is the best way to extract the score from a string variable. For example extract 2-1 from "Match One 2-1 To Red Team".

I was going to add special characters around the score and do something like this

```<code>string in = "Match One |2-1| To Red Team";
string out = input.Split('|', '|')[1];
</code>```

But that would involve me adding two characters to hundreds of rows on a CSV file.

Could I split on the dash. The extract numbers into an array somehow?

```<code>scoreString.Split('-');
</code>```

Any help is appreciated.

EDIT: I have wrote this and it works, but doesnt seem very clean.

```<code>var splitScores = values[0].ToLower().Trim().Split('-');

var leftScore  = Regex.Match(splitScores[0], @"\d+").Value;
var rightScore = Regex.Match(splitScores[1], @"\d+").Value;
</code>```

答:
You could do something like:

```<code>if(splitScores.Length != 2 || !int.TryParse(splitScores[0].Split().Last(), var leftScore) || !int.TryParse(splitScores[1].Split().First(), var rightScore)
    throw new Exception("Invalid input file);
</code>```

The problem is that you need something to identify the score. If you use '-' it can happen that you split at the wrong position, because of a '-' e.g. in a team name. To avoid this you'll have to use a special identifier (as you did with |).

Body:
What is the best way to extract the score from a string variable. For example extract 2-1 from "Match One 2-1 To Red Team".

I was going to add special characters around the score and do something like this

string in = "Match One |2-1| To Red Team";
string out = input.Split('|', '|')[1];

But that would involve me adding two characters to hundreds of rows on a CSV file.

Could I split on the dash. The extract numbers into an array somehow?

scoreString.Split('-');

Any help is appreciated.

EDIT: I have wrote this and it works, but doesnt seem very clean.

var splitScores = values[0].ToLower().Trim().Split('-');

var leftScore  = Regex.Match(splitScores[0], @"\d+").Value;
var rightScore = Regex.Match(splitScores[1], @"\d+").Value;

Body:
You could do something like:

if(splitScores.Length != 2 || !int.TryParse(splitScores[0].Split().Last(), var leftScore) || !int.TryParse(splitScores[1].Split().First(), var rightScore)
    throw new Exception("Invalid input file);

The problem is that you need something to identify the score. If you use '-' it can happen that you split at the wrong position, because of a '-' e.g. in a team name. To avoid this you'll have to use a special identifier (as you did with |).


问:
protractor without selenium server
When I issue the protractor command at the command line, with the following configuration:

```<code>'use strict';

// Protractor configuration
var config = {
  specs: ['test/e2e/*spec.js']
};

if (process.env.TRAVIS) {
  config.capabilities = {
    browserName: 'firefox'
  };
}

exports.config = config;
</code>```

I get this:

```<code>$ protractor
[12:22:23] I/launcher - Running 1 instances of WebDriver
[12:22:23] I/local - Starting selenium standalone server...
[12:22:24] I/local - Selenium standalone server started at http://10.0.0.242:55414/wd/hub
Started
.

1 spec, 0 failures
Finished in 8.223 seconds

[12:22:33] I/local - Shutting down selenium standalone server.
[12:22:33] I/launcher - 0 instance(s) of WebDriver still running
[12:22:33] I/launcher - chrome #01 passed
</code>```

the problem is that it takes 5+ seconds to start up the "selenium standalone server".

Two questions - (1) do I need this server to run the tests? And (2), is there a way to run the server in the background without having to restart the server everytime?

答:
Do you use the protractor DirectConnect option? If so, you can also use the standalone webdriver-manager. Protractor also uses it as a dependency.

For local development I installed it as a global with npm install webdriver-manager -g, then update it with webdriver-manager update and start it with webdriver-manager start. It will then run on the background on the default port 4444, run webdriver-manager to see all the options.

You then don't need to start the webdriver for each test / suite.

Hope it helps

Title: protractor without selenium server

Body:
When I issue the protractor command at the command line, with the following configuration:

'use strict';

// Protractor configuration
var config = {
  specs: ['test/e2e/*spec.js']
};

if (process.env.TRAVIS) {
  config.capabilities = {
    browserName: 'firefox'
  };
}

exports.config = config;

I get this:

$ protractor
[12:22:23] I/launcher - Running 1 instances of WebDriver
[12:22:23] I/local - Starting selenium standalone server...
[12:22:24] I/local - Selenium standalone server started at http://10.0.0.242:55414/wd/hub
Started
.

1 spec, 0 failures
Finished in 8.223 seconds

[12:22:33] I/local - Shutting down selenium standalone server.
[12:22:33] I/launcher - 0 instance(s) of WebDriver still running
[12:22:33] I/launcher - chrome #01 passed

the problem is that it takes 5+ seconds to start up the "selenium standalone server".

Two questions - (1) do I need this server to run the tests? And (2), is there a way to run the server in the background without having to restart the server everytime?


答: An abstract method must be implemented in order for the class to be instantiated.  There's no such thing as checking whether a method is implemented, the compiler will do this for you.  In this case, you can't have a CBase object because it has abstract methods.</p>

Title: How to check if C++ abstract method is defined at runtime


问:
Random.choice not working correctly python
I have the following code for example:

```<code>n = ['321','243','780']
b = ['12','56','90']
a = ['178', '765', '111']

E = input('Enter Word...')
qw = 1
Code = ('')
E_ready = [E[no:no+qw] for no in range(0, len(E), qw)]
for code in E_Ready:
   letter = random.choice(code)
   Code += letter
</code>```

If you enter the word 'nba' then it will output as 'nba', I want it to output with random elements from each letter's respective list so for example '32112178'

答:
Okay, you have a few fundamental issues.
When you want to assign one variable to another then you wouldn't put it in quotes.
So it should be:

```<code>code = n
</code>```

But actually I'm wondering why you need the variable code at all.
You could simply do

```<code>import random
code = [ '321', '243', '780' ]
letter = random.choice(code)
print letter
</code>```

Body:
I have the following code for example:

n = ['321','243','780']
b = ['12','56','90']
a = ['178', '765', '111']

E = input('Enter Word...')
qw = 1
Code = ('')
E_ready = [E[no:no+qw] for no in range(0, len(E), qw)]
for code in E_Ready:
   letter = random.choice(code)
   Code += letter

If you enter the word 'nba' then it will output as 'nba', I want it to output with random elements from each letter's respective list so for example '32112178'

Body:
Okay, you have a few fundamental issues.
When you want to assign one variable to another then you wouldn't put it in quotes.
So it should be:

code = n

But actually I'm wondering why you need the variable code at all.
You could simply do

import random
code = [ '321', '243', '780' ]
letter = random.choice(code)
print letter


问:
Function Literal vs Function Expression in Javascript
Are function literals and function expressions the same thing, or is there a difference?</p>

答:
As answered on topic Exact meaning of Function literal in JavaScript: "A function literal is just an expression that defines an unnamed function."

Description of "function expression" on MDN about function name says, that it "Can be omitted, in which case the function is anonymous.". (unnamed function === anonymous function)

Another example of anonymous function notation is "arrow function expression" in ES6

```<code>var func = (x, y) => { return x + y; };
</code>```

This does the same thing as:

```<code>var func = function (x, y) { return x + y; };
</code>```

and (almost) the same thing as:

```<code>function func(x, y) { return x + y; };
</code>```

For more in-deph explanation read: Difference between “anonymous function” and “function literal” in JavaScript

TL;DR:

Function Literal is kind of function expression.

Body:
As answered on topic Exact meaning of Function literal in JavaScript: "A function literal is just an expression that defines an unnamed function."

Description of "function expression" on MDN about function name says, that it "Can be omitted, in which case the function is anonymous.". (unnamed function === anonymous function)

Another example of anonymous function notation is "arrow function expression" in ES6

var func = (x, y) => { return x + y; };

This does the same thing as:

var func = function (x, y) { return x + y; };

and (almost) the same thing as:

function func(x, y) { return x + y; };

For more in-deph explanation read: Difference between “anonymous function” and “function literal” in JavaScript

TL;DR:

Function Literal is kind of function expression.


问:
Restrict a input to only specific character and 6 digit of numbers
I want to restrict an input to only One Character (R) and 6 numbers only...
E.g: R123896

If Input length increase 7 it will remove that digit and if First word is not R , it should replace that character to "R"

I have written this script, but don't know how to move forward and shape it to what i want...

```<code>$("#consultationident").keyup(function(key){
var txtVal = $(this).val();
 if(isNumber(txtVal) && txtVal.length>6)
 {
     $(this).val(txtVal.substring(0,6) )
 }
});
</code>```

Please help!

答:
The use of a regular expression would be an idea...

$("#consultationident").keyup(function(key){

  // Uppercase the first character.
  var firstChar = $(this).val().substr(0,1).toUpperCase();
  var rest = $(this).val().substr(1);

  $(this).val( firstChar + rest );

  var txtVal = $(this).val();
  var pattern = /^(R)(\d{6})$/;

  // Check if the value entered fits the pattern.
  if(pattern.test(txtVal)){
    console.log("Value ok");
  }else{
    console.log("Value wrong");
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="consultationident"></code>```

Body:
I want to restrict an input to only One Character (R) and 6 numbers only...
E.g: R123896

If Input length increase 7 it will remove that digit and if First word is not R , it should replace that character to "R"

I have written this script, but don't know how to move forward and shape it to what i want...

$("#consultationident").keyup(function(key){
var txtVal = $(this).val();
 if(isNumber(txtVal) && txtVal.length>6)
 {
     $(this).val(txtVal.substring(0,6) )
 }
});

Please help!

Body:
The use of a regular expression would be an idea...

$("#consultationident").keyup(function(key){

  // Uppercase the first character.
  var firstChar = $(this).val().substr(0,1).toUpperCase();
  var rest = $(this).val().substr(1);

  $(this).val( firstChar + rest );

  var txtVal = $(this).val();
  var pattern = /^(R)(\d{6})$/;

  // Check if the value entered fits the pattern.
  if(pattern.test(txtVal)){
    console.log("Value ok");
  }else{
    console.log("Value wrong");
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="consultationident">


问:
windows phone silverlight 8 app system tray color change
I am making a windows phone silverlight 8 app. and I want to change the color of the top system tray throught the application, i.e; during the transition between pages and also when splash screen is visible. is there a way to do it? Please let me know if there is or there isn't.

I already know how to change color on a specific page but that color isn't applied during page transitions and also the splash screen. I want the following colors.

background: #244421
foreground : White

Thanks in advance.

答:
You can do it as follows (or via code) for all your pages:

```<code><phone:PhoneApplicationPage
    ...
    shell:SystemTray.IsVisible="True"
    shell:SystemTray.BackgroundColor="#FF244421"
    shell:SystemTray.ForegroundColor="White">
</code>```

Or you can try defining a resource.

Body:
You can do it as follows (or via code) for all your pages:

<phone:PhoneApplicationPage
    ...
    shell:SystemTray.IsVisible="True"
    shell:SystemTray.BackgroundColor="#FF244421"
    shell:SystemTray.ForegroundColor="White">

Or you can try defining a resource.


问:
Regular expressions don't work as expected in bash if-else block's condition
My pattern defined to match in if-else block is :

```<code>pat="17[0-1][0-9][0-9][0-9].AUG"
nln=""
</code>```

In my script, I'm taking user input which needs to be matched against the pattern, which if doesn't match, appropriate error messages are to be shown. Pretty simple, but giving me a hard time though. My code block from the script is this:

```<code>echo "How many days' AUDIT Logs need to be searched?"
read days
echo "Enter file name(s)[For multiple files, one file per line]: "
for(( c = 0 ; c < $days ; c++))
do
  read elements
  if [[  $elements =~ $pat ]];
     then
       array[$c]="$elements"
  elif [[  $elements =~ $nln ]];
     then
        echo "No file entered.Run script again. Exiting"
        exit;
  else
      echo "Invalid filename entered: $elements.Run script again. Exiting"
      exit;
  fi
done
</code>```

The format I want from the user for filenames to be entered is this:

```<code>170402.AUG
</code>```

So basically yymmdd.AUG (where y-year,m-month,d-day), with trailing or leading spaces is fine. Anything other than that should throw "Invalid filename entered: $elements.Run script again. Exiting" message. Also I want to check if if it is a blank line with a "Enter" hit, it should give an error saying "No file entered.Run script again. Exiting"

However my code, even if I enter something like "xxx" as filename, which should be throwing "Invalid filename entered: $elements.Run script again. Exiting", is actually checking true against a blank line, and throwing "No file entered.Run script again. Exiting"

Need some help with handling the regular expressions' check with user input, as otherwise rest of my script works just fine.

答:
I think as discussed in the comments you are confusing with the glob match and a regEx match, what you have defined as pat is a glob match which needs to be equated with the == operator as,

```<code>pat="17[0-1][0-9][0-9][0-9].AUG"
string="170402.AUG"

[[ $string == $pat ]] && printf "Match success\n"
</code>```

The equivalent ~ match would be to something as

```<code>pat="17[[:digit:]]{4}\.AUG"
[[ $string =~ $pat ]] && printf "Match success\n"
</code>```

As you can see the . in the regex syntax has been escaped to deprive of its special meaning ( to match any character) but just to use as a literal dot. The POSIX character class [[:digit:]] with a character count {4} allows you to match 4 digits followed by .AUG

And for the string empty check do as suggested by the comments from Cyrus, or by Benjamin.W

```<code>[[ $elements == "" ]]
</code>```

(or)

```<code>[[ -z $elements ]]
</code>```

Body:
My pattern defined to match in if-else block is :

pat="17[0-1][0-9][0-9][0-9].AUG"
nln=""

In my script, I'm taking user input which needs to be matched against the pattern, which if doesn't match, appropriate error messages are to be shown. Pretty simple, but giving me a hard time though. My code block from the script is this:

echo "How many days' AUDIT Logs need to be searched?"
read days
echo "Enter file name(s)[For multiple files, one file per line]: "
for(( c = 0 ; c < $days ; c++))
do
  read elements
  if [[  $elements =~ $pat ]];
     then
       array[$c]="$elements"
  elif [[  $elements =~ $nln ]];
     then
        echo "No file entered.Run script again. Exiting"
        exit;
  else
      echo "Invalid filename entered: $elements.Run script again. Exiting"
      exit;
  fi
done

The format I want from the user for filenames to be entered is this:

170402.AUG

So basically yymmdd.AUG (where y-year,m-month,d-day), with trailing or leading spaces is fine. Anything other than that should throw "Invalid filename entered: $elements.Run script again. Exiting" message. Also I want to check if if it is a blank line with a "Enter" hit, it should give an error saying "No file entered.Run script again. Exiting"

However my code, even if I enter something like "xxx" as filename, which should be throwing "Invalid filename entered: $elements.Run script again. Exiting", is actually checking true against a blank line, and throwing "No file entered.Run script again. Exiting"

Need some help with handling the regular expressions' check with user input, as otherwise rest of my script works just fine.

Body:
I think as discussed in the comments you are confusing with the glob match and a regEx match, what you have defined as pat is a glob match which needs to be equated with the == operator as,

pat="17[0-1][0-9][0-9][0-9].AUG"
string="170402.AUG"

[[ $string == $pat ]] && printf "Match success\n"

The equivalent ~ match would be to something as

pat="17[[:digit:]]{4}\.AUG"
[[ $string =~ $pat ]] && printf "Match success\n"

As you can see the . in the regex syntax has been escaped to deprive of its special meaning ( to match any character) but just to use as a literal dot. The POSIX character class [[:digit:]] with a character count {4} allows you to match 4 digits followed by .AUG

And for the string empty check do as suggested by the comments from Cyrus, or by Benjamin.W

[[ $elements == "" ]]

(or)

[[ -z $elements ]]


问:
Using OpenGL in Universal Windows App with Angle : glLoadIdentity and glOrtho undefined
I'm currently trying to adapt existing OpenGL code to a Universal Windows App, using the Angle component that is supposed to translate OpenGL calls to DirectX.
One base function that is giving me problem is a full screen display of a quad in a texture (in order to apply shaders to that quad).
The regular OpenGL code is straightforward :

```<code>glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-viewWidth, viewWidth, -viewHeight, viewHeight, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
my_quad.RenderObject();
</code>```

(RenderObject binds the appropriate buffers for vertices and texture coordinates, and then calls glDrawElements).

That code builds and runs fine in regular Win32 applications, using OpenGL and Glut. When trying to use the same code in Angle+UWP, the compiler returns build errors on basic functions :

```<code>error C2065: 'GL_PROJECTION': undeclared identifier
error C3861: 'glMatrixMode': identifier not found
error C3861: 'glLoadIdentity': identifier not found
error C3861: 'glOrtho': identifier not found
error C2065: 'GL_MODELVIEW': undeclared identifier
error C3861: 'glMatrixMode': identifier not found
error C3861: 'glLoadIdentity': identifier not found
error C2065: 'GL_TEXTURE_ENV': undeclared identifier
error C2065: 'GL_TEXTURE_ENV_MODE': undeclared identifier
error C2065: 'GL_MODULATE': undeclared identifier
error C3861: 'glTexEnvf': identifier not found
</code>```

I'm not too familiar with OpenGL ES (obviously), but according to tutorials functions like glLoadIdentity should be supported.
Did I miss anything ? The headers in the Angle folder (gl2.h, glext.h and gl2platform.h) don't define them.

答: Angle support only OpenGL-ES 2.0 and 3.0 (3.1 work in progress). Since OpenGL-ES 2.0 removed the whole fixed function pipeline, non of the functions you are using is available with OpenGL-ES 2.0 or higher. Have a look at the OpenGL-ES 2.0 Reference.</p>

Body:
I'm currently trying to adapt existing OpenGL code to a Universal Windows App, using the Angle component that is supposed to translate OpenGL calls to DirectX.
One base function that is giving me problem is a full screen display of a quad in a texture (in order to apply shaders to that quad).
The regular OpenGL code is straightforward :

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-viewWidth, viewWidth, -viewHeight, viewHeight, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
my_quad.RenderObject();

(RenderObject binds the appropriate buffers for vertices and texture coordinates, and then calls glDrawElements).

That code builds and runs fine in regular Win32 applications, using OpenGL and Glut. When trying to use the same code in Angle+UWP, the compiler returns build errors on basic functions :

error C2065: 'GL_PROJECTION': undeclared identifier
error C3861: 'glMatrixMode': identifier not found
error C3861: 'glLoadIdentity': identifier not found
error C3861: 'glOrtho': identifier not found
error C2065: 'GL_MODELVIEW': undeclared identifier
error C3861: 'glMatrixMode': identifier not found
error C3861: 'glLoadIdentity': identifier not found
error C2065: 'GL_TEXTURE_ENV': undeclared identifier
error C2065: 'GL_TEXTURE_ENV_MODE': undeclared identifier
error C2065: 'GL_MODULATE': undeclared identifier
error C3861: 'glTexEnvf': identifier not found

I'm not too familiar with OpenGL ES (obviously), but according to tutorials functions like glLoadIdentity should be supported.
Did I miss anything ? The headers in the Angle folder (gl2.h, glext.h and gl2platform.h) don't define them.


问:
Can anyone help? Getting "[Errno 13] Permission denied" when I try to install pip on Mac
Thank you in advance for any guidance (I've heard mixed advice on sudo command?). Here is the script from Terminal:

running install

  Checking .pth file support in /Library/Python/2.7/site-packages/

  error: can't create or remove files in install directory

The following error occurred while trying to add or remove files in the
installation directory:

[Errno 13] Permission denied: '/Library/Python/2.7/site-packages/test-easy-install-85961.pth'

答:
You need to be root in order to write inside /Library, therefore you have to issue the install command as root: </p>

```<code>sudo <command>
</code>```

Body:
You need to be root in order to write inside /Library, therefore you have to issue the install command as root:

sudo <command>


问:
Align center depending on number of columns susy
I am using the following style to align the columns at the center of the page using susy:

```<code>card{
@include span(3 of 12);
  margin: 0 auto;
  cursor: pointer;
}
</code>```

But its not moving the elements (div) to center of the page by default, if I have single element it is placing it on left side and but I want that single element to be placed at the center of the page. Elements grows dynamically and they are not static.

答:
The span() mixin generates a float: left; property, which keeps your item from centering. Use the function instead, to avoid unwanted output:

```<code>.card {
  width: span(3 of 12);
  margin: 0 auto;
  cursor: pointer;
}
</code>```

Update based on clarifying comment...

There are two ways you might be able to center/left-align based on siblings. One uses flexbox:

```<code>.container {
  display: flex;
  justify-content: center;
}

.card {
  flex: 0 0 span(3 of 12);

  // add gutters to all but the first element
  & + & {
    margin-left: gutter(of 12);
  }
}
</code>```

The other uses sibling-logic only:

```<code>.card {
  @include span(3 of 12);
  outline: 1px dotted red;

  &:first-child:last-child {
    float: none;
    margin: 0 auto;
  }
}
</code>```

The flexbox solution keeps everything centered until you've filled up the space. The floating solution only centers when there is a single .card

Body:
I am using the following style to align the columns at the center of the page using susy:

card{
@include span(3 of 12);
  margin: 0 auto;
  cursor: pointer;
}

But its not moving the elements (div) to center of the page by default, if I have single element it is placing it on left side and but I want that single element to be placed at the center of the page. Elements grows dynamically and they are not static.

Body:
The span() mixin generates a float: left; property, which keeps your item from centering. Use the function instead, to avoid unwanted output:

.card {
  width: span(3 of 12);
  margin: 0 auto;
  cursor: pointer;
}

Update based on clarifying comment...

There are two ways you might be able to center/left-align based on siblings. One uses flexbox:

.container {
  display: flex;
  justify-content: center;
}

.card {
  flex: 0 0 span(3 of 12);

  // add gutters to all but the first element
  & + & {
    margin-left: gutter(of 12);
  }
}

The other uses sibling-logic only:

.card {
  @include span(3 of 12);
  outline: 1px dotted red;

  &:first-child:last-child {
    float: none;
    margin: 0 auto;
  }
}

The flexbox solution keeps everything centered until you've filled up the space. The floating solution only centers when there is a single .card


答:
By your layout, it seems that all your match results will be of a similar layout as follows:

Match [count] [int]-[int] To [Color] Team

If this is the case, then a simple regex should be able to identify and pull the information out of the string into the format desired (in your case, an array with the two values, in order).

This link should get you some more information about pulling matches from the string:

C# Documentation - Regex.Matches

However, there is a more significant problem with what is going on here.  The data is currently stored in a manner that is mixing presentation with the data, and this is the reason you are fighting with processing a string at all.  It would be better to implement the CSV file as follows:

```<code>Match_number,Winner,Winner_Score,Loser_score
1,Red,2,1
2,Blue,3,2
3,Red,4,1
etc...
</code>```

The match number could be inferred, but that is a matter for another time.  If the data were stored in this manner, getting access to the data would be a very simple matter.

Title: Getting Game Score (Sub String) From String C#

Body:
By your layout, it seems that all your match results will be of a similar layout as follows:

Match [count] [int]-[int] To [Color] Team

If this is the case, then a simple regex should be able to identify and pull the information out of the string into the format desired (in your case, an array with the two values, in order).

This link should get you some more information about pulling matches from the string:

C# Documentation - Regex.Matches

However, there is a more significant problem with what is going on here.  The data is currently stored in a manner that is mixing presentation with the data, and this is the reason you are fighting with processing a string at all.  It would be better to implement the CSV file as follows:

Match_number,Winner,Winner_Score,Loser_score
1,Red,2,1
2,Blue,3,2
3,Red,4,1
etc...

The match number could be inferred, but that is a matter for another time.  If the data were stored in this manner, getting access to the data would be a very simple matter.


问:
Comparison operator with boolean always returning false
I'm trying to understand objects and functions, this is my code:

```<code>function house(roof) {
  this.roof = roof;
  this.roofdescrip = describehouse();
}

function describehouse(){
  var z = this.roof;
  x="The house has a roof.";
  y="The house does not have a roof.";
  if(z===true){return x;}
  else{return y;}

  }

var myhouse = new house(true);

document.write(myhouse.roofdescrip);
</code>```

always returns

```<code>The house does not have a roof.
</code>```

whether I change the parameter to true or false. Why?

答:
That's because the this operator in describehouse() function points to the window object which will have roof equal to undefined, try passing the this as a parameter.
Something like this

```<code>function house(roof) {
  this.roof = roof;
  this.roofdescrip = describehouse(this);
}

function describehouse(that){
  var z = that.roof;
  x="The house has a roof.";
  y="The house does not have a roof.";
  if(z===true){return x;}
  else{return y;}

  }

var myhouse = new house(true);

document.write(myhouse.roofdescrip);
</code>```

Body:
I'm trying to understand objects and functions, this is my code:

function house(roof) {
  this.roof = roof;
  this.roofdescrip = describehouse();
}

function describehouse(){
  var z = this.roof;
  x="The house has a roof.";
  y="The house does not have a roof.";
  if(z===true){return x;}
  else{return y;}

  }

var myhouse = new house(true);

document.write(myhouse.roofdescrip);

always returns

The house does not have a roof.

whether I change the parameter to true or false. Why?

Body:
That's because the this operator in describehouse() function points to the window object which will have roof equal to undefined, try passing the this as a parameter.
Something like this

function house(roof) {
  this.roof = roof;
  this.roofdescrip = describehouse(this);
}

function describehouse(that){
  var z = that.roof;
  x="The house has a roof.";
  y="The house does not have a roof.";
  if(z===true){return x;}
  else{return y;}

  }

var myhouse = new house(true);

document.write(myhouse.roofdescrip);


问:
How do I bulk upload Couchdb attachments?
I am converting my sqlite database to Couchdb. I can convert the db and upload to the Couchdb server. Everything but the images. I want to upload the images as standalone attachments and I would like to do this in bulk using javascript, REST, and xhr.

```<code>POST http://127.0.0.1:5984/database/_bulk_docs

Data : {"_id": "701", "_attachments": {"555_image.png": { "content_type": "image/jpg","data":[object TiFilesystemFile]      }}}
</code>```

I have CURLed a single file to test and that works. How do I do bulk?

This is and iOS app developed with Appcelerator Titanium.

答:
A simple work around..Export all data to excel first. Then create a column which will have the exact urls needed for executing the curl statements for every docs(in the excel there will be rows for every documents).
Simple curl statement to execute image upload:

```<code>curl -v -X PUT "http://username:password@serverip:portno/dbname/doc_id/image.JPG?rev=revisionid" --data-binary @image.JPG -H "Content-Type:image/jpg"
</code>```

After building up the individual urls required for curl, which will be pretty easy in excel, copy the entire column of built up urls in a text file and place the text file where the images to be uploaded are present. Then create a bash script to which will read all the lines and keep on posting the images to the couchdb server:
bash script

```<code>#!/bin/bash
while read line
do
        curl -v -X PUT $line
done < test.txt
</code>```

In my case all the url lines are present in the test.txt file.

This method has worked for me flawlessly the size of the images were around 60-65kb though with 380 docs. Not sure what will happen with large files.

Body:
I am converting my sqlite database to Couchdb. I can convert the db and upload to the Couchdb server. Everything but the images. I want to upload the images as standalone attachments and I would like to do this in bulk using javascript, REST, and xhr.

POST http://127.0.0.1:5984/database/_bulk_docs

Data : {"_id": "701", "_attachments": {"555_image.png": { "content_type": "image/jpg","data":[object TiFilesystemFile]      }}}

I have CURLed a single file to test and that works. How do I do bulk?

This is and iOS app developed with Appcelerator Titanium.

Body:
A simple work around..Export all data to excel first. Then create a column which will have the exact urls needed for executing the curl statements for every docs(in the excel there will be rows for every documents).
Simple curl statement to execute image upload:

curl -v -X PUT "http://username:password@serverip:portno/dbname/doc_id/image.JPG?rev=revisionid" --data-binary @image.JPG -H "Content-Type:image/jpg"

After building up the individual urls required for curl, which will be pretty easy in excel, copy the entire column of built up urls in a text file and place the text file where the images to be uploaded are present. Then create a bash script to which will read all the lines and keep on posting the images to the couchdb server:
bash script

#!/bin/bash
while read line
do
        curl -v -X PUT $line
done < test.txt

In my case all the url lines are present in the test.txt file.

This method has worked for me flawlessly the size of the images were around 60-65kb though with 380 docs. Not sure what will happen with large files.


问:
How to check if C++ abstract method is defined at runtime
How to check if C++ abstract method is defined at runtime

```<code>class ABase{
public:
 virtual void do1() = 0;
};

class BBase: public ABase{
public:
 virtual void do1(){}
};

class CBase: public ABase{
public:
};

ABase * base = rand() % 2 ? new BBase() : new CBase();
if(&(base->do1) != 0)
  base->do1();
</code>```

This gives error.

Thanks,
Max

答: You don't need to check if the method is implemented at runtime (you can't in this case anyway) because CBase must implement do1() to satisfy inheriting from ABase.

Body:
How to check if C++ abstract method is defined at runtime

class ABase{
public:
 virtual void do1() = 0;
};

class BBase: public ABase{
public:
 virtual void do1(){}
};

class CBase: public ABase{
public:
};

ABase * base = rand() % 2 ? new BBase() : new CBase();
if(&(base->do1) != 0)
  base->do1();

This gives error.

Thanks,
Max