问:
How to do the monitoring upload status?
Well i haven't been able to solve this, and i really need to get the upload status, when you upload someting using the MultipartUploadRequest, i want to print with a toast or anything else the status that appears on the notification bar.
i've been following these tutorial but i haven't succeed:https://github.com/gotev/android-upload-service/wiki/Monitoring-upload-status

i REALLY appreciate someone to tell why im not able to achieve this please.
here's my code:

```<code> public class CargarDatos extends AsyncTask<String, Void, String> {
    protected String doInBackground(String... urls) {

        ////////////////-------------
        String correo = campo_correo.getText().toString().trim();
        String nombre = campo_nombre.getText().toString().trim();
        String apellido= campo_apellido.getText().toString().trim();
        String telefono= campo_telefono.getText().toString().trim();
        String categoria= customspinner.getSelectedItem().toString().trim();
        String titulo = campo_titulo.getText().toString().trim();
        String descripcion = campo_descripcion.getText().toString().trim();
        String latitud = Double.toString(latitudeeeee);
        String longitud = Double.toString(longitudeeee);

        String s = (campo_publico.isChecked() ? "1" : "0");
        String r = (campo_terminos.isChecked() ? "1" : "0");

        //getting the actual path of the image
        String path = getPath(filePath);

        //Uploading code
        try {
            String uploadId = UUID.randomUUID().toString();

            //Creating a multi part request
            new MultipartUploadRequest(TerminosYC.this.getActivity(), uploadId, Constants.UPLOAD_URL)
                    .addFileToUpload(path, "image") //Adding file
                    .addParameter("name",correo) //Adding text parameter to the request
                    .addParameter("nombre",nombre)
                    .addParameter("apellido",apellido)
                    .addParameter("telefono", telefono)
                    .addParameter("categoria", categoria)
                    .addParameter("titulo", titulo)
                    .addParameter("descripcion", descripcion)
                    .addParameter("publico", s)
                    .addParameter("terminos", r)
                    .addParameter("latitud",latitud)
                    .addParameter("longitud",longitud)
                    .setNotificationConfig(new UploadNotificationConfig())
                    .setMaxRetries(2)
                    .startUpload(); //Starting the upload

        } catch (Exception exc) {
            Toast.makeText(TerminosYC.this.getActivity(), exc.getMessage(), Toast.LENGTH_SHORT).show();

        }

        // params comes from the execute() call: params[0] is the url.
        try {
            return downloadUrl(urls[0]);
        } catch (IOException e) {
            return "Unable to retrieve web page. URL may be invalid.";
        }
    }
</code>```

答:
best way for debug use Stetho facebook

link

Title: How to do the monitoring upload status?

Body:
Well i haven't been able to solve this, and i really need to get the upload status, when you upload someting using the MultipartUploadRequest, i want to print with a toast or anything else the status that appears on the notification bar.
i've been following these tutorial but i haven't succeed:https://github.com/gotev/android-upload-service/wiki/Monitoring-upload-status

i REALLY appreciate someone to tell why im not able to achieve this please.
here's my code:

 public class CargarDatos extends AsyncTask<String, Void, String> {
    protected String doInBackground(String... urls) {

        ////////////////-------------
        String correo = campo_correo.getText().toString().trim();
        String nombre = campo_nombre.getText().toString().trim();
        String apellido= campo_apellido.getText().toString().trim();
        String telefono= campo_telefono.getText().toString().trim();
        String categoria= customspinner.getSelectedItem().toString().trim();
        String titulo = campo_titulo.getText().toString().trim();
        String descripcion = campo_descripcion.getText().toString().trim();
        String latitud = Double.toString(latitudeeeee);
        String longitud = Double.toString(longitudeeee);

        String s = (campo_publico.isChecked() ? "1" : "0");
        String r = (campo_terminos.isChecked() ? "1" : "0");

        //getting the actual path of the image
        String path = getPath(filePath);

        //Uploading code
        try {
            String uploadId = UUID.randomUUID().toString();

            //Creating a multi part request
            new MultipartUploadRequest(TerminosYC.this.getActivity(), uploadId, Constants.UPLOAD_URL)
                    .addFileToUpload(path, "image") //Adding file
                    .addParameter("name",correo) //Adding text parameter to the request
                    .addParameter("nombre",nombre)
                    .addParameter("apellido",apellido)
                    .addParameter("telefono", telefono)
                    .addParameter("categoria", categoria)
                    .addParameter("titulo", titulo)
                    .addParameter("descripcion", descripcion)
                    .addParameter("publico", s)
                    .addParameter("terminos", r)
                    .addParameter("latitud",latitud)
                    .addParameter("longitud",longitud)
                    .setNotificationConfig(new UploadNotificationConfig())
                    .setMaxRetries(2)
                    .startUpload(); //Starting the upload

        } catch (Exception exc) {
            Toast.makeText(TerminosYC.this.getActivity(), exc.getMessage(), Toast.LENGTH_SHORT).show();

        }

        // params comes from the execute() call: params[0] is the url.
        try {
            return downloadUrl(urls[0]);
        } catch (IOException e) {
            return "Unable to retrieve web page. URL may be invalid.";
        }
    }


来源: stackexchange

问:
Jquery document.ready is not responding
The document.ready function is not responding while my page load.
And also i am facing problem with .submit function. Please help.
Please help me to rewrite this code.
I just want to design a form in php to check whether the given email id is already present in the database or not using jquery ajax
Please help .... ! I am getting late in my school project.

```<code> $(document).ready(function(){
                alert("Working..");
                $("#userSubmit").submit(function(){
                    alert("Working ..");
                    var email=document.getElementById("userEamil").value;
                    $.ajax({
                        type:'POST',
                        data:"SELECT * FROM user WHERE userEmail='"+email+"'",
                        url:'common1.php',
                        success:function(data)
                        {
                            $result=$.parseJSON($data);
                            alert($result);
                            return false;
                        },
                        error:function(data)
                        {
                            alert(data);
                            return false;
                        }
                    });
                });
            });
</code>```

答:
You have some error in your code, i hope following code will do the work. and for further problem please check the $.ajax portion.

$(document).ready(function() {
        // alert("Working..");
        $("#userSubmit").submit(function(event) {
            event.preventDefault();
            alert("Working ..");
            var email = document.getElementById("#userEamil").value;
            $.ajax({
                type: 'POST',
                data: "SELECT * FROM user WHERE userEmail='" + email + "'",
                url: 'common1.php',
                success: function(data) {
                    $result = $.parseJSON($data);
                    alert($result);
                    return false;
                },
                error: function(data) {
                    alert(data);
                    return false;
                }
            });
        });
    });

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="userSubmit" action="">
            <input type="email">
            <input type="submit" value="submit">
        </form></code>```

<form action="">
    <input type="email" >
    <input id="userSubmit" type="submit" value="submit">
</form>
```

ContentLicense: CC BY-SA 3.0

Title: Jquery document.ready is not responding

Body:
The document.ready function is not responding while my page load.
And also i am facing problem with .submit function. Please help.
Please help me to rewrite this code.
I just want to design a form in php to check whether the given email id is already present in the database or not using jquery ajax
Please help .... ! I am getting late in my school project.

 $(document).ready(function(){
                alert("Working..");
                $("#userSubmit").submit(function(){
                    alert("Working ..");
                    var email=document.getElementById("userEamil").value;
                    $.ajax({
                        type:'POST',
                        data:"SELECT * FROM user WHERE userEmail='"+email+"'",
                        url:'common1.php',
                        success:function(data)
                        {
                            $result=$.parseJSON($data);
                            alert($result);
                            return false;
                        },
                        error:function(data)
                        {
                            alert(data);
                            return false;
                        }
                    });
                });
            });

Body:
You have some error in your code, i hope following code will do the work. and for further problem please check the $.ajax portion.

$(document).ready(function() {
        // alert("Working..");
        $("#userSubmit").submit(function(event) {
            event.preventDefault();
            alert("Working ..");
            var email = document.getElementById("#userEamil").value;
            $.ajax({
                type: 'POST',
                data: "SELECT * FROM user WHERE userEmail='" + email + "'",
                url: 'common1.php',
                success: function(data) {
                    $result = $.parseJSON($data);
                    alert($result);
                    return false;
                },
                error: function(data) {
                    alert(data);
                    return false;
                }
            });
        });
    });

<!-- begin snippet: js hide: false console: true babel: false -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="userSubmit" action="">
            <input type="email">
            <input type="submit" value="submit">
        </form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
    <input type="email" >
    <input id="userSubmit" type="submit" value="submit">
</form>


问:
Zend_Session / Zend_Auth randomly throws Error Message ps_files_cleanup_dir: opendir(/var/lib/php5) failed: Permission denied (13)
I'm currently working on a new Application using (among other things) Zend_Auth but, for whatever reason, this Error Message is showing up at any location totally randomly (or so it seams)

Zend_Session::start() - /home/hannes/workspace/develop/library/Zend/Session.php(Line:480): Error #8 session_start() [function.session-start]: ps_files_cleanup_dir: opendir(/var/lib/php5) failed: Permission denied (13) Array

#0 /home/hannes/workspace/develop/library/Zend/Session/Namespace.php(143): Zend_Session::start(true)

#1 /home/hannes/workspace/develop/library/Zend/Auth/Storage/Session.php(87): Zend_Session_Namespace->__construct('Zend_Auth')

#2 /home/hannes/workspace/develop/library/Zend/Auth.php(91): Zend_Auth_Storage_Session->__construct()

#3 /home/hannes/workspace/develop/library/Zend/Auth.php(141): Zend_Auth->getStorage()

#4 /home/hannes/workspace/develop/xxxxxxx/application/controllers/AdminController.php(10): Zend_Auth->hasIdentity()

#5 /home/hannes/workspace/develop/library/Zend/Controller/Action.php(133): AdminController->init()

#6 /home/hannes/workspace/develop/library/Zend/Controller/Dispatcher/Standard.php(262): Zend_Controller_Action->__construct(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http), Array)

#7 /home/hannes/workspace/develop/library/Zend/Controller/Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))

#8 /home/hannes/workspace/develop/library/Zend/Application/Bootstrap/Bootstrap.php(97): Zend_Controller_Front->dispatch()

#9 /home/hannes/workspace/develop/library/Zend/Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()

#10 /home/hannes/workspace/develop/xxxxxxx/public/index.php(26): Zend_Application->run()

#11 {main}

答:
A solution is to set the session.save_path in the php.ini file to a writable directory.
for example: session.save_path = "/tmp".
Switching the session garbage collection off in the first example is not a good idea. The second example does not work on Ubuntu 10.04</p>

ContentLicense: CC BY-SA 2.5


问:
return character in fuction
I have some basic question about the pointers, I have a char array and I am extracting some words my char array with using function  and I want to return value and print it main I have Code But it's not working, thanks for your help</p>

```<code> #include <stdio.h>
#include <stdlib.h>
#include <string.h>
    char cumle[30];
char kelimecikart(char *cumle,char *sozcuk);
int main(){
    int i;
    char sozcuk[30];
    printf("sentence:\n");
    gets(cumle);
    puts(cumle);

    printf("What is the word you want to extract of:\n");
    gets(sozcuk);
    puts(sozcuk);
    printf("\n");

    cumle[0]=kelimecikart(cumle,sozcuk);
    for(i=0;i<17;i++){

        printf("%c",cumle[i]);
    }
}
char kelimecikart(char *dizi,char *cikansoz)
{
    int a = strlen(dizi);
    int b = strlen(cikansoz);

    int i,j,tmp=0;
    for(i=0;i<a;i++){
        for(j=0;j<b;j++){
            if(*(dizi+i+j)==*(cikansoz+j)){
                tmp++;
            }
            else{
                break;
            }
            }
            if(tmp==b){
                i+=tmp-1;
            }
            else{
                *(cumle+i)=*(dizi+i);
            }
            tmp=0;
    }

    return *cumle;
}
</code>```

答:
```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
    char cumle[30];
void kelimecikart(char *cumle,char *sozcuk);
int main(){
    int i;
    char sozcuk[30];
    printf("sentence:\n");
    gets(cumle);
    puts(cumle);

    printf("What is the word you want to extract of:\n");
    gets(sozcuk);
    puts(sozcuk);
    printf("\n");

    kelimecikart(cumle,sozcuk);
    for(i=0;i<17;i++){

        printf("%c",cumle[i]);
    }
}
void kelimecikart(char *dizi,char *cikansoz)
{
    int a = strlen(dizi);
    int b = strlen(cikansoz);
    int i,j=1;
    for(i=0;i<a;){
        if(j==0){
            i++;
        }
        else if(j==b){
            break;
        }
        for(j=0;j<b;j++){
            if(dizi[i]==cikansoz[j]){
                i++;

            }
            else{
                break;
            }

        }
    }

    for(;i<a;i++){
        dizi[i-b]=dizi[i];

    }

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

Title: return character in fuction

Body:
I have some basic question about the pointers, I have a char array and I am extracting some words my char array with using function  and I want to return value and print it main I have Code But it's not working, thanks for your help

 #include <stdio.h>
#include <stdlib.h>
#include <string.h>
    char cumle[30];
char kelimecikart(char *cumle,char *sozcuk);
int main(){
    int i;
    char sozcuk[30];
    printf("sentence:\n");
    gets(cumle);
    puts(cumle);

    printf("What is the word you want to extract of:\n");
    gets(sozcuk);
    puts(sozcuk);
    printf("\n");

    cumle[0]=kelimecikart(cumle,sozcuk);
    for(i=0;i<17;i++){

        printf("%c",cumle[i]);
    }
}
char kelimecikart(char *dizi,char *cikansoz)
{
    int a = strlen(dizi);
    int b = strlen(cikansoz);

    int i,j,tmp=0;
    for(i=0;i<a;i++){
        for(j=0;j<b;j++){
            if(*(dizi+i+j)==*(cikansoz+j)){
                tmp++;
            }
            else{
                break;
            }
            }
            if(tmp==b){
                i+=tmp-1;
            }
            else{
                *(cumle+i)=*(dizi+i);
            }
            tmp=0;
    }

    return *cumle;
}


问:
Using custom styling for jQuery unobstrusive validation .NET MVC 5
I have a HTML markup like this:

```<code>  <div class="col-sm-6">
        <div class="main-contact">
            <form id="registerForm">
                @Html.TextBoxFor(model=>model.FirstName, new { @placeholder="First Name" })
                @Html.ValidationMessageFor(model=>model.FirstName)
                @Html.TextBoxFor(model => model.LastName, new { @placeholder = "Last Name" })
                @Html.ValidationMessageFor(model => model.LastName)
                @Html.TextBoxFor(model => model.Email, new { @placeholder = "Email" })
                @Html.ValidationMessageFor(model => model.Email)
                @Html.TextBoxFor(model => model.Password, new { @placeholder = "Password" })
                @Html.ValidationMessageFor(model => model.Password)
                @Html.TextBoxFor(model => model.RepeatPassword, new { @placeholder = "Repeat Password" })
                @Html.ValidationMessageFor(model => model.RepeatPassword)
                @Html.DropDownListFor(model => model.selectedCountryId, Model.Countries, "-- Select a country --")
                @Html.ValidationMessageFor(model => model.selectedCountryId)

                <button type="submit">Send message</button>
            </form>
        </div>
    </div>
</code>```

And using these libraries to activate jQuery's unobstrusive validation:

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>
</code>```

And now I'm trying to add some style to the textboxes themselves and validation messages when the form is not valid... ?

I'd like to use the bootstrap's default way of displaying the messages and adding the red glow around the textbox itself... Or maybe if some of you guys have some custom css that wanna share here ?

How can I apply the default bootstrap styling to this now or add some custom one ?

答:
add Reference to below CDN's and modify your form to use bootstrap classes to change the UI look.

```<code>!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</code>```

something like this,

```<code> <div class="form-group">
        @Html.LabelFor(m => m.Name)
        @Html.TextBoxFor(m => m.Name, new { @class = "form-control"})
        @Html.ValidationMessageFor(m => m.Name)
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Description)
        @Html.TextAreaFor(m => m.Description, new { @class = "form-control", placeholder = "eg: details about the deal..." })
        @Html.ValidationMessageFor(m => m.Description)
    </div>
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</code>```

Here form-group, form-control classes are from Bootstrap

Also you can refer to this link to see what classes you need to use for different form elements

Body:
I have a HTML markup like this:

            <form id="registerForm">
                @Html.TextBoxFor(model=>model.FirstName, new { @placeholder="First Name" })
                @Html.ValidationMessageFor(model=>model.FirstName)
                @Html.TextBoxFor(model => model.LastName, new { @placeholder = "Last Name" })
                @Html.ValidationMessageFor(model => model.LastName)
                @Html.TextBoxFor(model => model.Email, new { @placeholder = "Email" })
                @Html.ValidationMessageFor(model => model.Email)
                @Html.TextBoxFor(model => model.Password, new { @placeholder = "Password" })
                @Html.ValidationMessageFor(model => model.Password)
                @Html.TextBoxFor(model => model.RepeatPassword, new { @placeholder = "Repeat Password" })
                @Html.ValidationMessageFor(model => model.RepeatPassword)
                @Html.DropDownListFor(model => model.selectedCountryId, Model.Countries, "-- Select a country --")
                @Html.ValidationMessageFor(model => model.selectedCountryId)

                <button type="submit">Send message</button>
            </form>

And using these libraries to activate jQuery's unobstrusive validation:

And now I'm trying to add some style to the textboxes themselves and validation messages when the form is not valid... ?

I'd like to use the bootstrap's default way of displaying the messages and adding the red glow around the textbox itself... Or maybe if some of you guys have some custom css that wanna share here ?

How can I apply the default bootstrap styling to this now or add some custom one ?

Body:
add Reference to below CDN's and modify your form to use bootstrap classes to change the UI look.

!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

something like this,

 <div class="form-group">
        @Html.LabelFor(m => m.Name)
        @Html.TextBoxFor(m => m.Name, new { @class = "form-control"})
        @Html.ValidationMessageFor(m => m.Name)
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Description)
        @Html.TextAreaFor(m => m.Description, new { @class = "form-control", placeholder = "eg: details about the deal..." })
        @Html.ValidationMessageFor(m => m.Description)
    </div>
<button type="submit" class="btn btn-primary btn-lg">Submit</button>

Here form-group, form-control classes are from Bootstrap

Also you can refer to this link to see what classes you need to use for different form elements


问:
Extract Text between HTML tags with sed or grep
I have a Problem. I want to get two parts of this html in values with the sed or grep command. How i can extract both of them?

test.html:

```<code><html>
 <body>
  <div id="foo" class="foo">
   Some Text.
    <p id="author" class="author">
     <br>
     <a href="example.com">bar</a>
    </p>
  </div>
 </body>
</html>
</code>```

script.sh

```<code>#!/bin/bash

author=$(sed 's/.*<p id="author" class="author"><br><a href="*">\(.*\)<\/a><\/p>.*/\1/p' test.html)
quote=$(sed 's/.*<div id="foo" class="foo">\(.*\)<\/div>.*/\1/p' test.html)
</code>```

Under the line i want only the text in the values. without the html tags.
But my script doesent works..

答:
You can use xmllint to parse html/xml text and extract values for defined xpath.

Here is the working example:

```<code>#!/bin/bash

author=$(xmllint --html --xpath '//div[@class="foo"]/text()' test.html | tr -d '\n' | sed -e "s/ //g")
quote=$(xmllint --html --xpath '//a/text()' test.html | sed -e "s/ //g")
echo "Author:'$author'"
echo "Quote:'$quote'"
</code>```

xpath defines xml node path from which text needs to be extracted.

tr is used remove new-line characters.

sed is used to trim string from extracted text value.

Body:
I have a Problem. I want to get two parts of this html in values with the sed or grep command. How i can extract both of them?

test.html:

   Some Text.

     bar

script.sh

#!/bin/bash

author=$(sed 's/.*

\(.*\)<\/a><\/p>.*/\1/p' test.html)
quote=$(sed 's/.*
\(.*\)<\/div>.*/\1/p' test.html)

Under the line i want only the text in the values. without the html tags.
But my script doesent works..

Body:
You can use xmllint to parse html/xml text and extract values for defined xpath.

Here is the working example:

#!/bin/bash

author=$(xmllint --html --xpath '//div[@class="foo"]/text()' test.html | tr -d '\n' | sed -e "s/ //g")
quote=$(xmllint --html --xpath '//a/text()' test.html | sed -e "s/ //g")
echo "Author:'$author'"
echo "Quote:'$quote'"

xpath defines xml node path from which text needs to be extracted.

tr is used remove new-line characters.

sed is used to trim string from extracted text value.


问:
Need assistance to remove outdated =* join operator from SQL 2005 query
Following query no longer compatible in SQL2012 and above. Need assistance to convert.</p>

```<code>select distinct po.name , sc.name, sc2.name
from sysobjects fo, sysobjects po, sysforeignkeys fk, sysobjects oo
    , syscolumns sc, sysreferences ref, syscolumns sc2
where fo.xtype = 'F' and oo.name = @tab_name
  and po.id = fo.parent_obj and fo.id = fk.constid and oo.id = fk.rkeyid
  and sc.id = po.id and ref.constid = fk.constid and sc.colid = ref.fkey1
  and sc2.id =* po.id and sc2.colid =* ref.fkey2;
</code>```

答:
Try this query --

```<code>SELECT DISTINCT po.NAME
    ,sc.NAME
    ,sc2.NAME
FROM sysobjects fo
    ,sysobjects po
    ,sysforeignkeys fk
    ,sysobjects oo
    ,syscolumns sc
    ,sysreferences ref
    ,syscolumns sc2
WHERE fo.xtype = 'F'
    AND oo.NAME = @tab_name
    AND po.id = fo.parent_obj
    AND fo.id = fk.constid
    AND oo.id = fk.rkeyid
    AND sc.id = po.id
    AND ref.constid = fk.constid
    AND sc.colid = ref.fkey1
    AND sc2.id = Null -- sc2.id = * po.id
    AND sc2.colid = Null -- sc2.colid = * ref.fkey2
</code>```

Because,

```<code>*= Left Outer Join

=* Right Outer Join
</code>```

And in above query are trying to achieve the same by searching for Ids which are Nulls.

I hope it works.

Body:
Following query no longer compatible in SQL2012 and above. Need assistance to convert.

select distinct po.name , sc.name, sc2.name
from sysobjects fo, sysobjects po, sysforeignkeys fk, sysobjects oo
    , syscolumns sc, sysreferences ref, syscolumns sc2
where fo.xtype = 'F' and oo.name = @tab_name
  and po.id = fo.parent_obj and fo.id = fk.constid and oo.id = fk.rkeyid
  and sc.id = po.id and ref.constid = fk.constid and sc.colid = ref.fkey1
  and sc2.id =* po.id and sc2.colid =* ref.fkey2;

Body:
Try this query --

SELECT DISTINCT po.NAME
    ,sc.NAME
    ,sc2.NAME
FROM sysobjects fo
    ,sysobjects po
    ,sysforeignkeys fk
    ,sysobjects oo
    ,syscolumns sc
    ,sysreferences ref
    ,syscolumns sc2
WHERE fo.xtype = 'F'
    AND oo.NAME = @tab_name
    AND po.id = fo.parent_obj
    AND fo.id = fk.constid
    AND oo.id = fk.rkeyid
    AND sc.id = po.id
    AND ref.constid = fk.constid
    AND sc.colid = ref.fkey1
    AND sc2.id = Null -- sc2.id = * po.id
    AND sc2.colid = Null -- sc2.colid = * ref.fkey2

Because,

*= Left Outer Join

=* Right Outer Join

And in above query are trying to achieve the same by searching for Ids which are Nulls.

I hope it works.


问:
Can j# be used to provide jdbc functionality to an asp.net mvc application?
I have a service which exposes a JDBC interface ("yolus"/"ion arc" if anybody is familiar), and i'd like to be able to commincate with it from .net.

I'd rather not use an ODBC-JDBC Bridge, it's a real pain.

Is it possible to use J# for this and to integrate with or expose it to an existing .net codebase (asp.net mvc 2).

Thanks

答: J# is no longer supported so I would recommend you to stay away from it. Also why would a .NET application ever need JDBC functionailty when there's ADO.NET?


问:
get column number from label in DataFrame
how to get the column number from label in DataFrame, for instance.

```<code>import pandas as pd
from pandas import DataFrame

df = DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'b'],
                'data1': range(6)},
                index=['a1','a2','a3','a4','a5','a6'])
In[31]:df
Out[31]:
</code>```

```
      data1 key
a1      0   b
a2      1   b
a3      2   a
a4      3   c
a5      4   a
a6      5   b
```

if I run

```<code>df.iloc[2,1]
</code>```

it would return 'a'.
the question is,  I just know the column label is 'key', how can I get the column number? then I can use df.iloc.

you see, .ix is deprecated in pandas, else I would just use df.ix[2,'key'].

I just know how the solution for the similar question: get column label from column number. for instance,

```<code>df.loc['a3',df.iloc[:,[1]].columns]
</code>```

答:
You need Index.get_loc or Index.searchsorted:

```<code>a = df.columns.get_loc('key')
print (a)
1
</code>```

```<code>a = df.columns.searchsorted('key')
print (a)
1
</code>```

Then iloc works nice:

```<code>a = df.iloc[2, df.columns.get_loc('key')]
print (a)
a
</code>```

Body:
how to get the column number from label in DataFrame, for instance.

import pandas as pd
from pandas import DataFrame

df = DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'b'],
                'data1': range(6)},
                index=['a1','a2','a3','a4','a5','a6'])
In[31]:df
Out[31]:

      data1 key
a1      0   b
a2      1   b
a3      2   a
a4      3   c
a5      4   a
a6      5   b

if I run

df.iloc[2,1]

it would return 'a'.
the question is,  I just know the column label is 'key', how can I get the column number? then I can use df.iloc.

you see, .ix is deprecated in pandas, else I would just use df.ix[2,'key'].

I just know how the solution for the similar question: get column label from column number. for instance,

df.loc['a3',df.iloc[:,[1]].columns]

Body:
You need Index.get_loc or Index.searchsorted:

a = df.columns.get_loc('key')
print (a)
1

a = df.columns.searchsorted('key')
print (a)
1

Then iloc works nice:

a = df.iloc[2, df.columns.get_loc('key')]
print (a)
a


问:
How would the MONITOR instruction (_mm_monitor intrinsic) be used by a driver?
I am exploring the usage of MONITOR instruction (or the equivalent intrinsic, _mm_monitor). Although I found literature describing them, I could not find any concrete examples/samples on how to use it.

Can anyone share an example of how this instruction/intrinsic would be used in a driver? Essentially, I would like to use it to watch memory ranges.

答:
The monitor instruction arms the address monitoring hardware using the address specified in RAX/EAX/AX.Quote from Intel

The state of the monitor is used by the instruction mwait.

The effective address size used (16, 32 or 64-bit) depends on the effective address size of the encoded instruction (i.e. it can be overridden with the 67h prefix and by default it is the same as the code size).

The address given in rax/eax/ax is the offset part of the logical address from which the linear address used to arm the monitor is computed.

The segment part is ds by default, segment override prefixes can be applied to change segment.

Being a linear address used for the monitor, paging doesn't affect the monitoring.

The availability of the monitor (and mwait) instruction is indicated by the bit CPUID.01H:ECX.MONITOR[bit 3]1.

It is a privileged instruction but Intel claims:

The instructions are conditionally available at levels greater than 0.

The suggested method to detect such condition is to try to execute monitor and handle the eventual #UD exception (in the custom way to OS reports it to a userland program).

The address range monitored must be write-back cacheable.

Due to the involvement with the cache and cache coherence subsystems the size of the address range is given in term of the minimal and maximal sizes.

CPUID.01H:EAX[bit 15:0] gives the minimal range size. This is the length of the region monitored by the hardware monitor.

However, cache coherence traffic may work with "chunks" (lines) of bigger size and a write adjacent to the monitored region would trigger it nonetheless if the latter is included in the former.

This gives rise to the maximum range size, it can be found in CPUID.01H:EBX[bit 15:0].

To properly use monitor make sure that the data structure monitored fits the minimal range size but also make sure that no agents write in the addresses next to it up to the maximal range size.

For example, if the minimal range size is 8 bytes and the maximal size is 16 bytes, make sure that the structure watched fits 8 bytes but pad it with eight more bytes to reach a total of sixteen so that no write from the 8-th to the 16-th byte occurs.

In a single cluster system, the two values above are equal. Mine are both 64 bytes.

The BIOS is responsible for reporting the cache coherence line size in IA32_MONITOR_FILTER_LINE_SIZE in multi-clustered systems.

For the purpose of instruction ordering and access right, monitor is a load.

monitor allows the programmer to specify hints and extensions.

Extensions are specified in ecx while hints are in edx.

Unsupported extensions raise a #GP exception, unsupported hints are ignored.

I'm not aware of any extension or hint for monitor, the Intel manual reports

For the Pentium 4
  processor (family 15, model 3), no extensions or hints are defined.

I believe that line is true in general, it just has an outdated processor model in it.

Further, the pseudo code for monitor report a #GP If ECX ≠ 0.

Arming the monitor without checking its state afterwards (with mwait) doesn't cause any harm.

The intrinsic is void _mm_monitor(void const *p, unsigned extensions,unsigned hints).

Once the monitor is armed, it can be trigger by different conditions:

External interrupts: NMI, SMM, INIT, BINIT, MCERR

Faults, Aborts including Machine Check

Architectural TLB invalidations, including writes to CR0, CR3, CR4 and certain MSR writes

Voluntary transitions due to fast system call and far calls

Masked interrupt (if enabled)

A write in the monitored address range

The state of the monitor is not visible to the programmer but it can be tested with mwait.

mwait enters an implementation-defined low power state until the monitor is in a triggered state.

If the monitor is not into an armed state or if it is already triggered mwait is a nop otherwise it makes the processor stop executing instructions until the monitor is triggered.

mwait can also be given extensions and hints.

Extensions are set in ecx and hints in eax.

At the time of writing the only extension is:

Bit 0 Treat interrupts as break events even if masked (e.g., even if EFLAGS.IF=0). May be set only if
  CPUID.05H:ECX[bit 1] = 1.

  Bits 31-1 Reserved

The hints lets the programmer specify the implementation defined low power mode.

Bits 3:0 Sub C-state within a C-state, indicated by bits [7:4]

  Bits 7:4 Target C-state

  Value of 0 means C1; 1 means C2 and so on

  Value of 01111B means C0

  Note: Target C states for MWAIT extensions are processor-specific C-states, not ACPI C-states

The number of sub-states of a C-mode (and thus is availability) is given in CPUID.05h.EDX:

Bits 03 - 00: Number of C0* sub C-states supported using MWAIT.

  Bits 07 - 04: Number of C1* sub C-states supported using MWAIT.

  Bits 11 - 08: Number of C2* sub C-states supported using MWAIT.

  Bits 15 - 12: Number of C3* sub C-states supported using MWAIT.

  Bits 19 - 16: Number of C4* sub C-states supported using MWAIT.

  Bits 23 - 20: Number of C5* sub C-states supported using MWAIT.

  Bits 27 - 24: Number of C6* sub C-states supported using MWAIT.

  Bits 31 - 28: Number of C7* sub C-states supported using MWAIT.

Note that putting the CPU into a state higher than C1 disable other threads too, so the write that triggers the monitor must come from other agents.

The intrinsic is void _mm_mwait(unsigned extensions, unsigned hints).

The monitor/mwait machinery was introduced to help synchronisation between threads, it is not well suited for monitoring accesses to a memory range because the trigger conditions include frequently occurring events.

After a mwait is always mandatory to check if the monitored range was written to.

There is an example here where the pattern is as follow:

The watched structure is initialized with a specific value (say 0).

The monitor/mwait pair is used.

At some point later, another again write a specific value (say 1) to the watched structure.

The monitor is triggered and mwait "returns", the watched structure value is compared to 1 (a write occurred) and if it is not equal execution jump back to 2.

Some sample, untested pseudo-code may be:

```<code>struct MonitoredType
{
  int (*event)(struct MonitoredType const* m);              /*Return 0 to keep monitoring*/
  struct AnyType data;                                /*Less, in size, than MIN_MONITOR_RANGE*/
  char padding[MAX_MONITOR_RANGE - sizeof(AnyType)];
};

void wait_for_write(struct MonitoredType const* m)
{
   /* This may miss a write if it happens before MONITOR, beware of race conditions if necessary */
   do
   {
     _mm_monitor(&m->data, 0, 0);
     _mm_mwait(0, 0);
   } while ( ! m->event(m));
}
</code>```

Care must be taken to ensure that the exit condition of mwait was a write and not one of the other events.

That's the reason for the function pointer event.

For monitoring writes/reads to linear address an alternative can be the use of the debugging registers.

See chapter 17 of Intel manual 3 and check your OS documentation for the proper use of those registers.

1 Meaning: Execute cpuid with eax set to 01h and test the bit 3 of ecx afterward. Note that IA32_MISC_ENABLE allows the OS or the firmware to disable monitor/mwait.

Body:
The monitor instruction arms the address monitoring hardware using the address specified in RAX/EAX/AX.Quote from Intel

The state of the monitor is used by the instruction mwait.

The effective address size used (16, 32 or 64-bit) depends on the effective address size of the encoded instruction (i.e. it can be overridden with the 67h prefix and by default it is the same as the code size).

The address given in rax/eax/ax is the offset part of the logical address from which the linear address used to arm the monitor is computed.

The segment part is ds by default, segment override prefixes can be applied to change segment.

Being a linear address used for the monitor, paging doesn't affect the monitoring.

The availability of the monitor (and mwait) instruction is indicated by the bit CPUID.01H:ECX.MONITOR[bit 3]1.

It is a privileged instruction but Intel claims:

The instructions are conditionally available at levels greater than 0.

The suggested method to detect such condition is to try to execute monitor and handle the eventual #UD exception (in the custom way to OS reports it to a userland program).

The address range monitored must be write-back cacheable.

Due to the involvement with the cache and cache coherence subsystems the size of the address range is given in term of the minimal and maximal sizes.

CPUID.01H:EAX[bit 15:0] gives the minimal range size. This is the length of the region monitored by the hardware monitor.

However, cache coherence traffic may work with "chunks" (lines) of bigger size and a write adjacent to the monitored region would trigger it nonetheless if the latter is included in the former.

This gives rise to the maximum range size, it can be found in CPUID.01H:EBX[bit 15:0].

To properly use monitor make sure that the data structure monitored fits the minimal range size but also make sure that no agents write in the addresses next to it up to the maximal range size.

For example, if the minimal range size is 8 bytes and the maximal size is 16 bytes, make sure that the structure watched fits 8 bytes but pad it with eight more bytes to reach a total of sixteen so that no write from the 8-th to the 16-th byte occurs.

In a single cluster system, the two values above are equal. Mine are both 64 bytes.

The BIOS is responsible for reporting the cache coherence line size in IA32_MONITOR_FILTER_LINE_SIZE in multi-clustered systems.

For the purpose of instruction ordering and access right, monitor is a load.

monitor allows the programmer to specify hints and extensions.

Extensions are specified in ecx while hints are in edx.

Unsupported extensions raise a #GP exception, unsupported hints are ignored.

I'm not aware of any extension or hint for monitor, the Intel manual reports

For the Pentium 4
  processor (family 15, model 3), no extensions or hints are defined.

I believe that line is true in general, it just has an outdated processor model in it.

Further, the pseudo code for monitor report a #GP If ECX ≠ 0.

Arming the monitor without checking its state afterwards (with mwait) doesn't cause any harm.

The intrinsic is void _mm_monitor(void const *p, unsigned extensions,unsigned hints).

Once the monitor is armed, it can be trigger by different conditions:

External interrupts: NMI, SMM, INIT, BINIT, MCERR

Faults, Aborts including Machine Check

Architectural TLB invalidations, including writes to CR0, CR3, CR4 and certain MSR writes

Voluntary transitions due to fast system call and far calls

Masked interrupt (if enabled)

A write in the monitored address range

The state of the monitor is not visible to the programmer but it can be tested with mwait.

mwait enters an implementation-defined low power state until the monitor is in a triggered state.

If the monitor is not into an armed state or if it is already triggered mwait is a nop otherwise it makes the processor stop executing instructions until the monitor is triggered.

mwait can also be given extensions and hints.

Extensions are set in ecx and hints in eax.

At the time of writing the only extension is:

Bit 0 Treat interrupts as break events even if masked (e.g., even if EFLAGS.IF=0). May be set only if
  CPUID.05H:ECX[bit 1] = 1.

  Bits 31-1 Reserved

The hints lets the programmer specify the implementation defined low power mode.

Bits 3:0 Sub C-state within a C-state, indicated by bits [7:4]

  Bits 7:4 Target C-state

  Value of 0 means C1; 1 means C2 and so on

  Value of 01111B means C0

  Note: Target C states for MWAIT extensions are processor-specific C-states, not ACPI C-states

The number of sub-states of a C-mode (and thus is availability) is given in CPUID.05h.EDX:

Bits 03 - 00: Number of C0* sub C-states supported using MWAIT.

  Bits 07 - 04: Number of C1* sub C-states supported using MWAIT.

  Bits 11 - 08: Number of C2* sub C-states supported using MWAIT.

  Bits 15 - 12: Number of C3* sub C-states supported using MWAIT.

  Bits 19 - 16: Number of C4* sub C-states supported using MWAIT.

  Bits 23 - 20: Number of C5* sub C-states supported using MWAIT.

  Bits 27 - 24: Number of C6* sub C-states supported using MWAIT.

  Bits 31 - 28: Number of C7* sub C-states supported using MWAIT.

Note that putting the CPU into a state higher than C1 disable other threads too, so the write that triggers the monitor must come from other agents.

The intrinsic is void _mm_mwait(unsigned extensions, unsigned hints).

The monitor/mwait machinery was introduced to help synchronisation between threads, it is not well suited for monitoring accesses to a memory range because the trigger conditions include frequently occurring events.

After a mwait is always mandatory to check if the monitored range was written to.

There is an example here where the pattern is as follow:

The watched structure is initialized with a specific value (say 0).

The monitor/mwait pair is used.

At some point later, another again write a specific value (say 1) to the watched structure.

The monitor is triggered and mwait "returns", the watched structure value is compared to 1 (a write occurred) and if it is not equal execution jump back to 2.

Some sample, untested pseudo-code may be:

struct MonitoredType
{
  int (*event)(struct MonitoredType const* m);              /*Return 0 to keep monitoring*/
  struct AnyType data;                                /*Less, in size, than MIN_MONITOR_RANGE*/
  char padding[MAX_MONITOR_RANGE - sizeof(AnyType)];
};

void wait_for_write(struct MonitoredType const* m)
{
   /* This may miss a write if it happens before MONITOR, beware of race conditions if necessary */
   do
   {
     _mm_monitor(&m->data, 0, 0);
     _mm_mwait(0, 0);
   } while ( ! m->event(m));
}

Care must be taken to ensure that the exit condition of mwait was a write and not one of the other events.

That's the reason for the function pointer event.

For monitoring writes/reads to linear address an alternative can be the use of the debugging registers.

See chapter 17 of Intel manual 3 and check your OS documentation for the proper use of those registers.

1 Meaning: Execute cpuid with eax set to 01h and test the bit 3 of ecx afterward. Note that IA32_MISC_ENABLE allows the OS or the firmware to disable monitor/mwait.


问:
How to check the version of scipy
How can I check the version of scipy installed on my system?

答:
From the python command prompt:

```<code>import scipy
print scipy.__version__
</code>```

In python 3 you'll need to change it to:

```<code>print (scipy.__version__)
</code>```

Title: How to check the version of scipy

Body:
From the python command prompt:

import scipy
print scipy.__version__

In python 3 you'll need to change it to:

print (scipy.__version__)


问:
Why this don't work?
This Function is Work:

```<code>function son_bolum_liste_cek($limit)
{
global $db;
$query = $db->prepare("SELECT `anime_bolum`.`id`, `anime`.`isim`, `anime_bolum`.`bolum_no`, `image`.`url` as `image`, `gifimage`.`url` as `gifimage` FROM `anime_bolum` JOIN `anime` ON `anime`.`id` = `anime_bolum`.`anime_id` JOIN `image` ON `anime_bolum`.`image` = `image`.`id` JOIN `image` as `gifimage` ON `gifimage`.`id` = `anime_bolum`.`gifimage` ORDER BY `anime_bolum`.`id` DESC LIMIT :limit;");
$query->bindValue(':limit', $limit, PDO::PARAM_INT);
$select = $query->execute();
return $query->fetchAll();
}
foreach (son_bolum_liste_cek(12) as $anime){blabla};
</code>```

But This is Don't Work:

```<code>function db_toplu_veri_oku($query, $execute = array() , $binds = array(),$debug = false)
{
global $db;
$query = $db->prepare($query);
foreach($binds as $bind)
    {
    $query->bindValue($bind[0], $bind[1], $bind[2]);
    }

$select = $query->execute($execute);
if($debug){$query->debugDumpParams();};
return $query->fetchAll();
}

function son_bolum_liste_cek($limit)
{
$query = "SELECT `anime_bolum`.`id`, `anime`.`isim`, `anime_bolum`.`bolum_no`, `image`.`url` as `image`, `gifimage`.`url` as `gifimage` FROM `anime_bolum` JOIN `anime` ON `anime`.`id` = `anime_bolum`.`anime_id` JOIN `image` ON `anime_bolum`.`image` = `image`.`id` JOIN `image` as `gifimage` ON `gifimage`.`id` = `anime_bolum`.`gifimage` ORDER BY `anime_bolum`.`id` DESC LIMIT :limit;";
$binds = array(array(':limit',$limit,PDO::PARAM_INT));
return db_toplu_veri_oku($query,array(),$binds);
}
foreach (son_bolum_liste_cek(12) as $anime){blabla};
</code>```

Two Function doing same work but bottom function don't work why ? Where am I doing wrong ?

答:
Little change. Issue in execute. You are passing blank array in this. So you have to check first if array containing value or not

```<code>function db_toplu_veri_oku($query, $execute = array() , $binds = array(),$debug = false)
{
global $db;
$query = $db->prepare($query);
foreach($binds as $bind)
    {
    $query->bindValue($bind[0], $bind[1], $bind[2]);
    }

if(count($execute)) //<-----------Add this condition
    $select = $query->execute($execute);
else
    $select = $query->execute();
if($debug){$query->debugDumpParams();};
return $query->fetchAll();
}
</code>```

Title: Why this don't work?

Body:
This Function is Work:

function son_bolum_liste_cek($limit)
{
global $db;
$query = $db->prepare("SELECT `anime_bolum`.`id`, `anime`.`isim`, `anime_bolum`.`bolum_no`, `image`.`url` as `image`, `gifimage`.`url` as `gifimage` FROM `anime_bolum` JOIN `anime` ON `anime`.`id` = `anime_bolum`.`anime_id` JOIN `image` ON `anime_bolum`.`image` = `image`.`id` JOIN `image` as `gifimage` ON `gifimage`.`id` = `anime_bolum`.`gifimage` ORDER BY `anime_bolum`.`id` DESC LIMIT :limit;");
$query->bindValue(':limit', $limit, PDO::PARAM_INT);
$select = $query->execute();
return $query->fetchAll();
}
foreach (son_bolum_liste_cek(12) as $anime){blabla};

But This is Don't Work:

function db_toplu_veri_oku($query, $execute = array() , $binds = array(),$debug = false)
{
global $db;
$query = $db->prepare($query);
foreach($binds as $bind)
    {
    $query->bindValue($bind[0], $bind[1], $bind[2]);
    }

$select = $query->execute($execute);
if($debug){$query->debugDumpParams();};
return $query->fetchAll();
}

function son_bolum_liste_cek($limit)
{
$query = "SELECT `anime_bolum`.`id`, `anime`.`isim`, `anime_bolum`.`bolum_no`, `image`.`url` as `image`, `gifimage`.`url` as `gifimage` FROM `anime_bolum` JOIN `anime` ON `anime`.`id` = `anime_bolum`.`anime_id` JOIN `image` ON `anime_bolum`.`image` = `image`.`id` JOIN `image` as `gifimage` ON `gifimage`.`id` = `anime_bolum`.`gifimage` ORDER BY `anime_bolum`.`id` DESC LIMIT :limit;";
$binds = array(array(':limit',$limit,PDO::PARAM_INT));
return db_toplu_veri_oku($query,array(),$binds);
}
foreach (son_bolum_liste_cek(12) as $anime){blabla};

Two Function doing same work but bottom function don't work why ? Where am I doing wrong ?

Body:
Little change. Issue in execute. You are passing blank array in this. So you have to check first if array containing value or not

function db_toplu_veri_oku($query, $execute = array() , $binds = array(),$debug = false)
{
global $db;
$query = $db->prepare($query);
foreach($binds as $bind)
    {
    $query->bindValue($bind[0], $bind[1], $bind[2]);
    }

if(count($execute)) //<-----------Add this condition
    $select = $query->execute($execute);
else
    $select = $query->execute();
if($debug){$query->debugDumpParams();};
return $query->fetchAll();
}


问:
what is the time complexity (big O) of a recursive function?
Does a recursive function have a time complexity of it's own.
Like the the time complexity of a for loop which is looping 'n' time is Big O(n).
Similarly does a recursive function have a fixed time complexity or does it depend on the problem.

答: You can use master theorem. It helps determine the time complexity of a recursive function.</p>


问:
Does &quot prints " in python 3?
I was going through the following piece of code:

```<code>try:
            with open('python.json', 'a') as f:
                f.write(data)
                return True
except BaseException as e:
            print("Error on_data: %s" % str(e))
</code>```

I am not quite able to explain what does the print statement do here?

答:
It does not do anything, it's a syntax error.

The example you pasted probably went through some oh-my-god-I-need-to-escape-all-special-characters-zomg-css-attacks handling that mercilessly replaced the ".

Title: Does &quot prints " in python 3?

Body:
I was going through the following piece of code:

try:
            with open('python.json', 'a') as f:
                f.write(data)
                return True
except BaseException as e:
            print("Error on_data: %s" % str(e))

I am not quite able to explain what does the print statement do here?


问:
WScript.Shell not working in FireFox
I have following javascript code. (Actually I have to launch an exe on client side)

```<code>function executeCommands()
{
      var commandtoRun ="C:\\WINDOWS\\notepad.exe";
      var oShell = new ActiveXObject("WScript.Shell");
      oShell.run(commandtoRun);
}
</code>```

This code can launch notepad in the Internet Explorer when I made Security option to "Low" but this code can't launch Notepad in FireFox.

Any suggestion will be appreciated..

答:
Firefox doesn't support ActiveXObject(), it's a proprietary feature of JScript (Microsoft's version of JavaScript).

Read more information here.

Title: WScript.Shell not working in FireFox

Body:
I have following javascript code. (Actually I have to launch an exe on client side)

function executeCommands()
{
      var commandtoRun ="C:\\WINDOWS\\notepad.exe";
      var oShell = new ActiveXObject("WScript.Shell");
      oShell.run(commandtoRun);
}

This code can launch notepad in the Internet Explorer when I made Security option to "Low" but this code can't launch Notepad in FireFox.

Any suggestion will be appreciated..


问:
RStudio does not see packages being updated
After I run install.packages('some_package') and it is installed successfully RStudio asks me whether I want to update a list of old packages:

```<code>The downloaded source packages are in
    ‘/tmp/Rtmpu75mCG/downloaded_packages’
Old packages: 'acepack', 'base64', 'colorspace', 'DBI', 'digest', 'ggplot2', 'gridSVG', 'Hmisc', 'limma', 'plyr', 'Rcpp',
  'reshape2', 'R.oo', 'RSQLite', 'R.utils', 'scales', 'stringi', 'stringr', 'XML', 'abind', 'colorspace', 'crayon',
  'digest', 'ggplot2', 'gtable', 'mapproj', 'maps', 'memoise', 'munsell', 'pkgKitten', 'plyr', 'proto', 'Rcpp',
  'reshape2', 'scales', 'sp', 'stringi', 'stringr'
Update all/some/none? [a/s/n]:
</code>```

I say a and seem to have no errors but next time I install some package RStudio asks me to update the very same packages. I can successfully install single package install.packages('acepack') but RStudio still asks me to update it next time.

How to convince RStudio I have updated packages already?

Using R version 3.4.0 (2017-04-21), RStudio version 1.0.143, Ubuntu 16.04

Upd:

The same when I do it in plain R.

The same when I run Bioconductor's biocLite() function

答:
Sometimes, packages get stored in different folders, and when you update them, old versions may remain in some of them, causing these kind of issues.

Have a look at the output of .libPaths() and search these corresponding folders. There are many ways to prevent these conflicts from emerging, for instance by defining a fixed package repository in your RPROFILE file.

Body:
After I run install.packages('some_package') and it is installed successfully RStudio asks me whether I want to update a list of old packages:

The downloaded source packages are in
    ‘/tmp/Rtmpu75mCG/downloaded_packages’
Old packages: 'acepack', 'base64', 'colorspace', 'DBI', 'digest', 'ggplot2', 'gridSVG', 'Hmisc', 'limma', 'plyr', 'Rcpp',
  'reshape2', 'R.oo', 'RSQLite', 'R.utils', 'scales', 'stringi', 'stringr', 'XML', 'abind', 'colorspace', 'crayon',
  'digest', 'ggplot2', 'gtable', 'mapproj', 'maps', 'memoise', 'munsell', 'pkgKitten', 'plyr', 'proto', 'Rcpp',
  'reshape2', 'scales', 'sp', 'stringi', 'stringr'
Update all/some/none? [a/s/n]:

I say a and seem to have no errors but next time I install some package RStudio asks me to update the very same packages. I can successfully install single package install.packages('acepack') but RStudio still asks me to update it next time.

How to convince RStudio I have updated packages already?

Using R version 3.4.0 (2017-04-21), RStudio version 1.0.143, Ubuntu 16.04

Upd:

The same when I do it in plain R.

The same when I run Bioconductor's biocLite() function


问:
Can't access ArtifactStagingDirectory variable in MSBuild
During my build process I'm trying to copy a folder to the artifacts folder (\myserver\d$\TFBuild-Agent01\66\a).

So I put this in the .csproj file:

<Target Name="BeforeBuild">
  <Exec
    Command="xcopy.exe  Databases "$(Build.ArtifactStagingDirectory)\Databases" /i /e /y /d" />
</Target>
```

<p>This gets me </p>

<blockquote>
  <p>Error MSB4184: The expression """.ArtifactStagingDirectory" cannot be evaluated. Method 'System.String.ArtifactStagingDirectory' not found*</p>
</blockquote>

<p>Everything I can find online says that $(Build.ArtifactStagingDirectory) is the way to do it.  But it doesn't work.</p>

<p>Building with Visual Studio 2015 on TFS 2015</p>

<p>This doesn't work either:</p>

```<Exec
Command="xcopy.exe  Databases "$($Env:BUILD_ARTIFACTSTAGINGDIRECTORY)\Databases" /i /e /y /d" />
```

<blockquote>
  <p>The expression "$Env:BUILD_ARTIFACTSTAGINGDIRECTORY" cannot be evaluated.*</p>
</blockquote>

<p>This doesn't error, but it looks like %BUILD_ARTIFACTSTAGINGDIRECTORY% gets replaced as an empty string:</p>

``` <Exec Command="xcopy.exe  Databases "%BUILD_ARTIFACTSTAGINGDIRECTORY%\Databases" /i /e /y /d" />
```

答:
You have been mixing ways to access the build variables that the agent allows you. The syntax using $(some.variable) is interpreted by the agent itself. MSBuild has a similar looking syntax - $(PropertyName) - which does something different - it gives access to msbuild properties and does not allow for dots (.) in it's name, since you can use the dot to call functions on the value (e.g. $(OutputPath.Substring(3))).

When you want to reference build variables from MSBuild, you need to reference the environment variable that the agent sets. This is possible because MSBuild makes all environment variables accessible as global properties using its property syntax. The environment variable for Build.ArtifactStagingDirectory is BUILD_ARTIFACTSTAGINGDIRECTORY so you can use it in MSBuild using $(BUILD_ARTIFACTSTAGINGDIRECTORY).

I have been using it successfully in this script to default a property when run as part of a TFS/VSTS build (PublishBaseDir is a custom property used later):

```<code><PropertyGroup>
  <!-- Default artifact staging directory when built via VSTS / TFS agent -->
  <PublishBaseDir Condition="'$(PublishBaseDir)' == '' and '$(BUILD_ARTIFACTSTAGINGDIRECTORY)' != '' ">$(BUILD_ARTIFACTSTAGINGDIRECTORY)</PublishBaseDir>

  <!-- If not built on a known agent, use a "publish" subdir next to this file -->
  <PublishBaseDir Condition="'$(PublishBaseDir)' == ''">$(MSBuildThisFileDirectory)publish\</PublishBaseDir>

  <!-- Normalize directory if set manually or through ENV var -->
  <PublishBaseDir Condition="!HasTrailingSlash('$(PublishBaseDir)')">$(PublishBaseDir)\</PublishBaseDir>
</PropertyGroup>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
During my build process I'm trying to copy a folder to the artifacts folder (\myserver\d$\TFBuild-Agent01\66\a).

So I put this in the .csproj file:

<Target Name="BeforeBuild">
  <Exec
    Command="xcopy.exe  Databases "$(Build.ArtifactStagingDirectory)\Databases" /i /e /y /d" />
</Target>

This gets me

Error MSB4184: The expression """.ArtifactStagingDirectory" cannot be evaluated. Method 'System.String.ArtifactStagingDirectory' not found*

Everything I can find online says that $(Build.ArtifactStagingDirectory) is the way to do it.  But it doesn't work.

Building with Visual Studio 2015 on TFS 2015

This doesn't work either:

<Exec
Command="xcopy.exe  Databases "$($Env:BUILD_ARTIFACTSTAGINGDIRECTORY)\Databases" /i /e /y /d" />

The expression "$Env:BUILD_ARTIFACTSTAGINGDIRECTORY" cannot be evaluated.*

This doesn't error, but it looks like %BUILD_ARTIFACTSTAGINGDIRECTORY% gets replaced as an empty string:

 <Exec Command="xcopy.exe  Databases "%BUILD_ARTIFACTSTAGINGDIRECTORY%\Databases" /i /e /y /d" />

Body:
You have been mixing ways to access the build variables that the agent allows you. The syntax using $(some.variable) is interpreted by the agent itself. MSBuild has a similar looking syntax - $(PropertyName) - which does something different - it gives access to msbuild properties and does not allow for dots (.) in it's name, since you can use the dot to call functions on the value (e.g. $(OutputPath.Substring(3))).

When you want to reference build variables from MSBuild, you need to reference the environment variable that the agent sets. This is possible because MSBuild makes all environment variables accessible as global properties using its property syntax. The environment variable for Build.ArtifactStagingDirectory is BUILD_ARTIFACTSTAGINGDIRECTORY so you can use it in MSBuild using $(BUILD_ARTIFACTSTAGINGDIRECTORY).

I have been using it successfully in this script to default a property when run as part of a TFS/VSTS build (PublishBaseDir is a custom property used later):

<PropertyGroup>
  <!-- Default artifact staging directory when built via VSTS / TFS agent -->
  <PublishBaseDir Condition="'$(PublishBaseDir)' == '' and '$(BUILD_ARTIFACTSTAGINGDIRECTORY)' != '' ">$(BUILD_ARTIFACTSTAGINGDIRECTORY)</PublishBaseDir>

  <!-- If not built on a known agent, use a "publish" subdir next to this file -->
  <PublishBaseDir Condition="'$(PublishBaseDir)' == ''">$(MSBuildThisFileDirectory)publish\</PublishBaseDir>

  <!-- Normalize directory if set manually or through ENV var -->
  <PublishBaseDir Condition="!HasTrailingSlash('$(PublishBaseDir)')">$(PublishBaseDir)\</PublishBaseDir>
</PropertyGroup>


问:
I am unable to understand below php Function code -
How it will print hello - If hello is true, then the function must print hello, but if the function doesn’t receive hello or hello is false the function must print bye.</p>

```<code><?php
function showMessage($hello=false){
  echo ($hello)?'hello':'bye';
}
?>
</code>```

答:
Basically ($hello)?'hello':'bye'; is the shorthand for:

```<code>if ($hello == true) {
  echo 'hello';
} else {
  echo 'bye';
}
</code>```

Reference: http://php.net/manual/en/control-structures.if.php

Body:
How it will print hello - If hello is true, then the function must print hello, but if the function doesn’t receive hello or hello is false the function must print bye.

<?php
function showMessage($hello=false){
  echo ($hello)?'hello':'bye';
}
?>

Body:
Basically ($hello)?'hello':'bye'; is the shorthand for:

if ($hello == true) {
  echo 'hello';
} else {
  echo 'bye';
}

Reference: http://php.net/manual/en/control-structures.if.php


问:
How can i make custom buttons to control the <embed>?
Im trying to play some sound(mp3) in my browser. Found <embed> but the default controllers (pause button, volume and timeslider) aint really pretty so what im wondering is how i could control it with some jquery buttons?

i would then hide the embed and call controls with jquery and the embed tags id.

Is this possible, and where could i find a overview of that?

答:
Actually you can do this better with html5 (less load from CPU, but less crossbrowser too)
(google it: custom html5 audio player)

but if you want flash behind the scenes, better go with jPlayer :
http://www.happyworm.com/jquery/jplayer/


问:
get original template before replaced by the angularjs directive
How can I get the original markup before getting replaced by angular js directives? This question has already been asked, but I am posting this as the solutions don't work for me and also I want to know if the angular js team may have introduced any new methods for this.

This is what I have tried so far:

```<code>  function $block($compile) {

    var html = '<div>new content</div>';

    return {
      restrict: 'E',
      template: function(element, attrs) {
        console.log(element); // still getting the new element
        return html;
      },
      link: function(scope, element, attrs) {
           console.log(element)
      }
    };

  }

  angular.module('directive', [])
    .directive('myDirective', $block);
</code>```

How can I get the old template and then replace it with the new one?

答:
When you console.log an object, the browser displays the content value at the time it is viewed. Not at the time it was logged. That is the way the Developer Console works.

If you log the innerHTML you will see that they are different:

angular.module('directive', [])

    .directive('myDirective', $block);

  function $block($compile) {

    var html = '
new content
';

    return {
      restrict: 'E',
      template: function(element, attrs) {
        console.log(element[0].innerHTML);
        return html;
      },
      link: function(scope, element, attrs) {
           console.log(element[0].innerHTML);
      }
    };

  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app=directive>
    <h1>Directive Demo</h1>
    <my-directive><div>Old Content</div>
    </my-directive>
  </body></code>```

Body:
How can I get the original markup before getting replaced by angular js directives? This question has already been asked, but I am posting this as the solutions don't work for me and also I want to know if the angular js team may have introduced any new methods for this.

This is what I have tried so far:

  function $block($compile) {

    var html = '
new content
';

    return {
      restrict: 'E',
      template: function(element, attrs) {
        console.log(element); // still getting the new element
        return html;
      },
      link: function(scope, element, attrs) {
           console.log(element)
      }
    };

  }

  angular.module('directive', [])
    .directive('myDirective', $block);

How can I get the old template and then replace it with the new one?

Body:
When you console.log an object, the browser displays the content value at the time it is viewed. Not at the time it was logged. That is the way the Developer Console works.

If you log the innerHTML you will see that they are different:

angular.module('directive', [])

    .directive('myDirective', $block);

  function $block($compile) {

    var html = '<div>new content</div>';

    return {
      restrict: 'E',
      template: function(element, attrs) {
        console.log(element[0].innerHTML);
        return html;
      },
      link: function(scope, element, attrs) {
           console.log(element[0].innerHTML);
      }
    };

  }

<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app=directive>
    <h1>Directive Demo</h1>
    <my-directive><div>Old Content</div>
    </my-directive>
  </body>


问:
Static member access in constant expressions
Accessing static class member functions or variables, can be done in two ways: through an object (obj.member_fun() or obj.member_var) or through the class (Class::member_fun() or Class::member_var). However, in constexpr functions, Clang gives an error on the object access and requires to use class access:

```<code>struct S
{
    constexpr static auto s_v = 42;
    constexpr static auto v() { return s_v; }
};

#define TEST 1

constexpr auto foo(S const& s [[maybe_unused]])
{
#if TEST
    constexpr auto v = s.v();   // ERROR for clang, OK for gcc
#else
    constexpr auto v = S::v();  // OK for clang and gcc
#endif
    return v;
}

constexpr auto bar(S const& s [[maybe_unused]])
{
#if TEST
    constexpr auto v = s.s_v;   // ERROR for clang, OK for gcc
#else
    constexpr auto v = S::s_v;  // OK for clang and gcc
#endif
    return v;
}

int main() {}
</code>```

Live Example compiled with -std=c++1z and #define TEST 1 for Clang 5.0 SVN, with error message:

```<code>Start
prog.cc:12:24: error: constexpr variable 'v' must be initialized by a constant expression
    constexpr auto v = s.v();   // ERROR for clang, OK for gcc
                       ^~~~~
prog.cc:22:24: error: constexpr variable 'v' must be initialized by a constant expression
    constexpr auto v = s.s_v;   // ERROR for clang, OK for gcc
                       ^~~~~
2 errors generated.
1
Finish
</code>```

Question: is this is a Clang bug, or is gcc too liberal in accepting both syntax forms for static member access in a constexpr function?

答:
Clang seems to be in the right. When accessing a static member with the member access syntax [class.static/1]:

A static member s of class X may be referred to using the qualified-id
  expression X::s; it is not necessary to use the class member access
  syntax to refer to a static member. A static member may be referred to
  using the class member access syntax, in which case the object
  expression is evaluated.

So s.v() will cause s to be evaluated. Now, according to [expr.const/2.11], s is not a constant expression:

2 An expression e is a core constant expression unless the evaluation
  of e, following the rules of the abstract machine, would evaluate one
  of the following expressions:

[...]

an id-expression that refers to a variable or data member of reference
  type unless the reference has a preceding initialization and either:

  (2.11.1) - it is initialized with a constant expression or

  (2.11.2) - its lifetime began within the evaluation of e;

s doesn't have a preceding initialization with a constant expression, not in the scope of foo.

If you want to access the static members based of a function parameter, without hard-coding the type, the way forward is std::remove_reference_t<decltype(s)>. This is accepted by Clang and GCC both:

```<code>#include <type_traits>

struct S
{
    constexpr static auto s_v = 42;
    constexpr static auto v() { return s_v; }
};

constexpr auto foo(S const& s)
{
    constexpr auto v = std::remove_reference_t<decltype(s)>::v();
    return v;
}

constexpr auto bar(S const& s)
{
    constexpr auto v = std::remove_reference_t<decltype(s)>::s_v;
    return v;
}

int main() {}
</code>```

Body:
Accessing static class member functions or variables, can be done in two ways: through an object (obj.member_fun() or obj.member_var) or through the class (Class::member_fun() or Class::member_var). However, in constexpr functions, Clang gives an error on the object access and requires to use class access:

struct S
{
    constexpr static auto s_v = 42;
    constexpr static auto v() { return s_v; }
};

#define TEST 1

constexpr auto foo(S const& s [[maybe_unused]])
{
#if TEST
    constexpr auto v = s.v();   // ERROR for clang, OK for gcc
#else
    constexpr auto v = S::v();  // OK for clang and gcc
#endif
    return v;
}

constexpr auto bar(S const& s [[maybe_unused]])
{
#if TEST
    constexpr auto v = s.s_v;   // ERROR for clang, OK for gcc
#else
    constexpr auto v = S::s_v;  // OK for clang and gcc
#endif
    return v;
}

int main() {}

Live Example compiled with -std=c++1z and #define TEST 1 for Clang 5.0 SVN, with error message:

Start
prog.cc:12:24: error: constexpr variable 'v' must be initialized by a constant expression
    constexpr auto v = s.v();   // ERROR for clang, OK for gcc
                       ^~~~~
prog.cc:22:24: error: constexpr variable 'v' must be initialized by a constant expression
    constexpr auto v = s.s_v;   // ERROR for clang, OK for gcc
                       ^~~~~
2 errors generated.
1
Finish

Question: is this is a Clang bug, or is gcc too liberal in accepting both syntax forms for static member access in a constexpr function?

Body:
Clang seems to be in the right. When accessing a static member with the member access syntax [class.static/1]:

A static member s of class X may be referred to using the qualified-id
  expression X::s; it is not necessary to use the class member access
  syntax to refer to a static member. A static member may be referred to
  using the class member access syntax, in which case the object
  expression is evaluated.

So s.v() will cause s to be evaluated. Now, according to [expr.const/2.11], s is not a constant expression:

2 An expression e is a core constant expression unless the evaluation
  of e, following the rules of the abstract machine, would evaluate one
  of the following expressions:

[...]

an id-expression that refers to a variable or data member of reference
  type unless the reference has a preceding initialization and either:

  (2.11.1) - it is initialized with a constant expression or

  (2.11.2) - its lifetime began within the evaluation of e;

s doesn't have a preceding initialization with a constant expression, not in the scope of foo.

If you want to access the static members based of a function parameter, without hard-coding the type, the way forward is std::remove_reference_t<decltype(s)>. This is accepted by Clang and GCC both:

#include <type_traits>

struct S
{
    constexpr static auto s_v = 42;
    constexpr static auto v() { return s_v; }
};

constexpr auto foo(S const& s)
{
    constexpr auto v = std::remove_reference_t<decltype(s)>::v();
    return v;
}

constexpr auto bar(S const& s)
{
    constexpr auto v = std::remove_reference_t<decltype(s)>::s_v;
    return v;
}

int main() {}


问:
How opencl work with opencv
I'm trying to create a region groiwing algorithm using OpenCL,for that i will open one image using OpenCV. The problem is how transform the data into OpenCL.

I'm using opencv version : 2.4.9 and opencl : AMD APP SDK\2.9-1 in visual studio

Would someone tell me after openning the image using opencv what should i do

答:
Generally, there are two ways in order to transfer images (or any other data) from host program to device program in OpenCL applications: 1-Using Buffers 2- Using Image2d.
Both of them use cl_mem type. Because using buffer is simpler than using image2d (especially in gray-scale images), I explain how to transfer images from host program to device using buffers in OpenCL.

After reading input image by the openCV object Mat, convert it to a gray-scale image. Then, we use the method clCreateBuffer which returns a cl_mem buffer. We can simply pass data (a property of Mat obeject) to the clCreateBuffer to initialize our input kernel buffer by input image data. Then we can transfer created buffer to kernel using clSetKernelArg method. Finally, when kernel finish its job, we can read the results by clEnqueueReadBuffer.

Read the comments to understand this code and don't hesitate to ask questions.

Host code:

// Make Contex, Kerenl and other requirements for OpenCL before this section....

Mat image = imread("logo.bmp", CV_LOAD_IMAGE_COLOR); // reading input image by opencv to Mat type
Mat input_;

cvtColor(image, input_, CV_BGR2GRAY); // convert input image to gray scale

cl_mem inputSignalBuffer = clCreateBuffer(
    context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, input_.rows *input_.cols *input_.elemSize(),
    static_cast<void *>(
        input_.data), // inputSignalBuffers will be initialized by input_.data which contains input image data
    &errNum);

cl_mem outputSignalBuffer =
    clCreateBuffer( // make and preparing an empty output buffer to use after opencl kernel call back
        context, CL_MEM_WRITE_ONLY, input_.rows *input_.cols *input_.elemSize(), NULL, &errNum);
checkErr(errNum, "clCreateBuffer(outputSignal)");

errNum = clSetKernelArg(
    kernel, 0, sizeof(cl_mem),
    &inputSignalBuffer); // passing input buffer and output buffer to kernel in order to be used on device
errNum |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &maskBuffer);
errNum |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &outputSignalBuffer);
errNum |= clSetKernelArg(kernel, 3, sizeof(cl_uint), &input_.rows);
errNum |= clSetKernelArg(kernel, 4, sizeof(cl_uint), &input_.cols);
errNum |= clSetKernelArg(kernel, 5, sizeof(cl_uint), &maskWidth);

size_t localWorkSize[2] = {16, 16}; // Using 2 dimensional range  with size of work group 16
size_t globalWorkSize[2] = {
    input_
        .rows, // Note: Global work size (input image rows and cols) should be multiple of size of work group.
    input_.cols};

// Queue the kernel up for execution across the array
errNum =
    clEnqueueNDRangeKernel( // enqueue kernel with enabling host blocking until finishing kernel execution
        queue, kernel, 2, NULL, globalWorkSize, localWorkSize, 0, NULL, NULL);
checkErr(errNum, "clEnqueueNDRangeKernel");

Mat output_ = cv::Mat(input_.rows, input_.cols, CV_8UC1);

errNum = clEnqueueReadBuffer( //  reading from ourput parameter of kernel
    queue, outputSignalBuffer, CL_TRUE, 0, input_.rows *input_.cols *input_.elemSize(),
    output_.data, // initialize OpenCV Mat by output_.data which contains output results of kernel
    0, NULL, NULL);
checkErr(errNum, "clEnqueueReadBuffer");

// cut the extra border spaces which has been added in the first part of the code in order to adjust image
// size with Work Group Size;

cv::imwrite("output.bmp", output_); // saving output in image file
```
<p>Kernel code:</p>
<pre class="lang-cpp prettyprint-override"><code>__kernel void convolve(const __global uchar *const input, __constant uint *const mask,
                       __global uchar *const output, const int inputHeight, const int inputWidth,
                       const int maskWidth) {
  uint sum = 0;

  const int curr_x = get_global_id(0); // current curr_x (row)
  const int curr_y = get_global_id(1); // current curr_y (col)
  int d = maskWidth / 2;

  if (curr_x > d - 1 && curr_y > d - 1 && curr_x < inputHeight - d &&
      curr_y < inputWidth - d) // checking mask borders not to be out of input matrix
    for (int i = -d; i <= d; i++)
      for (int j = -d; j <= d; j++) {
        int mask_ptr =
            maskWidth * (i + d) + (j + d); // you can also use mad24(maskWidth, i+d, j+d) which is faster.
        sum += input[(curr_x + i) * inputWidth + curr_y + j] * mask[mask_ptr];
      }

  sum /= (maskWidth * maskWidth); // miangin gereftan

  sum = clamp(sum, (uint)0, (uint)255); // clamp == min(max(x, minval), maxval)

  output[curr_x * inputWidth + curr_y] = sum;
}
</code>```

Title: How opencl work with opencv

Body:
Generally, there are two ways in order to transfer images (or any other data) from host program to device program in OpenCL applications: 1-Using Buffers 2- Using Image2d.
Both of them use cl_mem type. Because using buffer is simpler than using image2d (especially in gray-scale images), I explain how to transfer images from host program to device using buffers in OpenCL.

After reading input image by the openCV object Mat, convert it to a gray-scale image. Then, we use the method clCreateBuffer which returns a cl_mem buffer. We can simply pass data (a property of Mat obeject) to the clCreateBuffer to initialize our input kernel buffer by input image data. Then we can transfer created buffer to kernel using clSetKernelArg method. Finally, when kernel finish its job, we can read the results by clEnqueueReadBuffer.

Read the comments to understand this code and don't hesitate to ask questions.

Host code:

// Make Contex, Kerenl and other requirements for OpenCL before this section....

Mat image = imread("logo.bmp", CV_LOAD_IMAGE_COLOR); // reading input image by opencv to Mat type
Mat input_;

cvtColor(image, input_, CV_BGR2GRAY); // convert input image to gray scale

cl_mem inputSignalBuffer = clCreateBuffer(
    context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, input_.rows *input_.cols *input_.elemSize(),
    static_cast<void *>(
        input_.data), // inputSignalBuffers will be initialized by input_.data which contains input image data
    &errNum);

cl_mem outputSignalBuffer =
    clCreateBuffer( // make and preparing an empty output buffer to use after opencl kernel call back
        context, CL_MEM_WRITE_ONLY, input_.rows *input_.cols *input_.elemSize(), NULL, &errNum);
checkErr(errNum, "clCreateBuffer(outputSignal)");

errNum = clSetKernelArg(
    kernel, 0, sizeof(cl_mem),
    &inputSignalBuffer); // passing input buffer and output buffer to kernel in order to be used on device
errNum |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &maskBuffer);
errNum |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &outputSignalBuffer);
errNum |= clSetKernelArg(kernel, 3, sizeof(cl_uint), &input_.rows);
errNum |= clSetKernelArg(kernel, 4, sizeof(cl_uint), &input_.cols);
errNum |= clSetKernelArg(kernel, 5, sizeof(cl_uint), &maskWidth);

size_t localWorkSize[2] = {16, 16}; // Using 2 dimensional range  with size of work group 16
size_t globalWorkSize[2] = {
    input_
        .rows, // Note: Global work size (input image rows and cols) should be multiple of size of work group.
    input_.cols};

// Queue the kernel up for execution across the array
errNum =
    clEnqueueNDRangeKernel( // enqueue kernel with enabling host blocking until finishing kernel execution
        queue, kernel, 2, NULL, globalWorkSize, localWorkSize, 0, NULL, NULL);
checkErr(errNum, "clEnqueueNDRangeKernel");

Mat output_ = cv::Mat(input_.rows, input_.cols, CV_8UC1);

errNum = clEnqueueReadBuffer( //  reading from ourput parameter of kernel
    queue, outputSignalBuffer, CL_TRUE, 0, input_.rows *input_.cols *input_.elemSize(),
    output_.data, // initialize OpenCV Mat by output_.data which contains output results of kernel
    0, NULL, NULL);
checkErr(errNum, "clEnqueueReadBuffer");

// cut the extra border spaces which has been added in the first part of the code in order to adjust image
// size with Work Group Size;

cv::imwrite("output.bmp", output_); // saving output in image file

Kernel code:

__kernel void convolve(const __global uchar *const input, __constant uint *const mask,
                       __global uchar *const output, const int inputHeight, const int inputWidth,
                       const int maskWidth) {
  uint sum = 0;

  const int curr_x = get_global_id(0); // current curr_x (row)
  const int curr_y = get_global_id(1); // current curr_y (col)
  int d = maskWidth / 2;

  if (curr_x > d - 1 && curr_y > d - 1 && curr_x < inputHeight - d &&
      curr_y < inputWidth - d) // checking mask borders not to be out of input matrix
    for (int i = -d; i <= d; i++)
      for (int j = -d; j <= d; j++) {
        int mask_ptr =
            maskWidth * (i + d) + (j + d); // you can also use mad24(maskWidth, i+d, j+d) which is faster.
        sum += input[(curr_x + i) * inputWidth + curr_y + j] * mask[mask_ptr];
      }

  sum /= (maskWidth * maskWidth); // miangin gereftan

  sum = clamp(sum, (uint)0, (uint)255); // clamp == min(max(x, minval), maxval)

  output[curr_x * inputWidth + curr_y] = sum;
}


问:
C++ return array without dynamic memory allocation?
I can't find a way to return an array without dynamic memory allocation. I will explain it in detail using an example:

With dynamic memory allocation:

```<code>Device* getConnectedDevices() {
    // scan for devices.
    Device *connectedDevices = new Device[deviceCount]; // Dynamically allocate memory for the Devices
    // Get for each device an ID
    return connectedDevices;
}
void doSomething() {
    // some code
    // I need a list with all the connected devices!!
    Device *connectedDevices;
    connectedDevices = getConnectedDevices();
    // do something with the array
}
</code>```

doSomething() don't know the size of the array, so i used a struct to solve that problem:

```<code>struct deviceArray {
    Device* devices;
    int deviceCount;
};
</code>```

Without dynamic memory allocation:
I have no idea how to do this. I tried the following things:

Pass by reference. Problem: we don't know the array size before scanning.

Return without dynamic memory allocation (local variable) . Problem: the object no longer exist (of course).

答:
You don't need to new anything for this,

```<code>std::vector<Device> getConnectedDevices()
{
    std::vector<Device> devices;
    // Fill `devices' with devices.push_back()
    return devices;
}
</code>```

you can iterate through the list of devices in many different ways, usng iterators for instance.

Normally you don't need pointers at all in c++, if you know how to use references and STL containers, you can do anything you want without a single pointer. There are cases however where it does make sense to use pointers but I doubt this is one of such.

Body:
I can't find a way to return an array without dynamic memory allocation. I will explain it in detail using an example:

With dynamic memory allocation:

Device* getConnectedDevices() {
    // scan for devices.
    Device *connectedDevices = new Device[deviceCount]; // Dynamically allocate memory for the Devices
    // Get for each device an ID
    return connectedDevices;
}
void doSomething() {
    // some code
    // I need a list with all the connected devices!!
    Device *connectedDevices;
    connectedDevices = getConnectedDevices();
    // do something with the array
}

doSomething() don't know the size of the array, so i used a struct to solve that problem:

struct deviceArray {
    Device* devices;
    int deviceCount;
};

Without dynamic memory allocation:
I have no idea how to do this. I tried the following things:

Pass by reference. Problem: we don't know the array size before scanning.

Return without dynamic memory allocation (local variable) . Problem: the object no longer exist (of course).

Body:
You don't need to new anything for this,

std::vector<Device> getConnectedDevices()
{
    std::vector<Device> devices;
    // Fill `devices' with devices.push_back()
    return devices;
}

you can iterate through the list of devices in many different ways, usng iterators for instance.

Normally you don't need pointers at all in c++, if you know how to use references and STL containers, you can do anything you want without a single pointer. There are cases however where it does make sense to use pointers but I doubt this is one of such.


问:
how to parse json into php
i have a json data retrieved from data base i.e```<code>$result=array();
$query="SELECT * FROM fish";
$result1 = mysql_query($query, $conn);
while ($table = mysql_fetch_array($result1, MYSQL_ASSOC)){
   $result[]=$table;
}
   echo json_encode($result);</code>```
and this give me the result ```[{"fish_id":"1","name":"first fish update","info":"this is my first fish update","image":"http:\/\/www.localhost\/cafe\/pics\/logout (1).gif"}]```

but from another page when i call this json data i.e```$input = file_get_contents("http://localhost/fish/fish-json.php");
$json=json_decode($input);
echo $json->fish_id;```

it give me the error

```Notice: Trying to get property of non-object in /var/www/fish/json-to-php.php on line 13 Call Stack: 0.0005 318764 1. {main}() /var/www/fish/json-to-php.php:0```

答:
By default json_decode returns an stdClass object.
You have to give a second parameter for this function TRUE.</p>

```<code>$json=json_decode($input, TRUE);
echo $json[0]['fish_id'];
</code>```

Title: how to parse json into php

Body:
i have a json data retrieved from data base i.e
$result=array();
$query="SELECT * FROM fish";
$result1 = mysql_query($query, $conn);
while ($table = mysql_fetch_array($result1, MYSQL_ASSOC)){
   $result[]=$table;
}
   echo json_encode($result);

and this give me the result
[{"fish_id":"1","name":"first fish update","info":"this is my first fish update","image":"http:\/\/www.localhost\/cafe\/pics\/logout (1).gif"}]

but from another page when i call this json data i.e
$input = file_get_contents("http://localhost/fish/fish-json.php");
$json=json_decode($input);
echo $json->fish_id;

it give me the error

Notice: Trying to get property of non-object in /var/www/fish/json-to-php.php on line 13 Call Stack: 0.0005 318764 1. {main}() /var/www/fish/json-to-php.php:0

Body:
By default json_decode returns an stdClass object.
You have to give a second parameter for this function TRUE.

$json=json_decode($input, TRUE);
echo $json[0]['fish_id'];


问:
How to get the string out of a box which a user has inputted into? Tkinter Python
Hello i am making a log in program on tkinter and i am having trouble when using the box widget where the user is able to input a string. i am trying to take that string out and store it in a variable ready for another time but the way i am trying to do it doesn't actually save anything, is there something that im doing wrong?</p>

```<code> from tkinter import *
 Wsignup = Tk()
 Wsignup.title('Sign up')

 UserLabel = Label(Wsignup, text = "Please enter your new username: ")
 UserLabel.grid(row = 1, column = 1, sticky = E)
 UserEntry = Entry(Wsignup)
 UserEntry.grid(row = 1, column = 2, sticky = E)
 Username = UserEntry.get()

 PassLabel = Label(Wsignup, text = "Please enter your new password: ")
 PassLabel.grid(row = 2, column = 1, sticky = E)
 PassEntry = Entry(Wsignup, show = '*')
 PassEntry.grid(row = 2, column = 2, sticky = E)
 Password = PassEntry.get()
</code>```

答:
You are calling get() before the user had a chance to enter something. Add a Button and call get() in a callback function instead:

```<code>def callback():
    # global Username, Password # if you want to set global variables
    Username = UserEntry.get()
    Password = PassEntry.get()
    print(Username, Password) # or whatever you need to do with them

Button(Wsignup, text="Login", command=callback).grid(row=3,column=1)
</code>```

Body:
Hello i am making a log in program on tkinter and i am having trouble when using the box widget where the user is able to input a string. i am trying to take that string out and store it in a variable ready for another time but the way i am trying to do it doesn't actually save anything, is there something that im doing wrong?

 from tkinter import *
 Wsignup = Tk()
 Wsignup.title('Sign up')

 UserLabel = Label(Wsignup, text = "Please enter your new username: ")
 UserLabel.grid(row = 1, column = 1, sticky = E)
 UserEntry = Entry(Wsignup)
 UserEntry.grid(row = 1, column = 2, sticky = E)
 Username = UserEntry.get()

 PassLabel = Label(Wsignup, text = "Please enter your new password: ")
 PassLabel.grid(row = 2, column = 1, sticky = E)
 PassEntry = Entry(Wsignup, show = '*')
 PassEntry.grid(row = 2, column = 2, sticky = E)
 Password = PassEntry.get()

Body:
You are calling get() before the user had a chance to enter something. Add a Button and call get() in a callback function instead:

def callback():
    # global Username, Password # if you want to set global variables
    Username = UserEntry.get()
    Password = PassEntry.get()
    print(Username, Password) # or whatever you need to do with them

Button(Wsignup, text="Login", command=callback).grid(row=3,column=1)


问:
chrome.proxy API for Firefox WebExtensions
Does Firefox WebExtensions support an API to change proxy preferences (like the chrome.proxy API)?

Does Mozilla have plans to add it?

答:
Yes. Starting from 55th Firefox it will be possible.
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/proxy

Keep in mind, this API absolutely different from Chrome version.

For code split use typeof browser === 'undefined'


答:
In general it is not possible to do so without dynamic memory allocation.

The problems that arise with that (keeping track of the size, correct deallocation, etc.) are common.

These problems you describe are solved in c++ using container classes and dynamic memory management smart pointers.

In your case it would be appropriate to use a std::vector<Device> to represent the list of devices and hide the details and complications of dynamic memory management from you.

Title: C++ return array without dynamic memory allocation?


问:
Using FLAG_KEEP_SCREEN_ON across the Android system
The goal of my app is to keep the screen on across the whole Android system. Previously, I've used FULL_WAKE_LOCK for this and it allowed me to block dimming of the screen across  the system. However, since the API Level 17, it got deprecated:

This constant was deprecated in API level 17. Most applications should
  use FLAG_KEEP_SCREEN_ON instead of this type of wake lock, as it will
  be correctly managed by the platform as the user moves between
  applications and doesn't require a special permission.

Official documentation recommends using FLAG_KEEP_SCREEN_ON, however it is possible to use it only for particular Activity.

I would still FULL_WAKE_LOCK, however I've found that it doesn't work now on some of the devices, like MediaPad Huawei x2, Redmi Note 3, etc. The way I'm currently using the PowerManager can be found on GitHub. Is there any better way to do accomplish this task after API level 17?

答:
Starting with API 23 and its new Doze mode Wake Locks are ignored and they do not prevent the system from entering sleep.

You should experiment with maintaining a foreground service in parallel with the wake lock, theoretically that should prevent the device from entering sleep.

NOTE: the foreground Service has to call startForeground and show a non dismissable Notification


问:
How to copy files
How do I copy a file in Python?</p>

答:
You can use one of the copy functions from the shutil package:

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Function              preserves     supports          accepts     copies other
                      permissions   directory dest.   file obj    metadata
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
<a href="https://docs.python.org/3/library/shutil.html#shutil.copy" rel="noreferrer">shutil.copy</a>              ✔             ✔                 ☐           ☐
<a href="https://docs.python.org/3/library/shutil.html#shutil.copy2" rel="noreferrer">shutil.copy2</a>             ✔             ✔                 ☐           ✔
<a href="https://docs.python.org/3/library/shutil.html#shutil.copyfile" rel="noreferrer">shutil.copyfile</a>          ☐             ☐                 ☐           ☐
<a href="https://docs.python.org/3/library/shutil.html#shutil.copyfileobj" rel="noreferrer">shutil.copyfileobj</a>       ☐             ☐                 ✔           ☐
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```

Example:

```<code>import shutil
shutil.copy('/etc/hostname', '/var/tmp/testhostname')
</code>```

OwnerDisplayName: Matt

Title: How to copy files

Body: How do I copy a file in Python?

LastEditorDisplayName: Matt

Body:
You can use one of the copy functions from the shutil package:

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Function              preserves     supports          accepts     copies other
                      permissions   directory dest.   file obj    metadata
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
shutil.copy              ✔             ✔                 ☐           ☐
shutil.copy2             ✔             ✔                 ☐           ✔
shutil.copyfile          ☐             ☐                 ☐           ☐
shutil.copyfileobj       ☐             ☐                 ✔           ☐
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Example:

import shutil
shutil.copy('/etc/hostname', '/var/tmp/testhostname')


问:
Tmux not using my Powerline characters
I have been trying to update tmux and add Powerline character support in it. I am currently using oh-my-zsh with 'agnoster' theme and powerline characters and prompt are getting displayed as they should but when i start tmux session, those character on prompt disappears and _ is replaced with them.What can i do to rectify it.

My tmux.conf

Using ubuntu 16.04

Output of echo $TERM is screen-256color.

Not using tmux-powerline as it's no longer maintained.

I have also tried reinstalling Powerline.

答: Instead of source "/usr/local/lib/python2.7/dist-packages/powerline/bindings/tmux/powerline.conf" you should use run 'powerline-config tmux setup', which should do all the automagic for you without explicily naming paths. You can give it a try by simply executing it in your shell after starting tmux.

Title: Tmux not using my Powerline characters


问:
How to save the data into File in java?
I have one problem, that is I have one string of data and I want to save it into a separate file every time. Please give me a suggestion.

Thanks,
vara kumar.pjd

答: One solution can be, use a random number generator to generate a random number. Use this random number with some text as a filename. Maintain a list of already used names and each time you are saving the file, check through this list if the file name is unique.</p>

Title: How to save the data into File in java?