问:
Is it save to store server response in SharedPreferences
I would like to store my server response as a string in Shared Preferences so that I can use this response later without fetching from server. But when I saved the data in Shared Preferences and later I use I miss the whole response. I have no security issue and any other cause like uninstall app etc. My question is whether the response will be lost in Shared Preferences so that the response contain multiple JSONObject and JSONArray.

```<code>private void productListApi(String url){
    final ProgressDialog pDialog = new ProgressDialog(mContext);
    pDialog.setMessage(mContext.getResources().getString(R.string.loading_message));
    pDialog.show();
    System.out.println("product list urlllllllllllllllllllll:" + url);

    RequestQueue mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());

    StringRequest postRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    System.out.println("response of product list data is:"
                            + response);
                    apiResponse = response ;
                    pDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(response);
                        if (json.has("code")) {

                            if (code.equalsIgnoreCase("200")) {

                                //set response to shared preference
                                SharedPreference.setStringValue(mContext, SharedPreference.PRODUCT_LIST_RESPONSE, response);

                                parseData(SharedPreference.getStringValue(mContext,SharedPreference.PRODUCT_LIST_RESPONSE));

                            }else {
                                UserDialog
                                        .showUserAlert(mContext,
                                                mContext.getResources().getString(R.string.product_list_failed));
                            }
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            pDialog.dismiss();
            UserDialog.showUserAlert(mContext,
                    mContext.getResources().getString(R.string.no_response));
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            // the POST parameters:

            params.put("user_id", SharedPreference.getStringValue(getActivity(), SharedPreference.USER_ID));
            params.put("temp_user_id", SharedPreference.getStringValue(getActivity(), SharedPreference.TEMP_USER_ID));
            params.put("version", Utilities.getVersionCode(mContext));
            params.put("device_token", SharedPreference.getStringValue(getActivity(), SharedPreference.DEVICE_TOKEN));
            return params;
        }
    };

    int socketTimeout = Constant.socketTimeout
            ;//30 seconds - change to what you want
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    //RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    postRequest.setRetryPolicy(policy);
    mRequestQueue.add(postRequest);

}
public class SharedPreference {

SharedPreferences preferences;
SharedPreferences.Editor editor;

private static final String PREFS_NAME = "nevada_food";

public static final String PRODUCT_LIST_RESPONSE = "product_list" ;

public SharedPreference() {
    super();
    // TODO Auto-generated constructor stub
}

public static String getStringValue(final Context context, String key) {
    return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
            .getString(key, "");
}

public static void setStringValue(final Context context, String key,
                                  String value) {
    final SharedPreferences prefs = context.getSharedPreferences(
            PREFS_NAME, Context.MODE_PRIVATE);
    final SharedPreferences.Editor editor = prefs.edit();

    editor.putString(key, value);
    editor.commit();
}
</code>```

}

this is my server response. I saved it in Shared Preferences and parse data in UI from Shared Preferences. This method

   parseData(SharedPreference.getStringValue(mContext,SharedPreference.PRODUCT_LIST_RESPONSE));
works properly first time when directly from server but when we use this method in another it does not work.

答:
You are using a wrong way to save into SharedPreference.

Your Code:

```<code> //set response to shared preference
  SharedPreference.setStringValue(mContext, SharedPreference.PRODUCT_LIST_RESPONSE, response);
  parseData(SharedPreference.getStringValue(mContext,SharedPreference.PRODUCT_LIST_RESPONSE));
</code>```

I don't have any clue what you written here. Try my solution below.

You should have to follow the simple SharedPreference format followed by its Editor.

Just save your data like below:

```<code>SharedPreferences.Editor editor = getSharedPreferences("PREFS_NAME", 0).edit();
editor.putString("PRODUCT_LIST_RESPONSE", response);
editor.commit();
</code>```

And get it by the KEY (PRODUCT_LIST_RESPONSE here)

```<code>SharedPreferences prefs = getSharedPreferences("PREFS_NAME", 0);
String response = prefs.getString("PRODUCT_LIST_RESPONSE", any_default_Value);
</code>```

Body:
I would like to store my server response as a string in Shared Preferences so that I can use this response later without fetching from server. But when I saved the data in Shared Preferences and later I use I miss the whole response. I have no security issue and any other cause like uninstall app etc. My question is whether the response will be lost in Shared Preferences so that the response contain multiple JSONObject and JSONArray.

private void productListApi(String url){
    final ProgressDialog pDialog = new ProgressDialog(mContext);
    pDialog.setMessage(mContext.getResources().getString(R.string.loading_message));
    pDialog.show();
    System.out.println("product list urlllllllllllllllllllll:" + url);

    RequestQueue mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());

    StringRequest postRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    System.out.println("response of product list data is:"
                            + response);
                    apiResponse = response ;
                    pDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(response);
                        if (json.has("code")) {

                            if (code.equalsIgnoreCase("200")) {

                                //set response to shared preference
                                SharedPreference.setStringValue(mContext, SharedPreference.PRODUCT_LIST_RESPONSE, response);

                                parseData(SharedPreference.getStringValue(mContext,SharedPreference.PRODUCT_LIST_RESPONSE));

                            }else {
                                UserDialog
                                        .showUserAlert(mContext,
                                                mContext.getResources().getString(R.string.product_list_failed));
                            }
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            pDialog.dismiss();
            UserDialog.showUserAlert(mContext,
                    mContext.getResources().getString(R.string.no_response));
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            // the POST parameters:

            params.put("user_id", SharedPreference.getStringValue(getActivity(), SharedPreference.USER_ID));
            params.put("temp_user_id", SharedPreference.getStringValue(getActivity(), SharedPreference.TEMP_USER_ID));
            params.put("version", Utilities.getVersionCode(mContext));
            params.put("device_token", SharedPreference.getStringValue(getActivity(), SharedPreference.DEVICE_TOKEN));
            return params;
        }
    };

    int socketTimeout = Constant.socketTimeout
            ;//30 seconds - change to what you want
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    //RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    postRequest.setRetryPolicy(policy);
    mRequestQueue.add(postRequest);

}
public class SharedPreference {

SharedPreferences preferences;
SharedPreferences.Editor editor;

private static final String PREFS_NAME = "nevada_food";

public static final String PRODUCT_LIST_RESPONSE = "product_list" ;

public SharedPreference() {
    super();
    // TODO Auto-generated constructor stub
}

public static String getStringValue(final Context context, String key) {
    return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
            .getString(key, "");
}

public static void setStringValue(final Context context, String key,
                                  String value) {
    final SharedPreferences prefs = context.getSharedPreferences(
            PREFS_NAME, Context.MODE_PRIVATE);
    final SharedPreferences.Editor editor = prefs.edit();

    editor.putString(key, value);
    editor.commit();
}

}

this is my server response. I saved it in Shared Preferences and parse data in UI from Shared Preferences. This method

   parseData(SharedPreference.getStringValue(mContext,SharedPreference.PRODUCT_LIST_RESPONSE));
works properly first time when directly from server but when we use this method in another it does not work.

Body:
You are using a wrong way to save into SharedPreference.

Your Code:

 //set response to shared preference
  SharedPreference.setStringValue(mContext, SharedPreference.PRODUCT_LIST_RESPONSE, response);
  parseData(SharedPreference.getStringValue(mContext,SharedPreference.PRODUCT_LIST_RESPONSE));

I don't have any clue what you written here. Try my solution below.

You should have to follow the simple SharedPreference format followed by its Editor.

Just save your data like below:

SharedPreferences.Editor editor = getSharedPreferences("PREFS_NAME", 0).edit();
editor.putString("PRODUCT_LIST_RESPONSE", response);
editor.commit();

And get it by the KEY (PRODUCT_LIST_RESPONSE here)

SharedPreferences prefs = getSharedPreferences("PREFS_NAME", 0);
String response = prefs.getString("PRODUCT_LIST_RESPONSE", any_default_Value);


来源: stackexchange

问:
Using LINQ to return average of distinct values
I don't have much experience with LINQ and I'm having difficulties using LINQ to extract the average, mode and median for a column of a ListView based on distinct values in a different column.

For example, consider this data:

```<code>ReportID  TAT  Col3  Col4  etc...
--------  ---  ----  ----  -------
80424     9    1     7     ...
80424     9    2     3     ...
80424     9    2     2     ...
80423     5    1     5     ...
80425     4    1     5     ...
80423     7    1     4     ...
82541     7    1     5     ...
</code>```

To extract the count of distinct reports that have a TAT (turnaround time) greater than 5 days, I use the following:

```<code>int countDistinctReports = (from ListViewItem itm in lvList.Items
                            where itm.SubItems[1].Text) > 5
                            select itm.SubItems[0].Text
                           ).Distinct().Count();
</code>```

The value of countDistinctReports is 3.

To extract the minimum TAT for these reports I use this:

```<code>string minVal = (from ListViewItem itm in lvList.Items
             where itm.SubItems[1].Text) > 5
             select itm.SubItems[1].Text
            ).Min();
</code>```

The value of minVal is 7.

However, I don't know how to write LINQ expressions to calculate the average, mode and median TAT of distinct reports that have their TAT greater than 5. In the above example, the average should be (9+7+7)/3 = 7.67. The mode should be 7.

Can someone please help? Many thanks.

答:
For the average there's also a LINQ-method called Average. However you have to convert your strings to numbers to efficently work with number-arithmetic.

```<code>var minVal = (from ListViewItem itm in lvList.Items
             where itm.SubItems[1].Text) > 5
             select Convert.ToInt32(itm.SubItems[1].Text)
            ).Average();
</code>```

However there are no such methods for median or mode. You´d have to create you own ones.

E.g. for median:

```<code>string subList = (from ListViewItem itm in lvList.Items
             where itm.SubItems[1].Text) > 5
             select Convert.ToIn32(itm.SubItems[1].Text)
            ).OrderBy(x => x).ToList();
var median = subList[subList.Count / 2];
</code>```

This will first create a list of all your items with a value greater 5 and than take the center one.

ContentLicense: CC BY-SA 3.0

Body:
I don't have much experience with LINQ and I'm having difficulties using LINQ to extract the average, mode and median for a column of a ListView based on distinct values in a different column.

For example, consider this data:

ReportID  TAT  Col3  Col4  etc...
--------  ---  ----  ----  -------
80424     9    1     7     ...
80424     9    2     3     ...
80424     9    2     2     ...
80423     5    1     5     ...
80425     4    1     5     ...
80423     7    1     4     ...
82541     7    1     5     ...

To extract the count of distinct reports that have a TAT (turnaround time) greater than 5 days, I use the following:

int countDistinctReports = (from ListViewItem itm in lvList.Items
                            where itm.SubItems[1].Text) > 5
                            select itm.SubItems[0].Text
                           ).Distinct().Count();

The value of countDistinctReports is 3.

To extract the minimum TAT for these reports I use this:

string minVal = (from ListViewItem itm in lvList.Items
             where itm.SubItems[1].Text) > 5
             select itm.SubItems[1].Text
            ).Min();

The value of minVal is 7.

However, I don't know how to write LINQ expressions to calculate the average, mode and median TAT of distinct reports that have their TAT greater than 5. In the above example, the average should be (9+7+7)/3 = 7.67. The mode should be 7.

Can someone please help? Many thanks.

Body:
For the average there's also a LINQ-method called Average. However you have to convert your strings to numbers to efficently work with number-arithmetic.

var minVal = (from ListViewItem itm in lvList.Items
             where itm.SubItems[1].Text) > 5
             select Convert.ToInt32(itm.SubItems[1].Text)
            ).Average();

However there are no such methods for median or mode. You´d have to create you own ones.

E.g. for median:

string subList = (from ListViewItem itm in lvList.Items
             where itm.SubItems[1].Text) > 5
             select Convert.ToIn32(itm.SubItems[1].Text)
            ).OrderBy(x => x).ToList();
var median = subList[subList.Count / 2];

This will first create a list of all your items with a value greater 5 and than take the center one.


问:
Pattern Matcher Android Split a String
Problem Statement: I want to read the USSD codes in the background and want to fetch some values:

E.g

Your data balance left is 400 MB, validity is 20 APR 2017. (need to extract '400 MB')

Your data balance left is 0.04 GB, validity is 20 APR 2017. (I need to extract 0.04 GB)

and so on...

How can I ? Can anyone please help. How can I do these types of splits

答:
I am not sure if your crawler is geting the same info msga but for sure you can use regex to match the info you need...</p>

```<code>String str = "Your data balance left is 400 MB, validity is 20 APR 2017. (need to extract '400 MB')\n"
            + "Your data balance left is 0.04 GB, validity is 20 APR 2017. (I need to extract 0.04 GB)";

Matcher myMatcher = Pattern.compile(Pattern.quote("left is") + "(.*?)" + Pattern.quote(", validity is"))
            .matcher(str);
while (myMatcher.find()) {
     String result = myMatcher.group(1).trim();
     String[] spltter = result.split(" ");
     System.out.println("result: " + result);
     System.out.println("value: " + spltter[0]);
     System.out.println("result: " + spltter[1]);
}
</code>```

Title: Pattern Matcher Android Split a String

Body:
I am not sure if your crawler is geting the same info msga but for sure you can use regex to match the info you need...

String str = "Your data balance left is 400 MB, validity is 20 APR 2017. (need to extract '400 MB')\n"
            + "Your data balance left is 0.04 GB, validity is 20 APR 2017. (I need to extract 0.04 GB)";

Matcher myMatcher = Pattern.compile(Pattern.quote("left is") + "(.*?)" + Pattern.quote(", validity is"))
            .matcher(str);
while (myMatcher.find()) {
     String result = myMatcher.group(1).trim();
     String[] spltter = result.split(" ");
     System.out.println("result: " + result);
     System.out.println("value: " + spltter[0]);
     System.out.println("result: " + spltter[1]);
}


问:
Understanding RSpec Failure
I'm getting these failures when running rspec spec/. The spec that is failing is was auto-generated with the scaffolding. I'm trying to understand RSpec but I don't know where to begin looking for the cause other than it feels like some method is missing?!? Yet, app appears to be working fine. Nothing about these failures appears in test.log. Is there another place I should be looking for hints to track this down?

```<code>$ rspec spec/
.....................F.F.

Failures:

  1) clowns/edit.html.haml renders the edit clown form
     Failure/Error: render
     undefined method `to_sym' for nil:NilClass
     # ./app/views/clowns/_form.html.haml:4:in `block in _app_views_clowns__form_html_haml__3590088286240866241_2176114460_3896491916910336970'
     # ./app/views/clowns/_form.html.haml:1:in `_app_views_clowns__form_html_haml__3590088286240866241_2176114460_3896491916910336970'
     # ./app/views/clowns/edit.html.haml:3:in `_app_views_clowns_edit_html_haml___574620942879655923_2176081980_599706797287605391'
     # ./spec/views/clowns/edit.html.haml_spec.rb:13:in `block (2 levels) in <top (required)>'

  2) clowns/new.html.haml renders new clown form
     Failure/Error: render
     undefined method `to_sym' for nil:NilClass
     # ./app/views/clowns/_form.html.haml:4:in `block in _app_views_clowns__form_html_haml__3590088286240866241_2176114460_3896491916910336970'
     # ./app/views/clowns/_form.html.haml:1:in `_app_views_clowns__form_html_haml__3590088286240866241_2176114460_3896491916910336970'
     # ./app/views/clowns/new.html.haml:3:in `_app_views_clowns_new_html_haml__1085372210838170129_2159651900_599706797287605391'
     # ./spec/views/clowns/new.html.haml_spec.rb:12:in `block (2 levels) in <top (required)>'

Finished in 1.03 seconds
27 examples, 2 failures, 2 pending
</code>```

And here is the spec that apparently fails (edit.html.haml_spec.rb). It was auto-generated by rails g scaffold Clown name:string balloons:integer:

```<code>#spec/views/clowns/edit.html.haml_spec.rb
require 'spec_helper'

describe "clowns/edit.html.haml" do
  before(:each) do
    @clown = assign(:clown, stub_model(Clown,
      :name => "MyString",
      :balloons => 1
    ))
  end

  it "renders the edit clown form" do
    render

    # Run the generator again with the --webrat-matchers flag if you want to use webrat matchers
    assert_select "form", :action => clown_path(@clown), :method => "post" do
      assert_select "input#clown_name", :name => "clown[name]"
      assert_select "input#clown_balloons", :name => "clown[balloons]"
    end
  end
end
</code>```

答:
Are you also using simple_form (or perhaps even formtastic)?  I get the same error when I convert the scaffold forms from standards forms to simple_form forms (form_for(@user) => simple_form_for(@user)).

It still works, as you say, so I'm not sure it's worth worrying about.  I think you'd be better off just letting Cucumber worry about it.  Sarah Mei says view specs are a waste of time. :-)

ContentLicense: CC BY-SA 2.5

Title: Understanding RSpec Failure

Body:
I'm getting these failures when running rspec spec/. The spec that is failing is was auto-generated with the scaffolding. I'm trying to understand RSpec but I don't know where to begin looking for the cause other than it feels like some method is missing?!? Yet, app appears to be working fine. Nothing about these failures appears in test.log. Is there another place I should be looking for hints to track this down?

$ rspec spec/
.....................F.F.

Failures:

  1) clowns/edit.html.haml renders the edit clown form
     Failure/Error: render
     undefined method `to_sym' for nil:NilClass
     # ./app/views/clowns/_form.html.haml:4:in `block in _app_views_clowns__form_html_haml__3590088286240866241_2176114460_3896491916910336970'
     # ./app/views/clowns/_form.html.haml:1:in `_app_views_clowns__form_html_haml__3590088286240866241_2176114460_3896491916910336970'
     # ./app/views/clowns/edit.html.haml:3:in `_app_views_clowns_edit_html_haml___574620942879655923_2176081980_599706797287605391'
     # ./spec/views/clowns/edit.html.haml_spec.rb:13:in `block (2 levels) in <top (required)>'

  2) clowns/new.html.haml renders new clown form
     Failure/Error: render
     undefined method `to_sym' for nil:NilClass
     # ./app/views/clowns/_form.html.haml:4:in `block in _app_views_clowns__form_html_haml__3590088286240866241_2176114460_3896491916910336970'
     # ./app/views/clowns/_form.html.haml:1:in `_app_views_clowns__form_html_haml__3590088286240866241_2176114460_3896491916910336970'
     # ./app/views/clowns/new.html.haml:3:in `_app_views_clowns_new_html_haml__1085372210838170129_2159651900_599706797287605391'
     # ./spec/views/clowns/new.html.haml_spec.rb:12:in `block (2 levels) in <top (required)>'

Finished in 1.03 seconds
27 examples, 2 failures, 2 pending

And here is the spec that apparently fails (edit.html.haml_spec.rb). It was auto-generated by rails g scaffold Clown name:string balloons:integer:

#spec/views/clowns/edit.html.haml_spec.rb
require 'spec_helper'

describe "clowns/edit.html.haml" do
  before(:each) do
    @clown = assign(:clown, stub_model(Clown,
      :name => "MyString",
      :balloons => 1
    ))
  end

  it "renders the edit clown form" do
    render

    # Run the generator again with the --webrat-matchers flag if you want to use webrat matchers
    assert_select "form", :action => clown_path(@clown), :method => "post" do
      assert_select "input#clown_name", :name => "clown[name]"
      assert_select "input#clown_balloons", :name => "clown[balloons]"
    end
  end
end


问:
Xcode FIRRemoteConfig Build error
In my xcode project, firebase realtime database and Analytics already implemented and working successfully. To implement, Firebase remote config feature, I added FirebaseRemoteConfig.framework and Protobuf.framework into my project. I am getting build error with following message. I have not write any code yet related with remote config.

```<code>Undefined symbols for architecture arm64:
  "_kFIRAppIsDefaultAppKey", referenced from:
      +[FIRRemoteConfig(FIRApp) receivedReadyToConfigureNotification:] in FirebaseRemoteConfig(FIRRemoteConfig+FIRApp_718fa6fc16d7fc9251249ec4e3a58ce2.o)
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

Here is all framework that I added into my project.

答: I have found solution of this issue. First you need to add all the updated frameworks of firebase. If you are using it. In my case I was having older version of firebase sdks. I just updated it & error went off. Happy Coding :)</p>

Title: Xcode FIRRemoteConfig Build error

Body:
In my xcode project, firebase realtime database and Analytics already implemented and working successfully. To implement, Firebase remote config feature, I added FirebaseRemoteConfig.framework and Protobuf.framework into my project. I am getting build error with following message. I have not write any code yet related with remote config.

Undefined symbols for architecture arm64:
  "_kFIRAppIsDefaultAppKey", referenced from:
      +[FIRRemoteConfig(FIRApp) receivedReadyToConfigureNotification:] in FirebaseRemoteConfig(FIRRemoteConfig+FIRApp_718fa6fc16d7fc9251249ec4e3a58ce2.o)
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Here is all framework that I added into my project.


问:
How to correctly implement "hamburger" to back button functionality when using Fragments
How to move to a new fragment and automatically have the "hamburger" menu change to a <- button which brings the user back to the previous menu?

This seems to be an arcane art, no matter how many stackoverflow questions I read and things I try the "hamburger" menu always just opens the drawer. I am getting confused with certain posts using backstacklisteners to change icons, others using the onoptionselected and others directly attaching a click listener.

Activity

```<code>    public class MainActivity extends AppCompatActivity {

        private ActionBarDrawerToggle drawerToggle;
        private ActionBar actionBar;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            setToolbar();
            // show first fragment here
        }

        private void setToolbar() {
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            actionBar = getSupportActionBar();

            if (actionBar != null) {
                actionBar.setDisplayHomeAsUpEnabled(true);
                DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer);
                drawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.open, R.string.close);
                drawerToggle.setDrawerIndicatorEnabled(true);
                drawerToggle.syncState();
            }
        }

        @Override
        protected void onPostCreate(Bundle savedInstanceState) {
            super.onPostCreate(savedInstanceState);
            drawerToggle.syncState();
        }

        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
            drawerToggle.onConfigurationChanged(newConfig);
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.toolbar_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.mnuSettings:
                showSettingsFragment();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void showSettingsFragment() {
        getFragmentManager()
                .beginTransaction()
                .replace(R.id.fragHolder, new SettingsFragment())
                .addToBackStack(null)
                .commit();
    }
}
</code>```

Activity Layout

```<code><?xml version="1.0" encoding="utf-8"?>

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                        xmlns:app="http://schemas.android.com/apk/res-auto"
                                        xmlns:tools="http://schemas.android.com/tools"
                                        android:id="@+id/drawer"
                                        android:layout_width="match_parent"
                                        android:layout_height="match_parent"
                                        android:fitsSystemWindows="true">

    <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:orientation="vertical">

        <android.support.design.widget.AppBarLayout
             android:layout_width="match_parent"
             android:layout_height="wrap_content">

            <android.support.v7.widget.Toolbar
                 android:id="@+id/toolbar"
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:background="@color/primary"
                 android:minHeight="?attr/actionBarSize"
                 app:popupTheme="@style/Theme.AppCompat.Light"
                 app:theme="@style/Theme.AppCompat">

            </android.support.v7.widget.Toolbar>

            <FrameLayout
                 android:id="@+id/pnlSearch"
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:layout_margin="8dp">

                <EditText
                     android:id="@+id/txtSearch"
                     android:layout_width="match_parent"
                     android:layout_height="44dp"
                     android:background="#FAFAFA"
                     android:gravity="center"
                     android:hint="@string/search_hint"
                     android:imeOptions="flagNoExtractUi|actionDone"
                     android:inputType="textNoSuggestions"
                     android:maxLines="1"
                     android:textSize="16sp"/>

                <ImageView
                     android:layout_width="24dp"
                     android:layout_height="24dp"
                     android:layout_gravity="start|center_vertical"
                     android:layout_marginLeft="15dp"
                     android:layout_marginStart="15dp"
                     android:alpha="0.2"
                     android:contentDescription="@string/magnifying_glass_icon"
                     android:src="@drawable/ic_search_black_24dp"/>

                <Button
                     android:id="@+id/btnClear"
                     android:layout_width="24dp"
                     android:layout_height="24dp"
                     android:layout_gravity="end|center_vertical"
                     android:layout_marginEnd="15dp"
                     android:layout_marginRight="15dp"
                     android:alpha="0.5"
                     android:background="@drawable/ic_clear_black_24dp"
                     android:visibility="gone"/>

            </FrameLayout>

        </android.support.design.widget.AppBarLayout>

        <FrameLayout
             android:id="@+id/fragHolder"
             android:layout_width="match_parent"
             android:layout_height="match_parent"/>

    </LinearLayout>

    <android.support.design.widget.NavigationView
         android:layout_width="wrap_content"
         android:layout_height="match_parent"
         android:layout_gravity="start"
         app:headerLayout="@layout/nav_header"
         app:menu="@menu/toolbar_menu"/>

</android.support.v4.widget.DrawerLayout>
</code>```

SettingsFragment:

```<code>public class SettingsFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        addPreferencesFromResource(R.xml.preferences);
    }

    @Override
    public void onResume() {
        super.onResume();
        setToolbarTitle();
    }

    private void setToolbarTitle() {
        ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle(R.string.settings);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                getFragmentManager().popBackStack();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}
</code>```

What I am looking for is the standard way to acheive this and not to start adding click/backstack listeners without understanding how its really meant to be done.

答:
Mike M.'s answer helped me immensly. Once I had it working I slowly removed code until the wrapper was half its size, then I realised the whole thing was working because of one line:

toggle.setDrawerIndicatorEnabled(false);

At which point, I thought it best to remove the wrapper altogether and use the following code to acheive the same functionality. I feel this is the best way to go about it.

```<code>public class MainActivity extends AppCompatActivity implements FragmentManager.OnBackStackChangedListener
...
private void setToolbar() {
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();

    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer);
        drawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.open, R.string.close);
        drawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        drawerToggle.syncState();
    }
}

@Override
public void onBackStackChanged() {
    boolean onHomeScreen = getFragmentManager().getBackStackEntryCount() == 0;
    drawerToggle.setDrawerIndicatorEnabled(onHomeScreen);
}
</code>```

And if I wanted to get rid of the title setting code in the detail fragments, or any fragments which add to the backstack I could do:

```<code>if (!onHomeScreen) {
    String fragmentTitle = getFragmentManager()
            .findFragmentById(R.id.fragHolder)
            .getClass()
            .getSimpleName()
            .replaceAll("(\\p{Ll})(\\p{Lu})", "$1 $2")
            .replace("Fragment", "");
    actionBar.setTitle(fragmentTitle);
}
</code>```

This would make the SettingsFragment have the title of Settings and UserDetailsFragment to User Details.

Body:
How to move to a new fragment and automatically have the "hamburger" menu change to a <- button which brings the user back to the previous menu?

This seems to be an arcane art, no matter how many stackoverflow questions I read and things I try the "hamburger" menu always just opens the drawer. I am getting confused with certain posts using backstacklisteners to change icons, others using the onoptionselected and others directly attaching a click listener.

Activity

    public class MainActivity extends AppCompatActivity {

        private ActionBarDrawerToggle drawerToggle;
        private ActionBar actionBar;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            setToolbar();
            // show first fragment here
        }

        private void setToolbar() {
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            actionBar = getSupportActionBar();

            if (actionBar != null) {
                actionBar.setDisplayHomeAsUpEnabled(true);
                DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer);
                drawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.open, R.string.close);
                drawerToggle.setDrawerIndicatorEnabled(true);
                drawerToggle.syncState();
            }
        }

        @Override
        protected void onPostCreate(Bundle savedInstanceState) {
            super.onPostCreate(savedInstanceState);
            drawerToggle.syncState();
        }

        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
            drawerToggle.onConfigurationChanged(newConfig);
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.toolbar_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.mnuSettings:
                showSettingsFragment();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void showSettingsFragment() {
        getFragmentManager()
                .beginTransaction()
                .replace(R.id.fragHolder, new SettingsFragment())
                .addToBackStack(null)
                .commit();
    }
}

Activity Layout

<?xml version="1.0" encoding="utf-8"?>

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                        xmlns:app="http://schemas.android.com/apk/res-auto"
                                        xmlns:tools="http://schemas.android.com/tools"
                                        android:id="@+id/drawer"
                                        android:layout_width="match_parent"
                                        android:layout_height="match_parent"
                                        android:fitsSystemWindows="true">

    <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:orientation="vertical">

        <android.support.design.widget.AppBarLayout
             android:layout_width="match_parent"
             android:layout_height="wrap_content">

            <android.support.v7.widget.Toolbar
                 android:id="@+id/toolbar"
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:background="@color/primary"
                 android:minHeight="?attr/actionBarSize"
                 app:popupTheme="@style/Theme.AppCompat.Light"
                 app:theme="@style/Theme.AppCompat">

            </android.support.v7.widget.Toolbar>

            <FrameLayout
                 android:id="@+id/pnlSearch"
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:layout_margin="8dp">

                <EditText
                     android:id="@+id/txtSearch"
                     android:layout_width="match_parent"
                     android:layout_height="44dp"
                     android:background="#FAFAFA"
                     android:gravity="center"
                     android:hint="@string/search_hint"
                     android:imeOptions="flagNoExtractUi|actionDone"
                     android:inputType="textNoSuggestions"
                     android:maxLines="1"
                     android:textSize="16sp"/>

                <ImageView
                     android:layout_width="24dp"
                     android:layout_height="24dp"
                     android:layout_gravity="start|center_vertical"
                     android:layout_marginLeft="15dp"
                     android:layout_marginStart="15dp"
                     android:alpha="0.2"
                     android:contentDescription="@string/magnifying_glass_icon"
                     android:src="@drawable/ic_search_black_24dp"/>

                <Button
                     android:id="@+id/btnClear"
                     android:layout_width="24dp"
                     android:layout_height="24dp"
                     android:layout_gravity="end|center_vertical"
                     android:layout_marginEnd="15dp"
                     android:layout_marginRight="15dp"
                     android:alpha="0.5"
                     android:background="@drawable/ic_clear_black_24dp"
                     android:visibility="gone"/>

            </FrameLayout>

        </android.support.design.widget.AppBarLayout>

        <FrameLayout
             android:id="@+id/fragHolder"
             android:layout_width="match_parent"
             android:layout_height="match_parent"/>

    </LinearLayout>

    <android.support.design.widget.NavigationView
         android:layout_width="wrap_content"
         android:layout_height="match_parent"
         android:layout_gravity="start"
         app:headerLayout="@layout/nav_header"
         app:menu="@menu/toolbar_menu"/>

</android.support.v4.widget.DrawerLayout>

SettingsFragment:

public class SettingsFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        addPreferencesFromResource(R.xml.preferences);
    }

    @Override
    public void onResume() {
        super.onResume();
        setToolbarTitle();
    }

    private void setToolbarTitle() {
        ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle(R.string.settings);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                getFragmentManager().popBackStack();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

What I am looking for is the standard way to acheive this and not to start adding click/backstack listeners without understanding how its really meant to be done.

Body:
Mike M.'s answer helped me immensly. Once I had it working I slowly removed code until the wrapper was half its size, then I realised the whole thing was working because of one line:

toggle.setDrawerIndicatorEnabled(false);

At which point, I thought it best to remove the wrapper altogether and use the following code to acheive the same functionality. I feel this is the best way to go about it.

public class MainActivity extends AppCompatActivity implements FragmentManager.OnBackStackChangedListener
...
private void setToolbar() {
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();

    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer);
        drawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.open, R.string.close);
        drawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        drawerToggle.syncState();
    }
}

@Override
public void onBackStackChanged() {
    boolean onHomeScreen = getFragmentManager().getBackStackEntryCount() == 0;
    drawerToggle.setDrawerIndicatorEnabled(onHomeScreen);
}

And if I wanted to get rid of the title setting code in the detail fragments, or any fragments which add to the backstack I could do:

if (!onHomeScreen) {
    String fragmentTitle = getFragmentManager()
            .findFragmentById(R.id.fragHolder)
            .getClass()
            .getSimpleName()
            .replaceAll("(\\p{Ll})(\\p{Lu})", "$1 $2")
            .replace("Fragment", "");
    actionBar.setTitle(fragmentTitle);
}

This would make the SettingsFragment have the title of Settings and UserDetailsFragment to User Details.


问:
Why does SSL Labs test say that HSTS is enabled when the header is sent over HTTP, but not when sent over HTTPS?
I'm trying to configure HSTS on my server. I've noticed that the test on SSLLabs.com will tell me that HSTS has been enabled if I send the HSTS header over the initial unencrypted HTTP connection. This, however, is in violation of the HSTS spec according to RFC-6797 Section 7.2, which clearly states that you should NOT send this header over an unencrypted connection.

On the other hand, if my server sends out that HSTS header ONLY after doing a 302 redirect from HTTP to HTTPS, which is precisely what the official HSTS spec says you SHOULD do, then SSL Labs does NOT acknowledge that I have HSTS enabled.

So what am I missing here? What's the actual correct way to do this?

If you want to see what I'm talking about, the site in question is
nightowlcircusarts.com

You can view the unencrypted headers using curl with this bash command:

```<code>curl -I http://www.nightowlcircusarts.com/
</code>```

Or change that http to https to see the encrypted headers:

```<code>curl -I https://www.nightowlcircusarts.com/
</code>```

Currently, I have it configured to ONLY send that header over TLS, and not without it, as the HSTS spec says to do. But you'll see that the SSL Labs test still says I DON'T have HSTS enabled:
https://www.ssllabs.com/ssltest/analyze.html?d=nightowlcircusarts.com

答:
Well for a start ssllabs does not scan sites on unencrypted connections - only on encrypted ones (https). So it will not tell you that you have it enabled on http.

Your issue is that nightowlcircusarts.com and www.nightowlcircusarts.com are two different sites and you are only setting it on the latter but scanning it on the former:

https://www.ssllabs.com/ssltest/analyze.html?d=nightowlcircusarts.com

https://www.ssllabs.com/ssltest/analyze.html?d=www.nightowlcircusarts.com

Now the scan results do show, at the bottom, that the bare domain does redirect to the www version, but ssllabs is tasked with testing the SSL/TLS connection (which happens before redirects) so it deliberately does not follow redirects and instead reports the SSL/TLS connection config. It expects you to scan the redirect site separately - precisely for use cases like this where you have it set up differently!

I guess when you "send the HSTS header over the initial unencrypted HTTP connection", what you are actually doing is setting it everywhere (including the bare domain over https) which is why you thought it "worked" when you did that.

It is permissible (and expected!) to set HSTS over https-to-https redirects. And in fact your specific example is covered in the RFC in section 11.4.1.

Btw adding HSTS to the bare domain is best practice, but do ensure your entire domain is only ever served over https. If you have one subsite (e.g. blog.example.com) or also use this for non public sites which are not yet secured (e.g. intranet.example.com) then this can cause problems. In this case you could add HSTS to bare domain but without the includeSubdomain option - though that will not give you the full protection of HSTS.

Lastly, if checking out the various security Headers of a site rather than the SSL/TLS config then https://securityheaders.io is a great site and a lot quicker to run than the whole set of SSL/TLS tests that ssllabs does:

https://securityheaders.io/?q=https%3A%2F%2Fnightowlcircusarts.com

https://securityheaders.io/?q=https%3A%2F%2Fwww.nightowlcircusarts.com

Note these two sites check for different things, so one us not a replacement of another (big fan of both!), but some settings (HSTS and HPKP) are shown by both. And while on the subject be very careful with HPKP (I am not a fan and do not think it should be widely used at all).

Body:
I'm trying to configure HSTS on my server. I've noticed that the test on SSLLabs.com will tell me that HSTS has been enabled if I send the HSTS header over the initial unencrypted HTTP connection. This, however, is in violation of the HSTS spec according to RFC-6797 Section 7.2, which clearly states that you should NOT send this header over an unencrypted connection.

On the other hand, if my server sends out that HSTS header ONLY after doing a 302 redirect from HTTP to HTTPS, which is precisely what the official HSTS spec says you SHOULD do, then SSL Labs does NOT acknowledge that I have HSTS enabled.

So what am I missing here? What's the actual correct way to do this?

If you want to see what I'm talking about, the site in question is
nightowlcircusarts.com

You can view the unencrypted headers using curl with this bash command:

curl -I http://www.nightowlcircusarts.com/

Or change that http to https to see the encrypted headers:

curl -I https://www.nightowlcircusarts.com/

Currently, I have it configured to ONLY send that header over TLS, and not without it, as the HSTS spec says to do. But you'll see that the SSL Labs test still says I DON'T have HSTS enabled:
https://www.ssllabs.com/ssltest/analyze.html?d=nightowlcircusarts.com


问:
Results duplicating
My code below is duplicating my department name results and I don't know why. I need to display the name of the department, job id for the employees who work there and their salary. Plus I need to figure out if department_id or job_id was used in the CUBE expression.

```<code>SELECT d.department_name AS "Name",
       e.job_id AS "Job ID",
       SUM(e.salary) AS "salary",
       DECODE(GROUPING(d.department_id),1, 'Yes', 'No') AS "Department Used",
       DECODE(GROUPING(e.job_id), 1, 'Yes', 'No') AS "Job used"
FROM employees e
    full OUTER JOIN departments d
    ON (e.department_id = d.department_id)
GROUP BY CUBE(d.department_name, e.job_id, d.department_id)
ORDER BY d.department_name;
</code>```

答:
The problem is your CUBE() clause: you include two attributes from DEPARTMENT, so the results are cubed for all combinations of DEPARTMENT_ID and DEPARTMENT_NAME.

However, these two columns are correlated: there's a one to one relationship between ID and NAME (assuming you're using the HR schema or some other decent data model).

So the solution is quite simple: change the CUBE() clause to use one. As DEPARTMENT_NAME is in the projection that's the one to pick. You'll need to change the DECODE() to match.

```<code>SELECT d.department_name AS "Name",
       e.job_id AS "Job ID",
       SUM(e.salary) AS "salary",
       DECODE(GROUPING(d.department_name),1, 'Yes', 'No') AS "Department Used",
       DECODE(GROUPING(e.job_id), 1, 'Yes', 'No') AS "Job used"
FROM employees e
    full OUTER JOIN departments d
    ON (e.department_id = d.department_id)
GROUP BY CUBE(d.department_name, e.job_id)
ORDER BY d.department_name;
</code>```

Title: Results duplicating

Body:
My code below is duplicating my department name results and I don't know why. I need to display the name of the department, job id for the employees who work there and their salary. Plus I need to figure out if department_id or job_id was used in the CUBE expression.

SELECT d.department_name AS "Name",
       e.job_id AS "Job ID",
       SUM(e.salary) AS "salary",
       DECODE(GROUPING(d.department_id),1, 'Yes', 'No') AS "Department Used",
       DECODE(GROUPING(e.job_id), 1, 'Yes', 'No') AS "Job used"
FROM employees e
    full OUTER JOIN departments d
    ON (e.department_id = d.department_id)
GROUP BY CUBE(d.department_name, e.job_id, d.department_id)
ORDER BY d.department_name;

Body:
The problem is your CUBE() clause: you include two attributes from DEPARTMENT, so the results are cubed for all combinations of DEPARTMENT_ID and DEPARTMENT_NAME.

However, these two columns are correlated: there's a one to one relationship between ID and NAME (assuming you're using the HR schema or some other decent data model).

So the solution is quite simple: change the CUBE() clause to use one. As DEPARTMENT_NAME is in the projection that's the one to pick. You'll need to change the DECODE() to match.

SELECT d.department_name AS "Name",
       e.job_id AS "Job ID",
       SUM(e.salary) AS "salary",
       DECODE(GROUPING(d.department_name),1, 'Yes', 'No') AS "Department Used",
       DECODE(GROUPING(e.job_id), 1, 'Yes', 'No') AS "Job used"
FROM employees e
    full OUTER JOIN departments d
    ON (e.department_id = d.department_id)
GROUP BY CUBE(d.department_name, e.job_id)
ORDER BY d.department_name;


问:
Compilation errors in simple Java program with Scanner
```<code>import java.util.*;
public class strings {
    public static void main (String [] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = keyboard.next();
        System.out.print("Type your seconds integer : ");
        int second = keyboard.next();
        System.out.print("The sum of your two integers are:");
    }
}
</code>```

<p>I dont know why im getting 2 errors on strings cannot converted to int. </p>

答:
Scanner class next() method returns String value. You can do anyone of the following steps to solve the compilation error.

You need to convert the String value to int.

```<code>int first = Integer.parseInt(keyboard.next());
</code>```

You can use nextInt() method to get int value directly from the user.

Body:
import java.util.*;
public class strings {
    public static void main (String [] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = keyboard.next();
        System.out.print("Type your seconds integer : ");
        int second = keyboard.next();
        System.out.print("The sum of your two integers are:");
    }
}

I dont know why im getting 2 errors on strings cannot converted to int.

Body:
Scanner class next() method returns String value. You can do anyone of the following steps to solve the compilation error.

You need to convert the String value to int.

int first = Integer.parseInt(keyboard.next());

You can use nextInt() method to get int value directly from the user.


问:
Pandas dataframe to json list format
I have large pandas tabular dataframe to convert into JSON.
The standard .to_json() functions does not make a compact format for JSON.
How to get JSON output forma like this,  using pandas only ?

```<code>{"index": [ 0, 1 ,3 ],
 "col1": [ "250", "1" ,"3" ],
 "col2": [ "250", "1" ,"3" ]
}
</code>```

This is a much compact format form of JSON for tabular data.
(I can do a loop over the rows.... but)

答:
You can use to_dict and json (and add the index as extra column if required via assign):

```<code>import json

df = pd.DataFrame({"col1": [250, 1, 3],
                   "col2": [250, 1, 3]})

json_dict = df.assign(index=df.index).to_dict(orient="list")
print(json.dumps(json_dict))

>>> '{"index": [0, 1, 2], "col1": [250, 1, 3], "col2": [250, 1, 3]}'
</code>```

Title: Pandas dataframe to json list format

Body:
I have large pandas tabular dataframe to convert into JSON.
The standard .to_json() functions does not make a compact format for JSON.
How to get JSON output forma like this,  using pandas only ?

{"index": [ 0, 1 ,3 ],
 "col1": [ "250", "1" ,"3" ],
 "col2": [ "250", "1" ,"3" ]
}

This is a much compact format form of JSON for tabular data.
(I can do a loop over the rows.... but)

Body:
You can use to_dict and json (and add the index as extra column if required via assign):

import json

df = pd.DataFrame({"col1": [250, 1, 3],
                   "col2": [250, 1, 3]})

json_dict = df.assign(index=df.index).to_dict(orient="list")
print(json.dumps(json_dict))

>>> '{"index": [0, 1, 2], "col1": [250, 1, 3], "col2": [250, 1, 3]}'


问:
Create the page with hyperlinks from txt file
I would like to know if you can create a php page, by importing data from a txt file, let me explain better (I hope) I have a .txt file which is composed as follows:

```<code>Link 1
http://www.example.com/index1.php
Link 2
http://www.example.com/index2.php
Link 3
http://www.example.com/index3.php
</code>```

is possible with a php script to create a page in php so

```<code><a href="http://www.example.com/index1.php">Link 1</a>
<a href="http://www.example.com/index2.php">Link 2</a>
<a href="http://www.example.com/index3.php">Link 3</a>
</code>```

how can I do,thank you

答:
```<code><?php
   $links = File("put path to file here");
   foreach ($links as $key=>$val)
      if ($key%2) $link_name = $val;
        else
           print "<a href='$val'>$link_name</a>";

?>
</code>```

Body:
I would like to know if you can create a php page, by importing data from a txt file, let me explain better (I hope) I have a .txt file which is composed as follows:

Link 1
http://www.example.com/index1.php
Link 2
http://www.example.com/index2.php
Link 3
http://www.example.com/index3.php

is possible with a php script to create a page in php so

Link 1
Link 2
Link 3

how can I do,thank you


问:
Spinner in fragment becomes slow?
I added a spinner in a fragment. It works but not as i expected. The spinner when being selected is very slow and becomes unresponsive. In the logcat without a filter, it would return the error message : Window already focused, ignoring focus gain of spinner and W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.   here is my code : `

```<code>public class FourthTab extends Fragment implements OnItemSelectedListener` {

private View rootView;
private ViewGroup container;

public FourthTab() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.fourth_tab, container, false);
    this.container = container;

    makeSpinner(rootView, getContext());

    return rootView;
}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    // On selecting a spinner item
    String item = parent.getItemAtPosition(position).toString();

    // Showing selected spinner item

    //TextView tes = (TextView) rootView.findViewById(R.id.tes);
    //tes.setText(item);

    Handler mhandler = new Handler();
    mhandler.postDelayed(new DisplayToast(getContext(), "Selected2: " + item), 100 );

}
public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub
}

/*agar prosess calling ke network hanya dilakukan apabila fragment terlihat    */
@Override
public void setUserVisibleHint(boolean visible)
{
    super.setUserVisibleHint(visible);
    if (visible && isResumed())
    {
        //Only manually call onResume if fragment is already visible
        //Otherwise allow natural fragment lifecycle to call onResume
        onResume();
    }
}

@Override
public void onResume()
{
    super.onResume();
    if (!getUserVisibleHint())
    {
        return;
    }

}

private void makeSpinner(View rootView, Context context) {

    // Spinner element
    Spinner spinner = (Spinner) rootView.findViewById(R.id.semester_spinner);

    // Spinner click listener
    spinner.setOnItemSelectedListener(this);

    // Spinner Drop down elements
    List<String> categories = new ArrayList<String>();
    categories.add("Automobile");
    categories.add("Business Services");
    categories.add("Computers");
    categories.add("Education");
    categories.add("Personal");
    categories.add("Travel");

    // Creating adapter for spinner
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_spinner_item, categories);

    // Drop down layout style - list view with radio button
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // attaching data adapter to spinner
    spinner.setAdapter(dataAdapter);

}
</code>```

Please, can someone suggest what is happening to it? I already tried this method : https://www.laurivan.com/attempted-to-finish-an-input-event/
 but it still didnt work and I tried to find this error on Google Window already focused, W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed. ignoring focus gain of spinner here is my code but never get any good point. Thank u

```<code>public class DisplayToast implements Runnable {
private final Context mContext;
private final String mText;

public DisplayToast(Context mContext, String text) {
    this.mContext = mContext;
    mText = text;
}

public void run() {
    Toast.makeText(mContext, mText, Toast.LENGTH_SHORT).show();
}
</code>```

答:
as someone comment on my question i become suspicious that this about the integrated device / emulator. so i install genymotion emulator to try this. fortunately it works.

the default emulator is : Nexus 5 API 21
and the geny motion emulator is samsung S3

hope it would make other get informed

Title: Spinner in fragment becomes slow?

Body:
I added a spinner in a fragment. It works but not as i expected. The spinner when being selected is very slow and becomes unresponsive. In the logcat without a filter, it would return the error message : Window already focused, ignoring focus gain of spinner and W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.   here is my code : `

public class FourthTab extends Fragment implements OnItemSelectedListener` {

private View rootView;
private ViewGroup container;

public FourthTab() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.fourth_tab, container, false);
    this.container = container;

    makeSpinner(rootView, getContext());

    return rootView;
}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    // On selecting a spinner item
    String item = parent.getItemAtPosition(position).toString();

    // Showing selected spinner item

    //TextView tes = (TextView) rootView.findViewById(R.id.tes);
    //tes.setText(item);

    Handler mhandler = new Handler();
    mhandler.postDelayed(new DisplayToast(getContext(), "Selected2: " + item), 100 );

}
public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub
}

/*agar prosess calling ke network hanya dilakukan apabila fragment terlihat    */
@Override
public void setUserVisibleHint(boolean visible)
{
    super.setUserVisibleHint(visible);
    if (visible && isResumed())
    {
        //Only manually call onResume if fragment is already visible
        //Otherwise allow natural fragment lifecycle to call onResume
        onResume();
    }
}

@Override
public void onResume()
{
    super.onResume();
    if (!getUserVisibleHint())
    {
        return;
    }

}

private void makeSpinner(View rootView, Context context) {

    // Spinner element
    Spinner spinner = (Spinner) rootView.findViewById(R.id.semester_spinner);

    // Spinner click listener
    spinner.setOnItemSelectedListener(this);

    // Spinner Drop down elements
    List<String> categories = new ArrayList<String>();
    categories.add("Automobile");
    categories.add("Business Services");
    categories.add("Computers");
    categories.add("Education");
    categories.add("Personal");
    categories.add("Travel");

    // Creating adapter for spinner
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_spinner_item, categories);

    // Drop down layout style - list view with radio button
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // attaching data adapter to spinner
    spinner.setAdapter(dataAdapter);

}

Please, can someone suggest what is happening to it? I already tried this method : https://www.laurivan.com/attempted-to-finish-an-input-event/
 but it still didnt work and I tried to find this error on Google Window already focused, W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed. ignoring focus gain of spinner here is my code but never get any good point. Thank u

public class DisplayToast implements Runnable {
private final Context mContext;
private final String mText;

public DisplayToast(Context mContext, String text) {
    this.mContext = mContext;
    mText = text;
}

public void run() {
    Toast.makeText(mContext, mText, Toast.LENGTH_SHORT).show();
}


问:
How does Go's heap interface work?
In Go, you can implement a heap as such: https://golang.org/src/container/heap/example_pq_test.go

You implement the sort.Interface, Pop, and Push and you've got yourself a priority queue/heap. In the example of both Pop and Push implementations the heap.Fix function isn't called. I see that heap.Init is called, so I can understand some heap-ifying happening then. However, you are able to push and pop items, which runs your own code, and the heap property is maintained.

If you push or pop items after init without calling heap.fix, how does the heap property get maintained?

Here's a playground of the example: https://play.golang.org/p/wE413xwmxE

答:
To keep heap implementation simple, you are only required to provide queuing logic for your custom type. Heapification is done by the heap package itself. It does so by calling the Push/Pop defined on your type, and then calling the heapification procedure:

```<code>// from golang.org/src/container/heap/heap.go

// Push pushes the element x onto the heap. The complexity is
// O(log(n)) where n = h.Len().
//
func Push(h Interface, x interface{}) {
    h.Push(x)        // call to Push defined on your custom type
    up(h, h.Len()-1) // **heapification**
}

// Pop removes the minimum element (according to Less) from the heap
// and returns it. The complexity is O(log(n)) where n = h.Len().
// It is equivalent to Remove(h, 0).
//
func Pop(h Interface) interface{} {
    n := h.Len() - 1
    h.Swap(0, n)
    down(h, 0, n) // **heapification**
    return h.Pop()
}
</code>```

Title: How does Go's heap interface work?

Body:
To keep heap implementation simple, you are only required to provide queuing logic for your custom type. Heapification is done by the heap package itself. It does so by calling the Push/Pop defined on your type, and then calling the heapification procedure:

// from golang.org/src/container/heap/heap.go

// Push pushes the element x onto the heap. The complexity is
// O(log(n)) where n = h.Len().
//
func Push(h Interface, x interface{}) {
    h.Push(x)        // call to Push defined on your custom type
    up(h, h.Len()-1) // **heapification**
}

// Pop removes the minimum element (according to Less) from the heap
// and returns it. The complexity is O(log(n)) where n = h.Len().
// It is equivalent to Remove(h, 0).
//
func Pop(h Interface) interface{} {
    n := h.Len() - 1
    h.Swap(0, n)
    down(h, 0, n) // **heapification**
    return h.Pop()
}


问:
How do I detect if ActiveX is enabled in the browser of client?
How do I detect if ActiveX is enabled in the browser of client?

I tried following code, but it's not working in Firefox.

```<code>window.ActiveXObject not working in Firefox
</code>```

any ideas?

check the example here: http://jsfiddle.net/qXSvQ/2/

I get false when I run this example.

答:
What isn't working?  Is that throwing an error in FF?  How about</p>

```<code>var hasAX = "ActiveXObject" in window;</code>```

OwnerDisplayName: twesh

Body:
How do I detect if ActiveX is enabled in the browser of client?

I tried following code, but it's not working in Firefox.

window.ActiveXObject not working in Firefox

any ideas?

check the example here: http://jsfiddle.net/qXSvQ/2/

I get false when I run this example.

Body:
What isn't working?  Is that throwing an error in FF?  How about

var hasAX = "ActiveXObject" in window;


问:
get output of query in source-edge-destination format
I am new to cypher. I am using the movie database of neo4j CE 3.1.2.
I want to get output of my query

```<code>match (a:Person)-[r]-(b:Movie) return a, r, b
</code>```

in the form source, edge, destination, for example

Tom Hanks, ACTED_IN, That Thing You Do

Tom Hanks, DIRECTED, That Thing You Do

Gary Sinise, ACTED_IN, The Green Mile

Basically I want a row for every source_node, destination_node connection.
Please help.

EDIT 1
If my graph is like A->B->C->D and if I want all down tree nodes of A, then my output should be like

A,connected,B

B,connected,C

C,connected,D

答:
You're looking at the graphical view of the results. If you look to the left of the graph, you'll see the ability to change to Row and Text views of the results, which should give you what you want...almost.

Output for relationships currently shows only properties on the relationships, not the type, so you may need to adjust your query slightly.

```<code>match (a:Person)-[r]-(b:Movie)
return a, type(r) as type, b
</code>```

If you want ONLY the person's name, the type of the relationship, and the movie title, then you'll need to return the properties from the nodes, not just the nodes themselves:

```<code>match (a:Person)-[r]-(b:Movie)
return a.name as name, type(r) as type, b.title as title
</code>```

Body:
I am new to cypher. I am using the movie database of neo4j CE 3.1.2.
I want to get output of my query

match (a:Person)-[r]-(b:Movie) return a, r, b

in the form source, edge, destination, for example

Tom Hanks, ACTED_IN, That Thing You Do

Tom Hanks, DIRECTED, That Thing You Do

Gary Sinise, ACTED_IN, The Green Mile

Basically I want a row for every source_node, destination_node connection.
Please help.

EDIT 1
If my graph is like A->B->C->D and if I want all down tree nodes of A, then my output should be like

A,connected,B

B,connected,C

C,connected,D

Body:
You're looking at the graphical view of the results. If you look to the left of the graph, you'll see the ability to change to Row and Text views of the results, which should give you what you want...almost.

Output for relationships currently shows only properties on the relationships, not the type, so you may need to adjust your query slightly.

match (a:Person)-[r]-(b:Movie)
return a, type(r) as type, b

If you want ONLY the person's name, the type of the relationship, and the movie title, then you'll need to return the properties from the nodes, not just the nodes themselves:

match (a:Person)-[r]-(b:Movie)
return a.name as name, type(r) as type, b.title as title


问:
Android studio: how to properly use the support library AppCompat?
I know there are many versions such as v4, v7, v8, v13, v14, v17, etc and they aren't in order of upgrades. What I don't understand is the meaning of this checkbox in Android Studio when you create a new project and choose an empty activity

Backwards compatibility (AppCompat)

The description says

if false, this activity will be Activity instead of AppCompatActivity

It's a bit foggy to me, then I checked the library and I found out that it was  android.support.v7.app.AppCompatActivity

The descriptions says that

v7 Support Libraries
  There are several libraries designed to be used with Android 2.3 (API level 9) and higher.

Again I don't understand whether I have to use it or not, depending on different cases. If I set the maximum target API, what is the necessary minSdk to not use it?

答:
It is not simple to answer your question.

The Support Libraries provide a wide range of classes for building apps, from fundamental app components, to user interface widgets, to media handling, to TV app components.

Many of the classes are backward compatible implementations, but some of them are new features in their own right.

It is very important this step. Not all support libraries are used to support backward implementation.

For example in your application you will need to use some components like:

RecyclerView

CardView

ViewPager

Design Library

.....

In particular the design support library has a dependency with the appcompat library.

It means that you can't avoid the use of the support libraries only using a minSdk. Or in other words you have to use them always.

Here more info about the support libraries.


问:
ReCaptcha within a Selenium browser
I am currently writing a script to automate the process of navigating through a handful of pages and fill a form; however, before the final form can be submitted a google ReCaptcha needs to be solved by the user. When my script reaches this point I have it stop so that I can complete the ReCaptcha and submit the form manually. Now this is where I am having issues. When I attempt to solve the ReCaptcha I always get an error that says 'Please Try Again' or something like that (Yes I am 100% sure I am solving them perfectly). While investigating this issue I also tried the audio option that ReCaptcha offers. This option does not even allow me to hear the audio, instead it says "We're sorry, but your computer or network may be sending automated queries. To protect our users, we can't process your request right now."

So, my question is: How do I prevent getting this error message when I am trying to solve the captcha manually? Do I need to add a delay to my script?

I am very confused and I do not know how to fix. Any help would be appreciated!!

答:
Performing manual operation while running automation scripts is not recommended.

Possible solution is please ask your dev team for a workaround, like configure CAPTCHA in test environment in such a way it will always accept 1 specific value.
or
ask to disable the CAPTCHA in testing environment.

Hope this link useful.

Title: ReCaptcha within a Selenium browser


问:
JSF 2 panelGrid column formatting - uniform alignment
I have a multi column form that I need to display and I used the JSF panelGrid component like this. each panelgrid is within a primefaces p:panel element

```<code><h:panelGrid columns="6" cellpadding="1" cellspacing="1" style="width: 100%"  columnClasses="column1">
</code>```

my column1 in CSS is:

```<code>.column1 {
width: 14%;
</code>```

}

It renders on screen like image below. Notice the columns within the panels are not aligned and it looks haphazard. How can I align the form elements/labels in a uniform manner and also get rid of the spaces and padding to make the form layout more compact.

Thanks in Advance BaluSC if you answer! You really are the king of JSF:-)

答:
I also have a multi-column form using JSF PanelGrid.

```<code><h:panelGrid id="panelGrid" columns="4" cellpadding="3"
        columnClasses="colLeft,colRight,colLeft,colRight">
        <p:outputLabel for="username" value="Username" />
        <p:inputText id="username" value="#{myBean.user.username}"
            required="true" />

        <p:outputLabel for="fullName" value="Full Name" />
        <p:inputText id="fullName" value="#{myBean.user.fullName}"
            required="true" />

        <p:outputLabel for="password" value="Password" />
        <p:password id="password" value="#{myBean.user.password}"
            required="true" match="passConfirm" />

        <p:outputLabel for="passConfirm"
            value="Re-type Password" />
        <p:password id="passConfirm" value="#{myBean.user.password}"
            required="true" />
</h:panelGrid>
</code>```

Here is CSS.

```<code>#panelGrid {
    width: 100%;
}

.colLeft {
    width: 15%;
}

.colRight {
    width: 35%;
}
</code>```

Here is output.

Hope it works!

Body:
I have a multi column form that I need to display and I used the JSF panelGrid component like this. each panelgrid is within a primefaces p:panel element

<h:panelGrid columns="6" cellpadding="1" cellspacing="1" style="width: 100%"  columnClasses="column1">

my column1 in CSS is:

.column1 {
width: 14%;

}

It renders on screen like image below. Notice the columns within the panels are not aligned and it looks haphazard. How can I align the form elements/labels in a uniform manner and also get rid of the spaces and padding to make the form layout more compact.

Thanks in Advance BaluSC if you answer! You really are the king of JSF:-)

Body:
I also have a multi-column form using JSF PanelGrid.

<h:panelGrid id="panelGrid" columns="4" cellpadding="3"
        columnClasses="colLeft,colRight,colLeft,colRight">
        <p:outputLabel for="username" value="Username" />
        <p:inputText id="username" value="#{myBean.user.username}"
            required="true" />

        <p:outputLabel for="fullName" value="Full Name" />
        <p:inputText id="fullName" value="#{myBean.user.fullName}"
            required="true" />

        <p:outputLabel for="password" value="Password" />
        <p:password id="password" value="#{myBean.user.password}"
            required="true" match="passConfirm" />

        <p:outputLabel for="passConfirm"
            value="Re-type Password" />
        <p:password id="passConfirm" value="#{myBean.user.password}"
            required="true" />
</h:panelGrid>

Here is CSS.

#panelGrid {
    width: 100%;
}

.colLeft {
    width: 15%;
}

.colRight {
    width: 35%;
}

Here is output.

Hope it works!


问:
React-bootstrap-router LinkContainer doesn't route anywhere
I use react-bootstrap-router where I want to link to /logout which logs out the user and routes them to the front-page(automatically, from the backend). I simply need to make what is essentially a href to it.

But LinkContainer doesnt appear to work?

Here's my sourcecode:

```<code>import { LinkContainer } from 'react-router-bootstrap';

<Dropdown id="dropdown-custom-1">
    <Dropdown.Toggle>
        <Glyphicon glyph="cog" />
    </Dropdown.Toggle>
    <Dropdown.Menu style={{textAlign: "left", right: "0", left: "auto"}}>
        <MenuItem className='disabled u-graph-text'>
            <Glyphicon glyph="user" style={{paddingRight: "10px"}}/>
            {this.state.data.username}
            </div>
        </MenuItem>
        <MenuItem divider />
        <LinkContainer to="/logout" activeClassName="active"> // It doesn't do anythign here?
            <MenuItem className="u-graph-text">
                log out
            </MenuItem>
        </LinkContainer>
    </Dropdown.Menu>
</Dropdown>
</code>```

Nothing changes in the URL of the browser.

答:
Not sure what exactly is the problem with your implementation. Maybe you are using React Router v4, which is not quite compatible with react-router-bootstrap. But if nothing proposed works then try to do it in a programmatic way:

```<code>import React from 'react';
import {Navbar, Nav, NavItem, NavDropdown, MenuItem} from 'react-bootstrap';
import {Route} from 'react-router-dom';

class YourComponent extends Component {
  constructor(props) {
    super(props);
    this.handleLink = this.handleLink.bind(this);
  }

  handleLink(path) {
    this.props.history.push(path);
  }
  render() {
    return (
      <Dropdown id="dropdown-custom-1">
        <Dropdown.Toggle>
          <Glyphicon glyph="cog" />
        </Dropdown.Toggle>
        <Dropdown.Menu style={{textAlign: "left", right: "0", left: "auto"}}>
          <MenuItem className='disabled u-graph-text'>
            <Glyphicon glyph="user" style={{paddingRight: "10px"}}/>
            {this.state.data.username}
          </div>
          </MenuItem>
          <MenuItem divider />
          <MenuItem className="u-graph-text" onClick={()=>this.handleLink("logout")}>
            log out
          </MenuItem>
        </Dropdown.Menu>
      </Dropdown>
    );
  }
}

YourComponent.propTypes = {};

export default YourComponent;
</code>```

Body:
I use react-bootstrap-router where I want to link to /logout which logs out the user and routes them to the front-page(automatically, from the backend). I simply need to make what is essentially a href to it.

But LinkContainer doesnt appear to work?

Here's my sourcecode:

import { LinkContainer } from 'react-router-bootstrap';

<Dropdown id="dropdown-custom-1">
    <Dropdown.Toggle>
        <Glyphicon glyph="cog" />
    </Dropdown.Toggle>
    <Dropdown.Menu style={{textAlign: "left", right: "0", left: "auto"}}>
        <MenuItem className='disabled u-graph-text'>
            <Glyphicon glyph="user" style={{paddingRight: "10px"}}/>
            {this.state.data.username}

        </MenuItem>
        <MenuItem divider />
        <LinkContainer to="/logout" activeClassName="active"> // It doesn't do anythign here?
            <MenuItem className="u-graph-text">
                log out
            </MenuItem>
        </LinkContainer>
    </Dropdown.Menu>
</Dropdown>

Nothing changes in the URL of the browser.

Body:
Not sure what exactly is the problem with your implementation. Maybe you are using React Router v4, which is not quite compatible with react-router-bootstrap. But if nothing proposed works then try to do it in a programmatic way:

import React from 'react';
import {Navbar, Nav, NavItem, NavDropdown, MenuItem} from 'react-bootstrap';
import {Route} from 'react-router-dom';

class YourComponent extends Component {
  constructor(props) {
    super(props);
    this.handleLink = this.handleLink.bind(this);
  }

  handleLink(path) {
    this.props.history.push(path);
  }
  render() {
    return (
      <Dropdown id="dropdown-custom-1">
        <Dropdown.Toggle>
          <Glyphicon glyph="cog" />
        </Dropdown.Toggle>
        <Dropdown.Menu style={{textAlign: "left", right: "0", left: "auto"}}>
          <MenuItem className='disabled u-graph-text'>
            <Glyphicon glyph="user" style={{paddingRight: "10px"}}/>
            {this.state.data.username}
          </div>
          </MenuItem>
          <MenuItem divider />
          <MenuItem className="u-graph-text" onClick={()=>this.handleLink("logout")}>
            log out
          </MenuItem>
        </Dropdown.Menu>
      </Dropdown>
    );
  }
}

YourComponent.propTypes = {};

export default YourComponent;