问:
Certain Clips are stopped at frame 44100 - Java sound
I have this code for playing the sound from the given sound file:

```<code>public class SoundPlayer {
    private Clip clip;
    private String sound = "bomb.wav";

    public SoundPlayer() {
        try {
            clip = loadClip();
        } catch (LineUnavailableException e) {
            e.printStackTrace();
        } catch (UnsupportedAudioFileException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Clip loadClip() throws LineUnavailableException, UnsupportedAudioFileException, IOException{
        AudioInputStream audio = AudioSystem.getAudioInputStream(this.getClass().getResource(sound));
        AudioFormat format = audio.getFormat();
        DataLine.Info info = new DataLine.Info(Clip.class, format);
        final Clip clip =  (Clip) AudioSystem.getLine(info);
        clip.open(audio);

        clip.addLineListener(new LineListener() {

            @Override
            public void update(LineEvent event) {
                System.out.println(event);
                System.out.println(clip.getFramePosition());
            }
        });

        return clip;
    }

    public void playSound(){
        System.out.println(clip.getFrameLength());
        clip.start();
    }

    public static void main(String[] args) throws InterruptedException{

        SoundPlayer sp = new SoundPlayer();
        Thread.sleep(2000); //Let open the file
        sp.playSound();
        Thread.sleep(10000); //Wait for the playback to finish
    }

}
</code>```

It plays some sounds without and problems but playback of some sounds (the sounds of exploding bomb) does not work well. For these bomb sounds, the playback always stops at frame 44100 and I don't understand why.

I added debug code to follow the frames which are being played. First number is length in frames, the second is frame when the clip starts and the last is frame positions when it stops.

Output for playing bomb sounds:

```<code>72846
Start event from line com.sun.media.sound.DirectAudioDevice$DirectClip@659bd1ca
44099
Stop event from line com.sun.media.sound.DirectAudioDevice$DirectClip@659bd1ca
44100
</code>```

I uploaded the explosion sounds here:

http://speedy.sh/v5QTy/bomb.wav

http://speedy.sh/nxysB/explosion.wav

Sound which plays ok:

http://speedy.sh/NzBJr/adios.wav

EDIT: This happens only on Linux - Ubuntu 12.04 with Oracle JDK 1.7.0_51

Is there another easy-to-use sound API which (unlike java.sound) is really without cross-platform issues? This is not my first issue with java.sound under Linux.

答:
I came across this post via a link from a more recent person having the same issue. I don't have an answer as to why the example code doesn't work. It all looks good to me.

I just wanted to suggest trying the newly coded AudioCue (BSD type license) as an alternative. It behaves very much like a Clip, but has some advantages. The data is loaded into a float array and output via a SourceDataLine. The implementation is only three classes, two of which are for adding line listening capabilities. As a bonus, it supports concurrent playback, and real time fading for volume, panning and pitch. It only works with stereo 44100 16-bit format ("CD quality") or float arrays loaded directly that follow that format.

I'm very curious if it will work on Ubuntu. Since it plays via a SourceDataLine, it should work across the usual Java platforms.

Body:
I have this code for playing the sound from the given sound file:

public class SoundPlayer {
    private Clip clip;
    private String sound = "bomb.wav";

    public SoundPlayer() {
        try {
            clip = loadClip();
        } catch (LineUnavailableException e) {
            e.printStackTrace();
        } catch (UnsupportedAudioFileException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Clip loadClip() throws LineUnavailableException, UnsupportedAudioFileException, IOException{
        AudioInputStream audio = AudioSystem.getAudioInputStream(this.getClass().getResource(sound));
        AudioFormat format = audio.getFormat();
        DataLine.Info info = new DataLine.Info(Clip.class, format);
        final Clip clip =  (Clip) AudioSystem.getLine(info);
        clip.open(audio);

        clip.addLineListener(new LineListener() {

            @Override
            public void update(LineEvent event) {
                System.out.println(event);
                System.out.println(clip.getFramePosition());
            }
        });

        return clip;
    }

    public void playSound(){
        System.out.println(clip.getFrameLength());
        clip.start();
    }

    public static void main(String[] args) throws InterruptedException{

        SoundPlayer sp = new SoundPlayer();
        Thread.sleep(2000); //Let open the file
        sp.playSound();
        Thread.sleep(10000); //Wait for the playback to finish
    }

}

It plays some sounds without and problems but playback of some sounds (the sounds of exploding bomb) does not work well. For these bomb sounds, the playback always stops at frame 44100 and I don't understand why.

I added debug code to follow the frames which are being played. First number is length in frames, the second is frame when the clip starts and the last is frame positions when it stops.

Output for playing bomb sounds:

72846
Start event from line com.sun.media.sound.DirectAudioDevice$DirectClip@659bd1ca
44099
Stop event from line com.sun.media.sound.DirectAudioDevice$DirectClip@659bd1ca
44100

I uploaded the explosion sounds here:

http://speedy.sh/v5QTy/bomb.wav

http://speedy.sh/nxysB/explosion.wav

Sound which plays ok:

http://speedy.sh/NzBJr/adios.wav

EDIT: This happens only on Linux - Ubuntu 12.04 with Oracle JDK 1.7.0_51

Is there another easy-to-use sound API which (unlike java.sound) is really without cross-platform issues? This is not my first issue with java.sound under Linux.


来源: stackexchange

问:
Invoke a SOAP method with namespace prefixes
My C# web service client sends following soap message to Java-based web service:

```<code><?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<getData>
<request>
<requestParameters xmlns="http://b...">
<equals>
...
</equals>
</requestParameters>
</request>
</getData>
</soap:Body>
</soap:Envelope>
</code>```

and Java-based web service returns error:

```<code>500 Internal Server Error
...
Cannot find dispatch method for {}getData
...
</code>```

Client written in Java, which works, sends the following message:

```<code><?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<ns2:getData xmlns:ns2="http://a...">
<ns2:request>
<ns3:requestParameters xmlns:ns3="http://b...">
<ns3:equals>
...
</ns3:equals>
</ns3:requestParameters>
</ns2:request>
</ns2:getData>
</soap:Body>
</soap:Envelope>
</code>```

Is there an easy way in C# to send SOAP messages the same way Java client sends: with namespace prefixes?

Following is C# code that sends message:

```<code>// class MyService is auto-generated using wsdl.exe tool
MyService service = new MyService();

RequestMessage request = new RequestMessage();
...

ResponseMessage response = service.getData(request);
...
</code>```

UPDATE:

Here is RequestMessage class:

```<code>/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("svcutil", "3.0.4506.2152")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://uri.etsi.org/02657/v1.5.1#/RetainedData")]
public partial class RequestMessage
{

    private byte[] requestPriorityField;

    private RequestConstraints requestParametersField;

    private string deliveryPointHIBField;

    private string maxHitsField;

    private NationalRequestParameters nationalRequestParametersField;

    private System.Xml.XmlElement anyField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(DataType="hexBinary", Order=0)]
    public byte[] requestPriority
    {
        get
        {
            return this.requestPriorityField;
        }
        set
        {
            this.requestPriorityField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Order=1)]
    public RequestConstraints requestParameters
    {
        get
        {
            return this.requestParametersField;
        }
        set
        {
            this.requestParametersField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Order=2)]
    public string deliveryPointHIB
    {
        get
        {
            return this.deliveryPointHIBField;
        }
        set
        {
            this.deliveryPointHIBField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(DataType="integer", Order=3)]
    public string maxHits
    {
        get
        {
            return this.maxHitsField;
        }
        set
        {
            this.maxHitsField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Order=4)]
    public NationalRequestParameters nationalRequestParameters
    {
        get
        {
            return this.nationalRequestParametersField;
        }
        set
        {
            this.nationalRequestParametersField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAnyElementAttribute(Order=5)]
    public System.Xml.XmlElement Any
    {
        get
        {
            return this.anyField;
        }
        set
        {
            this.anyField = value;
        }
    }
}
</code>```

UPDATE #2:

The reason why Java-based web service didn't like my C# client produced SOAP message is not omission of namespace prefixes, but only because of omission of xmlns in getData element, so if my message looks like this:

```<code>...
<getData xmlns="http://a...">
...
</getData>
...
</code>```

it works!

I managed to put xmlns inside getData by manually editing SoapRpcMethodAttribute in wsdl.exe-produced source code. Here is excerpt:

```<code>/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(
    Name="AxxxPortTypeBinding", Namespace="http://a...")]
public partial class AxxxService
    : System.Web.Services.Protocols.SoapHttpClientProtocol {

    ...

    /// <remarks/>
    [System.Web.Services.Protocols.SoapRpcMethodAttribute(
        "http://a.../getData",
        RequestNamespace = "http://a...",
        ResponseNamespace = "http://a...",
        Use = System.Web.Services.Description.SoapBindingUse.Literal)]
    [return: System.Xml.Serialization.XmlElementAttribute("response")]
    public ResponseMessage getData(RequestMessage request) {
        object[] results = this.Invoke("getData", new object[] {
                    request});
        return ((ResponseMessage)(results[0]));
    }

    ...
}
</code>```

Before my change, SoapRpcMethodAttribute had following constructor:

```<code>[System.Web.Services.Protocols.SoapRpcMethodAttribute(
    "", RequestNamespace = "", ResponseNamespace = "",
    Use = System.Web.Services.Description.SoapBindingUse.Literal)]
</code>```

Now, the question is: what to put in WSDL file so that SoapRpcMethodAttribute have those strings in constructor (filled by the wsdl.exe tool) in the first place?

答:
The generated proxy class should have had the correct namespace in it. I recommend two things:

1) Run WSDL.EXE from the command line and note whether there are any errors or warnings. If so, please edit your question to include them.

2) Unless you are stuck using .NET 2.0, you should try to create your proxy classes using either "Add Service Reference" or the equivalent "SVCUTIL.EXE" these will use the modern, WCF infrastructure on the client side, which is much more likely to have been fixed to resolve this problem.

ContentLicense: CC BY-SA 3.0

Body:
My C# web service client sends following soap message to Java-based web service:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<getData>
<request>
<requestParameters xmlns="http://b...">
<equals>
...
</equals>
</requestParameters>
</request>
</getData>
</soap:Body>
</soap:Envelope>

and Java-based web service returns error:

500 Internal Server Error
...
Cannot find dispatch method for {}getData
...

Client written in Java, which works, sends the following message:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<ns2:getData xmlns:ns2="http://a...">
<ns2:request>
<ns3:requestParameters xmlns:ns3="http://b...">
<ns3:equals>
...
</ns3:equals>
</ns3:requestParameters>
</ns2:request>
</ns2:getData>
</soap:Body>
</soap:Envelope>

Is there an easy way in C# to send SOAP messages the same way Java client sends: with namespace prefixes?

Following is C# code that sends message:

// class MyService is auto-generated using wsdl.exe tool
MyService service = new MyService();

RequestMessage request = new RequestMessage();
...

ResponseMessage response = service.getData(request);
...

UPDATE:

Here is RequestMessage class:

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("svcutil", "3.0.4506.2152")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://uri.etsi.org/02657/v1.5.1#/RetainedData")]
public partial class RequestMessage
{

    private byte[] requestPriorityField;

    private RequestConstraints requestParametersField;

    private string deliveryPointHIBField;

    private string maxHitsField;

    private NationalRequestParameters nationalRequestParametersField;

    private System.Xml.XmlElement anyField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(DataType="hexBinary", Order=0)]
    public byte[] requestPriority
    {
        get
        {
            return this.requestPriorityField;
        }
        set
        {
            this.requestPriorityField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Order=1)]
    public RequestConstraints requestParameters
    {
        get
        {
            return this.requestParametersField;
        }
        set
        {
            this.requestParametersField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Order=2)]
    public string deliveryPointHIB
    {
        get
        {
            return this.deliveryPointHIBField;
        }
        set
        {
            this.deliveryPointHIBField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(DataType="integer", Order=3)]
    public string maxHits
    {
        get
        {
            return this.maxHitsField;
        }
        set
        {
            this.maxHitsField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Order=4)]
    public NationalRequestParameters nationalRequestParameters
    {
        get
        {
            return this.nationalRequestParametersField;
        }
        set
        {
            this.nationalRequestParametersField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAnyElementAttribute(Order=5)]
    public System.Xml.XmlElement Any
    {
        get
        {
            return this.anyField;
        }
        set
        {
            this.anyField = value;
        }
    }
}

UPDATE #2:

The reason why Java-based web service didn't like my C# client produced SOAP message is not omission of namespace prefixes, but only because of omission of xmlns in getData element, so if my message looks like this:

...
<getData xmlns="http://a...">
...
</getData>
...

it works!

I managed to put xmlns inside getData by manually editing SoapRpcMethodAttribute in wsdl.exe-produced source code. Here is excerpt:

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(
    Name="AxxxPortTypeBinding", Namespace="http://a...")]
public partial class AxxxService
    : System.Web.Services.Protocols.SoapHttpClientProtocol {

    ...

    /// <remarks/>
    [System.Web.Services.Protocols.SoapRpcMethodAttribute(
        "http://a.../getData",
        RequestNamespace = "http://a...",
        ResponseNamespace = "http://a...",
        Use = System.Web.Services.Description.SoapBindingUse.Literal)]
    [return: System.Xml.Serialization.XmlElementAttribute("response")]
    public ResponseMessage getData(RequestMessage request) {
        object[] results = this.Invoke("getData", new object[] {
                    request});
        return ((ResponseMessage)(results[0]));
    }

    ...
}

Before my change, SoapRpcMethodAttribute had following constructor:

[System.Web.Services.Protocols.SoapRpcMethodAttribute(
    "", RequestNamespace = "", ResponseNamespace = "",
    Use = System.Web.Services.Description.SoapBindingUse.Literal)]

Now, the question is: what to put in WSDL file so that SoapRpcMethodAttribute have those strings in constructor (filled by the wsdl.exe tool) in the first place?

ContentLicense: CC BY-SA 2.5


问:
Format exception unhandled: input string was not in a correct format
when ever i try to run my program the compiler brings me an error  Input string was not in a correct format.

my code:

```<code>public int number;
public int evenOrOdd()
        {
            if(number % 2 == 0)
            {
                return int.Parse(number+" is a even number");
            }
            else
            {
                return int.Parse(number + " is a oddnumber");
            }
        }
</code>```

and

```<code>private void checkerButton_Click(object sender, EventArgs e)
        {
            pali = new Palindrome() { number = int.Parse(checkerBox.Text) };
            checkerLabel.Text = pali.evenOrOdd().ToString();
        }
</code>```

答:
To use int.parse parse only the data you want to convert.Take note that the return value of int.parse will be integer. So letters and characters will trigger the incorrect format. For example.
Correct - int.parse("2")
Incorrect - int.parse("2a")

public int number;

```<code>if(number % 2 == 0)
{
return int.Parse(number) + "is a even number";
}
else
{
return int.Parse(number) + "is a odd number";
}
</code>```

Body:
when ever i try to run my program the compiler brings me an error  Input string was not in a correct format.

my code:

public int number;
public int evenOrOdd()
        {
            if(number % 2 == 0)
            {
                return int.Parse(number+" is a even number");
            }
            else
            {
                return int.Parse(number + " is a oddnumber");
            }
        }

and

private void checkerButton_Click(object sender, EventArgs e)
        {
            pali = new Palindrome() { number = int.Parse(checkerBox.Text) };
            checkerLabel.Text = pali.evenOrOdd().ToString();
        }

Body:
To use int.parse parse only the data you want to convert.Take note that the return value of int.parse will be integer. So letters and characters will trigger the incorrect format. For example.
Correct - int.parse("2")
Incorrect - int.parse("2a")

public int number;

if(number % 2 == 0)
{
return int.Parse(number) + "is a even number";
}
else
{
return int.Parse(number) + "is a odd number";
}


问:
SAS drop records in by group with only one observation
I have a dataset and I am reading it with a by group statement:

```<code>  data TEMPDATA;
    SET RAWDATA; by SYMBOL DATE;
  run;
  proc expand data=TEMPDATA out=GAPDATA to=day method=step;
  by symbol date;
  id time;
  run;
</code>```

However, I realized that the proc expand procedure would return an error if there is a record in the by group that has only one observation.

For example:

```<code>| Symbol | Date     | Time | BB | BO | MIDPRICE |
|--------|----------|------|----|----|----------|
| AAPL   | 20130102 | 2    | 2  | 3  | 2.5      |
</code>```

If there is only one record of AAPL, SAS will refuse to execute the command.

Therefore, I was wondering if there is a way to drop all the records, with the same symbol, that has only one record in the by group (symbol, date)?

答:
Since you are using a data step already just add logic to delete the singletons. Any record that is both the first and last in its group indicates there is only one record in that group.</p>

```<code>data TEMPDATA;
  SET RAWDATA;
  by SYMBOL DATE;
  if first.date and last.date then delete;
run;
</code>```

Body:
I have a dataset and I am reading it with a by group statement:

  data TEMPDATA;
    SET RAWDATA; by SYMBOL DATE;
  run;
  proc expand data=TEMPDATA out=GAPDATA to=day method=step;
  by symbol date;
  id time;
  run;

However, I realized that the proc expand procedure would return an error if there is a record in the by group that has only one observation.

For example:

| Symbol | Date     | Time | BB | BO | MIDPRICE |
|--------|----------|------|----|----|----------|
| AAPL   | 20130102 | 2    | 2  | 3  | 2.5      |

If there is only one record of AAPL, SAS will refuse to execute the command.

Therefore, I was wondering if there is a way to drop all the records, with the same symbol, that has only one record in the by group (symbol, date)?

Body:
Since you are using a data step already just add logic to delete the singletons. Any record that is both the first and last in its group indicates there is only one record in that group.

data TEMPDATA;
  SET RAWDATA;
  by SYMBOL DATE;
  if first.date and last.date then delete;
run;


问:
AsyncTask not returning any response
Hi I have trouble getting the response of my url from my host. I tried putting static variables and it worked but when I tried to use a asynctask for response it didnt work.

```<code><?PHP
include_once('connection.php');

$where='';

if(isset($_GET['userLat']) && isset($_GET['userLng'])){

$where = "WHERE ((userLat >= '".addslashes($_GET['userLat'])."' AND userLat <= '".addslashes($_GET['userLat'])."' + .00901) OR (userLat <= '".addslashes($_GET['userLat'])."' AND userLat >= '".addslashes($_GET['userLat'])."' - .00901)) AND ((userLng >= '".addslashes($_GET['userLng'])."' AND userLng <= '".addslashes($_GET['userLng'])."' + .014935) OR (userLng <= '".addslashes($_GET['userLng'])."' AND userLng >= '".addslashes($_GET['userLng'])."' - .014935))";

    $query = "SELECT * FROM tbl_user ".$where." AND isOnline = 'Yes' LIMIT 1 ";
$result = mysqli_query($conn, $query);

$json = array();

if(mysqli_num_rows($result)){
    while($row = mysqli_fetch_assoc($result)){
     $json['details'][]=$row;
}
}
mysqli_close($conn);
echo json_encode($json);
}
?>
</code>```

AsyncTask

```<code>    private class JsonTask extends AsyncTask<String, String, String> {

    protected void onPreExecute() {
        super.onPreExecute();

        pd = new ProgressDialog(getActivity());
        pd.setMessage("Checking nearby wingmans");
        pd.setCancelable(false);
        pd.show();
    }

    protected String doInBackground(String... params) {

        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line = "";

            while ((line = reader.readLine()) != null) {
                buffer.append(line + "\n");
                Log.d("Response: ", "> " + line);   //here u ll get whole response...... :-)

            }

            return buffer.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (pd.isShowing()) {
            pd.dismiss();
        }
        request = result;
        Log.d("Test", result);
    }
}
</code>```

how i call my url

```<code>        btnEmergency.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String url = "http://10.0.2.2/wingman/emergency.php?userLat="+tvLat.getText().toString()+"ANDuserLng="+tvLng.getText().toString();
            new JsonTask().execute(url);
        }
    });
</code>```

Thanks guys i hope i get an answer to my question. Thanks :)

答:
Very foolish of me. I jsut change the AND to & in my url
from

```<code>String url = "http://10.0.2.2/wingman/emergency.php?userLat="+tvLat.getText().toString()+"ANDuserLng="+tvLng.getText().toString();
</code>```

to

```<code>String url = "http://10.0.2.2/wingman/emergency.php?userLat="+tvLat.getText().toString()+"&userLng="+tvLng.getText().toString();
</code>```

And it worked. Thanks!

Title: AsyncTask not returning any response

Body:
Hi I have trouble getting the response of my url from my host. I tried putting static variables and it worked but when I tried to use a asynctask for response it didnt work.

<?PHP
include_once('connection.php');

$where='';

if(isset($_GET['userLat']) && isset($_GET['userLng'])){

$where = "WHERE ((userLat >= '".addslashes($_GET['userLat'])."' AND userLat <= '".addslashes($_GET['userLat'])."' + .00901) OR (userLat <= '".addslashes($_GET['userLat'])."' AND userLat >= '".addslashes($_GET['userLat'])."' - .00901)) AND ((userLng >= '".addslashes($_GET['userLng'])."' AND userLng <= '".addslashes($_GET['userLng'])."' + .014935) OR (userLng <= '".addslashes($_GET['userLng'])."' AND userLng >= '".addslashes($_GET['userLng'])."' - .014935))";

    $query = "SELECT * FROM tbl_user ".$where." AND isOnline = 'Yes' LIMIT 1 ";
$result = mysqli_query($conn, $query);

$json = array();

if(mysqli_num_rows($result)){
    while($row = mysqli_fetch_assoc($result)){
     $json['details'][]=$row;
}
}
mysqli_close($conn);
echo json_encode($json);
}
?>

AsyncTask

    private class JsonTask extends AsyncTask<String, String, String> {

    protected void onPreExecute() {
        super.onPreExecute();

        pd = new ProgressDialog(getActivity());
        pd.setMessage("Checking nearby wingmans");
        pd.setCancelable(false);
        pd.show();
    }

    protected String doInBackground(String... params) {

        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line = "";

            while ((line = reader.readLine()) != null) {
                buffer.append(line + "\n");
                Log.d("Response: ", "> " + line);   //here u ll get whole response...... :-)

            }

            return buffer.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (pd.isShowing()) {
            pd.dismiss();
        }
        request = result;
        Log.d("Test", result);
    }
}

how i call my url

        btnEmergency.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String url = "http://10.0.2.2/wingman/emergency.php?userLat="+tvLat.getText().toString()+"ANDuserLng="+tvLng.getText().toString();
            new JsonTask().execute(url);
        }
    });

Thanks guys i hope i get an answer to my question. Thanks :)

Body:
Very foolish of me. I jsut change the AND to & in my url
from

String url = "http://10.0.2.2/wingman/emergency.php?userLat="+tvLat.getText().toString()+"ANDuserLng="+tvLng.getText().toString();

to

String url = "http://10.0.2.2/wingman/emergency.php?userLat="+tvLat.getText().toString()+"&userLng="+tvLng.getText().toString();

And it worked. Thanks!


问:
Rubymine - Rails gem not found
I installed Rails 3.2.3 and Ruby 1.9.3 going through this solution -  http://ryanbigg.com/2010/12/ubuntu-ruby-rvm-rails-and-you/. It's really amazing and effortless. There were no errors while I did this.

Now I try to create a Rails project in Rubymine 4 but there's an error: "Rails version - no Rails gem found".

Terminal shows me:

```<code>alex@ubuntu:~$ rails -v
Rails 3.2.3
alex@ubuntu:~$ ruby -v
ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-linux]
alex@ubuntu:~$
</code>```

UPDATE

```<code>alex@ubuntu:~$ gem environment
RubyGems Environment:
  - RUBYGEMS VERSION: 1.8.24
  - RUBY VERSION: 1.9.3 (2012-04-20 patchlevel 194) [x86_64-linux]
  - INSTALLATION DIRECTORY: /home/alex/.rvm/gems/ruby-1.9.3-p194
  - RUBY EXECUTABLE: /home/alex/.rvm/rubies/ruby-1.9.3-p194/bin/ruby
  - EXECUTABLE DIRECTORY: /home/alex/.rvm/gems/ruby-1.9.3-p194/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-linux
  - GEM PATHS:
     - /home/alex/.rvm/gems/ruby-1.9.3-p194
     - /home/alex/.rvm/gems/ruby-1.9.3-p194@global
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :benchmark => false
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - http://rubygems.org/
alex@ubuntu:~$ gem list

*** LOCAL GEMS ***

actionmailer (3.2.3)
actionpack (3.2.3)
activemodel (3.2.3)
activerecord (3.2.3)
activeresource (3.2.3)
activesupport (3.2.3)
arel (3.0.2)
builder (3.0.0)
bundler (1.1.4)
erubis (2.7.0)
hike (1.2.1)
i18n (0.6.0)
journey (1.0.4)
json (1.7.3)
mail (2.4.4)
mime-types (1.19)
multi_json (1.3.6)
polyglot (0.3.3)
rack (1.4.1)
rack-cache (1.2)
rack-ssl (1.3.2)
rack-test (0.6.1)
rails (3.2.3)
railties (3.2.3)
rake (0.9.2.2)
rdoc (3.12)
rubygems-bundler (1.0.3)
rvm (1.11.3.5)
sprockets (2.1.3)
thor (0.14.6)
tilt (1.3.3)
treetop (1.4.10)
tzinfo (0.3.33)
alex@ubuntu:~$
</code>```

答:
When you close and open again you will get a notification saying:

RubyMine Gem Manager: RubyMine has detected that some of the gems required for 'projectName' are not installed. Install

Click Install and it will run the bundle install for the project, all got solved after that.

Title: Rubymine - Rails gem not found

Body:
I installed Rails 3.2.3 and Ruby 1.9.3 going through this solution -  http://ryanbigg.com/2010/12/ubuntu-ruby-rvm-rails-and-you/. It's really amazing and effortless. There were no errors while I did this.

Now I try to create a Rails project in Rubymine 4 but there's an error: "Rails version - no Rails gem found".

Terminal shows me:

alex@ubuntu:~$ rails -v
Rails 3.2.3
alex@ubuntu:~$ ruby -v
ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-linux]
alex@ubuntu:~$

UPDATE

alex@ubuntu:~$ gem environment
RubyGems Environment:
  - RUBYGEMS VERSION: 1.8.24
  - RUBY VERSION: 1.9.3 (2012-04-20 patchlevel 194) [x86_64-linux]
  - INSTALLATION DIRECTORY: /home/alex/.rvm/gems/ruby-1.9.3-p194
  - RUBY EXECUTABLE: /home/alex/.rvm/rubies/ruby-1.9.3-p194/bin/ruby
  - EXECUTABLE DIRECTORY: /home/alex/.rvm/gems/ruby-1.9.3-p194/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-linux
  - GEM PATHS:
     - /home/alex/.rvm/gems/ruby-1.9.3-p194
     - /home/alex/.rvm/gems/ruby-1.9.3-p194@global
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :benchmark => false
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - http://rubygems.org/
alex@ubuntu:~$ gem list

*** LOCAL GEMS ***

actionmailer (3.2.3)
actionpack (3.2.3)
activemodel (3.2.3)
activerecord (3.2.3)
activeresource (3.2.3)
activesupport (3.2.3)
arel (3.0.2)
builder (3.0.0)
bundler (1.1.4)
erubis (2.7.0)
hike (1.2.1)
i18n (0.6.0)
journey (1.0.4)
json (1.7.3)
mail (2.4.4)
mime-types (1.19)
multi_json (1.3.6)
polyglot (0.3.3)
rack (1.4.1)
rack-cache (1.2)
rack-ssl (1.3.2)
rack-test (0.6.1)
rails (3.2.3)
railties (3.2.3)
rake (0.9.2.2)
rdoc (3.12)
rubygems-bundler (1.0.3)
rvm (1.11.3.5)
sprockets (2.1.3)
thor (0.14.6)
tilt (1.3.3)
treetop (1.4.10)
tzinfo (0.3.33)
alex@ubuntu:~$


问:
Is it possible to comment/mark out certain folders in a collection while running via postman runner
I am working on a collection arranged in different folders w.r.t. different business component scenarios. Now some of the scenario folders might be alternative/redundant paths for the same workflow. Is it possible to somehow unmark/comment and mark/uncomment some of these alternate path folders in postman runner to get varying runs easily.</p>

答:
Ok, so one way is to arrange the collection folders in following way to facilitate the same:

```<code>- Main Collection
   - Workflow1_Folder
   - Workflow2_Folder
   - Workflow3_Folder
   - Workflow4_Folder

- UnmarkedWorkflows Collection
   - Workflow2_Alternate_Folder - this will contain the steps that are alternate to ones on Main>Workflow2_Folder
   - Workflow3_Alternate_Folder - this will contain the steps that are alternate to ones on Main>Workflow3_Folder
</code>```

Only the Main folder needs to be run.
If/when required Workflow2_Alternate_Folder could be moved into Main folder from the UnmarkedWorkflows Collection followed by moving Workflow2_Folder to UnmarkedWorkflows Collection. Then Main collection could be run to test an alternate path for the same Use Case.

Body:
Ok, so one way is to arrange the collection folders in following way to facilitate the same:

- Main Collection
   - Workflow1_Folder
   - Workflow2_Folder
   - Workflow3_Folder
   - Workflow4_Folder

- UnmarkedWorkflows Collection
   - Workflow2_Alternate_Folder - this will contain the steps that are alternate to ones on Main>Workflow2_Folder
   - Workflow3_Alternate_Folder - this will contain the steps that are alternate to ones on Main>Workflow3_Folder

Only the Main folder needs to be run.
If/when required Workflow2_Alternate_Folder could be moved into Main folder from the UnmarkedWorkflows Collection followed by moving Workflow2_Folder to UnmarkedWorkflows Collection. Then Main collection could be run to test an alternate path for the same Use Case.


问:
Change quantity in Rails shopping cart
I am new to Ruby on Rails. I have built a shopping cart for a sample online store, and I have a shopping cart that I can add items to. If I want to increase the quantity, I have to go back to the product page and add it again. The only way I have to remove a product is to click the Empty Cart button to remove everything.

I am trying to find a way to have the quantity displayed in a number selector of some sort, with the current quantity set as the default value. If the quantity is changed within the cart, then the page will likely need to be refreshed so that the total price can be updated as well. If the quantity is set to 0, then the line item would ideally be removed from the cart.

I am lost when it comes to how to actually implement these features though. Any help would be greatly appreciated.

Here is my /carts/show.html.erb file:

```<code><p id="notice"><%= notice %></p>

<h2>My Cart</h2>
<table class="table table-responsive table-striped">
    <thead>
        <tr>
            <th>Item</th>
            <th>Quantity</th>
            <th>Total Price</th>
        </tr>
        <tbody>
            <%= render(@cart.line_items) %>
            <tr>
                <td>Total</td>
                <td><%= number_to_currency(@cart.total_price) %></td>
                <td></td>
            </tr>
        </tbody>
    </thead>
</table>

<%= button_to 'Empty Cart', @cart, method: :delete, data: {confirm: 'Are you sure you want to empty your cart?'}, :class => 'btn btn-danger' %>
<br>
<%= button_to "Checkout", new_order_path, method: :get, :class => 'btn btn-success' %>
<br>
<%= link_to 'Back', products_path, :class => 'btn btn-primary' %>
</code>```

Here is my /line_items/_line_item.html.erb file:

```<code><tr>
    <td><%= link_to line_item.product.product_name, line_item.product %></td>
    <td><%= line_item.quantity %></td>
    <td><%= number_to_currency(line_item.total_price) %></td>
</tr>
</code>```

答:
There are a number of different ways that this could be accomplished. I guess the easiest way would be to create a method in your cart controller

say...

```<code>def update_quantity
  @line_item.update_attribute(:quantity)
end
</code>```

Then in your view, you can build out a from selector

```<code><%= form_for line_item do |f| %>
  <%= f.select_tag :quantity, 'options_for_quantity' %>
  <%= f.submit, method: :patch %>
<% end %>
</code>```

That should handle most of what you are looking for.

Title: Change quantity in Rails shopping cart

Body:
I am new to Ruby on Rails. I have built a shopping cart for a sample online store, and I have a shopping cart that I can add items to. If I want to increase the quantity, I have to go back to the product page and add it again. The only way I have to remove a product is to click the Empty Cart button to remove everything.

I am trying to find a way to have the quantity displayed in a number selector of some sort, with the current quantity set as the default value. If the quantity is changed within the cart, then the page will likely need to be refreshed so that the total price can be updated as well. If the quantity is set to 0, then the line item would ideally be removed from the cart.

I am lost when it comes to how to actually implement these features though. Any help would be greatly appreciated.

Here is my /carts/show.html.erb file:

<%= notice %>

My Cart

            Item
            Quantity
            Total Price

            <%= render(@cart.line_items) %>

                Total
                <%= number_to_currency(@cart.total_price) %>

<%= button_to 'Empty Cart', @cart, method: :delete, data: {confirm: 'Are you sure you want to empty your cart?'}, :class => 'btn btn-danger' %>

<%= button_to "Checkout", new_order_path, method: :get, :class => 'btn btn-success' %>

<%= link_to 'Back', products_path, :class => 'btn btn-primary' %>

Here is my /line_items/_line_item.html.erb file:

    <%= link_to line_item.product.product_name, line_item.product %>
    <%= line_item.quantity %>
    <%= number_to_currency(line_item.total_price) %>

Body:
There are a number of different ways that this could be accomplished. I guess the easiest way would be to create a method in your cart controller

say...

def update_quantity
  @line_item.update_attribute(:quantity)
end

Then in your view, you can build out a from selector

<%= form_for line_item do |f| %>
  <%= f.select_tag :quantity, 'options_for_quantity' %>
  <%= f.submit, method: :patch %>
<% end %>

That should handle most of what you are looking for.


问:
Why UDP hole punching does not work for public IP address?
There are two Groovy sub programs below sending messages to each other via plain UDP sockets. They does receive the messages successfully when they are sent to 127.0.0.1. But the messages aren't received when sending them to the public IP address (the machine is behind NAT).

Why the hole is not punched? And how to fix that?

I tried querying a public STUN server via a Java library earlier but it responded with the same public IP address to me, so I use wtfismyip.com here.

```<code>class GroovyTest {

static String PUBLIC_IP = new URL('https://wtfismyip.com/text').text.trim()
//static String PUBLIC_IP = '127.0.0.1' // works fine

static void main(String[] args) {
    runInstance(11111, 22222)
    runInstance(22222, 11111)
}

static void runInstance(int thisPort, int anotherPort) {
    def socket = new DatagramSocket(thisPort)
    Thread.start {
        // message listener
        byte[] buf = new byte[1024]
        while (true) {
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
            socket.receive(packet);
            InetAddress remoteAddr = packet.getAddress();
            int remotePort = packet.getPort();
            String sentence = new String(packet.getData(), 0, packet.length);
            println("server-$thisPort: received [$sentence] from ${remoteAddr.hostAddress}:${remotePort}")
        }
    }
    Thread.start {
        // message sender
        while (true) {
            println("client-$thisPort: sending to ${PUBLIC_IP}:${anotherPort}...")
            byte[] buf = ("Hello " + System.currentTimeMillis()).bytes
            DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getByName(PUBLIC_IP), anotherPort)
            socket.send(packet)
            Thread.sleep(2000)
        }
    }
}

}
</code>```

答:
I have been successfully replying to UDP packets behind a NAT router by simply taking the address and port details from the UDP packet I'm responding to...

```<code>DatagramSocket socket = new DatagramSocket(port);
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
socket.receive(receivePacket);

DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length,
    receivePacket.getAddress(), receivePacket.getPort());
socket.send(sendPacket);
</code>```

The code is more robust in that it doesn't matter where the packet came from, or any address translation which occurred along the way. It will always reply to the right place.

I'v also noticed you are using two different port numbers. "thisPort" and "anotherPort". As far as I know, the hole punching will only work if you reply on the same port number. This makes sense for security reasons.

The marine robot on top of my head, pictured in my avatar, uses this UDP hole punching technique.

Body:
There are two Groovy sub programs below sending messages to each other via plain UDP sockets. They does receive the messages successfully when they are sent to 127.0.0.1. But the messages aren't received when sending them to the public IP address (the machine is behind NAT).

Why the hole is not punched? And how to fix that?

I tried querying a public STUN server via a Java library earlier but it responded with the same public IP address to me, so I use wtfismyip.com here.

class GroovyTest {

static String PUBLIC_IP = new URL('https://wtfismyip.com/text').text.trim()
//static String PUBLIC_IP = '127.0.0.1' // works fine

static void main(String[] args) {
    runInstance(11111, 22222)
    runInstance(22222, 11111)
}

static void runInstance(int thisPort, int anotherPort) {
    def socket = new DatagramSocket(thisPort)
    Thread.start {
        // message listener
        byte[] buf = new byte[1024]
        while (true) {
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
            socket.receive(packet);
            InetAddress remoteAddr = packet.getAddress();
            int remotePort = packet.getPort();
            String sentence = new String(packet.getData(), 0, packet.length);
            println("server-$thisPort: received [$sentence] from ${remoteAddr.hostAddress}:${remotePort}")
        }
    }
    Thread.start {
        // message sender
        while (true) {
            println("client-$thisPort: sending to ${PUBLIC_IP}:${anotherPort}...")
            byte[] buf = ("Hello " + System.currentTimeMillis()).bytes
            DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getByName(PUBLIC_IP), anotherPort)
            socket.send(packet)
            Thread.sleep(2000)
        }
    }
}

}

Body:
I have been successfully replying to UDP packets behind a NAT router by simply taking the address and port details from the UDP packet I'm responding to...

DatagramSocket socket = new DatagramSocket(port);
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
socket.receive(receivePacket);

DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length,
    receivePacket.getAddress(), receivePacket.getPort());
socket.send(sendPacket);

The code is more robust in that it doesn't matter where the packet came from, or any address translation which occurred along the way. It will always reply to the right place.

I'v also noticed you are using two different port numbers. "thisPort" and "anotherPort". As far as I know, the hole punching will only work if you reply on the same port number. This makes sense for security reasons.

The marine robot on top of my head, pictured in my avatar, uses this UDP hole punching technique.


问:
PHP files not working when using Bootstrap
I am new to Programming hence need some help. Below is the code I am using for a Contact Form using Bootstrap but my PHP code doesn't seem to work.
I have been keeping "index.php" file with other files of Bootstrap. But when I run this it shows an error and doesn't run.
And when I save this file as "index.html", the HTML part of the code runs but PHP files don't.
In order to run PHP file in wamp server where should I save the files in Bootstrap or in Wamp?</p>

```<code><?php

if ($_POST['submit']) {

    if(!$_POST['name']) {
        $error="<br/>-Please enter your name";
    }

    if(!$_POST['email']) {
        $error.="<br/>- Please enter your email";
    }

    if(!$_POST['subject']) {
        $error.="<br/>- Please enter a subject";
    }

    if(!$_POST['message']) {
        $error.="<br/>- Please enter a message";
    }

    if(!$_POST['check']) {
        $error.="<br/>- Please confirm you are human";
    }

    if($error) {
        $result="Whoops, there is an error; Please correct the following: $error";
    } else {
        mail("namitajamwal19@gmail.com", "Contact message", "Name: ".$_POST['name']."
        Email: ".$_POST['name']."
        Subject: ".$_POST['subject']."
        Message: ".$_POST['message']);"

        {
        $result="Thank you, I'll be in touch shortly";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Contact Us</title>

    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>

    <section id="contact">
        <div class="container">

            <div class="row">
                <div class="col-md-6 col-md-offset-3">
                    <h1>Contact Us</h1>

                    <?php echo $result;?>

                    <p>Send a message via the form below</p>

                    <form method="post" role="form">

                        <div class="form-group">
                            <input type="text" name="name" class="form-control" placeholder="Your Name" value="<?php echo $_POST['name']; ?>">
                        </div>

                        <div class="form-group">
                            <input type="email" name="email" class="form-control" placeholder="Your email" value="<?php echo $_POST['email']; ?>">
                        </div>

                        <div class="form-group">
                            <textarea name="subject" rows="5" class="form-control" placeholder="Subject"><?php echo $_POST['subject']; ?></textarea>
                        </div>

                        <div class="form-group">
                            <textarea name="message" rows="5" class="form-control" placeholder="Message..."><?php echo $_POST['message']; ?></textarea>
                        </div>

                        <div class="checkbox">
                            <label>
                                <input type="checkbox" name="check">I am Human
                            </label>
                        </div>

                        <div align="center">
                        <input type="submit" name="submit" class="btn btn-secondary" value="send message"/>
                        </div>
                    </form>

                </div>
            </div>

        </div>
    </section>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
  </body>
</html>
</code>```

答:
In order to process php, the file needs to have a .php extension and you would store it in your webroot which is the same place you keep the .html files.

If your php isn't running, you either have a php error or your webserver isn't configured properly to process php files.

Body:
I am new to Programming hence need some help. Below is the code I am using for a Contact Form using Bootstrap but my PHP code doesn't seem to work.
I have been keeping "index.php" file with other files of Bootstrap. But when I run this it shows an error and doesn't run.
And when I save this file as "index.html", the HTML part of the code runs but PHP files don't.
In order to run PHP file in wamp server where should I save the files in Bootstrap or in Wamp?

<?php

if ($_POST['submit']) {

    if(!$_POST['name']) {
        $error="
-Please enter your name";
    }

    if(!$_POST['email']) {
        $error.="
- Please enter your email";
    }

    if(!$_POST['subject']) {
        $error.="
- Please enter a subject";
    }

    if(!$_POST['message']) {
        $error.="
- Please enter a message";
    }

    if(!$_POST['check']) {
        $error.="
- Please confirm you are human";
    }

    if($error) {
        $result="Whoops, there is an error; Please correct the following: $error";
    } else {
        mail("namitajamwal19@gmail.com", "Contact message", "Name: ".$_POST['name']."
        Email: ".$_POST['name']."
        Subject: ".$_POST['subject']."
        Message: ".$_POST['message']);"

        {
        $result="Thank you, I'll be in touch shortly";
        }
    }
}
?>

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Contact Us</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

Contact Us

                    <?php echo $result;?>

Send a message via the form below

                    <form method="post" role="form">

                            <input type="text" name="name" class="form-control" placeholder="Your Name" value="<?php echo $_POST['name']; ?>">

                            <input type="email" name="email" class="form-control" placeholder="Your email" value="<?php echo $_POST['email']; ?>">

                            <textarea name="subject" rows="5" class="form-control" placeholder="Subject"><?php echo $_POST['subject']; ?></textarea>

                            <textarea name="message" rows="5" class="form-control" placeholder="Message..."><?php echo $_POST['message']; ?></textarea>

                                <input type="checkbox" name="check">I am Human

                        <input type="submit" name="submit" class="btn btn-secondary" value="send message"/>

                    </form>


问:
Impersonalization - domain specific user without password - ASP.NET MVC
How to programmatically impersonate domain specific user with assigned groups without a password and without SeTcbPrivilege in ASP.NET MVC application?

This feature will be used as "See the application as specific user".

答:
I'm not sure if it is possible to impersonate a domain user without password.

There are two way:

put user account and password in web.config

programming impersonate in code

you may refer to below MSDN article for detail

https://support.microsoft.com/en-us/help/306158/how-to-implement-impersonation-in-an-asp.net-application


问:
Is the primary key stored implicitly in other keys in mysql myisam engine?
My problem: imagine a table with millions of rows, like

```<code>CREATE TABLE a {
id INT PRIMARY KEY,
column2..,
column3..,
many other columns..
..
INDEX (column2);
</code>```

and a query like this:

```<code>SELECT id FROM a WHERE column2 > 10000 LIMIT 1000 OFFSET 5000;
</code>```

My question: does mysql only use the index "column2" (so the primary key id is implicitly stored as a reference in other indexes), or does it have to fetch all rows to get also the id, which is selected for output? In that case the query should be much faster with a key declared as:

```<code>INDEX column2(column2, id)
</code>```

答:
Short answer:  No.

Long answer:

MyISAM, unlike InnoDB, has a "pointer" to the data in the leaf node of each index, including that PRIMARY KEY.

So, INDEX(col2) is essentially INDEX(col2, ptr).  Ditto for INDEX(id) being INDEX(id, ptr).

The "pointer" is either a byte offset into the .MYD file (for DYNAMIC) or record number (for FIXED).  In either case, the pointer leads to a "seek" into the .MYD file.

The pointer defaults to a 6-byte number, allowing for a huge number of rows.  It can be changed by a setting, either for saving space or allowing an even bigger number of rows.

For your particular query, INDEX(col2, id) is optimal and "covering".  It is better than INDEX(col2) for MyISAM, but they are equivalent for InnoDB, since InnoDB implicitly has the PK in each secondary index.

The query will have to scan at least 5000+1000 rows, at least in the index's BTree.

Note that InnoDB's PRIMARY KEY is clustered with the data, but MyISAM's PRIMARY KEY is a separate BTree, just like other secondary indexes.

You really should consider moving to InnoDB; there is virtually no reason to use MyISAM today.

Body:
My problem: imagine a table with millions of rows, like

CREATE TABLE a {
id INT PRIMARY KEY,
column2..,
column3..,
many other columns..
..
INDEX (column2);

and a query like this:

SELECT id FROM a WHERE column2 > 10000 LIMIT 1000 OFFSET 5000;

My question: does mysql only use the index "column2" (so the primary key id is implicitly stored as a reference in other indexes), or does it have to fetch all rows to get also the id, which is selected for output? In that case the query should be much faster with a key declared as:

INDEX column2(column2, id)


问:
Lua - how to simulate "multithreading"?
I have 2 functions:

```<code>function func1()
   while true do
       -- listen on connection
   end
end

function func2()
   while true do
       -- execute other code
   end
end
</code>```

I want to run both functions "simultaneously" while sharing variables between them. I have tried to create a dispatcher that makes a coroutine with the two functions but I can't think of a way to schedule them to quickly alternate their execution. (func1 runs for a second, func2 runs for a second, func1 runs for a second, and so on)

答:
There exist C libraries for Lua which expose methods for multithreading or multiprocessing.  Some examples would be

MPI for Lua

lua-llthread

Lua 5.1 pthread

lua---parallel (apparently (?) depends on Torch)

Torch has some parallel methods

All of these are third-party solution and, as the other answer explains, there are no built-in capabilities for asynchronous multithreading in Lua.

I think lua-llthread would come closest to what you describe.  It supports communication between threads via ZeroMQ.

Title: Lua - how to simulate "multithreading"?

Body:
I have 2 functions:

function func1()
   while true do
       -- listen on connection
   end
end

function func2()
   while true do
       -- execute other code
   end
end

I want to run both functions "simultaneously" while sharing variables between them. I have tried to create a dispatcher that makes a coroutine with the two functions but I can't think of a way to schedule them to quickly alternate their execution. (func1 runs for a second, func2 runs for a second, func1 runs for a second, and so on)


问:
Adding android fragment terminates the app
I am a newbie to Android development and I created a blank fragment, which has a textview by default. I tried to add the fragment to my main activity and I am getting following error:

Connected to process 3689 on device samsung-gt_i9300-32305248b97211f9
Application terminated.

Not getting any other exception reason.

```<code> <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorWhite"
    tools:context="com.ideasurge.winfertility.AccountActivity">

    <ImageView
        android:id="@+id/titleImageView"
        android:layout_width="wrap_content"
        android:layout_height="80dp"
        android:layout_marginLeft="30dp"
        android:layout_marginStart="30dp"
        android:layout_marginRight="30dp"
        android:layout_marginEnd="30dp"
        android:scaleType="centerInside"
        android:background="@color/colorWhite"
        app:srcCompat="@drawable/wftitleimage" />

    <TextView
        android:id="@+id/fertilityTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Your Fertility Companion"
        android:textStyle="bold"
        android:textSize="20sp"
        android:textColor="@color/colorBlack"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:layout_marginTop="20dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/titleImageView"/>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fragmentPlaceholder"
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/fertilityTextView">

        <!-- Fragment will go here eventually, but it's not added in the layout -->

    </LinearLayout>

</android.support.constraint.ConstraintLayout>
</code>```

Here is Java code:

```<code> AccountFragment fragment = new AccountFragment();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.fragmentPlaceholder, fragment);
    ft.commit();
</code>```

答: You can't add a Fragment to a LinearLayout. In must be a FrameLayout in order for it to work correctly.</p>

Body:
I am a newbie to Android development and I created a blank fragment, which has a textview by default. I tried to add the fragment to my main activity and I am getting following error:

Connected to process 3689 on device samsung-gt_i9300-32305248b97211f9
Application terminated.

Not getting any other exception reason.

 <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorWhite"
    tools:context="com.ideasurge.winfertility.AccountActivity">

    <ImageView
        android:id="@+id/titleImageView"
        android:layout_width="wrap_content"
        android:layout_height="80dp"
        android:layout_marginLeft="30dp"
        android:layout_marginStart="30dp"
        android:layout_marginRight="30dp"
        android:layout_marginEnd="30dp"
        android:scaleType="centerInside"
        android:background="@color/colorWhite"
        app:srcCompat="@drawable/wftitleimage" />

    <TextView
        android:id="@+id/fertilityTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Your Fertility Companion"
        android:textStyle="bold"
        android:textSize="20sp"
        android:textColor="@color/colorBlack"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:layout_marginTop="20dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/titleImageView"/>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fragmentPlaceholder"
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/fertilityTextView">

    </LinearLayout>

</android.support.constraint.ConstraintLayout>

Here is Java code:

 AccountFragment fragment = new AccountFragment();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.fragmentPlaceholder, fragment);
    ft.commit();


问:
Detect empty directory with Perl
What is an easy way to test if a folder is empty in perl? -s, and -z are not working.

Example:

```<code>#Ensure Apps directory exists on the test PC.
if ( ! -s $gAppsDir )
{
    die "\n$gAppsDir is not accessible or does not exist.\n";
}

#Ensure Apps directory exists on the test PC.
if ( ! -z $gAppsDir )
{
    die "\n$gAppsDir is not accessible or does not exist.\n";
}
</code>```

These above, do not work properly to tell me that the folder is empty. Thanks!

Thanks all! I ended up using:

```<code>sub is_folder_empty { my $dirname = shift; opendir(my $dh, $dirname) or die "Not a directory";
return scalar(grep { $_ ne "." && $_ ne ".." } readdir($dh)) == 0; }
</code>```

答: There is also File::List from cpan. It's overkill here, but can be handy for slightly more complex requests like test if a directory is empty with the meaning it contains only empty directories (ie: not files).

Title: Detect empty directory with Perl

Body:
What is an easy way to test if a folder is empty in perl? -s, and -z are not working.

Example:

#Ensure Apps directory exists on the test PC.
if ( ! -s $gAppsDir )
{
    die "\n$gAppsDir is not accessible or does not exist.\n";
}

#Ensure Apps directory exists on the test PC.
if ( ! -z $gAppsDir )
{
    die "\n$gAppsDir is not accessible or does not exist.\n";
}

These above, do not work properly to tell me that the folder is empty. Thanks!

Thanks all! I ended up using:

sub is_folder_empty { my $dirname = shift; opendir(my $dh, $dirname) or die "Not a directory";
return scalar(grep { $_ ne "." && $_ ne ".." } readdir($dh)) == 0; }


问:
REST API calls not working in swift
I'm following this tutorial for making a simple REST API call in swift: https://grokswift.com/simple-rest-with-swift/

The problem I'm running into is that the data task completion handler next gets executed. When I'm debugging it step by step, it just jumps over the completion handler block. Nothing is printed in the console, either.

I've searched for other methods of making REST API calls, but they are all very similar to this one and not working, either.

Here is my code:

```<code>    let endpoint: String = "https://jsonplaceholder.typicode.com/todos/1"
    guard let url = URL(string: endpoint) else {
        return
    }
    let urlRequest = URLRequest(url: url)
    let session = URLSession.shared

    let task = session.dataTask(with: urlRequest) { (data, response, error) -> Void in
        guard error == nil else {
            print("Error calling GET")
            return
        }
        guard let responseData = data else {
            print("Error receiving data")
            return
        }
        do {
            print ("Parsing response...")
        }
    }
    task.resume()
</code>```

答:
Your code looks right to me. I tested it in a Playground and I'm getting the Parsing response... message printed to the console which makes me think the issue is elsewhere in your code or environment. I'd be happy to take a look at the whole project if you can post a Github link or something similar.

Here are the steps I would take to debug an issue like this:

1) Confirm my execution environment has an active internet connection. The Safari app can be used to confirm on iOS devices or the Simulator. Playgrounds can be tested by pasting the following lines.

```<code>let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")!
print (try? String(contentsOf: url))
</code>```

Look for a line in the console output similar to:

```<code>Optional("{\n  \"userId\": 1,\n  \"id\": 1,\n  \"title\": \"delectus aut autem\",\n  \"completed\": false\n}")
</code>```

2) Confirm the url is valid and returns data by pasting it into a web browser url bar and hitting enter. You will either see JSON printed in the browser or not.

3) Confirm my code is actually getting called when the application runs. You can do this with either breakpoints or print() statements. As OOPer2 pointed out asynchronous callback closures like that used in session.dataTask() execute in a different time than the rest of your code which is why "it just jumps over the completion handler block" while stepping through with the debugger. You'll need to put another breakpoint or print() statement inside the completion handler closure. I'd put the breakpoint on the guard error == nil else { line.

4) Make sure the application is still executing when the network request finishes and the completion handler closure executes. If your code is in a ViewController running in an iOS application it's probably fine, but if it's running in a Playground it may not be. Playgrounds by default stop execution once the last line of code has been evaluated which means the completion closure will never execute. You can tell a Playground to continue executing indefinitely by importing the PlaygroundSupport framework and setting needsIndefiniteExecution = true on the current Playground page. Paste the entire code block below into a Playground to see it in action:

```<code>import Foundation
import PlaygroundSupport

// Keep executing the program after the last line has evaluated so the
// closure can execute when the asynchronous network request finishes.
PlaygroundPage.current.needsIndefiniteExecution = true

// Generic Result enum useful for returning values OR an error from
// asynchronous functions.
enum Result<T> {
    case failure(Error)
    case success(T)
}

// Custom Errors to be returned when something goes wrong.
enum NetworkError: Error {
    case couldNotCreateURL(for: String)
    case didNotReceiveData
}

// Perform network request asynchronous returning the result via a
// completion closure called on the main thread.
//
// In really life the result type will not be a String, it will
// probably be an array of custom structs or similar.
func performNetworkRequest(completion: @escaping (Result<String>)->Void ) {
    let endpoint: String = "https://jsonplaceholder.typicode.com/todos/1"

    guard let url = URL(string: endpoint) else {
        let error = NetworkError.couldNotCreateURL(for: endpoint)
        completion(Result.failure(error))
        return
    }

    let urlRequest = URLRequest(url: url)
    let session = URLSession.shared

    let task = session.dataTask(with: urlRequest) { (data, response, error) -> Void in
        // This closure is still executing on a background thread so
        // don't touch anything related to the UI.
        //
        // Remember to dispatch back to the main thread when calling
        // the completion closure.

        guard error == nil else {
            // Call the completion handler on the main thread.
            DispatchQueue.main.async {
                completion(Result.failure(error!))
            }
            return
        }
        guard let responseData = data else {
            // Call the completion handler on the main thread.
            DispatchQueue.main.async {
                completion(Result.failure(NetworkError.didNotReceiveData))
            }
            return
        }

        // Parse response here...

        // Call the completion handler on the main thread.
        DispatchQueue.main.async {
            completion(Result.success("Sucessfully parsed results"))
        }
    }
    task.resume()
}

performNetworkRequest(completion: { result in
    // The generic Result type makes handling the success and error
    // cases really nice by just using a switch statement.
    switch result {
    case .failure(let error):
        print(error)

    case .success(let parsedResponse):
        print(parsedResponse)
    }
})
</code>```

Title: REST API calls not working in swift

Body:
I'm following this tutorial for making a simple REST API call in swift: https://grokswift.com/simple-rest-with-swift/

The problem I'm running into is that the data task completion handler next gets executed. When I'm debugging it step by step, it just jumps over the completion handler block. Nothing is printed in the console, either.

I've searched for other methods of making REST API calls, but they are all very similar to this one and not working, either.

Here is my code:

    let endpoint: String = "https://jsonplaceholder.typicode.com/todos/1"
    guard let url = URL(string: endpoint) else {
        return
    }
    let urlRequest = URLRequest(url: url)
    let session = URLSession.shared

    let task = session.dataTask(with: urlRequest) { (data, response, error) -> Void in
        guard error == nil else {
            print("Error calling GET")
            return
        }
        guard let responseData = data else {
            print("Error receiving data")
            return
        }
        do {
            print ("Parsing response...")
        }
    }
    task.resume()

Body:
Your code looks right to me. I tested it in a Playground and I'm getting the Parsing response... message printed to the console which makes me think the issue is elsewhere in your code or environment. I'd be happy to take a look at the whole project if you can post a Github link or something similar.

Here are the steps I would take to debug an issue like this:

1) Confirm my execution environment has an active internet connection. The Safari app can be used to confirm on iOS devices or the Simulator. Playgrounds can be tested by pasting the following lines.

let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")!
print (try? String(contentsOf: url))

Look for a line in the console output similar to:

Optional("{\n  \"userId\": 1,\n  \"id\": 1,\n  \"title\": \"delectus aut autem\",\n  \"completed\": false\n}")

2) Confirm the url is valid and returns data by pasting it into a web browser url bar and hitting enter. You will either see JSON printed in the browser or not.

3) Confirm my code is actually getting called when the application runs. You can do this with either breakpoints or print() statements. As OOPer2 pointed out asynchronous callback closures like that used in session.dataTask() execute in a different time than the rest of your code which is why "it just jumps over the completion handler block" while stepping through with the debugger. You'll need to put another breakpoint or print() statement inside the completion handler closure. I'd put the breakpoint on the guard error == nil else { line.

4) Make sure the application is still executing when the network request finishes and the completion handler closure executes. If your code is in a ViewController running in an iOS application it's probably fine, but if it's running in a Playground it may not be. Playgrounds by default stop execution once the last line of code has been evaluated which means the completion closure will never execute. You can tell a Playground to continue executing indefinitely by importing the PlaygroundSupport framework and setting needsIndefiniteExecution = true on the current Playground page. Paste the entire code block below into a Playground to see it in action:

import Foundation
import PlaygroundSupport

// Keep executing the program after the last line has evaluated so the
// closure can execute when the asynchronous network request finishes.
PlaygroundPage.current.needsIndefiniteExecution = true

// Generic Result enum useful for returning values OR an error from
// asynchronous functions.
enum Result<T> {
    case failure(Error)
    case success(T)
}

// Custom Errors to be returned when something goes wrong.
enum NetworkError: Error {
    case couldNotCreateURL(for: String)
    case didNotReceiveData
}

// Perform network request asynchronous returning the result via a
// completion closure called on the main thread.
//
// In really life the result type will not be a String, it will
// probably be an array of custom structs or similar.
func performNetworkRequest(completion: @escaping (Result<String>)->Void ) {
    let endpoint: String = "https://jsonplaceholder.typicode.com/todos/1"

    guard let url = URL(string: endpoint) else {
        let error = NetworkError.couldNotCreateURL(for: endpoint)
        completion(Result.failure(error))
        return
    }

    let urlRequest = URLRequest(url: url)
    let session = URLSession.shared

    let task = session.dataTask(with: urlRequest) { (data, response, error) -> Void in
        // This closure is still executing on a background thread so
        // don't touch anything related to the UI.
        //
        // Remember to dispatch back to the main thread when calling
        // the completion closure.

        guard error == nil else {
            // Call the completion handler on the main thread.
            DispatchQueue.main.async {
                completion(Result.failure(error!))
            }
            return
        }
        guard let responseData = data else {
            // Call the completion handler on the main thread.
            DispatchQueue.main.async {
                completion(Result.failure(NetworkError.didNotReceiveData))
            }
            return
        }

        // Parse response here...

        // Call the completion handler on the main thread.
        DispatchQueue.main.async {
            completion(Result.success("Sucessfully parsed results"))
        }
    }
    task.resume()
}

performNetworkRequest(completion: { result in
    // The generic Result type makes handling the success and error
    // cases really nice by just using a switch statement.
    switch result {
    case .failure(let error):
        print(error)

    case .success(let parsedResponse):
        print(parsedResponse)
    }
})


问:
Java Exception Handling and streams
Before closing the stream and after reaching the end of stream marker, a program tries to read the stream again.
__error
__checked exception
__compile error
__no exception</p>

答:
you can also try this...

I have personal experience this will surely work.
public static void main(String Args[]) throws Exception

Title: Java Exception Handling and streams


问:
Building an array with select and objects in AngularJS
I'm trying to build an array that allows users to select from a set of options.  I have a generic array of objects, and when I add a new item to my model, I am able to select one of those objects.

The problem I'm having (I believe) is that the ng-options I'm using to populate the list of items get's cleared once a user makes a selection.  I'm not sure how to keep the full list of objects so that the user can change their mind if they want to.

I put together a quick sample of what I'm trying to do - http://jsfiddle.net/b0kwx1nj/

I'd appreciate any help anyone can provide.

Angular:

```<code>var myApp = angular.module('myApp', []);
function ToppingCtrl($scope) {
  $scope.toppings = [{
    name: 'Cheese',
    price: 0.5
  }, {
    name: 'Ham',
    price: 1.5
  }, {
    name: 'Sauce',
    price: 0.25
  }];
  $scope.myToppings = [];

  $scope.addTopping = function() {
    var newTopping = angular.copy($scope.toppings);
    $scope.myToppings.push(newTopping);
  }
}
</code>```

HTML:

```<code><div ng-controller="ToppingCtrl" class="container">
    <table>
        <tr>
            <th>Topping</th>
            <th>Price</th>
        </tr>
        <tr ng-repeat="item in myToppings track by $index">
            <td>
                <select
                    id="top_{{$index}}"
                    name="top_{{$index}}"
                    title="top_{{$index}}"
                    ng-model="myToppings[$index]"
                    ng-options="topping.name for topping in myToppings[$index]"
                >
                    <option value=''>-- select --</option>
                </select>
            </td>
            <td>{{myToppings[$index].price}}</td>
        </tr>
    </table>
    <button ng-click="addTopping()">Add topping</button>
</div>
</code>```

答:
Change ng-options to return the entire topping object and use the as label clause to show the topping name in the selector:

```<code><tr ng-repeat="item in myToppings track by $index">
    <td>
        <select
            id="top_{{$index}}"
            name="top_{{$index}}"
            title="top_{{$index}}"
            ng-model="item"
            <!-- REPLACE
            ng-options="topping.name for topping in myToppings[$index]"
            -->
            <!-- INSTEAD -->
            ng-options="topping as topping.name for topping in toppings"

            <option value=''>-- select --</option>
        </select>
    </td>
    <td>{{item.price}}</td>
</tr>
</code>```

The DEMO on JSFiddle

Body:
I'm trying to build an array that allows users to select from a set of options.  I have a generic array of objects, and when I add a new item to my model, I am able to select one of those objects.

The problem I'm having (I believe) is that the ng-options I'm using to populate the list of items get's cleared once a user makes a selection.  I'm not sure how to keep the full list of objects so that the user can change their mind if they want to.

I put together a quick sample of what I'm trying to do - http://jsfiddle.net/b0kwx1nj/

I'd appreciate any help anyone can provide.

Angular:

var myApp = angular.module('myApp', []);
function ToppingCtrl($scope) {
  $scope.toppings = [{
    name: 'Cheese',
    price: 0.5
  }, {
    name: 'Ham',
    price: 1.5
  }, {
    name: 'Sauce',
    price: 0.25
  }];
  $scope.myToppings = [];

  $scope.addTopping = function() {
    var newTopping = angular.copy($scope.toppings);
    $scope.myToppings.push(newTopping);
  }
}

HTML:

            Topping
            Price

                <select
                    id="top_{{$index}}"
                    name="top_{{$index}}"
                    title="top_{{$index}}"
                    ng-model="myToppings[$index]"
                    ng-options="topping.name for topping in myToppings[$index]"
                >
                    <option value=''>-- select --</option>
                </select>

            {{myToppings[$index].price}}

    <button ng-click="addTopping()">Add topping</button>

Body:
Change ng-options to return the entire topping object and use the as label clause to show the topping name in the selector:

<tr ng-repeat="item in myToppings track by $index">
    <td>
        <select
            id="top_{{$index}}"
            name="top_{{$index}}"
            title="top_{{$index}}"
            ng-model="item"
            <!-- REPLACE
            ng-options="topping.name for topping in myToppings[$index]"
            -->
            <!-- INSTEAD -->
            ng-options="topping as topping.name for topping in toppings"

            <option value=''>-- select --</option>
        </select>
    </td>
    <td>{{item.price}}</td>
</tr>

The DEMO on JSFiddle


问:
Swift 3 Send Email with Attachment Ambiguous Expression
I am trying to set up an email view controller using MFMailComposeViewControllerDelegate with the following code:

```<code>let fileName = "test.csv"

   let path = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)

 if MFMailComposeViewController.canSendMail() {
            let emailController = MFMailComposeViewController()
            emailController.mailComposeDelegate = self
            emailController.setToRecipients(["testemail.com"])
            emailController.setSubject("Test Email")
            emailController.setMessageBody("Test Message", isHTML: false)
            emailController.addAttachmentData(NSData(contentsOfURL: path)!, mimeType: "text/csv", fileName: "test.csv")
            present(emailController, animated: true, completion: nil)
        }
</code>```

The above throws an error on the addAttachmentData line is,

Type of expression is ambiguous without more context.

Am I missing something?

答:
Use two expressions instead of one:</p>

```<code>    let data = Data(contentsOf: path)!
 emailController.addAttachmentData(data, mimeType: "text/csv", fileName: "test.csv")
</code>```

Body:
I am trying to set up an email view controller using MFMailComposeViewControllerDelegate with the following code:

let fileName = "test.csv"

   let path = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)

 if MFMailComposeViewController.canSendMail() {
            let emailController = MFMailComposeViewController()
            emailController.mailComposeDelegate = self
            emailController.setToRecipients(["testemail.com"])
            emailController.setSubject("Test Email")
            emailController.setMessageBody("Test Message", isHTML: false)
            emailController.addAttachmentData(NSData(contentsOfURL: path)!, mimeType: "text/csv", fileName: "test.csv")
            present(emailController, animated: true, completion: nil)
        }

The above throws an error on the addAttachmentData line is,

Type of expression is ambiguous without more context.

Am I missing something?

Body:
Use two expressions instead of one:

    let data = Data(contentsOf: path)!
 emailController.addAttachmentData(data, mimeType: "text/csv", fileName: "test.csv")


问:
How to get newly created resource to client with CQRS and event sourcing based microservices
I'm experimenting with microservices, event sourcing and CQRS. However, I'm a little bit confused about how I go from issuing a command to performing a query to return the new state, specifically with regard to interactions with a web API gateway.

As an example, the simple application I am attempting to write (which probably doesn't actually need any of these; it is just something to aid my learning) creates a random-graph and then performs some long-running calculations on the graph. I've modelled this as two separate services: the GraphService and the ComputationService. The imagined process flow is as follows:

User requests new random graph.

API gateway constructs CreateGraph command and sends it to the
graph service.

GraphService command handler creates a graph and publishes a
GraphCreated event.

GraphService event handler subscribes to topic for graph events,
processes GraphCreated event and stores graph in persistent read
storage.

Client somehow gets the newly created graph.

ComputationService event handler subscribes to topic for graph
events, processes GraphCreated event and begins potentially
long-running computation, e.g. calculate diameter.

ComputationService publishes DiameterComputed event.

GraphService event handler subscribes to topic for computation
events, processed DiameterComputed event and updates the graph in
persistent read storage.

Client somehow gets updated - easier than getting the new graph, since already have an ID and can poll for changes / websockets / SSE, etc.

That seems relatively simple. However, my confusion lies in how to go about informing the API gateway, and thus the web client, of the new graph (as highlighted in bold above). In a typical CRUD process, the result of the POST request to create a new graph would be to return the URL of the new resource, for instance. However, with CQRS, commands should return nothing or an exception.

How do I pass information back to the client of the service (in this case the API gateway) about the ID of the new graph so that it can perform a query to get the representation of the new resource and send it to the user? Or at least get an ID so that the web client can ask the API gateway, etc?

As I see it at the moment, after sending a command, everyone is just left hanging. There needs to be some sort of subscription model that can be interrogated for the status of the graph creation. I considered having the API gateway generate a request ID which gets embedded with the CreateGraph command, but this then couples the service to the API.

I'm obviously missing something, but have no idea what. None of the examples I've looked at or discussions I've read address this issue and assume that the ID of whatever resource is already known. I couldn't find any discussions here addressing this issue, but if I've just missed them, please point me there rather than duplicating questions. Any pointers would be hugely welcomed.

答:
How do I pass information back to the client of the service (in this case the API gateway) about the ID of the new graph so that it can perform a query to get the representation of the new resource and send it to the user? Or at least get an ID so that the web client can ask the API gateway, etc?

By listening for the echo.

The basic idea behind at least once delivery is that I'm going to send you a message, and keep sending it over and over until I receive a message that proves you've received at least one copy of my message.

Therefore, my protocol looks something like

Establish a mail box where I can collect messages

Encode into the message instructions for delivering to my mailbox

Send the message to you

Check my mailbox

if the answer is there, I'm done

otherwise, I send you another copy of the message

The mail box could be implemented any number of ways -- it could be a callback; it could be a promise, it could be a correlation identifier.  You could have the signal dispatched by the command handler, when it gets acknowledgement of the write by the book of record, or by the "read model" when the new resource is available.


问:
Disable return key in UITextView
I am trying to disable the return key found when typing in a UITextView. I want the text to have no page indents like found in a UITextField. This is the code I have so far:

```<code>- (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)aRange replacementText:(NSString*)aText
{
if ([aTextView.text isEqualToString:@"\r\n"]) {
    return NO;
}
</code>```

Any ideas?

答:
In Swift 3+ add:

```<code>func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    guard text.rangeOfCharacter(from: CharacterSet.newlines) == nil else {
        // textView.resignFirstResponder() // uncomment this to close the keyboard when return key is pressed
        return false
    }

    return true
}
</code>```

Don't forget to add textView's delegate in order for this to be called

Title: Disable return key in UITextView

Body:
I am trying to disable the return key found when typing in a UITextView. I want the text to have no page indents like found in a UITextField. This is the code I have so far:

- (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)aRange replacementText:(NSString*)aText
{
if ([aTextView.text isEqualToString:@"\r\n"]) {
    return NO;
}

Any ideas?

Body:
In Swift 3+ add:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    guard text.rangeOfCharacter(from: CharacterSet.newlines) == nil else {
        // textView.resignFirstResponder() // uncomment this to close the keyboard when return key is pressed
        return false
    }

    return true
}

Don't forget to add textView's delegate in order for this to be called

ContentLicense: CC BY-SA 4.0


问:
Get an elements style inherited from classes *not* style attribute
How can I get the style of a div, that is being applied from stylesheets/style tags and ignore the element style programmatically?

e.g.

var alice = 'alice ' + $('.alice').css('color');
var boblice = 'alice ' + $('.bob').css('color');
var bob = 'bob ' + $('.bob').css('color');

$('#result').text(
alice + '\n' + bob
);

$('#expected').text(
boblice + '\n' + bob
);

var elem1 = document.getElementById("alice");
alicestyle = window.getComputedStyle(elem1, null);

console.log(alicestyle);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.alice {
  color:green;
}

.bob {
  color:green;
}</code>```

test

test

result:

expected:

getComputedStyle:

```

答:
Well, I don't think you can get the style directly from the stylesheets. But I think you can use below code for a workaround:

```<code>if( typeof( $('#alice').attr('style') ) != 'undefined' ) {
   $('#alice').removeAttr('style');
   var aliceSheets = $('.alice').css('color');
   console.log(aliceSheets);
}
</code>```

If you want to get the style only without changing the style of the element then you can add the style attribute back after reading the color.

Body:
How can I get the style of a div, that is being applied from stylesheets/style tags and ignore the element style programmatically?

e.g.

var alice = 'alice ' + $('.alice').css('color');
var boblice = 'alice ' + $('.bob').css('color');
var bob = 'bob ' + $('.bob').css('color');

$('#result').text(
alice + '\n' + bob
);

$('#expected').text(
boblice + '\n' + bob
);

var elem1 = document.getElementById("alice");
alicestyle = window.getComputedStyle(elem1, null);

console.log(alicestyle);

.alice {
  color:green;
}

.bob {
  color:green;
}

test

test

result:

expected:

getComputedStyle:

Body:
Well, I don't think you can get the style directly from the stylesheets. But I think you can use below code for a workaround:

if( typeof( $('#alice').attr('style') ) != 'undefined' ) {
   $('#alice').removeAttr('style');
   var aliceSheets = $('.alice').css('color');
   console.log(aliceSheets);
}

If you want to get the style only without changing the style of the element then you can add the style attribute back after reading the color.


问:
To Do List runtime issue
I tried to create a simple To-Do List program. It asks how many items you want in your list, it asks for each item, and it asks you if you want to display the items. However, I'm having a runtime error. When the program asks for the first item, it doesn't allow me to enter what my first list item is. When it lists my items in numerical order, the first item on the list (which I couldn't input text for, it skipped past it after displaying the text) appears twice. So, if I had 3 items on the list, here's what it would display:

```<code>1.
1.
2. (Second item)
3. (Third item)
</code>```

I've combed through the code, redone parts, and I can't find the issue. Here is my code:

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

/*
This is a program that will
help you create a To-Do List
*/

public class ToDoList
{
public static void main(String[] args)
{

    int numOfItems = -1, answer;
    Scanner keyboard = new Scanner(System.in);

    System.out.println("\n\nHello!\nThis is a program that will " +
                        "help you create a To-Do List.");

    while (numOfItems < 0)
    {
        System.out.println("\nHow many items do you want to add?");
        if (keyboard.hasNextInt())
            numOfItems = keyboard.nextInt();
    }

    String[] itemsArray = new String[numOfItems];

    for (int increasingNum = 0; numOfItems > increasingNum; increasingNum++)
    {
            System.out.println("\nPlease enter item number: " + (increasingNum + 1));
            itemsArray[increasingNum] = keyboard.nextLine();
    }

    System.out.println("\nCongratulations! You have successfully created a To-Do List." +
                        "\nWould you like to view the list now?" +
                        "\n\nEnter:\n\t\"1\" for Yes\n\t\"2\" for No");
    answer = keyboard.nextInt();

    if (answer == 1)
    {
        for (int secondIncreasingNum = 0; numOfItems > secondIncreasingNum; secondIncreasingNum++)
        {
            System.out.println((secondIncreasingNum + 1) + ". " + itemsArray[secondIncreasingNum]);
        }
    }

    System.exit(0);

}
}
</code>```

EDIT: I've fixed the first problem when it asks you to enter item number one, but the error at the end still occurs. It now lists it like this:

(empty)
1.(item 1)
2.(item 2)
etc.

答:
The problem is that you have a newline remaining in the scanner from after you have called nextInt() for getting the number of items you want to enter.

So the first call to nextLine() get that line which is empty.

Just add keyboard.nextLine() after your while loop to get the number of items, but before your for loop for the item text to clear it.

Also you have a lot of unnecessary variables declared for example in your loops:

```<code>for (int increasingNum = 0; numOfItems > increasingNum; increasingNum++)
{
     System.out.println("\nPlease enter item number: " + number);
     itemsArray[increasingNum] = keyboard.nextLine();
     number++;
}
</code>```

number is not required, you can replace it with

```<code>for (int increasingNum = 0; increasingNum < numOfItems ; increasingNum++)
{
     System.out.println("\nPlease enter item number: " + (increasingNum + 1));
     itemsArray[increasingNum] = keyboard.nextLine();
}
</code>```

and numOfItems != -1 && numOfItems < 0 is equivalent to just numOfItems < 0

Title: To Do List runtime issue

Body:
I tried to create a simple To-Do List program. It asks how many items you want in your list, it asks for each item, and it asks you if you want to display the items. However, I'm having a runtime error. When the program asks for the first item, it doesn't allow me to enter what my first list item is. When it lists my items in numerical order, the first item on the list (which I couldn't input text for, it skipped past it after displaying the text) appears twice. So, if I had 3 items on the list, here's what it would display:

1.
1.
2. (Second item)
3. (Third item)

I've combed through the code, redone parts, and I can't find the issue. Here is my code:

import java.util.Scanner;

/*
This is a program that will
help you create a To-Do List
*/

public class ToDoList
{
public static void main(String[] args)
{

    int numOfItems = -1, answer;
    Scanner keyboard = new Scanner(System.in);

    System.out.println("\n\nHello!\nThis is a program that will " +
                        "help you create a To-Do List.");

    while (numOfItems < 0)
    {
        System.out.println("\nHow many items do you want to add?");
        if (keyboard.hasNextInt())
            numOfItems = keyboard.nextInt();
    }

    String[] itemsArray = new String[numOfItems];

    for (int increasingNum = 0; numOfItems > increasingNum; increasingNum++)
    {
            System.out.println("\nPlease enter item number: " + (increasingNum + 1));
            itemsArray[increasingNum] = keyboard.nextLine();
    }

    System.out.println("\nCongratulations! You have successfully created a To-Do List." +
                        "\nWould you like to view the list now?" +
                        "\n\nEnter:\n\t\"1\" for Yes\n\t\"2\" for No");
    answer = keyboard.nextInt();

    if (answer == 1)
    {
        for (int secondIncreasingNum = 0; numOfItems > secondIncreasingNum; secondIncreasingNum++)
        {
            System.out.println((secondIncreasingNum + 1) + ". " + itemsArray[secondIncreasingNum]);
        }
    }

    System.exit(0);

}
}

EDIT: I've fixed the first problem when it asks you to enter item number one, but the error at the end still occurs. It now lists it like this:

(empty)
1.(item 1)
2.(item 2)
etc.

Body:
The problem is that you have a newline remaining in the scanner from after you have called nextInt() for getting the number of items you want to enter.

So the first call to nextLine() get that line which is empty.

Just add keyboard.nextLine() after your while loop to get the number of items, but before your for loop for the item text to clear it.

Also you have a lot of unnecessary variables declared for example in your loops:

for (int increasingNum = 0; numOfItems > increasingNum; increasingNum++)
{
     System.out.println("\nPlease enter item number: " + number);
     itemsArray[increasingNum] = keyboard.nextLine();
     number++;
}

number is not required, you can replace it with

for (int increasingNum = 0; increasingNum < numOfItems ; increasingNum++)
{
     System.out.println("\nPlease enter item number: " + (increasingNum + 1));
     itemsArray[increasingNum] = keyboard.nextLine();
}

and numOfItems != -1 && numOfItems < 0 is equivalent to just numOfItems < 0