问:
C# Coding a Tie in Tic Tac Toe
I've developed a game of tic tac toe in C# and set a function for the win conditions, but I can't seem to figure out how to set the condition for a tie when the grid is full. When I tried to input, the tie would occur randomly. I wonder if it's how I set the or and and operators.Here's what I tried. </p>

```<code>public bool Ended()
{
    if (grid[0, 0] == 'X' && grid[0, 1] == 'X' && grid[0, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[1, 0] == 'X' && grid[1, 1] == 'X' && grid[1, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[2, 0] == 'X' && grid[2, 1] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'X' && grid[1, 0] == 'X' && grid[2, 0] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 1] == 'X' && grid[1, 1] == 'X' && grid[2, 1] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 2] == 'X' && grid[1, 2] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'X' && grid[1, 1] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 2] == 'X' && grid[1, 1] == 'X' && grid[2, 0] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[0, 1] == 'O' && grid[0, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[1, 0] == 'O' && grid[1, 1] == 'O' && grid[1, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[2, 0] == 'O' && grid[2, 1] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[1, 0] == 'O' && grid[2, 0] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 1] == 'O' && grid[1, 1] == 'O' && grid[2, 1] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 2] == 'O' && grid[1, 2] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[1, 1] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 2] == 'O' && grid[1, 1] == 'O' && grid[2, 0] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    else if (grid[0, 0] == 'X' || grid[0, 0] == 'O' &&
        grid[0, 1] == 'X' || grid[0, 1] == 'O' &&
        grid[0, 2] == 'X' || grid[0, 2] == 'O' &&
        grid[1, 0] == 'X' || grid[1, 0] == 'O' &&
        grid[1, 1] == 'X' || grid[1, 1] == 'O' &&
        grid[1, 2] == 'X' || grid[1, 2] == 'O' &&
        grid[2, 0] == 'X' || grid[2, 0] == 'O' &&
        grid[2, 1] == 'X' || grid[2, 1] == 'O' &&
        grid[2, 2] == 'X' || grid[2, 2] == 'O')
    { Console.WriteLine("It's a Tie"); return true; }
    return false;
}
</code>```

答:
The fundamental problem is that the indentation of your program does not match its meaning. Suppose I wrote:

```<code>int x =
   2 + 3 *
   4 + 5;
</code>```

It would be very easy to think that this should be 5 x 9 = 45, but in fact it is 2 + 12 + 5 = 19.

You've done the same thing.

```<code>if (a || b &&
    c || d)
</code>```

means

```<code>if (a || (b && c) || d)
</code>```

not what you want it to mean, which is

```<code>if ((a || b) && (c || d))
</code>```

You probably already remember that multiplication is higher precedence than addition. You can remember that AND is higher than OR because AND is the same as multiplication!

```<code>true && true == true
true && false == false
false && true == false
false && false == false
</code>```

If we replace true with 1, false with 0 and && with * then we get true statements out:

```<code>1 * 1 == 1
1 * 0 == 0
0 * 1 == 0
0 * 0 == 0
</code>```

Now let's address the other problems in your program.

Any time you find you're writing the same code twice or more, consider making a method.  Cutting and pasting is a bad habit in code.

```<code>if (grid[0, 0] == 'X' && grid[0, 1] == 'X' && grid[0, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
if (grid[1, 0] == 'X' && grid[1, 1] == 'X' && grid[1, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
if (grid[2, 0] == 'X' && grid[2, 1] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
</code>```

I notice that you've cut and pasted a typo! Just another reason why its so bad.

If you find you're cutting and pasting, make a method:

```<code>private bool HasRow(char player, int row)
{
  return grid[row,0] == player && grid[row,1] == player && grid[row,2] == player;
}
</code>```

And now you can replace that code with

```<code>if (HasRow('X', 0) || HasRow('X', 1) || HasRow('X', 2)) { ... }
...
if (HasRow('O', 0) || HasRow('O', 1) || HasRow('O', 2)) { ... }
</code>```

But wait, we just cut and pasted code again.  So fix that!

```<code>private bool HasAnyRow(char player)
{
  return HasRow(player, 0) || HasRow(player, 1) || HasRow(player, 2);
}
</code>```

And now your code becomes

```<code>if (HasAnyRow('X')) { ... }
...
if (HasAnyRow('O')) { ... }
...
</code>```

Do the same thing for columns and diagonals and you end up with

```<code>if (HasAnyRow('X') || HasAnyColumn('X') || HasAnyDiagonal('X')) { ... }
if (HasAnyRow('O') || HasAnyColumn('O') || HasAnyDiagonal('O')) { ... }
</code>```

But wait, this is still too much copy pasting.

```<code>private bool HasWin(char player)
{
  return HasAnyRow(player) || HasAnyColumn(player) || HasAnyDiagonal(player);
}
</code>```

And now the code is:

```<code>if (HasWin('X')) { ... }
if (HasWin('O')) { ... }
</code>```

Your code will get much better -- easier to write, easier to read, easier to debug, more likely correct the first time -- if you:

Eliminate redundant code by making helper methods instead of copy-pasting code.

Make helper methods that are in the business domain of the program. What is a win in tic-tac-toe?  Having a row, column or diagonal. So make methods called HasRow, HasColumn and HasDiagonal, and now you can reason about your program more easily because it is written using the concepts from the business domain of the program.

Title: C# Coding a Tie in Tic Tac Toe

Body:
I've developed a game of tic tac toe in C# and set a function for the win conditions, but I can't seem to figure out how to set the condition for a tie when the grid is full. When I tried to input, the tie would occur randomly. I wonder if it's how I set the or and and operators.Here's what I tried.

public bool Ended()
{
    if (grid[0, 0] == 'X' && grid[0, 1] == 'X' && grid[0, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[1, 0] == 'X' && grid[1, 1] == 'X' && grid[1, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[2, 0] == 'X' && grid[2, 1] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'X' && grid[1, 0] == 'X' && grid[2, 0] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 1] == 'X' && grid[1, 1] == 'X' && grid[2, 1] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 2] == 'X' && grid[1, 2] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'X' && grid[1, 1] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 2] == 'X' && grid[1, 1] == 'X' && grid[2, 0] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[0, 1] == 'O' && grid[0, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[1, 0] == 'O' && grid[1, 1] == 'O' && grid[1, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[2, 0] == 'O' && grid[2, 1] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[1, 0] == 'O' && grid[2, 0] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 1] == 'O' && grid[1, 1] == 'O' && grid[2, 1] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 2] == 'O' && grid[1, 2] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[1, 1] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 2] == 'O' && grid[1, 1] == 'O' && grid[2, 0] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    else if (grid[0, 0] == 'X' || grid[0, 0] == 'O' &&
        grid[0, 1] == 'X' || grid[0, 1] == 'O' &&
        grid[0, 2] == 'X' || grid[0, 2] == 'O' &&
        grid[1, 0] == 'X' || grid[1, 0] == 'O' &&
        grid[1, 1] == 'X' || grid[1, 1] == 'O' &&
        grid[1, 2] == 'X' || grid[1, 2] == 'O' &&
        grid[2, 0] == 'X' || grid[2, 0] == 'O' &&
        grid[2, 1] == 'X' || grid[2, 1] == 'O' &&
        grid[2, 2] == 'X' || grid[2, 2] == 'O')
    { Console.WriteLine("It's a Tie"); return true; }
    return false;
}

Body:
The fundamental problem is that the indentation of your program does not match its meaning. Suppose I wrote:

int x =
   2 + 3 *
   4 + 5;

It would be very easy to think that this should be 5 x 9 = 45, but in fact it is 2 + 12 + 5 = 19.

You've done the same thing.

if (a || b &&
    c || d)

means

if (a || (b && c) || d)

not what you want it to mean, which is

if ((a || b) && (c || d))

You probably already remember that multiplication is higher precedence than addition. You can remember that AND is higher than OR because AND is the same as multiplication!

true && true == true
true && false == false
false && true == false
false && false == false

If we replace true with 1, false with 0 and && with * then we get true statements out:

1 * 1 == 1
1 * 0 == 0
0 * 1 == 0
0 * 0 == 0

Now let's address the other problems in your program.

Any time you find you're writing the same code twice or more, consider making a method.  Cutting and pasting is a bad habit in code.

if (grid[0, 0] == 'X' && grid[0, 1] == 'X' && grid[0, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
if (grid[1, 0] == 'X' && grid[1, 1] == 'X' && grid[1, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
if (grid[2, 0] == 'X' && grid[2, 1] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

I notice that you've cut and pasted a typo! Just another reason why its so bad.

If you find you're cutting and pasting, make a method:

private bool HasRow(char player, int row)
{
  return grid[row,0] == player && grid[row,1] == player && grid[row,2] == player;
}

And now you can replace that code with

if (HasRow('X', 0) || HasRow('X', 1) || HasRow('X', 2)) { ... }
...
if (HasRow('O', 0) || HasRow('O', 1) || HasRow('O', 2)) { ... }

But wait, we just cut and pasted code again.  So fix that!

private bool HasAnyRow(char player)
{
  return HasRow(player, 0) || HasRow(player, 1) || HasRow(player, 2);
}

And now your code becomes

if (HasAnyRow('X')) { ... }
...
if (HasAnyRow('O')) { ... }
...

Do the same thing for columns and diagonals and you end up with

if (HasAnyRow('X') || HasAnyColumn('X') || HasAnyDiagonal('X')) { ... }
if (HasAnyRow('O') || HasAnyColumn('O') || HasAnyDiagonal('O')) { ... }

But wait, this is still too much copy pasting.

private bool HasWin(char player)
{
  return HasAnyRow(player) || HasAnyColumn(player) || HasAnyDiagonal(player);
}

And now the code is:

if (HasWin('X')) { ... }
if (HasWin('O')) { ... }

Your code will get much better -- easier to write, easier to read, easier to debug, more likely correct the first time -- if you:

Eliminate redundant code by making helper methods instead of copy-pasting code.

Make helper methods that are in the business domain of the program. What is a win in tic-tac-toe?  Having a row, column or diagonal. So make methods called HasRow, HasColumn and HasDiagonal, and now you can reason about your program more easily because it is written using the concepts from the business domain of the program.


来源: stackexchange

问:
Datatables and bootstrap tooltips
I am adding Datatables to my Rails app.  I have it working for the most part but I am stuck on a CSS / jQuery issue.  I have a row cell defined as follows:

```<code>content_tag(:abbr, "#{record.od} mm", data: { container: 'body', toggle: 'tooltip', placement: 'bottom', html: 'true' }, title: 'test' )
</code>```

which renders:

```<code><abbr data-container="body" data-toggle="tooltip" data-placement="bottom" data-html="true" title="test">88.9 mm</abbr>
</code>```

In a non-datatable table the bootstrap tooltip works fine but fails on the datatable.  From experience I gather it's because the datatable is rendered after the body completes etc.

After some digging I tried this:

```<code>$ ->
  $('#table').dataTable
    ajax:
      url: myurl
    processing: true
    serverSide: false
    responsive: true
    'fnCreatedCell': (nTd, sData, oData, iRow, iCol) ->
      $(nTd "abbr").tooltip()
</code>```

This almost works... almost because I get a tooltip but I am guessing it's a datatable tooltip vs the bootstrap tooltip:

Forget the tooltip content - the formatting etc. is the issue.  The non-bootstrap tooltip also takes way longer to fade in.

Is there perhaps an easy fix here?

Thanks,

Dan

答:
You need to use drawCallback to initialize tooltips every time DataTables redraws the table.

```<code>var table = $('#example').DataTable( {
"drawCallback": function( settings ) {

$('[data-toggle="tooltip1"]').tooltip();
$('[data-toggle="tooltip2"]').tooltip();

// add as many tooltips you want

},
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Datatables and bootstrap tooltips

Body:
I am adding Datatables to my Rails app.  I have it working for the most part but I am stuck on a CSS / jQuery issue.  I have a row cell defined as follows:

content_tag(:abbr, "#{record.od} mm", data: { container: 'body', toggle: 'tooltip', placement: 'bottom', html: 'true' }, title: 'test' )

which renders:

88.9 mm

In a non-datatable table the bootstrap tooltip works fine but fails on the datatable.  From experience I gather it's because the datatable is rendered after the body completes etc.

After some digging I tried this:

$ ->
  $('#table').dataTable
    ajax:
      url: myurl
    processing: true
    serverSide: false
    responsive: true
    'fnCreatedCell': (nTd, sData, oData, iRow, iCol) ->
      $(nTd "abbr").tooltip()

This almost works... almost because I get a tooltip but I am guessing it's a datatable tooltip vs the bootstrap tooltip:

Forget the tooltip content - the formatting etc. is the issue.  The non-bootstrap tooltip also takes way longer to fade in.

Is there perhaps an easy fix here?

Thanks,

Dan

Body:
You need to use drawCallback to initialize tooltips every time DataTables redraws the table.

var table = $('#example').DataTable( {
"drawCallback": function( settings ) {

$('[data-toggle="tooltip1"]').tooltip();
$('[data-toggle="tooltip2"]').tooltip();

// add as many tooltips you want

},
});


问:
How to implement an API key on PHP software?
I am distributing a PHP created plugin like a Wordpress plugin but I want to implement an API key for it and users would need to enter an API key to unlock it for it to work.

How can that be done?  And yes I already know it could be easily bypassed since PHP is not compiled but atleast it will deter some people with no PHP knowledge.

Thanks..

答: You can scramble the actual source code with the API key. Encrypt some essential part of the source code (e.g. using libmcrypt), and have the script load and decrypt the source. Of course, somebody finding the relevant routine could then easily dump the source to disk and use that instead, but it won't be as trivial as removing a check.</p>

ContentLicense: CC BY-SA 2.5


问:
How to close an NSWindow during UI Testing with Xcode?
I am developing a document based Application for macOS. How can I close an existing NSWindow at the beginning of a test case?</p>

答:
This was the code that does the trick. I had problems not saving it. Not sure why, but then I realised that there might be cases when I want to save the existing document anyway. </p>

```<code> var untitledWindow = app.windows["Untitled"]
    if untitledWindow.exists {
        untitledWindow.typeKey("w", modifierFlags:.command)
        //untitledWindow.buttons[XCUIIdentifierCloseWindow].click() should work too
        if untitledWindow.buttons["Save"].exists{
            untitledWindow.buttons["Save"].click()
        }
        if untitledWindow.buttons["Replace"].exists {
            untitledWindow.buttons["Replace"].click()
        }
    }
</code>```

Body:
This was the code that does the trick. I had problems not saving it. Not sure why, but then I realised that there might be cases when I want to save the existing document anyway.

 var untitledWindow = app.windows["Untitled"]
    if untitledWindow.exists {
        untitledWindow.typeKey("w", modifierFlags:.command)
        //untitledWindow.buttons[XCUIIdentifierCloseWindow].click() should work too
        if untitledWindow.buttons["Save"].exists{
            untitledWindow.buttons["Save"].click()
        }
        if untitledWindow.buttons["Replace"].exists {
            untitledWindow.buttons["Replace"].click()
        }
    }


问:
How to run and install files in directory inside /opt in ubuntu?
Hi I have installed ubuntu in virtual box and I downloaded petalinux2017.1 into downloads directory and moved the run file into a directory called PetaLinux in opt in my root directory.

But i couldnot run the file when my commands are in the following way and it is showing an error "command not found".

```<code>my@my-Ubuntu: /opt/PetaLinux$petalinux-v2017.1-finalinstaller.run
</code>```

i tried the same with sudo and the error is same and i want to install it into the directory PetaLinux and I am a beginner in these.

答:
Why you put this into /opt/?

Whatever, try this:

```<code>$ cd /opt/PetaLinux
$ sudo chmod +x petalinux-v2017.1-finalinstaller.run
$ ./petalinux-v2017.1-finalinstaller.run
</code>```

Body:
Hi I have installed ubuntu in virtual box and I downloaded petalinux2017.1 into downloads directory and moved the run file into a directory called PetaLinux in opt in my root directory.

But i couldnot run the file when my commands are in the following way and it is showing an error "command not found".

my@my-Ubuntu: /opt/PetaLinux$petalinux-v2017.1-finalinstaller.run

i tried the same with sudo and the error is same and i want to install it into the directory PetaLinux and I am a beginner in these.

Body:
Why you put this into /opt/?

Whatever, try this:

$ cd /opt/PetaLinux
$ sudo chmod +x petalinux-v2017.1-finalinstaller.run
$ ./petalinux-v2017.1-finalinstaller.run


问:
Google developer screenshot (graphic assets) error image not valid
Trying to upload any graphics such as screenshot, icon, Feature graphic and I keep having the same error from from Google while my picture have the right spec.
message is "Upload Error" "You need to check that your screenshot image is valid valid" or "You need to fix your feature graphic is valid"

Anyone has the same error or any clue?

I've even used another graphic from another app published and it still dont want it anymore.
I've also deleted my app and create a new one in the Dev account. Same issue. I'm desperate.

答: I have the same error. Try with another browser. Firefox works for me.</p>


问:
android java insertsort using ArrayList
First of all, I'm writing program to visualize sorting algorithms on Android
I wrote method for insertion sort algorithm. I'm using MPAndroidChart for it.

```<code>    void insertionSort(int[] arr) {
    int i, j, newValue;
    for (i = 1; i < arr.length; i++) {
        newValue = arr[i];
        j = i;
        while (j > 0 && arr[j - 1] > newValue) {
            arr[j] = arr[j - 1];
            j--;
        }
        arr[j] = newValue;
    }
}
</code>```

...and it works fine. I want to redesign it to get the same result using ArrayList, but unfortunately, it crashes, and I have no idea why! This is my collection approach insertionSort:

```<code>void insertionSort(ArrayList<BarEntry> list) {
    int i, j;
    float newValue;
    for (i = 1; i < list.size(); i++) {
        newValue = list.get(i).getY();
        j = i;
        while (j > 0 && list.get(j-1).getY() > newValue) {
            list.set(j, list.get(j-1));
            j--;
        }
        BarEntry be = list.get(list.indexOf(newValue));
        list.set(j, be);
    }
}
</code>```

BarEntry is class used to create charts. I want to sort my data by its Y coordinate, what I do by getY() function. Program shuts down there:

BarEntry be = list.get(list.indexOf(newValue));
          list.set(j, be);

In a nutshell:
How can I substitute

arr[j] = newValue;

to collection approach like this (not working):

list.set(j, list.get(list.indexOf(newValue)));

答:
From java doc

```<code>public void add(int index, E element)
</code>```

Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

So no need to shift the rest of the array.

Title: android java insertsort using ArrayList

Body:
First of all, I'm writing program to visualize sorting algorithms on Android
I wrote method for insertion sort algorithm. I'm using MPAndroidChart for it.

    void insertionSort(int[] arr) {
    int i, j, newValue;
    for (i = 1; i < arr.length; i++) {
        newValue = arr[i];
        j = i;
        while (j > 0 && arr[j - 1] > newValue) {
            arr[j] = arr[j - 1];
            j--;
        }
        arr[j] = newValue;
    }
}

...and it works fine. I want to redesign it to get the same result using ArrayList, but unfortunately, it crashes, and I have no idea why! This is my collection approach insertionSort:

void insertionSort(ArrayList<BarEntry> list) {
    int i, j;
    float newValue;
    for (i = 1; i < list.size(); i++) {
        newValue = list.get(i).getY();
        j = i;
        while (j > 0 && list.get(j-1).getY() > newValue) {
            list.set(j, list.get(j-1));
            j--;
        }
        BarEntry be = list.get(list.indexOf(newValue));
        list.set(j, be);
    }
}

BarEntry is class used to create charts. I want to sort my data by its Y coordinate, what I do by getY() function. Program shuts down there:

BarEntry be = list.get(list.indexOf(newValue));
          list.set(j, be);

In a nutshell:
How can I substitute

arr[j] = newValue;

to collection approach like this (not working):

list.set(j, list.get(list.indexOf(newValue)));

Body:
From java doc

public void add(int index, E element)

Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

So no need to shift the rest of the array.


问:
How Can I use Case clause within WHERE condition in this procedure?
I'm writing a simple stored procedure for retrieve information about all employees but, I'd add 2 parameters to retrieve information only one employee if is passed for parameter. My intention is create a cursor and add condition in WHERE using parameters but It is not working for now. Do you have any idea? Thanks!

First parameter is for employee id.

Second parameter is for a raise salary.

The procedure is:

```<code>CREATE OR REPLACE PROCEDURE test6(
        p_empid        empleados.legajo%TYPE := NULL,
        p_raise_salary empleados.sueldo_basico%TYPE := NULL)
IS
    CURSOR c_emps
    IS
        SELECT legajo, apellido, nombre, fecha_alta, sueldo_basico,
               (CASE
                    WHEN p_raise_salary IS NOT NULL THEN
                        sueldo_basico * p_raise_salary
                    ELSE
                        sueldo_Basico
                END) aumento_sueldo_basico
        FROM    empleados
        WHERE  (legajo = p_empid AND fecha_alta IS NOT NULL)
        OR     fecha_alta IS NOT NULL;
BEGIN
    FOR i IN c_emps
    LOOP
        DBMS_OUTPUT.PUT_LINE(
            'NOMBRE: ' || i.apellido || ' ' || i.nombre || ' ' || i.legajo);
        DBMS_OUTPUT.PUT_LINE(
            'Antiguo Sueldo: ' || i.sueldo_basico);
        DBMS_OUTPUT.PUT_LINE(
            'Nuevo Sueldo: ' || i.aumento_sueldo_basico);

        EXIT WHEN c_emps%NOTFOUND;
    END LOOP;
END test6;
</code>```

Second parameter for raise salary is working but when I add a value for id parameter is currently displaying all employees info.

答:
What you want is to select all records if the p_empid is not passed but restrict the result set when it is passed.

The problem is your WHERE clause is not formed tightly enough:

```<code>    WHERE  (legajo = p_empid AND fecha_alta IS NOT NULL)
    OR     fecha_alta IS NOT NULL;
</code>```

Because the condition is specified as a Boolean OR the result sets will include every record where fecha_alta IS NOT NULL, regardless of whether a values is passed in p_empid.

What you need to do is check p_empid in both branches:

```<code>    WHERE  (legajo = p_empid AND fecha_alta IS NOT NULL)
    OR     (p_empid IS NULL AND fecha_alta IS NOT NULL);
</code>```

This version removes the duplication:

```<code>CREATE OR REPLACE PROCEDURE test6(
        p_empid        empleados.legajo%TYPE := NULL,
        p_raise_salary empleados.sueldo_basico%TYPE := NULL)
IS
    CURSOR c_emps
    IS
        SELECT legajo, apellido, nombre, fecha_alta, sueldo_basico,
               (CASE
                    WHEN p_raise_salary IS NOT NULL THEN
                        sueldo_basico * p_raise_salary
                    ELSE
                        sueldo_Basico
                END) aumento_sueldo_basico
        FROM    empleados
        WHERE  (p_empid IS NULL or legajo = p_empid)
        AND    fecha_alta IS NOT NULL;
BEGIN
    FOR i IN c_emps
    LOOP
        DBMS_OUTPUT.PUT_LINE(
            'NOMBRE: ' || i.apellido || ' ' || i.nombre || ' ' || i.legajo);
        DBMS_OUTPUT.PUT_LINE(
            'Antiguo Sueldo: ' || i.sueldo_basico);
        DBMS_OUTPUT.PUT_LINE(
            'Nuevo Sueldo: ' || i.aumento_sueldo_basico);

        EXIT WHEN c_emps%NOTFOUND;
    END LOOP;
END test6;
</code>```

Body:
I'm writing a simple stored procedure for retrieve information about all employees but, I'd add 2 parameters to retrieve information only one employee if is passed for parameter. My intention is create a cursor and add condition in WHERE using parameters but It is not working for now. Do you have any idea? Thanks!

First parameter is for employee id.

Second parameter is for a raise salary.

The procedure is:

CREATE OR REPLACE PROCEDURE test6(
        p_empid        empleados.legajo%TYPE := NULL,
        p_raise_salary empleados.sueldo_basico%TYPE := NULL)
IS
    CURSOR c_emps
    IS
        SELECT legajo, apellido, nombre, fecha_alta, sueldo_basico,
               (CASE
                    WHEN p_raise_salary IS NOT NULL THEN
                        sueldo_basico * p_raise_salary
                    ELSE
                        sueldo_Basico
                END) aumento_sueldo_basico
        FROM    empleados
        WHERE  (legajo = p_empid AND fecha_alta IS NOT NULL)
        OR     fecha_alta IS NOT NULL;
BEGIN
    FOR i IN c_emps
    LOOP
        DBMS_OUTPUT.PUT_LINE(
            'NOMBRE: ' || i.apellido || ' ' || i.nombre || ' ' || i.legajo);
        DBMS_OUTPUT.PUT_LINE(
            'Antiguo Sueldo: ' || i.sueldo_basico);
        DBMS_OUTPUT.PUT_LINE(
            'Nuevo Sueldo: ' || i.aumento_sueldo_basico);

        EXIT WHEN c_emps%NOTFOUND;
    END LOOP;
END test6;

Second parameter for raise salary is working but when I add a value for id parameter is currently displaying all employees info.

Body:
What you want is to select all records if the p_empid is not passed but restrict the result set when it is passed.

The problem is your WHERE clause is not formed tightly enough:

    WHERE  (legajo = p_empid AND fecha_alta IS NOT NULL)
    OR     fecha_alta IS NOT NULL;

Because the condition is specified as a Boolean OR the result sets will include every record where fecha_alta IS NOT NULL, regardless of whether a values is passed in p_empid.

What you need to do is check p_empid in both branches:

    WHERE  (legajo = p_empid AND fecha_alta IS NOT NULL)
    OR     (p_empid IS NULL AND fecha_alta IS NOT NULL);

This version removes the duplication:

CREATE OR REPLACE PROCEDURE test6(
        p_empid        empleados.legajo%TYPE := NULL,
        p_raise_salary empleados.sueldo_basico%TYPE := NULL)
IS
    CURSOR c_emps
    IS
        SELECT legajo, apellido, nombre, fecha_alta, sueldo_basico,
               (CASE
                    WHEN p_raise_salary IS NOT NULL THEN
                        sueldo_basico * p_raise_salary
                    ELSE
                        sueldo_Basico
                END) aumento_sueldo_basico
        FROM    empleados
        WHERE  (p_empid IS NULL or legajo = p_empid)
        AND    fecha_alta IS NOT NULL;
BEGIN
    FOR i IN c_emps
    LOOP
        DBMS_OUTPUT.PUT_LINE(
            'NOMBRE: ' || i.apellido || ' ' || i.nombre || ' ' || i.legajo);
        DBMS_OUTPUT.PUT_LINE(
            'Antiguo Sueldo: ' || i.sueldo_basico);
        DBMS_OUTPUT.PUT_LINE(
            'Nuevo Sueldo: ' || i.aumento_sueldo_basico);

        EXIT WHEN c_emps%NOTFOUND;
    END LOOP;
END test6;


问:
Sharing data between two Redux Reducers/States
Is this a reasonable solution for data sharing between two states/reducers?

```<code>//combineReducers
function coreReducer(state = {}, action){

    let filtersState = filters(state.filters, action);
    let eventsState = events(state.events, action, { filters: filtersState});

    return { events: eventsState, filters : filtersState};

}

export const rootReducer = combineReducers(
    {
        core  : coreReducer,
        users
    }
);
</code>```

If so, how can one guarantee the order in which reducer functions are executed if both answer to the same dispatched event and the second reducing function depends on the new state of the first one?

Let's say that we dispatch a SET_FILTER event that appends to activeFilters collection in the filters Store and later changes the visibility of items in the events Store with respect to the activeFilters values.

```<code>//ActiveFilters reducer
function filtersActions(state = {}, action){

    switch (action.type) {
        case SET_FILTER:
            return Object.assign({}, state, {
                [action.filterType]: action.filter
            })
        case REMOVE_FILTER:
            var temp = Object.assign({}, state);
            delete temp[action.filterType];
            return temp;

        case REMOVE_ALL_FILTERS:
            return {};

        default:
            return state
    }
}
</code>```

I think I found the answer - Computing Derived Data - Reselect

http://redux.js.org/docs/recipes/ComputingDerivedData.html

答:
If you have two reducers, and one depend on a value from a first one, you just have to update them carefully, and the best solution will be just to use a special function, which will first set the filtering, and then query corresponding events. Also, keep in mind that if events fetching is asynchronous operation, you should also nest based on filtering type -- otherwise there is a chance of race condition, and you will have wrong events.

I have created a library redux-tiles to deal with verbosity of raw redux, so I will use it in this example:

```<code>import { createSyncTile, createTile } from 'redux-tiles';

const filtering = createSyncTile({
  type: ['ui', 'filtering'],
  fn: ({ params }) => params.type,
});

const events = createTile({
  type: ['api', 'events'],
  fn: ({ api, params }) => api.get('/events', { type: params.type }),
  nesting: ({ type }) => [type],
});

// this function will just fetch events, but we will connect to apiEvents
// and filter by type
const fetchEvents = createTile({
  type: ['api', 'fetchEvents'],
  fn: ({ selectors, getState, dispatch, actions }) => {
    const type = selectors.ui.filtering(getState());
    return dispatch(actions.api.events({ type }));
  },
});
</code>```

Body:
Is this a reasonable solution for data sharing between two states/reducers?

//combineReducers
function coreReducer(state = {}, action){

    let filtersState = filters(state.filters, action);
    let eventsState = events(state.events, action, { filters: filtersState});

    return { events: eventsState, filters : filtersState};

}

export const rootReducer = combineReducers(
    {
        core  : coreReducer,
        users
    }
);

If so, how can one guarantee the order in which reducer functions are executed if both answer to the same dispatched event and the second reducing function depends on the new state of the first one?

Let's say that we dispatch a SET_FILTER event that appends to activeFilters collection in the filters Store and later changes the visibility of items in the events Store with respect to the activeFilters values.

//ActiveFilters reducer
function filtersActions(state = {}, action){

    switch (action.type) {
        case SET_FILTER:
            return Object.assign({}, state, {
                [action.filterType]: action.filter
            })
        case REMOVE_FILTER:
            var temp = Object.assign({}, state);
            delete temp[action.filterType];
            return temp;

        case REMOVE_ALL_FILTERS:
            return {};

        default:
            return state
    }
}

I think I found the answer - Computing Derived Data - Reselect

http://redux.js.org/docs/recipes/ComputingDerivedData.html

Body:
If you have two reducers, and one depend on a value from a first one, you just have to update them carefully, and the best solution will be just to use a special function, which will first set the filtering, and then query corresponding events. Also, keep in mind that if events fetching is asynchronous operation, you should also nest based on filtering type -- otherwise there is a chance of race condition, and you will have wrong events.

I have created a library redux-tiles to deal with verbosity of raw redux, so I will use it in this example:

import { createSyncTile, createTile } from 'redux-tiles';

const filtering = createSyncTile({
  type: ['ui', 'filtering'],
  fn: ({ params }) => params.type,
});

const events = createTile({
  type: ['api', 'events'],
  fn: ({ api, params }) => api.get('/events', { type: params.type }),
  nesting: ({ type }) => [type],
});

// this function will just fetch events, but we will connect to apiEvents
// and filter by type
const fetchEvents = createTile({
  type: ['api', 'fetchEvents'],
  fn: ({ selectors, getState, dispatch, actions }) => {
    const type = selectors.ui.filtering(getState());
    return dispatch(actions.api.events({ type }));
  },
});


问:
bash: oneliner to convert hex numbers in output to decimals
Does anyone know of a oneliner into which some output can be piped into in bash, to match and convert all occurrences of hexadecimal numbers and leave all other text untouched?

maybe match rather arbitrary output which could be a hexadecimal
shall somehow converted through a regexp, i.e.
/(0x)?[0-9a-fA-F]{5,}/

a leading 0x shall not be neccessary, but
also be handled properly

there can be false-positives, if not
specifying a minimum length of the numbers, but that should not be an
issue

the goal is to find solution which can be used with as much possible outputs having hex numbers in them

It should work on output like:

```<code>ssg sjas # cat /proc/net/stat/arp_cache | column -t
entries   allocs    destroys  hash_grows  lookups   hits      res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
0000000d  00000006  00000004  00000000    0000c3b9  0000c35e  00000000    00000000          00000000          0000965b          00000000        00000000             00000000
0000000d  0000000d  00000004  00000001    00000000  00000000  00000000    00000000          00000000          000007cd          00000000        00000000             00000000
0000000d  00000008  00000008  00000001    00000000  00000000  00000000    00000000          00000000          000006e0          00000000        00000000             00000000
0000000d  0000000a  00000008  00000000    00000000  00000000  00000002    00000000          00000000          00000704          00000000        00000000             00000000
</code>```

Most other questions on stackoverflow only tackle the issue of how to convert single numbers between number systems, only do the conversion for a specified column or completely kill the formatting being present in the input.

Desired output should look like: (column -t is there anyway, it really just need to replace the hex values it can find, and adding leading zeroes to a printf statement is also not a problem)

```<code>ssg sjas # cat /proc/net/stat/arp_cache | perl -pe 's/(?:0x)?[0-9a-f]{5,}/hex($&)/ge' | column -t
entries  allocs  destroys  hash_grows  lookups  hits   res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
13       6       4         0           50105    50014  0           0                 0                 38491             0               0                    0
13       13      4         1           0        0      0           0                 0                 1997              0               0                    0
13       8       8         1           0        0      0           0                 0                 1760              0               0                    0
13       10      8         0           0        0      2           0                 0                 1796              0               0                    0
</code>```

I could not find a short viable/reliable solution via sed/awk/perl in the last two hours, so I came here for help.

答:
perl using e flag to substitution</p>

```<code>perl -pe 's/(0x)?[0-9a-f]{5,}/hex $&/ge' file | column -t
</code>```

Body:
Does anyone know of a oneliner into which some output can be piped into in bash, to match and convert all occurrences of hexadecimal numbers and leave all other text untouched?

maybe match rather arbitrary output which could be a hexadecimal
shall somehow converted through a regexp, i.e.
/(0x)?[0-9a-fA-F]{5,}/

a leading 0x shall not be neccessary, but
also be handled properly

there can be false-positives, if not
specifying a minimum length of the numbers, but that should not be an
issue

the goal is to find solution which can be used with as much possible outputs having hex numbers in them

It should work on output like:

ssg sjas # cat /proc/net/stat/arp_cache | column -t
entries   allocs    destroys  hash_grows  lookups   hits      res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
0000000d  00000006  00000004  00000000    0000c3b9  0000c35e  00000000    00000000          00000000          0000965b          00000000        00000000             00000000
0000000d  0000000d  00000004  00000001    00000000  00000000  00000000    00000000          00000000          000007cd          00000000        00000000             00000000
0000000d  00000008  00000008  00000001    00000000  00000000  00000000    00000000          00000000          000006e0          00000000        00000000             00000000
0000000d  0000000a  00000008  00000000    00000000  00000000  00000002    00000000          00000000          00000704          00000000        00000000             00000000

Most other questions on stackoverflow only tackle the issue of how to convert single numbers between number systems, only do the conversion for a specified column or completely kill the formatting being present in the input.

Desired output should look like: (column -t is there anyway, it really just need to replace the hex values it can find, and adding leading zeroes to a printf statement is also not a problem)

ssg sjas # cat /proc/net/stat/arp_cache | perl -pe 's/(?:0x)?[0-9a-f]{5,}/hex($&)/ge' | column -t
entries  allocs  destroys  hash_grows  lookups  hits   res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
13       6       4         0           50105    50014  0           0                 0                 38491             0               0                    0
13       13      4         1           0        0      0           0                 0                 1997              0               0                    0
13       8       8         1           0        0      0           0                 0                 1760              0               0                    0
13       10      8         0           0        0      2           0                 0                 1796              0               0                    0

I could not find a short viable/reliable solution via sed/awk/perl in the last two hours, so I came here for help.

Body:
perl using e flag to substitution

perl -pe 's/(0x)?[0-9a-f]{5,}/hex $&/ge' file | column -t


问:
c# printing ID, name and birthdate from sql table using Entity Framework 6
I want to print the Id, name and birthdate of entities from "Clients" table in sql using entity framework 6. so far i managed to print out one coloumn at a time but now combining Int with String and DateTime gives me an error: "Operator && cannot be applied to operands of type 'int' and 'string'.

this is my code which i was trying to combine those types. am i missing a method of combining those type together unlike SQL?

```<code>var clientsList = (from c in context.Clients
                               orderby c.birthdate ascending
                               select c.ID && c.name && c.birthdate);

            foreach (var c in clientsList)
            {
                Console.WriteLine(c);
            }
</code>```

答:
you could also </p>

```<code>var clientsList = (from c in context.Clients
                   orderby c.birthdate ascending);

foreach (var c in clientsList)
{
    Console.WriteLine(string.Format("ClientID:{0}, ClientName:{1}, ClientBirthDate:{2}",c.ID,c.name,c.birthdate));
}
</code>```

Body:
I want to print the Id, name and birthdate of entities from "Clients" table in sql using entity framework 6. so far i managed to print out one coloumn at a time but now combining Int with String and DateTime gives me an error: "Operator && cannot be applied to operands of type 'int' and 'string'.

this is my code which i was trying to combine those types. am i missing a method of combining those type together unlike SQL?

var clientsList = (from c in context.Clients
                               orderby c.birthdate ascending
                               select c.ID && c.name && c.birthdate);

            foreach (var c in clientsList)
            {
                Console.WriteLine(c);
            }

Body:
you could also

var clientsList = (from c in context.Clients
                   orderby c.birthdate ascending);

foreach (var c in clientsList)
{
    Console.WriteLine(string.Format("ClientID:{0}, ClientName:{1}, ClientBirthDate:{2}",c.ID,c.name,c.birthdate));
}


问:
sql case statement IN with group by
I have a 2 column table with the columns : "user_name" and "characteristic".   Each user_name may appear multiple times with a different characteristic.

The values in characteristic are:

Online

Instore

Account

Email

I want to write a sql statement that goes like this - but obviously this isn't working:

```<code>SELECT user_name,
       case
          when characteristic in ("online","instore") then 1
          else 0
       END as purchase_yn,
       case
          when characteristic in ("online","instore") and
               characteristic in ("email",'account')   then 1
          else 0
       END as   purchaser_with_account
 FROM my_table
 GROUP BY user_name;
</code>```

Essentially the first is a flag where I check for the presence of either value for that user_name.
The Second field  is that they  meet this criteria AND that they meet the criteria for having either 'email' or 'account'

答:
You haven't mentioned a specific RDBMS, but if SUM(DISTINCT ...) is available the following is quite nice:

```<code>SELECT
    username,
    SUM(DISTINCT
        CASE
            WHEN characteristic in ('online','instore') THEN 1
            ELSE 0
        END) AS purchase_yn,
    CASE WHEN (
        SUM(DISTINCT
            CASE
                WHEN characteristic in ('online','instore') THEN 1
                WHEN characteristic in ('email','account') THEN 2
            ELSE 0 END
       )
    ) = 3 THEN 1 ELSE 0 END as purchaser_with_account
FROM
    my_table
GROUP BY
    username
</code>```

Title: sql case statement IN with group by

Body:
I have a 2 column table with the columns : "user_name" and "characteristic".   Each user_name may appear multiple times with a different characteristic.

The values in characteristic are:

Online

Instore

Account

Email

I want to write a sql statement that goes like this - but obviously this isn't working:

SELECT user_name,
       case
          when characteristic in ("online","instore") then 1
          else 0
       END as purchase_yn,
       case
          when characteristic in ("online","instore") and
               characteristic in ("email",'account')   then 1
          else 0
       END as   purchaser_with_account
 FROM my_table
 GROUP BY user_name;

Essentially the first is a flag where I check for the presence of either value for that user_name.
The Second field  is that they  meet this criteria AND that they meet the criteria for having either 'email' or 'account'

Body:
You haven't mentioned a specific RDBMS, but if SUM(DISTINCT ...) is available the following is quite nice:

SELECT
    username,
    SUM(DISTINCT
        CASE
            WHEN characteristic in ('online','instore') THEN 1
            ELSE 0
        END) AS purchase_yn,
    CASE WHEN (
        SUM(DISTINCT
            CASE
                WHEN characteristic in ('online','instore') THEN 1
                WHEN characteristic in ('email','account') THEN 2
            ELSE 0 END
       )
    ) = 3 THEN 1 ELSE 0 END as purchaser_with_account
FROM
    my_table
GROUP BY
    username


问:
Checking for equality of RDDs
I making some tests in JUnit and I need to check the equality of two Spark RDDs.

A way I thought of doing it is this:

```<code>JavaRDD<SomeClass> expResult = ...;
JavaRDD<SomeClass> result = ...;

assertEquals(expResult.collect(), result.collect());
</code>```

Is there a better way than this?

答:
In my case, using Spark into Java, just use the collect method didn't worked. The result of assertEquals was always false.

So this test:

```<code>assertEquals(
  this.fooExpectedRddTest.collect(),
  this.fooServiceTest.getRdd().collect()
);
</code>```

Generate this result:

```<code>FooServiceTest.getRdd:143 expected:

scala.collection.convert.Wrappers$SeqWrapper<[
    {"a":1,"b":2,"c":1496405614},
    {"a":1,"b":3,"c":1496243614},
    {"a":2,"b":2,"c":1496416414}
]>

but was:

scala.collection.convert.Wrappers$SeqWrapper<[
    {"a":1,"b":2,"c":1496405614},
    {"a":1,"b":3,"c":1496243614},
    {"a":2,"b":2,"c":1496416414}
]>
</code>```

My way to deal with that was converting them into something more easy to compare

```<code>List<Tuple3<Integer,Integer,Double>> expectedList = this.fooExpectedRddTest.map(
        (Foo foo) -> {
            return new Tuple3<Integer,Integer,Double>(
                    foo.getA(),
                    foo.getB(),
                    foo.getC()
            );
        }
).collect();

List<Tuple3<Integer,Integer,Double>> receivedList = this.fooServiceTest.getRdd().map(
        (Foo foo) -> {
            return new Tuple3<Integer,Integer,Double>(
                    foo.getA(),
                    foo.getB(),
                    foo.getC()
            );
        }
).collect();

assertEquals(
    expectedList,
    receivedList
);
</code>```

Title: Checking for equality of RDDs

Body:
I making some tests in JUnit and I need to check the equality of two Spark RDDs.

A way I thought of doing it is this:

JavaRDD<SomeClass> expResult = ...;
JavaRDD<SomeClass> result = ...;

assertEquals(expResult.collect(), result.collect());

Is there a better way than this?

Body:
In my case, using Spark into Java, just use the collect method didn't worked. The result of assertEquals was always false.

So this test:

assertEquals(
  this.fooExpectedRddTest.collect(),
  this.fooServiceTest.getRdd().collect()
);

Generate this result:

FooServiceTest.getRdd:143 expected:

scala.collection.convert.Wrappers$SeqWrapper<[
    {"a":1,"b":2,"c":1496405614},
    {"a":1,"b":3,"c":1496243614},
    {"a":2,"b":2,"c":1496416414}
]>

but was:

scala.collection.convert.Wrappers$SeqWrapper<[
    {"a":1,"b":2,"c":1496405614},
    {"a":1,"b":3,"c":1496243614},
    {"a":2,"b":2,"c":1496416414}
]>

My way to deal with that was converting them into something more easy to compare

List<Tuple3<Integer,Integer,Double>> expectedList = this.fooExpectedRddTest.map(
        (Foo foo) -> {
            return new Tuple3<Integer,Integer,Double>(
                    foo.getA(),
                    foo.getB(),
                    foo.getC()
            );
        }
).collect();

List<Tuple3<Integer,Integer,Double>> receivedList = this.fooServiceTest.getRdd().map(
        (Foo foo) -> {
            return new Tuple3<Integer,Integer,Double>(
                    foo.getA(),
                    foo.getB(),
                    foo.getC()
            );
        }
).collect();

assertEquals(
    expectedList,
    receivedList
);


问:
Why are these templates ambiguous?
The book C++ Templates : The Complete Guide has an example on page 275 that I'm having trouble wrapping my head around.

Quoting excerpts from the book...

```<code>template <typename T>
class Promotion<T,T> {
  public:
    typdef T ResultT;
};

template<typename T1, typename T2>
class Promotion<Array<T1>, Array<T2> > {
  public:
    typedef Array<typename Promotion<T1,T2>::ResultT> ResultT;
};

template<typename T>
class Promotion<Array<T>, Array<T> > {
  public:
    typedef Array<typename Promotion<T,T>::ResultT> ResultT;
};
</code>```

Unfortunately, the partial specialization Promotion<Array<T1>, Array<T2> > is
  neither more nor less specialized than the partial specialization
  Promotion<T,T>. To avoid template selection ambiguity, the last partial
  specialization was added. It is more specialized than either of the previous
  two partial specializations.

Why are the first two templates ambiguous, and why does the last template solve the ambiguity issue? When I try to apply the rules I either can't figure out how it comes up with an ambiguity, or if I think I have a way for it to happen I don't know why the last template solves the problem.

答:
It's because while deducing parameters, one template is better for the first parameter, but the other is better for the second.

Let's look at Promotion< Array<S>, Array<S> >.

Both candidates can match.  On the first parameter, Promotion< T, T > matches by deducing T = Array<S>.  Promotion< T1, T2 > matches by deducing T1 = S.  The second one is a better match, since Array<T1> is more specific than T.

On the second parameter, Promotion< T = Array<S>, T = Array<S> > is an exact match.  Promotion< T1 = S, T2 > matches by deducing T2 = S.  Since Array<S> is a better match than Array<T2>, the first is more specific.

The rules for choosing the best template say that one parameter has to be a better match, and all the other be no worse, as compared to all other candidates.  Since no candidate meets these criteria, it is ambiguous.

The third specialization does meet the criteria (first parameter is as good as Array<T1>, second is perfect), so it resolves the ambiguity.

If you REALLY want to make your head spin, try reading section [temp.deduct.partial] in the standard, where all these rules are stated in good lawyer-ese. It's 14.8.2.4 in draft n3225, numbering may vary in other versions.

Title: Why are these templates ambiguous?

Body:
The book C++ Templates : The Complete Guide has an example on page 275 that I'm having trouble wrapping my head around.

Quoting excerpts from the book...

template <typename T>
class Promotion<T,T> {
  public:
    typdef T ResultT;
};

template<typename T1, typename T2>
class Promotion<Array<T1>, Array<T2> > {
  public:
    typedef Array<typename Promotion<T1,T2>::ResultT> ResultT;
};

template<typename T>
class Promotion<Array<T>, Array<T> > {
  public:
    typedef Array<typename Promotion<T,T>::ResultT> ResultT;
};

Unfortunately, the partial specialization Promotion<Array<T1>, Array<T2> > is
  neither more nor less specialized than the partial specialization
  Promotion<T,T>. To avoid template selection ambiguity, the last partial
  specialization was added. It is more specialized than either of the previous
  two partial specializations.

Why are the first two templates ambiguous, and why does the last template solve the ambiguity issue? When I try to apply the rules I either can't figure out how it comes up with an ambiguity, or if I think I have a way for it to happen I don't know why the last template solves the problem.


答:
An example the structure of your data would help better understand what you are trying to accomplish.  But I think I get what you are trying to do.

You have to use an aggregate function in order to use a group by.
Something like SUM or AVG.

But you need first to build a pivot of your data and then you could use that pivot to check for your criterias:

This would create a table pivot that shows for each record what criterias are met:

```<code>SELECT
   user_name,
   case when characteristic = "online"  then 1 else 0 end as online_yn,
   case when characteristic = "instore" then 1 else 0 end as instore_yn,
   case when characteristic = "account" then 1 else 0 end as account_yn,
   case when characteristic = "email"   then 1 else 0 end as email_yn,
FROM my_table
</code>```

Now what you might wanted to do is to create an averaged version of these entries grouped by user_name and use those averages to create the fields you wanted.  For that you need to use the same statement created earlier as an inline table :

```<code>Select
   user_name,
   case when avg(online_yn + instore_yn) >= 1 then 1 else 0 end as purchase_yn,
   case when avg(online_yn + instore_yn) >= 1 and avg(email_yn + account_yn) >= 1 then 1 else 0 end as purchaser_with_account
From
    (SELECT
       user_name,
       case when characteristic = "online"  then 1 else 0 end as online_yn,
       case when characteristic = "instore" then 1 else 0 end as instore_yn,
       case when characteristic = "account" then 1 else 0 end as account_yn,
       case when characteristic = "email"   then 1 else 0 end as email_yn,
     FROM my_table) avg_table

group by
   user_name;
</code>```

This should help.

It may not be efficient in terms of performance but you'll get what you want.

Title: sql case statement IN with group by

Body:
An example the structure of your data would help better understand what you are trying to accomplish.  But I think I get what you are trying to do.

You have to use an aggregate function in order to use a group by.
Something like SUM or AVG.

But you need first to build a pivot of your data and then you could use that pivot to check for your criterias:

This would create a table pivot that shows for each record what criterias are met:

SELECT
   user_name,
   case when characteristic = "online"  then 1 else 0 end as online_yn,
   case when characteristic = "instore" then 1 else 0 end as instore_yn,
   case when characteristic = "account" then 1 else 0 end as account_yn,
   case when characteristic = "email"   then 1 else 0 end as email_yn,
FROM my_table

Now what you might wanted to do is to create an averaged version of these entries grouped by user_name and use those averages to create the fields you wanted.  For that you need to use the same statement created earlier as an inline table :

Select
   user_name,
   case when avg(online_yn + instore_yn) >= 1 then 1 else 0 end as purchase_yn,
   case when avg(online_yn + instore_yn) >= 1 and avg(email_yn + account_yn) >= 1 then 1 else 0 end as purchaser_with_account
From
    (SELECT
       user_name,
       case when characteristic = "online"  then 1 else 0 end as online_yn,
       case when characteristic = "instore" then 1 else 0 end as instore_yn,
       case when characteristic = "account" then 1 else 0 end as account_yn,
       case when characteristic = "email"   then 1 else 0 end as email_yn,
     FROM my_table) avg_table

group by
   user_name;

This should help.

It may not be efficient in terms of performance but you'll get what you want.


问:
Behat, Mink and Selenium. How to check a checkbox?
I am getting an error when trying to check a checkbox with Behat/Mink/Selenium.  Below is my setup and a description of my error.

behat.yml

```<code>default:
    extensions:
        Behat\MinkExtension:
            goutte: ~
            selenium2: ~
</code>```

composer.json

```<code>{
    "require": {
        "behat/behat": "~3.3",
        "behat/mink-extension": "~2.2",
        "behat/mink-goutte-driver": "~1.2",
        "behat/mink-selenium2-driver": "~1.3"
    },
    "config": {
        "bin-dir": "bin/"
    }
</code>```

}

I run selenium 3.4.0 like this (including a gecko driver)

```<code>java -Dwebdriver.gecko.driver=/home/ubuntu/path/to/geckodriver -jar selenium-server-standalone-3.4.0.jar
</code>```

FeatureContext Class:

```<code><?php

use Behat\MinkExtension\Context\MinkContext;
use Behat\Behat\Tester\Exception\PendingException;

/**
 * Defines application features from the specific context.
 */
class FeatureContext extends MinkContext
{
}

?>
</code>```

The feature under test

```<code>Feature: Search
    In order to use behat
    As a tester
    I need to be able to get all these componets to work!

    @javascript
    Scenario: A very simple test of behat functionality
        Given I am on "http://behat-testing.christaylordeveloper.co.uk/"
        Then I should see "MY BLOG"
        And the "#slave-para" element should not contain "Hi there"
        When I check "test-cb"
        Then the "#slave-para" element should contain "Hi there"
</code>```

The error

this is the output of the test showing a mouseMoveTo error

```<code>ubuntu@ip-172-31-7-6:~/behat-tests$ bin/behat
Feature: Search
  In order to use behat
    As a tester
    I need to be able to get all these componets to work!

  @javascript
  Scenario: A very simple test of behat functionality                # features/simple-test.feature:7
    Given I am on "http://behat-testing.christaylordeveloper.co.uk/" # FeatureContext::visit()
    Then I should see "MY BLOG"                                      # FeatureContext::assertPageContainsText()
    And the "#slave-para" element should not contain "Hi there"      # FeatureContext::assertElementNotContains()
    When I check "test-cb"                                           # FeatureContext::checkOption()
      mouseMoveTo
      Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
      System info: host: 'ip-172-31-7-6', ip: '172.31.7.6', os.name: 'Linux', os.arch: 'amd64', os.version: '4.4.0-1018-aws', java.version: '1.8.0_131'
      Driver info: driver.version: RemoteWebDriver (WebDriver\Exception\UnknownCommand)
    Then the "#slave-para" element should contain "Hi there"         # FeatureContext::assertElementContains()

--- Failed scenarios:

    features/simple-test.feature:7

1 scenario (1 failed)
5 steps (3 passed, 1 failed, 1 skipped)
0m3.75s (10.46Mb)
</code>```

If I comment-out the @javascript tag and comment-out the last step of the scenario (which involves javascript) it passes just fine.

How can I test with javascript without this mouseMoveTo error?

Thank you

Update Number 2:

I now have this working using chromedriver version 2.32 and selenium standalone server 3.5.3

I run the server from the command line like this:

```<code>java -Dwebdriver.chrome.driver=chromedriver -jar selenium-server-standalone-3.5.3.jar
</code>```

My behat.yml is

```<code>default:
    extensions:
        Behat\MinkExtension:
            goutte: ~
            selenium2: ~
            browser_name: 'chrome'
</code>```

答:
For checking the checbox MinkContext already has predefined methods, such as checkOption(optionName) and uncheckOption(optionName)
Documentation says:

Checks checkbox with specified id|name|label|value

Example: When I check "Pearl Necklace"

Example: And I check "Pearl Necklace"

As this method is in MinkContext you can use it from your .feature file like:

```<code>When I check "accept_checkbox"
</code>```

Or in your FeatureContext.php file like

```<code>$this->checkOption('optionIdentifier')
</code>```

MinkContext link has a lot of predefined methods, check them out!

Body:
I am getting an error when trying to check a checkbox with Behat/Mink/Selenium.  Below is my setup and a description of my error.

behat.yml

default:
    extensions:
        Behat\MinkExtension:
            goutte: ~
            selenium2: ~

composer.json

{
    "require": {
        "behat/behat": "~3.3",
        "behat/mink-extension": "~2.2",
        "behat/mink-goutte-driver": "~1.2",
        "behat/mink-selenium2-driver": "~1.3"
    },
    "config": {
        "bin-dir": "bin/"
    }

}

I run selenium 3.4.0 like this (including a gecko driver)

java -Dwebdriver.gecko.driver=/home/ubuntu/path/to/geckodriver -jar selenium-server-standalone-3.4.0.jar

FeatureContext Class:

<?php

use Behat\MinkExtension\Context\MinkContext;
use Behat\Behat\Tester\Exception\PendingException;

/**
 * Defines application features from the specific context.
 */
class FeatureContext extends MinkContext
{
}

?>

The feature under test

Feature: Search
    In order to use behat
    As a tester
    I need to be able to get all these componets to work!

    @javascript
    Scenario: A very simple test of behat functionality
        Given I am on "http://behat-testing.christaylordeveloper.co.uk/"
        Then I should see "MY BLOG"
        And the "#slave-para" element should not contain "Hi there"
        When I check "test-cb"
        Then the "#slave-para" element should contain "Hi there"

The error

this is the output of the test showing a mouseMoveTo error

ubuntu@ip-172-31-7-6:~/behat-tests$ bin/behat
Feature: Search
  In order to use behat
    As a tester
    I need to be able to get all these componets to work!

  @javascript
  Scenario: A very simple test of behat functionality                # features/simple-test.feature:7
    Given I am on "http://behat-testing.christaylordeveloper.co.uk/" # FeatureContext::visit()
    Then I should see "MY BLOG"                                      # FeatureContext::assertPageContainsText()
    And the "#slave-para" element should not contain "Hi there"      # FeatureContext::assertElementNotContains()
    When I check "test-cb"                                           # FeatureContext::checkOption()
      mouseMoveTo
      Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
      System info: host: 'ip-172-31-7-6', ip: '172.31.7.6', os.name: 'Linux', os.arch: 'amd64', os.version: '4.4.0-1018-aws', java.version: '1.8.0_131'
      Driver info: driver.version: RemoteWebDriver (WebDriver\Exception\UnknownCommand)
    Then the "#slave-para" element should contain "Hi there"         # FeatureContext::assertElementContains()

--- Failed scenarios:

    features/simple-test.feature:7

1 scenario (1 failed)
5 steps (3 passed, 1 failed, 1 skipped)
0m3.75s (10.46Mb)

If I comment-out the @javascript tag and comment-out the last step of the scenario (which involves javascript) it passes just fine.

How can I test with javascript without this mouseMoveTo error?

Thank you

Update Number 2:

I now have this working using chromedriver version 2.32 and selenium standalone server 3.5.3

I run the server from the command line like this:

java -Dwebdriver.chrome.driver=chromedriver -jar selenium-server-standalone-3.5.3.jar

My behat.yml is

default:
    extensions:
        Behat\MinkExtension:
            goutte: ~
            selenium2: ~
            browser_name: 'chrome'

Body:
For checking the checbox MinkContext already has predefined methods, such as checkOption(optionName) and uncheckOption(optionName)
Documentation says:

Checks checkbox with specified id|name|label|value

Example: When I check "Pearl Necklace"

Example: And I check "Pearl Necklace"

As this method is in MinkContext you can use it from your .feature file like:

When I check "accept_checkbox"

Or in your FeatureContext.php file like

$this->checkOption('optionIdentifier')

MinkContext link has a lot of predefined methods, check them out!


问:
empty values from ng-repeat json
Why this is not working?

  {{ '{{ names }}' }}

Hello {{'{{ item.age}}'}}!

```

<pre class="lang-js prettyprint-override"><code>  var app = angular.module('myapp', []);
  app.controller('myctrl', ["$scope",function($scope){
    $scope.name = [ { "age": "3" },
        {"age" : "2"}];
  }]);
</code>```

It prints me all the ages but it can't access the numbers. It doesn't print anything.

答: change $scope.name to $scope.names

Title: empty values from ng-repeat json

Body:
Why this is not working?

  {{ '{{ names }}' }}

Hello {{'{{ item.age}}'}}!

  var app = angular.module('myapp', []);
  app.controller('myctrl', ["$scope",function($scope){
    $scope.name = [ { "age": "3" },
        {"age" : "2"}];
  }]);

It prints me all the ages but it can't access the numbers. It doesn't print anything.

Body: change $scope.name to $scope.names


问:
How to Modify default separator for CTAGS generated tag file
The default separator is tab character which is \t. However, if there are comments in a line of code being analyzed it messes up the format of the generated tag file. How to Modify default separator for CTAGS generated tag file?</p>

答:
You may like xformat feature of Universal-ctags. With the feature you can define your own format of output.

```<code>[jet@localhost]~/var/ctags% cat input.c

#define ZERO 0
int main(void)
{
    return ZERO;
}
[jet@localhost]~/var/ctags% ./ctags -x --_xformat='(N, K, L) = ("%{name}", "%{kind}", %{line})' input.c

(N, K, L) = ("ZERO", "macro", 1)
(N, K, L) = ("main", "function", 2)
</code>```

http://docs.ctags.io/en/latest/news.html#customizing-xref-output may give you more hints.

Body:
You may like xformat feature of Universal-ctags. With the feature you can define your own format of output.

[jet@localhost]~/var/ctags% cat input.c

#define ZERO 0
int main(void)
{
    return ZERO;
}
[jet@localhost]~/var/ctags% ./ctags -x --_xformat='(N, K, L) = ("%{name}", "%{kind}", %{line})' input.c

(N, K, L) = ("ZERO", "macro", 1)
(N, K, L) = ("main", "function", 2)

http://docs.ctags.io/en/latest/news.html#customizing-xref-output may give you more hints.


问:
When and how to use POST, PUT, and Delete method in Web API
I am new to Web API and the tutorial I was watching uses Fiddler to sniff and send request.

My question is how to use the post, put and delete methods without using fiddler and where are these usually used in the when creating in software development? Fiddler allows you to compose a request body how about the browser though?

I don't seem to understand why you are only able to use these on a sniffing tool. I understand that I am most probably speaking out of ignorance.

答:
If you simply want to create requests using some tool, then you can use tools like Fiddler, Postman, curl, etc. - as you have stated, Fiddler can also be used to monitor as well as create requests.

If you want to go beyond that,

you have HttpClient, WebClient to build requests on your own, and for testing.

If you want to get "full control" then look into HttpWebRequest.

VS debugging tools will allow you to inspect the full flow  - from request to response - using things like breakpoints, watch, etc.

See previous/other answers if you want to build/create requests client-side (Javascript / XMLHttpRequest)

Hth.


问:
For loop does not complete inside Promise
I'm trying to write a function that includes a for loop inside a Promise, however the loop only performs on iteration and the promise is never resolved.

My code looks like this:

```<code>function appendPosts() {
    return functionThatReturnsAPromise()
       .then( result => {
           return new Promise( (resolve, reject) => {
              var list = [];
              result.forEach( item => {
                 //do stuff to item
                 list.push(item);
              });
             resolve(list);
           });
       })
       .then( list => {
          return new Promise( (resolve, reject) => {
             //This loop only runs once, even when list has contains many items
          for ( var i = 0; i < list.length; i++ ) {
             document.querySelector("someSelector").appendChild( list[i] );
          }
          resolve();
       });
   });
}
</code>```

Clearly I'm doing something wrong. Any ideas?

Thanks for your time.
- Daniel

答: @MaazSyedAdeeb is right. There was an exception thrown in the loop and I didn't have a catch block in place. Thanks.</p>

Body:
I'm trying to write a function that includes a for loop inside a Promise, however the loop only performs on iteration and the promise is never resolved.

My code looks like this:

function appendPosts() {
    return functionThatReturnsAPromise()
       .then( result => {
           return new Promise( (resolve, reject) => {
              var list = [];
              result.forEach( item => {
                 //do stuff to item
                 list.push(item);
              });
             resolve(list);
           });
       })
       .then( list => {
          return new Promise( (resolve, reject) => {
             //This loop only runs once, even when list has contains many items
          for ( var i = 0; i < list.length; i++ ) {
             document.querySelector("someSelector").appendChild( list[i] );
          }
          resolve();
       });
   });
}

Clearly I'm doing something wrong. Any ideas?

Thanks for your time.
- Daniel


问:
Read input stream twice
How do you read the same inputstream twice? Is it possible to copy it somehow?

I need to get a image from web, save it locally and then return the saved image. I just thought it would be faster to use the same stream instead of starting a new stream to the downloaded content and then read it again.

答:
How about:</p>

```<code>if (stream.markSupported() == false) {

        // lets replace the stream object
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(stream, baos);
        stream.close();
        stream = new ByteArrayInputStream(baos.toByteArray());
        // now the stream should support 'mark' and 'reset'

    }
</code>```

ContentLicense: CC BY-SA 4.0

Title: Read input stream twice

Body:
How about:

if (stream.markSupported() == false) {

        // lets replace the stream object
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(stream, baos);
        stream.close();
        stream = new ByteArrayInputStream(baos.toByteArray());
        // now the stream should support 'mark' and 'reset'

    }


问:
Framework 7 Vue2: Error in Mounted Hook for this.$f7
I'm trying to use the Framework 7 api for

this.$f7.showPreloader()

```<code> mounted() {
this.getPosts();
</code>```

},

```<code>methods: {
  getPosts() {
    this.$f7.showPreloader();
    var self = this
    axios.get('http://jsonplaceholder.typicode.com/posts')
        .then(response => {
          self.posts = response.data
          self.$f7.hidePreloader();
        })
        .catch(e => {
          this.errors.push(e)
        })
},
</code>```

When the app loads, it gives a Error in mounted hook: "TypeError: this.$f7 is undefined". However when I call it as a @click event, it works

```<code>clickme() {
    this.getPosts();
},
</code>```

How do I call the F7 api object from the mounted event hook correctly?

答:
Ok, this may not be the final answer but this is the best I got.

There is a special hook for f7 Vue called

```<code>methods: {

onF7Init: function () {
    //do some code here
    });
  }
}
</code>```

This a special hook that occurs after F7 framework has been init after mounted. Put it in your methods. Apparently nobody wrote this in the documentation. If you put window.f7 here, the object will be defined and you can use it.

Body:
I'm trying to use the Framework 7 api for

this.$f7.showPreloader()

 mounted() {
this.getPosts();

},

methods: {
  getPosts() {
    this.$f7.showPreloader();
    var self = this
    axios.get('http://jsonplaceholder.typicode.com/posts')
        .then(response => {
          self.posts = response.data
          self.$f7.hidePreloader();
        })
        .catch(e => {
          this.errors.push(e)
        })
},

When the app loads, it gives a Error in mounted hook: "TypeError: this.$f7 is undefined". However when I call it as a @click event, it works

clickme() {
    this.getPosts();
},

How do I call the F7 api object from the mounted event hook correctly?

Body:
Ok, this may not be the final answer but this is the best I got.

There is a special hook for f7 Vue called

methods: {

onF7Init: function () {
    //do some code here
    });
  }
}

This a special hook that occurs after F7 framework has been init after mounted. Put it in your methods. Apparently nobody wrote this in the documentation. If you put window.f7 here, the object will be defined and you can use it.


问:
sql calculating minutes for two dates between two times
I have a table with two DateTimes (StartDateTime, EndDateTime) and I want to calculate the minutes between the two.

Now, I know to use the DATEDIFF() function to get this, but I only want to get the number of minutes that fall between two TIME(0) values.

For example:

```<code>  StartDateTime     | EndDateTime         | TimeStart | TimeEnd
2017-06-01 03:00:00 | 2017-06-01 23:00:00 | 06:00:00  | 20:00:00
</code>```

For the above example, I would get:
   DATEDIFF(minute, StartDateTime, EndDateTime) = 1200.

However, I want to only get the number of minutes that fall between TimeStart and TimeEnd, which would be 840.

How can I write my query to get this?

答:
In SQL Server, DATEDIFF() works on time values, so you can do:

```<code>DATEDIFF(minute, TimeStart, TimeEnd)
</code>```

You can run this as a demonstration:

```<code>select DATEDIFF(minute, cast('06:00:00' as time), cast('20:00:00' as time))
</code>```

Body:
I have a table with two DateTimes (StartDateTime, EndDateTime) and I want to calculate the minutes between the two.

Now, I know to use the DATEDIFF() function to get this, but I only want to get the number of minutes that fall between two TIME(0) values.

For example:

  StartDateTime     | EndDateTime         | TimeStart | TimeEnd
2017-06-01 03:00:00 | 2017-06-01 23:00:00 | 06:00:00  | 20:00:00

For the above example, I would get:
   DATEDIFF(minute, StartDateTime, EndDateTime) = 1200.

However, I want to only get the number of minutes that fall between TimeStart and TimeEnd, which would be 840.

How can I write my query to get this?

Body:
In SQL Server, DATEDIFF() works on time values, so you can do:

DATEDIFF(minute, TimeStart, TimeEnd)

You can run this as a demonstration:

select DATEDIFF(minute, cast('06:00:00' as time), cast('20:00:00' as time))


问:
Rails Devise Signout not working
I am having issues logging out of my Rails app via Devise. I have looked at several different posts about this and have been struggling for a couple days now.

couldnt-find-user-with-id-sign-out

couldnt-find-user-with-id-sign-out

are some examples that have not worked so far. I have a feeling it is javascript related but I am not sure.

routes.rb:

```<code>Rails.application.routes.draw do
resources :events
devise_for :users
resources :users
resources :articles
resources :athletes

get 'welcome/index'
get 'athletes/index'
get 'users/login'
root 'welcome#index'
end
</code>```

application.html.rb

```<code><% if user_signed_in? %>
    <%= link_to 'Logout', destroy_user_session_path, :method => :delete %>
</code>```

application.js

```<code>//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_bootstrap
//= require_tree .
</code>```

Any advise or direction would be appreciated I am not sure where to go from here.

thanks,

答:
I resolved this be modifying ./config/initializers/devise.rb and changing</p>

```<code>config.sign_out_via = :get
</code>```

Title: Rails Devise Signout not working

Body:
I am having issues logging out of my Rails app via Devise. I have looked at several different posts about this and have been struggling for a couple days now.

couldnt-find-user-with-id-sign-out

couldnt-find-user-with-id-sign-out

are some examples that have not worked so far. I have a feeling it is javascript related but I am not sure.

routes.rb:

Rails.application.routes.draw do
resources :events
devise_for :users
resources :users
resources :articles
resources :athletes

get 'welcome/index'
get 'athletes/index'
get 'users/login'
root 'welcome#index'
end

application.html.rb

<% if user_signed_in? %>
    <%= link_to 'Logout', destroy_user_session_path, :method => :delete %>

application.js

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_bootstrap
//= require_tree .

Any advise or direction would be appreciated I am not sure where to go from here.

thanks,

Body:
I resolved this be modifying ./config/initializers/devise.rb and changing

config.sign_out_via = :get


问:
Uploading picked image from gallery and camera to database getting java.lang.NullPointerException error
every thing seem to be ok but when i click to upload to server the app crushes

```<code>    btnSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //uploadimage function
            uploadImage();
        }
    }

     private void uploadImage() {
            final ProgressDialog loading = ProgressDialog.show(this,
   "Uploading....","Please wait...",false,false);
          StringRequest stringRequest = new
                    StringRequest(Request.Method.POST, UPLOAD_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    //Disimissing the progress dialog
                    loading.dismiss();
                    //Showing toast message of the response
                    Toast.makeText(increport.this, s , Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    //Dismissing the progress dialog
                    loading.dismiss();

                    //Showing toast
                    Toast.makeText(increport.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            //Converting Bitmap to String
            String image = getStringImage(bitmap);

            //Creating parameters
            Map<String,String> params = new Hashtable<>();

            //Adding parameters
            params.put(KEY_IMAGE, image);

            //returning parameters
            return params;
        }
    };
    //Creating a Request Queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //Adding request to the queue
    requestQueue.add(stringRequest);
}

 private String getStringImage(Bitmap bmp){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
}

 @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if(userChoosenTask.equals("Take Photo"))
                    cameraIntent();
                else if(userChoosenTask.equals("Choose from Library"))
                    galleryIntent();
            } else {
                //code for deny
            }
            break;
    }
}

private void selectImage() {
    final CharSequence[] items = { "Take Photo", "Choose from Library",
            "Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(increport.this);
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            boolean result=Utility.checkPermission(increport.this);

            if (items[item].equals("Take Photo")) {
                userChoosenTask ="Take Photo";
                if(result)
                    cameraIntent();

            } else if (items[item].equals("Choose from Library")) {
                userChoosenTask ="Choose from Library";
                if(result)
                    galleryIntent();

            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

private void galleryIntent()
{
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);//
    startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}

private void cameraIntent()
{
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, REQUEST_CAMERA);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
        if (requestCode == SELECT_FILE)
            onSelectFromGalleryResult(data);
        else if (requestCode == REQUEST_CAMERA)
            onCaptureImageResult(data);
    }

}

private void onCaptureImageResult(Intent data) {
    Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

    File destination = new File(Environment.getExternalStorageDirectory(),
            System.currentTimeMillis() + ".jpg");

    FileOutputStream fo;
    try {
        destination.createNewFile();
        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
        fo.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    ivImage.setImageBitmap(thumbnail);
}

@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {

    Bitmap bm=null;
    if (data != null) {
        try {
            bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    ivImage.setImageBitmap(bm);
}
</code>```

here is the error

E/Volley: [207] NetworkDispatcher.run: Unhandled exception java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
          java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
              at com.example.mariamhp.inicrepot.increport$override.getStringImage(increport.java:318)
              at com.example.mariamhp.inicrepot.increport$override.static$access$300(increport.java:66)
              at com.example.mariamhp.inicrepot.increport$override.access$dispatch(increport.java)
              at com.example.mariamhp.inicrepot.increport.access$300(increport.java:0)
              at com.example.mariamhp.inicrepot.increport$8$override.getParams(increport.java:297)
              at com.example.mariamhp.inicrepot.increport$8$override.access$dispatch(increport.java)
              at com.example.mariamhp.inicrepot.increport$8.getParams(increport.java:0)
              at com.android.volley.Request.getBody(Request.java:434)
              at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:260)
              at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:234)
              at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:107)
              at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:96)
              at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)

答:
```<code>String image = getStringImage(bitmap);
</code>```

bitmap is not defined anywhere in the code shown in your question, and it is not assigned a value in the code shown in your question. Apparently, bitmap is null. Either assign the appropriate value to bitmap or pass some other non-null value to getStringImage().

Body:
every thing seem to be ok but when i click to upload to server the app crushes

    btnSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //uploadimage function
            uploadImage();
        }
    }

     private void uploadImage() {
            final ProgressDialog loading = ProgressDialog.show(this,
   "Uploading....","Please wait...",false,false);
          StringRequest stringRequest = new
                    StringRequest(Request.Method.POST, UPLOAD_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    //Disimissing the progress dialog
                    loading.dismiss();
                    //Showing toast message of the response
                    Toast.makeText(increport.this, s , Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    //Dismissing the progress dialog
                    loading.dismiss();

                    //Showing toast
                    Toast.makeText(increport.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            //Converting Bitmap to String
            String image = getStringImage(bitmap);

            //Creating parameters
            Map<String,String> params = new Hashtable<>();

            //Adding parameters
            params.put(KEY_IMAGE, image);

            //returning parameters
            return params;
        }
    };
    //Creating a Request Queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //Adding request to the queue
    requestQueue.add(stringRequest);
}

 private String getStringImage(Bitmap bmp){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
}

 @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if(userChoosenTask.equals("Take Photo"))
                    cameraIntent();
                else if(userChoosenTask.equals("Choose from Library"))
                    galleryIntent();
            } else {
                //code for deny
            }
            break;
    }
}

private void selectImage() {
    final CharSequence[] items = { "Take Photo", "Choose from Library",
            "Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(increport.this);
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            boolean result=Utility.checkPermission(increport.this);

            if (items[item].equals("Take Photo")) {
                userChoosenTask ="Take Photo";
                if(result)
                    cameraIntent();

            } else if (items[item].equals("Choose from Library")) {
                userChoosenTask ="Choose from Library";
                if(result)
                    galleryIntent();

            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

private void galleryIntent()
{
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);//
    startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}

private void cameraIntent()
{
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, REQUEST_CAMERA);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
        if (requestCode == SELECT_FILE)
            onSelectFromGalleryResult(data);
        else if (requestCode == REQUEST_CAMERA)
            onCaptureImageResult(data);
    }

}

private void onCaptureImageResult(Intent data) {
    Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

    File destination = new File(Environment.getExternalStorageDirectory(),
            System.currentTimeMillis() + ".jpg");

    FileOutputStream fo;
    try {
        destination.createNewFile();
        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
        fo.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    ivImage.setImageBitmap(thumbnail);
}

@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {

    Bitmap bm=null;
    if (data != null) {
        try {
            bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    ivImage.setImageBitmap(bm);
}

here is the error

E/Volley: [207] NetworkDispatcher.run: Unhandled exception java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
          java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
              at com.example.mariamhp.inicrepot.increport$override.getStringImage(increport.java:318)
              at com.example.mariamhp.inicrepot.increport$override.static$access$300(increport.java:66)
              at com.example.mariamhp.inicrepot.increport$override.access$dispatch(increport.java)
              at com.example.mariamhp.inicrepot.increport.access$300(increport.java:0)
              at com.example.mariamhp.inicrepot.increport$8$override.getParams(increport.java:297)
              at com.example.mariamhp.inicrepot.increport$8$override.access$dispatch(increport.java)
              at com.example.mariamhp.inicrepot.increport$8.getParams(increport.java:0)
              at com.android.volley.Request.getBody(Request.java:434)
              at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:260)
              at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:234)
              at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:107)
              at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:96)
              at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)

Body:
String image = getStringImage(bitmap);

bitmap is not defined anywhere in the code shown in your question, and it is not assigned a value in the code shown in your question. Apparently, bitmap is null. Either assign the appropriate value to bitmap or pass some other non-null value to getStringImage().


问:
How to add folder of property files in eclipse
I shifted my project from tomcat to eclipse. All files are working fine but the folder containing property files are not working.

What I did so far:

Added folder in project -> build

created a source folder in project/src root and moved all

Set the classpath environment variables

Changed path with //, first folder without / etc.

but nothing worked for me. Here is screen shot:

Please advise where I am making mistake?
My OS is windows 8 but I have to deploy on CentOS
IDE: eclipse neon 3.0

thanks in anticipation

答: It will be just /lang/global/settings.properties without main


问:
How to execute some code when user switches to a nested tabsheet?
I have a TPageCOntrol which has 3 TTabSheet and some of those have further TPageCOntrol which have a TTabSheet

Sort of

```<code>Page Control 1
  TabSheet 1
  TabSheet 2
    Page Control 2
      TabSheet 2a
      TabSheet 2b
  TabSheet 3
</code>```

Now, whenever one of those tabsheets becomes visible to the user I want to execute some code, but I'm not sure which event to hook.

For instance, if the user is looking at TabSheet 1 and switches to TabSheet 2 where TabSheet 2a is showing,  then I want to execute Tabsheet 2a's code, but I can't hook TabSheet 2a's OnEnter or OnShow.  And it isn't Page Control2's OnChange.

In fact, all that I can see is to put a whole bunch of switch/case into Page Control 1's OnChange event ... is tehre a better way?

答: I hooked each PageControl's OnChange() and checked ActivePage.  It works for me, without redesigning to use frames.</p>

Body:
I have a TPageCOntrol which has 3 TTabSheet and some of those have further TPageCOntrol which have a TTabSheet

Sort of

Page Control 1
  TabSheet 1
  TabSheet 2
    Page Control 2
      TabSheet 2a
      TabSheet 2b
  TabSheet 3

Now, whenever one of those tabsheets becomes visible to the user I want to execute some code, but I'm not sure which event to hook.

For instance, if the user is looking at TabSheet 1 and switches to TabSheet 2 where TabSheet 2a is showing,  then I want to execute Tabsheet 2a's code, but I can't hook TabSheet 2a's OnEnter or OnShow.  And it isn't Page Control2's OnChange.

In fact, all that I can see is to put a whole bunch of switch/case into Page Control 1's OnChange event ... is tehre a better way?


问:
mysqli_insert_id() expects exactly 1 parameter, 0 given in CodeIgniter
I have a problem, Please Help me. I'm using Code igniter
This is my code.

my Models (M_register.php)

```<code>class M_register extends CI_Model {

    function __construct()
    {
        parent::__construct();
    }

    function add_account($data)
    {
        $this->load->database();
        $this->db->insert('login',$data);
        **return  mysqli_insert_id();**
    }

    function changeActiveState($key)
    {
        $this->load->database();
        $data = array(
           'active' => 1
        );

        $this->db->where('md5(id)', $key);
        $this->db->update('login', $data);

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

And this is partly code in Controller
$data = array(

```<code>        'username' => $username,
        'password' => $password,
        'nama' => $nama,
        'email' => $email,
        'active' => 0
    );
    $this->load->model('m_register');
    **$id = $this->m_register->add_account($data);**
    $encrypted_id = md5($id);
enter code here
</code>```

And this My error:

答:
The error message is clear :
mysqli_insert_id() expects exactly 1 parameter, 0 given

You must give it the connection in parameter. For example :

$con = mysqli_connect("localhost","my_user","my_password","my_db");

mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Glenn','Quagmire',33)");

// Here the call to "mysqli_insert_id" takes the output of "mysqli_connect" as parameter
echo "New record has id: " . mysqli_insert_id($con);

mysqli_close($con);
```

Source: https://www.w3schools.com/php/func_mysqli_insert_id.asp

I don't know in your code where you're doing the connection, but check that your call to $this->load->database() doesn't return the connection resource.

Body:
I have a problem, Please Help me. I'm using Code igniter
This is my code.

my Models (M_register.php)

class M_register extends CI_Model {

    function __construct()
    {
        parent::__construct();
    }

    function add_account($data)
    {
        $this->load->database();
        $this->db->insert('login',$data);
        **return  mysqli_insert_id();**
    }

    function changeActiveState($key)
    {
        $this->load->database();
        $data = array(
           'active' => 1
        );

        $this->db->where('md5(id)', $key);
        $this->db->update('login', $data);

        return true;
    }
}

And this is partly code in Controller
$data = array(

        'username' => $username,
        'password' => $password,
        'nama' => $nama,
        'email' => $email,
        'active' => 0
    );
    $this->load->model('m_register');
    **$id = $this->m_register->add_account($data);**
    $encrypted_id = md5($id);
enter code here

And this My error:

Body:
The error message is clear :
mysqli_insert_id() expects exactly 1 parameter, 0 given

You must give it the connection in parameter. For example :

$con = mysqli_connect("localhost","my_user","my_password","my_db");

mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Glenn','Quagmire',33)");

// Here the call to "mysqli_insert_id" takes the output of "mysqli_connect" as parameter
echo "New record has id: " . mysqli_insert_id($con);

mysqli_close($con);

Source: https://www.w3schools.com/php/func_mysqli_insert_id.asp

I don't know in your code where you're doing the connection, but check that your call to $this->load->database() doesn't return the connection resource.