问:
Hosted server is not providing any data to Android app
I've been working on an Android project where I want to show all the data those are stored in the database. I've done that part already but the problem is I'm able to get the data from localhost but when I move to the hosted server it is not giving me any data. I've connected to the server and am able to access the specific php file but it is returning an empty JSON string where there are a of data.

Here is my Connection Class:

```<code>public class Connecter {

public static HttpURLConnection connect (String urlAddress){

    try {
        URL  url = new URL(urlAddress);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        ///////Setting properties to con object
        con.setRequestMethod("POST");
        con.setConnectTimeout(20000);
        con.setReadTimeout(20000);

        con.setDoInput(true);
        con.setDoOutput(true);
        ////////Returning the Con object
        return con;

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

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

I'm posting using another class.
And here is the process I'm using to pass the url of the specific php file:

```<code>String address2 = "http://www.tutorshubbd.com/android/allTeacher.php";
    Log.d(TAG," .............///..........Primary Data Display ");
    String query = "";
    SendGetAllTeachers sg2 = new SendGetAllTeachers(ActivityTeacher.this,address2,query,listViewTeachers,ivNoData,ivNoInternet);
    sg2.execute();
</code>```

Here is the specific php file that I'm using:

<?php

$host ='tutorshubbd.com';
$username = 'cpanel_username';
$pwd = 'cpanel_password';
$db = 'tutorshu_db';

$con = mysqli_connect($host, $username, $pwd, $db) or die('Unable to connect');

if (mysqli_connect_error($con)) {
 echo "Failed to connect to the DataBase".mysqli_connect_error();

}

$name = $_POST['Query'];

$sql = "SELECT * FROM Teacher WHERE Name LIKE '%$name%'";

$query = mysqli_query($con, $sql);

if ($query) {
 while ($row = mysqli_fetch_array($query)) {
  $data[] = $row;
 }
 print(json_encode($data));

}else{
 echo "Not Found!";
}
mysqli_close($con);

?>```
</div>
</div>
</p>

<p>Here is some additional code where I'm posting and fetching data. (I'm having no trouble fetching data from localhost using this code but putting this just because if you need to see it to figure out the issue).</p>

```public class SendGetAllTeachers extends AsyncTask<Void,Void,String> {

private static final String TAG ="ActivityTeacher";
private Context context;
private String urlAddress;
private String query;
private ListView listView;
private ImageView imageViewNoData, imageViewNoSignal;
private ProgressDialog progressDialog;

public SendGetAllTeachers(Context context, String urlAddress, String query, ListView listView, ImageView...imageViews) {
    this.context = context;
    this.urlAddress = urlAddress;
    this.query = query;
    this.listView = listView;

    this.imageViewNoData=imageViews[0];
    this.imageViewNoSignal=imageViews[1];
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    progressDialog = new ProgressDialog(context);
    progressDialog.setTitle("Search:");
    progressDialog.setMessage("Searching for Data...");
    progressDialog.show();
}

@Override
protected String doInBackground(Void... params) {
    return this.sendAndReceive();
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    progressDialog.dismiss();

    //RESET LISTVIEW
    listView.setAdapter(null);

    if (s != null){
        if (!s.contains("null")){
            ParserTeacher parserT = new ParserTeacher(context,s,listView);
            parserT.execute();

            imageViewNoData.setVisibility(View.INVISIBLE);
            imageViewNoSignal.setVisibility(View.INVISIBLE);

        }else{
            Log.d(TAG,"......//////////.........///////// Getting Visible ......... NO DATA______AT");
            Toast.makeText(context, "Sorry! No Such Data Exists.", Toast.LENGTH_SHORT).show();
        }

    }else {
        imageViewNoData.setVisibility(View.INVISIBLE);
        Toast.makeText(context, "Sorry! Unable to connect to the server.", Toast.LENGTH_SHORT).show();
        imageViewNoSignal.setVisibility(View.INVISIBLE);
    }

}

private String sendAndReceive(){
    HttpURLConnection con = Connecter.connect(urlAddress);
    if(con == null)
        return null;

    try {
        OutputStream outputStream = con.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        Log.d(TAG,"......//////////.........///////// WRITING DATA ......... FIRED______");
        bufferedWriter.write(new DataPackager(query).packageData());

        Log.d(TAG,"......//////////.........///////// NOT WORKING___!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        bufferedWriter.flush();
        //Release Resources.
        bufferedWriter.close();
        outputStream.close();

        //Response Code
        int responseCode = con.getResponseCode();
        //Decoding response code
        if (responseCode == con.HTTP_OK){

            //Return Data
            InputStream inputStream = con.getInputStream();

            //Read the returned data...
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            Log.d(TAG,"......//////////.........///////// DATA READ......... FIRED______");
            StringBuffer response = new StringBuffer();

            if (bufferedReader!=null){
                while((line = bufferedReader.readLine())!=null){

                    response.append(line+"\n");
                }

            }else
                return null;
            return response.toString();

        }else
            return String.valueOf(responseCode);

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

    return null;
}

}
```

<p>////////////////////////////////</p>

```public class DataPackager {

String query;

public DataPackager(String query) {
    this.query = query;
}

public String packageData(){

    JSONObject jsonObject = new JSONObject();
    StringBuffer queryStringBuffer = new StringBuffer();

    try {
        jsonObject.put("Query", query);
        Boolean fistValue = true;
        Iterator iterator = jsonObject.keys();

        do {
            String key = iterator.next().toString();
            String value = jsonObject.get(key).toString();

            if (fistValue){
                fistValue = false;
            }else{
                queryStringBuffer.append("&");
            }

            queryStringBuffer.append(URLEncoder.encode(key,"UTF-8"));
            queryStringBuffer.append("=");
            queryStringBuffer.append(URLEncoder.encode(value,"UTF-8"));

        }while (iterator.hasNext());

        return queryStringBuffer.toString();

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

    return null;
}

}
```

<p>///////////////////////////////</p>

```public class ParserTeacher extends AsyncTask<Void,Void,Integer> {
public static final String TAG = "Parser Teacher";

    private Context c;
    private String data;
    private ListView lv;

    List<GetItems> items = new ArrayList<>();

    public ParserTeacher(Context c, String data, ListView lv) {
        this.c = c;
        this.data = data;
        this.lv = lv;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Integer doInBackground(Void... params){
        return this.parse();
    }

    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);

        if (integer ==1 ){
            ///////BIND TO LIST VIEW...............................
            CustomAdapter adapter = new CustomAdapter(c, items);
            lv.setAdapter(adapter);

            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                    GetItems sendItem = items.get(i);

                    String name = sendItem.getName();

                    //Snackbar.make(view,"Teachers Detail Mode",Snackbar.LENGTH_LONG).show();

                    Intent I = new Intent();
                    I.setClass(view.getContext(),TeachersView.class);
                    Bundle extras = new Bundle();
                    extras.putString("Name", name);

                    I.putExtras(extras);
                    view.getContext().startActivity(I);

                }
            });

        }else{
            Log.d(TAG," >>>>>>>>>>>>>>>>>>>>>>>>>>>> Parsing Error!");
            Toast.makeText(c, "Unable to Parse...!", Toast.LENGTH_SHORT).show();

        }

    }

    private int parse(){

        try{
            JSONArray ja = new JSONArray(data);

            //Log.i("tagconvertstr","............................................\n\n"+ "["+ja+"]");
            JSONObject jo = null;
            items.clear();

            GetItems getItems = null;

            for (int i=0; i<ja.length();i++){
                jo=ja.getJSONObject(i);

                String name = jo.getString("Name");

                getItems = new GetItems();

                getItems.setName(name);

                items.add(getItems);

            }

            return 1;

        } catch (JSONException e) {
            Log.d(TAG,"Here is the STACK TRACE.........>>>>>>>>>>>>>>>>>>>>>>>>>>>");
            e.printStackTrace();
        }
        return 0;
    }
    }
```

(I'm having no trouble fetching data in localhost using this code).

if you load the url you will see that there are a lot of data(could take time to load sometimes) but in the app It is returning an empty string. I'm not using any libraries like volley or retrofit.

I've seen a lot of issues regarding this but this is slightly different from them. I'm being able to connect but not fetch from hosted server but I'm able to fetch from local host.

答:
Your response header doesn't have Content-Type values. You have to add to your php code, this line before print the data.</p>

```<code>header('Content-type:application/json;charset=utf-8');
</code>```

Body:
I've been working on an Android project where I want to show all the data those are stored in the database. I've done that part already but the problem is I'm able to get the data from localhost but when I move to the hosted server it is not giving me any data. I've connected to the server and am able to access the specific php file but it is returning an empty JSON string where there are a of data.

Here is my Connection Class:

public class Connecter {

public static HttpURLConnection connect (String urlAddress){

    try {
        URL  url = new URL(urlAddress);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        ///////Setting properties to con object
        con.setRequestMethod("POST");
        con.setConnectTimeout(20000);
        con.setReadTimeout(20000);

        con.setDoInput(true);
        con.setDoOutput(true);
        ////////Returning the Con object
        return con;

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
    }
}

I'm posting using another class.
And here is the process I'm using to pass the url of the specific php file:

String address2 = "http://www.tutorshubbd.com/android/allTeacher.php";
    Log.d(TAG," .............///..........Primary Data Display ");
    String query = "";
    SendGetAllTeachers sg2 = new SendGetAllTeachers(ActivityTeacher.this,address2,query,listViewTeachers,ivNoData,ivNoInternet);
    sg2.execute();

Here is the specific php file that I'm using:

<?php

$host ='tutorshubbd.com';
$username = 'cpanel_username';
$pwd = 'cpanel_password';
$db = 'tutorshu_db';

$con = mysqli_connect($host, $username, $pwd, $db) or die('Unable to connect');

if (mysqli_connect_error($con)) {
 echo "Failed to connect to the DataBase".mysqli_connect_error();

}

$name = $_POST['Query'];

$sql = "SELECT * FROM Teacher WHERE Name LIKE '%$name%'";

$query = mysqli_query($con, $sql);

if ($query) {
 while ($row = mysqli_fetch_array($query)) {
  $data[] = $row;
 }
 print(json_encode($data));

}else{
 echo "Not Found!";
}
mysqli_close($con);

?>

Here is some additional code where I'm posting and fetching data. (I'm having no trouble fetching data from localhost using this code but putting this just because if you need to see it to figure out the issue).

public class SendGetAllTeachers extends AsyncTask<Void,Void,String> {

private static final String TAG ="ActivityTeacher";
private Context context;
private String urlAddress;
private String query;
private ListView listView;
private ImageView imageViewNoData, imageViewNoSignal;
private ProgressDialog progressDialog;

public SendGetAllTeachers(Context context, String urlAddress, String query, ListView listView, ImageView...imageViews) {
    this.context = context;
    this.urlAddress = urlAddress;
    this.query = query;
    this.listView = listView;

    this.imageViewNoData=imageViews[0];
    this.imageViewNoSignal=imageViews[1];
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    progressDialog = new ProgressDialog(context);
    progressDialog.setTitle("Search:");
    progressDialog.setMessage("Searching for Data...");
    progressDialog.show();
}

@Override
protected String doInBackground(Void... params) {
    return this.sendAndReceive();
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    progressDialog.dismiss();

    //RESET LISTVIEW
    listView.setAdapter(null);

    if (s != null){
        if (!s.contains("null")){
            ParserTeacher parserT = new ParserTeacher(context,s,listView);
            parserT.execute();

            imageViewNoData.setVisibility(View.INVISIBLE);
            imageViewNoSignal.setVisibility(View.INVISIBLE);

        }else{
            Log.d(TAG,"......//////////.........///////// Getting Visible ......... NO DATA______AT");
            Toast.makeText(context, "Sorry! No Such Data Exists.", Toast.LENGTH_SHORT).show();
        }

    }else {
        imageViewNoData.setVisibility(View.INVISIBLE);
        Toast.makeText(context, "Sorry! Unable to connect to the server.", Toast.LENGTH_SHORT).show();
        imageViewNoSignal.setVisibility(View.INVISIBLE);
    }

}

private String sendAndReceive(){
    HttpURLConnection con = Connecter.connect(urlAddress);
    if(con == null)
        return null;

    try {
        OutputStream outputStream = con.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        Log.d(TAG,"......//////////.........///////// WRITING DATA ......... FIRED______");
        bufferedWriter.write(new DataPackager(query).packageData());

        Log.d(TAG,"......//////////.........///////// NOT WORKING___!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        bufferedWriter.flush();
        //Release Resources.
        bufferedWriter.close();
        outputStream.close();

        //Response Code
        int responseCode = con.getResponseCode();
        //Decoding response code
        if (responseCode == con.HTTP_OK){

            //Return Data
            InputStream inputStream = con.getInputStream();

            //Read the returned data...
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            Log.d(TAG,"......//////////.........///////// DATA READ......... FIRED______");
            StringBuffer response = new StringBuffer();

            if (bufferedReader!=null){
                while((line = bufferedReader.readLine())!=null){

                    response.append(line+"\n");
                }

            }else
                return null;
            return response.toString();

        }else
            return String.valueOf(responseCode);

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

    return null;
}

}

////////////////////////////////

public class DataPackager {

String query;

public DataPackager(String query) {
    this.query = query;
}

public String packageData(){

    JSONObject jsonObject = new JSONObject();
    StringBuffer queryStringBuffer = new StringBuffer();

    try {
        jsonObject.put("Query", query);
        Boolean fistValue = true;
        Iterator iterator = jsonObject.keys();

        do {
            String key = iterator.next().toString();
            String value = jsonObject.get(key).toString();

            if (fistValue){
                fistValue = false;
            }else{
                queryStringBuffer.append("&");
            }

            queryStringBuffer.append(URLEncoder.encode(key,"UTF-8"));
            queryStringBuffer.append("=");
            queryStringBuffer.append(URLEncoder.encode(value,"UTF-8"));

        }while (iterator.hasNext());

        return queryStringBuffer.toString();

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

    return null;
}

}

///////////////////////////////

public class ParserTeacher extends AsyncTask<Void,Void,Integer> {
public static final String TAG = "Parser Teacher";

    private Context c;
    private String data;
    private ListView lv;

    List<GetItems> items = new ArrayList<>();

    public ParserTeacher(Context c, String data, ListView lv) {
        this.c = c;
        this.data = data;
        this.lv = lv;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Integer doInBackground(Void... params){
        return this.parse();
    }

    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);

        if (integer ==1 ){
            ///////BIND TO LIST VIEW...............................
            CustomAdapter adapter = new CustomAdapter(c, items);
            lv.setAdapter(adapter);

            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                    GetItems sendItem = items.get(i);

                    String name = sendItem.getName();

                    //Snackbar.make(view,"Teachers Detail Mode",Snackbar.LENGTH_LONG).show();

                    Intent I = new Intent();
                    I.setClass(view.getContext(),TeachersView.class);
                    Bundle extras = new Bundle();
                    extras.putString("Name", name);

                    I.putExtras(extras);
                    view.getContext().startActivity(I);

                }
            });

        }else{
            Log.d(TAG," >>>>>>>>>>>>>>>>>>>>>>>>>>>> Parsing Error!");
            Toast.makeText(c, "Unable to Parse...!", Toast.LENGTH_SHORT).show();

        }

    }

    private int parse(){

        try{
            JSONArray ja = new JSONArray(data);

            //Log.i("tagconvertstr","............................................\n\n"+ "["+ja+"]");
            JSONObject jo = null;
            items.clear();

            GetItems getItems = null;

            for (int i=0; i<ja.length();i++){
                jo=ja.getJSONObject(i);

                String name = jo.getString("Name");

                getItems = new GetItems();

                getItems.setName(name);

                items.add(getItems);

            }

            return 1;

        } catch (JSONException e) {
            Log.d(TAG,"Here is the STACK TRACE.........>>>>>>>>>>>>>>>>>>>>>>>>>>>");
            e.printStackTrace();
        }
        return 0;
    }
    }

(I'm having no trouble fetching data in localhost using this code).

if you load the url you will see that there are a lot of data(could take time to load sometimes) but in the app It is returning an empty string. I'm not using any libraries like volley or retrofit.

I've seen a lot of issues regarding this but this is slightly different from them. I'm being able to connect but not fetch from hosted server but I'm able to fetch from local host.

Body:
Your response header doesn't have Content-Type values. You have to add to your php code, this line before print the data.

header('Content-type:application/json;charset=utf-8');


来源: stackexchange

问:
Call (show) a modal popup located in MasterPage from it's childs
I'm trying to make a default modal box that must be accessible from any part of the application, and need to be called whenever I want from inside any page. (must be called from code-behind).

So I came up with the idea of a Panel + modalPopupExtender placed in the MasterPage, and calling it from child pages via code-behind.

How can I do that? Or perhaps you guys have a better idea to solve this.

答:
Add a method to your Master page. For example:

```<code>public void ShowMpSignup4free()
{
    mpSignup4free.Show();
}
</code>```

Then call this method from the code behind page like this:

```<code>protected void lbSignin_Click(object sender, EventArgs e)
{
    MasterPages_WebMasterPage wm = (MasterPages_WebMasterPage)(this.Master);
    wm.ShowMpSignup4free();
}
</code>```

Here mpSignup4free is ID of ModelPopupExtender and MasterPages_WebMasterPage is name of master page (WebMasterPage is name of master page placed in folder MasterPages. That is why the complete name of master page is MasterPages_WebMasterPage).

and lbSignin is Link button on the page whose master page is WebMasterPage  to whose click event will show the model popup.

For avoiding post back place the lbSignin link button in UpdatePanel...

ContentLicense: CC BY-SA 2.5

Body:
Add a method to your Master page. For example:

public void ShowMpSignup4free()
{
    mpSignup4free.Show();
}

Then call this method from the code behind page like this:

protected void lbSignin_Click(object sender, EventArgs e)
{
    MasterPages_WebMasterPage wm = (MasterPages_WebMasterPage)(this.Master);
    wm.ShowMpSignup4free();
}

Here mpSignup4free is ID of ModelPopupExtender and MasterPages_WebMasterPage is name of master page (WebMasterPage is name of master page placed in folder MasterPages. That is why the complete name of master page is MasterPages_WebMasterPage).

and lbSignin is Link button on the page whose master page is WebMasterPage  to whose click event will show the model popup.

For avoiding post back place the lbSignin link button in UpdatePanel...

ContentLicense: CC BY-SA 3.0


问:
Concurrent requests handling on Google App Engine
I was experimenting with concurrent request handling on few platforms.

The aim of the experiment was to have a broad measure of the capacity bounds of some selected technologies.

I set up a Linux VM on my machine with a basic Go http server (the vanilla http.HandleFunc of the http default package).
The server would then compute a modified version of the fasta algorithm that restricted threads and processes to 1, and return the result. N was set to 100000.
The algorithm runs in roughly 2 seconds.
I used the same algorithm and logic on a Google App Engine project.

The algorithm is written using the same code, just the handler set up is done on init() instead of main() as per GAE requirements.

On the other end an Android client is spawning 500 threads each one issuing in parallel a GET request to the fasta computing server, with a request timeout of 5000 ms.

I was expecting the GAE application to scale and answer back to each request and the local Go server to fail on some of the 500 requests but results were the opposite:
the local server correctly replied to each request within the timeout bounds while the GAE application was able to handle just 160 requests out of 500. The remaining requests timed out.

I checked on the Cloud Console and I verified that 18 GAE instances were spawned, but still the vast majority of requests failed.

I thought that most of them failed because of the start-up time of each GAE instance, so I repeated the experiment right after but I had the same results: most of the requests timed out.

I was expecting GAE to scale to accomodate ALL the requests, believing that if a single local VM could successfully reply to 500 concurrent requests GAE would have done the same, but this is not what happened.

The GAE console doesn't show any error and correctly reports the number of incoming requests.

What could be the cause of this?
Also, if a single instance could handle all the incoming requests on my machine by virtue of only goroutines, how come that GAE needed to scale so much at all?

答:
To make optimal usage in terms of minimizing costs you need to configure few things in app.yaml:

Enable threadsafe: true - actually it's from Python config and not applicable to Go but I would set it just in case.

Adjust scaling section:

max_concurrent_requests - set to maximum 80

max_idle_instances - set to minimum 0

max_pending_latency -  set it to automatic or greater then min_pending_latency

min_idle_instances - set it to 0

min_pending_latency - set to higher number. If you are OK to get 1 second latency and you handlers take on average 100ms to process set it to 900ms.

Then you should be able to proceed a lot of request on single instance.

If you OK to burn cash for the sake of responsiveness & scalabiluty - increase min_idle_instances & max_idle_instances.

Also do you use similar instance types for VM and GAE? The GAE F1 instance is not too fast and is more optimal for async tasks like working with IO (datastore,http,etc.). You can configure usage of more powerful instance to better scale for computation intensive tasks.

Also do you test on paid account? Free accounts have quotas and AppEngine would refuse percentage of requests if it believe the load would exceed the daily quota if continuous with the same pattern.


问:
Get conversation list using Sinch API & iOS SDK
I have to develop a messaging app and I came across this Sinch messaging SDK. I had downloaded the iOS SDK and tried the Sinch Instant Messaging sample app. I was able to send messages and get messages. But I need to know:

Can I get the conversation list using Sinch SDK with latest message for each conversation to show in list?

How can I differentiate the incoming chat messages from different users. In the sample I see only one chat messages screen which populates all the messages from different users. So, do we have any property in Sinch SDK that differentiates the conversations?

Is there any possibility to create group name, group image for group chat? And how will Sinch API will possibly maintain these group chat and single chat message?

答:
you can create the group name, group image for group chat etc features more easily.  Many API SDK's resources are available in an internet market.  For instant communication between users.

Refer to this, you may get an idea:
https://www.quora.com/What-SDKs-APIs-are-viable-for-implementing-instant-messaging-between-clients-Android-iOS-and-web


问:
How to copy a python object/ How to get element of a python object

Question 1:

I need to make a copy of one circle I create

```<code>import matplotlib.pyplot as plt
from matplotlib.patches import Circle
C1=Circle(xy=(3, 4), radius=2, fill=False, color='g')
</code>```

I want to do something like:

```<code>C2 = C1.copy()
</code>```

To be able to modify C2 without modifying C1 but I get the error:

```<code>'AttributeError: 'Circle' object has no attribute 'copy''
</code>```

Does anyone know how to do it?

Question 2:

I try to get the element of C1

```<code>xy = C1.xy
</code>```

AttributeError: 'Circle' object has no attribute 'xy'

```<code>color = C1.color
</code>```

AttributeError: 'Circle' object has no attribute 'color'

For xy, I manage to get it by doing

```<code>xy = C1.center
</code>```

But I do not understand why I have to use center even if I declare it as 'xy'. For color I still don't know how to get it... I thin it is probably a characteristic of a parent object (not specific to the circle object) but how to get it????

答:
Those are two completely different questions.

Copy

You may copy any python element using copy.

```<code>from matplotlib.patches import Circle
from copy import copy

C1=Circle(xy=(3, 4), radius=2, fill=False, color='g')
C2 = copy(C1)

print(C1 == C2)  # prints False
</code>```

Attriutes

Instead of accessing the attributes directly, matplotlib artists provide getters/setters for most of its attributes.

```<code>C1.get_facecolor()
C1.get_edgecolor()
C1.get_radius()
</code>```

It is indeed a little inconsistent that the Circle does not have a .get_center method. So to get the center use

```<code>C1.center
</code>```

Replicate Artist

In order to replicate an artist, you may use its update_from method. This will copy all the styling at once from once artist to the other. It will not update its position.

```<code>import matplotlib.pyplot as plt
from matplotlib.patches import Circle

C1=Circle(xy=(3, 4), radius=2, fill=False, color='g')
C2=Circle(xy=(1, 2), radius=1, fill=True, color='b')

plt.gca().add_patch(C1)
plt.gca().add_patch(C2)

C1.update_from(C2)

plt.show()
</code>```

Body:
Question 1:

I need to make a copy of one circle I create

import matplotlib.pyplot as plt
from matplotlib.patches import Circle
C1=Circle(xy=(3, 4), radius=2, fill=False, color='g')

I want to do something like:

C2 = C1.copy()

To be able to modify C2 without modifying C1 but I get the error:

'AttributeError: 'Circle' object has no attribute 'copy''

Does anyone know how to do it?

Question 2:

I try to get the element of C1

xy = C1.xy

AttributeError: 'Circle' object has no attribute 'xy'

color = C1.color

AttributeError: 'Circle' object has no attribute 'color'

For xy, I manage to get it by doing

xy = C1.center

But I do not understand why I have to use center even if I declare it as 'xy'. For color I still don't know how to get it... I thin it is probably a characteristic of a parent object (not specific to the circle object) but how to get it????

Body:
Those are two completely different questions.

Copy

You may copy any python element using copy.

from matplotlib.patches import Circle
from copy import copy

C1=Circle(xy=(3, 4), radius=2, fill=False, color='g')
C2 = copy(C1)

print(C1 == C2)  # prints False

Attriutes

Instead of accessing the attributes directly, matplotlib artists provide getters/setters for most of its attributes.

C1.get_facecolor()
C1.get_edgecolor()
C1.get_radius()

It is indeed a little inconsistent that the Circle does not have a .get_center method. So to get the center use

C1.center

Replicate Artist

In order to replicate an artist, you may use its update_from method. This will copy all the styling at once from once artist to the other. It will not update its position.

import matplotlib.pyplot as plt
from matplotlib.patches import Circle

C1=Circle(xy=(3, 4), radius=2, fill=False, color='g')
C2=Circle(xy=(1, 2), radius=1, fill=True, color='b')

plt.gca().add_patch(C1)
plt.gca().add_patch(C2)

C1.update_from(C2)

plt.show()


答:
Use a Pivot Table:

.

.

Or, make the same Pivot Table with VBA:

```<code>ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Sheet1!R1C1:R4C2", Version:=6).CreatePivotTable TableDestination:="Sheet1!R1C4", TableName:="PivotTable1"
With ActiveSheet.PivotTables("PivotTable1")
    .PivotFields("Heading 1").Orientation = xlRowField
    .AddDataField ActiveSheet.PivotTables("PivotTable1").PivotFields("Heading 2"), "Sum of Heading 2", xlSum
End With
</code>```

☃

Title: Combine duplicate rows and sum up the next column vba

Body:
How do i find the duplicates in a cloumn and merge them as a single cell and
    add their adjacent columns and show them as a single cell value?
    In short how do i convert table 1 to table 2 format?
   Table 1

|---------------------|------------------|
|      Heading 1      |     Heading 2    |
|---------------------|------------------|
|          12         |         34       |
|---------------------|------------------|
|---------------------|------------------|
|          12         |         54       |
|---------------------|------------------|
|---------------------|------------------|
|          13         |         43       |
|---------------------|------------------|

Table 2

|---------------------|------------------|
|      Heading 1      |     Heading 2    |
|---------------------|------------------|
|          12         |         88       |
|---------------------|------------------|
|---------------------|------------------|
|          13         |         43       |
|---------------------|------------------|

Below is the code i have tried. It just marks the duplicate values as duplicate and i am unable to sum up the values and show them in the previous cell

Sub sbFindDuplicatesInColumn()
Dim lastRow As Long
Dim matchFoundIndex As Long
Dim iCntr As Long
lastRow = Range("A65000").End(xlUp).Row
For iCntr = 1 To lastRow
If Cells(iCntr, 1) <> "" Then
matchFoundIndex = WorksheetFunction.Match(Cells(iCntr, 1), Range("A1:A" &
lastRow), 0)
If iCntr <> matchFoundIndex Then
Cells(iCntr, 2) = "Duplicate"
End If
End If
Next
End Sub

Body:
Use a Pivot Table:

.

.

Or, make the same Pivot Table with VBA:

ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Sheet1!R1C1:R4C2", Version:=6).CreatePivotTable TableDestination:="Sheet1!R1C4", TableName:="PivotTable1"
With ActiveSheet.PivotTables("PivotTable1")
    .PivotFields("Heading 1").Orientation = xlRowField
    .AddDataField ActiveSheet.PivotTables("PivotTable1").PivotFields("Heading 2"), "Sum of Heading 2", xlSum
End With

☃


问:
Can I simplify this Rust code dealing with Option<T> and Result<T>?
I'm working on my first actual Rust program, a custom i3status. It's coming along nicely, but there's two places where I have to deal with Result<T> and Option<T> and the code looks really ugly, leading me to believe that I've missed some language feature or library function for writing these parts more cleanly.

This is the file in question, but I'll quote the relevant parts here. The first one is this:

```<code>fn read_number_from_file(path: &str) -> Option<i64> {
    let mut file = match File::open(path) {
        Ok(f) => f,
        Err(_) => return None,
    };
    let mut contents = String::new();
    match file.read_to_string(&mut contents) {
        Ok(_) => {},
        Err(_) => return None,
    };
    match contents.trim().parse::<i64>() {
        Ok(val) => Some(val),
        Err(_) => None,
    }
}
</code>```

Swallowing error messages here is intentional. An i3status does not have an stderr, so all I can do is skip rendering of the broken parts.

Regardless of that, this code looks ugly, with its repeated use of match to discard Err values. I tried to use the new ? operator by making the return type a std::io::Result<i64>, but str::parse returns a different type of error, so that doesn't work AFAICS. I therefore went with Option<i64> as the lowest common denominator.

The second ugly part is where this function gets used:

```<code>let energy_full = match read_number_from_file(ENERGY_FULL_PATH) {
    Some(val) => val,
    None      => return Vec::new(),
};
let energy_now = match read_number_from_file(ENERGY_NOW_PATH) {
    Some(val) => val,
    None      => return Vec::new(),
};
let is_charging = match read_number_from_file(POWER_ONLINE_PATH) {
    Some(val) => val > 0,
    None      => return Vec::new(),
};
</code>```

I feel like one should be able to contract each of the match expressions into a function call like .or_else(), but .or_else(|| return Vec::new()) obviously won't work since the return is scoped to the lambda instead of the original function.

So, in both cases, my question is whether I can replace match by something more compact and idiomatic.

答:
For the second part, you can use one of the comprehension crates available on crates.io like map_for, comp or mdo. For example with map_for:

```<code>return map_for!(
    energy_full  <- read_number_from_file(ENERGY_FULL_PATH);
    energy_now   <- read_number_from_file(ENERGY_NOW_PATH);
    power_online <- read_number_from_file(POWER_ONLINE_PATH);
    is_charging  = power_online > 0;
    => vec![ energy_full, energy_now ]
).unwrap_or_else (|| vec![]);
</code>```

Full disclosure: I am the author of the map_for crate.

Body:
I'm working on my first actual Rust program, a custom i3status. It's coming along nicely, but there's two places where I have to deal with Result<T> and Option<T> and the code looks really ugly, leading me to believe that I've missed some language feature or library function for writing these parts more cleanly.

This is the file in question, but I'll quote the relevant parts here. The first one is this:

fn read_number_from_file(path: &str) -> Option<i64> {
    let mut file = match File::open(path) {
        Ok(f) => f,
        Err(_) => return None,
    };
    let mut contents = String::new();
    match file.read_to_string(&mut contents) {
        Ok(_) => {},
        Err(_) => return None,
    };
    match contents.trim().parse::<i64>() {
        Ok(val) => Some(val),
        Err(_) => None,
    }
}

Swallowing error messages here is intentional. An i3status does not have an stderr, so all I can do is skip rendering of the broken parts.

Regardless of that, this code looks ugly, with its repeated use of match to discard Err values. I tried to use the new ? operator by making the return type a std::io::Result<i64>, but str::parse returns a different type of error, so that doesn't work AFAICS. I therefore went with Option<i64> as the lowest common denominator.

The second ugly part is where this function gets used:

let energy_full = match read_number_from_file(ENERGY_FULL_PATH) {
    Some(val) => val,
    None      => return Vec::new(),
};
let energy_now = match read_number_from_file(ENERGY_NOW_PATH) {
    Some(val) => val,
    None      => return Vec::new(),
};
let is_charging = match read_number_from_file(POWER_ONLINE_PATH) {
    Some(val) => val > 0,
    None      => return Vec::new(),
};

I feel like one should be able to contract each of the match expressions into a function call like .or_else(), but .or_else(|| return Vec::new()) obviously won't work since the return is scoped to the lambda instead of the original function.

So, in both cases, my question is whether I can replace match by something more compact and idiomatic.

Body:
For the second part, you can use one of the comprehension crates available on crates.io like map_for, comp or mdo. For example with map_for:

return map_for!(
    energy_full  <- read_number_from_file(ENERGY_FULL_PATH);
    energy_now   <- read_number_from_file(ENERGY_NOW_PATH);
    power_online <- read_number_from_file(POWER_ONLINE_PATH);
    is_charging  = power_online > 0;
    => vec![ energy_full, energy_now ]
).unwrap_or_else (|| vec![]);

Full disclosure: I am the author of the map_for crate.


问:
Xamarin Label losing text alignment when page returned to
I have a label inside of a stack layout. It has its HorizontalTextAlignment set to TextAlignment.Center. It works correctly on the initial loading of the page, and when a new value is selected - however when the page is left and then returned to, it loses its alignment. This is only a problem on Android and not on iOS. I hope the image below can help illustrate my point. This is the only code that affects the Label's alignment, other than that it's just changing it's text through a binding, but I don't see how that would change it's alignment. Any ideas? Thanks.

StackLayout durationLayout = new StackLayout {
    Orientation = StackOrientation.Vertical,
    WidthRequest = (App.ScreenDpWidth / 3) - (GMStyle.Margin.PageMargin.Left * 2),
    VerticalOptions = LayoutOptions.Center,
    Margin = new Thickness(0, 5, 0, 0),
    HorizontalOptions = LayoutOptions.Start
};
durationLabel = new Label {
    Style = (Style)Application.Current.Resources["DurationLabelStyle"],
    HorizontalTextAlignment = TextAlignment.Center,
    //VerticalTextAlignment = TextAlignment.Center,
};
durationLabel.SetBinding(Label.TextProperty, "DurationDisplay");
durationLayout.Children.Add(timeSpanPicker);
durationLayout.Children.Add(durationLabel);
durationLayout.GestureRecognizers.Add(timeSpanTap);
```

答:
This is bug of xamarin forms. You have to make a custom renderer of label and not to refresh its children drawable state Hope it will work</p>

```<code>public override void ChildDrawableStateChanged(Android.Views.View child)
{
   base.ChildDrawableStateChanged(child);
   Control.Text = Control.Text;
}
</code>```

Body:
This is bug of xamarin forms. You have to make a custom renderer of label and not to refresh its children drawable state Hope it will work

public override void ChildDrawableStateChanged(Android.Views.View child)
{
   base.ChildDrawableStateChanged(child);
   Control.Text = Control.Text;
}


问:
deploying addon in atlassian marketplace
I have created an add-on in jira, in developement mode I uploaded them using localhost link from ngrok (https:// 32570d96.ngrok.io). Referring that URL in links and baseURL(add-on descriptor) as above in atlassian-connect.json.

Now, I have to release the add-on in atlassian marketplace. How can I release the add-on in marketplace(cloud based add-on)?

I have referred this link, for creating fields in addon descriptor: https://developer.atlassian.com/static/connect/docs/latest/modules/#properties

For, uploding the add-on in atlassian marketplace, I followed these steps, as given here:
https://developer.atlassian.com/static/connect/docs/latest/developing/cloud-installation.html

While uploading add-on, it ask for URL of addon descriptor. How to create addon descriptor URL by uploading the atlassian-connect.json in cloud instead of using ngrok(https:// 32570d96.ngrok.io/atlassian-connect.json)

Currently, I use the format of add-on descriptor fields in atlassian-connect.json file, as shown below:

```<code>"baseUrl": "https://253e4f95.ngrok.io",
"links": {
    "self": "https://253e4f95.ngrok.io/atlassian-connect.json",
    "homepage": "https://253e4f95.ngrok.io/atlassian-connect.json"
},
</code>```

答:
While uploading add-on, it ask for URL of addon descriptor. How to create addon descriptor URL by uploading the atlassian-connect.json in cloud instead of using ngrok(https:// 32570d96.ngrok.io/atlassian-connect.json)

ngrok is something that you use for local development and testing(https://developer.atlassian.com/cloud/jira/platform/getting-started/). Obviously you cannot use same links to upload your descriptor in production ( cloud marketplace). You need to put is over some hosting site where your addon descriptor is reachable from a https url and also the certificates are not self signed.

You can use service like heroku to deploy your app/atlassian-connect.json file. You should be able to find able documentation on Heroku web app deployment online.

Being a AWS certified solutions architect I would recommend adding atlassian-connect.json to an S3 bucket and making this object publicly accessible and use the https url of this object to give to market place. Things would be must complicated when you start with actual app deployment in which case you will have to use load balancers and EC2 instances to deploy your server logic.

Body:
I have created an add-on in jira, in developement mode I uploaded them using localhost link from ngrok (https:// 32570d96.ngrok.io). Referring that URL in links and baseURL(add-on descriptor) as above in atlassian-connect.json.

Now, I have to release the add-on in atlassian marketplace. How can I release the add-on in marketplace(cloud based add-on)?

I have referred this link, for creating fields in addon descriptor: https://developer.atlassian.com/static/connect/docs/latest/modules/#properties

For, uploding the add-on in atlassian marketplace, I followed these steps, as given here:
https://developer.atlassian.com/static/connect/docs/latest/developing/cloud-installation.html

While uploading add-on, it ask for URL of addon descriptor. How to create addon descriptor URL by uploading the atlassian-connect.json in cloud instead of using ngrok(https:// 32570d96.ngrok.io/atlassian-connect.json)

Currently, I use the format of add-on descriptor fields in atlassian-connect.json file, as shown below:

"baseUrl": "https://253e4f95.ngrok.io",
"links": {
    "self": "https://253e4f95.ngrok.io/atlassian-connect.json",
    "homepage": "https://253e4f95.ngrok.io/atlassian-connect.json"
},


问:
FF addon toolbar - anything added sits on the right side of the toolbar
I am having a problem with the firefox toolbar that I made. If I drag icons or say the search box onto it they all align to the left side of the toolbar and push over my toolbar icons over to the right. If I move the icons I dragged onto the bar to the right side of my icons they move back to the left side when Firefox restarts. I don't know what I am doing wrong.

Here is my code:

```<code>   <toolbox id="navigator-toolbox">

    <toolbar id="TutTB-Toolbar" toolbarname="FreeLayer Toolbar" accesskey="T"
             class="chromeclass-toolbar" context="toolbar-context-menu"
             hidden="false" mode="icons" persist="hidden" customizable="true" observes="cmd_viewrstb" inherits="hidden" >

        <toolbaritem>
            <toolbarbutton id="Back-MainMenu" type="Plain" oncommand="gBrowser.webNavigation.goBack()"
                           tooltiptext="Back">
            </toolbarbutton>
            <toolbarbutton id="Foward-MainMenu" type="Plain" oncommand="gBrowser.webNavigation.goForward()"
                           tooltiptext="Forward">
            </toolbarbutton>
            <toolbarbutton id="Reload-MainMenu" type="Plain" oncommand="BrowserReloadSkipCache();"
                           tooltiptext="Reload">
            </toolbarbutton>
            <toolbarbutton id="Home-MainMenu" type="Plain" oncommand="window.BrowserHome()"
                           tooltiptext="Home">
            </toolbarbutton>

            <menulist id="TutTB-SearchTerms" editable="true" flex="1"
                      minwidth="100" width="450"
                      onkeypress="objTutorialToolbar.KeyHandler(event);">
                <menupopup id="TutTB-SearchTermsMenu" onpopupshowing="objTutorialToolbar.Populate()" />
            </menulist>

        <splitter id="TutTB-ResizeSplitter" state="open" collapse="none"
                  resizebefore="closest" resizeafter="farthest"
                  tooltiptext="Resize the Search Box">
            <vbox id="TutTB-ResizeBar" />
        </splitter>

            <toolbarbutton id="TutTB-Combined-Button" label="Search"
                           type="Plain" tooltiptext="Search"
                           oncommand="objTutorialToolbar.Search(event, 'web')">

            </toolbarbutton>

             <toolbarbutton id="Loc-MainMenu" type="menu-button"
               tooltiptext="Actual Location">
                 <menupopup>
                    <menuitem id="web-location" label="Actual Location"
                    class="menuitem-iconic" tooltiptext="Actual Location" />
                 </menupopup>
            </toolbarbutton>
        </toolbaritem>

        <toolbarspring />

    </toolbar>
</toolbox>
</code>```

答: Your toolbaritem doesn't have an id which means that the toolbar customisation code can't persist its position.</p>

Body:
I am having a problem with the firefox toolbar that I made. If I drag icons or say the search box onto it they all align to the left side of the toolbar and push over my toolbar icons over to the right. If I move the icons I dragged onto the bar to the right side of my icons they move back to the left side when Firefox restarts. I don't know what I am doing wrong.

Here is my code:

   <toolbox id="navigator-toolbox">

    <toolbar id="TutTB-Toolbar" toolbarname="FreeLayer Toolbar" accesskey="T"
             class="chromeclass-toolbar" context="toolbar-context-menu"
             hidden="false" mode="icons" persist="hidden" customizable="true" observes="cmd_viewrstb" inherits="hidden" >

        <toolbaritem>
            <toolbarbutton id="Back-MainMenu" type="Plain" oncommand="gBrowser.webNavigation.goBack()"
                           tooltiptext="Back">
            </toolbarbutton>
            <toolbarbutton id="Foward-MainMenu" type="Plain" oncommand="gBrowser.webNavigation.goForward()"
                           tooltiptext="Forward">
            </toolbarbutton>
            <toolbarbutton id="Reload-MainMenu" type="Plain" oncommand="BrowserReloadSkipCache();"
                           tooltiptext="Reload">
            </toolbarbutton>
            <toolbarbutton id="Home-MainMenu" type="Plain" oncommand="window.BrowserHome()"
                           tooltiptext="Home">
            </toolbarbutton>

            <menulist id="TutTB-SearchTerms" editable="true" flex="1"
                      minwidth="100" width="450"
                      onkeypress="objTutorialToolbar.KeyHandler(event);">
                <menupopup id="TutTB-SearchTermsMenu" onpopupshowing="objTutorialToolbar.Populate()" />
            </menulist>

        <splitter id="TutTB-ResizeSplitter" state="open" collapse="none"
                  resizebefore="closest" resizeafter="farthest"
                  tooltiptext="Resize the Search Box">
            <vbox id="TutTB-ResizeBar" />
        </splitter>

            <toolbarbutton id="TutTB-Combined-Button" label="Search"
                           type="Plain" tooltiptext="Search"
                           oncommand="objTutorialToolbar.Search(event, 'web')">

            </toolbarbutton>

             <toolbarbutton id="Loc-MainMenu" type="menu-button"
               tooltiptext="Actual Location">
                 <menupopup>
                    <menuitem id="web-location" label="Actual Location"
                    class="menuitem-iconic" tooltiptext="Actual Location" />
                 </menupopup>
            </toolbarbutton>
        </toolbaritem>

        <toolbarspring />

    </toolbar>
</toolbox>


问:
How to modify Negative Axis Bar Graph in Highcharts?
I have created a negative Axis Bar Graph using Highcharts but the format in which I would like it to be is not appearing. I am not able to manipulate it to the format as shown.

My output for the code mentioned below is attached. http://jsfiddle.net/00bh7yp7/2/

```<code>// Age categories
var categories = [
        '0-4', '5-9', '10-14', '15-19',
        '20-24', '25-29', '30-34', '35-39', '40-44',
        '45-49', '50-54', '55-59', '60-64', '65-69',
        '70-74', '75-79', '80-84', '85-89', '90-94',
        '95-99', '100 + ' ];

    Highcharts.chart('container', {
        chart: {
            type: 'bar'
        },
        title: {
            text: 'Population pyramid for Germany, 2015'
        },
        subtitle: {
            text: 'Source: <a href="http://populationpyramid.net/germany/2015/">Population Pyramids of the World from 1950 to 2100</a>'
        },
        xAxis: {
            categories: categories,
            reversed: false,
            offset: 0,
            labels: {
                step: 1
            },

        },
        yAxis: {

            title: {
                text: null
            },
            labels: {
                formatter: function () {
                    return Math.abs(this.value) + '%';
                }
            }
        },

        plotOptions: {
            series: {
               stacking: 'normal'
            }
        },

        tooltip: {
            formatter: function () {
                return '<b>' + this.series.name + ', age ' + this.point.category + '</b><br/>' +
                    'Population: ' + Highcharts.numberFormat(Math.abs(this.point.y), 0);
            }
        },

        series: [{
            name: 'Male',
            data: [-2.2, -2.2, -2.3, -2.5, -2.7, -3.1, -3.2,
                -3.0, -3.2, -4.3, -4.4, -3.6, -3.1, -2.4,
                -2.5, -2.3, -1.2, -0.6, -0.2, -0.0, -0.0]
        }, {
            name: 'Female',
            data: [2.1, 2.0, 2.2, 2.4, 2.6, 3.0, 3.1, 2.9,
                3.1, 4.1, 4.3, 3.6, 3.4, 2.6, 2.9, 2.9,
                1.8, 1.2, 0.6, 0.1, 0.0]
        }] });
</code>```

CURRENT OUTPUT

REQUIRED OUTPUT

I just am looking for formatting so that the Category Scale comes in between the two graphs and then we can manage it further. Please help.

答:
One way of achieving that spacing is using two y axes and positioning them with left and width properties (they're not documented in the API, but they work):

```<code>  yAxis: [{
    left: '55%',
    width: '45%'
    (...)
  }, {
    reversed: true,
    width: '45%',
    offset: 0
    (...)
  }],
  series: [{
    data: [1, 3]
  }, {
    data: [2, 5],
    yAxis: 1
  }]
</code>```

X axis is treated similarly:

```<code>  xAxis: {
    left: '50%',
    (...)
  }
</code>```

Live demo: http://jsfiddle.net/kkulig/dx2vj8k1/

Body:
I have created a negative Axis Bar Graph using Highcharts but the format in which I would like it to be is not appearing. I am not able to manipulate it to the format as shown.

My output for the code mentioned below is attached. http://jsfiddle.net/00bh7yp7/2/

// Age categories
var categories = [
        '0-4', '5-9', '10-14', '15-19',
        '20-24', '25-29', '30-34', '35-39', '40-44',
        '45-49', '50-54', '55-59', '60-64', '65-69',
        '70-74', '75-79', '80-84', '85-89', '90-94',
        '95-99', '100 + ' ];

    Highcharts.chart('container', {
        chart: {
            type: 'bar'
        },
        title: {
            text: 'Population pyramid for Germany, 2015'
        },
        subtitle: {
            text: 'Source: Population Pyramids of the World from 1950 to 2100'
        },
        xAxis: {
            categories: categories,
            reversed: false,
            offset: 0,
            labels: {
                step: 1
            },

        },
        yAxis: {

            title: {
                text: null
            },
            labels: {
                formatter: function () {
                    return Math.abs(this.value) + '%';
                }
            }
        },

        plotOptions: {
            series: {
               stacking: 'normal'
            }
        },

        tooltip: {
            formatter: function () {
                return '' + this.series.name + ', age ' + this.point.category + '
' +
                    'Population: ' + Highcharts.numberFormat(Math.abs(this.point.y), 0);
            }
        },

        series: [{
            name: 'Male',
            data: [-2.2, -2.2, -2.3, -2.5, -2.7, -3.1, -3.2,
                -3.0, -3.2, -4.3, -4.4, -3.6, -3.1, -2.4,
                -2.5, -2.3, -1.2, -0.6, -0.2, -0.0, -0.0]
        }, {
            name: 'Female',
            data: [2.1, 2.0, 2.2, 2.4, 2.6, 3.0, 3.1, 2.9,
                3.1, 4.1, 4.3, 3.6, 3.4, 2.6, 2.9, 2.9,
                1.8, 1.2, 0.6, 0.1, 0.0]
        }] });

CURRENT OUTPUT

REQUIRED OUTPUT

I just am looking for formatting so that the Category Scale comes in between the two graphs and then we can manage it further. Please help.

Body:
One way of achieving that spacing is using two y axes and positioning them with left and width properties (they're not documented in the API, but they work):

  yAxis: [{
    left: '55%',
    width: '45%'
    (...)
  }, {
    reversed: true,
    width: '45%',
    offset: 0
    (...)
  }],
  series: [{
    data: [1, 3]
  }, {
    data: [2, 5],
    yAxis: 1
  }]

X axis is treated similarly:

  xAxis: {
    left: '50%',
    (...)
  }

Live demo: http://jsfiddle.net/kkulig/dx2vj8k1/


问:
WCF Not Timing out correctly?
I am having a timeout issue, these are the details:

My binding configuration looks like this:

```<code><netTcpBinding>
 <binding name="WindowsServerOverTcp"
   maxReceivedMessageSize="10000000"
   maxBufferSize="10000000"
   maxBufferPoolSize="10000000"
   closeTimeout="00:00:03"
  openTimeout="00:00:03"
  sendTimeout="00:00:03"
  receiveTimeout="00:00:03">
  <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
  maxArrayLength="2147483647" maxBytesPerRead="2147483647"
  maxNameTableCharCount="2147483647" />
  <security mode="None">
  </security>
 </binding>
 </netTcpBinding>
</code>```

I am sending a message to a server which I know is turned off so the connection should just time out after 3 seconds as stipulated in my app.config, but for some reason it is taking 20-30 seconds.

When the EndPointNotFoundException is thrown this is the info I get:

System.ServiceModel.EndPointNotFoundException:
  Could not connect to
  net.tcp://10.0.0.82:4466/MegaMatcherWcf.
  The connection attempt lasted for a
  time span of 00:00:03. TCP error code
  10060: A connection attempt failed
  because the connected party did not
  properly respond after a period of
  time, or established connection failed
  because connected host has failed to
  respond 10.0.0.82:4466

If I try the same test with the machine turned on, but no listening software running I get the expected behaviour, with the connection timing out after 3 seconds. Why if the machine is off does it take 30 seconds, and then tell me it took 3 seconds?

答:
I was facing the same problem

Did every thing, tried every configuration nothing helped.

net.tcp over internet is timing out like hell on lengthy processes

the only thing that helped me is when i used

Duplex or Callback Message Exchange Pattern

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

Title: WCF Not Timing out correctly?

Body:
I am having a timeout issue, these are the details:

My binding configuration looks like this:

<netTcpBinding>
 <binding name="WindowsServerOverTcp"
   maxReceivedMessageSize="10000000"
   maxBufferSize="10000000"
   maxBufferPoolSize="10000000"
   closeTimeout="00:00:03"
  openTimeout="00:00:03"
  sendTimeout="00:00:03"
  receiveTimeout="00:00:03">
  <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
  maxArrayLength="2147483647" maxBytesPerRead="2147483647"
  maxNameTableCharCount="2147483647" />
  <security mode="None">
  </security>
 </binding>
 </netTcpBinding>

I am sending a message to a server which I know is turned off so the connection should just time out after 3 seconds as stipulated in my app.config, but for some reason it is taking 20-30 seconds.

When the EndPointNotFoundException is thrown this is the info I get:

System.ServiceModel.EndPointNotFoundException:
  Could not connect to
  net.tcp://10.0.0.82:4466/MegaMatcherWcf.
  The connection attempt lasted for a
  time span of 00:00:03. TCP error code
  10060: A connection attempt failed
  because the connected party did not
  properly respond after a period of
  time, or established connection failed
  because connected host has failed to
  respond 10.0.0.82:4466

If I try the same test with the machine turned on, but no listening software running I get the expected behaviour, with the connection timing out after 3 seconds. Why if the machine is off does it take 30 seconds, and then tell me it took 3 seconds?

ContentLicense: CC BY-SA 4.0


问:
Parse Function Returning Empty Promise
I'm calling a Parse cloud method from our front-end, but rather than the expected test return of "123", I am receiving a blank array.

The method pushes to an array called 'promiseArray' the String "123". Front end is receiving "[]" rather than "["123"]"

Code (reduced for relevancy):

```<code>Parse.Cloud.define('newReport', function(req, res) {

try{

for (let i = 0; i < fEPath.length; i++) {

  let outputPart;

  switch(fEPath[i].elementName){

    case 'testOutput':
    promiseArray.push(
      "123"
    );
    break

  }
}
</code>```

We use the syntax:

```<code>Promise.all(promiseArray).then(values => {
  res.success(values);
});
</code>```

To send the array back to the front-end.

答:
Your return value should be a Promise object. Try this:</p>

```<code>case 'testOutput':
    promiseArray.push(
        new Promise(
            function (resolve, reject) {
                resolve("123")
            }
        )
    );
break
</code>```

Title: Parse Function Returning Empty Promise

Body:
I'm calling a Parse cloud method from our front-end, but rather than the expected test return of "123", I am receiving a blank array.

The method pushes to an array called 'promiseArray' the String "123". Front end is receiving "[]" rather than "["123"]"

Code (reduced for relevancy):

Parse.Cloud.define('newReport', function(req, res) {

try{

for (let i = 0; i < fEPath.length; i++) {

  let outputPart;

  switch(fEPath[i].elementName){

    case 'testOutput':
    promiseArray.push(
      "123"
    );
    break

  }
}

We use the syntax:

Promise.all(promiseArray).then(values => {
  res.success(values);
});

To send the array back to the front-end.

Body:
Your return value should be a Promise object. Try this:

case 'testOutput':
    promiseArray.push(
        new Promise(
            function (resolve, reject) {
                resolve("123")
            }
        )
    );
break


问:
Create an xml file for dlib training
I'm trying to create an XML file by exploiting the imglab tool provided by dlib. I have a dataset of 21 images each with a single face. I must affix on each 68 landmarks at my leisure.

The file created with my landmarks is different from the XML file provided by dlib : namely each record is defined as a single box and should be considered as a part of the main box with containing the face.

Help me!

答:
Evgeniy's answer is useful but when running imglab with --parts argument, numerical labels should be like:

```<code>imglab --parts "01 02 03 04 05 06 07 08 09 10 11 12" xml_file_name.xml
</code>```

Otherwise, since dlib sorts the parts by name in xml, labels will be confusing while predicting.

Title: Create an xml file for dlib training

Body:
Evgeniy's answer is useful but when running imglab with --parts argument, numerical labels should be like:

imglab --parts "01 02 03 04 05 06 07 08 09 10 11 12" xml_file_name.xml

Otherwise, since dlib sorts the parts by name in xml, labels will be confusing while predicting.


问:
Set Location for new form
I use below code to make lightbox effect and it works as i expected. However if i move the parent form it still pop-ups on the center of the screen.

```<code>// Execute this code from parent form
Form f = new Form();
f.ShowInTaskbar = false;
f.BackColor = Color.Black;
f.Size = this.Size;
f.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
f.StartPosition = this.StartPosition;
f.Opacity = 0.6;
f.Show();
</code>```

So i changed the above code like below;

```<code>f.StartPosition = FormStartPosition.CenterParent;
</code>```

However it still doesn't pop-up  center of the parent form.

Also i tried below, It didn't work too;

```<code>f.SetBounds(this.Location.X, this.Location.Y,this.Width, this.Height);
</code>```

I already tried the solutions here;

Show a child form in the centre of Parent form in C#

They also didn't work.

What i want to do is, creating a second form with the same size and same location.

答:
Just changing this line;

```<code>f.Show();
</code>```

to  this line, It worked;

```<code>f.ShowDialog();
</code>```

Title: Set Location for new form

Body:
I use below code to make lightbox effect and it works as i expected. However if i move the parent form it still pop-ups on the center of the screen.

// Execute this code from parent form
Form f = new Form();
f.ShowInTaskbar = false;
f.BackColor = Color.Black;
f.Size = this.Size;
f.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
f.StartPosition = this.StartPosition;
f.Opacity = 0.6;
f.Show();

So i changed the above code like below;

f.StartPosition = FormStartPosition.CenterParent;

However it still doesn't pop-up  center of the parent form.

Also i tried below, It didn't work too;

f.SetBounds(this.Location.X, this.Location.Y,this.Width, this.Height);

I already tried the solutions here;

Show a child form in the centre of Parent form in C#

They also didn't work.

What i want to do is, creating a second form with the same size and same location.

Body:
Just changing this line;

f.Show();

to  this line, It worked;

f.ShowDialog();


问:
$(selector, element) Native JS alternative
Hi I'm trying to remove all jQuery from my platform one line at a time.

But I'm having some trouble finding a replacement for this

```<code>$('[data-attribute="value"]', GenericHTMLElement);
</code>```

I was hoping it would be something simple like

var div = document.createElement('div');
div.innerHTML = '

';
var b = div.childNodes;

var a = b.querySelector('[data-attribute="value"]');```

But that's not working either. Does have any suggestions for me?

答:
As commented,

childNodes will give you a list of elements. This list will not have querySelector. If you loop over nodes, you should be able to get it though. But, my suggestion is just do div.querySelector(...)

To be specific, it will be of type NodeList. This is a collection of nodes. So you cannot run querySelector on it. You can either loop over all nodes and do querySelector on them or just so this operation on parent div.

var div = document.createElement('div');
div.innerHTML = '
Dummy Text
';
var b = div.childNodes;

console.log('Type of childNodes is: ', Object.prototype.toString.call(b))

// getting element using loop over childNodes
for(var i = 0; i<b.length; i++) {
  var el = b[i].querySelector('[data-attribute="value"]');
  el && console.log(el.textContent)
}

// getting element using parent elenent.
var el1 = div.querySelector('[data-attribute="value"]');
console.log(el1.textContent)```

Body:
Hi I'm trying to remove all jQuery from my platform one line at a time.

But I'm having some trouble finding a replacement for this

$('[data-attribute="value"]', GenericHTMLElement);

I was hoping it would be something simple like

var div = document.createElement('div');
div.innerHTML = '

';
var b = div.childNodes;

var a = b.querySelector('[data-attribute="value"]');

But that's not working either. Does have any suggestions for me?

Body:
As commented,

childNodes will give you a list of elements. This list will not have querySelector. If you loop over nodes, you should be able to get it though. But, my suggestion is just do div.querySelector(...)

To be specific, it will be of type NodeList. This is a collection of nodes. So you cannot run querySelector on it. You can either loop over all nodes and do querySelector on them or just so this operation on parent div.

var div = document.createElement('div');
div.innerHTML = '<div><span data-attribute="value">Dummy Text</span><span data-something-else="1000"></span></div>';
var b = div.childNodes;

console.log('Type of childNodes is: ', Object.prototype.toString.call(b))

// getting element using loop over childNodes
for(var i = 0; i<b.length; i++) {
  var el = b[i].querySelector('[data-attribute="value"]');
  el && console.log(el.textContent)
}

// getting element using parent elenent.
var el1 = div.querySelector('[data-attribute="value"]');
console.log(el1.textContent)


问:
react native converting array into string
I am trying to print out array's value, converting into string in the description of  mapview marker.
when I put <Text>nameList</text> inside of return() under <View style={styles.container}> is okay, but description={nameList.toString()} in  is just print out {object,object}, {object,object}, {object,object}

Please let me know how would I solve.

```<code>constructor(){
super()
this.state = {name: []}

}

  componentDidMount(){

   return fetch('https://transportapi.com/v3/uk/bus/stop/6090282/live.jsonapp_id=8425e834&app_key=a9de6fe50081ecf38d2e9c9d5f1a87e0&group=route&nextbuses=yes')
.then((response) => response.json())
.then((responseJson) => {
for(var x in responseJson.departures){
this.setState({
state : this.state["name"].push(responseJson.departures[x][0])

});
}

   })
.catch((error) => {
  console.error(error);
});
  }

render() {

const info = this.state.name;
const nameList = info.map(name =>{
  return(

    <Text key={name.line}>{name.line}{name.aimed_departure_time}</Text>
  )

})

 return (

  <View style={styles.container}>
    <MapView
initialRegion={{
  latitude: 37.78825,
  longitude: -122.4324,
  latitudeDelta: 0.0922,
  longitudeDelta: 0.0421,
}}
>

  <MapView.Marker
   coordinate={{
   latitude: 37.78825,
  longitude: -122.4324,
   }}
   title={'Hello'}
   description={nameList.toString()}

   />

    </MapView>

 </View>

 }
</code>```

答:
Use

```<code>JSON.stringify(nameList)
</code>```

instead of

```<code>nameList.toString()
</code>```

Source: https://www.w3schools.com/js/js_json_stringify.asp

Edited

Change your map to

```<code>const nameList = info.map(name => {
  return `${name.line} : ${name.aimed_departure_time}`
})
</code>```

Body:
I am trying to print out array's value, converting into string in the description of  mapview marker.
when I put <Text>nameList</text> inside of return() under <View style={styles.container}> is okay, but description={nameList.toString()} in  is just print out {object,object}, {object,object}, {object,object}

Please let me know how would I solve.

constructor(){
super()
this.state = {name: []}

}

  componentDidMount(){

   return fetch('https://transportapi.com/v3/uk/bus/stop/6090282/live.jsonapp_id=8425e834&app_key=a9de6fe50081ecf38d2e9c9d5f1a87e0&group=route&nextbuses=yes')
.then((response) => response.json())
.then((responseJson) => {
for(var x in responseJson.departures){
this.setState({
state : this.state["name"].push(responseJson.departures[x][0])

});
}

   })
.catch((error) => {
  console.error(error);
});
  }

render() {

const info = this.state.name;
const nameList = info.map(name =>{
  return(

    <Text key={name.line}>{name.line}{name.aimed_departure_time}</Text>
  )

})

 return (

  <View style={styles.container}>
    <MapView
initialRegion={{
  latitude: 37.78825,
  longitude: -122.4324,
  latitudeDelta: 0.0922,
  longitudeDelta: 0.0421,
}}
>

  <MapView.Marker
   coordinate={{
   latitude: 37.78825,
  longitude: -122.4324,
   }}
   title={'Hello'}
   description={nameList.toString()}

   />

    </MapView>

 </View>

 }

Body:
Use

JSON.stringify(nameList)

instead of

nameList.toString()

Source: https://www.w3schools.com/js/js_json_stringify.asp

Edited

Change your map to

const nameList = info.map(name => {
  return `${name.line} : ${name.aimed_departure_time}`
})


问:
403(Forbidden), Invalid Key Error On Google Speech API
I am trying to access speech api using following url and always getting 403(Forbidden) Error, Invalid Key.

https://www.google.com/speech-api/v2/recognize?output=json&lang=en-us&key={MyKey}

I have tried with both Server Key and Browser key as shown on this Keys image.

I am sending http request using .NET HTTP Client; Code snippet is given below:

```<code>Stream stream = null;
            StreamReader sr = null;
            WebResponse response = null;
            JSon.RecognizedItem result;
            try
            {
                WebRequest request = WebRequest.Create(Constants.GoogleRequestString);
                request.Method = "POST";
                request.ContentType = "audio/x-flac; rate=" + sampleRate;
                request.ContentLength = bytes.Length;

                stream = request.GetRequestStream();

                stream.Write(bytes, 0, bytes.Length);
                stream.Close();

                response = request.GetResponse();

                stream = response.GetResponseStream();
                if (stream == null)
                {
                    throw new Exception("Can't get a response from server. Response stream is null.");
                }
                sr = new StreamReader(stream);

                //Get response in JSON format
                string respFromServer = sr.ReadToEnd();

                var parsedResult = JSon.Parse(respFromServer);
                result =
                    parsedResult.hypotheses.Where(d => d.confidence == parsedResult.hypotheses.Max(p => p.confidence)).FirstOrDefault();
            }
            finally
            {
                if (stream != null)
                    stream.Close();

                if (sr != null)
                    sr.Close();

                if (response != null)
                    response.Close();
            }

            return result == null ? "" : result.utterance;
</code>```

Can anybody please help me to identify the problem here.

Thanks,
Ab.

答:
For that API endpoint, usage quota is no longer offered. And, apparently, it was an endpoint specific for community developers for the Chromium project.

Google's Speech API is the Cloud Speech API .

The keys you are referencing appear to be set up in your Google Cloud Project (GCP). GCP, implicitly those keys, can be linked to the Cloud Speech API, as pointed out here, not the https://www.google.com/speech-api/v2/ one.

Body:
I am trying to access speech api using following url and always getting 403(Forbidden) Error, Invalid Key.

https://www.google.com/speech-api/v2/recognize?output=json&lang=en-us&key={MyKey}

I have tried with both Server Key and Browser key as shown on this Keys image.

I am sending http request using .NET HTTP Client; Code snippet is given below:

Stream stream = null;
            StreamReader sr = null;
            WebResponse response = null;
            JSon.RecognizedItem result;
            try
            {
                WebRequest request = WebRequest.Create(Constants.GoogleRequestString);
                request.Method = "POST";
                request.ContentType = "audio/x-flac; rate=" + sampleRate;
                request.ContentLength = bytes.Length;

                stream = request.GetRequestStream();

                stream.Write(bytes, 0, bytes.Length);
                stream.Close();

                response = request.GetResponse();

                stream = response.GetResponseStream();
                if (stream == null)
                {
                    throw new Exception("Can't get a response from server. Response stream is null.");
                }
                sr = new StreamReader(stream);

                //Get response in JSON format
                string respFromServer = sr.ReadToEnd();

                var parsedResult = JSon.Parse(respFromServer);
                result =
                    parsedResult.hypotheses.Where(d => d.confidence == parsedResult.hypotheses.Max(p => p.confidence)).FirstOrDefault();
            }
            finally
            {
                if (stream != null)
                    stream.Close();

                if (sr != null)
                    sr.Close();

                if (response != null)
                    response.Close();
            }

            return result == null ? "" : result.utterance;

Can anybody please help me to identify the problem here.

Thanks,
Ab.


问:
What is wrong with my syntax
I am trying to create a global dictionary for my module, but it keep telling me that my syntax is wrong. I did I wrong?

```<code>_dummy_date = dict{
    '0'=datetime(year=1990, month=1, day=1, hour=0,minutes=0,second=0),
    '1'=datetime(year=1990, month=1, day=2, hour=0,minutes=0,second=0),
    '2'=datetime(year=1990, month=1, day=3, hour=0,minutes=0,second=0),
    '3'=datetime(year=1990, month=1, day=4, hour=0,minutes=0,second=0),
    '4'=datetime(year=1990, month=1, day=5, hour=0,minutes=0,second=0),
    '5'=datetime(year=1990, month=1, day=6, hour=0,minutes=0,second=0),
    '6'=datetime(year=1990, month=1, day=7, hour=0,minutes=0,second=0)
}
</code>```

Here is the error

```<code>File "/usr/lib/python2.7/dist-packages/odoo/modules/module.py", line 367, in load_openerp_module
    __import__('odoo.addons.' + module_name)
  File "/usr/lib/python2.7/dist-packages/odoo/modules/module.py", line 81, in load_module
    execfile(modfile, new_mod.__dict__)
  File "/mnt/extra-addons/jy_attendance_base/__init__.py", line 3, in <module>
    from . import models
  File "/mnt/extra-addons/jy_attendance_base/models/__init__.py", line 3, in <module>
    from . import models
File "/mnt/extra-addons/jy_attendance_base/models/models.py", line 8
    _dummy_date = dict{
                      ^
SyntaxError: invalid syntax
</code>```

答:
dict() is a method, so you must call it explicitly:

```<code>dict()
</code>```

Also, a dict constructed this way is not separated with an equal(=) sign, but a colon, like so:

```<code>_dummy_date = dict({
    '0':datetime(year=1990, month=1, day=1, hour=0,minutes=0,second=0),
    '1':datetime(year=1990, month=1, day=2, hour=0,minutes=0,second=0),
    '2':datetime(year=1990, month=1, day=3, hour=0,minutes=0,second=0),
    '3':datetime(year=1990, month=1, day=4, hour=0,minutes=0,second=0),
    '4':datetime(year=1990, month=1, day=5, hour=0,minutes=0,second=0),
    '5':datetime(year=1990, month=1, day=6, hour=0,minutes=0,second=0),
    '6':datetime(year=1990, month=1, day=7, hour=0,minutes=0,second=0)
})
</code>```

But, since you're creating your dictionary explicitly, you can remove the dict() call at all, and simply write:

```<code>_dummy_date = {
    '0':datetime(year=1990, month=1, day=1, hour=0,minutes=0,second=0),
    '1':datetime(year=1990, month=1, day=2, hour=0,minutes=0,second=0),
    '2':datetime(year=1990, month=1, day=3, hour=0,minutes=0,second=0),
    '3':datetime(year=1990, month=1, day=4, hour=0,minutes=0,second=0),
    '4':datetime(year=1990, month=1, day=5, hour=0,minutes=0,second=0),
    '5':datetime(year=1990, month=1, day=6, hour=0,minutes=0,second=0),
    '6':datetime(year=1990, month=1, day=7, hour=0,minutes=0,second=0)
}
</code>```

And this will simply create the dict as you like

Title: What is wrong with my syntax

Body:
I am trying to create a global dictionary for my module, but it keep telling me that my syntax is wrong. I did I wrong?

_dummy_date = dict{
    '0'=datetime(year=1990, month=1, day=1, hour=0,minutes=0,second=0),
    '1'=datetime(year=1990, month=1, day=2, hour=0,minutes=0,second=0),
    '2'=datetime(year=1990, month=1, day=3, hour=0,minutes=0,second=0),
    '3'=datetime(year=1990, month=1, day=4, hour=0,minutes=0,second=0),
    '4'=datetime(year=1990, month=1, day=5, hour=0,minutes=0,second=0),
    '5'=datetime(year=1990, month=1, day=6, hour=0,minutes=0,second=0),
    '6'=datetime(year=1990, month=1, day=7, hour=0,minutes=0,second=0)
}

Here is the error

File "/usr/lib/python2.7/dist-packages/odoo/modules/module.py", line 367, in load_openerp_module
    __import__('odoo.addons.' + module_name)
  File "/usr/lib/python2.7/dist-packages/odoo/modules/module.py", line 81, in load_module
    execfile(modfile, new_mod.__dict__)
  File "/mnt/extra-addons/jy_attendance_base/__init__.py", line 3, in <module>
    from . import models
  File "/mnt/extra-addons/jy_attendance_base/models/__init__.py", line 3, in <module>
    from . import models
File "/mnt/extra-addons/jy_attendance_base/models/models.py", line 8
    _dummy_date = dict{
                      ^
SyntaxError: invalid syntax

Body:
dict() is a method, so you must call it explicitly:

dict()

Also, a dict constructed this way is not separated with an equal(=) sign, but a colon, like so:

_dummy_date = dict({
    '0':datetime(year=1990, month=1, day=1, hour=0,minutes=0,second=0),
    '1':datetime(year=1990, month=1, day=2, hour=0,minutes=0,second=0),
    '2':datetime(year=1990, month=1, day=3, hour=0,minutes=0,second=0),
    '3':datetime(year=1990, month=1, day=4, hour=0,minutes=0,second=0),
    '4':datetime(year=1990, month=1, day=5, hour=0,minutes=0,second=0),
    '5':datetime(year=1990, month=1, day=6, hour=0,minutes=0,second=0),
    '6':datetime(year=1990, month=1, day=7, hour=0,minutes=0,second=0)
})

But, since you're creating your dictionary explicitly, you can remove the dict() call at all, and simply write:

_dummy_date = {
    '0':datetime(year=1990, month=1, day=1, hour=0,minutes=0,second=0),
    '1':datetime(year=1990, month=1, day=2, hour=0,minutes=0,second=0),
    '2':datetime(year=1990, month=1, day=3, hour=0,minutes=0,second=0),
    '3':datetime(year=1990, month=1, day=4, hour=0,minutes=0,second=0),
    '4':datetime(year=1990, month=1, day=5, hour=0,minutes=0,second=0),
    '5':datetime(year=1990, month=1, day=6, hour=0,minutes=0,second=0),
    '6':datetime(year=1990, month=1, day=7, hour=0,minutes=0,second=0)
}

And this will simply create the dict as you like


问:
Apache/PHP application sessions timing out
I am fairly new to PHP and am running an open source web application called GLPI.  We have several users that have the application open all day long and after a while they have to log back on the application.  Is this the Apache session timing out?  If so what is the default and how do I change it.</p>

答:
Try setting the session lifetime to a day (24*60*60 seconds):

In your php.ini:

session.gc_maxlifetime = 86400

In the code:

ini_set( 'session.gc_maxlifetime' ,86400);

http://www.php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime


问:
How to delete particular data from core data attribute (column) in swift 3
I am doing core data in Swift 3. I am able to store data and able to fetch, working fine. But, while trying to delete particular data suppose string data, its not able to do.

Following is my code

```<code>        //Delete if existing data there
        let context = DatabaseController.persistentContainer.viewContext
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "UserData")
        fetchRequest.predicate = NSPredicate.init(format: "userFocusData==\(node.label.text!)")

        let result = try? context.fetch(fetchRequest)
        let resultData = result as! [UserData]

        for object in resultData {
            context.delete(object)
        }

        do {
            try context.save()
            print("saved!")
        } catch let error as NSError  {
            print("Could not save \(error), \(error.userInfo)")
            self.showAlert(message: "Data not able to save, please try again later.", title: kText_AppName)
        } catch {

        }
</code>```

And its getting crash at following line

```<code>        let result = try? context.fetch(fetchRequest)
</code>```

And crash report is

```<code>*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath Sharepoint not found in entity <NSSQLEntity UserData id=6>'
</code>```

But, I am passing some string, that string I want to delete from database.
Can anyone suggest me, how to fix this, I have not used core data well.

答:
Issue found.

So, the solution answer is

```<code>fetchRequest.predicate = NSPredicate(format: "UserData.userFocusData = %@",node.label.text!)
</code>```

Body:
I am doing core data in Swift 3. I am able to store data and able to fetch, working fine. But, while trying to delete particular data suppose string data, its not able to do.

Following is my code

        //Delete if existing data there
        let context = DatabaseController.persistentContainer.viewContext
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "UserData")
        fetchRequest.predicate = NSPredicate.init(format: "userFocusData==\(node.label.text!)")

        let result = try? context.fetch(fetchRequest)
        let resultData = result as! [UserData]

        for object in resultData {
            context.delete(object)
        }

        do {
            try context.save()
            print("saved!")
        } catch let error as NSError  {
            print("Could not save \(error), \(error.userInfo)")
            self.showAlert(message: "Data not able to save, please try again later.", title: kText_AppName)
        } catch {

        }

And its getting crash at following line

        let result = try? context.fetch(fetchRequest)

And crash report is

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath Sharepoint not found in entity <NSSQLEntity UserData id=6>'

But, I am passing some string, that string I want to delete from database.
Can anyone suggest me, how to fix this, I have not used core data well.

Body:
Issue found.

So, the solution answer is

fetchRequest.predicate = NSPredicate(format: "UserData.userFocusData = %@",node.label.text!)


问:
can't access codeigniter controller function from curl but in browser working
I provide the API in my website so need to access the site from curl. when call the particular url from curl it can't be accessed. but in the browser it shows the result. If we put echo to check the process, upto parent construct we can get the result </p>

```<code>class Apicall extends CI_Controller {
    // Constructor function
    public function __construct()
    {
        echo "test"; //this echo  worked
        parent::__construct();
        echo "hfksdjhfkjsdhflksdhflkjh"; //this is not worked
        $this->load->library(array('form_validation'));
        $this->load->helper(array('url', 'language'));
    }
    public function v1()
    {
    }
}
</code>```

答: The problem is in our core controller we write the redirect function so now its working fine</p>

Body:
I provide the API in my website so need to access the site from curl. when call the particular url from curl it can't be accessed. but in the browser it shows the result. If we put echo to check the process, upto parent construct we can get the result

class Apicall extends CI_Controller {
    // Constructor function
    public function __construct()
    {
        echo "test"; //this echo  worked
        parent::__construct();
        echo "hfksdjhfkjsdhflksdhflkjh"; //this is not worked
        $this->load->library(array('form_validation'));
        $this->load->helper(array('url', 'language'));
    }
    public function v1()
    {
    }
}


问:
How to convert a byte array to two long values?
I'm reading a 16 byte array (byte[16]) from a JDBC ResultSet with rs.getBytes("id") and now I need to convert it to two long values. How can I do that?

This is the code I have tried, but I probably didn't use ByteBuffer correctly.

```<code>byte[] bytes = rs.getBytes("id");
System.out.println("bytes: "+bytes.length); // prints "bytes: 16"

ByteBuffer buffer = ByteBuffer.allocate(16);
buffer = buffer.put(bytes);

// throws an java.nio.BufferUnderflowException
long leastSignificant = buffer.getLong();
long mostSignificant = buffer.getLong();
</code>```

I stored the byte array to the database using:

```<code>byte[] bytes = ByteBuffer.allocate(16)
    .putLong(leastSignificant)
    .putLong(mostSignificant).array();
</code>```

答:
You have to reset the ByteBuffer using the flip() method after you insert the bytes into it (thereby allowing the getLong() calls to read from the start - offset 0):

```<code>buffer.put(bytes);     // Note: no reassignment either

buffer.flip();

long leastSignificant = buffer.getLong();
long mostSignificant = buffer.getLong();
</code>```

Body:
I'm reading a 16 byte array (byte[16]) from a JDBC ResultSet with rs.getBytes("id") and now I need to convert it to two long values. How can I do that?

This is the code I have tried, but I probably didn't use ByteBuffer correctly.

byte[] bytes = rs.getBytes("id");
System.out.println("bytes: "+bytes.length); // prints "bytes: 16"

ByteBuffer buffer = ByteBuffer.allocate(16);
buffer = buffer.put(bytes);

// throws an java.nio.BufferUnderflowException
long leastSignificant = buffer.getLong();
long mostSignificant = buffer.getLong();

I stored the byte array to the database using:

byte[] bytes = ByteBuffer.allocate(16)
    .putLong(leastSignificant)
    .putLong(mostSignificant).array();

Body:
You have to reset the ByteBuffer using the flip() method after you insert the bytes into it (thereby allowing the getLong() calls to read from the start - offset 0):

buffer.put(bytes);     // Note: no reassignment either

buffer.flip();

long leastSignificant = buffer.getLong();
long mostSignificant = buffer.getLong();


问:
Two-way data binding (Angular) vs one-way data flow (React/Flux)
In the last week, I’ve been trying to make sense how two-way data binding (Angular) and one-way data flow (React/Flux) are different. They say that one-way data flow is more powerful and easier to understand and follow: it is deterministic and helps avoiding side-effects. In my newbie eyes though, they both look pretty much the same: the view listens to the model, and the model reacts on actions done to the view. Both claim that the model is the single source of truth.

Could anybody comprehensively explain in understandable way how they are really different and how one-way data flow is more beneficial and easier to reason about?

答:
Data flow here is a flow of write events - i.e. state updates

These events are flowing between views and controllers (and services, such as HTTP backends)

One-way flow is basically the giant cycle:

app view uses (reads, not writes) app state to render

when application gets some stimuli from outside (user typed some text in input field, or result of HTTP request has arrived), it emits write event - or, in Redux/Flux slang, dispatches an action

all events, from all controllers and views, are flowing into the single sink - dispatch function (reducer); although the nature of dispatch function allows it to be composed from simpler dispatch functions, conceptually, there's only one dispatcher for the whole app

dispatcher uses an event to figure out which part of the state is to be updated

go to start

Two-way flow aka data binding binds two pieces of state: in most cases, one inside the controller (e. g. some variable), and one inside the view (e. g. contents of textbox). Binding means that, when one piece changes, the other piece changes as well and gets the same value, so you can pretend that there's only one piece of state involved (while there's two actually). Write events are going back and forth between controllers and views - thus two-way.

Data-binding is cool when you need to figure out what variable holds the contents of this particular textbox - it shows immediately. But it requires complex framework to maintain the illusion of one piece of state where there's two pieces really. Usually you'll be forced to use framework-specific syntax to write your views' code - i. e. to learn yet another language.

One-way data flow is cool when you can leverage that extra entity - events flow. And, usually, you can - it's useful for Undo/Redo, user actions replay (e. g. for debug), replication, etc, etc. And the code to support this is much, much simpler, and usually can be written in plain JavaScript instead of framework-specific syntax. On the other hand, since you no longer have data-binding, it no longer saves you some boilerplate.

Also, see great visual explanation in this answer: https://stackoverflow.com/a/37566693/1643115. Single-headed and two-headed arrows visually represents one-way and two-way data flow respectively.


问:
Rewrite profile.php?user=username to profile/username
I've created a very basic php templating system that I'm using to display a page with this URL: /basedir/index.php?page=home

The home content is served by the script home.php.

With a rewrite rule in .htaccess, I want my url to look like this: /basedir/home.

The problem that I'm having is that I've got stuck when it comes to rewrite one more GET variable that I'm using to display a user's profile. For now the profile page url looks like this: /basedir/profile?user=username.

Now I want it to look like this: /basedir/profile/username.

So far, my .htaccess looks like this:

```<code>RewriteEngine On

RewriteBase /basedir/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) ?page=$1 [L,QSA]
</code>```

I have no idea if this is good or if i have to write a completely new .htaccess file.

答:
Based on your code, and my limited understanding, I would guess something like this:

```<code>RewriteRule ^profile/([^?]*) ?page=profile&user=$1 [L,QSA]
</code>```

.. insert it above your RewriteRule ^([^?]*) ?page=$1 [L,QSA].

Body:
I've created a very basic php templating system that I'm using to display a page with this URL: /basedir/index.php?page=home

The home content is served by the script home.php.

With a rewrite rule in .htaccess, I want my url to look like this: /basedir/home.

The problem that I'm having is that I've got stuck when it comes to rewrite one more GET variable that I'm using to display a user's profile. For now the profile page url looks like this: /basedir/profile?user=username.

Now I want it to look like this: /basedir/profile/username.

So far, my .htaccess looks like this:

RewriteEngine On

RewriteBase /basedir/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) ?page=$1 [L,QSA]

I have no idea if this is good or if i have to write a completely new .htaccess file.

Body:
Based on your code, and my limited understanding, I would guess something like this:

RewriteRule ^profile/([^?]*) ?page=profile&user=$1 [L,QSA]

.. insert it above your RewriteRule ^([^?]*) ?page=$1 [L,QSA].


问:
SendGrid Templates with Web API vs. SMTP API
I have gone through various documentation of SendGrid Implementation. Actually, I want to use Email Templates defined in the SendGrid.

I only found that we can use Email Templates and can use substitution tags in it if we are implementing SendGrid SMTP API.

I want to make it confirm that, can we use Email Templates with substitution tags in it, if we are using SendGrid via Web API?

Thanks in advance!

答:
Oh Yes!

After going through some SendGrid mail examples on GitHub. I got that we can use Email Templates + Substitution tags if we are using the SendGrid Web APIs.

Here is the link from where I got to know this -

SendGrid Java examples for various scenarios on GitHub.

Thanks if someone was looking into it!


问:
How to change the application launcher icon on Flutter?
When I create an app with a flutter create command, the flutter logo is used as an application icon for both platforms.

If I want to change the app icon, shall I go to both platforms directories and replace images there?, by platforms directories I mean  myapp/ios/Runner/Assets.xcassets/AppIcon.appiconset for iOS and myapp/android/app/src/main/res for Android.

Or is it possible to define an image as a Flutter Asset and the icons are generated somehow?.

答:
Flutter Launcher Icons has been designed to help quickly generate launcher icons for both Android and iOS: https://pub.dartlang.org/packages/flutter_launcher_icons

Add the package to your pubspec.yaml file (within your Flutter project) to use it

Within pubspec.yaml file specify the path of the icon you wish to use for the app and then choose whether you want to use the icon for the iOS app, Android app or both.

Run the package

Voila! The default launcher icons have now been replaced with your custom icon

I'm hoping to add a video to the GitHub README to demonstrate it

Video showing how to run the tool can be found here.

If anyone wants to suggest improvements / report bugs, please add it as an issue on the GitHub project.

Update: As of Wednesday 24th January 2018, you should be able to create new icons without overriding the old existing launcher icons in your Flutter project.

Update 2: As of v0.4.0 (8th June 2018) you can specify one image for your Android icon and a separate image for your iOS icon.

Update 3: As of v0.5.2 (20th June 2018) you can now add adaptive launcher icons for the Android app of your Flutter project


问:
Is there way to save trained model after overfitting occurs in CatBoost?
I am using CatBoostRegressor in Python version of the Catboost library.

According to documentation, it's possible to use overfitting detector, which I am doing, like this:

```<code>model = CatBoostRegressor(iterations=iters, learning_rate=0.03, depth=depth, verbose=True, od_pval=1, od_type='IncToDec', od_wait=20)
model.fit(train_pool, eval_set=validation_pool)

# this code didn't executed
model.save_model(model_name)
</code>```

However, after the overfitting occurs, I've got my Python script interrupted, prematurely stopped, pick any phrase you want, and save model part didn't get executed, which leads to a lot of waisted time and no results in the end. I didn't get any stacktrace.

Is there any possibility to handle it in CatBoost and save hours of fitting work?

答:
Well i don't know how catboost work but i would like to share a different way to save/store your trained data maybe it could help</p>

```<code>import pickle
model = CatBoostRegressor(iterations=iters, learning_rate=0.03, depth=depth, verbose=True, od_pval=1, od_type='IncToDec', od_wait=20)
model.fit(train_pool, eval_set=validation_pool)
#----To store model----------
filename = 'final_model' # name to store model
pickle.dump(model, open(filename, 'wb')) # pickling
#-----To load model------------
loaded_model = pickle.load(open(filename, 'rb'))
</code>```

Body:
I am using CatBoostRegressor in Python version of the Catboost library.

According to documentation, it's possible to use overfitting detector, which I am doing, like this:

model = CatBoostRegressor(iterations=iters, learning_rate=0.03, depth=depth, verbose=True, od_pval=1, od_type='IncToDec', od_wait=20)
model.fit(train_pool, eval_set=validation_pool)

# this code didn't executed
model.save_model(model_name)

However, after the overfitting occurs, I've got my Python script interrupted, prematurely stopped, pick any phrase you want, and save model part didn't get executed, which leads to a lot of waisted time and no results in the end. I didn't get any stacktrace.

Is there any possibility to handle it in CatBoost and save hours of fitting work?

Body:
Well i don't know how catboost work but i would like to share a different way to save/store your trained data maybe it could help

import pickle
model = CatBoostRegressor(iterations=iters, learning_rate=0.03, depth=depth, verbose=True, od_pval=1, od_type='IncToDec', od_wait=20)
model.fit(train_pool, eval_set=validation_pool)
#----To store model----------
filename = 'final_model' # name to store model
pickle.dump(model, open(filename, 'wb')) # pickling
#-----To load model------------
loaded_model = pickle.load(open(filename, 'rb'))