问:
Task manager with Java
Hi so I'm a student in high school and have a project to do with CS. I'm trying  to write a program that shuts down an external application after a certain amount of time has passed. That time part was pretty easy to do but now the problem is the actual shutting down of the problem. I looked around and couldn't find anything that worked for me and need some help with this.

Here's what I have so far:

```<code>import java.util.concurrent.TimeUnit;
import javax.swing.JOptionPane;
public class TaskKiller {
    public static void main(String[] args) {
        JOptionPane pane = new JOptionPane();
        String userInput1 = JOptionPane.showInputDialog("Hours: ");
        String userInput2 = JOptionPane.showInputDialog("Minutes: ");
        String userInput3 = JOptionPane.showInputDialog("Seconds: ");
        long inputHours = Long.parseLong(userInput1);
        long inputMinutes = Long.parseLong(userInput2);
        long inputSeconds = Long.parseLong(userInput3);
        long hours = inputHours * 3600000;
        long minutes = inputMinutes * 60000;
        long seconds = inputSeconds * 1000;
        long time = (hours + minutes) + seconds;
        try {
            TimeUnit.MILLISECONDS.sleep(time);
            System.exit(0);//was just an idea
            System.out.println("You sucessfully closed the program");
        }
        catch (InterruptedException ex) {
        }
    }
}
</code>```

UPDATED CODE:

```<code>import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import java.lang.*;
public class TaskKiller {
@SuppressWarnings("IndexOfReplaceableByContains")
public static void main(String[] args) {
    JOptionPane pane = new JOptionPane();
    String userInput1 = JOptionPane.showInputDialog("Hours: ");
    String userInput2 = JOptionPane.showInputDialog("Minutes: ");
    String userInput3 = JOptionPane.showInputDialog("Seconds: ");
    long inputHours = Long.parseLong(userInput1);
    long inputMinutes = Long.parseLong(userInput2);
    long inputSeconds = Long.parseLong(userInput3);
    long hours = inputHours * 3600000;
    long minutes = inputMinutes * 60000;
    long seconds = inputSeconds * 1000;
    long time = (hours + minutes) + seconds;
    String OS = System.getProperty("os.name").toLowerCase();
 int run = 1;

while (run > 0){
 JOptionPane.showMessageDialog(null,"Program names: chrome, firefox, safari, gta, csgo", "Info", JOptionPane.INFORMATION_MESSAGE);
    String prog = JOptionPane.showInputDialog("Program: ");
    String gta="gta";
    String chrome="chrome";
    String firefox="firefox";
    String safari="safari";
    String csgo="csgo";
    int gt=prog.compareTo(gta);
    int ch=prog.compareTo(chrome);
    int fi=prog.compareTo(firefox);
    int sa=prog.compareTo(safari);
    int cs=prog.compareTo(csgo);

if (gt == 0) {
    if(OS.indexOf("win") >= 0){
    try {
        TimeUnit.MILLISECONDS.sleep(time);
    Runtime.getRuntime().exec("cmd /c Taskkill /IM GTA5.exe /F");
        TimeUnit.MILLISECONDS.sleep(5000);
        Runtime.getRuntime().exec("cmd /c Taskkill /IM GTAVLauncher.exe /F");
        System.out.println("Win");
        run=run-1;
    }
    catch (InterruptedException ex) {
    }
    catch (IOException ex) {
        Logger.getLogger(TaskKiller.class.getName()).log(Level.SEVERE, null, ex);
    }
    }else if(OS.indexOf("mac") >= 0){
        try {
            Runtime.getRuntime().exec("/bin/bash -c  sudo killall process PID");
            System.out.println("Mac");
            run=run-1;
        } catch (IOException ex) {
            Logger.getLogger(TaskKiller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
else if (ch==0) {
if(OS.indexOf("win") >= 0){
    try {
        TimeUnit.MILLISECONDS.sleep(time);
    Runtime.getRuntime().exec("cmd /c Taskkill /IM chrome.exe /F");
        System.out.println("Win");
        run=run-1;
    }
    catch (InterruptedException ex) {
    }
    catch (IOException ex) {
        Logger.getLogger(TaskKiller.class.getName()).log(Level.SEVERE, null, ex);
    }
    }else if(OS.indexOf("mac") >= 0){
        try {
            Runtime.getRuntime().exec("/bin/bash -c  sudo killall process PID");
            System.out.println("Mac");
            run=run-1;
        } catch (IOException ex) {
            Logger.getLogger(TaskKiller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
else if (fi==0) {
    if(OS.indexOf("win") >= 0){
    try {
        TimeUnit.MILLISECONDS.sleep(time);
    Runtime.getRuntime().exec("cmd /c Taskkill /IM firefox.exe /F");
        System.out.println("Win");
        run=run-1;
    }
    catch (InterruptedException ex) {
    }
    catch (IOException ex) {
        Logger.getLogger(TaskKiller.class.getName()).log(Level.SEVERE, null, ex);
    }
    }else if(OS.indexOf("mac") >= 0){
        try {
            Runtime.getRuntime().exec("/bin/bash -c  sudo killall process PID");
            System.out.println("Mac");
            run=run-1;
        } catch (IOException ex) {
            Logger.getLogger(TaskKiller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
else if (sa==0) {
    if(OS.indexOf("win") >= 0){
    try {
        TimeUnit.MILLISECONDS.sleep(time);
    Runtime.getRuntime().exec("cmd /c Taskkill /IM safari.exe /F");
        System.out.println("Win");
        run=run-1;
    }
    catch (InterruptedException ex) {
    }
    catch (IOException ex) {
        Logger.getLogger(TaskKiller.class.getName()).log(Level.SEVERE, null, ex);
    }
    }else if(OS.indexOf("mac") >= 0){
        try {
            Runtime.getRuntime().exec("/bin/bash -c  sudo killall process PID");
            System.out.println("Mac");
            run=run-1;
        } catch (IOException ex) {
            Logger.getLogger(TaskKiller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
else if (cs==0) {
    if(OS.indexOf("win") >= 0){
    try {
        TimeUnit.MILLISECONDS.sleep(time);
    Runtime.getRuntime().exec("cmd /c Taskkill /IM csgo.exe /F");
        System.out.println("Win");
        run=run-1;
    }
    catch (InterruptedException ex) {
    }
    catch (IOException ex) {
        Logger.getLogger(TaskKiller.class.getName()).log(Level.SEVERE, null, ex);
    }
    }else if(OS.indexOf("mac") >= 0){
        try {
            Runtime.getRuntime().exec("/bin/bash -c  sudo killall process PID");
            System.out.println("Mac");
            run=run-1;
        } catch (IOException ex) {
            Logger.getLogger(TaskKiller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
else {
    JOptionPane.showMessageDialog(null, "Invalid name. Try Again or quit", "Error", JOptionPane.ERROR_MESSAGE);
    run=run+1;
}
}
}
}
</code>```

Still needs some working on when it comes to Mac OS. But the windows part works great. Added some video games that i had on my computer to shut down.

答:
Use System.getProperty("os.name"); to determine which OS is running the program:

```<code>String os = System.getProperty("os.name").toLowerCase();
if(os.indexOf("win") >= 0) {
//run windows process kill method
} else if(os.indexOf("mac") >= 0) {
//run mac process kill method
}
</code>```

Then kill the  task based on the OS:

---- For Windows ---

You could use the method Runtime.getRuntime().exec(); to execute a
cmd command in order to kill the process.

```<code>Runtime.getRuntime().exec("cmd /c Taskkill /IM process.exe /F");
</code>```

Replacing process.exe with the filename of the process you want to kill. You might have to run the program as administrator, because taskkill requires elevation to kill some processes.

--- For Mac ---

For mac, you will use the same method, just passing different arguments to it. Consider the following:

```<code>Runtime.getRuntime().exec("/bin/bash -c  sudo kill process PID");
</code>```

or

```<code>Runtime.getRuntime().exec("/bin/bash -c  sudo killall process PID");
</code>```

Title: Task manager with Java

Body:
Hi so I'm a student in high school and have a project to do with CS. I'm trying  to write a program that shuts down an external application after a certain amount of time has passed. That time part was pretty easy to do but now the problem is the actual shutting down of the problem. I looked around and couldn't find anything that worked for me and need some help with this.

Here's what I have so far:

import java.util.concurrent.TimeUnit;
import javax.swing.JOptionPane;
public class TaskKiller {
    public static void main(String[] args) {
        JOptionPane pane = new JOptionPane();
        String userInput1 = JOptionPane.showInputDialog("Hours: ");
        String userInput2 = JOptionPane.showInputDialog("Minutes: ");
        String userInput3 = JOptionPane.showInputDialog("Seconds: ");
        long inputHours = Long.parseLong(userInput1);
        long inputMinutes = Long.parseLong(userInput2);
        long inputSeconds = Long.parseLong(userInput3);
        long hours = inputHours * 3600000;
        long minutes = inputMinutes * 60000;
        long seconds = inputSeconds * 1000;
        long time = (hours + minutes) + seconds;
        try {
            TimeUnit.MILLISECONDS.sleep(time);
            System.exit(0);//was just an idea
            System.out.println("You sucessfully closed the program");
        }
        catch (InterruptedException ex) {
        }
    }
}

UPDATED CODE:

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import java.lang.*;
public class TaskKiller {
@SuppressWarnings("IndexOfReplaceableByContains")
public static void main(String[] args) {
    JOptionPane pane = new JOptionPane();
    String userInput1 = JOptionPane.showInputDialog("Hours: ");
    String userInput2 = JOptionPane.showInputDialog("Minutes: ");
    String userInput3 = JOptionPane.showInputDialog("Seconds: ");
    long inputHours = Long.parseLong(userInput1);
    long inputMinutes = Long.parseLong(userInput2);
    long inputSeconds = Long.parseLong(userInput3);
    long hours = inputHours * 3600000;
    long minutes = inputMinutes * 60000;
    long seconds = inputSeconds * 1000;
    long time = (hours + minutes) + seconds;
    String OS = System.getProperty("os.name").toLowerCase();
 int run = 1;

while (run > 0){
 JOptionPane.showMessageDialog(null,"Program names: chrome, firefox, safari, gta, csgo", "Info", JOptionPane.INFORMATION_MESSAGE);
    String prog = JOptionPane.showInputDialog("Program: ");
    String gta="gta";
    String chrome="chrome";
    String firefox="firefox";
    String safari="safari";
    String csgo="csgo";
    int gt=prog.compareTo(gta);
    int ch=prog.compareTo(chrome);
    int fi=prog.compareTo(firefox);
    int sa=prog.compareTo(safari);
    int cs=prog.compareTo(csgo);

if (gt == 0) {
    if(OS.indexOf("win") >= 0){
    try {
        TimeUnit.MILLISECONDS.sleep(time);
    Runtime.getRuntime().exec("cmd /c Taskkill /IM GTA5.exe /F");
        TimeUnit.MILLISECONDS.sleep(5000);
        Runtime.getRuntime().exec("cmd /c Taskkill /IM GTAVLauncher.exe /F");
        System.out.println("Win");
        run=run-1;
    }
    catch (InterruptedException ex) {
    }
    catch (IOException ex) {
        Logger.getLogger(TaskKiller.class.getName()).log(Level.SEVERE, null, ex);
    }
    }else if(OS.indexOf("mac") >= 0){
        try {
            Runtime.getRuntime().exec("/bin/bash -c  sudo killall process PID");
            System.out.println("Mac");
            run=run-1;
        } catch (IOException ex) {
            Logger.getLogger(TaskKiller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
else if (ch==0) {
if(OS.indexOf("win") >= 0){
    try {
        TimeUnit.MILLISECONDS.sleep(time);
    Runtime.getRuntime().exec("cmd /c Taskkill /IM chrome.exe /F");
        System.out.println("Win");
        run=run-1;
    }
    catch (InterruptedException ex) {
    }
    catch (IOException ex) {
        Logger.getLogger(TaskKiller.class.getName()).log(Level.SEVERE, null, ex);
    }
    }else if(OS.indexOf("mac") >= 0){
        try {
            Runtime.getRuntime().exec("/bin/bash -c  sudo killall process PID");
            System.out.println("Mac");
            run=run-1;
        } catch (IOException ex) {
            Logger.getLogger(TaskKiller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
else if (fi==0) {
    if(OS.indexOf("win") >= 0){
    try {
        TimeUnit.MILLISECONDS.sleep(time);
    Runtime.getRuntime().exec("cmd /c Taskkill /IM firefox.exe /F");
        System.out.println("Win");
        run=run-1;
    }
    catch (InterruptedException ex) {
    }
    catch (IOException ex) {
        Logger.getLogger(TaskKiller.class.getName()).log(Level.SEVERE, null, ex);
    }
    }else if(OS.indexOf("mac") >= 0){
        try {
            Runtime.getRuntime().exec("/bin/bash -c  sudo killall process PID");
            System.out.println("Mac");
            run=run-1;
        } catch (IOException ex) {
            Logger.getLogger(TaskKiller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
else if (sa==0) {
    if(OS.indexOf("win") >= 0){
    try {
        TimeUnit.MILLISECONDS.sleep(time);
    Runtime.getRuntime().exec("cmd /c Taskkill /IM safari.exe /F");
        System.out.println("Win");
        run=run-1;
    }
    catch (InterruptedException ex) {
    }
    catch (IOException ex) {
        Logger.getLogger(TaskKiller.class.getName()).log(Level.SEVERE, null, ex);
    }
    }else if(OS.indexOf("mac") >= 0){
        try {
            Runtime.getRuntime().exec("/bin/bash -c  sudo killall process PID");
            System.out.println("Mac");
            run=run-1;
        } catch (IOException ex) {
            Logger.getLogger(TaskKiller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
else if (cs==0) {
    if(OS.indexOf("win") >= 0){
    try {
        TimeUnit.MILLISECONDS.sleep(time);
    Runtime.getRuntime().exec("cmd /c Taskkill /IM csgo.exe /F");
        System.out.println("Win");
        run=run-1;
    }
    catch (InterruptedException ex) {
    }
    catch (IOException ex) {
        Logger.getLogger(TaskKiller.class.getName()).log(Level.SEVERE, null, ex);
    }
    }else if(OS.indexOf("mac") >= 0){
        try {
            Runtime.getRuntime().exec("/bin/bash -c  sudo killall process PID");
            System.out.println("Mac");
            run=run-1;
        } catch (IOException ex) {
            Logger.getLogger(TaskKiller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
else {
    JOptionPane.showMessageDialog(null, "Invalid name. Try Again or quit", "Error", JOptionPane.ERROR_MESSAGE);
    run=run+1;
}
}
}
}

Still needs some working on when it comes to Mac OS. But the windows part works great. Added some video games that i had on my computer to shut down.

Body:
Use System.getProperty("os.name"); to determine which OS is running the program:

String os = System.getProperty("os.name").toLowerCase();
if(os.indexOf("win") >= 0) {
//run windows process kill method
} else if(os.indexOf("mac") >= 0) {
//run mac process kill method
}

Then kill the  task based on the OS:

---- For Windows ---

You could use the method Runtime.getRuntime().exec(); to execute a
cmd command in order to kill the process.

Runtime.getRuntime().exec("cmd /c Taskkill /IM process.exe /F");

Replacing process.exe with the filename of the process you want to kill. You might have to run the program as administrator, because taskkill requires elevation to kill some processes.

--- For Mac ---

For mac, you will use the same method, just passing different arguments to it. Consider the following:

Runtime.getRuntime().exec("/bin/bash -c  sudo kill process PID");

or

Runtime.getRuntime().exec("/bin/bash -c  sudo killall process PID");

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
getting error for VHDL shift_left operation
I have been searching this for a while and have not been able to replicate any posted solutions online so I was hoping some of you wonderful people could help me out.
     I am creating an ALU. i have a two 32 bit inputs and one 32 bit output along with a 5 bit shamt and a 4 bit control signal. My code is as follows with the error location commented on.

```<code>library ieee;
use ieee.std_logic_1164.all;
use IEEE.STD_LOGIC_UNSIGNED.ALL;
use ieee.numeric_std.all;

Entity mips_alu IS
    PORT(ALUControl : IN STD_LOGIC_VECTOR(3 DOWNTO 0);
    inputA, inputB      : IN STD_LOGIC_VECTOR(31 DOWNTO 0);
    shamt                   : IN STD_LOGIC_VECTOR(4 DOWNTO 0);
    Zero                    : OUT STD_LOGIC;
    ALU_Result          : OUT STD_LOGIC_VECTOR(31 DOWNTO 0)
    );
END mips_alu;

ARCHITECTURE behavior of mips_alu IS
BEGIN
    PROCESS(ALUControl)
    BEGIN
        CASE ALUControl is
        WHEN "0000" =>
            ALU_Result <= inputA AND inputB;
        WHEN "0001" =>
            ALU_Result <= inputA OR inputB;
        WHEN "0010" =>
            ALU_Result <= inputA + inputB;
        WHEN "0110" =>
            ALU_Result <= inputA - inputB;
        WHEN "0111" =>
            IF (inputA < inputB) THEN
                ALU_Result <= inputA;
            END IF;
        WHEN "1000" =>
            ALU_Result <= shift_left(inputB, to_integer(unsigned(shamt)));
            -- The line above is where i get my first error, The following lines will have the same issue
        WHEN "1001" =>
            ALU_Result <= shift_right(inputB, shamt);
        WHEN "1010" =>
            ALU_Result <= shift_left(inputB, inputA);
        WHEN "1011" =>
            ALU_Result <= shift_right(inputB, inputA);
        WHEN "1100" =>
            ALU_Result <= inputA NOR inputB;
        WHEN "1101" =>
            ALU_Result <= inputB(31 DOWNTO 16);
        WHEN OTHERS =>
            ALU_Result <= inputA;
        END CASE;
    END PROCESS;
END behavior;
</code>```

The error I am getting says:

10511 VHDL Qualified Expression error at mips_alu.vhd(33): shift_left type specified in qualified expression must match std_logic_vector type that is implied for expression by context

I have tried several variations of this so if i am missing something please let me know, all help is appreciated as I am a bit of a novice to vhdl

答:
In  the numeric_std document you can find the function shift_left or shift_right. In both descriptions there you can see that function SHIFT_LEFT (ARG: UNSIGNED; COUNT: NATURAL) return UNSIGNED;. So you need to use casting of your std_logic_vector to unsigned.

In your case it will looks like:

```<code>ALU_Result <= std_logic_vector(shift_left(unsigned(inputB), to_integer(unsigned(shamt))));
</code>```

end etc. for other lines where you use shift_left or shift_right function.

ContentLicense: CC BY-SA 3.0

Body:
I have been searching this for a while and have not been able to replicate any posted solutions online so I was hoping some of you wonderful people could help me out.
     I am creating an ALU. i have a two 32 bit inputs and one 32 bit output along with a 5 bit shamt and a 4 bit control signal. My code is as follows with the error location commented on.

library ieee;
use ieee.std_logic_1164.all;
use IEEE.STD_LOGIC_UNSIGNED.ALL;
use ieee.numeric_std.all;

Entity mips_alu IS
    PORT(ALUControl : IN STD_LOGIC_VECTOR(3 DOWNTO 0);
    inputA, inputB      : IN STD_LOGIC_VECTOR(31 DOWNTO 0);
    shamt                   : IN STD_LOGIC_VECTOR(4 DOWNTO 0);
    Zero                    : OUT STD_LOGIC;
    ALU_Result          : OUT STD_LOGIC_VECTOR(31 DOWNTO 0)
    );
END mips_alu;

ARCHITECTURE behavior of mips_alu IS
BEGIN
    PROCESS(ALUControl)
    BEGIN
        CASE ALUControl is
        WHEN "0000" =>
            ALU_Result <= inputA AND inputB;
        WHEN "0001" =>
            ALU_Result <= inputA OR inputB;
        WHEN "0010" =>
            ALU_Result <= inputA + inputB;
        WHEN "0110" =>
            ALU_Result <= inputA - inputB;
        WHEN "0111" =>
            IF (inputA < inputB) THEN
                ALU_Result <= inputA;
            END IF;
        WHEN "1000" =>
            ALU_Result <= shift_left(inputB, to_integer(unsigned(shamt)));
            -- The line above is where i get my first error, The following lines will have the same issue
        WHEN "1001" =>
            ALU_Result <= shift_right(inputB, shamt);
        WHEN "1010" =>
            ALU_Result <= shift_left(inputB, inputA);
        WHEN "1011" =>
            ALU_Result <= shift_right(inputB, inputA);
        WHEN "1100" =>
            ALU_Result <= inputA NOR inputB;
        WHEN "1101" =>
            ALU_Result <= inputB(31 DOWNTO 16);
        WHEN OTHERS =>
            ALU_Result <= inputA;
        END CASE;
    END PROCESS;
END behavior;

The error I am getting says:

10511 VHDL Qualified Expression error at mips_alu.vhd(33): shift_left type specified in qualified expression must match std_logic_vector type that is implied for expression by context

I have tried several variations of this so if i am missing something please let me know, all help is appreciated as I am a bit of a novice to vhdl

Body:
In  the numeric_std document you can find the function shift_left or shift_right. In both descriptions there you can see that function SHIFT_LEFT (ARG: UNSIGNED; COUNT: NATURAL) return UNSIGNED;. So you need to use casting of your std_logic_vector to unsigned.

In your case it will looks like:

ALU_Result <= std_logic_vector(shift_left(unsigned(inputB), to_integer(unsigned(shamt))));

end etc. for other lines where you use shift_left or shift_right function.


问:
multithreading and strtok
I will be continually splitting strings in a multithreaded application, I've read that strtok is not suitable for this, but why?

Should I consider using a semaphore around the portion of my code that calls strtok?

答:
You should consider not using strtok or strtok_r at all. It's trivial to write your own functions similar to these but better-tailored to the exact way you want to use them, and of course have the caller store all the state and pass a pointer to the state for thread-safety/reentrancy.

As for your question about using a semaphore (or other locking primitive) around calls to strtok, that will not help if you just put it around the actual call. You'd have to hold the lock during the whole process of parsing the string to protect the internal state of strtok. I believe this is what many people refer to as locking code in place of data and it's generally considered A Bad Thing.

ContentLicense: CC BY-SA 2.5

Title: multithreading and strtok


问:
jQuery.ajax doesn't send Authorization header with OPTIONS request
It appears that jQuery doesn't send along the Authorization header when sending an OPTIONS request before a POST request (or possibly other types). The server I'm trying to reach is returning a 401 status for the OPTIONS request - how can I force jQuery to include the Authorization header, even in this initial request?

```<code>$.ajax({
    type: "POST",
    url: url,
    data: postData,
    beforeSend: function ajaxBeforeSend(jqXHR) {
        jqXHR.withCredentials = true;
        jqXHR.setRequestHeader("Authorization", "Basic " + btoa(encodeURIComponent(escape($username.val())) + ":" + encodeURIComponent(escape($password.val()))));
    },
    success: runReportUrlCallback,
    error: runReportErrorCallback
});
</code>```

I also tried adding username and password to the ajax options, to no avail.

答:
It seems that the 3rd party server has been configured incorrectly without the OPTIONS request in mind.

W3 states that preflight OPTIONS request must:

Exclude user credentials.

User credentials are defined:

The term user credentials for the purposes of this specification means cookies, HTTP authentication, and client-side SSL certificates

See https://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0

If the server is in your control then you simply put the OPTIONS request handler in front of your auth check.

If the server is NOT in your control, which seems to be the case here, then you moan at the server administrator explaining they've done it wrong and hope they change it.

Body:
It appears that jQuery doesn't send along the Authorization header when sending an OPTIONS request before a POST request (or possibly other types). The server I'm trying to reach is returning a 401 status for the OPTIONS request - how can I force jQuery to include the Authorization header, even in this initial request?

$.ajax({
    type: "POST",
    url: url,
    data: postData,
    beforeSend: function ajaxBeforeSend(jqXHR) {
        jqXHR.withCredentials = true;
        jqXHR.setRequestHeader("Authorization", "Basic " + btoa(encodeURIComponent(escape($username.val())) + ":" + encodeURIComponent(escape($password.val()))));
    },
    success: runReportUrlCallback,
    error: runReportErrorCallback
});

I also tried adding username and password to the ajax options, to no avail.


问:
Ansible create a virtualenv using the venv module
How can one use Ansible to create a virtualenv using the venv module from Python3's standard library?

Manually, one would do this to create a venv (virtual environment):

```<code>python3 -m venv <venv-name>
</code>```

How do I do this using Ansible?

答:
I ran into the same issue tonight and found that specifying the full path to the interpreter, including the arguments, worked for me (at least it does in ansible==2.2.2.0):

```<code>- pip:
     requirements: /website/requirements.txt
     virtualenv: /opt/website-venv
     virtualenv_command: /usr/bin/python3.6 -m venv
</code>```

or

```<code>- pip:
    requirements: /opt/project/requirements_prod.txt
    virtualenv: /opt/.virtualenv/project_env
    virtualenv_python: python3
</code>```

Body:
How can one use Ansible to create a virtualenv using the venv module from Python3's standard library?

Manually, one would do this to create a venv (virtual environment):

python3 -m venv <venv-name>

How do I do this using Ansible?

Body:
I ran into the same issue tonight and found that specifying the full path to the interpreter, including the arguments, worked for me (at least it does in ansible==2.2.2.0):

- pip:
     requirements: /website/requirements.txt
     virtualenv: /opt/website-venv
     virtualenv_command: /usr/bin/python3.6 -m venv

or

- pip:
    requirements: /opt/project/requirements_prod.txt
    virtualenv: /opt/.virtualenv/project_env
    virtualenv_python: python3


Title: Position Numbers Above & Below Bars of a Barplot

Body:
I would like to have positive numbers on my barplots displayed above the bars and negative numbers displayed below the bars. Is there anyway to do this in R? Thanks

par(mfrow=c(2,1))
HOLD <- matrix(c(0.711993046435892, 0.732294839190538,
                 0.393938967564015, -0.456254046041675,
                 -0.284020839130226, 0.544765413396821,
                 0.349792656944892, 0.395227638605604,
                 0.55130390493582, -0.513905184144522,
                 0.0989034381192891, 0.0908636716369119), ncol=6, nrow=2)

for (i in 1:2) {
  BP <- barplot(HOLD[,i], main=M[[i]], ylab="%", ylim=c(-1, 1), col=SEQUENTIAL)
  text(BP, HOLD[,i], labels=HOLD[,i], pos=3, offset=0.8)
}

Body:
HOLD <- matrix(c(0.711993046435892, 0.732294839190538,
                 0.393938967564015, -0.456254046041675,
                 -0.284020839130226, 0.544765413396821,
                 0.349792656944892, 0.395227638605604,
                 0.55130390493582, -0.513905184144522,
                 0.0989034381192891, 0.0908636716369119), ncol=6, nrow=2)

HOLD <- data.frame(HOLD)
HOLD <- stack(HOLD)
HOLD$grp2 <- factor(1:2)
offset <- 0.05
library('ggplot2')
ggplot(data = HOLD, mapping = aes( x = ind, y = values, fill = grp2 ) ) +
  geom_bar(stat = 'identity', position = 'dodge' ) +
  geom_text( aes( x     = ind,
                  y     = ifelse( sign( values ) > 0, values + offset, values - offset ),
                  label = round( values, 2 ) ),
             position = position_dodge( width = 1 ),
             size = 3)


问:
OkHttpClient get response body
I want get body response, but get error 403, although the page opens in webview and browser. My code:

```<code>OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(url)
                            .build();

                    client.newCall(request).enqueue(new Callback()
                    {
                        @Override
                        public void onFailure(Call call, IOException e)
                        {
                            Log.e("Error load URL", e.toString());
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException
                        {
                            if (response.isSuccessful())
                            {
                                htmlPage = response.body().string();
                            }
                            else
                            {
                                //I find myself here.
                                Log.e("Error load URL", "Response error");
                            }
                        }
                    });
</code>```

url =
  "http://shop.lenovo.com/SEUILibrary/controller/e/web/LenovoPortal/en_US/cart.workflow:ShowCart?shopping-menu-selected-line=cart&menu-id=currentcart"

response from server:

Response{protocol=http/1.1, code=403, message=Forbidden,
  url=http://shop.lenovo.com/SEUILibrary/controller/e/web/LenovoPortal/en_US/cart.workflow:ShowCart?shopping-menu-selected-line=cart&menu-id=currentcart}

In browser everything is good. Why?

答:
Make sure your client has authorized or authenticated to the web service.
This can happen if the security is enabled on the web service that you are calling try to authenticate / authorize yourself to the web service and then start consuming it.</p>

Title: OkHttpClient get response body

Body:
I want get body response, but get error 403, although the page opens in webview and browser. My code:

OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(url)
                            .build();

                    client.newCall(request).enqueue(new Callback()
                    {
                        @Override
                        public void onFailure(Call call, IOException e)
                        {
                            Log.e("Error load URL", e.toString());
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException
                        {
                            if (response.isSuccessful())
                            {
                                htmlPage = response.body().string();
                            }
                            else
                            {
                                //I find myself here.
                                Log.e("Error load URL", "Response error");
                            }
                        }
                    });

url =
  "http://shop.lenovo.com/SEUILibrary/controller/e/web/LenovoPortal/en_US/cart.workflow:ShowCart?shopping-menu-selected-line=cart&menu-id=currentcart"

response from server:

Response{protocol=http/1.1, code=403, message=Forbidden,
  url=http://shop.lenovo.com/SEUILibrary/controller/e/web/LenovoPortal/en_US/cart.workflow:ShowCart?shopping-menu-selected-line=cart&menu-id=currentcart}

In browser everything is good. Why?


问:
Push Data in Firebase
I Have a Database as follow:

```<code>Root Categories/restaurantid/{text:Item1 AL:Item 2 TEXT:Item 3 ...}
</code>```

So I want to push a Data (variable myKey) in a specific child that item is equal to item 1. I am doing as follow (this.restaurant is the restaurantid):

```<code>var ref2 = firebase.database().ref().child('/categories/' + this.restaurant);
var query = ref2.orderByChild('text').equalTo(this.categoria1);
query.once('child_added', function(snapshot) {
  snapshot.ref().child('dishes').push({
    mykey: 'true',
</code>```

But I am getting an error: Cannot invoke an expression whose type lacks a call signature. Type 'Reference' has no compatible call signatures.

Where I am doing a mistake?

答:
In DataSnapshot, ref
 is a property - not a method - so your push call should be something like this:

```<code>snapshot.ref.child('dishes').push({ mykey: 'true', ...
</code>```

Title: Push Data in Firebase

Body:
I Have a Database as follow:

Root Categories/restaurantid/{text:Item1 AL:Item 2 TEXT:Item 3 ...}

So I want to push a Data (variable myKey) in a specific child that item is equal to item 1. I am doing as follow (this.restaurant is the restaurantid):

var ref2 = firebase.database().ref().child('/categories/' + this.restaurant);
var query = ref2.orderByChild('text').equalTo(this.categoria1);
query.once('child_added', function(snapshot) {
  snapshot.ref().child('dishes').push({
    mykey: 'true',

But I am getting an error: Cannot invoke an expression whose type lacks a call signature. Type 'Reference' has no compatible call signatures.

Where I am doing a mistake?

Body:
In DataSnapshot, ref
 is a property - not a method - so your push call should be something like this:

snapshot.ref.child('dishes').push({ mykey: 'true', ...


问:
Assign multiple private IPs to a VM in Azure
I have 2 Virtual Networks and each of them has a subnet. I want to assign 2 private IP's to a virtual machine. One private IP resides in 1st Virtual Network while second private IP is in 2nd Virtual Network.

I have tried attaching 2 NIC's to the VM, and attached the first private IP to first NIC and second private IP to second NIC.

When I deploy the ARM template it says that second NIC is referring to a subnet which is not in same Virtual Network?

How can I achieve this in Azure?

答:
Select the existing NIC for the box you are trying to assign the second Private IP,

Select IP configuration on the right tab bar,

Click on +Add, write a name for your new IP address,

Select static Private IP address (it could stay as dynamic as well)


问:
.exe file throws exception when opening file
I'm trying to write a CGI script in c++ which prints the reverse network path (using
traceroute) from the web server to the IP address of the client invoking the CGI script.

When I run the program in Visual Studio, it works fine(creates the process, prints the result into "C:/result.out" file, opens the file, prints each line from file, closes file) BUT after compiling and trying to run just its .exe file, it throws an exception. What could I do to make the .exe work properly ?
    Just as a note, I'm using Windows XP and Visual C++ 2008

Here`s the code:

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <process.h>
#include <conio.h>

int main()
{
    char *line, *command, *userIp;

    printf("Content-Type:text/html\n\n");
    printf("<html><head></head><br/>");
    printf("<body><br/>");

    line    = (char*)malloc(255*sizeof(char));
    command = (char*)malloc(10*sizeof(char));
    userIp  = (char*)malloc(30*sizeof(char));
    //userIp = getenv("REMOTE_ADDR"); // use a default IP until program works
    strcpy(command,"tracert ");
    strcpy(userIp,"74.125.87.104");

    strcat(command,userIp);
    strcat(command," > C:/result.out");
    // create command "tracert 74.125.87.104 > C:/result.out"

    printf("%s",command);
    system(command);
    FILE *f;
    f = fopen("C:/result.out","r");  // open C:/result.out and read line - by - line
    strcpy(line,"");
    while(!feof(f)){
      fgets(line,255,f);
      printf("%s\n",line);
    }
    fclose(f);
    printf("<br/>Test running OK<br/>");
    printf("</body></html>");
    getch();
    return 0;
}
</code>```

答:
Well the following two lines cause buffer over-runs

```<code>strcat(command,userIp);
strcat(command," > C:/result.out");
</code>```

So this is likely the result of a crash.

Please do not use the term "Exception" unless an exception is being thrown, and since you are writing C code that is unlikely. So it is not an exception.

Rather than running a command using system() and piping the result to a file use the popen() command this will run a command and pipe the output to a stream that you can read just like a file (but without the security implications of writing to the file system).

```<code>FILE *f;
f = popen(command,"r");  // run the command. The std out goes to the FILE stream
    ^^^^^^
strcpy(line,"");
while(!feof(f)){
  fgets(line,255,f);
  printf("%s\n",line);
}
fclose(f);
</code>```

Body:
I'm trying to write a CGI script in c++ which prints the reverse network path (using
traceroute) from the web server to the IP address of the client invoking the CGI script.

When I run the program in Visual Studio, it works fine(creates the process, prints the result into "C:/result.out" file, opens the file, prints each line from file, closes file) BUT after compiling and trying to run just its .exe file, it throws an exception. What could I do to make the .exe work properly ?
    Just as a note, I'm using Windows XP and Visual C++ 2008

Here`s the code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <process.h>
#include <conio.h>

int main()
{
    char *line, *command, *userIp;

    printf("Content-Type:text/html\n\n");
    printf("
");
    printf("
");

    line    = (char*)malloc(255*sizeof(char));
    command = (char*)malloc(10*sizeof(char));
    userIp  = (char*)malloc(30*sizeof(char));
    //userIp = getenv("REMOTE_ADDR"); // use a default IP until program works
    strcpy(command,"tracert ");
    strcpy(userIp,"74.125.87.104");

    strcat(command,userIp);
    strcat(command," > C:/result.out");
    // create command "tracert 74.125.87.104 > C:/result.out"

    printf("%s",command);
    system(command);
    FILE *f;
    f = fopen("C:/result.out","r");  // open C:/result.out and read line - by - line
    strcpy(line,"");
    while(!feof(f)){
      fgets(line,255,f);
      printf("%s\n",line);
    }
    fclose(f);
    printf("
Test running OK
");
    printf("");
    getch();
    return 0;
}

Body:
Well the following two lines cause buffer over-runs

strcat(command,userIp);
strcat(command," > C:/result.out");

So this is likely the result of a crash.

Please do not use the term "Exception" unless an exception is being thrown, and since you are writing C code that is unlikely. So it is not an exception.

Rather than running a command using system() and piping the result to a file use the popen() command this will run a command and pipe the output to a stream that you can read just like a file (but without the security implications of writing to the file system).

FILE *f;
f = popen(command,"r");  // run the command. The std out goes to the FILE stream
    ^^^^^^
strcpy(line,"");
while(!feof(f)){
  fgets(line,255,f);
  printf("%s\n",line);
}
fclose(f);


问:
Warning in StringBuffer and StringBuilder
I have a StringBuffer initialized outside for loop and inside for loop I am concatenating some strings.

I am getting the warning

'StringBuffer stringBuffer' may be declared as 'StringBuilder'

and

string concatenation as argument to 'stringbuilder.append()' call

Then I changed that StringBuffer to StringBuilder, since it is comparatively faster than StringBuffer. Now I am getting the warning as

string concatenation as argument to 'stringbuilder.append()' call

Sample code:

```<code>public static String stringConcat(String[] words) {
    StringBuffer stringBuffer = new StringBuffer();
    for (String word : words) {
        stringBuffer.append(word).append(" ");
    }
    return stringBuffer.toString();
}
</code>```

Why I am getting these warnings.

Edit Actual code:

```<code>stringBuffer.append(word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()).append(" ");
</code>```

答:
The point is : you are still using the + operator for strings in your expression that you give to append():

```<code>... word.substring(0, 1).toUpperCase() + word...
</code>```

That negates the whole point of using a StringBuilder (or StringBuffer).

Instead: simply call append() twice! The core idea of using a buffer/builder is to concat your desired result by only using append calls; like:

```<code>append(word.substring(0, 1).toUpperCase()).append(word...
</code>```

Body:
I have a StringBuffer initialized outside for loop and inside for loop I am concatenating some strings.

I am getting the warning

'StringBuffer stringBuffer' may be declared as 'StringBuilder'

and

string concatenation as argument to 'stringbuilder.append()' call

Then I changed that StringBuffer to StringBuilder, since it is comparatively faster than StringBuffer. Now I am getting the warning as

string concatenation as argument to 'stringbuilder.append()' call

Sample code:

public static String stringConcat(String[] words) {
    StringBuffer stringBuffer = new StringBuffer();
    for (String word : words) {
        stringBuffer.append(word).append(" ");
    }
    return stringBuffer.toString();
}

Why I am getting these warnings.

Edit Actual code:

stringBuffer.append(word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()).append(" ");

Body:
The point is : you are still using the + operator for strings in your expression that you give to append():

... word.substring(0, 1).toUpperCase() + word...

That negates the whole point of using a StringBuilder (or StringBuffer).

Instead: simply call append() twice! The core idea of using a buffer/builder is to concat your desired result by only using append calls; like:

append(word.substring(0, 1).toUpperCase()).append(word...


问:
PowerShell Select Excel Cell
I have an Excel sheet which is the product of multiple CSVs.  After all the pasting is completed and the file opens, I just want cell C5 to be selected.

Previously in this script, my last step before closing all documents was $Worksheet2.Range("C5").select().  It was working until I added a third CSV from which this Excel sheet ($Worksheet2) is pulling data.  Now I get Unable to get the Select property of the Range class and it leaves the last copy/paste area highlighted.  Help is appreciated.

Code Snippet

```<code>#Copy the data from the export to Worklog Template file
$Excel = New-Object -ComObject excel.application
$Excel.visible = $false
$WorkBook = $excel.Workbooks.Open($SAMTemp2)
$WorkBook2 = $excel.Workbooks.open($Template)
$Worksheet = $Workbook.WorkSheets.item("Export2")
$Worksheet.activate()
#Open the Planned SO Flags CSV
$WorkBook3 = $excel.Workbooks.open($SAMTemp3)
$Worksheet3 = $Workbook3.WorkSheets.item("Export3")
$Worksheet3.activate()
#SO Range Copy
$rangeAc = $WorkSheet.Range(“B2:B26”)
$rangeAc.Copy() | out-null
#Select sheet 2
$Worksheet2 = $Workbook2.Worksheets.item(“Worklog”)
$worksheet2.activate()
#SO Range Paste
$rangeAp = $Worksheet2.Range(“K6:K30”)
$rangeAp.PasteSpecial(-4163)

#Target Range Copy
$rangeC1c = $WorkSheet.Range(“F2:F26”)
$rangeC1c.Copy() | out-null
#Target Range Paste
$rangeC1p = $Worksheet2.Range(“AC6:AC30”)
$rangeC1p.PasteSpecial(-4163)
#SODetails Range Copy
$rangeC2c = $WorkSheet.Range(“D2:D26”)
$rangeC2c.Copy() | out-null
#SODetails Range Paste
$rangeC2p = $Worksheet2.Range(“AB6:AB30”)
$rangeC2p.PasteSpecial(-4163)
#RowDetails Range Copy
$rangeC2c = $WorkSheet.Range(“E2:E26”)
$rangeC2c.Copy() | out-null
#RowDetails Range Paste
$rangeC2p = $Worksheet2.Range(“AD6:AD30”)
$rangeC2p.PasteSpecial(-4163)

#Trim Status down to "O" or "C" and paste...
#Status Range Copy
$rangeFc = $WorkSheet.Range(“C2:C26”)
$rangeFc.Copy() | out-null
#Status Range Paste
$rangeFp = $Worksheet2.Range(“AA6:AA30”)
$rangeFp.PasteSpecial(-4163)

#Comments are just RowDetails again.
#RowDetails Range Copy
$rangeEc = $WorkSheet.Range(“E2:E26”)
$rangeEc.Copy() | out-null
#RowDetails Range Paste
$rangeEp = $Worksheet2.Range(“P6:P30”)
$rangeEp.PasteSpecial(-4163)

$Worksheet2.Range("C6") = $TechName
$Worksheet2.Range("C3:C4") = $VisitDate

#Adds all planned SOs to the Planned SO section
#Planned SO Range Copy
$rangeGc = $WorkSheet3.Range(“B2:B16”)
$rangeGc.Copy() | out-null
#Planned SO Range Paste to the Planned SO section
$rangeGp = $Worksheet2.Range(“F6:F20”)
$rangeGp.PasteSpecial(-4163)

#Hours Range Copy
$rangeHc = $WorkSheet.Range(“I2:I16”)
$rangeHc.Copy() | out-null
#Hours Range Paste
$rangeHp = $Worksheet2.Range(“L6:L20”)
$rangeHp.PasteSpecial(-4163)

#PlannedHours Range Copy
$rangeHc = $WorkSheet3.Range(“I2:I16”)
$rangeHc.Copy() | out-null
#PlannedHours Range Paste
$rangeHp = $Worksheet2.Range(“G6:G20”)
$rangeHp.PasteSpecial(-4163)

$Worksheet2.Item("C5").select()

$workbook2.SaveAs($WorkLogSave)
$workbook.close($true)
$WorkBook3.close($true)
</code>```

答:
Well, I never got this to work.  So I ended up doing this:

```<code>$rangeC5c = $WorkSheet.Range(“G2”)
$rangeC5c.Copy() | out-null
$rangeC5p = $Worksheet2.Range("C5")
$rangeC5p.PasteSpecial(-4163)
</code>```

G2 has the same data that was in C5 but it ends up leaving that as the selected cell when the document is opened and that's all I wanted.  Totally worth it.

Title: PowerShell Select Excel Cell

Body:
I have an Excel sheet which is the product of multiple CSVs.  After all the pasting is completed and the file opens, I just want cell C5 to be selected.

Previously in this script, my last step before closing all documents was $Worksheet2.Range("C5").select().  It was working until I added a third CSV from which this Excel sheet ($Worksheet2) is pulling data.  Now I get Unable to get the Select property of the Range class and it leaves the last copy/paste area highlighted.  Help is appreciated.

Code Snippet

#Copy the data from the export to Worklog Template file
$Excel = New-Object -ComObject excel.application
$Excel.visible = $false
$WorkBook = $excel.Workbooks.Open($SAMTemp2)
$WorkBook2 = $excel.Workbooks.open($Template)
$Worksheet = $Workbook.WorkSheets.item("Export2")
$Worksheet.activate()
#Open the Planned SO Flags CSV
$WorkBook3 = $excel.Workbooks.open($SAMTemp3)
$Worksheet3 = $Workbook3.WorkSheets.item("Export3")
$Worksheet3.activate()
#SO Range Copy
$rangeAc = $WorkSheet.Range(“B2:B26”)
$rangeAc.Copy() | out-null
#Select sheet 2
$Worksheet2 = $Workbook2.Worksheets.item(“Worklog”)
$worksheet2.activate()
#SO Range Paste
$rangeAp = $Worksheet2.Range(“K6:K30”)
$rangeAp.PasteSpecial(-4163)

#Target Range Copy
$rangeC1c = $WorkSheet.Range(“F2:F26”)
$rangeC1c.Copy() | out-null
#Target Range Paste
$rangeC1p = $Worksheet2.Range(“AC6:AC30”)
$rangeC1p.PasteSpecial(-4163)
#SODetails Range Copy
$rangeC2c = $WorkSheet.Range(“D2:D26”)
$rangeC2c.Copy() | out-null
#SODetails Range Paste
$rangeC2p = $Worksheet2.Range(“AB6:AB30”)
$rangeC2p.PasteSpecial(-4163)
#RowDetails Range Copy
$rangeC2c = $WorkSheet.Range(“E2:E26”)
$rangeC2c.Copy() | out-null
#RowDetails Range Paste
$rangeC2p = $Worksheet2.Range(“AD6:AD30”)
$rangeC2p.PasteSpecial(-4163)

#Trim Status down to "O" or "C" and paste...
#Status Range Copy
$rangeFc = $WorkSheet.Range(“C2:C26”)
$rangeFc.Copy() | out-null
#Status Range Paste
$rangeFp = $Worksheet2.Range(“AA6:AA30”)
$rangeFp.PasteSpecial(-4163)

#Comments are just RowDetails again.
#RowDetails Range Copy
$rangeEc = $WorkSheet.Range(“E2:E26”)
$rangeEc.Copy() | out-null
#RowDetails Range Paste
$rangeEp = $Worksheet2.Range(“P6:P30”)
$rangeEp.PasteSpecial(-4163)

$Worksheet2.Range("C6") = $TechName
$Worksheet2.Range("C3:C4") = $VisitDate

#Adds all planned SOs to the Planned SO section
#Planned SO Range Copy
$rangeGc = $WorkSheet3.Range(“B2:B16”)
$rangeGc.Copy() | out-null
#Planned SO Range Paste to the Planned SO section
$rangeGp = $Worksheet2.Range(“F6:F20”)
$rangeGp.PasteSpecial(-4163)

#Hours Range Copy
$rangeHc = $WorkSheet.Range(“I2:I16”)
$rangeHc.Copy() | out-null
#Hours Range Paste
$rangeHp = $Worksheet2.Range(“L6:L20”)
$rangeHp.PasteSpecial(-4163)

#PlannedHours Range Copy
$rangeHc = $WorkSheet3.Range(“I2:I16”)
$rangeHc.Copy() | out-null
#PlannedHours Range Paste
$rangeHp = $Worksheet2.Range(“G6:G20”)
$rangeHp.PasteSpecial(-4163)

$Worksheet2.Item("C5").select()

$workbook2.SaveAs($WorkLogSave)
$workbook.close($true)
$WorkBook3.close($true)

Body:
Well, I never got this to work.  So I ended up doing this:

$rangeC5c = $WorkSheet.Range(“G2”)
$rangeC5c.Copy() | out-null
$rangeC5p = $Worksheet2.Range("C5")
$rangeC5p.PasteSpecial(-4163)

G2 has the same data that was in C5 but it ends up leaving that as the selected cell when the document is opened and that's all I wanted.  Totally worth it.


问:
Dynamically adding rows to a table using attribute directive in AngularJs
I need to display a table on my HTML page. The table will contain multiple rows. On clicking the '+' icon of a row(let's call it R1), I call an attribute directive to fetch data and display it in a new row(R2) which should be added below the clicked row(R1).

But currently, the data isn't getting displayed and I get a blank row(R2) added below the clicked row(R1).

The code for directive is:

```<code>angular.module(
  "app", []
).controller(
  'Ctrl', [
    "$scope",
    function(
      $scope
    ) {
      $scope.items = {
        "first": {
          "name": "item1"
        },
        "second": {
          "name": "item2"
        },
        "third": {
          "name": "item3"
        }
      };
      $scope.showData = false;

    }
  ]
).directive(
  "expandItem", [
    function() {
      return {
        link: function($scope) {
          $scope.showRdoData = false;

          $scope.subitems = {
            "fir": {
              "names": "subitem1"
            },
            "sec": {
              "names": "subitem2"
            },
            "thd": {
              "names": "subitem3"
            }
          };
        },
        restrict: 'A',
        replace: false,
        template: '<tr ng-repeat="row in ::subitems">' +
          '<td style="background-color: red"><i class="fa fa-fw fa-{{showRdoData ? \'minus\' : \'plus\'}}"></i></td>' +
          '<td style="background-color: blueviolet">{{::row.names}}</td></tr>'
      }
    }
  ]
);
</code>```

Can someone help me in getting the data displayed in the table please? The code is present at JSFiddle.
Please let me know if the question isn't clear. I will try to rephrase it if needed.

答:
So the reason you were having issues was because the ngIf directive does not play well with ngRepeat by passing showData to the directive via an isolate scope you can move the ngIf to the 's and achieve the expected behavior. Here is a link to a working fiddle

HTML

```<code><body ng-app="app">
  <table ng-controller="Ctrl">
    <thead>
      <th>Col1</th>
      <th>Col2</th>
    </thead>
    <tbody>
      <tr ng-repeat-start="item in items" ng-click="showData = !showData">
        <td><i class="fa fa-fw fa-{{showData ? 'minus' : 'plus'}}"></i></td>
        <td>{{item.name}}</td>
      </tr>
      <tr ng-repeat-end expand-item show-data="showData"></tr>
    </tbody>
  </table>
</body>
</code>```

Modified Directive Values

```<code>replace:true,
template: '<tr ng-repeat="row in ::subitems">' +
            '<td ng-if="showData" style="background-color: red"><i class="fa fa-fw fa-{{showRdoData ? \'minus\' : \'plus\'}}"></i></td>' +
            '<td ng-if="showData" style="background-color: blueviolet">{{::row.names}}</td>' +
          '</tr>'
</code>```

Body:
I need to display a table on my HTML page. The table will contain multiple rows. On clicking the '+' icon of a row(let's call it R1), I call an attribute directive to fetch data and display it in a new row(R2) which should be added below the clicked row(R1).

But currently, the data isn't getting displayed and I get a blank row(R2) added below the clicked row(R1).

The code for directive is:

angular.module(
  "app", []
).controller(
  'Ctrl', [
    "$scope",
    function(
      $scope
    ) {
      $scope.items = {
        "first": {
          "name": "item1"
        },
        "second": {
          "name": "item2"
        },
        "third": {
          "name": "item3"
        }
      };
      $scope.showData = false;

    }
  ]
).directive(
  "expandItem", [
    function() {
      return {
        link: function($scope) {
          $scope.showRdoData = false;

          $scope.subitems = {
            "fir": {
              "names": "subitem1"
            },
            "sec": {
              "names": "subitem2"
            },
            "thd": {
              "names": "subitem3"
            }
          };
        },
        restrict: 'A',
        replace: false,
        template: '
' +
          '	' +
          '{{::row.names}}
'
      }
    }
  ]
);

Can someone help me in getting the data displayed in the table please? The code is present at JSFiddle.
Please let me know if the question isn't clear. I will try to rephrase it if needed.

Body:
So the reason you were having issues was because the ngIf directive does not play well with ngRepeat by passing showData to the directive via an isolate scope you can move the ngIf to the <td>'s and achieve the expected behavior. Here is a link to a working fiddle

HTML

<body ng-app="app">
  <table ng-controller="Ctrl">
    <thead>
      <th>Col1</th>
      <th>Col2</th>
    </thead>
    <tbody>
      <tr ng-repeat-start="item in items" ng-click="showData = !showData">
        <td><i class="fa fa-fw fa-{{showData ? 'minus' : 'plus'}}"></i></td>
        <td>{{item.name}}</td>
      </tr>
      <tr ng-repeat-end expand-item show-data="showData"></tr>
    </tbody>
  </table>
</body>

Modified Directive Values

replace:true,
template: '<tr ng-repeat="row in ::subitems">' +
            '<td ng-if="showData" style="background-color: red"><i class="fa fa-fw fa-{{showRdoData ? \'minus\' : \'plus\'}}"></i></td>' +
            '<td ng-if="showData" style="background-color: blueviolet">{{::row.names}}</td>' +
          '</tr>'


问:
How to get filtered object length
I am trying to show that there is no data to display when the size of filtered object is zero. Is there any way to check its size after calling filter method?

```<code>this.state.items
.filter(item => {
    // filter code
})
.map(item => {
    // display data
})
</code>```

For example, this.state.items has ten items and becomes zero after passing through filter method. I'd like to display the message at this point.

答:
First store the filtered data in a variable:

```<code>let filteredData = this.state.items
                         .filter(item => {
                              // filter code
                          });
</code>```

Now filteredData will contain the filtered data, now you can check the length of this variable and return 'No Data Found' if length = 0, Use either ternary operator:

```<code>return filteredData.length ?

               filteredData.map(item => {
                    // display data
               })

               :

               <div>No data found </div>;
</code>```

Or you can use if-else condition also:

```<code>if(filteredData.length)
      filteredData.map(item => {
         // display data
      })
else
   <div>No data found </div>
</code>```

Title: How to get filtered object length

Body:
I am trying to show that there is no data to display when the size of filtered object is zero. Is there any way to check its size after calling filter method?

this.state.items
.filter(item => {
    // filter code
})
.map(item => {
    // display data
})

For example, this.state.items has ten items and becomes zero after passing through filter method. I'd like to display the message at this point.

Body:
First store the filtered data in a variable:

let filteredData = this.state.items
                         .filter(item => {
                              // filter code
                          });

Now filteredData will contain the filtered data, now you can check the length of this variable and return 'No Data Found' if length = 0, Use either ternary operator:

return filteredData.length ?

               filteredData.map(item => {
                    // display data
               })

               :

               <div>No data found </div>;

Or you can use if-else condition also:

if(filteredData.length)
      filteredData.map(item => {
         // display data
      })
else
   <div>No data found </div>


问:
How to take a subset of datatable?
```<code>SomeDS.SomeDT subDt = new SomeDS.SomeDT();

subDt = mainds.mainDT.Where(x=>x.status=='Active').CopyToDataTable();
</code>```

Basically the idea is very simple, i have a mainDS which consists of masterset of data and i need only those data that is active and store into another variable under the exact same datatable type. but CopyToDataTable() change the type to become System.Data.DataTable and it cannot be converted to type SomeDS.SomeDT

答:
Check with the below one

```<code>SomeDS.SomeDT subDt = mainds.mainDT.Clone();
subDt = mainds.mainDT.Where(x=>x.status=='Active').Select(x=> x).CopyToDataTable();
</code>```

or you can use a foreach too

```<code>SomeDS.SomeDT subDt = mainds.mainDT.Clone();
foreach (DataRow dr in mainds.mainDT.Rows)
{
   if (/*put some Condition */)
   {
      subDt.ImportRow(dr);
   }
}
</code>```

See below the complete example

```<code>        DataTable dtMain = new DataTable();
        dtMain.Columns.Add("C1", typeof(string));
        dtMain.Columns.Add("C2", typeof(string));
        dtMain.Columns.Add("C3", typeof(string));
        dtMain.Rows.Add(new object[] { "1", "test1", "test1" });
        dtMain.Rows.Add(new object[] { "2", "test2", "test2" });
        dtMain.Rows.Add(new object[] { "3", "test3", "test3" });

        DataTable dtChild = dtMain.Clone();
        dtChild = dtMain.AsEnumerable()
                        .Where(x => x.Field<string>("C2") != "test2")
                        .Select(x=> x).CopyToDataTable();

        foreach (DataRow dr in dtChild.Rows)
        {
            Console.WriteLine(dr["C1"].ToString());
            Console.WriteLine(dr["C2"].ToString());
            Console.WriteLine(dr["C3"].ToString());
        }
</code>```

OUTPUT

Title: How to take a subset of datatable?

Body:
SomeDS.SomeDT subDt = new SomeDS.SomeDT();

subDt = mainds.mainDT.Where(x=>x.status=='Active').CopyToDataTable();

Basically the idea is very simple, i have a mainDS which consists of masterset of data and i need only those data that is active and store into another variable under the exact same datatable type. but CopyToDataTable() change the type to become System.Data.DataTable and it cannot be converted to type SomeDS.SomeDT

Body:
Check with the below one

SomeDS.SomeDT subDt = mainds.mainDT.Clone();
subDt = mainds.mainDT.Where(x=>x.status=='Active').Select(x=> x).CopyToDataTable();

or you can use a foreach too

SomeDS.SomeDT subDt = mainds.mainDT.Clone();
foreach (DataRow dr in mainds.mainDT.Rows)
{
   if (/*put some Condition */)
   {
      subDt.ImportRow(dr);
   }
}

See below the complete example

        DataTable dtMain = new DataTable();
        dtMain.Columns.Add("C1", typeof(string));
        dtMain.Columns.Add("C2", typeof(string));
        dtMain.Columns.Add("C3", typeof(string));
        dtMain.Rows.Add(new object[] { "1", "test1", "test1" });
        dtMain.Rows.Add(new object[] { "2", "test2", "test2" });
        dtMain.Rows.Add(new object[] { "3", "test3", "test3" });

        DataTable dtChild = dtMain.Clone();
        dtChild = dtMain.AsEnumerable()
                        .Where(x => x.Field<string>("C2") != "test2")
                        .Select(x=> x).CopyToDataTable();

        foreach (DataRow dr in dtChild.Rows)
        {
            Console.WriteLine(dr["C1"].ToString());
            Console.WriteLine(dr["C2"].ToString());
            Console.WriteLine(dr["C3"].ToString());
        }

OUTPUT


问:
Switch statement ends prematurely in for loop
So I am doing a HackerRank question and cant seem to pass all the tests for some reason. My code passed the first run but appears to fail all the other tests. Looking through debugging, it seems that the for loop terminates once all the switch cases have been used.

This exercise is a Java List problem. An input is given such as

```<code>5
12 0 1 78 12
2
Insert
5 23
Delete
0
</code>```

The first line contains an integer,N  (the initial number of elements in the list, which is 5 in this case ).
The second line contains N space-separated integers that make up the list.
The third line contains an integer,q  (the number of queries).
The  subsequent lines describe the queries, and each query is described over two lines:

If the first line of a query contains the String Insert, then the second line contains two space separated integer, and the value  must be inserted into  at index .
   If the first line of a query contains the String Delete, then the second line contains index , whose element must be deleted from .

```<code>import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ListSolution {
public static void main(String[] args){
    List<Integer> list1 = new ArrayList<>();
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    sc.nextLine();
    for(int i =0;i<n;i++){
        list1.add(sc.nextInt());
    }

    sc.nextLine();
    int q = sc.nextInt();
    sc.nextLine();
    for(int i=0;i<q;i++){
        switch(sc.nextLine()){
        case "Insert" :
            int x = sc.nextInt();
            int y = sc.nextInt();
            sc.nextLine();
            list1.add(x,y);
            continue;
        case "Delete" :
            int z = sc.nextInt();
            list1.remove(z);
            continue;
        default:
            continue;
        }
    }
    for(int i=0;i<list1.size(); i++){
        System.out.print(list1.get(i)+" ");;
    }
}
}
</code>```

I was able to finish the problem and pass this specific input. However, it failed all the other in which there were 3 queries in which Insert and Delete are the first two. It seemed that once the switch went through all the cases, it terminated the for loop even though there were more iterations to be done. An example of such input is this:

```<code>10
100 50 20 10 70 80 200 259 1 900
3
Insert
2 80
Delete
6
Insert
5 89
</code>```

答:
Here is a solution that works:

```<code>import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class ListSolution {
    public static void main(String[] args){
        List<Integer> list1 = new ArrayList<>();
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.nextLine();
        for(int i =0;i<n;i++){
            list1.add(sc.nextInt());
        }

        sc.nextLine();
        int q = sc.nextInt();
        sc.nextLine();
        for(int i=0;i<=q;i++){
            String input = sc.nextLine();
            switch(input) {
                case "Insert" :
                    int x = sc.nextInt();
                    int y = sc.nextInt();
                    sc.nextLine();
                    list1.add(x,y);
                    continue;
                case "Delete" :
                    int z = sc.nextInt();
                    list1.remove(z);
                    sc.nextLine();
                    continue;
                default:
                    continue;
            }
        }
        for(int i=0;i<list1.size(); i++){
            System.out.print(list1.get(i)+" ");;
        }
    }
}
</code>```

The main thing you forgot was that after delete you did not request to get a new line.  So in your second example, the switch was on an empty line return, hence you getting the value wrong.

If I were doing this exercise I would get each line as a String, then parse it.  E.g. for getting to integers:

```<code>String[] numbers = sc.nextLine().split(" ");
for(String number: numbers){
    list1.add(Integer.valueOf(number));
}
</code>```

This way you do not have the weird end of line confusions.

Body:
So I am doing a HackerRank question and cant seem to pass all the tests for some reason. My code passed the first run but appears to fail all the other tests. Looking through debugging, it seems that the for loop terminates once all the switch cases have been used.

This exercise is a Java List problem. An input is given such as

5
12 0 1 78 12
2
Insert
5 23
Delete
0

The first line contains an integer,N  (the initial number of elements in the list, which is 5 in this case ).
The second line contains N space-separated integers that make up the list.
The third line contains an integer,q  (the number of queries).
The  subsequent lines describe the queries, and each query is described over two lines:

If the first line of a query contains the String Insert, then the second line contains two space separated integer, and the value  must be inserted into  at index .
   If the first line of a query contains the String Delete, then the second line contains index , whose element must be deleted from .

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ListSolution {
public static void main(String[] args){
    List<Integer> list1 = new ArrayList<>();
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    sc.nextLine();
    for(int i =0;i<n;i++){
        list1.add(sc.nextInt());
    }

    sc.nextLine();
    int q = sc.nextInt();
    sc.nextLine();
    for(int i=0;i<q;i++){
        switch(sc.nextLine()){
        case "Insert" :
            int x = sc.nextInt();
            int y = sc.nextInt();
            sc.nextLine();
            list1.add(x,y);
            continue;
        case "Delete" :
            int z = sc.nextInt();
            list1.remove(z);
            continue;
        default:
            continue;
        }
    }
    for(int i=0;i<list1.size(); i++){
        System.out.print(list1.get(i)+" ");;
    }
}
}

I was able to finish the problem and pass this specific input. However, it failed all the other in which there were 3 queries in which Insert and Delete are the first two. It seemed that once the switch went through all the cases, it terminated the for loop even though there were more iterations to be done. An example of such input is this:

10
100 50 20 10 70 80 200 259 1 900
3
Insert
2 80
Delete
6
Insert
5 89

Body:
Here is a solution that works:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class ListSolution {
    public static void main(String[] args){
        List<Integer> list1 = new ArrayList<>();
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.nextLine();
        for(int i =0;i<n;i++){
            list1.add(sc.nextInt());
        }

        sc.nextLine();
        int q = sc.nextInt();
        sc.nextLine();
        for(int i=0;i<=q;i++){
            String input = sc.nextLine();
            switch(input) {
                case "Insert" :
                    int x = sc.nextInt();
                    int y = sc.nextInt();
                    sc.nextLine();
                    list1.add(x,y);
                    continue;
                case "Delete" :
                    int z = sc.nextInt();
                    list1.remove(z);
                    sc.nextLine();
                    continue;
                default:
                    continue;
            }
        }
        for(int i=0;i<list1.size(); i++){
            System.out.print(list1.get(i)+" ");;
        }
    }
}

The main thing you forgot was that after delete you did not request to get a new line.  So in your second example, the switch was on an empty line return, hence you getting the value wrong.

If I were doing this exercise I would get each line as a String, then parse it.  E.g. for getting to integers:

String[] numbers = sc.nextLine().split(" ");
for(String number: numbers){
    list1.add(Integer.valueOf(number));
}

This way you do not have the weird end of line confusions.


问:
Calling AWS Lambda Function from MVC controller
I have an AWS Lambda function (API) that returns a result based on some parameters. I want to pass the parameters from my C# controller and consume the returned result as well. How can I call my Lambda API from the C# controller?</p>

答:
somethings like this:</p>

```<code>        AmazonLambdaClient alc = new AmazonLambdaClient(AWSAccessKey, AWSSecretKey, RegionEndpoint.USEast1);
        Amazon.Lambda.Model.InvokeRequest ir = new Amazon.Lambda.Model.InvokeRequest();
        ir.FunctionName = "arn:YOUR_FUNCTIONS_ARN";
        ir.Payload = SOME_JSON_ARGUMENTS;
        var res = alc.Invoke(ir);
        var yourResult = DESERIALIZE_SOMEHOW(res.Payload);
</code>```

Body:
somethings like this:

        AmazonLambdaClient alc = new AmazonLambdaClient(AWSAccessKey, AWSSecretKey, RegionEndpoint.USEast1);
        Amazon.Lambda.Model.InvokeRequest ir = new Amazon.Lambda.Model.InvokeRequest();
        ir.FunctionName = "arn:YOUR_FUNCTIONS_ARN";
        ir.Payload = SOME_JSON_ARGUMENTS;
        var res = alc.Invoke(ir);
        var yourResult = DESERIALIZE_SOMEHOW(res.Payload);


问:
Interaction.Behaviors in Windows 10 UAP
I'm experimenting with using Interaction.Behaviors in XAML to bind events to my controller like so,

```<code><GridView x:Name="mygrid" >
    <interact:Interaction.Behaviors>
        <interactcore:EventTriggerBehavior EventName="SelectionChanged">
            <interactcore:InvokeCommandAction
                Command="{Binding Controller.Test}"
                CommandParameter="{Binding ElementName=mygrid, Path=SelectedItem}"/>
        </interactcore:EventTriggerBehavior>
    </interact:Interaction.Behaviors>
</GridView>
</code>```

This works perfectly except... Visual Studio 2015 shows the following errors,

```<code>Severity    Code    Description Project File    Line    Suppression State
Error       The name "EventTriggerBehavior" does not exist in the namespace "using:Microsoft.Xaml.Interactions.Core".   MVC C:\Prototype\MVC\MVC\MainPage.xaml  19
Error       The name "InvokeCommandAction" does not exist in the namespace "using:Microsoft.Xaml.Interactions.Core".    MVC C:\Prototype\MVC\MVC\MainPage.xaml  20
Error       The name "Interaction" does not exist in the namespace "using:Microsoft.Xaml.Interactivity".    MVC C:\Prototype\MVC\MVC\MainPage.xaml  18
</code>```

This has caused the designer to break, so even though the code works, the designer doesn't.  Any ideas?

My includes are...

```<code>xmlns:interact="using:Microsoft.Xaml.Interactivity"
xmlns:interactcore="using:Microsoft.Xaml.Interactions.Core"
</code>```

And just to clarify, I included the behaviors SDK via the "Add Reference..." dialog.

答:
The answer that worked for me were the comments made by Grace Feng in the question and confirmed by Nick.

That is when doing Windows 10 Universal apps use the Microsoft.Xaml.Behaviors.Uwp.Managed nuget package and remove the Behaviors SDK (XAML) package

Title: Interaction.Behaviors in Windows 10 UAP

Body:
I'm experimenting with using Interaction.Behaviors in XAML to bind events to my controller like so,

<GridView x:Name="mygrid" >
    <interact:Interaction.Behaviors>
        <interactcore:EventTriggerBehavior EventName="SelectionChanged">
            <interactcore:InvokeCommandAction
                Command="{Binding Controller.Test}"
                CommandParameter="{Binding ElementName=mygrid, Path=SelectedItem}"/>
        </interactcore:EventTriggerBehavior>
    </interact:Interaction.Behaviors>
</GridView>

This works perfectly except... Visual Studio 2015 shows the following errors,

Severity    Code    Description Project File    Line    Suppression State
Error       The name "EventTriggerBehavior" does not exist in the namespace "using:Microsoft.Xaml.Interactions.Core".   MVC C:\Prototype\MVC\MVC\MainPage.xaml  19
Error       The name "InvokeCommandAction" does not exist in the namespace "using:Microsoft.Xaml.Interactions.Core".    MVC C:\Prototype\MVC\MVC\MainPage.xaml  20
Error       The name "Interaction" does not exist in the namespace "using:Microsoft.Xaml.Interactivity".    MVC C:\Prototype\MVC\MVC\MainPage.xaml  18

This has caused the designer to break, so even though the code works, the designer doesn't.  Any ideas?

My includes are...

xmlns:interact="using:Microsoft.Xaml.Interactivity"
xmlns:interactcore="using:Microsoft.Xaml.Interactions.Core"

And just to clarify, I included the behaviors SDK via the "Add Reference..." dialog.


问:
Creating a new thymeleaf template in IntelliJ
I am using IntelliJ to make an app that uses thymeleaf but when I click to create a new file there is no option for thymeleaf. I know thymeleaf files are just html, but it seems like there should be a preconfigured option for this?</p>

答:
Use Plugin Configuration Wizard to enable Thymeleaf plugin.

You can manage plugins to enable or disable plugins in intellij.

or

File -> Other Settings -> Config Plugins -> check thymeleaf.

Don't forget to add xmlns:th=”http://www.thymeleaf.org” in HTML root as shown here.


问:
alamofire throws "expected declaration" error
I downloaded the latest versions of xcode and alamofire to create a simple app... unfortunately it seems impossible to send out a request !

Every time I try to build the project, xcode sends me a "expected declaration" error which I don't understand.

Any ideas ? I googled for hours and couldn't find any helpful posts...

答:
If Xcode sends you a "expected declaration" error message, you probably located Alamofire part in class declaration area.

Solution:
Move Alamofire part inside some method. like viewDidLoad method.

Example:

```<code>class MyView : UIViewController {

    // Not here
    // Alamofire.request( ...

    override func viewDidLoad() {
        super.viewDidLoad()

        // Here
        Alamofire.request( ...
    }
}
</code>```

Body:
If Xcode sends you a "expected declaration" error message, you probably located Alamofire part in class declaration area.

Solution:
Move Alamofire part inside some method. like viewDidLoad method.

Example:

class MyView : UIViewController {

    // Not here
    // Alamofire.request( ...

    override func viewDidLoad() {
        super.viewDidLoad()

        // Here
        Alamofire.request( ...
    }
}


问:
Ignoring exceptions when using c# selenium webdriverWait wait.untill() function
In order to check if an Element is exists and clickble  i'm trying to write a boolean method which will wait for the element to be enabled and displyed using C# selenium's webDriverWait as follow:

```<code>webDriverWait wait = new webDriverWait(driver, timeSpan.fromSeconds(60));

Wait.untill( d => webElement.enabled() && webElement.displayed());
</code>```

In case the above conditions do not happen, I want the method to return 'false'. The problem is that I get exceptions thrown.
How can I ignore exceptions such as noSuchElementException and timeOutException in case they are thrown?
I have tried to use try catch block but it didn't help and exceptions were thrown.

答:
WebDriverWait implements DefaultWait class that contains public void IgnoreExceptionTypes(params Type[] exceptionTypes) method.

You can use this method for defining all the exception types you want to ignore while waiting for element to get enabled before clicking.

For example :

```<code>WebDriverWait wdw = new WebDriverWait(driver, TimeSpan.FromSeconds(120));
wdw.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(ElementNotVisibleException));
</code>```

In the preceding code wait will ignore NoSuchElementException and ElementNotVisibleException exceptions

Body:
In order to check if an Element is exists and clickble  i'm trying to write a boolean method which will wait for the element to be enabled and displyed using C# selenium's webDriverWait as follow:

webDriverWait wait = new webDriverWait(driver, timeSpan.fromSeconds(60));

Wait.untill( d => webElement.enabled() && webElement.displayed());

In case the above conditions do not happen, I want the method to return 'false'. The problem is that I get exceptions thrown.
How can I ignore exceptions such as noSuchElementException and timeOutException in case they are thrown?
I have tried to use try catch block but it didn't help and exceptions were thrown.

Body:
WebDriverWait implements DefaultWait class that contains public void IgnoreExceptionTypes(params Type[] exceptionTypes) method.

You can use this method for defining all the exception types you want to ignore while waiting for element to get enabled before clicking.

For example :

WebDriverWait wdw = new WebDriverWait(driver, TimeSpan.FromSeconds(120));
wdw.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(ElementNotVisibleException));

In the preceding code wait will ignore NoSuchElementException and ElementNotVisibleException exceptions


问:
Execute multiple functions at once
I need to make a simple calculator for a school project using only functions.

One of the functions is:

```<code>double addition(double a, double b)
{
    return a + b;
}
</code>```

And I call it and show the results doing this:

```<code>printf( "Addition: %.2lf\n", addition(x,y));
</code>```

I have other functions for substraction, multiplication, and division.

I need to perform each one of those separately, and then, perform them all at once.

How can I integrate all of these functions in just one function, like this:

```<code>printf( "All of the results %.2lf\n", allfunctions(x,y));
</code>```

Is it possible?

I'm trying to avoid doing something like this:

```<code>printf( "Addition: %.2lf\n", addition(x,y));
printf( "Substraction: %.2lf\n", substraction(x,y));
</code>```

Thanks.

答:
```<code>#define NUMBER_OF_FUNCTIONS 4 //assuming add subtract multiply divide
double[NUMBER_OF_FUNCTIONS] allFunctions(double x,double y) {
  double answer[NUMBER_OF_FUNCTIONS];
  int i = 0;
  answer[i++]=addition(x,y);
  answer[i++]=subtraction(x,y);
  answer[i++]=multiplication(x,y);
  answer[i++]=division(x,y);
  return answer;
}

// ...
  {
    double a[NUMBER_OF_FUNCTIONS] = allFunctions(x,y);
    printf("Addition: %2lf\nSubtraction: %2lf\nMultiplication: %2lf\nDivision: %2lf\n",*a,a[1],a[2],a[3]);
  }
</code>```

Title: Execute multiple functions at once

Body:
I need to make a simple calculator for a school project using only functions.

One of the functions is:

double addition(double a, double b)
{
    return a + b;
}

And I call it and show the results doing this:

printf( "Addition: %.2lf\n", addition(x,y));

I have other functions for substraction, multiplication, and division.

I need to perform each one of those separately, and then, perform them all at once.

How can I integrate all of these functions in just one function, like this:

printf( "All of the results %.2lf\n", allfunctions(x,y));

Is it possible?

I'm trying to avoid doing something like this:

printf( "Addition: %.2lf\n", addition(x,y));
printf( "Substraction: %.2lf\n", substraction(x,y));

Thanks.


问:
tensorflow loss summary with respect to iteration time
Is there a way to logging tensorflow loss (along training iterations) with respect to both iteration number and time elapsed during training. Then in tensorboard, we can see two curves for the training loss?</p>

答: TensorBoard has three options for choosing the X-axis display, which can be found in the left panel on the scalar dashboard. They are "step", "wall time" and "relative time". You can change the display to relative or wall if you want to get a chronological view of the data.</p>


问:
Replace attribute not valid html5 with jquery
How to replace attribute and set value with jquery

old html

```<code><div class="container">
<table>
<tr>
    <td width="106" valign="top" style="background: red">
          <p align="center">text</p>
    </td>
</tr>
</table>
</div>
</code>```

New HTML

```<code><div class="container">
<table>
<tr>
    <td style="width:106px; background: red;">
          <p style="text-align:center;">text</p>
    </td>
</tr>
</table>
</div>
</code>```

Thank you in advance

答:
```<code>You can replace the attributes and set the value for it using jquery :
</code>```

HTML Code :

Give some class name to the tag you want to set the attribute value

```<code><div class="container">
<table>
<tr>
    <td class ="table-cell">
      <p class = "text">text</p>
    </td>
</tr>
</table>
</div>
</code>```

jquery Code :

While using class name like this (table-cell) it should be converted to Camel casing (tableCell)

```<code>$(function(){
     $(".tableCell").style.width = "106px";
     $(".tableCell").style.backgroundColor = "red";
     $(".text").style.textAlign = "center";
});
</code>```

Body:
How to replace attribute and set value with jquery

old html

text

New HTML

text

Thank you in advance

Body:
You can replace the attributes and set the value for it using jquery :

HTML Code :

Give some class name to the tag you want to set the attribute value

<div class="container">
<table>
<tr>
    <td class ="table-cell">
      <p class = "text">text</p>
    </td>
</tr>
</table>
</div>

jquery Code :

While using class name like this (table-cell) it should be converted to Camel casing (tableCell)

$(function(){
     $(".tableCell").style.width = "106px";
     $(".tableCell").style.backgroundColor = "red";
     $(".text").style.textAlign = "center";
});


问:
Changing UIImage color
I'm trying to change color of UIImage. My code:

```<code>-(UIImage *)coloredImage:(UIImage *)firstImage withColor:(UIColor *)color {
    UIGraphicsBeginImageContext(firstImage.size);

    CGContextRef context = UIGraphicsGetCurrentContext();
    [color setFill];

    CGContextTranslateCTM(context, 0, firstImage.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextSetBlendMode(context, kCGBlendModeCopy);
    CGRect rect = CGRectMake(0, 0, firstImage.size.width, firstImage.size.height);
    CGContextDrawImage(context, rect, firstImage.CGImage);

    CGContextClipToMask(context, rect, firstImage.CGImage);
    CGContextAddRect(context, rect);
    CGContextDrawPath(context,kCGPathElementMoveToPoint);

    UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return coloredImg;
}
</code>```

This code works, but obtained image is not so well as shoud be: bounds pixels of returned image are intermittent and not so smooth as in my first image. How can I resolve this problem?

答:
Swift 3:</p>

```<code>extension UIImage{

    static func multiplyImageByConstantColor(image:UIImage,color:UIColor) -> UIImage{

        let backgroundSize = image.size
        UIGraphicsBeginImageContext(backgroundSize)

        guard let ctx = UIGraphicsGetCurrentContext() else {return image}

        var backgroundRect=CGRect()
        backgroundRect.size = backgroundSize
        backgroundRect.origin.x = 0
        backgroundRect.origin.y = 0

        var r:CGFloat = 0
        var g:CGFloat = 0
        var b:CGFloat = 0
        var a:CGFloat = 0
        color.getRed(&r, green: &g, blue: &b, alpha: &a)
        ctx.setFillColor(red: r, green: g, blue: b, alpha: a)

        // Unflip the image
        ctx.translateBy(x: 0, y: backgroundSize.height)
        ctx.scaleBy(x: 1.0, y: -1.0)
        ctx.clip(to: CGRect(0, 0, image.size.width, image.size.height), mask: image.cgImage!)
        ctx.fill(backgroundRect)

        var imageRect=CGRect()
        imageRect.size = image.size
        imageRect.origin.x = (backgroundSize.width - image.size.width)/2
        imageRect.origin.y = (backgroundSize.height - image.size.height)/2

        ctx.setBlendMode(.multiply)
        ctx.draw(image.cgImage!, in: imageRect)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }
}
</code>```

Title: Changing UIImage color

Body:
I'm trying to change color of UIImage. My code:

-(UIImage *)coloredImage:(UIImage *)firstImage withColor:(UIColor *)color {
    UIGraphicsBeginImageContext(firstImage.size);

    CGContextRef context = UIGraphicsGetCurrentContext();
    [color setFill];

    CGContextTranslateCTM(context, 0, firstImage.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextSetBlendMode(context, kCGBlendModeCopy);
    CGRect rect = CGRectMake(0, 0, firstImage.size.width, firstImage.size.height);
    CGContextDrawImage(context, rect, firstImage.CGImage);

    CGContextClipToMask(context, rect, firstImage.CGImage);
    CGContextAddRect(context, rect);
    CGContextDrawPath(context,kCGPathElementMoveToPoint);

    UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return coloredImg;
}

This code works, but obtained image is not so well as shoud be: bounds pixels of returned image are intermittent and not so smooth as in my first image. How can I resolve this problem?

Body:
Swift 3:

extension UIImage{

    static func multiplyImageByConstantColor(image:UIImage,color:UIColor) -> UIImage{

        let backgroundSize = image.size
        UIGraphicsBeginImageContext(backgroundSize)

        guard let ctx = UIGraphicsGetCurrentContext() else {return image}

        var backgroundRect=CGRect()
        backgroundRect.size = backgroundSize
        backgroundRect.origin.x = 0
        backgroundRect.origin.y = 0

        var r:CGFloat = 0
        var g:CGFloat = 0
        var b:CGFloat = 0
        var a:CGFloat = 0
        color.getRed(&r, green: &g, blue: &b, alpha: &a)
        ctx.setFillColor(red: r, green: g, blue: b, alpha: a)

        // Unflip the image
        ctx.translateBy(x: 0, y: backgroundSize.height)
        ctx.scaleBy(x: 1.0, y: -1.0)
        ctx.clip(to: CGRect(0, 0, image.size.width, image.size.height), mask: image.cgImage!)
        ctx.fill(backgroundRect)

        var imageRect=CGRect()
        imageRect.size = image.size
        imageRect.origin.x = (backgroundSize.width - image.size.width)/2
        imageRect.origin.y = (backgroundSize.height - image.size.height)/2

        ctx.setBlendMode(.multiply)
        ctx.draw(image.cgImage!, in: imageRect)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }
}


问:
iphone, xcode; Reverse engineer a nib
I was wondering if there is a way i can design a nib/xib file and generate code for that?
meaning, instead of writing lines of code to generate an interface, would'nt it be easier to design and nib file using IB and get the source or something?

Thanks

答:
I don't think its possible in xcode to generate code for a nib file designed.I know you are referring to web designing tools like macromedia dreamweaver.

Secondly why do you require the code?X code provides the facility to integrate the nib in the code itself.

Thanks

Title: iphone, xcode; Reverse engineer a nib


问:
Amazon SNS GCM/FCM message payload
I am trying to send a push notification (PN) from my application server to an android device using publish end point in the Amazon SNS console with this message and message structure as json it works fine.

```<code>{
"GCM": "{ \"notification\": { \"text\": \"test message\" } }"
}
</code>```

But when I try to implement the same in Java it the device does not receive the notification.

```<code>PublishRequest publishRequest = new PublishRequest();
        publishRequest.setTargetArn("arn:aws:sns:ap-south-1:818862955266:endpoint/GCM/TestApp/a1ec8114-58c9-371b-bb76-d8d16e674e52");
        String message = "{\"GCM\": \"{ \"notification\": { \"text\": \"test message\" } }\"}";

        ObjectMapper mapper = new ObjectMapper();
        PushRequest pushRequest = new PushRequest();
        pushRequest.setDef("Test");

        GCM gcm = new GCM();
        Notification notification = new Notification();
        notification.setText("hello");
        gcm.setNotification(notification);
        pushRequest.setGcm(gcm);

        String jsonInString = mapper.writeValueAsString(pushRequest);
        publishRequest.setMessage(jsonInString);
        publishRequest.setMessageStructure("json");
        System.out.println("Publist request:"+publishRequest.toString());
        PublishResult publishResult = amazonSNSTemplate.getAmazonSNSClient().publish(publishRequest);
        System.out.println(publishResult.toString());
        System.out.println(publishResult.getSdkResponseMetadata().toString());

public class PushRequest {

    @JsonProperty("default")
    private String def;
    @JsonProperty("GCM")
    private GCM gcm;
    public String getDef() {
        return def;
    }
    public void setDef(String def) {
        this.def = def;
    }
    public GCM getGcm() {
        return gcm;
    }
    public void setGcm(GCM gcm) {
        this.gcm = gcm;
    }

}

public class GCM {
    private Notification notification;

    @JsonProperty("notification")
    public Notification getNotification() {
        return notification;
    }

    public void setNotification(Notification notification) {
        this.notification = notification;
    }

}
public class Notification {
    private String text;

    @JsonProperty("text")
    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

}
</code>```

Response on the console

Publist request:{TargetArn:
  arn:aws:sns:ap-south-1:818862955266:endpoint/GCM/TestApp/a1ec8114-58c9-371b-bb76-d8d16e674e52,Message:
  {"default":"Test","GCM":{"notification":{"text":"hello"}}},MessageStructure:
  json,MessageAttributes: {}} {MessageId:
  7dfb613c-06d0-5fe6-8766-3068c9438614}
  {AWS_REQUEST_ID=3d0e13f4-b2be-5c95-ad43-42a07d2d5567}

What could be the problem?

Also, I am following the pattern suggested in the SO answer here.

答:
This worked finally. I used jackson parser.</p>

```<code>public class PushRequest {

    @JsonProperty("default")
    private String def;
    @JsonProperty("GCM")
    private GCM gcm;
    public String getDef() {
        return def;
    }
    public void setDef(String def) {
        this.def = def;
    }
    public GCM getGcm() {
        return gcm;
    }
    public void setGcm(GCM gcm) {
        this.gcm = gcm;
    }

}

public class GCM {
    private Notification notification;

    @JsonProperty("notification")
    public Notification getNotification() {
        return notification;
    }

    public void setNotification(Notification notification) {
        this.notification = notification;
    }

}
public class Notification {
    private String text;

    @JsonProperty("text")
    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

}

PublishRequest publishRequest = new PublishRequest();
            publishRequest.setTargetArn("arn:aws:sns:ap-south-1:818862955266:endpoint/GCM/TestApp/ac338195-1b87-3521-bd98-b7867a83ff27");

//          String message = "{\"GCM\": \"{ \"notification\": { \"text\": \"test message\" } }\"}";

            ObjectMapper mapper = new ObjectMapper();
            PushRequest pushRequest = new PushRequest();
            pushRequest.setDef("Testing out FB messages");

            GCM gcm = new GCM();
            Notification notification = new Notification();
            notification.setText("hello");
            gcm.setNotification(notification);
            pushRequest.setGcm(gcm);

            String jsonInString = mapper.writeValueAsString(pushRequest);
            publishRequest.setMessage(jsonInString);
            publishRequest.setMessageStructure("json");
            System.out.println("Publist request:"+publishRequest.toString());
            PublishResult publishResult = amazonSNSTemplate.getAmazonSNSClient().publish(publishRequest);
            System.out.println(publishResult.toString());
            System.out.println(publishResult.getSdkResponseMetadata().toString());
</code>```

Title: Amazon SNS GCM/FCM message payload

Body:
I am trying to send a push notification (PN) from my application server to an android device using publish end point in the Amazon SNS console with this message and message structure as json it works fine.

{
"GCM": "{ \"notification\": { \"text\": \"test message\" } }"
}

But when I try to implement the same in Java it the device does not receive the notification.

PublishRequest publishRequest = new PublishRequest();
        publishRequest.setTargetArn("arn:aws:sns:ap-south-1:818862955266:endpoint/GCM/TestApp/a1ec8114-58c9-371b-bb76-d8d16e674e52");
        String message = "{\"GCM\": \"{ \"notification\": { \"text\": \"test message\" } }\"}";

        ObjectMapper mapper = new ObjectMapper();
        PushRequest pushRequest = new PushRequest();
        pushRequest.setDef("Test");

        GCM gcm = new GCM();
        Notification notification = new Notification();
        notification.setText("hello");
        gcm.setNotification(notification);
        pushRequest.setGcm(gcm);

        String jsonInString = mapper.writeValueAsString(pushRequest);
        publishRequest.setMessage(jsonInString);
        publishRequest.setMessageStructure("json");
        System.out.println("Publist request:"+publishRequest.toString());
        PublishResult publishResult = amazonSNSTemplate.getAmazonSNSClient().publish(publishRequest);
        System.out.println(publishResult.toString());
        System.out.println(publishResult.getSdkResponseMetadata().toString());

public class PushRequest {

    @JsonProperty("default")
    private String def;
    @JsonProperty("GCM")
    private GCM gcm;
    public String getDef() {
        return def;
    }
    public void setDef(String def) {
        this.def = def;
    }
    public GCM getGcm() {
        return gcm;
    }
    public void setGcm(GCM gcm) {
        this.gcm = gcm;
    }

}

public class GCM {
    private Notification notification;

    @JsonProperty("notification")
    public Notification getNotification() {
        return notification;
    }

    public void setNotification(Notification notification) {
        this.notification = notification;
    }

}
public class Notification {
    private String text;

    @JsonProperty("text")
    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

}

Response on the console

Publist request:{TargetArn:
  arn:aws:sns:ap-south-1:818862955266:endpoint/GCM/TestApp/a1ec8114-58c9-371b-bb76-d8d16e674e52,Message:
  {"default":"Test","GCM":{"notification":{"text":"hello"}}},MessageStructure:
  json,MessageAttributes: {}} {MessageId:
  7dfb613c-06d0-5fe6-8766-3068c9438614}
  {AWS_REQUEST_ID=3d0e13f4-b2be-5c95-ad43-42a07d2d5567}

What could be the problem?

Also, I am following the pattern suggested in the SO answer here.

Body:
This worked finally. I used jackson parser.

public class PushRequest {

    @JsonProperty("default")
    private String def;
    @JsonProperty("GCM")
    private GCM gcm;
    public String getDef() {
        return def;
    }
    public void setDef(String def) {
        this.def = def;
    }
    public GCM getGcm() {
        return gcm;
    }
    public void setGcm(GCM gcm) {
        this.gcm = gcm;
    }

}

public class GCM {
    private Notification notification;

    @JsonProperty("notification")
    public Notification getNotification() {
        return notification;
    }

    public void setNotification(Notification notification) {
        this.notification = notification;
    }

}
public class Notification {
    private String text;

    @JsonProperty("text")
    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

}

PublishRequest publishRequest = new PublishRequest();
            publishRequest.setTargetArn("arn:aws:sns:ap-south-1:818862955266:endpoint/GCM/TestApp/ac338195-1b87-3521-bd98-b7867a83ff27");

//          String message = "{\"GCM\": \"{ \"notification\": { \"text\": \"test message\" } }\"}";

            ObjectMapper mapper = new ObjectMapper();
            PushRequest pushRequest = new PushRequest();
            pushRequest.setDef("Testing out FB messages");

            GCM gcm = new GCM();
            Notification notification = new Notification();
            notification.setText("hello");
            gcm.setNotification(notification);
            pushRequest.setGcm(gcm);

            String jsonInString = mapper.writeValueAsString(pushRequest);
            publishRequest.setMessage(jsonInString);
            publishRequest.setMessageStructure("json");
            System.out.println("Publist request:"+publishRequest.toString());
            PublishResult publishResult = amazonSNSTemplate.getAmazonSNSClient().publish(publishRequest);
            System.out.println(publishResult.toString());
            System.out.println(publishResult.getSdkResponseMetadata().toString());


问:
keyboard not disappear when used resignFirstResponder in iOS
coding environment sierra 10.12，Xcode 8.1. Two textField in my roorView, if   first textfield's text is nil, second textfield will can't  be editing.When i used resignFirstResponder method to turn off keyboard in textFieldDidBeginEditing: method, keyboard not disappear. I add a fullscreen TapGesture in rootView. I'm very confused，anyone have ideas to help me deal with this problem?

`

```<code>  #pragma mark -- UITextFieldDelegate
        - (void)textFieldDidBeginEditing:(UITextField *)textField{
            if (textField == self.password) {
                [self.username resignFirstResponder];
                NSString *name = self.username.text;
                if ([name isEqualToString:@""]) {
                    [CFBlurHUD showFaild:@"sign in error!"];
                    [self performSelector:@selector(dismmiss) withObject:nil afterDelay:1.5f];
                    self.password.enabled = NO;
                }
            }
        }
        - (void)dismmiss{
            [CFBlurHUD dismiss];
            self.password.enabled = YES;
        }

`
</code>```

答:
If you want to simply dismiss a keyboard from view, try the following:

```<code>self.view.endEditing = true;
</code>```

use your UITextFieldDelegate methods specifically UITextFieldShouldBeginEditing and return NO and execute the code to show the popover instead. This way the keyboard is never shown to begin with

```<code>- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
 [self.view endEditing:YES];

  return NO;
 }
</code>```

Body:
coding environment sierra 10.12，Xcode 8.1. Two textField in my roorView, if   first textfield's text is nil, second textfield will can't  be editing.When i used resignFirstResponder method to turn off keyboard in textFieldDidBeginEditing: method, keyboard not disappear. I add a fullscreen TapGesture in rootView. I'm very confused，anyone have ideas to help me deal with this problem?

`

  #pragma mark -- UITextFieldDelegate
        - (void)textFieldDidBeginEditing:(UITextField *)textField{
            if (textField == self.password) {
                [self.username resignFirstResponder];
                NSString *name = self.username.text;
                if ([name isEqualToString:@""]) {
                    [CFBlurHUD showFaild:@"sign in error!"];
                    [self performSelector:@selector(dismmiss) withObject:nil afterDelay:1.5f];
                    self.password.enabled = NO;
                }
            }
        }
        - (void)dismmiss{
            [CFBlurHUD dismiss];
            self.password.enabled = YES;
        }

`

Body:
If you want to simply dismiss a keyboard from view, try the following:

self.view.endEditing = true;

use your UITextFieldDelegate methods specifically UITextFieldShouldBeginEditing and return NO and execute the code to show the popover instead. This way the keyboard is never shown to begin with

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
 [self.view endEditing:YES];

  return NO;
 }