问:
Handle queries inside loop in node.js
In the following code, the val variable value keeps changing due to asynchronous behavior and generates unexpected output i.e. before connection query for first loop is finished, var variable according to second loop and generates wrong output.What is the best way to handle queries in loop that avoid idiosyncrasies caused by asynchronous nature.

```<code>    var output = [];
    for ( var j = 0; j < someArr.length ; j++ ) {
         val = someArr[j];//some manipulation of someArr[j]
         connection.query( "select id from someTable where someCol = ?",val, function(err, rows, fields) {
             if ( err ) {
               console.log( err );
             } else {
               output.push( rows[0].someVal );//push query output to this variable
             }
       });
    }
</code>```

console.log( output );//should contain output for all queries.

答:
The best & standard  way to use loop & inside the that execute query is use async.eachSeries.

So using async.eachSeries it will execute one by one in series & once foreach complete you can use callback.

Ref : http://caolan.github.io/async/docs.html#eachSeries

```<code>var async = require('async');
var output = [];
connection.query('SELECT * FROM tablename LIMIT 10',function(error,results,filelds){
    if(error) throw err;

    async.eachSeries(results,function(data,callback){ // It will be executed one by one
            //Here it will be wait query execute. It will work like synchronous
            connection.query('SELECT * FROM tablename  where id = 1',function(error,results1,filelds){
                if(error) throw err;

                output.push(results1[0].id)
                callback();
            });

    }, function(err, results) {
        console.log(output); // Output will the value that you have inserted in array, once for loop completed ex . 1,2,3,4,5,6,7,8,9
    });

})
</code>```

Title: Handle queries inside loop in node.js

Body:
In the following code, the val variable value keeps changing due to asynchronous behavior and generates unexpected output i.e. before connection query for first loop is finished, var variable according to second loop and generates wrong output.What is the best way to handle queries in loop that avoid idiosyncrasies caused by asynchronous nature.

    var output = [];
    for ( var j = 0; j < someArr.length ; j++ ) {
         val = someArr[j];//some manipulation of someArr[j]
         connection.query( "select id from someTable where someCol = ?",val, function(err, rows, fields) {
             if ( err ) {
               console.log( err );
             } else {
               output.push( rows[0].someVal );//push query output to this variable
             }
       });
    }

console.log( output );//should contain output for all queries.

Body:
The best & standard  way to use loop & inside the that execute query is use async.eachSeries.

So using async.eachSeries it will execute one by one in series & once foreach complete you can use callback.

Ref : http://caolan.github.io/async/docs.html#eachSeries

var async = require('async');
var output = [];
connection.query('SELECT * FROM tablename LIMIT 10',function(error,results,filelds){
    if(error) throw err;

    async.eachSeries(results,function(data,callback){ // It will be executed one by one
            //Here it will be wait query execute. It will work like synchronous
            connection.query('SELECT * FROM tablename  where id = 1',function(error,results1,filelds){
                if(error) throw err;

                output.push(results1[0].id)
                callback();
            });

    }, function(err, results) {
        console.log(output); // Output will the value that you have inserted in array, once for loop completed ex . 1,2,3,4,5,6,7,8,9
    });

})


来源: stackexchange

问:
Convert integer (YYYYMMDD) to date format (mm/dd/yyyy) in python
I have following dataframe.

```<code>id int_date
1  20160228
2  20161231
3  20160618
4  20170123
5  20151124
</code>```

How to convert above date in int format to date format of mm/dd/yyyy? Want this in particular format for further excel operations?

```<code>id int_date
1  02/28/2016
2  12/31/2016
3  06/18/2016
4  01/23/2017
5  11/24/2015
</code>```

IS it also possible to generate third column with only Month in words? like January, February etc from int_date?

I tried following

```<code>date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))
</code>```

but date is in datetime object, how to put it as date in pandas DF?

答:
You can use datetime methods.

```<code>from datetime import datetime
a = '20160228'
date = datetime.strptime(a, '%Y%m%d').strftime('%m/%d/%Y')
</code>```

Good Luck;

ContentLicense: CC BY-SA 3.0

Body:
I have following dataframe.

id int_date
1  20160228
2  20161231
3  20160618
4  20170123
5  20151124

How to convert above date in int format to date format of mm/dd/yyyy? Want this in particular format for further excel operations?

id int_date
1  02/28/2016
2  12/31/2016
3  06/18/2016
4  01/23/2017
5  11/24/2015

IS it also possible to generate third column with only Month in words? like January, February etc from int_date?

I tried following

date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))

but date is in datetime object, how to put it as date in pandas DF?

Body:
You can use datetime methods.

from datetime import datetime
a = '20160228'
date = datetime.strptime(a, '%Y%m%d').strftime('%m/%d/%Y')

Good Luck;


问:
Adding id and attributes to Form element, Volt engine and Phalcon 3
I was trying to add an id to form element in Phalcon using volt syntax. But never found a solution for it.

Here is how I render the form:

```<code>{{ form("admin/saveSettings", "method": "post") }}
</code>```

答:
It is simple as that:

```<code>{{ form("admin/saveSettings", "method": "post", "id": "form-id", "class": "css-class") }}
</code>```

You can add more attributes by separating them with commas.

More examples of Tag Helpers can be found in the docs.

Body:
I was trying to add an id to form element in Phalcon using volt syntax. But never found a solution for it.

Here is how I render the form:

{{ form("admin/saveSettings", "method": "post") }}

Body:
It is simple as that:

{{ form("admin/saveSettings", "method": "post", "id": "form-id", "class": "css-class") }}

You can add more attributes by separating them with commas.

More examples of Tag Helpers can be found in the docs.


问:
How to match a folder name and use it in an if condition using grep in bash?
```<code>for d in */ ; do
    cd $d
    NUM = $(echo ${PWD##*/} | grep -q "*abc*");
    if [[ "$NUM" -ne "0" ]]; then
        pwd
    fi
    cd ..
done
</code>```

Here I'm trying to match a folder name to some substring 'abc' in the name of the folder and check if the output of the grep is not 0. But it gives me an error which reads that NUM: command not found

An error was addressed in comments.
NUM = $(echo ${PWD##*/} | grep -q "*abc*"); should be NUM=$(echo ${PWD##*/} | grep -q "*abc*");.

To clarify, the core problem would be to be able to match current directory name to a pattern.

答:
You can probably simply the code to just

```<code>if grep -q "*abc*" <<< "${PWD##*/}" 2>/dev/null; then
   echo "$PWD"
   # Your rest of the code goes here
fi
</code>```

You can use the exit code of the grep directly in a if-conditional without using a temporary variable here ($NUM here). The condition will pass if grep was able to find a match. The here-string <<<, will pass the input to grep similar to echo with a pipeline. The part 2>/dev/null is to just suppress any errors (stderr - file descriptor 2) if grep throws!

As an additional requirement asked by OP, to negate the conditional check just do

```<code>if ! grep -q "*abc*" <<< "${PWD##*/}" 2>/dev/null; then
</code>```

Body:
for d in */ ; do
    cd $d
    NUM = $(echo ${PWD##*/} | grep -q "*abc*");
    if [[ "$NUM" -ne "0" ]]; then
        pwd
    fi
    cd ..
done

Here I'm trying to match a folder name to some substring 'abc' in the name of the folder and check if the output of the grep is not 0. But it gives me an error which reads that NUM: command not found

An error was addressed in comments.
NUM = $(echo ${PWD##*/} | grep -q "*abc*"); should be NUM=$(echo ${PWD##*/} | grep -q "*abc*");.

To clarify, the core problem would be to be able to match current directory name to a pattern.

Body:
You can probably simply the code to just

if grep -q "*abc*" <<< "${PWD##*/}" 2>/dev/null; then
   echo "$PWD"
   # Your rest of the code goes here
fi

You can use the exit code of the grep directly in a if-conditional without using a temporary variable here ($NUM here). The condition will pass if grep was able to find a match. The here-string <<<, will pass the input to grep similar to echo with a pipeline. The part 2>/dev/null is to just suppress any errors (stderr - file descriptor 2) if grep throws!

As an additional requirement asked by OP, to negate the conditional check just do

if ! grep -q "*abc*" <<< "${PWD##*/}" 2>/dev/null; then


答: You can create a class with the JSON structure and use GSON to get the data like User user = gson.fromJson(json, User.class)

Title: Android JSON parsing error cannot be converted to JSONArray

Body:
I'm fairly new to Android dev, and am trying to write a programme to parse some JSON from a website and output it in a ListView. However, when I run my programme, I get the error: (There are more then 7 row same as this error)

03-31 05:25:14.296 3196-3196/nazilli.tenispark E/FAILED: Json parsing
error: Value
{"0":"2","id":"2","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-01","date":"2017-04-01","4":"20","hour":"20"}
of type org.json.JSONObject cannot be converted to JSONArray

03-31 05:25:14.297 3196-3196/nazilli.tenispark E/FAILED: Json parsing error:
Value
{"0":"3","id":"3","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-08","date":"2017-04-08","4":"20","hour":"20"}
of type org.json.JSONObject cannot be converted to JSONArray

The JSON I'm trying to parse is:

{"appointments":[{"0":"2","id":"2","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-01","date":"2017-04-01","4":"20","hour":"20"},{"0":"3","id":"3","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-08","date":"2017-04-08","4":"20","hour":"20"},{"0":"4","id":"4","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-15","date":"2017-04-15","4":"20","hour":"20"},{"0":"5","id":"5","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-22","date":"2017-04-22","4":"20","hour":"20"},{"0":"6","id":"6","1":"0","cid":"0","2":"1","uid":"1","3":"2017-03-24","date":"2017-03-24","4":"17","hour":"17"},{"0":"7","id":"7","1":"0","cid":"0","2":"1","uid":"1","3":"2017-03-26","date":"2017-03-26","4":"17","hour":"17"},{"0":"8","id":"8","1":"1","cid":"1","2":"1","uid":"1","3":"2017-03-26","date":"2017-03-26","4":"16","hour":"16"},{"0":"9","id":"9","1":"2","cid":"2","2":"1","uid":"1","3":"2017-03-26","date":"2017-03-26","4":"15","hour":"15"},{"0":"10","id":"10","1":"3","cid":"3","2":"1","uid":"1","3":"2017-03-26","date":"2017-03-26","4":"13","hour":"13"}]}

this my listview custom row java

public class adapter_appointment extends ArrayAdapter<String> {
    public adapter_appointment(Context context, String[] data){
        super(context, R.layout.row_layout, data);
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View customView = inflater.inflate(R.layout.row_layout, parent, false);
        String all_data = getItem(position);
        TextView title = (TextView) customView.findViewById(R.id.title);
        //title.setText(all_data.toString());
        try {
            JSONArray array = new JSONArray(all_data);
            JSONObject obj = array.getJSONObject(0);
            Log.d("SUCCESS", "JSON Object: " + obj.toString());
            if (obj.has("date") && !obj.isNull("date")) {
                title.setText(obj.getString("date").toString());
                Log.d("SUCCESS", "Date: " + obj.getString("date").toString());
            } else {
                // Do something
            }
        } catch (Exception e) {
            Log.e("FAILED", "Json parsing error: " + e.getMessage());
        }
        return customView;
    }
}

This is json.java

public class my_appointments extends AppCompatActivity {
    ListView lv;
    InputStream is = null;
    String line = null;
    String result = null;
    String[] data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_appointments);

        lv=(ListView) findViewById(R.id.my_appointments);
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
        //Run
        getData();
        ArrayAdapter adapter = new adapter_appointment(this, data);
        lv.setAdapter(adapter);
    }

    private void getData()
    {
        try {
            URL url = new URL("MY URL");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            is=new BufferedInputStream(con.getInputStream());
            //
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            while((line=br.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
            //
            JSONObject jo = new JSONObject(result);
            JSONArray ja = jo.getJSONArray("appointments");
            data = new String[ja.length()];
            for(int i=0;i<ja.length();i++)
            {
                jo=ja.getJSONObject(i);
                data[i]=jo.toString();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

If I don't parse:


问:
How can I pass a return value of a Function to another Function as Parameter?
How to pass a value returned by one function to another function.

```<code>function myFunction(){
    $a = "Hello World";
    return $a;
}

function anotherFunction(????){
    //how can I call the return value of myFunction() as parameter in this function?
}
</code>```

答:
Here's how:</p>

```<code><?php

function myFunction() {
    $a = "Hello World";

    return $a;
}

function anotherFunction( $yourvariable ) {
    //how can I call the return value of myFunction() as parameter in this function?
}

$myFunction = myFunction();

$anotherFunction = anotherFunction( $myFunction );
</code>```

Body:
How to pass a value returned by one function to another function.

function myFunction(){
    $a = "Hello World";
    return $a;
}

function anotherFunction(????){
    //how can I call the return value of myFunction() as parameter in this function?
}

Body:
Here's how:

<?php

function myFunction() {
    $a = "Hello World";

    return $a;
}

function anotherFunction( $yourvariable ) {
    //how can I call the return value of myFunction() as parameter in this function?
}

$myFunction = myFunction();

$anotherFunction = anotherFunction( $myFunction );


问:
Android FileProvider, is it possible to modify its paths programmatically in runtime

A FileProvider can only generate a content URI for files in
  directories that you specify beforehand.

Our app allows users to change our default save directory to an arbitrary folder on their device's SD Card.

We have no way of foreseeing such paths and specifying them in the provide_paths.xml file.

Has anybody had this problem before and have you managed to modify these paths in runtime?

答:
FileProvider cannot serve files from SD card or other removable media.

You cannot specify such folders in the xml.

If the user chooses a folder on external memory then you do not need to change paths in xml. If you call getUriForFile with the right File object then you are done.


问:
how to call handler within asyncTask
```<code>class GET_DOC_CONTACT_DELAY_TIME extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(PdfView.this);
            pDialog.setMessage("Processing...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

        }

        protected String doInBackground(String... args) {

            List<NameValuePair> params = new ArrayList<NameValuePair>();

            params.add(new BasicNameValuePair("dhw_gp_id",String.valueOf(Login.reg_id)));
            params.add(new BasicNameValuePair("dreg_id",String.valueOf(E_patId)));
            params.add(new BasicNameValuePair("dslno",String.valueOf(E_slno)));
            params.add(new BasicNameValuePair("ddos",String.valueOf(dosString)));
            params.add(new BasicNameValuePair("ddocid",String.valueOf(doc_id)));
            params.add(new BasicNameValuePair("dimei",String.valueOf(Login.imei)));

            JSONObject json = jsonParser.makeHttpRequest(DOC_SMS, "POST", params);

            final String dm = doc_contaclist.get(current_doc).get("vdocmobile");
            final String delay = doc_contaclist.get(current_doc).get("vdoctime");

            // check for success tag
            try {
                 rsuccess = json.getInt(TAG_RMSUCCESS);

                if (rsuccess == 1) {

                    runOnUiThread(new Runnable() {
                        public void run() {

                            final String message = "Patient "  + patFirstName + " " + patLastName +" with Id : "+ E_patId + "\n"+" is having an emergency and needs diagnosis immediately,";
                            SmsManager.getDefault().sendTextMessage(String.valueOf(dm), null,message, null, null);

                            new AlertDialog.Builder(PdfView.this)
                                    .setTitle("Confirmation Message")
                                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                            Intent i = new Intent(PdfView.this,Patient_Register.class);
                                            i.putExtra("clear_text",status_info);
                                            startActivity(i);
                                        }
                                    })
                                    .setMessage("ECG Sent to Doctor")
                                    .setIcon(R.drawable.alert1)
                                    .show();

                        }
                    });
                } else if (rsuccess == 0) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast toast = Toast.makeText(PdfView.this, "Required fields missing", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER,0,0);
                            toast.show();

                        }
                    });
                }else if (rsuccess == 2) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast toast = Toast.makeText(PdfView.this, "Database selection failed", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER,0,0);
                            toast.show();

                        }
                    });
                }else if (rsuccess == 3) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast toast = Toast.makeText(PdfView.this, "Failed to insert", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER,0,0);
                            toast.show();

                        }
                    });
                }else if (rsuccess == 4) {

                    runOnUiThread(new Runnable() {
                        public void run() {

                            current_doc++ ;

                             Toast toast = Toast.makeText(PdfView.this, "SMS to next doctor", Toast.LENGTH_SHORT);
                             toast.setGravity(Gravity.CENTER,0,0);
                             toast.show();

                       }
                   });
                }  else if (rsuccess == 5) {
                    runOnUiThread(new Runnable() {
                        public void run() {

                            loop_exit= true;

                            Toast toast = Toast.makeText(PdfView.this, "Processed", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER,0,0);
                            toast.show();

                        }
                    });
                }

          Handler handler = new Handler();
       handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Send_sms();
            }
       }, 20000);

            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            if ((pDialog != null) && pDialog.isShowing()) {
                pDialog.dismiss();
            }
        }
    }
</code>```

Trying to call handler inside asyncTask method but its throwing the error (application crahing). This handler should be called with a delay of 1 min or 2mins. Tried with multiple methods.  Anybody pls help me out in calling handler inside asynctask.

答:
According to your Requirement call Handler in onPostExecute Method .

onPostExecute => Runs on the UI thread after doInBackground(Params...).

```<code>protected void onPostExecute(String file_url) {

     Handler handler = new Handler();
     handler.postDelayed(new Runnable()
        {
        @Override
        public void run()
           {
            Send_sms();
           }
        }, 20000); //Time Delay
      }
</code>```

Title: how to call handler within asyncTask

Body:
class GET_DOC_CONTACT_DELAY_TIME extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(PdfView.this);
            pDialog.setMessage("Processing...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

        }

        protected String doInBackground(String... args) {

            List<NameValuePair> params = new ArrayList<NameValuePair>();

            params.add(new BasicNameValuePair("dhw_gp_id",String.valueOf(Login.reg_id)));
            params.add(new BasicNameValuePair("dreg_id",String.valueOf(E_patId)));
            params.add(new BasicNameValuePair("dslno",String.valueOf(E_slno)));
            params.add(new BasicNameValuePair("ddos",String.valueOf(dosString)));
            params.add(new BasicNameValuePair("ddocid",String.valueOf(doc_id)));
            params.add(new BasicNameValuePair("dimei",String.valueOf(Login.imei)));

            JSONObject json = jsonParser.makeHttpRequest(DOC_SMS, "POST", params);

            final String dm = doc_contaclist.get(current_doc).get("vdocmobile");
            final String delay = doc_contaclist.get(current_doc).get("vdoctime");

            // check for success tag
            try {
                 rsuccess = json.getInt(TAG_RMSUCCESS);

                if (rsuccess == 1) {

                    runOnUiThread(new Runnable() {
                        public void run() {

                            final String message = "Patient "  + patFirstName + " " + patLastName +" with Id : "+ E_patId + "\n"+" is having an emergency and needs diagnosis immediately,";
                            SmsManager.getDefault().sendTextMessage(String.valueOf(dm), null,message, null, null);

                            new AlertDialog.Builder(PdfView.this)
                                    .setTitle("Confirmation Message")
                                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                            Intent i = new Intent(PdfView.this,Patient_Register.class);
                                            i.putExtra("clear_text",status_info);
                                            startActivity(i);
                                        }
                                    })
                                    .setMessage("ECG Sent to Doctor")
                                    .setIcon(R.drawable.alert1)
                                    .show();

                        }
                    });
                } else if (rsuccess == 0) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast toast = Toast.makeText(PdfView.this, "Required fields missing", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER,0,0);
                            toast.show();

                        }
                    });
                }else if (rsuccess == 2) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast toast = Toast.makeText(PdfView.this, "Database selection failed", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER,0,0);
                            toast.show();

                        }
                    });
                }else if (rsuccess == 3) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast toast = Toast.makeText(PdfView.this, "Failed to insert", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER,0,0);
                            toast.show();

                        }
                    });
                }else if (rsuccess == 4) {

                    runOnUiThread(new Runnable() {
                        public void run() {

                            current_doc++ ;

                             Toast toast = Toast.makeText(PdfView.this, "SMS to next doctor", Toast.LENGTH_SHORT);
                             toast.setGravity(Gravity.CENTER,0,0);
                             toast.show();

                       }
                   });
                }  else if (rsuccess == 5) {
                    runOnUiThread(new Runnable() {
                        public void run() {

                            loop_exit= true;

                            Toast toast = Toast.makeText(PdfView.this, "Processed", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER,0,0);
                            toast.show();

                        }
                    });
                }

          Handler handler = new Handler();
       handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Send_sms();
            }
       }, 20000);

            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            if ((pDialog != null) && pDialog.isShowing()) {
                pDialog.dismiss();
            }
        }
    }

Trying to call handler inside asyncTask method but its throwing the error (application crahing). This handler should be called with a delay of 1 min or 2mins. Tried with multiple methods.  Anybody pls help me out in calling handler inside asynctask.

Body:
According to your Requirement call Handler in onPostExecute Method .

onPostExecute => Runs on the UI thread after doInBackground(Params...).

protected void onPostExecute(String file_url) {

     Handler handler = new Handler();
     handler.postDelayed(new Runnable()
        {
        @Override
        public void run()
           {
            Send_sms();
           }
        }, 20000); //Time Delay
      }


问:
Access Denied when opening phpMyAdmin
What could be the problem of my MySQL database server in WAMP.

I can't open it. The error says:

MySQL said: Documentation
#2002 - No connection could be made because the target machine actively refused it.

The server is not responding (or the local server's socket is not correctly configured).
```
<p>I checked the ports, but no other apps are using port 3306 which is dedicated to mysqld.</p>
<p>Here's what <code>mysql.log</code> says:</p>
<pre class="lang-none prettyprint-override"><code>120728 22:34:40 [Note] Plugin 'FEDERATED' is disabled.
120728 22:34:42 InnoDB: The InnoDB memory heap is disabled
120728 22:34:42 InnoDB: Mutexes and rw_locks use Windows interlocked functions
120728 22:34:42 InnoDB: Compressed tables use zlib 1.2.3
120728 22:34:43 InnoDB: Initializing buffer pool, size = 128.0M
120728 22:34:43 InnoDB: Completed initialization of buffer pool
120728 22:34:44 InnoDB: highest supported file format is Barracuda.
120728 22:34:52  InnoDB: Waiting for the background threads to start
120728 22:34:53 InnoDB: 1.1.8 started; log sequence number 74876578
wampmysqld: File '.\mysql-bin.000025' not found (Errcode: 2)
120728 22:34:53 [ERROR] Failed to open log (file '.\mysql-bin.000025', errno 2)
120728 22:34:53 [ERROR] Could not open log file
120728 22:34:53 [ERROR] Can't init tc log
120728 22:34:53 [ERROR] Aborting

120728 22:34:53  InnoDB: Starting shutdown...
120728 22:34:53  InnoDB: Shutdown completed; log sequence number 74876578
120728 22:34:53 [Note] wampmysqld: Shutdown complete

120728 22:35:16 [Note] Plugin 'FEDERATED' is disabled.
120728 22:35:16 InnoDB: The InnoDB memory heap is disabled
120728 22:35:16 InnoDB: Mutexes and rw_locks use Windows interlocked functions
120728 22:35:16 InnoDB: Compressed tables use zlib 1.2.3
120728 22:35:16 InnoDB: Initializing buffer pool, size = 128.0M
120728 22:35:16 InnoDB: Completed initialization of buffer pool
120728 22:35:16 InnoDB: highest supported file format is Barracuda.
120728 22:35:32  InnoDB: Waiting for the background threads to start
120728 22:35:33 InnoDB: 1.1.8 started; log sequence number 74876578
wampmysqld: File '.\mysql-bin.000025' not found (Errcode: 2)
120728 22:35:33 [ERROR] Failed to open log (file '.\mysql-bin.000025', errno 2)
120728 22:35:33 [ERROR] Could not open log file
120728 22:35:33 [ERROR] Can't init tc log
120728 22:35:33 [ERROR] Aborting

120728 22:35:33  InnoDB: Starting shutdown...
120728 22:35:34  InnoDB: Shutdown completed; log sequence number 74876578
120728 22:35:34 [Note] wampmysqld: Shutdown complete

120728 22:35:42 [Note] Plugin 'FEDERATED' is disabled.
120728 22:35:42 InnoDB: The InnoDB memory heap is disabled
120728 22:35:42 InnoDB: Mutexes and rw_locks use Windows interlocked functions
120728 22:35:42 InnoDB: Compressed tables use zlib 1.2.3
120728 22:35:42 InnoDB: Initializing buffer pool, size = 128.0M
120728 22:35:42 InnoDB: Completed initialization of buffer pool
120728 22:35:44 InnoDB: highest supported file format is Barracuda.
120728 22:35:59  InnoDB: Waiting for the background threads to start
120728 22:36:00 InnoDB: 1.1.8 started; log sequence number 74876578
wampmysqld: File '.\mysql-bin.000025' not found (Errcode: 2)
120728 22:36:00 [ERROR] Failed to open log (file '.\mysql-bin.000025', errno 2)
120728 22:36:00 [ERROR] Could not open log file
120728 22:36:00 [ERROR] Can't init tc log
120728 22:36:00 [ERROR] Aborting

120728 22:36:00  InnoDB: Starting shutdown...
120728 22:36:01  InnoDB: Shutdown completed; log sequence number 74876578
120728 22:36:01 [Note] wampmysqld: Shutdown complete
</code>```

PS: I don't have a Skype. So I think it's not the conflict.

答:
You can solve this problem by rebooting your system.

In Ubuntu you can use:

```<code>reboot
</code>```

ContentLicense: CC BY-SA 4.0

Title: Access Denied when opening phpMyAdmin

Body:
What could be the problem of my MySQL database server in WAMP.

I can't open it. The error says:

MySQL said: Documentation
#2002 - No connection could be made because the target machine actively refused it.

The server is not responding (or the local server's socket is not correctly configured).

I checked the ports, but no other apps are using port 3306 which is dedicated to mysqld.

Here's what mysql.log says:

120728 22:34:40 [Note] Plugin 'FEDERATED' is disabled.
120728 22:34:42 InnoDB: The InnoDB memory heap is disabled
120728 22:34:42 InnoDB: Mutexes and rw_locks use Windows interlocked functions
120728 22:34:42 InnoDB: Compressed tables use zlib 1.2.3
120728 22:34:43 InnoDB: Initializing buffer pool, size = 128.0M
120728 22:34:43 InnoDB: Completed initialization of buffer pool
120728 22:34:44 InnoDB: highest supported file format is Barracuda.
120728 22:34:52  InnoDB: Waiting for the background threads to start
120728 22:34:53 InnoDB: 1.1.8 started; log sequence number 74876578
wampmysqld: File '.\mysql-bin.000025' not found (Errcode: 2)
120728 22:34:53 [ERROR] Failed to open log (file '.\mysql-bin.000025', errno 2)
120728 22:34:53 [ERROR] Could not open log file
120728 22:34:53 [ERROR] Can't init tc log
120728 22:34:53 [ERROR] Aborting

120728 22:34:53  InnoDB: Starting shutdown...
120728 22:34:53  InnoDB: Shutdown completed; log sequence number 74876578
120728 22:34:53 [Note] wampmysqld: Shutdown complete

120728 22:35:16 [Note] Plugin 'FEDERATED' is disabled.
120728 22:35:16 InnoDB: The InnoDB memory heap is disabled
120728 22:35:16 InnoDB: Mutexes and rw_locks use Windows interlocked functions
120728 22:35:16 InnoDB: Compressed tables use zlib 1.2.3
120728 22:35:16 InnoDB: Initializing buffer pool, size = 128.0M
120728 22:35:16 InnoDB: Completed initialization of buffer pool
120728 22:35:16 InnoDB: highest supported file format is Barracuda.
120728 22:35:32  InnoDB: Waiting for the background threads to start
120728 22:35:33 InnoDB: 1.1.8 started; log sequence number 74876578
wampmysqld: File '.\mysql-bin.000025' not found (Errcode: 2)
120728 22:35:33 [ERROR] Failed to open log (file '.\mysql-bin.000025', errno 2)
120728 22:35:33 [ERROR] Could not open log file
120728 22:35:33 [ERROR] Can't init tc log
120728 22:35:33 [ERROR] Aborting

120728 22:35:33  InnoDB: Starting shutdown...
120728 22:35:34  InnoDB: Shutdown completed; log sequence number 74876578
120728 22:35:34 [Note] wampmysqld: Shutdown complete

120728 22:35:42 [Note] Plugin 'FEDERATED' is disabled.
120728 22:35:42 InnoDB: The InnoDB memory heap is disabled
120728 22:35:42 InnoDB: Mutexes and rw_locks use Windows interlocked functions
120728 22:35:42 InnoDB: Compressed tables use zlib 1.2.3
120728 22:35:42 InnoDB: Initializing buffer pool, size = 128.0M
120728 22:35:42 InnoDB: Completed initialization of buffer pool
120728 22:35:44 InnoDB: highest supported file format is Barracuda.
120728 22:35:59  InnoDB: Waiting for the background threads to start
120728 22:36:00 InnoDB: 1.1.8 started; log sequence number 74876578
wampmysqld: File '.\mysql-bin.000025' not found (Errcode: 2)
120728 22:36:00 [ERROR] Failed to open log (file '.\mysql-bin.000025', errno 2)
120728 22:36:00 [ERROR] Could not open log file
120728 22:36:00 [ERROR] Can't init tc log
120728 22:36:00 [ERROR] Aborting

120728 22:36:00  InnoDB: Starting shutdown...
120728 22:36:01  InnoDB: Shutdown completed; log sequence number 74876578
120728 22:36:01 [Note] wampmysqld: Shutdown complete

PS: I don't have a Skype. So I think it's not the conflict.

Body:
You can solve this problem by rebooting your system.

In Ubuntu you can use:

reboot


问:
UWP Creation of app packages loses localizations
I have bunch of languages:

I'm creating packages for Hockey App distribution.

Selected Never, in order to include all resources.

Installing the app on my PC, if I have this settings:

No Latvian in settings, then the app will not switch to LV language - it will use EN.

But why, when I have set the "Generate app bundle" to Never as described here:

http://www.guruumeditation.net/en/dynamically-change-the-language-of-a-universal-app/

What I want: I want a simple app, that has a menu with many languages (not based on users OS settings) and user could switch the language in runtime without app restart.

答:
I finally found a solution. This link helps to achieve a normal behavior:

https://msdn.microsoft.com/en-us/library/dn482043.aspx

Shortly:

1) Modify the .csproj
2) Create app bundle = always ( to include packages for x86, x64 and ARM )

And thats it. The language resources will always be available in app


问:
How do I add features to Visual Studio 2017?
Let's say that when I installed Visual Studio 2017 I decided to use the "Windows Universal Platform" packages.  Later, I realize that I'd like to install the ".Net Desktop packages" (either instead, or in addition).

How can I go back and add those features to Visual Studio 2017?  Is there a way to do this within Visual Studio?  Do I have to re-run the installer?

答: Re-run the visual studio launcher and click on modify. Make your edits and the launcher install the missing components. </p>


问:
Online or offline text to html entities converter
Does anyone know of any online or offline software that will take, say, a paragraph of text with quotes and other characters in it and convert it to html entities ?

I am not looking for the normal alphabetic characters to be converted, just the quotes and dashes etc.

Reason I ask is that we have a copywriting department who insist on using Word for writing copy for websites but copying and pasting this into a site whilst having to find the strange characters is time consuming and tedious.

答:
PHP functions htmlspecialchars makes this easy. You can easily make a small html form who posts to a php script that write out the result.

PHP:

```<code>echo htmlspecialchars($_POST['input']);
</code>```

HTML:

```<code><form method="post">
<textarea name="input"></textarea>
</form>
</code>```

http://php.net/htmlspecialchars

Body:
PHP functions htmlspecialchars makes this easy. You can easily make a small html form who posts to a php script that write out the result.

PHP:

echo htmlspecialchars($_POST['input']);

HTML:

<form method="post">
<textarea name="input"></textarea>
</form>

http://php.net/htmlspecialchars

ContentLicense: CC BY-SA 2.5


问:
creating local push notification using react-native
I am developing android app using react-native. I want to create local push notification by clicking on button. how can I do this? which all the libraries I need to import?  prasanna</p>

答:
```<code>import PushNotification from 'react-native-push-notification';

scheduleNotfication() {
 PushNotification.localNotificationSchedule({
 message: "My Notification Message", // message
 date: new Date(Date.now() + (60 * 1000)) // your required time
 });
}
</code>```

<p>call the scheduleNotfication() method inside button </p>

Body:
import PushNotification from 'react-native-push-notification';

scheduleNotfication() {
 PushNotification.localNotificationSchedule({
 message: "My Notification Message", // message
 date: new Date(Date.now() + (60 * 1000)) // your required time
 });
}

call the scheduleNotfication() method inside button


问:
Display placeholder instead of 0 when binding empty fields of numbers in MVC5
I am working on edit in MVC 5 with API Controllers. When user presses edit, a model with values fetched from db will be passed. However when adding a new data, empty model will be passed with following code

```<code>var Model = {
    Id: '',
    Type: ''
}
$.ajax({
    url: '@Url.Action("Action", "Control")',
    type: 'POST',
    data: { model: Model },
    success: function (data) {
    }
</code>```

My web controller

```<code>public ActionResult Add(Model model)
{
    return View(model);
}
</code>```

Now when I try to add the values, all the fields with string type will show placeholder but integers will show 0 instead of placeholder. I know its because I have passed empty field for numbers in my model but I need a workaround such that when empty numbers are passed it shows placeholder instead of displaying 0 using javascript or jquery

答:
When you want to model binding to avoid 0 as default to integer type , please user null able integer value

```<code> public int? Count { get; set; }
</code>```

This will assign as null to integer property rather than zero when you post model from java script or jquery as black or empty.

Body:
I am working on edit in MVC 5 with API Controllers. When user presses edit, a model with values fetched from db will be passed. However when adding a new data, empty model will be passed with following code

var Model = {
    Id: '',
    Type: ''
}
$.ajax({
    url: '@Url.Action("Action", "Control")',
    type: 'POST',
    data: { model: Model },
    success: function (data) {
    }

My web controller

public ActionResult Add(Model model)
{
    return View(model);
}

Now when I try to add the values, all the fields with string type will show placeholder but integers will show 0 instead of placeholder. I know its because I have passed empty field for numbers in my model but I need a workaround such that when empty numbers are passed it shows placeholder instead of displaying 0 using javascript or jquery

Body:
When you want to model binding to avoid 0 as default to integer type , please user null able integer value

 public int? Count { get; set; }

This will assign as null to integer property rather than zero when you post model from java script or jquery as black or empty.


答:
PHP code demo</p>

```<code><?php
function myFunction(){
   $a = "Hello World";
   return $a;
}

function anotherFunction($requiredParameter)
{
   echo $requiredParameter; //here you will see your parameter.
}

function someOtherFunction()
{
    anotherFunction(myFunction());
}
someOtherFunction();
</code>```

Title: How can I pass a return value of a Function to another Function as Parameter?

Body:
PHP code demo

<?php
function myFunction(){
   $a = "Hello World";
   return $a;
}

function anotherFunction($requiredParameter)
{
   echo $requiredParameter; //here you will see your parameter.
}

function someOtherFunction()
{
    anotherFunction(myFunction());
}
someOtherFunction();


问:
QSslSocket times out when waiting for data (but QTcpSocket does not)
Here's a pair of simple client and server apps that try to communicate over QTcpSocket or QSslSocket and send each other a few bytes of data. It seems to work over TCP, but when I attempt to use SSL, the read always times out on the server's side. Please tell me what I'm doing wrong.

Here's my full code:

Client:

```<code>#include <QTcpSocket>
#include <QSslSocket>
#include <QTimer>
#include <QApplication>

#define dumpvar(x) qDebug()<<#x<<'='<<x

// reads exactly len bytes from d into data,
// blocks until data is available
// or throws std::runtime_error on error or timeout
// timeout_msec = -1 means no timeout
void readWrapper(QIODevice &d, void *data, qint64 len, int timeout_msec)
{
    QTimer t;
    t.setSingleShot(true);
    // note: inactive timer's remainingTime() returns -1
    if (timeout_msec >= 0) t.start(timeout_msec);
    qint64 bytesRead = 0;
    auto dataPtr = (char*)data;
    while (bytesRead < len){
        auto bytesNeeded = len - bytesRead;
        auto ret = d.read(dataPtr, bytesNeeded);
        if (ret == -1){
            throw std::runtime_error(d.errorString().toStdString());
        }
        qDebug()<<QString("Attempted to read %1 bytes, got %2 bytes")
                  .arg(bytesNeeded)
                  .arg(ret);
        if (ret == 0) {
            qDebug("Calling waitForReadyRead");
            bool ret = d.waitForReadyRead(t.remainingTime());
            if (!ret){
                qDebug()<<"waitForReadyRead failed";
                throw std::runtime_error(d.errorString().toStdString());
            }
        }
        else {
            bytesRead += ret;
            dataPtr += ret;
        }
        if (t.remainingTime() == 0)
            throw std::runtime_error("blockingRead timeout");
    }
}

QByteArray readWrapper(QIODevice &d, qint64 len, int timeout_msec = 10000)
{
    QByteArray ret;
    ret.resize(len);
    readWrapper(d, ret.data(), len, timeout_msec);
    return ret;
}

void writeWrapper(QIODevice &d, void *data, qint64 len)
{
    auto ret = d.write((char*)data, len);
    if (ret < len){
        throw std::runtime_error(QString("error writing data: %1")
                                 .arg(d.errorString())
                                 .toStdString());
    }
}

void writeWrapper(QIODevice &d, const QByteArray &data)
{
    writeWrapper(d, (void*)data.data(), data.size());
}

using namespace std;

void handleConnection(QAbstractSocket& s)
{
    QByteArray data = "test c";
    qDebug()<<"writing data";
    writeWrapper(s, data);
    qDebug()<<"reading data";
    auto readData = readWrapper(s, 6);
    dumpvar(readData);
    s.disconnectFromHost();
    s.waitForDisconnected();
}

void tcpclient()
{
    QTcpSocket s;
    s.connectToHost("localhost", 1234);
    if(!s.waitForConnected(-1)){
        qDebug()<<s.errorString();
        return;
    }

    qDebug()<<"client connected";
    handleConnection(s);
}

void sslclient()
{
    QSslSocket s;
    auto cert = QSslCertificate::fromPath("/home/piotrek/cert.pem");
    Q_ASSERT(!cert.isEmpty());
    s.setCaCertificates({cert});
    s.ignoreSslErrors({{QSslError::HostNameMismatch, cert[0]}});
    s.connectToHostEncrypted("localhost", 1234);
    if (!s.waitForEncrypted(10000)){
        dumpvar(s.errorString());
        dumpvar(s.sslErrors());
        return;
    }

    qDebug()<<"client connected";
    handleConnection(s);
}

int main(int argc, char** argv)
{
    QCoreApplication a(argc, argv);

//  tcpclient();
    sslclient();

}
</code>```

Server:

```<code>#include <QTcpSocket>
#include <QSslSocket>
#include <QTimer>
#include <QCoreApplication>
#include <QTcpServer>
#include <QSslKey>

#define dumpvar(x) qDebug()<<#x<<'='<<x

// reads exactly len bytes from d into data,
// blocks until data is available
// or throws std::runtime_error on error or timeout
// timeout_msec = -1 means no timeout
void readWrapper(QIODevice &d, void *data, qint64 len, int timeout_msec)
{
    QTimer t;
    t.setSingleShot(true);
    // note: inactive timer's remainingTime() returns -1
    if (timeout_msec >= 0) t.start(timeout_msec);
    qint64 bytesRead = 0;
    auto dataPtr = (char*)data;
    while (bytesRead < len){
        auto bytesNeeded = len - bytesRead;
        auto ret = d.read(dataPtr, bytesNeeded);
        if (ret == -1){
            throw std::runtime_error(d.errorString().toStdString());
        }
        qDebug()<<QString("Attempted to read %1 bytes, got %2 bytes")
                  .arg(bytesNeeded)
                  .arg(ret);
        if (ret == 0) {
            qDebug("Calling waitForReadyRead");
            bool ret = d.waitForReadyRead(t.remainingTime());
            if (!ret){
                qDebug()<<"waitForReadyRead failed";
                throw std::runtime_error(d.errorString().toStdString());
            }
        }
        else {
            bytesRead += ret;
            dataPtr += ret;
        }
        if (t.remainingTime() == 0)
            throw std::runtime_error("blockingRead timeout");
    }
}

QByteArray readWrapper(QIODevice &d, qint64 len, int timeout_msec = 10000)
{
    QByteArray ret;
    ret.resize(len);
    readWrapper(d, ret.data(), len, timeout_msec);
    return ret;
}

void writeWrapper(QIODevice &d, void *data, qint64 len)
{
    auto ret = d.write((char*)data, len);
    if (ret < len){
        throw std::runtime_error(QString("error writing data: %1")
                                 .arg(d.errorString())
                                 .toStdString());
    }
}

void writeWrapper(QIODevice &d, const QByteArray &data)
{
    writeWrapper(d, (void*)data.data(), data.size());
}

void handleConnection(QAbstractSocket* s)
{
    qDebug()<<__FUNCTION__;
    QByteArray data = "test s";
    qDebug()<<"writing data";
    writeWrapper(*s, data);
    qDebug()<<"reading data";
    auto readData = readWrapper(*s, 6);
    dumpvar(readData);
    s->disconnectFromHost();
    s->waitForDisconnected();
}

class SslServer: public QTcpServer
{
    // QTcpServer interface
protected:
    void incomingConnection(qintptr handle) override
    {
        QSslSocket s;
        if (!s.setSocketDescriptor(handle)){
            dumpvar(s.errorString());
            return;
        }

        s.setLocalCertificate("/home/piotrek/cert.pem");
        Q_ASSERT(!s.localCertificate().isNull());
        s.setPrivateKey("/home/piotrek/key.pem", QSsl::Rsa, QSsl::Pem, "test"); // last argument is private key decryption password
        Q_ASSERT(!s.privateKey().isNull());
        s.startServerEncryption();
        qDebug()<<"waiting for encrypted";
        if(!s.waitForEncrypted(10000)){
            dumpvar(s.errorString());
            dumpvar(s.sslErrors());
            return;
        }

        qDebug()<<"server encrypted";

        handleConnection(&s);
    }
};

void tcpserver()
{
    QTcpServer *s = new QTcpServer;
    QObject::connect(s, &QTcpServer::newConnection, [s]{
        handleConnection(s->nextPendingConnection());
    });

    s->listen(QHostAddress::Any, 1234);
}

void sslserver()
{
    auto s = new SslServer;
    s->listen(QHostAddress::Any, 1234);
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

//  tcpserver();
    sslserver();

    return a.exec();
}
</code>```

Command used to generate self-signed cert:

```<code>openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365
</code>```

Here's the output on TCP:

Client:

```<code>client connected
writing data
reading data
"Attempted to read 6 bytes, got 0 bytes"
Calling waitForReadyRead
"Attempted to read 6 bytes, got 6 bytes"
readData = "test s"
QAbstractSocket::waitForDisconnected() is not allowed in UnconnectedState
</code>```

Server:

```<code>handleConnection
writing data
reading data
"Attempted to read 6 bytes, got 0 bytes"
Calling waitForReadyRead
"Attempted to read 6 bytes, got 6 bytes"
readData = "test c"
</code>```

And with SSL:

CLient:

```<code>qt.network.ssl: QSslSocket: cannot resolve SSLv2_client_method
qt.network.ssl: QSslSocket: cannot resolve SSLv2_server_method
client connected
writing data
reading data
"Attempted to read 6 bytes, got 6 bytes"
readData = "test s"
</code>```

Server:

```<code>qt.network.ssl: QSslSocket: cannot resolve SSLv2_client_method
qt.network.ssl: QSslSocket: cannot resolve SSLv2_server_method
waiting for encrypted
server encrypted
handleConnection
writing data
reading data
"Attempted to read 6 bytes, got 0 bytes"
Calling waitForReadyRead
waitForReadyRead failed
terminate called after throwing an instance of 'std::runtime_error'
  what():  Network operation timed out
</code>```

EDIT: Also, if I ignore the return value of waitForReadyRead(), read() still keeps returning 0, even though I definitely wrote 6 bytes to the other end of the connection.

答:
Because you are not using sockets asynchronously with signals and slots you have to select which side writes first and blocks in waitForBytesWritten and then blocks in read until data received. And the other side does the same things in opposite order.

Server:

```<code>void handleConnection(QAbstractSocket* s)
{
    qDebug()<<__FUNCTION__;
    QByteArray data = "test s";
    qDebug()<<"writing data";
    writeWrapper(*s, data);
    s->waitForBytesWritten(3000);
    qDebug()<<"reading data";
    auto readData = readWrapper(*s, 6);
    dumpvar(readData);
    s->disconnectFromHost();
    s->waitForDisconnected();
}
</code>```

Client:

```<code>void handleConnection(QAbstractSocket& s)
{
    QByteArray data = "test c";
    qDebug()<<"reading data";
    auto readData = readWrapper(s, 6);
    dumpvar(readData);
    qDebug()<<"writing data";
    writeWrapper(s, data);
    s.waitForBytesWritten(3000);
    s.disconnectFromHost();
    s.waitForDisconnected();
}
</code>```

Server output:

```<code>qt.network.ssl: QSslSocket: cannot resolve SSLv2_client_method
qt.network.ssl: QSslSocket: cannot resolve SSLv2_server_method
waiting for encrypted
server encrypted
handleConnection
writing data
reading data
"Attempted to read 6 bytes, got 0 bytes"
Calling waitForReadyRead
"Attempted to read 6 bytes, got 6 bytes"
readData = "test c"
qt.network.ssl: QSslSocket::waitForDisconnected() is not allowed in UnconnectedState
</code>```

Client output:

```<code>qt.network.ssl: QSslSocket: cannot resolve SSLv2_client_method
qt.network.ssl: QSslSocket: cannot resolve SSLv2_server_method
client connected
reading data
"Attempted to read 6 bytes, got 6 bytes"
readData = "test s"
writing data
Press <RETURN> to close this window...
</code>```

Body:
Here's a pair of simple client and server apps that try to communicate over QTcpSocket or QSslSocket and send each other a few bytes of data. It seems to work over TCP, but when I attempt to use SSL, the read always times out on the server's side. Please tell me what I'm doing wrong.

Here's my full code:

Client:

#include <QTcpSocket>
#include <QSslSocket>
#include <QTimer>
#include <QApplication>

#define dumpvar(x) qDebug()<<#x<<'='<<x

// reads exactly len bytes from d into data,
// blocks until data is available
// or throws std::runtime_error on error or timeout
// timeout_msec = -1 means no timeout
void readWrapper(QIODevice &d, void *data, qint64 len, int timeout_msec)
{
    QTimer t;
    t.setSingleShot(true);
    // note: inactive timer's remainingTime() returns -1
    if (timeout_msec >= 0) t.start(timeout_msec);
    qint64 bytesRead = 0;
    auto dataPtr = (char*)data;
    while (bytesRead < len){
        auto bytesNeeded = len - bytesRead;
        auto ret = d.read(dataPtr, bytesNeeded);
        if (ret == -1){
            throw std::runtime_error(d.errorString().toStdString());
        }
        qDebug()<<QString("Attempted to read %1 bytes, got %2 bytes")
                  .arg(bytesNeeded)
                  .arg(ret);
        if (ret == 0) {
            qDebug("Calling waitForReadyRead");
            bool ret = d.waitForReadyRead(t.remainingTime());
            if (!ret){
                qDebug()<<"waitForReadyRead failed";
                throw std::runtime_error(d.errorString().toStdString());
            }
        }
        else {
            bytesRead += ret;
            dataPtr += ret;
        }
        if (t.remainingTime() == 0)
            throw std::runtime_error("blockingRead timeout");
    }
}

QByteArray readWrapper(QIODevice &d, qint64 len, int timeout_msec = 10000)
{
    QByteArray ret;
    ret.resize(len);
    readWrapper(d, ret.data(), len, timeout_msec);
    return ret;
}

void writeWrapper(QIODevice &d, void *data, qint64 len)
{
    auto ret = d.write((char*)data, len);
    if (ret < len){
        throw std::runtime_error(QString("error writing data: %1")
                                 .arg(d.errorString())
                                 .toStdString());
    }
}

void writeWrapper(QIODevice &d, const QByteArray &data)
{
    writeWrapper(d, (void*)data.data(), data.size());
}

using namespace std;

void handleConnection(QAbstractSocket& s)
{
    QByteArray data = "test c";
    qDebug()<<"writing data";
    writeWrapper(s, data);
    qDebug()<<"reading data";
    auto readData = readWrapper(s, 6);
    dumpvar(readData);
    s.disconnectFromHost();
    s.waitForDisconnected();
}

void tcpclient()
{
    QTcpSocket s;
    s.connectToHost("localhost", 1234);
    if(!s.waitForConnected(-1)){
        qDebug()<<s.errorString();
        return;
    }

    qDebug()<<"client connected";
    handleConnection(s);
}

void sslclient()
{
    QSslSocket s;
    auto cert = QSslCertificate::fromPath("/home/piotrek/cert.pem");
    Q_ASSERT(!cert.isEmpty());
    s.setCaCertificates({cert});
    s.ignoreSslErrors({{QSslError::HostNameMismatch, cert[0]}});
    s.connectToHostEncrypted("localhost", 1234);
    if (!s.waitForEncrypted(10000)){
        dumpvar(s.errorString());
        dumpvar(s.sslErrors());
        return;
    }

    qDebug()<<"client connected";
    handleConnection(s);
}

int main(int argc, char** argv)
{
    QCoreApplication a(argc, argv);

//  tcpclient();
    sslclient();

}

Server:

#include <QTcpSocket>
#include <QSslSocket>
#include <QTimer>
#include <QCoreApplication>
#include <QTcpServer>
#include <QSslKey>

#define dumpvar(x) qDebug()<<#x<<'='<<x

// reads exactly len bytes from d into data,
// blocks until data is available
// or throws std::runtime_error on error or timeout
// timeout_msec = -1 means no timeout
void readWrapper(QIODevice &d, void *data, qint64 len, int timeout_msec)
{
    QTimer t;
    t.setSingleShot(true);
    // note: inactive timer's remainingTime() returns -1
    if (timeout_msec >= 0) t.start(timeout_msec);
    qint64 bytesRead = 0;
    auto dataPtr = (char*)data;
    while (bytesRead < len){
        auto bytesNeeded = len - bytesRead;
        auto ret = d.read(dataPtr, bytesNeeded);
        if (ret == -1){
            throw std::runtime_error(d.errorString().toStdString());
        }
        qDebug()<<QString("Attempted to read %1 bytes, got %2 bytes")
                  .arg(bytesNeeded)
                  .arg(ret);
        if (ret == 0) {
            qDebug("Calling waitForReadyRead");
            bool ret = d.waitForReadyRead(t.remainingTime());
            if (!ret){
                qDebug()<<"waitForReadyRead failed";
                throw std::runtime_error(d.errorString().toStdString());
            }
        }
        else {
            bytesRead += ret;
            dataPtr += ret;
        }
        if (t.remainingTime() == 0)
            throw std::runtime_error("blockingRead timeout");
    }
}

QByteArray readWrapper(QIODevice &d, qint64 len, int timeout_msec = 10000)
{
    QByteArray ret;
    ret.resize(len);
    readWrapper(d, ret.data(), len, timeout_msec);
    return ret;
}

void writeWrapper(QIODevice &d, void *data, qint64 len)
{
    auto ret = d.write((char*)data, len);
    if (ret < len){
        throw std::runtime_error(QString("error writing data: %1")
                                 .arg(d.errorString())
                                 .toStdString());
    }
}

void writeWrapper(QIODevice &d, const QByteArray &data)
{
    writeWrapper(d, (void*)data.data(), data.size());
}

void handleConnection(QAbstractSocket* s)
{
    qDebug()<<__FUNCTION__;
    QByteArray data = "test s";
    qDebug()<<"writing data";
    writeWrapper(*s, data);
    qDebug()<<"reading data";
    auto readData = readWrapper(*s, 6);
    dumpvar(readData);
    s->disconnectFromHost();
    s->waitForDisconnected();
}

class SslServer: public QTcpServer
{
    // QTcpServer interface
protected:
    void incomingConnection(qintptr handle) override
    {
        QSslSocket s;
        if (!s.setSocketDescriptor(handle)){
            dumpvar(s.errorString());
            return;
        }

        s.setLocalCertificate("/home/piotrek/cert.pem");
        Q_ASSERT(!s.localCertificate().isNull());
        s.setPrivateKey("/home/piotrek/key.pem", QSsl::Rsa, QSsl::Pem, "test"); // last argument is private key decryption password
        Q_ASSERT(!s.privateKey().isNull());
        s.startServerEncryption();
        qDebug()<<"waiting for encrypted";
        if(!s.waitForEncrypted(10000)){
            dumpvar(s.errorString());
            dumpvar(s.sslErrors());
            return;
        }

        qDebug()<<"server encrypted";

        handleConnection(&s);
    }
};

void tcpserver()
{
    QTcpServer *s = new QTcpServer;
    QObject::connect(s, &QTcpServer::newConnection, [s]{
        handleConnection(s->nextPendingConnection());
    });

    s->listen(QHostAddress::Any, 1234);
}

void sslserver()
{
    auto s = new SslServer;
    s->listen(QHostAddress::Any, 1234);
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

//  tcpserver();
    sslserver();

    return a.exec();
}

Command used to generate self-signed cert:

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365

Here's the output on TCP:

Client:

client connected
writing data
reading data
"Attempted to read 6 bytes, got 0 bytes"
Calling waitForReadyRead
"Attempted to read 6 bytes, got 6 bytes"
readData = "test s"
QAbstractSocket::waitForDisconnected() is not allowed in UnconnectedState

Server:

handleConnection
writing data
reading data
"Attempted to read 6 bytes, got 0 bytes"
Calling waitForReadyRead
"Attempted to read 6 bytes, got 6 bytes"
readData = "test c"

And with SSL:

CLient:

qt.network.ssl: QSslSocket: cannot resolve SSLv2_client_method
qt.network.ssl: QSslSocket: cannot resolve SSLv2_server_method
client connected
writing data
reading data
"Attempted to read 6 bytes, got 6 bytes"
readData = "test s"

Server:

qt.network.ssl: QSslSocket: cannot resolve SSLv2_client_method
qt.network.ssl: QSslSocket: cannot resolve SSLv2_server_method
waiting for encrypted
server encrypted
handleConnection
writing data
reading data
"Attempted to read 6 bytes, got 0 bytes"
Calling waitForReadyRead
waitForReadyRead failed
terminate called after throwing an instance of 'std::runtime_error'
  what():  Network operation timed out

EDIT: Also, if I ignore the return value of waitForReadyRead(), read() still keeps returning 0, even though I definitely wrote 6 bytes to the other end of the connection.

Body:
Because you are not using sockets asynchronously with signals and slots you have to select which side writes first and blocks in waitForBytesWritten and then blocks in read until data received. And the other side does the same things in opposite order.

Server:

void handleConnection(QAbstractSocket* s)
{
    qDebug()<<__FUNCTION__;
    QByteArray data = "test s";
    qDebug()<<"writing data";
    writeWrapper(*s, data);
    s->waitForBytesWritten(3000);
    qDebug()<<"reading data";
    auto readData = readWrapper(*s, 6);
    dumpvar(readData);
    s->disconnectFromHost();
    s->waitForDisconnected();
}

Client:

void handleConnection(QAbstractSocket& s)
{
    QByteArray data = "test c";
    qDebug()<<"reading data";
    auto readData = readWrapper(s, 6);
    dumpvar(readData);
    qDebug()<<"writing data";
    writeWrapper(s, data);
    s.waitForBytesWritten(3000);
    s.disconnectFromHost();
    s.waitForDisconnected();
}

Server output:

qt.network.ssl: QSslSocket: cannot resolve SSLv2_client_method
qt.network.ssl: QSslSocket: cannot resolve SSLv2_server_method
waiting for encrypted
server encrypted
handleConnection
writing data
reading data
"Attempted to read 6 bytes, got 0 bytes"
Calling waitForReadyRead
"Attempted to read 6 bytes, got 6 bytes"
readData = "test c"
qt.network.ssl: QSslSocket::waitForDisconnected() is not allowed in UnconnectedState

Client output:

qt.network.ssl: QSslSocket: cannot resolve SSLv2_client_method
qt.network.ssl: QSslSocket: cannot resolve SSLv2_server_method
client connected
reading data
"Attempted to read 6 bytes, got 6 bytes"
readData = "test s"
writing data
Press <RETURN> to close this window...


问:
SqlAlchemy - Filtering by Relationship Attribute
I don't have much experience with SQLAlchemy and I have a problem, which I can't solve. I tried searching and I tried a lot of code.
This is my Class (reduced to the most significant code):

```<code>class Patient(Base):
    __tablename__ = 'patients'
    id = Column(Integer, primary_key=True, nullable=False)
    mother_id = Column(Integer, ForeignKey('patients.id'), index=True)
    mother = relationship('Patient', primaryjoin='Patient.id==Patient.mother_id', remote_side='Patient.id', uselist=False)
    phenoscore = Column(Float)
</code>```

and I would like to query all patients, whose mother's phenoscore is (for example) == 10

As told, I tried a lot of code, but I don't get it. The logically solution, in my eyes, would be

```<code>patients = Patient.query.filter(Patient.mother.phenoscore == 10)
</code>```

because, you can access .mother.phenoscore for each element when outputting but, this code doesn't do it.

Is there a (direct) possibility to filter by an attribute of a relationship (without writing the SQL Statement, or an extra join-statement), I need this kind of filter more than one time.

Even if there is no easy solution, I am happy to get all answers.

答:
Good news for you: I recently made package that gives you filtering/sorting with "magical" strings as in Django, so you can now write something like

```<code>Patient.where(mother___phenoscore=10)
</code>```

It's a lot shorter, especially for complex filters, say,

```<code>Comment.where(post___public=True, post___user___name__like='Bi%')
</code>```

Hope you will enjoy this package

https://github.com/absent1706/sqlalchemy-mixins#django-like-queries

Body:
I don't have much experience with SQLAlchemy and I have a problem, which I can't solve. I tried searching and I tried a lot of code.
This is my Class (reduced to the most significant code):

class Patient(Base):
    __tablename__ = 'patients'
    id = Column(Integer, primary_key=True, nullable=False)
    mother_id = Column(Integer, ForeignKey('patients.id'), index=True)
    mother = relationship('Patient', primaryjoin='Patient.id==Patient.mother_id', remote_side='Patient.id', uselist=False)
    phenoscore = Column(Float)

and I would like to query all patients, whose mother's phenoscore is (for example) == 10

As told, I tried a lot of code, but I don't get it. The logically solution, in my eyes, would be

patients = Patient.query.filter(Patient.mother.phenoscore == 10)

because, you can access .mother.phenoscore for each element when outputting but, this code doesn't do it.

Is there a (direct) possibility to filter by an attribute of a relationship (without writing the SQL Statement, or an extra join-statement), I need this kind of filter more than one time.

Even if there is no easy solution, I am happy to get all answers.

Body:
Good news for you: I recently made package that gives you filtering/sorting with "magical" strings as in Django, so you can now write something like

Patient.where(mother___phenoscore=10)

It's a lot shorter, especially for complex filters, say,

Comment.where(post___public=True, post___user___name__like='Bi%')

Hope you will enjoy this package

https://github.com/absent1706/sqlalchemy-mixins#django-like-queries


问:
Grok parse error while parsing multiple line messages
I am trying to figure out grok pattern for parsing multiple messages like exception trace & below is one such log

```<code>2017-03-30 14:57:41 [12345] [qtp1533780180-12] ERROR com.app.XYZ - Exception occurred while processing
java.lang.NullPointerException: null
        at spark.webserver.MatcherFilter.doFilter(MatcherFilter.java:162)
        at spark.webserver.JettyHandler.doHandle(JettyHandler.java:61)
        at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:189)
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
        at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:119)
        at org.eclipse.jetty.server.Server.handle(Server.java:517)
        at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:302)
        at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:242)
        at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:245)
        at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
        at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:75)
        at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceAndRun(ExecuteProduceConsume.java:213)
        at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:147)
        at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:654)
        at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:572)
        at java.lang.Thread.run(Thread.java:745)
</code>```

Here is my logstash.conf

```<code>    input {
  file {
    path => ["/debug.log"]
    codec => multiline {
      # Grok pattern names are valid! :)
      pattern => "^%{TIMESTAMP_ISO8601} "
      negate => true
      what => previous
    }
  }
}

filter {

  mutate {
    gsub => ["message", "r", ""]
  }
  grok {
    match => [ "message", "%{TIMESTAMP_ISO8601:timestamp} \[%{NOTSPACE:uid}\] \[%{NOTSPACE:thread}\] %{LOGLEVEL:loglevel} %{DATA:class}\-%{GREEDYDATA:message}" ]
    overwrite => [ "message" ]
  }
  date {
    match => [ "timestamp" , "yyyy-MM-dd HH:mm:ss" ]
  }
}

output {
  elasticsearch { hosts => localhost }
  stdout { codec => rubydebug }
}
</code>```

This works fine for single line logs parsing but fails in

0] "_grokparsefailure"

for multiline exception traces

Can someone please suggest me the correct filter pattern for parsing multiline logs ?

答:
If you are working with Multiline logs then please use Multiline filter provided by logstash. You first need to distinguish the starting of a new record in multiline filter. From your logs I can see new record is starting with "TIMESTAMP", below is the example usage.

Example usage ::

```<code>filter {
  multiline {
    type => "/debug.log"
    pattern => "^%{TIMESTAMP}"
    what => "previous"
 }
}
</code>```

You can then use Gsub to replace "\n" and "\r" which will be added by multiline filter to your record. After that use Grok.

Body:
I am trying to figure out grok pattern for parsing multiple messages like exception trace & below is one such log

2017-03-30 14:57:41 [12345] [qtp1533780180-12] ERROR com.app.XYZ - Exception occurred while processing
java.lang.NullPointerException: null
        at spark.webserver.MatcherFilter.doFilter(MatcherFilter.java:162)
        at spark.webserver.JettyHandler.doHandle(JettyHandler.java:61)
        at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:189)
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
        at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:119)
        at org.eclipse.jetty.server.Server.handle(Server.java:517)
        at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:302)
        at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:242)
        at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:245)
        at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
        at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:75)
        at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceAndRun(ExecuteProduceConsume.java:213)
        at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:147)
        at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:654)
        at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:572)
        at java.lang.Thread.run(Thread.java:745)

Here is my logstash.conf

    input {
  file {
    path => ["/debug.log"]
    codec => multiline {
      # Grok pattern names are valid! :)
      pattern => "^%{TIMESTAMP_ISO8601} "
      negate => true
      what => previous
    }
  }
}

filter {

  mutate {
    gsub => ["message", "r", ""]
  }
  grok {
    match => [ "message", "%{TIMESTAMP_ISO8601:timestamp} \[%{NOTSPACE:uid}\] \[%{NOTSPACE:thread}\] %{LOGLEVEL:loglevel} %{DATA:class}\-%{GREEDYDATA:message}" ]
    overwrite => [ "message" ]
  }
  date {
    match => [ "timestamp" , "yyyy-MM-dd HH:mm:ss" ]
  }
}

output {
  elasticsearch { hosts => localhost }
  stdout { codec => rubydebug }
}

This works fine for single line logs parsing but fails in

0] "_grokparsefailure"

for multiline exception traces

Can someone please suggest me the correct filter pattern for parsing multiline logs ?

Body:
If you are working with Multiline logs then please use Multiline filter provided by logstash. You first need to distinguish the starting of a new record in multiline filter. From your logs I can see new record is starting with "TIMESTAMP", below is the example usage.

Example usage ::

filter {
  multiline {
    type => "/debug.log"
    pattern => "^%{TIMESTAMP}"
    what => "previous"
 }
}

You can then use Gsub to replace "\n" and "\r" which will be added by multiline filter to your record. After that use Grok.


问:
How to get the time slot of Telerik's Scheduler from client side by the time or date of that time slot
I'm using Telerik's RadScheduler Control with WebService Binding.

I've used RadScheduler with Server Side Binding which has an event called OnTimeSlotCreated which fires every time when a particular time slot creates so that I can access the time slot and get the control (HtmlTableCell Control) to modify it according to the requirement.

But now I'm binding it from client side through WebService which has no such onClientTimeSlotCreated event, also these time slots are not having any identity at client side to access.

Is there any one has encountered such kind of issue or can give some suggestions please go ahead.

I've wasted lot of time on that.

答:
Unfortunately,

There is no easy solution to this and we are not supporting this scenario.

Veronica,
The Telerik Team


问:
linux vm login Using Shellscript
we have cloud virtual machines where we able to login using pem and ppk file through WinSCP & Putty. I am going to write a shell script program to login into these machines.I tried something like but did not work.</p>

```<code>ssh -i ~/ec2.pem ubuntu@12.34.56.78

Permissions 0664 for '/home/cloud-user/house_keeping/conf/ecp.pem' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
bad permissions: ignore key: /home/cloud-user/house_keeping/conf/ecp.pem`enter code here`
Permission denied (publickey,gssapi-keyex,gssapi-with-mic).
</code>```

答:
The problem is

```<code>Permissions 0664 for '/home/cloud-user/house_keeping/conf/ecp.pem' are too open.
</code>```

The manual page for ssh explans the permissions that should be on the private keys:

These files contain sensitive data and should be readable by the user but not accessible by others (read/write/execute).

So you should change the permission to 0600 using

```<code>chmod 600 ~/ec2.pem
</code>```

Title: linux vm login Using Shellscript

Body:
we have cloud virtual machines where we able to login using pem and ppk file through WinSCP & Putty. I am going to write a shell script program to login into these machines.I tried something like but did not work.

ssh -i ~/ec2.pem ubuntu@12.34.56.78

Permissions 0664 for '/home/cloud-user/house_keeping/conf/ecp.pem' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
bad permissions: ignore key: /home/cloud-user/house_keeping/conf/ecp.pem`enter code here`
Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

Body:
The problem is

Permissions 0664 for '/home/cloud-user/house_keeping/conf/ecp.pem' are too open.

The manual page for ssh explans the permissions that should be on the private keys:

These files contain sensitive data and should be readable by the user but not accessible by others (read/write/execute).

So you should change the permission to 0600 using

chmod 600 ~/ec2.pem


问:
I have got an error On SQL query - PHP-SQLWarning: mssql_query(): message: Incorrect syntax near '='. (severity 15)
I am running this php code with sql query but it keeps showing this error and i couldn't find where the mistake is? Can you help please.THANKS IN ADVANCE

Warning: mssql_query(): message: Incorrect syntax near '='. (severity 15)

Warning: mssql_query(): General SQL Server error: Check messages from the SQL Server (severity 15)

Warning: mssql_query(): Query failed

I have this on my user.php

```<code>if(isset($_POST['refresh'])){
    $mssql_real = db_connect_real();
    $sql = "UPDATE TOP(1) click_users_phones SET pin_failed = 0, status = 1, pin_blocked_time = NULL WHERE phone_num = $phone_num";
    mssql_query($sql, $mssql_real);
}
</code>```

I have this on another php file

```<code><form action="user.php" method="post">
    <button class="#" name="refresh">Refresh</button>
</form>
</code>```

答:
Your SQL statement should be like

```<code>UPDATE TOP(1) A SET pin_failed = 0, status = 1, pin_blocked_time = NULL
FROM click_users_phones A WHERE phone_num = ''
</code>```

Note:
But you should remember that SQL never guarantee you the order. So If you are updating the TOP 1 ,then you should provide the ORDER BY in the select. So that you will update the correct record.

Body:
I am running this php code with sql query but it keeps showing this error and i couldn't find where the mistake is? Can you help please.THANKS IN ADVANCE

Warning: mssql_query(): message: Incorrect syntax near '='. (severity 15)

Warning: mssql_query(): General SQL Server error: Check messages from the SQL Server (severity 15)

Warning: mssql_query(): Query failed

I have this on my user.php

if(isset($_POST['refresh'])){
    $mssql_real = db_connect_real();
    $sql = "UPDATE TOP(1) click_users_phones SET pin_failed = 0, status = 1, pin_blocked_time = NULL WHERE phone_num = $phone_num";
    mssql_query($sql, $mssql_real);
}

I have this on another php file

<form action="user.php" method="post">
    <button class="#" name="refresh">Refresh</button>
</form>

Body:
Your SQL statement should be like

UPDATE TOP(1) A SET pin_failed = 0, status = 1, pin_blocked_time = NULL
FROM click_users_phones A WHERE phone_num = ''

Note:
But you should remember that SQL never guarantee you the order. So If you are updating the TOP 1 ,then you should provide the ORDER BY in the select. So that you will update the correct record.


问:
Download a file with AngularJS
I need to provide a link to download a file, the link must be hidden and accessible by any users, Here is my code , there are no errors whatsoever, but I can't even get the download dialog box to open:

Template

```<code> <a ng-href="#" target="page" type="button" class="btn"
ng-click="download()">Download</a>
</code>```

Script file

```<code>$scope.download = function(){
 //here i need to know the code,can anybody explain me
}
</code>```

答:
I had to achieve the functionality. Also had to make sure that it works for all the major supported browsers.
Here's the solution for the same!!!

Happy Coding!!!

Your View/HTML

```<code><a target="_self" class="ui right floated btn btn-warning" href ng-click="downloadInvoice()"> Download </a>
</code>```

Your Controller

```<code>$scope.downloadInvoice = function () {
    $http.post(url,requestData, {responseType:'arraybuffer',headers:header
        })
            .success(function (response) {
                var file = new Blob([response], {type: 'application/pdf'});

                var isChrome = !!window.chrome && !!window.chrome.webstore;
                var isIE = /*@cc_on!@*/false || !!document.documentMode;
                var isEdge = !isIE && !!window.StyleMedia;

                if (isChrome){
                    var url = window.URL || window.webkitURL;

                    var downloadLink = angular.element('<a></a>');
                    downloadLink.attr('href',url.createObjectURL(file));
                    downloadLink.attr('target','_self');
                    downloadLink.attr('download', 'invoice.pdf');
                    downloadLink[0].click();
                }
                else if(isEdge || isIE){
                    window.navigator.msSaveOrOpenBlob(file,'invoice.pdf');

                }
                else {
                    var fileURL = URL.createObjectURL(file);
                    window.open(fileURL);
                }

            })
};
</code>```

Title: Download a file with AngularJS

Body:
I need to provide a link to download a file, the link must be hidden and accessible by any users, Here is my code , there are no errors whatsoever, but I can't even get the download dialog box to open:

Template

 Download

Script file

$scope.download = function(){
 //here i need to know the code,can anybody explain me
}

Body:
I had to achieve the functionality. Also had to make sure that it works for all the major supported browsers.
Here's the solution for the same!!!

Happy Coding!!!

Your View/HTML

<a target="_self" class="ui right floated btn btn-warning" href ng-click="downloadInvoice()"> Download </a>

Your Controller

$scope.downloadInvoice = function () {
    $http.post(url,requestData, {responseType:'arraybuffer',headers:header
        })
            .success(function (response) {
                var file = new Blob([response], {type: 'application/pdf'});

                var isChrome = !!window.chrome && !!window.chrome.webstore;
                var isIE = /*@cc_on!@*/false || !!document.documentMode;
                var isEdge = !isIE && !!window.StyleMedia;

                if (isChrome){
                    var url = window.URL || window.webkitURL;

                    var downloadLink = angular.element('<a></a>');
                    downloadLink.attr('href',url.createObjectURL(file));
                    downloadLink.attr('target','_self');
                    downloadLink.attr('download', 'invoice.pdf');
                    downloadLink[0].click();
                }
                else if(isEdge || isIE){
                    window.navigator.msSaveOrOpenBlob(file,'invoice.pdf');

                }
                else {
                    var fileURL = URL.createObjectURL(file);
                    window.open(fileURL);
                }

            })
};


问:
Is it possible to automate two apps at the same time in iOS?
We have this scenario:

Execute the script in app1, in certain step app1 sends us a SMS with a URL, app1 is expecting a validation code in a textfield

We have to open SMS app to verify if SMS exists, this SMS has a URL and when we click on it, it sends us to app1 again but automatically the validation code is written in the textfield.

then, continue with the script.

is it possible to do this?
what do we need to make it?

Thanks.

答:
Yes, As per your scenario you have to launch the messages(call it as app2) application in the middle of execution of script in app1. You can open the app2 by using below code.

```<code> driver.startActivity(app2PackageName, app2ActivityName);
</code>```

Now app2 will be opened you can click on the link in app2 which will open app1 and you can access the elements in app1.

Body:
Yes, As per your scenario you have to launch the messages(call it as app2) application in the middle of execution of script in app1. You can open the app2 by using below code.

 driver.startActivity(app2PackageName, app2ActivityName);

Now app2 will be opened you can click on the link in app2 which will open app1 and you can access the elements in app1.


问:
Jquery custom trigger anchor tag
Hello every one I am creating custom multistep form but when I click on next button it can't trigger related  anchor tag ( auto click )

Please help me to resolve my issue

Thanks in Advance

$(function() {
  $("#nextBtn").click(function() {
    var $tabs = $("li");
    $tabs.each(function() {

      var activeTab = $(this).hasClass("active");
      if (activeTab == true) {
        //var activeAnch = $(this).children().attr("href");
        alert($(this).next('li').children().attr("href"));
        var nextId = $(this).next('li').children().attr("id");
        //$("#"+nextId).click();// trigger click to #menu 1
      }
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
  <ul class="nav nav-pills">
    <li class="active">Home</li>
    <li>Menu 1</li>
    <li>Menu 2</li>
    <li>Menu 3</li>
  </ul>

  <div class="tab-content">
    <div id="home" class="tab-pane fade in active">
      <h3>HOME</h3>
      <span>Form 1</span>
    </div>
    <div id="menu1" class="tab-pane fade">
      <h3>Menu 1</h3>
      <span>Form 2</span>
    </div>
    <div id="menu2" class="tab-pane fade">
      <h3>Menu 2</h3>
      <span>Form 3</span>
    </div>
    <div id="menu3" class="tab-pane fade">
      <h3>Menu 3</h3>
      <span>Form 4</span>
    </div>
  </div>

  <button id="nextBtn">Next</button>

</body>

</html></code>```

答:
Please use the below code to achieve this.

$(document).ready(function() {
  $("#nextBtn").click(function() {
    $('li.active').next().find('a')[0].click();

    //hide the next button
    $('.nav li a').on('shown.bs.tab', function(e) {
      var $lastEle = $(".nav li:last-child").hasClass('active');
      if ($lastEle) {
        $("#nextBtn").hide();
      }else{
        $("#nextBtn").show();
     }
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>

<body>
  <ul class="nav nav-pills">
    <li class="active">Home</li>
    <li>Menu 1</li>
    <li>Menu 2</li>
    <li>Menu 3</li>
  </ul>

  <div class="tab-content">
    <div id="home" class="tab-pane fade in active">
      <h3>HOME</h3>
      <span>Form 1</span>
    </div>
    <div id="menu1" class="tab-pane fade">
      <h3>Menu 1</h3>
      <span>Form 2</span>
    </div>
    <div id="menu2" class="tab-pane fade">
      <h3>Menu 2</h3>
      <span>Form 3</span>
    </div>
    <div id="menu3" class="tab-pane fade">
      <h3>Menu 3</h3>
      <span>Form 4</span>
    </div>
  </div>

  <button id="nextBtn">Next</button>

</body>

</html></code>```

Title: Jquery custom trigger anchor tag

Body:
Hello every one I am creating custom multistep form but when I click on next button it can't trigger related  anchor tag ( auto click )

Please help me to resolve my issue

Thanks in Advance

$(function() {
  $("#nextBtn").click(function() {
    var $tabs = $("li");
    $tabs.each(function() {

      var activeTab = $(this).hasClass("active");
      if (activeTab == true) {
        //var activeAnch = $(this).children().attr("href");
        alert($(this).next('li').children().attr("href"));
        var nextId = $(this).next('li').children().attr("id");
        //$("#"+nextId).click();// trigger click to #menu 1
      }
    });
  });
});

<!DOCTYPE html>

  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Home

Menu 1

Menu 2

Menu 3

HOME

      Form 1

Menu 1

      Form 2

Menu 2

      Form 3

Menu 3

      Form 4

  <button id="nextBtn">Next</button>

Body:
Please use the below code to achieve this.

$(document).ready(function() {
  $("#nextBtn").click(function() {
    $('li.active').next().find('a')[0].click();

    //hide the next button
    $('.nav li a').on('shown.bs.tab', function(e) {
      var $lastEle = $(".nav li:last-child").hasClass('active');
      if ($lastEle) {
        $("#nextBtn").hide();
      }else{
        $("#nextBtn").show();
     }
    });
  });
});

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>

<body>
  <ul class="nav nav-pills">
    <li class="active"><a data-toggle="pill" href="#home">Home</a></li>
    <li><a data-toggle="pill" href="#menu1">Menu 1</a></li>
    <li><a data-toggle="pill" href="#menu2">Menu 2</a></li>
    <li><a data-toggle="pill" href="#menu3">Menu 3</a></li>
  </ul>

  <div class="tab-content">
    <div id="home" class="tab-pane fade in active">
      <h3>HOME</h3>
      <span>Form 1</span>
    </div>
    <div id="menu1" class="tab-pane fade">
      <h3>Menu 1</h3>
      <span>Form 2</span>
    </div>
    <div id="menu2" class="tab-pane fade">
      <h3>Menu 2</h3>
      <span>Form 3</span>
    </div>
    <div id="menu3" class="tab-pane fade">
      <h3>Menu 3</h3>
      <span>Form 4</span>
    </div>
  </div>

  <button id="nextBtn">Next</button>

</body>

</html>


问:
change iframe source in ie using javascript
I have used an iframe which looks like this:

```<code><iframe style='width: 330px; height: 278px' scrolling='no' name="iframeId" class="advPlayer" id="iframeId" frameborder="0" src='../../player/iabpreview.php?adid=<?php echo $selectedAdIdx ?>&autoPlay=true'></iframe>
</code>```

Whenever I click on a
, I have to change the source of the iframe. I am using the following code:

```<code>if ($j.browser.msie) {
  frames['iframeId'].window.location="../player/iabpreview.php?adid="+adId+"&autoPlay=true";
}else {
  $j(".advPlayer").eq(0).attr("src", "../player/iabpreview.php?adid="+adId+"&autoPlay=true");
}
</code>```

This works with Firefox, but not with Internet Explorer.

What code would work for Internet Explorer too?

答:
You should never user 'browser detection', but feature detection. The most safe way imho is this:

```<code>function SetIFrameSource(cid, url){
  var myframe = document.getElementById(cid);
  if(myframe !== null){
    if(myframe.src){
      myframe.src = url; }
    else if(myframe.contentWindow !== null && myframe.contentWindow.location !== null){
      myframe.contentWindow.location = url; }
    else{
      myframe.setAttribute('src', url);
    }
  }
}
</code>```

Just test if the src property is available. If not, test on content window, and the last try is setAttribute.

OwnerDisplayName: rohini

Body:
I have used an iframe which looks like this:

<iframe style='width: 330px; height: 278px' scrolling='no' name="iframeId" class="advPlayer" id="iframeId" frameborder="0" src='../../player/iabpreview.php?adid=<?php echo $selectedAdIdx ?>&autoPlay=true'>

Whenever I click on a
, I have to change the source of the iframe. I am using the following code:

if ($j.browser.msie) {
  frames['iframeId'].window.location="../player/iabpreview.php?adid="+adId+"&autoPlay=true";
}else {
  $j(".advPlayer").eq(0).attr("src", "../player/iabpreview.php?adid="+adId+"&autoPlay=true");
}

This works with Firefox, but not with Internet Explorer.

What code would work for Internet Explorer too?

Body:
You should never user 'browser detection', but feature detection. The most safe way imho is this:

function SetIFrameSource(cid, url){
  var myframe = document.getElementById(cid);
  if(myframe !== null){
    if(myframe.src){
      myframe.src = url; }
    else if(myframe.contentWindow !== null && myframe.contentWindow.location !== null){
      myframe.contentWindow.location = url; }
    else{
      myframe.setAttribute('src', url);
    }
  }
}

Just test if the src property is available. If not, test on content window, and the last try is setAttribute.


问:
How to change lambda expression to method reference
I need help regarding changing lambda expression to method reference:

lambda expression:

```<code>intervalCodes.stream().forEach(code -> {
            modProfile.addIntervalUsageCode(createIntervalCode(code));
          });
</code>```

Can I change the above expression to like this:

```<code>intervalCodes.stream().forEach(modProfile::addIntervalUsageCode(createIntervalCode));
</code>```

Any suggestions please?

答:
Assuming createIntervalCode() is a side-effect-free instance method, you can split your lambda into two method references:

```<code>intervalCodes.stream()
        .map(this::createIntervalCode)
        .forEach(modProfile::addIntervalUsageCode);
</code>```

If it's a static method, use ClassName::createIntervalCode.

Body:
I need help regarding changing lambda expression to method reference:

lambda expression:

intervalCodes.stream().forEach(code -> {
            modProfile.addIntervalUsageCode(createIntervalCode(code));
          });

Can I change the above expression to like this:

intervalCodes.stream().forEach(modProfile::addIntervalUsageCode(createIntervalCode));

Any suggestions please?

Body:
Assuming createIntervalCode() is a side-effect-free instance method, you can split your lambda into two method references:

intervalCodes.stream()
        .map(this::createIntervalCode)
        .forEach(modProfile::addIntervalUsageCode);

If it's a static method, use ClassName::createIntervalCode.