问:
How to create a single volley webservice class to use across the android app?
My android application uses multiple network calls in a single activity and i have several of these activities where i have to use both post and get requests. I want to create a single "VolleyWebservice" class and call the same in multiple activities instead of writing the complete volley code. I am relatively new to android development and i don't understand where i am going wrong.

```<code>public class VolleyWebService {

public JSONObject result;

public JSONObject getResponse(String url, Context mContext) {
    RequestQueue mQueue = Volley.newRequestQueue(mContext);
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.e(TAG, "Anshuman" + response.toString());

            result =  response;
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                }
            });

    mQueue.add(request);
   return result;
}
}
</code>```

The method in My activity where i am calling this class

```<code>    private void callFunctionGetDist() {
    ProgressDialog progressDialog;
    progressDialog = ProgressDialog.show(recorddata.this, "", "Please Wait...", true);
    JSONObject response = new VolleyWebService().getResponse(urlConfigClass.GET_DISTRICT, this);
    try {
        if(response.toString().contains("Status:Success,Details")){
            arrDistName.clear();
            arrDistCode.clear();
            arrDistName.add("Select District Name");
            arrDistCode.add("Select District Code");
            JSONArray jsonArray = response.getJSONArray("Status:Success,Details");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jobJ = jsonArray.getJSONObject(i);
                String scheName = jobJ.getString("post");
                JSONObject jobJDist = new JSONObject(scheName);
                String distname = jobJDist.getString("District");
                String distcode = jobJDist.getString("DistrictCode");
                arrDistName.add(distname);
                arrDistCode.add(distcode);
            }
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(recorddata.this,
                    R.layout.custom_textview_to_spinner, arrDistName);
            // Drop down layout style - list view with radio button
            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            // attaching data adapter to spinner
            district.setAdapter(dataAdapter);
            progressDialog.dismiss();
        }else{
            progressDialog.dismiss();
            Toast.makeText(getApplicationContext(), "Response is null or empty", Toast.LENGTH_LONG).show();
        }
    } catch (Exception volleyError) {
        progressDialog.dismiss();
        Toast.makeText(getApplicationContext(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
    }
}
</code>```

I tried creating the same class but i am not able to get the response to other activities. Although i am getting the correct response in the Volley jsonbject response, the response return null in other activities.

I want to have the result object return the response in my recorddata activity

This is what i have tried so far, no luck though!

```<code>  public void postResponse (String url, Context mContext, final VolleyResponseListener listener) {
    try {
        String encodedUrl = url.replace(" ", "%20") + "";
        if (encodedUrl.contains("("))
            encodedUrl = encodedUrl.replace("(", "%28");
        if (encodedUrl.contains(")"))
            encodedUrl = encodedUrl.replace(")", "%29");
        encodedUrl = encodedUrl.replace(" ", "%20");

        RequestQueue mQueue = Volley.newRequestQueue(mContext);
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POst, encodedUrl, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.e(TAG, "Anshuman" + response.toString());

                listener.onSuccess(response);
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        listener.onError(error);
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                return new HashMap<>();
            }

        };

        mQueue.add(request);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

答:
For the sake of achieving your goal, (without taking in to consideration architecture and coding principles), you can pass a callback:

```<code>public class VolleyWebService {

public interface VolleyResponseListener {
  void onSuccess(JSONObject response);
  void onError(VolleyError error);
}

public JSONObject result;

public JSONObject getResponse(String url, Context mContext, VolleyResponseListener listener) {
    RequestQueue mQueue = Volley.newRequestQueue(mContext);
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.e(TAG, "Anshuman" + response.toString());

            listener.onSuccess(response);
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                   listener.onError(error);
                }
            });

    mQueue.add(request);
   return result;
}
}
</code>```

To use it:

```<code>volleyWebService.getResponse("your url", context, new VolleyResponseListener() {
   @Override
   void onSuccess(JSONObject response) {
      //do what you want on success
   }

   @Override
   void onError(VolleyError error) {
      //do what you want on error
   }
});
</code>```

Body:
My android application uses multiple network calls in a single activity and i have several of these activities where i have to use both post and get requests. I want to create a single "VolleyWebservice" class and call the same in multiple activities instead of writing the complete volley code. I am relatively new to android development and i don't understand where i am going wrong.

public class VolleyWebService {

public JSONObject result;

public JSONObject getResponse(String url, Context mContext) {
    RequestQueue mQueue = Volley.newRequestQueue(mContext);
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.e(TAG, "Anshuman" + response.toString());

            result =  response;
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                }
            });

    mQueue.add(request);
   return result;
}
}

The method in My activity where i am calling this class

    private void callFunctionGetDist() {
    ProgressDialog progressDialog;
    progressDialog = ProgressDialog.show(recorddata.this, "", "Please Wait...", true);
    JSONObject response = new VolleyWebService().getResponse(urlConfigClass.GET_DISTRICT, this);
    try {
        if(response.toString().contains("Status:Success,Details")){
            arrDistName.clear();
            arrDistCode.clear();
            arrDistName.add("Select District Name");
            arrDistCode.add("Select District Code");
            JSONArray jsonArray = response.getJSONArray("Status:Success,Details");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jobJ = jsonArray.getJSONObject(i);
                String scheName = jobJ.getString("post");
                JSONObject jobJDist = new JSONObject(scheName);
                String distname = jobJDist.getString("District");
                String distcode = jobJDist.getString("DistrictCode");
                arrDistName.add(distname);
                arrDistCode.add(distcode);
            }
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(recorddata.this,
                    R.layout.custom_textview_to_spinner, arrDistName);
            // Drop down layout style - list view with radio button
            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            // attaching data adapter to spinner
            district.setAdapter(dataAdapter);
            progressDialog.dismiss();
        }else{
            progressDialog.dismiss();
            Toast.makeText(getApplicationContext(), "Response is null or empty", Toast.LENGTH_LONG).show();
        }
    } catch (Exception volleyError) {
        progressDialog.dismiss();
        Toast.makeText(getApplicationContext(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
    }
}

I tried creating the same class but i am not able to get the response to other activities. Although i am getting the correct response in the Volley jsonbject response, the response return null in other activities.

I want to have the result object return the response in my recorddata activity

This is what i have tried so far, no luck though!

  public void postResponse (String url, Context mContext, final VolleyResponseListener listener) {
    try {
        String encodedUrl = url.replace(" ", "%20") + "";
        if (encodedUrl.contains("("))
            encodedUrl = encodedUrl.replace("(", "%28");
        if (encodedUrl.contains(")"))
            encodedUrl = encodedUrl.replace(")", "%29");
        encodedUrl = encodedUrl.replace(" ", "%20");

        RequestQueue mQueue = Volley.newRequestQueue(mContext);
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POst, encodedUrl, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.e(TAG, "Anshuman" + response.toString());

                listener.onSuccess(response);
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        listener.onError(error);
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                return new HashMap<>();
            }

        };

        mQueue.add(request);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Body:
For the sake of achieving your goal, (without taking in to consideration architecture and coding principles), you can pass a callback:

public class VolleyWebService {

public interface VolleyResponseListener {
  void onSuccess(JSONObject response);
  void onError(VolleyError error);
}

public JSONObject result;

public JSONObject getResponse(String url, Context mContext, VolleyResponseListener listener) {
    RequestQueue mQueue = Volley.newRequestQueue(mContext);
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.e(TAG, "Anshuman" + response.toString());

            listener.onSuccess(response);
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                   listener.onError(error);
                }
            });

    mQueue.add(request);
   return result;
}
}

To use it:

volleyWebService.getResponse("your url", context, new VolleyResponseListener() {
   @Override
   void onSuccess(JSONObject response) {
      //do what you want on success
   }

   @Override
   void onError(VolleyError error) {
      //do what you want on error
   }
});


来源: stackexchange

问:
Unable to match 2 elements with one element having null value
I am trying to match the name and the sold quantity attribute of product listed on the this site: my site (as an example)
However, there is some product items not having sold quantity element. Exactly, that element is not displayed because that shop has not sold any such item.
I try to scrape and match product name (@class='name_product shop_color_hover') and sold quantity (@class='s_b').
Here are my working:

```<code>from selenium import webdriver
.......
element_name='//*[@class="name_product shop_color_hover"]'
element_price='//*[@class="current_price"]'
element_sold='//*[@class="s_b"]'
link='https://www.sendo.vn/shop/dungcuykhoa_tanphu/san-pham/?p=1'
browserdriver.get(link)
allrows_name=browserdriver.find_elements_by_xpath(element_name)
allrows_sold=browserdriver.find_elements_by_xpath(element_sold)
for row_name, row_sold in zip(allrows_name,allrows_sold):
    print( row_name.text +":::"+row_sold.text)
print("program end")
</code>```

That works but the result of matching is incorrect due to missing value (null value) in allrows_sold

```<code>Túi chườm đá lạnh size lớn:::2
Combo 6 cây giấy lau mặt trong thẩm mỹ, spa:::3
Thước đo mắt - compa mắt:::7
Bộ giác hơi không dùng lửa Duy Thành YGH02 - Valy đen:::3
Máy đo tiểu đường OGCare chính hãng tặng 3 hộp que:::6
Hộp 25 que thử đường huyết OGCare date xa:::33
Túi chườm nóng lạnh đa năng Hướng Dương cỡ đại:::1
Bộ giác hơi không dùng lửa Duy Thành valy nâu:::2
Kính bảo hộ Spider chống bụi gió an toàn cho bé:::2
Máy đo đường huyết OGCare kèm 25 que thử:::15
Vớ y khoa, vớ tĩnh mạch Đức chính hãng - Vớ gối:::19
Vớ y khoa phòng ngừa và điều trị suy giãn tĩnh mạch vùng gối Jiani - Ý:::11
Vớ y khoa phòng ngừa và điều trị giãn tĩnh mạch Jiani - Vớ gối:::4
program end
</code>```

As you can see, it works well until the third line where there is not value of sold quantity in allrows_sold
Now I want the program to key "0" into any item having null sold quantity (@class='s_b')

Plz, help me to find another solution for this matching problem. Thanks!

答:
I have just change the sold element xpath and checked if text value is null assigned
'0'

```<code>element_name='//*[@class="name_product shop_color_hover"]'
element_price='//*[@class="current_price"]'
element_sold='//div[@class="social_box"]'
link='https://www.sendo.vn/shop/dungcuykhoa_tanphu/san-pham/?p=1'
browserdriver.get(link)
allrows_name=browserdriver.find_elements_by_xpath(element_name)
allrows_sold=browserdriver.find_elements_by_xpath(element_sold)

for row_name, row_sold in zip(allrows_name,allrows_sold):
    if row_sold.text!='':

       print( row_name.text +":::"+row_sold.text)
    else:

        print(row_name.text + ":::" + "0")
print("program end")
</code>```

Output:

```<code>Túi chườm đá lạnh size lớn:::2
Combo 6 cây giấy lau mặt trong thẩm mỹ, spa:::3
Thước đo mắt - compa mắt:::0
Bộ giác hơi không dùng lửa Duy Thành YGH02 - Valy đen:::7
Máy đo tiểu đường OGCare chính hãng tặng 3 hộp que:::0
Hộp 25 que thử đường huyết OGCare date xa:::3
Túi chườm nóng lạnh đa năng Hướng Dương cỡ đại:::6
Bộ giác hơi không dùng lửa Duy Thành valy nâu:::33
Kính bảo hộ Spider chống bụi gió an toàn cho bé:::1
Máy đo đường huyết OGCare kèm 25 que thử:::2
Vớ y khoa, vớ tĩnh mạch Đức chính hãng - Vớ gối:::2
Vớ y khoa phòng ngừa và điều trị suy giãn tĩnh mạch vùng gối Jiani - Ý:::15
Vớ y khoa phòng ngừa và điều trị giãn tĩnh mạch Jiani - Vớ gối:::19
Vớ y khoa phòng ngừa và điều trị giãn tĩnh mạch Jiani - Vớ đùi:::11
Máy massage Mini Squirrel V-555 nhập khẩu chính hãng Hàn Quốc:::4
program end

Process finished with exit code 0
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to match the name and the sold quantity attribute of product listed on the this site: my site (as an example)
However, there is some product items not having sold quantity element. Exactly, that element is not displayed because that shop has not sold any such item.
I try to scrape and match product name (@class='name_product shop_color_hover') and sold quantity (@class='s_b').
Here are my working:

from selenium import webdriver
.......
element_name='//*[@class="name_product shop_color_hover"]'
element_price='//*[@class="current_price"]'
element_sold='//*[@class="s_b"]'
link='https://www.sendo.vn/shop/dungcuykhoa_tanphu/san-pham/?p=1'
browserdriver.get(link)
allrows_name=browserdriver.find_elements_by_xpath(element_name)
allrows_sold=browserdriver.find_elements_by_xpath(element_sold)
for row_name, row_sold in zip(allrows_name,allrows_sold):
    print( row_name.text +":::"+row_sold.text)
print("program end")

That works but the result of matching is incorrect due to missing value (null value) in allrows_sold

Túi chườm đá lạnh size lớn:::2
Combo 6 cây giấy lau mặt trong thẩm mỹ, spa:::3
Thước đo mắt - compa mắt:::7
Bộ giác hơi không dùng lửa Duy Thành YGH02 - Valy đen:::3
Máy đo tiểu đường OGCare chính hãng tặng 3 hộp que:::6
Hộp 25 que thử đường huyết OGCare date xa:::33
Túi chườm nóng lạnh đa năng Hướng Dương cỡ đại:::1
Bộ giác hơi không dùng lửa Duy Thành valy nâu:::2
Kính bảo hộ Spider chống bụi gió an toàn cho bé:::2
Máy đo đường huyết OGCare kèm 25 que thử:::15
Vớ y khoa, vớ tĩnh mạch Đức chính hãng - Vớ gối:::19
Vớ y khoa phòng ngừa và điều trị suy giãn tĩnh mạch vùng gối Jiani - Ý:::11
Vớ y khoa phòng ngừa và điều trị giãn tĩnh mạch Jiani - Vớ gối:::4
program end

As you can see, it works well until the third line where there is not value of sold quantity in allrows_sold
Now I want the program to key "0" into any item having null sold quantity (@class='s_b')

Plz, help me to find another solution for this matching problem. Thanks!

Body:
I have just change the sold element xpath and checked if text value is null assigned
'0'

element_name='//*[@class="name_product shop_color_hover"]'
element_price='//*[@class="current_price"]'
element_sold='//div[@class="social_box"]'
link='https://www.sendo.vn/shop/dungcuykhoa_tanphu/san-pham/?p=1'
browserdriver.get(link)
allrows_name=browserdriver.find_elements_by_xpath(element_name)
allrows_sold=browserdriver.find_elements_by_xpath(element_sold)

for row_name, row_sold in zip(allrows_name,allrows_sold):
    if row_sold.text!='':

       print( row_name.text +":::"+row_sold.text)
    else:

        print(row_name.text + ":::" + "0")
print("program end")

Output:

Túi chườm đá lạnh size lớn:::2
Combo 6 cây giấy lau mặt trong thẩm mỹ, spa:::3
Thước đo mắt - compa mắt:::0
Bộ giác hơi không dùng lửa Duy Thành YGH02 - Valy đen:::7
Máy đo tiểu đường OGCare chính hãng tặng 3 hộp que:::0
Hộp 25 que thử đường huyết OGCare date xa:::3
Túi chườm nóng lạnh đa năng Hướng Dương cỡ đại:::6
Bộ giác hơi không dùng lửa Duy Thành valy nâu:::33
Kính bảo hộ Spider chống bụi gió an toàn cho bé:::1
Máy đo đường huyết OGCare kèm 25 que thử:::2
Vớ y khoa, vớ tĩnh mạch Đức chính hãng - Vớ gối:::2
Vớ y khoa phòng ngừa và điều trị suy giãn tĩnh mạch vùng gối Jiani - Ý:::15
Vớ y khoa phòng ngừa và điều trị giãn tĩnh mạch Jiani - Vớ gối:::19
Vớ y khoa phòng ngừa và điều trị giãn tĩnh mạch Jiani - Vớ đùi:::11
Máy massage Mini Squirrel V-555 nhập khẩu chính hãng Hàn Quốc:::4
program end

Process finished with exit code 0


问:
JQuery: How to select label of input's ancestor
I have the following HTML:

  Description/Pack Size

    <input type="text" name="packetSize" class="wfinput required form_error" id="packetSize" />

      This field is required.

```

Is there a way to select the  element that is the child of .control-group (ie, the one with "Description/Pack Size" text), from the <input /> text field in my HTML?

答:
To select the  element that is above the <input/> element, you could:

first use .closest() to select the first .control-group above the <input/> element and then

select the first child label of that .control-group

This can be achieved via the following jQuery script:

```<code>const input = $('input[name="packetSize"]');

const controlGroup = input.closest('.control-group');

const label = $('label', controlGroup);
</code>```

It's possible to condense this into a single line but I've broken it into steps for clarity. Hope that helps.

Body:
I have the following HTML:

  Description/Pack Size

    <input type="text" name="packetSize" class="wfinput required form_error" id="packetSize" />

      This field is required.

Is there a way to select the  element that is the child of .control-group (ie, the one with "Description/Pack Size" text), from the <input /> text field in my HTML?

Body:
To select the <label> element that is above the <input/> element, you could:

first use .closest() to select the first .control-group above the <input/> element and then

select the first child label of that .control-group

This can be achieved via the following jQuery script:

const input = $('input[name="packetSize"]');

const controlGroup = input.closest('.control-group');

const label = $('label', controlGroup);

It's possible to condense this into a single line but I've broken it into steps for clarity. Hope that helps.


问:
Calling enrollment endpoint failed with error [Error: connect ECONNREFUSED
I am trying to run the Hyperledger fabric Tuna app and getting the below error when running the regiseterAdmin.js

```<code>  Store path:/home/chaindev/.hfc-key-store
Error: Calling enrollment endpoint failed with error [Error: connect ECONNREFUSED 127.0.0.1:7054]
    at ClientRequest.<anonymous> (/home/chaindev/fabricProjects/src/github.com/education/LFS171x/fabric-material/tuna-app/node_modules/fabric-ca-client/lib/FabricCAClientImpl.js:711:12)
    at emitOne (events.js:116:13)
    at ClientRequest.emit (events.js:211:7)
    at Socket.socketErrorListener (_http_client.js:387:9)
    at emitOne (events.js:116:13)
    at Socket.emit (events.js:211:7)
    at emitErrorNT (internal/streams/destroy.js:64:8)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)
Failed to enroll admin: Error: Failed to enroll admin
</code>```

答:
Run docker ps and check if all the docker containers are running or not.

If it is not running run it, if it fail, download the fabric binaries.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to run the Hyperledger fabric Tuna app and getting the below error when running the regiseterAdmin.js

  Store path:/home/chaindev/.hfc-key-store
Error: Calling enrollment endpoint failed with error [Error: connect ECONNREFUSED 127.0.0.1:7054]
    at ClientRequest.<anonymous> (/home/chaindev/fabricProjects/src/github.com/education/LFS171x/fabric-material/tuna-app/node_modules/fabric-ca-client/lib/FabricCAClientImpl.js:711:12)
    at emitOne (events.js:116:13)
    at ClientRequest.emit (events.js:211:7)
    at Socket.socketErrorListener (_http_client.js:387:9)
    at emitOne (events.js:116:13)
    at Socket.emit (events.js:211:7)
    at emitErrorNT (internal/streams/destroy.js:64:8)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)
Failed to enroll admin: Error: Failed to enroll admin


问:
How to retrieve all set cookies into browser tab angular
I need to retrieve all the cookies which are showing on my URL .

```<code>const allCookies = this.cookieService.getAll();
console.log('allcookies',allCookies);
</code>```

Please find the attached screenshot in which I want to get all cookies from google.com,localhost and from other providers (if any exists there).

But first, I would like to know if it is possible or not ?

Cookies-details

答:
You can try something like this:

In the Constructor of your service

```<code>constructor(
    @Inject( DOCUMENT ) private document: any,
    @Inject( PLATFORM_ID ) private platformId: InjectionToken<Object>,
  ) {
    this.isBrowser = isPlatformBrowser( this.platformId );
  }
</code>```

and then a method like

```<code> getAll(): {} {

if (!this.isBrowser) {
return;
}
    const _cookies: {} = {};

    if ( this.document.cookie) {
      const splittedCookies: string[] = this.document.cookie.split(';');

      for ( let i = 0; i < splittedCookies.length; i++ ) {
        const cookies: string[] = splittedCookies[ i ].split('=');

        cookies[ 0 ] = cookies[ 0 ].replace( /^ /, '' );
        _cookies[ decodeURIComponent( cookies[ 0 ] ) ] = decodeURIComponent( cookies[ 1 ] );
      }
    }

    return _cookies;
  }
</code>```

Body:
I need to retrieve all the cookies which are showing on my URL .

const allCookies = this.cookieService.getAll();
console.log('allcookies',allCookies);

Please find the attached screenshot in which I want to get all cookies from google.com,localhost and from other providers (if any exists there).

But first, I would like to know if it is possible or not ?

Cookies-details

Body:
You can try something like this:

In the Constructor of your service

constructor(
    @Inject( DOCUMENT ) private document: any,
    @Inject( PLATFORM_ID ) private platformId: InjectionToken<Object>,
  ) {
    this.isBrowser = isPlatformBrowser( this.platformId );
  }

and then a method like

 getAll(): {} {

if (!this.isBrowser) {
return;
}
    const _cookies: {} = {};

    if ( this.document.cookie) {
      const splittedCookies: string[] = this.document.cookie.split(';');

      for ( let i = 0; i < splittedCookies.length; i++ ) {
        const cookies: string[] = splittedCookies[ i ].split('=');

        cookies[ 0 ] = cookies[ 0 ].replace( /^ /, '' );
        _cookies[ decodeURIComponent( cookies[ 0 ] ) ] = decodeURIComponent( cookies[ 1 ] );
      }
    }

    return _cookies;
  }


问:
Form value not reset in angular if using mask='+1 000 000'
I am not able to reset form field after submit the form whereas if I remove mask="+1 000 000-0000" then we're able to reset form</p>

```<code><input class="form-control" [(ngModel)]="mobile" formControlName="mobile" type="tel" placeholder="Please enter a vaild mobile number" (keyup)="showDefaultRelationMobileerror($event)"  [dropSpecialCharacters]="false" mask="+1 000 000-0000">
</code>```

答:
Use of ngModel along with formControlName has been deprecated as of Angular 6 (https://angular.io/api/forms/FormControlName#use-with-ngmodel). You can use one or the other.

To make use of Reactive forms in Angular, use formControlName and to use template-driven forms, you can use ngModel.

As for your mask +1 000 000-0000, 1 is not recognised as a default pattern by ngx-mask (See the default patterns here: https://www.npmjs.com/package/ngx-mask#then). You can instead set the prefix attribute

```<code><form [formGroup]="form">
    <input type="tel"
           class="form-control"
           formControlName="mobile"
           placeholder="Please enter a vaild mobile number"
           (keyup)="showDefaultRelationMobileerror($event)"
           [dropSpecialCharacters]="false"
           prefix="+1"
           mask=" 000 000-0000"
    />
    <button (click)="resetForm()">Reset</button>
</form>
</code>```

To reset the form value, use the reset() method from the formControl class in your component

```<code>    form: FormGroup;

    ngOnInit() {
        this.form = new FormGroup({
            'mobile': new FormControl()
        });
    }

    resetForm() {
        this.form.get('mobile').reset()
    }
</code>```

Body:
I am not able to reset form field after submit the form whereas if I remove mask="+1 000 000-0000" then we're able to reset form

<input class="form-control" [(ngModel)]="mobile" formControlName="mobile" type="tel" placeholder="Please enter a vaild mobile number" (keyup)="showDefaultRelationMobileerror($event)"  [dropSpecialCharacters]="false" mask="+1 000 000-0000">

Body:
Use of ngModel along with formControlName has been deprecated as of Angular 6 (https://angular.io/api/forms/FormControlName#use-with-ngmodel). You can use one or the other.

To make use of Reactive forms in Angular, use formControlName and to use template-driven forms, you can use ngModel.

As for your mask +1 000 000-0000, 1 is not recognised as a default pattern by ngx-mask (See the default patterns here: https://www.npmjs.com/package/ngx-mask#then). You can instead set the prefix attribute

<form [formGroup]="form">
    <input type="tel"
           class="form-control"
           formControlName="mobile"
           placeholder="Please enter a vaild mobile number"
           (keyup)="showDefaultRelationMobileerror($event)"
           [dropSpecialCharacters]="false"
           prefix="+1"
           mask=" 000 000-0000"
    />
    <button (click)="resetForm()">Reset</button>
</form>

To reset the form value, use the reset() method from the formControl class in your component

    form: FormGroup;

    ngOnInit() {
        this.form = new FormGroup({
            'mobile': new FormControl()
        });
    }

    resetForm() {
        this.form.get('mobile').reset()
    }


问:
using getFragmentSupport Manager inside PreferenceFragment
I found this library that I want to use inside my PreferenceFragment extended class, my problem is that the getSupportFragmentManager can not be resolved.
My question is how do I show the fragment when it extends a PreferenceFragment

I tried changing to getFragmentManager but won't work

```<code>public class PreferencesFragment extends PreferenceFragment {

 final Preference currencyPreference = findPreference(getResources().getString(R.string.setting_category_currency_key));
        currencyPreference.setOnPreferenceClickListener(preference -> {
            //selectCurrencyDialog = new SelectCurrencyFragment();
            //selectCurrencyDialog.show(((SettingsActivity) getActivity()).getSupportFragmentManager(), "SelectCurrency");

            CurrencyPicker picker = CurrencyPicker.newInstance("Select Currency");  // dialog title
            picker.setListener((name, code, symbol, flagDrawableResID) -> {
                // Implement your code here
            });
            picker.show(getSupportFragmentManager(), "CURRENCY_PICKER");

            return false;
        });

}
</code>```

The error is on this Line

getSupportFragmentManager()

```<code>picker.show(getSupportFragmentManager(), "CURRENCY_PICKER");
</code>```

答: use getChildFragmentManager() instead of getSupportFragmentManager()</p>

Body:
I found this library that I want to use inside my PreferenceFragment extended class, my problem is that the getSupportFragmentManager can not be resolved.
My question is how do I show the fragment when it extends a PreferenceFragment

I tried changing to getFragmentManager but won't work

public class PreferencesFragment extends PreferenceFragment {

 final Preference currencyPreference = findPreference(getResources().getString(R.string.setting_category_currency_key));
        currencyPreference.setOnPreferenceClickListener(preference -> {
            //selectCurrencyDialog = new SelectCurrencyFragment();
            //selectCurrencyDialog.show(((SettingsActivity) getActivity()).getSupportFragmentManager(), "SelectCurrency");

            CurrencyPicker picker = CurrencyPicker.newInstance("Select Currency");  // dialog title
            picker.setListener((name, code, symbol, flagDrawableResID) -> {
                // Implement your code here
            });
            picker.show(getSupportFragmentManager(), "CURRENCY_PICKER");

            return false;
        });

}

The error is on this Line

getSupportFragmentManager()

picker.show(getSupportFragmentManager(), "CURRENCY_PICKER");


问:
Java: properly checked class instantiation using reflection
I'm trying to use one of the simplest forms of reflection to create an instance of class:

```<code>package some.common.prefix;

public interface My {
    void configure(...);
    void process(...);
}

public class MyExample implements My {
    ... // proper implementation
}

String myClassName = "MyExample"; // read from an external file in reality

Class<? extends My> myClass =
    (Class<? extends My>) Class.forName("some.common.prefix." + myClassName);
My my = myClass.newInstance();
</code>```

Typecasting unknown Class object we've got from Class.forName yields a warning:

```Type safety: Unchecked cast from Class<capture#1-of ?> to Class<? extends My>```

I've tried using instanceof check approach:

```<code>Class<?> loadedClass = Class.forName("some.common.prefix." + myClassName);
if (myClass instanceof Class<? extends RST>) {
    Class<? extends My> myClass = (Class<? extends My>) loadedClass;
    My my = myClass.newInstance();
} else {
    throw ... // some awful exception
}
</code>```

but this yields a compilation error:
Cannot perform instanceof check against parameterized type Class<? extends My>. Use the form Class<?> instead since further generic type information will be erased at runtime. So I guess I can't use instanceof approach.

How do I get rid of it and how am I supposed to do it properly? Is it possible to use reflection without these warnings at all (i.e. without ignoring or supressing them)?

答: See this question How do I address unchecked cast warnings?. I have found that where reflection is concerned, you are best just to responsibly use @SuppressWarnings("unchecked")

Body:
I'm trying to use one of the simplest forms of reflection to create an instance of class:

package some.common.prefix;

public interface My {
    void configure(...);
    void process(...);
}

public class MyExample implements My {
    ... // proper implementation
}

String myClassName = "MyExample"; // read from an external file in reality

Class<? extends My> myClass =
    (Class<? extends My>) Class.forName("some.common.prefix." + myClassName);
My my = myClass.newInstance();

Typecasting unknown Class object we've got from Class.forName yields a warning:

Type safety: Unchecked cast from Class<capture#1-of ?> to Class<? extends My>

I've tried using instanceof check approach:

Class<?> loadedClass = Class.forName("some.common.prefix." + myClassName);
if (myClass instanceof Class<? extends RST>) {
    Class<? extends My> myClass = (Class<? extends My>) loadedClass;
    My my = myClass.newInstance();
} else {
    throw ... // some awful exception
}

but this yields a compilation error:
Cannot perform instanceof check against parameterized type Class<? extends My>. Use the form Class<?> instead since further generic type information will be erased at runtime. So I guess I can't use instanceof approach.

How do I get rid of it and how am I supposed to do it properly? Is it possible to use reflection without these warnings at all (i.e. without ignoring or supressing them)?


问:
How to update the value of a key field in a dictionary in Python?
I have a dictionary as given below:

```<code>test = {"100":271,"updated_at":{"date":"2017-10-14T12:15:52.172Z"},"created_at":{"date":"2017-10-14T12:15:52.172Z"}}
</code>```

I have written below program to retrieve keys from the dictionary:

```<code>test = {"100":271,"updated_at":{"date":"2017-10-14T12:15:52.172Z"},"created_at":{"date":"2017-10-14T12:15:52.172Z"}}

for keys in test.keys():
    print(keys)
</code>```

I want to update the keys field value when we got a digit value in keys field. Example in the above dictionary

```<code>keys: 100
value: 271
</code>```

When we got keys value is an integer then I want to updates keys value like this xx_100:271

I would like to solve the problem in the simplest way possible using python.

Body:
I have a dictionary as given below:

test = {"100":271,"updated_at":{"date":"2017-10-14T12:15:52.172Z"},"created_at":{"date":"2017-10-14T12:15:52.172Z"}}

I have written below program to retrieve keys from the dictionary:

test = {"100":271,"updated_at":{"date":"2017-10-14T12:15:52.172Z"},"created_at":{"date":"2017-10-14T12:15:52.172Z"}}

for keys in test.keys():
    print(keys)

I want to update the keys field value when we got a digit value in keys field. Example in the above dictionary

keys: 100
value: 271

When we got keys value is an integer then I want to updates keys value like this xx_100:271

I would like to solve the problem in the simplest way possible using python.

Body:
Try this.

test = {"100":271,"updated_at":{"date":"2017-10-14T12:15:52.172Z"},"created_at":{"date":"2017-10-14T12:15:52.172Z"}}
for key in test.keys():
    try:
        if type(key)==int:
            test['xx_'+str(key)]=test.pop(key)
    except: pass


问:
Possible ways of making a common insert data function for whole project in asp.net using Repository Pattern
I am wondering how can I avoid writing cmd.Parameter.addwithvalue again and again for all pages.In short something like a generic insert function. I am not using Entity framework so regular generic function of adding entities won't help.

Till now I have tried:

```<code>public string AddCampus(Campus objCampus)
    {
                //string Params = "@Activity,@Name,@PhoneNo,@Email,@Logo,@StatusId,@CountryId,@CityId,@StateId,@DistrictId,@ClientId,@Pincode,@AddressLine1,@AddressLine2,@Area,@Street";
                //string Values = "Add" + ',' + objCampus.Name + ',' + objCampus.PhoneNo + ',' + objCampus.Email + ',' + objCampus.Logo + "," + objCampus.StatusId + ","+objCampus.CampusAddress.CountryId + "," + objCampus.CampusAddress.CityId + "," + objCampus.CampusAddress.StateId + "," + objCampus.CampusAddress.DistrictId + "," + objCampus.ClientId + "," + objCampus.CampusAddress.Pincode + "," + objCampus.CampusAddress.AddressLine1 + "," + objCampus.CampusAddress.AddressLine2 + "," + objCampus.CampusAddress.Area + "," + objCampus.CampusAddress.Streat;
                //return  Connection.CommandExecuteNonQuery(Params, Values,true, "sprCampus");
    }
</code>```

I made this and it works but i have just coommented that.This was the implementation:

```<code>   public static string CommandExecuteNonQuery(string Parameters,string Values,bool IsStoredProcedure,string command)
    {   string[] Parameter = Parameters.Split(',');
        string[] Value = Values.Split(',');
        string s_Message = "";
        if (Parameter.Count() < Value.Count())
        {
            s_Message = "Number of Paramters Supplied is less than Number of Values Supplied.";
            return s_Message;
        }
        else if (Parameter.Count() > Value.Count())
        {
            s_Message = "Number of Values Supplied is less than Number of Parameters Supplied.";
            return s_Message;
        }
        else
        {
            SqlCommand cmd = new SqlCommand();
            for (var i = 0; i < Parameter.Count(); i++)
            {
                cmd.Parameters.AddWithValue(Parameter[i], Value[i]);

            }
            cmd.CommandText = command;
            if (IsStoredProcedure)
                cmd.CommandType = CommandType.StoredProcedure;
            string saveSuccess = string.Empty;
            int execute = 0;
            using (SqlConnection con = new SqlConnection(sqlConStr))
            {
                try
                {
                    con.Open();
                    cmd.Connection = con;
                    execute = cmd.ExecuteNonQuery();
                    if (execute > 0)
                    {
                        s_Message = "Record Saved";
                    }
                    else
                        s_Message = "Operation Failed";

                }
                catch (Exception excp)
                {
                    s_Message = excp.Message;
                }

            }
        }
            return s_Message.ToString();

    }
</code>```

So am just looking for a better solution than this.

答:
I had the same idea a while back. The following probably isn't the most optimized solution however I think it's pretty good.</p>

```<code>    // Parameter used for StoredProcedure
    private class Parameter
    {
        public Parameter(string name, object value)
        {
            Name = name;
            Value = value;
        }

        public readonly string Name;
        public readonly object Value;
    }

    // Executes a given stored procedure with parameters and returns a SQLDataReader
    private static SqlDataReader ExecuteDataReader(string name, SqlConnection dbConnection, List<Parameter> parameters = null)
    {
        if (parameters == null)
            parameters = new List<Parameter>();

        using (var command = new SqlCommand(name, dbConnection) { CommandType = CommandType.StoredProcedure })
        {
            foreach (var parameter in parameters)
                command.Parameters.AddWithValue(parameter.Name, parameter.Value);

            return command.ExecuteReader();
        }
    }

    // Executes a given stored procedure with parameters
    private static void ExecuteNonQuery(string name, SqlConnection dbConnection, List<Parameter> parameters = null)
    {
        if (parameters == null)
            parameters = new List<Parameter>();

        using (var command = new SqlCommand(name, dbConnection) { CommandType = CommandType.StoredProcedure })
        {
            foreach (var parameter in parameters)
                command.Parameters.AddWithValue(parameter.Name, parameter.Value);

            command.ExecuteNonQuery();
        }
    }
</code>```

Body:
I am wondering how can I avoid writing cmd.Parameter.addwithvalue again and again for all pages.In short something like a generic insert function. I am not using Entity framework so regular generic function of adding entities won't help.

Till now I have tried:

public string AddCampus(Campus objCampus)
    {
                //string Params = "@Activity,@Name,@PhoneNo,@Email,@Logo,@StatusId,@CountryId,@CityId,@StateId,@DistrictId,@ClientId,@Pincode,@AddressLine1,@AddressLine2,@Area,@Street";
                //string Values = "Add" + ',' + objCampus.Name + ',' + objCampus.PhoneNo + ',' + objCampus.Email + ',' + objCampus.Logo + "," + objCampus.StatusId + ","+objCampus.CampusAddress.CountryId + "," + objCampus.CampusAddress.CityId + "," + objCampus.CampusAddress.StateId + "," + objCampus.CampusAddress.DistrictId + "," + objCampus.ClientId + "," + objCampus.CampusAddress.Pincode + "," + objCampus.CampusAddress.AddressLine1 + "," + objCampus.CampusAddress.AddressLine2 + "," + objCampus.CampusAddress.Area + "," + objCampus.CampusAddress.Streat;
                //return  Connection.CommandExecuteNonQuery(Params, Values,true, "sprCampus");
    }

I made this and it works but i have just coommented that.This was the implementation:

   public static string CommandExecuteNonQuery(string Parameters,string Values,bool IsStoredProcedure,string command)
    {   string[] Parameter = Parameters.Split(',');
        string[] Value = Values.Split(',');
        string s_Message = "";
        if (Parameter.Count() < Value.Count())
        {
            s_Message = "Number of Paramters Supplied is less than Number of Values Supplied.";
            return s_Message;
        }
        else if (Parameter.Count() > Value.Count())
        {
            s_Message = "Number of Values Supplied is less than Number of Parameters Supplied.";
            return s_Message;
        }
        else
        {
            SqlCommand cmd = new SqlCommand();
            for (var i = 0; i < Parameter.Count(); i++)
            {
                cmd.Parameters.AddWithValue(Parameter[i], Value[i]);

            }
            cmd.CommandText = command;
            if (IsStoredProcedure)
                cmd.CommandType = CommandType.StoredProcedure;
            string saveSuccess = string.Empty;
            int execute = 0;
            using (SqlConnection con = new SqlConnection(sqlConStr))
            {
                try
                {
                    con.Open();
                    cmd.Connection = con;
                    execute = cmd.ExecuteNonQuery();
                    if (execute > 0)
                    {
                        s_Message = "Record Saved";
                    }
                    else
                        s_Message = "Operation Failed";

                }
                catch (Exception excp)
                {
                    s_Message = excp.Message;
                }

            }
        }
            return s_Message.ToString();

    }

So am just looking for a better solution than this.

Body:
I had the same idea a while back. The following probably isn't the most optimized solution however I think it's pretty good.

    // Parameter used for StoredProcedure
    private class Parameter
    {
        public Parameter(string name, object value)
        {
            Name = name;
            Value = value;
        }

        public readonly string Name;
        public readonly object Value;
    }

    // Executes a given stored procedure with parameters and returns a SQLDataReader
    private static SqlDataReader ExecuteDataReader(string name, SqlConnection dbConnection, List<Parameter> parameters = null)
    {
        if (parameters == null)
            parameters = new List<Parameter>();

        using (var command = new SqlCommand(name, dbConnection) { CommandType = CommandType.StoredProcedure })
        {
            foreach (var parameter in parameters)
                command.Parameters.AddWithValue(parameter.Name, parameter.Value);

            return command.ExecuteReader();
        }
    }

    // Executes a given stored procedure with parameters
    private static void ExecuteNonQuery(string name, SqlConnection dbConnection, List<Parameter> parameters = null)
    {
        if (parameters == null)
            parameters = new List<Parameter>();

        using (var command = new SqlCommand(name, dbConnection) { CommandType = CommandType.StoredProcedure })
        {
            foreach (var parameter in parameters)
                command.Parameters.AddWithValue(parameter.Name, parameter.Value);

            command.ExecuteNonQuery();
        }
    }


问:
Received exception Bad Request: "Series could not be created as there are no occurrences in the current recurrence definition for given range
I am receiving this exception from CRM while creating a recurrence as start date = current date. Could you please help figure out what could be the possible miss.
CRM Exception Bad Request:

Series could not be created as there are no occurrences in the
  current recurrence definition for given range.

Some of the tags in request JSON as below:

```<code>"recurrencepatterntype": 0
starttime": "2019-05-30T10:00:00Z",
"endtime": "2019-05-30T10:30:00Z",
"patternstartdate": "2019-05-30T09:48:04Z",
"patternendtype": 2,
"occurrences": 1,
</code>```

Tried to create Daily recurrence which ends after 1 occurrence and start date is current date.

答:
I used the below code to create Recurrence rule and worked perfectly fine for me.</p>

```<code>var entity = {};
entity.patternstartdate = new Date("05/30/2019 14:00:00").toISOString();
entity.patternenddate = new Date("05/30/2019 14:30:00").toISOString();
entity.recurrencepatterntype = 0;
entity.occurrences = 1;
entity.patternendtype = 2;

var req = new XMLHttpRequest();
req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/recurrencerules", false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function() {
    if (this.readyState === 4) {
        req.onreadystatechange = null;
        if (this.status === 204) {
            var uri = this.getResponseHeader("OData-EntityId");
            var regExp = /\(([^)]+)\)/;
            var matches = regExp.exec(uri);
            var newEntityId = matches[1];
        } else {
            Xrm.Utility.alertDialog(this.statusText);
        }
    }
};
req.send(JSON.stringify(entity));
</code>```

Body:
I am receiving this exception from CRM while creating a recurrence as start date = current date. Could you please help figure out what could be the possible miss.
CRM Exception Bad Request:

Series could not be created as there are no occurrences in the
  current recurrence definition for given range.

Some of the tags in request JSON as below:

"recurrencepatterntype": 0
starttime": "2019-05-30T10:00:00Z",
"endtime": "2019-05-30T10:30:00Z",
"patternstartdate": "2019-05-30T09:48:04Z",
"patternendtype": 2,
"occurrences": 1,

Tried to create Daily recurrence which ends after 1 occurrence and start date is current date.

Body:
I used the below code to create Recurrence rule and worked perfectly fine for me.

var entity = {};
entity.patternstartdate = new Date("05/30/2019 14:00:00").toISOString();
entity.patternenddate = new Date("05/30/2019 14:30:00").toISOString();
entity.recurrencepatterntype = 0;
entity.occurrences = 1;
entity.patternendtype = 2;

var req = new XMLHttpRequest();
req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/recurrencerules", false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function() {
    if (this.readyState === 4) {
        req.onreadystatechange = null;
        if (this.status === 204) {
            var uri = this.getResponseHeader("OData-EntityId");
            var regExp = /\(([^)]+)\)/;
            var matches = regExp.exec(uri);
            var newEntityId = matches[1];
        } else {
            Xrm.Utility.alertDialog(this.statusText);
        }
    }
};
req.send(JSON.stringify(entity));


问:
Undo change on cancel button
I am trying to cancel the changes done during my page edit. But whenever I click on cancel, the updated changes are reflected. How to revert the changes on click of cancel button. Any help on this will be really helpful since I am new to knockout

https://jsfiddle.net/tan2dgsa/

// ViewModel.js

```<code>var viewModel = {

    articles: [{
        id: 1,
        title: "KnockOut Templating",
        content: "Content for Knockout goes here."
    }, {
        id: 2,
        title: "SharePoint 2013 REST API",
        content: "Content for SharePoint."
    }, {
        id: 3,
        title: "Knockout with SharePoint",
        content: "Content for knockout and SharePoint."
    }],

    selectedTemplate: ko.observable("readOnly"),
    selectedMode: ko.observable(),
};

viewModel.currentTemplate = function (tbl) {
    return tbl === this.selectedMode() ? 'editMode' : this.selectedTemplate();
}.bind(viewModel);

viewModel.reset = function (t) {
    this.selectedMode("editMode");
};
ko.applyBindings(viewModel);
</code>```

答:
If you're using KO Mapping plugin, this will be quite simple.

Hold parameter 'data' in another local variable, say 'originalData', and then simply call mapping plugin's function to re-map data.

For ex.,

```<code>    var myKOViewModel = function(data) {
        var self = this;
        var originalData = data;
        ko.mapping.fromJS(data, null, self);    // ViewModel initial mapping

        //....

        self.CancelClicked = function () {
            ko.mapping.fromJS(originalData, null, self);        // Refresh ViewModel
        }
    }
</code>```

Please refer to KO's documentation
https://knockoutjs.com/documentation/plugins-mapping.html for more details.

Title: Undo change on cancel button

Body:
I am trying to cancel the changes done during my page edit. But whenever I click on cancel, the updated changes are reflected. How to revert the changes on click of cancel button. Any help on this will be really helpful since I am new to knockout

https://jsfiddle.net/tan2dgsa/

// ViewModel.js

var viewModel = {

    articles: [{
        id: 1,
        title: "KnockOut Templating",
        content: "Content for Knockout goes here."
    }, {
        id: 2,
        title: "SharePoint 2013 REST API",
        content: "Content for SharePoint."
    }, {
        id: 3,
        title: "Knockout with SharePoint",
        content: "Content for knockout and SharePoint."
    }],

    selectedTemplate: ko.observable("readOnly"),
    selectedMode: ko.observable(),
};

viewModel.currentTemplate = function (tbl) {
    return tbl === this.selectedMode() ? 'editMode' : this.selectedTemplate();
}.bind(viewModel);

viewModel.reset = function (t) {
    this.selectedMode("editMode");
};
ko.applyBindings(viewModel);

Body:
If you're using KO Mapping plugin, this will be quite simple.

Hold parameter 'data' in another local variable, say 'originalData', and then simply call mapping plugin's function to re-map data.

For ex.,

    var myKOViewModel = function(data) {
        var self = this;
        var originalData = data;
        ko.mapping.fromJS(data, null, self);    // ViewModel initial mapping

        //....

        self.CancelClicked = function () {
            ko.mapping.fromJS(originalData, null, self);        // Refresh ViewModel
        }
    }

Please refer to KO's documentation
https://knockoutjs.com/documentation/plugins-mapping.html for more details.


问:
iterrows pandas get next rows value
I have a df in pandas

```<code>import pandas as pd
df = pd.DataFrame(['AA', 'BB', 'CC'], columns = ['value'])
</code>```

I want to iterate over rows in df. For each row i want rows value and next rows value
Something like(it does not work):

```<code>for i, row in df.iterrows():
     print row['value']
     i1, row1 = next(df.iterrows())
     print row1['value']
</code>```

As a result I want

```<code>'AA'
'BB'
'BB'
'CC'
'CC'
*Wrong index error here
</code>```

At this point i have mess way to solve this

```<code>for i in range(0, df.shape[0])
   print df.irow(i)['value']
   print df.irow(i+1)['value']
</code>```

Is there more efficient way to solve this issue?

答:
a combination of answers gave me a very fast running time.
using the shift method to create new column of next row values,
then using the row_iterator  function as @alisdt did,
but here i changed it from iterrows to itertuples which is 100
times faster.

my script is for iterating dataframe of duplications in different length and add
one second for each duplication so they all be unique.

```<code># create new column with shifted values from the departure time column
df['next_column_value'] = df['column_value'].shift(1)
# create row iterator that can 'save' the next row without running for loop
row_iterator = df.itertuples()
# jump to the next row using the row iterator
last = next(row_iterator)
# because pandas does not support items alteration i need to save it as an object
t = last[your_column_num]
# run and update the time duplications with one more second each
for row in row_iterator:
    if row.column_value == row.next_column_value:
         t = t + add_sec
         df_result.at[row.Index, 'column_name'] = t
    else:
         # here i resetting the 'last' and 't' values
         last = row
         t = last[your_column_num]
</code>```

Hope it will help.

Title: iterrows pandas get next rows value

Body:
I have a df in pandas

import pandas as pd
df = pd.DataFrame(['AA', 'BB', 'CC'], columns = ['value'])

I want to iterate over rows in df. For each row i want rows value and next rows value
Something like(it does not work):

for i, row in df.iterrows():
     print row['value']
     i1, row1 = next(df.iterrows())
     print row1['value']

As a result I want

'AA'
'BB'
'BB'
'CC'
'CC'
*Wrong index error here

At this point i have mess way to solve this

for i in range(0, df.shape[0])
   print df.irow(i)['value']
   print df.irow(i+1)['value']

Is there more efficient way to solve this issue?

Body:
a combination of answers gave me a very fast running time.
using the shift method to create new column of next row values,
then using the row_iterator  function as @alisdt did,
but here i changed it from iterrows to itertuples which is 100
times faster.

my script is for iterating dataframe of duplications in different length and add
one second for each duplication so they all be unique.

# create new column with shifted values from the departure time column
df['next_column_value'] = df['column_value'].shift(1)
# create row iterator that can 'save' the next row without running for loop
row_iterator = df.itertuples()
# jump to the next row using the row iterator
last = next(row_iterator)
# because pandas does not support items alteration i need to save it as an object
t = last[your_column_num]
# run and update the time duplications with one more second each
for row in row_iterator:
    if row.column_value == row.next_column_value:
         t = t + add_sec
         df_result.at[row.Index, 'column_name'] = t
    else:
         # here i resetting the 'last' and 't' values
         last = row
         t = last[your_column_num]

Hope it will help.


Title: How to update the value of a key field in a dictionary in Python?

Body:
Try this,

>>> test = {"100":271,"updated_at":{"date":"2017-10-14T12:15:52.172Z"},"created_at":{"date":"2017-10-14T12:15:52.172Z"}}

>>> dict(("xx_{}".format(k),v) if isinstance(v,int) else (k,v) for k,v in test.items())
{'xx_100': 271, 'updated_at': {'date': '2017-10-14T12:15:52.172Z'}, 'created_at': {'date': '2017-10-14T12:15:52.172Z'}}


问:
Implementing a tail recursive version of quicksort-like function in F#/OCaml
Is it possible to implement a tail recursive version of the quick sort algorithm (via the continuation pattern)? And if it is, how would one implement it?

Normal (not optimized) version:

```<code>let rec quicksort list =
 match list with
 | [] -> []
 | element::[] -> [element]
 | pivot::rest -> let ``elements smaller than pivot``, ``elements larger or equal to pivot``=
                    rest |> List.partition(fun element -> element < pivot)
                  quicksort ``elements smaller than pivot`` @ [pivot] @ quicksort ``elements larger or equal to pivot``
</code>```

答:
Direct style:

```<code>let rec quicksort list =
    match list with
    | [] -> []
    | [element] -> [element]
    | pivot::rest ->
        let left, right = List.partition (fun element -> element < pivot) rest in
        let sorted_left = quicksort left in
        let sorted_right = quicksort right in
        sorted_left @ [pivot] @ sorted_right
</code>```

My first, naive translation is very similar to Laurent's version, except indented a bit weirdly to make apparent that calls with continuations are really a kind of binding:

```<code>let rec quicksort list cont =
    match list with
    | [] -> cont []
    | element::[] -> cont [element]
    | pivot::rest ->
        let left, right = List.partition (fun element -> element < pivot) rest in
        quicksort left (fun sorted_left ->
        quicksort right (fun sorted_right ->
        cont (sorted_left @ [pivot] @ sorted_right)))
let qsort li = quicksort li (fun x -> x)
</code>```

Contrarily to Laurent, I find it easy to check that cont is not forgotten: CPS functions translated from direct style have the property that the continuation is used linearily, once and only once in each branch, in tail position. It is easy to check that no such call was forgotten.

But in fact, for most runs of quicksort (supposing you get a roughly logarithmic behavior because you're not unlucky or you shuffled the input first), the call stack is not an issue, as it only grows logarithmically. Much more worrying are the frequent calls to @ wich is linear in its left parameter. A common optimization technique is to define functions not as returning a list but as "adding input to an accumulator list":

```<code>let rec quicksort list accu =
    match list with
    | [] -> accu
    | element::[] -> element::accu
    | pivot::rest ->
        let left, right = List.partition (fun element -> element < pivot) rest in
        let sorted_right = quicksort right accu in
        quicksort left (pivot :: sorted_right)
let qsort li = quicksort li []
</code>```

Of course this can be turned into CPS again:

```<code>let rec quicksort list accu cont =
    match list with
    | [] -> cont accu
    | element::[] -> cont (element::accu)
    | pivot::rest ->
        let left, right = List.partition (fun element -> element < pivot) rest in
        quicksort right accu (fun sorted_right ->
        quicksort left (pivot :: sorted_right) cont)
let qsort li = quicksort li [] (fun x -> x)
</code>```

Now a last trick is to "defunctionalize" the continuations by turning them into data structure (supposing the allocation of data structures is slightly more efficient than the allocation of a closure):

```<code>type 'a cont =
  | Left of 'a list * 'a * 'a cont
  | Return
let rec quicksort list accu cont =
    match list with
    | [] -> eval_cont cont accu
    | element::[] -> eval_cont cont (element::accu)
    | pivot::rest ->
        let left, right = List.partition (fun element -> element < pivot) rest in
        quicksort right accu (Left (left, pivot, cont))
and eval_cont = function
  | Left (left, pivot, cont) ->
    (fun sorted_right -> quicksort left (pivot :: sorted_right) cont)
  | Return -> (fun x -> x)
let qsort li = quicksort li [] Return
</code>```

Finally, I chose the function .. fun style for eval_cont to make it apparent that those were just pieces of code from the CPS version, but the following version is probably better optimized by arity-raising:

```<code>and eval_cont cont accu = match cont with
  | Left (left, pivot, cont) ->
    quicksort left (pivot :: accu) cont
  | Return -> accu
</code>```

Body:
Is it possible to implement a tail recursive version of the quick sort algorithm (via the continuation pattern)? And if it is, how would one implement it?

Normal (not optimized) version:

let rec quicksort list =
 match list with
 | [] -> []
 | element::[] -> [element]
 | pivot::rest -> let ``elements smaller than pivot``, ``elements larger or equal to pivot``=
                    rest |> List.partition(fun element -> element < pivot)
                  quicksort ``elements smaller than pivot`` @ [pivot] @ quicksort ``elements larger or equal to pivot``

Body:
Direct style:

let rec quicksort list =
    match list with
    | [] -> []
    | [element] -> [element]
    | pivot::rest ->
        let left, right = List.partition (fun element -> element < pivot) rest in
        let sorted_left = quicksort left in
        let sorted_right = quicksort right in
        sorted_left @ [pivot] @ sorted_right

My first, naive translation is very similar to Laurent's version, except indented a bit weirdly to make apparent that calls with continuations are really a kind of binding:

let rec quicksort list cont =
    match list with
    | [] -> cont []
    | element::[] -> cont [element]
    | pivot::rest ->
        let left, right = List.partition (fun element -> element < pivot) rest in
        quicksort left (fun sorted_left ->
        quicksort right (fun sorted_right ->
        cont (sorted_left @ [pivot] @ sorted_right)))
let qsort li = quicksort li (fun x -> x)

Contrarily to Laurent, I find it easy to check that cont is not forgotten: CPS functions translated from direct style have the property that the continuation is used linearily, once and only once in each branch, in tail position. It is easy to check that no such call was forgotten.

But in fact, for most runs of quicksort (supposing you get a roughly logarithmic behavior because you're not unlucky or you shuffled the input first), the call stack is not an issue, as it only grows logarithmically. Much more worrying are the frequent calls to @ wich is linear in its left parameter. A common optimization technique is to define functions not as returning a list but as "adding input to an accumulator list":

let rec quicksort list accu =
    match list with
    | [] -> accu
    | element::[] -> element::accu
    | pivot::rest ->
        let left, right = List.partition (fun element -> element < pivot) rest in
        let sorted_right = quicksort right accu in
        quicksort left (pivot :: sorted_right)
let qsort li = quicksort li []

Of course this can be turned into CPS again:

let rec quicksort list accu cont =
    match list with
    | [] -> cont accu
    | element::[] -> cont (element::accu)
    | pivot::rest ->
        let left, right = List.partition (fun element -> element < pivot) rest in
        quicksort right accu (fun sorted_right ->
        quicksort left (pivot :: sorted_right) cont)
let qsort li = quicksort li [] (fun x -> x)

Now a last trick is to "defunctionalize" the continuations by turning them into data structure (supposing the allocation of data structures is slightly more efficient than the allocation of a closure):

type 'a cont =
  | Left of 'a list * 'a * 'a cont
  | Return
let rec quicksort list accu cont =
    match list with
    | [] -> eval_cont cont accu
    | element::[] -> eval_cont cont (element::accu)
    | pivot::rest ->
        let left, right = List.partition (fun element -> element < pivot) rest in
        quicksort right accu (Left (left, pivot, cont))
and eval_cont = function
  | Left (left, pivot, cont) ->
    (fun sorted_right -> quicksort left (pivot :: sorted_right) cont)
  | Return -> (fun x -> x)
let qsort li = quicksort li [] Return

Finally, I chose the function .. fun style for eval_cont to make it apparent that those were just pieces of code from the CPS version, but the following version is probably better optimized by arity-raising:

and eval_cont cont accu = match cont with
  | Left (left, pivot, cont) ->
    quicksort left (pivot :: accu) cont
  | Return -> accu


问:
Finding nth Match in a List in Excel
I have a table in Excel from A1:A5

```<code>a
a
b
a
b
</code>```

I want to find the row of the nth occurrence of the value 'a' using Excel Functions and not VBA

If I put in 1 into this function, I want to get 1.

If I put in 2 into this function, I want to get 2.

If I put in 3 into this function, I want to get 4

A solution that works is to add the following formula
=COUNTIF($A5:A5,"a") in B1 and then drag it down to B5.

I can then use =MATCH(C1,B1:B5,0) where C1 holds the variable n.

However is there a neater way without having to add extra columns?

答:
this should work ARRAY FORMULA: CTRL + SHIFT + ENTER

```<code>=SMALL(IF(C1=$A$1:$A$5,ROW($A$1:$A$5)),$C$2)
</code>```

Title: Finding nth Match in a List in Excel

Body:
I have a table in Excel from A1:A5

a
a
b
a
b

I want to find the row of the nth occurrence of the value 'a' using Excel Functions and not VBA

If I put in 1 into this function, I want to get 1.

If I put in 2 into this function, I want to get 2.

If I put in 3 into this function, I want to get 4

A solution that works is to add the following formula
=COUNTIF($A5:A5,"a") in B1 and then drag it down to B5.

I can then use =MATCH(C1,B1:B5,0) where C1 holds the variable n.

However is there a neater way without having to add extra columns?

Body:
this should work ARRAY FORMULA: CTRL + SHIFT + ENTER

=SMALL(IF(C1=$A$1:$A$5,ROW($A$1:$A$5)),$C$2)


问:
Where is the correct place in Inno Setup to perform these actions?
During my install I need to perform some code:

Delete an existing file in the app folder if it exists.

Read a registry key to see if they are using local help.

If they are using local help then prompt to download the help file.

If they answer yes, then download.

If they answer no, then update the registry key to say it is using online help.

Which step or event should I use in the code section to perform these tasks?

Is it CurStepChanged() / ssInstall?

答:
I think you should do the detection/prompting before the installation starts. You may use a custom page or a conditional task.

And the actual actions can be done in CurStepChanged(ssInstall).


问:
build-impl.xml:1031: The module has not been deployed
I have been working on a Java web application and i am  using SmartGwt on Netbeans 7.3 and out of a sudden I encountered this problem. I tried cleaning the build-impl.xml then restarting the IDE and I should say I have fairly low knowledge on this. Can someone please tell me why it is giving an error and how I can fix that?

The error message says :

```<code>nbproject/build-impl.xml:1031: The module has not been deployed. See the server log for details.
BUILD FAILED (total time: 4 seconds)
</code>```

Note: i am using Tomcat 7.0.34

答:
One of the main reason for this error is due to permission not granted to all users. so remove this error, follow the following steps :

1) Go to the C:/Programme Files/Apache Software Foundation/Tomcat 7.0

2) Right click on the Tomcat 7.0 folder and click on properties.

3) go to Security Tab.

4) Select the User and click on Edit... button

5) Grant all the permission to the user and click on apply and ok.

Refresh the system and now try. I hope it will work

Body:
I have been working on a Java web application and i am  using SmartGwt on Netbeans 7.3 and out of a sudden I encountered this problem. I tried cleaning the build-impl.xml then restarting the IDE and I should say I have fairly low knowledge on this. Can someone please tell me why it is giving an error and how I can fix that?

The error message says :

nbproject/build-impl.xml:1031: The module has not been deployed. See the server log for details.
BUILD FAILED (total time: 4 seconds)

Note: i am using Tomcat 7.0.34


问:
App Store/Play Store redirection if App is not installed on ionic App
I have implemented deeplink for my ionic v1 application and also implemented universal link for same. I also checked so many links to implement App store redirection functionality.

Most of the link suggest to implement javascript code which first check device and based on ios/adnroid/window it will redirect to particular store but let say I will create that javascript code look like below

```<code>const iOS = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform);

if (iOS) {
  window.location.href = "temp://itunes.apple.com/us/app/...";
}
</code>```

but where should I put this file so when user click on deeplink it should redirect to particular this file and redirect to App Store/Play Store?

Let say I want to give my deeplink to some other server for which i don't have any access then what?

is there any other param or attribute we can set like fallback url by which when app is not installed it will automatically going to that particular link?

Any answer would be great help.

Thanks.

答:
Usually it works that way:

You place a link on the website where you want to advertise your app. That link has a click tracking domain that points to your server. e.g. click.example.com/....

Upon clicking, if the app is installed, Universal Links would ensure that the app is opened. This is done by iOS (only if you configured Universal Links correctly, see https://developer.apple.com/ios/universal-links/). If the app is not installed, a redirect is done to your click tracking domain. This is where your Javascript logics should apply, so basically you need to reply to the request with a 302 redirect to an HTML file that contains the redirection logics (as in the example above). In that server response you can handle any fallback URL you want to use.

By the way, to make Universal Links work, anyway you had to host the AASA file, so you probably already created a server, so you can use it for the case where the app is not installed.

Body:
I have implemented deeplink for my ionic v1 application and also implemented universal link for same. I also checked so many links to implement App store redirection functionality.

Most of the link suggest to implement javascript code which first check device and based on ios/adnroid/window it will redirect to particular store but let say I will create that javascript code look like below

const iOS = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform);

if (iOS) {
  window.location.href = "temp://itunes.apple.com/us/app/...";
}

but where should I put this file so when user click on deeplink it should redirect to particular this file and redirect to App Store/Play Store?

Let say I want to give my deeplink to some other server for which i don't have any access then what?

is there any other param or attribute we can set like fallback url by which when app is not installed it will automatically going to that particular link?

Any answer would be great help.

Thanks.


问:
MySQL workbench is deleted after upgrade to Ubuntu 19.4
i was working on Ubuntu 18 and i installed MySQL workbench form Ubuntu store , now i upgraded my Ubuntu to new version and no MySQL workbench found in my system ,I tried to download it again from Ubuntu store and i did't found it  ??</p>

答: MySQL Workbench has not been updated yet to support Ubuntu 19.04. The upcoming version will, however.</p>


问:
How do I add an active class to a Link from React Router?
I've created a bootstrap-style sidebar using Link. Here is a snippet of my code:

MAIN NAVIGATION

<Link to="dashboard"> Dashboard</Link>

<Link to="email_lists"> Email Lists</Link>

<Link to="billing"> Buy Verifications</Link>

```

I want to set the class for the active path to active on the wrapping element
. I see there are other solutions out there that show how to do this like Conditionally set active class on menu using react router current route, however I don't think that it's the best way to set an active class on a wrapper to a Link.

I also found https://github.com/insin/react-router-active-component but it feels like it is unnecessary.

In React Router, is this possible or do I need to use an external solution?

答:
Its very easy to do that, react-router-dom provides all.

import React from 'react';
import { matchPath, withRouter } from 'react-router';

class NavBar extends React.Component {
  render(){
    return(

MAIN NAVIGATION

<Link to="dashboard">
        Dashboard</Link>

<Link to="email_lists">
        Email Lists</Link>

<Link to="billing">
        Buy Verifications</Link>

      )
   }
}

export default withRouter(NavBar);```

Wrapping You Navigation Component with withRouter() HOC will provide few props to your component:
1. match
2. history
3. location

here i used matchPath() method from react-router to compare the paths and decide if the 'li' tag should get "active" class name or not. and Im accessing the location from this.props.location.pathname.

changing the path name in props will happen when our link is clicked, and location props will get updated NavBar also get re-rendered and active style will get applied

Body:
I've created a bootstrap-style sidebar using Link. Here is a snippet of my code:

MAIN NAVIGATION

<Link to="dashboard"> Dashboard</Link>

<Link to="email_lists"> Email Lists</Link>

<Link to="billing"> Buy Verifications</Link>

I want to set the class for the active path to active on the wrapping element
. I see there are other solutions out there that show how to do this like Conditionally set active class on menu using react router current route, however I don't think that it's the best way to set an active class on a wrapper to a Link.

I also found https://github.com/insin/react-router-active-component but it feels like it is unnecessary.

In React Router, is this possible or do I need to use an external solution?

Body:
Its very easy to do that, react-router-dom provides all.

import React from 'react';
import { matchPath, withRouter } from 'react-router';

class NavBar extends React.Component {
  render(){
    return(
       <ul className="sidebar-menu">
      <li className="header">MAIN NAVIGATION</li>
      <li className={matchPath(this.props.location.pathname, { path: "/dashboard" }) ? 'active' : ''}><Link to="dashboard"><i className="fa fa-dashboard"></i>
        <span>Dashboard</span></Link></li>
      <li className={matchPath(this.props.location.pathname, { path: "/email_lists" }) ? 'active' : ''}><Link to="email_lists"><i className="fa fa-envelope-o"></i>
        <span>Email Lists</span></Link></li>
      <li className={matchPath(this.props.location.pathname, { path: "/billing" }) ? 'active' : ''}><Link to="billing"><i className="fa fa-credit-card"></i>
        <span>Buy Verifications</span></Link></li>
    </ul>
      )
   }
}

export default withRouter(NavBar);

Wrapping You Navigation Component with withRouter() HOC will provide few props to your component:
1. match
2. history
3. location

here i used matchPath() method from react-router to compare the paths and decide if the 'li' tag should get "active" class name or not. and Im accessing the location from this.props.location.pathname.

changing the path name in props will happen when our link is clicked, and location props will get updated NavBar also get re-rendered and active style will get applied


问:
How to reiterate through all the view in recyclerview?
I want to achieve expandable item inside RecyclerView and when one item is expanded the other expanded item must automatically close, can someone please help?</p>

答:
You can make use of notifyDataSetChanged().

keep a boolean to identify an item expanded or not. For example, suppose you are showing a list of students and on clicking a student expand the item and show details of the student.

```<code>class Student{
String name;
String age;
boolean isexpanded;
}
</code>```

On item click, you set 'isexpanded=true' to the clicked item and 'isexpanded=false' for all other items in the list.

and then call notifyDataSetChanged() to update the RecyclerView. (inside adapter class you have to manage expanding and closing of expanded views by checking the 'isexpanded')

(I am new to Android and I'm not sure this is the best solution or not)

Body:
You can make use of notifyDataSetChanged().

keep a boolean to identify an item expanded or not. For example, suppose you are showing a list of students and on clicking a student expand the item and show details of the student.

class Student{
String name;
String age;
boolean isexpanded;
}

On item click, you set 'isexpanded=true' to the clicked item and 'isexpanded=false' for all other items in the list.

and then call notifyDataSetChanged() to update the RecyclerView. (inside adapter class you have to manage expanding and closing of expanded views by checking the 'isexpanded')

(I am new to Android and I'm not sure this is the best solution or not)


问:
How to create a tunnel after ssh to remote machine using private key using bash script
I have a server where i will be logging into the server from my local machine and create a tunnel.

I have a bash script which is not creating tunnel

```<code>sshpass -p ${1} ssh ${2}@${3}
ssh -L <port1>:<host>:80 -i /home/<user>/private_key <user_ID>@<host2>
</code>```

Result i am getting -

```<code>sh ssh_to_box.sh pwd username remotehost
Welcome to Ubuntu 16.04.5 LTS (GNU/Linux 4.4.0-145-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

144 packages can be updated.
0 updates are security updates.

New release '18.04.2 LTS' available.
Run 'do-release-upgrade' to upgrade to it.

*** System restart required ***
Last login: Thu May 30 09:36:36 2019 from remotehost
$
</code>```

Script is not doing tunneling.
Also it should do $bash

How to ssh to remote and create tunnel from that remote machine and keep the tunnel alive?

答:
Probably you are in fact creating the tunnel, you should check if

```<code>ss -lptn | awk '{ print $4 }' | awk -F ':' '{ print $2 }' | sed -e '/<port1>/!d'
</code>```

Is returning something when the ssh console is opened, if true you have a tunnel.
(May there is a better way to do this check but I didn't know very well awk)

If you want the tunnel to be persistent may you execute it inside tmux/screen or run nohup <tunnel_command> &

It's important to note that  name will be dns resolved by the remote host also.

Body:
I have a server where i will be logging into the server from my local machine and create a tunnel.

I have a bash script which is not creating tunnel

sshpass -p ${1} ssh ${2}@${3}
ssh -L <port1>:<host>:80 -i /home/<user>/private_key <user_ID>@<host2>

Result i am getting -

sh ssh_to_box.sh pwd username remotehost
Welcome to Ubuntu 16.04.5 LTS (GNU/Linux 4.4.0-145-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

144 packages can be updated.
0 updates are security updates.

New release '18.04.2 LTS' available.
Run 'do-release-upgrade' to upgrade to it.

*** System restart required ***
Last login: Thu May 30 09:36:36 2019 from remotehost
$

Script is not doing tunneling.
Also it should do $bash

How to ssh to remote and create tunnel from that remote machine and keep the tunnel alive?

Body:
Probably you are in fact creating the tunnel, you should check if

ss -lptn | awk '{ print $4 }' | awk -F ':' '{ print $2 }' | sed -e '/<port1>/!d'

Is returning something when the ssh console is opened, if true you have a tunnel.
(May there is a better way to do this check but I didn't know very well awk)

If you want the tunnel to be persistent may you execute it inside tmux/screen or run nohup <tunnel_command> &

It's important to note that  name will be dns resolved by the remote host also.


问:
How to call a function and then navigate to a route when click on a button?
Here is my code.

```<code><button type="button" className="btn btn-outline-secondary" onClick={this.addToCart.bind(
    this,
    this.state.itemDetails.product.images[0].path,
    this.state.itemDetails.name,
    this.state.itemDetails.id,
    this.state.itemDetails.unitPrice,
    this.state.quantity
)} >
    <Link to="/proceedToCheckout">
    Buy Now
    </Link>
</button>
</code>```

Here I want to call the event onClick and with that I want to direct page to the link "/proceedToCheckout" when I click on the button. I want to do both of this with a single button click.
In the above code, when I click on the button area it calls the addToCart function. But route is not working. If I click on the word "Buy Now" (the link) then it directs to the route. But I want to do is with a single button click I need to call the function "addToCart" and then to direct to the route "/proceedToCheckout"

答:
As per your code, I have done some changes:

```<code><button type="button" className="btn btn-outline-secondary" onClick={this.addToCart.bind(
this,
this.state.itemDetails.product.images[0].path,
this.state.itemDetails.name,
this.state.itemDetails.id,
this.state.itemDetails.unitPrice,
this.state.quantity )} >

Buy Now </button>
</code>```

And In the 'addToCart' function, I have added the routing which you want to achieve

```<code>addToCart= () => {
   .... // what you want to achieve in this function
   ....
   this.props.history.push('/proceedToCheckout');

}
</code>```

Body:
Here is my code.

<button type="button" className="btn btn-outline-secondary" onClick={this.addToCart.bind(
    this,
    this.state.itemDetails.product.images[0].path,
    this.state.itemDetails.name,
    this.state.itemDetails.id,
    this.state.itemDetails.unitPrice,
    this.state.quantity
)} >
    <Link to="/proceedToCheckout">
    Buy Now
    </Link>
</button>

Here I want to call the event onClick and with that I want to direct page to the link "/proceedToCheckout" when I click on the button. I want to do both of this with a single button click.
In the above code, when I click on the button area it calls the addToCart function. But route is not working. If I click on the word "Buy Now" (the link) then it directs to the route. But I want to do is with a single button click I need to call the function "addToCart" and then to direct to the route "/proceedToCheckout"

Body:
As per your code, I have done some changes:

<button type="button" className="btn btn-outline-secondary" onClick={this.addToCart.bind(
this,
this.state.itemDetails.product.images[0].path,
this.state.itemDetails.name,
this.state.itemDetails.id,
this.state.itemDetails.unitPrice,
this.state.quantity )} >

Buy Now </button>

And In the 'addToCart' function, I have added the routing which you want to achieve

addToCart= () => {
   .... // what you want to achieve in this function
   ....
   this.props.history.push('/proceedToCheckout');

}


问:
Insert Update trigger how to determine if insert or update
I need to write an Insert, Update Trigger on table A which will delete all rows from table B whose one column (say Desc) has values like the value inserted/updated in the table A's column (say Col1). How would I go around writing it so that I can handle both Update and Insert cases. How would I determine if the trigger is executed for an update or insert.</p>

答:
After a lot of searching I could not find an exact example of a single SQL Server trigger that handles all (3) three conditions of the trigger actions INSERT, UPDATE, and DELETE.    I finally found a line of text that talked about the fact that when a DELETE or UPDATE occurs, the common DELETED table will contain a record for these two actions.   Based upon that information, I then created a small Action routine which determines why the trigger has been activated.  This type of interface is sometimes needed when there is both a common configuration and a specific action to occur on an INSERT vs. UPDATE trigger.  In these cases, to create a separate trigger for the UPDATE and the INSERT would become maintenance problem.  (i.e. were both triggers updated properly for the necessary common data algorithm fix?)

To that end, I would like to give the following multi-trigger event code snippet for handling INSERT, UPDATE, DELETE in one trigger for an Microsoft SQL Server.

```<code>CREATE TRIGGER [dbo].[INSUPDDEL_MyDataTable]
ON [dbo].[MyDataTable] FOR INSERT, UPDATE, DELETE
AS

-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with caller queries SELECT statements.
-- If an update/insert/delete occurs on the main table, the number of records affected
-- should only be based on that table and not what records the triggers may/may not
-- select.
SET NOCOUNT ON;

--
-- Variables Needed for this Trigger
--
DECLARE @PACKLIST_ID varchar(15)
DECLARE @LINE_NO smallint
DECLARE @SHIPPED_QTY decimal(14,4)
DECLARE @CUST_ORDER_ID varchar(15)
--
-- Determine if this is an INSERT,UPDATE, or DELETE Action
--
DECLARE @Action as char(1)
DECLARE @Count as int
SET @Action = 'I' -- Set Action to 'I'nsert by default.
SELECT @Count = COUNT(*) FROM DELETED
if @Count > 0
    BEGIN
        SET @Action = 'D' -- Set Action to 'D'eleted.
        SELECT @Count = COUNT(*) FROM INSERTED
        IF @Count > 0
            SET @Action = 'U' -- Set Action to 'U'pdated.
    END

if @Action = 'D'
    -- This is a DELETE Record Action
    --
    BEGIN
        SELECT @PACKLIST_ID =[PACKLIST_ID]
                    ,@LINE_NO = [LINE_NO]
        FROM DELETED

        DELETE [dbo].[MyDataTable]
        WHERE [PACKLIST_ID]=@PACKLIST_ID AND [LINE_NO]=@LINE_NO
    END
 Else
    BEGIN
            --
            -- Table INSERTED is common to both the INSERT, UPDATE trigger
            --
            SELECT @PACKLIST_ID =[PACKLIST_ID]
                ,@LINE_NO = [LINE_NO]
                ,@SHIPPED_QTY =[SHIPPED_QTY]
                ,@CUST_ORDER_ID = [CUST_ORDER_ID]
            FROM INSERTED

         if @Action = 'I'
            -- This is an Insert Record Action
            --
            BEGIN
                INSERT INTO [MyChildTable]
                    (([PACKLIST_ID]
                    ,[LINE_NO]
                    ,[STATUS]
                VALUES
                    (@PACKLIST_ID
                    ,@LINE_NO
                    ,'New Record'
                    )
            END
        else
            -- This is an Update Record Action
            --
            BEGIN
                UPDATE [MyChildTable]
                    SET [PACKLIST_ID] = @PACKLIST_ID
                          ,[LINE_NO] = @LINE_NO
                          ,[STATUS]='Update Record'
                WHERE [PACKLIST_ID]=@PACKLIST_ID AND [LINE_NO]=@LINE_NO
            END
    END
</code>```

ContentLicense: CC BY-SA 2.5

Body:
After a lot of searching I could not find an exact example of a single SQL Server trigger that handles all (3) three conditions of the trigger actions INSERT, UPDATE, and DELETE.    I finally found a line of text that talked about the fact that when a DELETE or UPDATE occurs, the common DELETED table will contain a record for these two actions.   Based upon that information, I then created a small Action routine which determines why the trigger has been activated.  This type of interface is sometimes needed when there is both a common configuration and a specific action to occur on an INSERT vs. UPDATE trigger.  In these cases, to create a separate trigger for the UPDATE and the INSERT would become maintenance problem.  (i.e. were both triggers updated properly for the necessary common data algorithm fix?)

To that end, I would like to give the following multi-trigger event code snippet for handling INSERT, UPDATE, DELETE in one trigger for an Microsoft SQL Server.

CREATE TRIGGER [dbo].[INSUPDDEL_MyDataTable]
ON [dbo].[MyDataTable] FOR INSERT, UPDATE, DELETE
AS

-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with caller queries SELECT statements.
-- If an update/insert/delete occurs on the main table, the number of records affected
-- should only be based on that table and not what records the triggers may/may not
-- select.
SET NOCOUNT ON;

--
-- Variables Needed for this Trigger
--
DECLARE @PACKLIST_ID varchar(15)
DECLARE @LINE_NO smallint
DECLARE @SHIPPED_QTY decimal(14,4)
DECLARE @CUST_ORDER_ID varchar(15)
--
-- Determine if this is an INSERT,UPDATE, or DELETE Action
--
DECLARE @Action as char(1)
DECLARE @Count as int
SET @Action = 'I' -- Set Action to 'I'nsert by default.
SELECT @Count = COUNT(*) FROM DELETED
if @Count > 0
    BEGIN
        SET @Action = 'D' -- Set Action to 'D'eleted.
        SELECT @Count = COUNT(*) FROM INSERTED
        IF @Count > 0
            SET @Action = 'U' -- Set Action to 'U'pdated.
    END

if @Action = 'D'
    -- This is a DELETE Record Action
    --
    BEGIN
        SELECT @PACKLIST_ID =[PACKLIST_ID]
                    ,@LINE_NO = [LINE_NO]
        FROM DELETED

        DELETE [dbo].[MyDataTable]
        WHERE [PACKLIST_ID]=@PACKLIST_ID AND [LINE_NO]=@LINE_NO
    END
 Else
    BEGIN
            --
            -- Table INSERTED is common to both the INSERT, UPDATE trigger
            --
            SELECT @PACKLIST_ID =[PACKLIST_ID]
                ,@LINE_NO = [LINE_NO]
                ,@SHIPPED_QTY =[SHIPPED_QTY]
                ,@CUST_ORDER_ID = [CUST_ORDER_ID]
            FROM INSERTED

         if @Action = 'I'
            -- This is an Insert Record Action
            --
            BEGIN
                INSERT INTO [MyChildTable]
                    (([PACKLIST_ID]
                    ,[LINE_NO]
                    ,[STATUS]
                VALUES
                    (@PACKLIST_ID
                    ,@LINE_NO
                    ,'New Record'
                    )
            END
        else
            -- This is an Update Record Action
            --
            BEGIN
                UPDATE [MyChildTable]
                    SET [PACKLIST_ID] = @PACKLIST_ID
                          ,[LINE_NO] = @LINE_NO
                          ,[STATUS]='Update Record'
                WHERE [PACKLIST_ID]=@PACKLIST_ID AND [LINE_NO]=@LINE_NO
            END
    END


问:
Java get value by key in JSON data
```<code>[
{
    "boylam":31.8039,
    "enlem":40.5906,
    "il":"",
    "ilPlaka":"",
    "ilce":"",
    "oncelik":0,
    "yukseklik":2052,
    "aciklama":"",
    "modelId":124774,
    "gps":0
}]
</code>```

Hi I have such a JSON data in my hand. I had a hard time getting the data out of here. For example, how do I print the "boylam" option in JSON data?

答:
Use Google Gson,the code maybe like this:</p>

```<code>    // construct the json object
    JsonArray jsonArray = new JsonArray();
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("boylam",31.8039);
    jsonArray.add(jsonObject);
    // iterate the json array
    jsonArray.forEach(jsonElement -> {
        JsonObject element = (JsonObject) jsonElement;
        System.out.println(element.get("boylam"));
    });
</code>```

Title: Java get value by key in JSON data

Body:
[
{
    "boylam":31.8039,
    "enlem":40.5906,
    "il":"",
    "ilPlaka":"",
    "ilce":"",
    "oncelik":0,
    "yukseklik":2052,
    "aciklama":"",
    "modelId":124774,
    "gps":0
}]

Hi I have such a JSON data in my hand. I had a hard time getting the data out of here. For example, how do I print the "boylam" option in JSON data?

Body:
Use Google Gson,the code maybe like this:

    // construct the json object
    JsonArray jsonArray = new JsonArray();
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("boylam",31.8039);
    jsonArray.add(jsonObject);
    // iterate the json array
    jsonArray.forEach(jsonElement -> {
        JsonObject element = (JsonObject) jsonElement;
        System.out.println(element.get("boylam"));
    });


问:
How can I populate Array with Ms SQL query results in swift?
I'm new to writing programs with Xcode.
I am doing the MS SQL connection successfully, but how can I populate an Array variable with a defined query result. I want to show the string values that I populate to the Array variable on TableView.
I've come up to my code:

```<code>import UIKit
class SecondViewController: UIViewController,SQLClientDelegate {
    func error(_ error: String!, code: Int32, severity: Int32) {
        print("\(error!) \(code) \(severity)")
}
    @IBOutlet weak var userListTableView: UITableView!
    var client:SQLClient!
    var uNames: [String] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        client = SQLClient.sharedInstance()!
//Initially we call the DB data in internal memory.
        strIP = UserDefaults.standard.string(forKey: "DBServerIP")!
        strDBName = UserDefaults.standard.string(forKey: "DBName")!
        strUName = UserDefaults.standard.string(forKey: "DBUser")!
        strPass = UserDefaults.standard.string(forKey: "DBPass")!
}
    @IBAction func btnUserAct(_ sender: Any) {
        client = SQLClient.sharedInstance()!
        client.delegate = self
        client.connect(strIP,username: strUName,password: strPass,database: strDBName){ success in
            if success {
                self.client.execute("Select UserId from Usertbl order by Id") {
                results in
                    for table in results as! [[[String:AnyObject]]] {
                        for row in table {
                            for (columnName, value) in row {
                                print(value)
//Here, UserId data appears successfully in the Xcode Debug area. So connection successful.
//How can I populate these values to the uNames Array variable?
}}}
                    self.client.disconnect()
}}}}}
extension SecondViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return uNames.count
}
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = uNames[indexPath.row]
        return cell
}}
</code>```

I need your help.

答:
It's trivial, if your question is How to add a value to array, you can use append method of array in Swift. The value is of type AnyObject, so you must convert to String. Try do this:

```<code>for (columnName, value) in row {
         print(value)

         // First option
         let newVal = value as? String ?? ""
         self.uNames.append(newVal)

         // Second option
         // self.uNames.append(value as! String)

        //Here, UserId data appears successfully in the Xcode Debug area. So connection successful.
        //How can I populate these values to the uNames Array variable?
}
</code>```

Body:
I'm new to writing programs with Xcode.
I am doing the MS SQL connection successfully, but how can I populate an Array variable with a defined query result. I want to show the string values that I populate to the Array variable on TableView.
I've come up to my code:

import UIKit
class SecondViewController: UIViewController,SQLClientDelegate {
    func error(_ error: String!, code: Int32, severity: Int32) {
        print("\(error!) \(code) \(severity)")
}
    @IBOutlet weak var userListTableView: UITableView!
    var client:SQLClient!
    var uNames: [String] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        client = SQLClient.sharedInstance()!
//Initially we call the DB data in internal memory.
        strIP = UserDefaults.standard.string(forKey: "DBServerIP")!
        strDBName = UserDefaults.standard.string(forKey: "DBName")!
        strUName = UserDefaults.standard.string(forKey: "DBUser")!
        strPass = UserDefaults.standard.string(forKey: "DBPass")!
}
    @IBAction func btnUserAct(_ sender: Any) {
        client = SQLClient.sharedInstance()!
        client.delegate = self
        client.connect(strIP,username: strUName,password: strPass,database: strDBName){ success in
            if success {
                self.client.execute("Select UserId from Usertbl order by Id") {
                results in
                    for table in results as! [[[String:AnyObject]]] {
                        for row in table {
                            for (columnName, value) in row {
                                print(value)
//Here, UserId data appears successfully in the Xcode Debug area. So connection successful.
//How can I populate these values to the uNames Array variable?
}}}
                    self.client.disconnect()
}}}}}
extension SecondViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return uNames.count
}
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = uNames[indexPath.row]
        return cell
}}

I need your help.

Body:
It's trivial, if your question is How to add a value to array, you can use append method of array in Swift. The value is of type AnyObject, so you must convert to String. Try do this:

for (columnName, value) in row {
         print(value)

         // First option
         let newVal = value as? String ?? ""
         self.uNames.append(newVal)

         // Second option
         // self.uNames.append(value as! String)

        //Here, UserId data appears successfully in the Xcode Debug area. So connection successful.
        //How can I populate these values to the uNames Array variable?
}