问:
Json reponse from Google API Distance Value
I would like to get only the distance value in a variable from a json Google API Distance Response. For info i use the package https://github.com/alexpechkarev/google-maps.

Here my function :

Route::get('/test', function () {

```<code>$origin = 'Paris';
$destination = 'Toulouse';

$response = \GoogleMaps::load('directions')
    ->setParam([
        'origin'          => $origin,
        'destination'     => $destination,
        'mode' => 'driving' ,
        'language' => 'fr',

    ])->get();

dd($response);
</code>```

});

Here a part of my Json reponse

```<code>"routes": [\n
        {\n
            "bounds": {\n
                "northeast": {\n
                    "lat": 43.605236,\n
                    "lng": 2.3535075\n
                },\n
                "southwest": {\n
                    "lat": 43.1955599,\n
                    "lng": 1.4444285\n
                }\n
            },\n
            "copyrights": "Donn\u00e9es cartographiques \u00a92017 Google",\n
            "legs": [\n
                {\n
                    "distance": {\n
                        "text": "93,2 km",\n
                        "value": 93199\n
                    },\n
</code>```

I would like to get the value from distance  = "93199" someone knows how i could access to the value ?

Thanks a lot in advance

答:
You can access the value distance by

```<code>Route::get('/test', function () {

$origin = 'Paris';
$destination = 'Toulouse';

$response = \GoogleMaps::load('directions')
    ->setParam([
        'origin'          => $origin,
        'destination'     => $destination,
        'mode' => 'driving' ,
        'language' => 'fr',

    ])->get();

$res = json_decode($response);;
foreach($res->routes as $resp) {
    foreach($resp->legs as $dist) {
        dd($dist->distance);
    }
}

});
</code>```

Feel free to manipulate the codes that I gave.

Hope it helps.

Body:
I would like to get only the distance value in a variable from a json Google API Distance Response. For info i use the package https://github.com/alexpechkarev/google-maps.

Here my function :

Route::get('/test', function () {

$origin = 'Paris';
$destination = 'Toulouse';

$response = \GoogleMaps::load('directions')
    ->setParam([
        'origin'          => $origin,
        'destination'     => $destination,
        'mode' => 'driving' ,
        'language' => 'fr',

    ])->get();

dd($response);

});

Here a part of my Json reponse

"routes": [\n
        {\n
            "bounds": {\n
                "northeast": {\n
                    "lat": 43.605236,\n
                    "lng": 2.3535075\n
                },\n
                "southwest": {\n
                    "lat": 43.1955599,\n
                    "lng": 1.4444285\n
                }\n
            },\n
            "copyrights": "Donn\u00e9es cartographiques \u00a92017 Google",\n
            "legs": [\n
                {\n
                    "distance": {\n
                        "text": "93,2 km",\n
                        "value": 93199\n
                    },\n

I would like to get the value from distance  = "93199" someone knows how i could access to the value ?

Thanks a lot in advance

Body:
You can access the value distance by

Route::get('/test', function () {

$origin = 'Paris';
$destination = 'Toulouse';

$response = \GoogleMaps::load('directions')
    ->setParam([
        'origin'          => $origin,
        'destination'     => $destination,
        'mode' => 'driving' ,
        'language' => 'fr',

    ])->get();

$res = json_decode($response);;
foreach($res->routes as $resp) {
    foreach($resp->legs as $dist) {
        dd($dist->distance);
    }
}

});

Feel free to manipulate the codes that I gave.

Hope it helps.


来源: stackexchange

问:
PHP sum two different minutes
i have two different break time

default break time

extra break time

here i want to sum of two times and display 12 hrs format

EX :

```<code>$default_time = "00:30";
 $extra_time   = "00:25";
</code>```

my expected output : 00:55

but now display 01:00

this is my code

```<code>$default_time = $work_data->break_time;
$break_time =  $work_data->extra_time;
$total_break = strtotime($default_time)+strtotime($break_time);
echo date("h:i",strtotime($total_break));
</code>```

答:
There is one function call to strtotime function too much.

You should leave out the strtotime() call in the last line, as $total_break already is a UNIX timestamp:

```<code>$total_break = strtotime($default_time)+strtotime($break_time);
echo date("h:i",$total_break);
</code>```

ContentLicense: CC BY-SA 3.0

Title: PHP sum two different minutes

Body:
i have two different break time

default break time

extra break time

here i want to sum of two times and display 12 hrs format

EX :

$default_time = "00:30";
 $extra_time   = "00:25";

my expected output : 00:55

but now display 01:00

this is my code

$default_time = $work_data->break_time;
$break_time =  $work_data->extra_time;
$total_break = strtotime($default_time)+strtotime($break_time);
echo date("h:i",strtotime($total_break));

Body:
There is one function call to strtotime function too much.

You should leave out the strtotime() call in the last line, as $total_break already is a UNIX timestamp:

$total_break = strtotime($default_time)+strtotime($break_time);
echo date("h:i",$total_break);


问:
setting value in CFDictionary with Swift 3.0
I'm just starting swift 3.0. I try to define a CFDictionary to set value.When the code run to function of "CFDictionarySetValue" , I got this error: EXC_BAD_ACCESS(code=1,address=0x7e8)</p>

```<code>    var keyCallBacks = kCFTypeDictionaryKeyCallBacks
    var valueCallBacks = kCFTypeDictionaryValueCallBacks
    let query = CFDictionaryCreateMutable(kCFAllocatorDefault, 4, &keyCallBacks,&valueCallBacks)

    var secClass = kSecClass
    var genericPassword = kSecClassGenericPassword
    CFDictionarySetValue(query,&secClass, &genericPassword)

    var attrCount = kSecAttrAccount
    var accountStr = "nothing_account" as CFString
    CFDictionarySetValue(query, &attrCount, &accountStr)
</code>```

答:
There is no need to use the cumbersome syntax to create CF.. collection types, you could declare the dictionary as Swift Dictionary – you have to annotate it explicitly and bridge the keys to String – and bridge the dictionary to CFDictionary for example:

```<code>let query : [String: Any] = [kSecClass as String : kSecClassGenericPassword,
                             kSecAttrAccount as String : "nothing_account"]

var result : CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &result)
</code>```

Body:
I'm just starting swift 3.0. I try to define a CFDictionary to set value.When the code run to function of "CFDictionarySetValue" , I got this error: EXC_BAD_ACCESS(code=1,address=0x7e8)

    var keyCallBacks = kCFTypeDictionaryKeyCallBacks
    var valueCallBacks = kCFTypeDictionaryValueCallBacks
    let query = CFDictionaryCreateMutable(kCFAllocatorDefault, 4, &keyCallBacks,&valueCallBacks)

    var secClass = kSecClass
    var genericPassword = kSecClassGenericPassword
    CFDictionarySetValue(query,&secClass, &genericPassword)

    var attrCount = kSecAttrAccount
    var accountStr = "nothing_account" as CFString
    CFDictionarySetValue(query, &attrCount, &accountStr)

Body:
There is no need to use the cumbersome syntax to create CF.. collection types, you could declare the dictionary as Swift Dictionary – you have to annotate it explicitly and bridge the keys to String – and bridge the dictionary to CFDictionary for example:

let query : [String: Any] = [kSecClass as String : kSecClassGenericPassword,
                             kSecAttrAccount as String : "nothing_account"]

var result : CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &result)


问:
Numpy: signed values of element-wise absolute maximum of a 2D array
Let us assume that I have a 2D array named arr of shape (4, 3) as follows:

```<code>>>> arr
array([[ nan,   1., -18.],
   [ -1.,  -1.,  -1.],
   [  1.,   1.,   5.],
   [  1.,  -1.,   0.]])
</code>```

Say that, I would like to assign the signed value of the element-wise absolute maximum of (1.0, 1.0, -15.0) and the rows arr[[0, 2], :] back to arr. Which means, I am looking for the output:

```<code>>>> arr
array([[ 1.,   1.,  -18.],
   [ -1.,  -1.,  -1.],
   [  1.,   1., -15.],
   [  1.,  -1.,   0.]])
</code>```

The closest thing I found in the API reference for this is numpy.fmax but it doesn't do the absolute value. If I used:

```<code>arr[index_list, :] = np.fmax(arr[index_list, :], new_tuple)
</code>```

my array would finally look like:

```<code>>>> arr
array([[ 1.,   1., -15.],
   [ -1.,  -1.,  -1.],
   [  1.,   1.,   5.],
   [  1.,  -1.,   0.]])
</code>```

Now, the API says that this function is

equivalent to np.where(x1 >= x2, x1, x2) when neither x1 nor x2 are NaNs, but it is faster and does proper broadcasting

I tried using the following:

```<code>arr[index_list, :] = np.where(np.absolute(arr[index_list, :]) >= np.absolute(new_tuple),
                              arr[index_list, :], new_tuple)
</code>```

Although this produced the desired output, I got the warning:

/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevconsole.py:1: RuntimeWarning: invalid value encountered in greater_equal

I believe this warning is because of the NaN which is not handled gracefully here, unlike the np.fmax function. In addition, the API docs mention that np.fmax is faster and does broadcasting correctly (not sure what part of broadcasting is missing in the np.where version)

In conclusion, what I am looking for is something similar to:

```<code>arr[index_list, :] = np.fmax(arr[index_list, :], new_tuple, key=abs)
</code>```

There is no such key attribute available to this function, unfortunately.

Just for context, I am interested in the fastest possible solution because my actual shape of the arr array is an average of (100000, 50) and I am looping through almost 1000 new_tuple tuples (with each tuple equal in shape to the number of columns in arr, of course). The index_list changes for each new_tuple.

Edit 1:

One possible solution is, to begin with replacing all NaN in arr with 0. i.e. arr[np.isnan(arr)] = 0. After this, I can use the np.where with np.absolute trick mentioned in my original text. However, this is probably a lot slower than np.fmax, as suggested by the API.

Edit 2:

The index_list may have repeated indexes in subsequent loops. Every new_tuple comes with a corresponding rule and the index_list is selected based on that rule. There is nothing stopping different rules from having overlapping indexes that they match to. @Divakar has an excellent answer for the case where index_list has no repeats. Other solutions are however welcome covering both cases.

答:
Assuming that list of all index_list has no repeated indexes:

Approach #1

I would propose more of a vectorized solution once we have all of index_lists and new_tuples stored in one place, preferably as a list. As such this could be the preferred one, if we are dealing with lots of such tuples and lists.

So, let's say we have them stored as the following :

```<code>new_tuples = [(1.0, 1.0, -15.0), (6.0, 3.0, -4.0)] # list of all new_tuple
index_lists =[[0,2],[4,1,6]]  # list of all index_list
</code>```

The solution thereafter would be to manually repeat, replacing the broadcasting and then use np.where as shown later on in the question. Using np.where on the concern around the said warning, we can ignore, if the new_tuples have non-NaN values. Thus, the solution would be -

```<code>idx = np.concatenate(index_lists)
lens = list(map(len,index_lists))

a = arr[idx]
b = np.repeat(new_tuples,lens,axis=0)
arr[idx] = np.where(np.abs(a) > np.abs(b), a, b)
</code>```

Approach #2

Another approach would be to store the absolute values of arr beforeand : abs_arr = np.abs(arr) and using those within np.where. This should save a lot time within the loop. Thus, the relevant computation would reduce to :

```<code>arr[index_list, :] = np.where(abs_arr[index_list, :] > np.abs(b), a, new_tuple)
</code>```

Body:
Let us assume that I have a 2D array named arr of shape (4, 3) as follows:

>>> arr
array([[ nan,   1., -18.],
   [ -1.,  -1.,  -1.],
   [  1.,   1.,   5.],
   [  1.,  -1.,   0.]])

Say that, I would like to assign the signed value of the element-wise absolute maximum of (1.0, 1.0, -15.0) and the rows arr[[0, 2], :] back to arr. Which means, I am looking for the output:

>>> arr
array([[ 1.,   1.,  -18.],
   [ -1.,  -1.,  -1.],
   [  1.,   1., -15.],
   [  1.,  -1.,   0.]])

The closest thing I found in the API reference for this is numpy.fmax but it doesn't do the absolute value. If I used:

arr[index_list, :] = np.fmax(arr[index_list, :], new_tuple)

my array would finally look like:

>>> arr
array([[ 1.,   1., -15.],
   [ -1.,  -1.,  -1.],
   [  1.,   1.,   5.],
   [  1.,  -1.,   0.]])

Now, the API says that this function is

equivalent to np.where(x1 >= x2, x1, x2) when neither x1 nor x2 are NaNs, but it is faster and does proper broadcasting

I tried using the following:

arr[index_list, :] = np.where(np.absolute(arr[index_list, :]) >= np.absolute(new_tuple),
                              arr[index_list, :], new_tuple)

Although this produced the desired output, I got the warning:

/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevconsole.py:1: RuntimeWarning: invalid value encountered in greater_equal

I believe this warning is because of the NaN which is not handled gracefully here, unlike the np.fmax function. In addition, the API docs mention that np.fmax is faster and does broadcasting correctly (not sure what part of broadcasting is missing in the np.where version)

In conclusion, what I am looking for is something similar to:

arr[index_list, :] = np.fmax(arr[index_list, :], new_tuple, key=abs)

There is no such key attribute available to this function, unfortunately.

Just for context, I am interested in the fastest possible solution because my actual shape of the arr array is an average of (100000, 50) and I am looping through almost 1000 new_tuple tuples (with each tuple equal in shape to the number of columns in arr, of course). The index_list changes for each new_tuple.

Edit 1:

One possible solution is, to begin with replacing all NaN in arr with 0. i.e. arr[np.isnan(arr)] = 0. After this, I can use the np.where with np.absolute trick mentioned in my original text. However, this is probably a lot slower than np.fmax, as suggested by the API.

Edit 2:

The index_list may have repeated indexes in subsequent loops. Every new_tuple comes with a corresponding rule and the index_list is selected based on that rule. There is nothing stopping different rules from having overlapping indexes that they match to. @Divakar has an excellent answer for the case where index_list has no repeats. Other solutions are however welcome covering both cases.

Body:
Assuming that list of all index_list has no repeated indexes:

Approach #1

I would propose more of a vectorized solution once we have all of index_lists and new_tuples stored in one place, preferably as a list. As such this could be the preferred one, if we are dealing with lots of such tuples and lists.

So, let's say we have them stored as the following :

new_tuples = [(1.0, 1.0, -15.0), (6.0, 3.0, -4.0)] # list of all new_tuple
index_lists =[[0,2],[4,1,6]]  # list of all index_list

The solution thereafter would be to manually repeat, replacing the broadcasting and then use np.where as shown later on in the question. Using np.where on the concern around the said warning, we can ignore, if the new_tuples have non-NaN values. Thus, the solution would be -

idx = np.concatenate(index_lists)
lens = list(map(len,index_lists))

a = arr[idx]
b = np.repeat(new_tuples,lens,axis=0)
arr[idx] = np.where(np.abs(a) > np.abs(b), a, b)

Approach #2

Another approach would be to store the absolute values of arr beforeand : abs_arr = np.abs(arr) and using those within np.where. This should save a lot time within the loop. Thus, the relevant computation would reduce to :

arr[index_list, :] = np.where(abs_arr[index_list, :] > np.abs(b), a, new_tuple)


问:
SQLite update table with entries from a subset of records in another table
I have the following two tables. The 'tracks' table has no artist/track names (thery are all currently NULL). I want to update 'tracks' with the artist_name and track_name from the 'names' table. The 'names' table has 242,416,787 records and the tracks table has about 4 million. The arist/track name is associated by track_id, so I only want entries form 'names' that I have track_ids for.

```<code>CREATE TABLE tracks (
        s3_url VARCHAR(128),
        track_id INTEGER KEY,
        cluster_id INTEGER KEY,
        rank INTEGER KEY,
        group_id VARCHAR(128),
        artist_name VARCHAR(128),
        track_name VARCHAR(128),
        set_name VARCHAR(128),
        file_size INTEGER KEY);

CREATE TABLE names (
        artist_name VARCHAR(128),
        track_name VARCHAR(128),
        track_id INTEGER KEY,
        album_name VARCHAR(128));
</code>```

Here's what I have so far, this gets me the records in 'names' that I have track_ids for:

```<code>SELECT names.artist_name, f.track_id FROM names INNER JOIN tracks AS f ON names.track_id=f.track_id
</code>```

I can't get figure out how to then stuff those results back into the 'tracks' table. I was trying something to the effect of the following:

```<code>UPDATE x SET artist_name=SELECT names.artist_name, f.track_id FROM names INNER JOIN tracks AS f ON names.track_id=f.track_id) AS x;
</code>```

These threads here, and here to accomplish similar things and show that JOIN/UPDATE is not supported in SQLite.

The desired end result is to populate all entries in 'tracks' with artist_name and track_name from 'names'.

答:
Try this:

```<code>replace into tracks
  (rowid, s3_url, track_id, cluster_id, rank, group_id, artist_name, track_name, set_name, file_size)
select
  t.rowid, t.s3_url, t.track_id, t.cluster_id, t.rank, t.group_id, n.artist_name, n.track_name, t.set_name, t.file_size
from names n
inner join tracks t on n.track_id = t.track_id
;
</code>```

Available as a working example here: http://sqlfiddle.com/#!5/573148/1

Body:
I have the following two tables. The 'tracks' table has no artist/track names (thery are all currently NULL). I want to update 'tracks' with the artist_name and track_name from the 'names' table. The 'names' table has 242,416,787 records and the tracks table has about 4 million. The arist/track name is associated by track_id, so I only want entries form 'names' that I have track_ids for.

CREATE TABLE tracks (
        s3_url VARCHAR(128),
        track_id INTEGER KEY,
        cluster_id INTEGER KEY,
        rank INTEGER KEY,
        group_id VARCHAR(128),
        artist_name VARCHAR(128),
        track_name VARCHAR(128),
        set_name VARCHAR(128),
        file_size INTEGER KEY);

CREATE TABLE names (
        artist_name VARCHAR(128),
        track_name VARCHAR(128),
        track_id INTEGER KEY,
        album_name VARCHAR(128));

Here's what I have so far, this gets me the records in 'names' that I have track_ids for:

SELECT names.artist_name, f.track_id FROM names INNER JOIN tracks AS f ON names.track_id=f.track_id

I can't get figure out how to then stuff those results back into the 'tracks' table. I was trying something to the effect of the following:

UPDATE x SET artist_name=SELECT names.artist_name, f.track_id FROM names INNER JOIN tracks AS f ON names.track_id=f.track_id) AS x;

These threads here, and here to accomplish similar things and show that JOIN/UPDATE is not supported in SQLite.

The desired end result is to populate all entries in 'tracks' with artist_name and track_name from 'names'.

Body:
Try this:

replace into tracks
  (rowid, s3_url, track_id, cluster_id, rank, group_id, artist_name, track_name, set_name, file_size)
select
  t.rowid, t.s3_url, t.track_id, t.cluster_id, t.rank, t.group_id, n.artist_name, n.track_name, t.set_name, t.file_size
from names n
inner join tracks t on n.track_id = t.track_id
;

Available as a working example here: http://sqlfiddle.com/#!5/573148/1


问:
How to set dropdown arrow in spinner?
I tried to set spinner with drop down arrow but i couldn't fix it can anyone help me with this? I have attached the source code.

my class file:

```<code>    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Spinner;
    import android.widget.AdapterView.OnItemSelectedListener;
    import android.widget.Toast;

        public class topup extends Activity  {
            Spinner spinner,spin1,spin2,spin3;
                EditText ed,ed1;
                Button btn;
                List<String> list, list1,list2,list3;
                    private String[] countries_list={"01","02","03","04","05","06","07","08","09","10","11","12"};

                    protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.topup);

                        spinner = (Spinner) findViewById(R.id.spinner1);
                        spin1= (Spinner) findViewById(R.id.spinner2);
                        spin2= (Spinner) findViewById(R.id.spinner3);
                        spin3= (Spinner) findViewById(R.id.spinner4);
                        ed = (EditText) findViewById(R.id.editText3);

                        list = new ArrayList<String>();
                        list.add("");
                        list.add("select");
                        list.add("01");
                        list.add("02");
                        list.add("03");
                        list.add("04");
                        list.add("05");
                        list.add("06");
                        list.add("07");
                        list.add("08");
                        list.add("09");
                        list.add("10");
                        list.add("11");
                        list.add("12");

                        ArrayAdapter<String> adp = new ArrayAdapter<String>
                            (this, android.R.layout.simple_spinner_item, list);
                        //adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

                        spinner.setAdapter(adp);

                        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

                            //@Override
                            public void onItemSelected(AdapterView<?> parent, View arg1,int arg2, long arg3) {
                                // TODO Auto-generated method stub
                                 String item = spinner.getItemAtPosition(1).toString();
                                 //Toast.makeText(spinner.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
                                 String ss=spinner.getSelectedItem().toString();
                                 String
                            }

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

                            }
                        });
</code>```

my xml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/back1"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="wrap_content"
        android:layout_height="55dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="20dp"
        android:background="@drawable/red">

        <Spinner
            android:id="@+id/spinner1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:dropDownWidth="fill_parent"
         />

    </LinearLayout>

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="55dp"
        android:layout_alignLeft="@+id/linearLayout1"
        android:layout_alignRight="@+id/linearLayout1"
        android:layout_below="@+id/linearLayout1"
        android:layout_marginTop="25dp"
        android:background="@drawable/red"
        android:ems="10"
        android:hint="enter card number" >

        <requestFocus />
    </EditText>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="wrap_content"
        android:layout_height="55dp"
        android:layout_alignLeft="@+id/editText1"
        android:layout_alignRight="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="33dp"
        android:orientation="horizontal"
        android:background="@drawable/red">

        <Spinner
            android:id="@+id/spinner3"
            android:layout_width="72dp"
            android:layout_height="wrap_content"
             />

        <Spinner
            android:id="@+id/spinner2"
            android:layout_width="72dp"
            android:layout_height="wrap_content"
            />

        <EditText
            android:id="@+id/editText2"
            android:layout_width="22dp"
            android:layout_height="match_parent"
            android:layout_weight="0.18"
            android:ems="10"
            android:hint="enter cvv" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout3"
        android:layout_width="wrap_content"
        android:layout_height="55dp"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/linearLayout2"
        android:layout_below="@+id/linearLayout2"
        android:layout_marginTop="26dp"
        android:orientation="vertical"
        android:background="@drawable/red" >
    </LinearLayout>

    <Spinner
        android:id="@+id/spinner4"
        android:layout_width="15dp"
        android:layout_height="18dp"
        android:layout_alignBottom="@+id/linearLayout3"
        android:layout_alignLeft="@+id/linearLayout3"
        android:layout_alignRight="@+id/linearLayout3"
        android:layout_alignTop="@+id/linearLayout3"

      />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/linearLayout3"
        android:layout_marginTop="18dp"
        android:text="Add Amount"
        android:background="@drawable/buttonsty"/>

</RelativeLayout>
</code>```

答:
Attach a Spinner Style using Java Code:

First, you need to a layout file such as below:

```<code><?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="?android:attr/spinnerDropDownItemStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="none"
android:minHeight="?android:attr/listPreferredItemHeight" />
</code>```

Let us name it spinner_item.xml and place it inside res/layouts folder.

Next, Create a String ArrayList and put all the Spinner options inside it:

```<code>ArrayList<String> spinnerArray = new ArrayList<String>();
spinnerArray.add("Item No. 1");
spinnerArray.add("Item No. 2");
spinnerArray.add("Item No. 3");
spinnerArray.add("Item No. 4");
</code>```

Finally, create the Spinner object and attach the style layout to it.

```<code>Spinner spinner = new Spinner(getActivity());
spinner.setTag("some_id");
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, spinnerArray);                  spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item);
spinner.setAdapter(spinnerArrayAdapter);
</code>```

Note the Spinner(getActivity()) in the above line will be changed to Spinner(this) if you are writing this from inside Activity rather than from inside a fragment.

Thats all!

Attach a Spinner Style inside Android Layout File:

First, create a  xml file the defines the style attribute (gradient_spinner.xml)

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item><layer-list>
        <item><shape>
            <gradient android:angle="90"  android:type="linear" />

            <stroke android:width="1dp" android:color="@color/colorBackground" />

            <corners android:radius="2dp" />

            <padding android:bottom="1dp" android:left="1dp" android:right="1dp" android:top="1dp" />
        </shape></item>
        <item android:right="5dp">
            <bitmap android:gravity="center_horizontal|right" android:src="@drawable/expand_icon">
            <padding android:right="2dp" />
        </bitmap>
        </item>
    </layer-list></item>

</selector>
</code>```

Next, inside the style.xml file specify the style and call the gradient_spinner as background

```<code><style name="spinner_style">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:background">@drawable/gradient_spinner</item>
<item name="android:layout_margin">1dp</item>
<item name="android:paddingLeft">5dp</item>
<item name="android:paddingRight">5dp</item>
<item name="android:paddingTop">5dp</item>
<item name="android:paddingBottom">5dp</item>
</style>
</code>```

Finally, attach the above style to the Spinner:

```<code><Spinner
   android:id="@+id/agent_id_spinner"
   android:layout_width="match_parent"
   android:layout_height="40dp"
   android:textSize="@dimen/title_text_view"
   style="@style/spinner_style"  />
</code>```

Thats it!

ContentLicense: CC BY-SA 4.0

Title: How to set dropdown arrow in spinner?

Body:
I tried to set spinner with drop down arrow but i couldn't fix it can anyone help me with this? I have attached the source code.

my class file:

    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Spinner;
    import android.widget.AdapterView.OnItemSelectedListener;
    import android.widget.Toast;

        public class topup extends Activity  {
            Spinner spinner,spin1,spin2,spin3;
                EditText ed,ed1;
                Button btn;
                List<String> list, list1,list2,list3;
                    private String[] countries_list={"01","02","03","04","05","06","07","08","09","10","11","12"};

                    protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.topup);

                        spinner = (Spinner) findViewById(R.id.spinner1);
                        spin1= (Spinner) findViewById(R.id.spinner2);
                        spin2= (Spinner) findViewById(R.id.spinner3);
                        spin3= (Spinner) findViewById(R.id.spinner4);
                        ed = (EditText) findViewById(R.id.editText3);

                        list = new ArrayList<String>();
                        list.add("");
                        list.add("select");
                        list.add("01");
                        list.add("02");
                        list.add("03");
                        list.add("04");
                        list.add("05");
                        list.add("06");
                        list.add("07");
                        list.add("08");
                        list.add("09");
                        list.add("10");
                        list.add("11");
                        list.add("12");

                        ArrayAdapter<String> adp = new ArrayAdapter<String>
                            (this, android.R.layout.simple_spinner_item, list);
                        //adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

                        spinner.setAdapter(adp);

                        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

                            //@Override
                            public void onItemSelected(AdapterView<?> parent, View arg1,int arg2, long arg3) {
                                // TODO Auto-generated method stub
                                 String item = spinner.getItemAtPosition(1).toString();
                                 //Toast.makeText(spinner.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
                                 String ss=spinner.getSelectedItem().toString();
                                 String
                            }

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

                            }
                        });

my xml file:

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/back1"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="wrap_content"
        android:layout_height="55dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="20dp"
        android:background="@drawable/red">

        <Spinner
            android:id="@+id/spinner1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:dropDownWidth="fill_parent"
         />

    </LinearLayout>

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="55dp"
        android:layout_alignLeft="@+id/linearLayout1"
        android:layout_alignRight="@+id/linearLayout1"
        android:layout_below="@+id/linearLayout1"
        android:layout_marginTop="25dp"
        android:background="@drawable/red"
        android:ems="10"
        android:hint="enter card number" >

        <requestFocus />
    </EditText>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="wrap_content"
        android:layout_height="55dp"
        android:layout_alignLeft="@+id/editText1"
        android:layout_alignRight="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="33dp"
        android:orientation="horizontal"
        android:background="@drawable/red">

        <Spinner
            android:id="@+id/spinner3"
            android:layout_width="72dp"
            android:layout_height="wrap_content"
             />

        <Spinner
            android:id="@+id/spinner2"
            android:layout_width="72dp"
            android:layout_height="wrap_content"
            />

        <EditText
            android:id="@+id/editText2"
            android:layout_width="22dp"
            android:layout_height="match_parent"
            android:layout_weight="0.18"
            android:ems="10"
            android:hint="enter cvv" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout3"
        android:layout_width="wrap_content"
        android:layout_height="55dp"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/linearLayout2"
        android:layout_below="@+id/linearLayout2"
        android:layout_marginTop="26dp"
        android:orientation="vertical"
        android:background="@drawable/red" >
    </LinearLayout>

    <Spinner
        android:id="@+id/spinner4"
        android:layout_width="15dp"
        android:layout_height="18dp"
        android:layout_alignBottom="@+id/linearLayout3"
        android:layout_alignLeft="@+id/linearLayout3"
        android:layout_alignRight="@+id/linearLayout3"
        android:layout_alignTop="@+id/linearLayout3"

      />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/linearLayout3"
        android:layout_marginTop="18dp"
        android:text="Add Amount"
        android:background="@drawable/buttonsty"/>

</RelativeLayout>

Body:
Attach a Spinner Style using Java Code:

First, you need to a layout file such as below:

<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="?android:attr/spinnerDropDownItemStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="none"
android:minHeight="?android:attr/listPreferredItemHeight" />

Let us name it spinner_item.xml and place it inside res/layouts folder.

Next, Create a String ArrayList and put all the Spinner options inside it:

ArrayList<String> spinnerArray = new ArrayList<String>();
spinnerArray.add("Item No. 1");
spinnerArray.add("Item No. 2");
spinnerArray.add("Item No. 3");
spinnerArray.add("Item No. 4");

Finally, create the Spinner object and attach the style layout to it.

Spinner spinner = new Spinner(getActivity());
spinner.setTag("some_id");
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, spinnerArray);                  spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item);
spinner.setAdapter(spinnerArrayAdapter);

Note the Spinner(getActivity()) in the above line will be changed to Spinner(this) if you are writing this from inside Activity rather than from inside a fragment.

Thats all!

Attach a Spinner Style inside Android Layout File:

First, create a  xml file the defines the style attribute (gradient_spinner.xml)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item><layer-list>
        <item><shape>
            <gradient android:angle="90"  android:type="linear" />

            <stroke android:width="1dp" android:color="@color/colorBackground" />

            <corners android:radius="2dp" />

            <padding android:bottom="1dp" android:left="1dp" android:right="1dp" android:top="1dp" />
        </shape></item>
        <item android:right="5dp">
            <bitmap android:gravity="center_horizontal|right" android:src="@drawable/expand_icon">
            <padding android:right="2dp" />
        </bitmap>
        </item>
    </layer-list></item>

</selector>

Next, inside the style.xml file specify the style and call the gradient_spinner as background

<style name="spinner_style">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:background">@drawable/gradient_spinner</item>
<item name="android:layout_margin">1dp</item>
<item name="android:paddingLeft">5dp</item>
<item name="android:paddingRight">5dp</item>
<item name="android:paddingTop">5dp</item>
<item name="android:paddingBottom">5dp</item>
</style>

Finally, attach the above style to the Spinner:

<Spinner
   android:id="@+id/agent_id_spinner"
   android:layout_width="match_parent"
   android:layout_height="40dp"
   android:textSize="@dimen/title_text_view"
   style="@style/spinner_style"  />

Thats it!


问:
How to perform OrderBy followed by OrderByDescending?
I have a collection where I am trying to sort the records first by Quarter and then inside the quarter by highest amounts. My code so far is:

```<code>using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Test> lstTest = new List<Test>();
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 2), amount = 2500 });
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 2), amount = 10000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 5), amount = 4000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 10), amount = 40000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 15), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 25), amount = 12000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 2, 5), amount = 38000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 2, 10), amount = 38000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 2, 15), amount = 4000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 2, 20), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 2, 20), amount = 20000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 3, 15), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 3, 20), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 3, 20), amount = 4000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 3, 31), amount = 1000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 4, 9), amount = 50000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 4, 11), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 4, 21), amount = 1000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 4, 21), amount = 10000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 4, 28), amount = 5000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 5, 5), amount = 45000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 5, 7), amount = 98000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 5, 9), amount = 7000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 5, 25), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 5, 31), amount = 1000 });

            var result = lstTest.Select(x => new
            {
                Amount = x.amount,
                Date = x.dt,
                MonthDiff = GetMonthsDiff(DateTime.Now, x.dt),
                Quater = GetQuarter(DateTime.Now, x.dt)
            }).OrderBy(o=>o.Quater).ToList();

            foreach (var res in result)
            {
                Console.WriteLine("Amount = {0}  Date= {1} MonthDiff= {2}  Quater= {3}", res.Amount, res.Date, res.MonthDiff, res.Quater);
            }
            Console.ReadKey();
        }

        public static string GetQuarter(DateTime start, DateTime end)// int month)
        {
            int month = GetMonthsDiff(start, end);
            string quarter =  month <= 3 ? "Q1" : (month >= 4 && month <= 6) ? "Q2" : (month >= 7 && month <= 9) ? "Q3" : "Q4";
            return quarter;
        }

        public static int GetMonthsDiff(DateTime start, DateTime end)
        {
            if (start > end)
                return GetMonthsDiff(end, start);

            int months = 0;
            do
            {
                start = start.AddMonths(1);
                if (start > end)
                    return months;

                months++;
            }
            while (true);
        }
    }

    public class Test
    {
        public DateTime dt { get; set; }
        public int amount { get; set; }
    }
}
</code>```

The output is

If I do OrderBy(o=>o.Quater).OrderByDescending(o=>o.Amount) the output changes to

That is it is first sorting by Quarter and then by Amount.

But I am looking for first sort by Quarter and within the Quarter sort by Amount descending.

The desired output is

What needs to be modified in the program so as achieve the target?

答:
You don't need to sort by a single property only. You can return the sort fields as <s>an anonymous object</s> tuple.

In C# 7 you can write :

```<code>OrderBy(o => (o.Quarter,o.Amount));
</code>```

In previous versions :

```<code>OrderBy(o => Tuple.Create(o.Quarter,o.Amount));
</code>```

If you want to use different sort orders you have to specify the fields one at a time, eg:

```<code>OrderBy(o=>o.Quarter).ThenByDescending(o=>o.Amount);
</code>```

Or you can use query syntax to make the code cleaner:

```<code>var result = ( from x in lstTest
               let o = new {
                            Amount = x.amount,
                            Date = x.dt,
                            MonthDiff = GetMonthsDiff(DateTime.Now, x.dt),
                            Quarter = GetQuarter(DateTime.Now, x.dt)
                          }
               orderby o.Quarter, o.Amount descending
               select o
             ).ToList()
</code>```

Body:
I have a collection where I am trying to sort the records first by Quarter and then inside the quarter by highest amounts. My code so far is:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Test> lstTest = new List<Test>();
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 2), amount = 2500 });
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 2), amount = 10000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 5), amount = 4000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 10), amount = 40000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 15), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 25), amount = 12000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 2, 5), amount = 38000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 2, 10), amount = 38000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 2, 15), amount = 4000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 2, 20), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 2, 20), amount = 20000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 3, 15), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 3, 20), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 3, 20), amount = 4000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 3, 31), amount = 1000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 4, 9), amount = 50000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 4, 11), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 4, 21), amount = 1000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 4, 21), amount = 10000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 4, 28), amount = 5000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 5, 5), amount = 45000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 5, 7), amount = 98000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 5, 9), amount = 7000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 5, 25), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 5, 31), amount = 1000 });

            var result = lstTest.Select(x => new
            {
                Amount = x.amount,
                Date = x.dt,
                MonthDiff = GetMonthsDiff(DateTime.Now, x.dt),
                Quater = GetQuarter(DateTime.Now, x.dt)
            }).OrderBy(o=>o.Quater).ToList();

            foreach (var res in result)
            {
                Console.WriteLine("Amount = {0}  Date= {1} MonthDiff= {2}  Quater= {3}", res.Amount, res.Date, res.MonthDiff, res.Quater);
            }
            Console.ReadKey();
        }

        public static string GetQuarter(DateTime start, DateTime end)// int month)
        {
            int month = GetMonthsDiff(start, end);
            string quarter =  month <= 3 ? "Q1" : (month >= 4 && month <= 6) ? "Q2" : (month >= 7 && month <= 9) ? "Q3" : "Q4";
            return quarter;
        }

        public static int GetMonthsDiff(DateTime start, DateTime end)
        {
            if (start > end)
                return GetMonthsDiff(end, start);

            int months = 0;
            do
            {
                start = start.AddMonths(1);
                if (start > end)
                    return months;

                months++;
            }
            while (true);
        }
    }

    public class Test
    {
        public DateTime dt { get; set; }
        public int amount { get; set; }
    }
}

The output is

If I do OrderBy(o=>o.Quater).OrderByDescending(o=>o.Amount) the output changes to

That is it is first sorting by Quarter and then by Amount.

But I am looking for first sort by Quarter and within the Quarter sort by Amount descending.

The desired output is

What needs to be modified in the program so as achieve the target?

Body:
You don't need to sort by a single property only. You can return the sort fields as <s>an anonymous object</s> tuple.

In C# 7 you can write :

OrderBy(o => (o.Quarter,o.Amount));

In previous versions :

OrderBy(o => Tuple.Create(o.Quarter,o.Amount));

If you want to use different sort orders you have to specify the fields one at a time, eg:

OrderBy(o=>o.Quarter).ThenByDescending(o=>o.Amount);

Or you can use query syntax to make the code cleaner:

var result = ( from x in lstTest
               let o = new {
                            Amount = x.amount,
                            Date = x.dt,
                            MonthDiff = GetMonthsDiff(DateTime.Now, x.dt),
                            Quarter = GetQuarter(DateTime.Now, x.dt)
                          }
               orderby o.Quarter, o.Amount descending
               select o
             ).ToList()


问:
hide menu even when click outside or anywhere on webpage
This is my menubar code. it works fine. But, I want to implement one thing that at present, when I click outside of the menubar it does not hide or close.
I want to hide the menubar even when I click anywhere on the webpage when menu bar active.

function openNav() {
    document.getElementById("mySidenav").style.width = "50%";
}
function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
}
(function ($) {
    // Instantiate MixItUp:
    // $('Container').mixItUp();
    // Add smooth scrolling to all links in navbar + footer link
    $(".sidenav a").on('click', function(event) {
        event.preventDefault();
        var datanew= this.href;
        var str2 = '.html';
        if(datanew.indexOf(str2) != -1){
            window.location.href = datanew;
        }else{
            var hash = this.hash;
            $('html, body').animate({scrollTop: $(hash).offset().top},
            900, function(){
                alert(window.location);
                window.location.hash = hash;
            });
        }
    });
})(jQuery);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.sidenav {
    height: 100%;
    width: 0;
    position: absolute;
    z-index: 1;
    top: 0;
    right: 0;
    background-color: #ef4f50;
    overflow-x: hidden;
    padding-top: 60px;
    transition: 0.5s;
    /*max-height: 551px;*/
}
.sidenav a {
    padding: 8px 8px 8px 32px;
    text-decoration: none;
    font-size: 25px;
    color: #ffffff;
    display: block;
    transition: 0.3s
}
.sidenav a:hover, .offcanvas a:focus{
    color: #f1f1f1;
}
.closebtn {
    position: absolute;
    top: 0;
    right: 25px;
    font-size: 36px !important;
    margin-left: 50px;
}
.menu-icon
{
    color: #114576;
    font-size: 30px;
    margin-top: 40px;
    margin-left: 40px;
    cursor: pointer;
}
.control {
    margin-top: 15px;
    margin-right: 40px;
}

.menu{
    min-height: 100px;
}</code>```

                    ×
                    Home
                    About Us
                    What We Do
                    Get Involved
                    Contact Us

                        ☰
                        <button type="button" class="pull-right btn btn-danger btn-round donate">DONATE NOW</button>

                ```

答:
Try use something like

```<code>$(window).click(function(event) {
  if ($(event.target).closest('div#mySidenav').length === 0 && $(event.target).closest('.menu-icon').length === 0) {
    closeNav()
  }
})
</code>```

This will check if you click on your "openNav" or anywhere in the menu

function openNav() {
  document.getElementById("mySidenav").style.width = "50%";
}

function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
}
(function($) {
  // Instantiate MixItUp:
  // $('Container').mixItUp();
  // Add smooth scrolling to all links in navbar + footer link
  $(".sidenav a").on('click', function(event) {
    event.preventDefault();
    var datanew = this.href;
    var str2 = '.html';
    if (datanew.indexOf(str2) != -1) {
      window.location.href = datanew;
    } else {
      var hash = this.hash;
      $('html, body').animate({
          scrollTop: $(hash).offset().top
        },
        900,
        function() {
          alert(window.location);
          window.location.hash = hash;
        });
    }
  });
})(jQuery);

$(window).click(function(event) {
  if ($(event.target).closest('div#mySidenav').length === 0 && $(event.target).closest('.menu-icon').length === 0) {
    closeNav()
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.sidenav {
  height: 100%;
  width: 0;
  position: absolute;
  z-index: 1;
  top: 0;
  right: 0;
  background-color: #ef4f50;
  overflow-x: hidden;
  padding-top: 60px;
  transition: 0.5s;
  /*max-height: 551px;*/
}

.sidenav a {
  padding: 8px 8px 8px 32px;
  text-decoration: none;
  font-size: 25px;
  color: #ffffff;
  display: block;
  transition: 0.3s
}

.sidenav a:hover,
.offcanvas a:focus {
  color: #f1f1f1;
}

.closebtn {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px !important;
  margin-left: 50px;
}

.menu-icon {
  color: #114576;
  font-size: 30px;
  margin-top: 40px;
  margin-left: 40px;
  cursor: pointer;
}

.control {
  margin-top: 15px;
  margin-right: 40px;
}

.menu {
  min-height: 100px;
}</code>```

    ×
    Home
    About Us
    What We Do
    Get Involved
    Contact Us

      ☰
      <button type="button" class="pull-right btn btn-danger btn-round donate">DONATE NOW</button>

```

Body:
This is my menubar code. it works fine. But, I want to implement one thing that at present, when I click outside of the menubar it does not hide or close.
I want to hide the menubar even when I click anywhere on the webpage when menu bar active.

function openNav() {
    document.getElementById("mySidenav").style.width = "50%";
}
function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
}
(function ($) {
    // Instantiate MixItUp:
    // $('Container').mixItUp();
    // Add smooth scrolling to all links in navbar + footer link
    $(".sidenav a").on('click', function(event) {
        event.preventDefault();
        var datanew= this.href;
        var str2 = '.html';
        if(datanew.indexOf(str2) != -1){
            window.location.href = datanew;
        }else{
            var hash = this.hash;
            $('html, body').animate({scrollTop: $(hash).offset().top},
            900, function(){
                alert(window.location);
                window.location.hash = hash;
            });
        }
    });
})(jQuery);

.sidenav {
    height: 100%;
    width: 0;
    position: absolute;
    z-index: 1;
    top: 0;
    right: 0;
    background-color: #ef4f50;
    overflow-x: hidden;
    padding-top: 60px;
    transition: 0.5s;
    /*max-height: 551px;*/
}
.sidenav a {
    padding: 8px 8px 8px 32px;
    text-decoration: none;
    font-size: 25px;
    color: #ffffff;
    display: block;
    transition: 0.3s
}
.sidenav a:hover, .offcanvas a:focus{
    color: #f1f1f1;
}
.closebtn {
    position: absolute;
    top: 0;
    right: 25px;
    font-size: 36px !important;
    margin-left: 50px;
}
.menu-icon
{
    color: #114576;
    font-size: 30px;
    margin-top: 40px;
    margin-left: 40px;
    cursor: pointer;
}
.control {
    margin-top: 15px;
    margin-right: 40px;
}

.menu{
    min-height: 100px;
}

                    ×
                    Home
                    About Us
                    What We Do
                    Get Involved
                    Contact Us

                        ☰
                        <button type="button" class="pull-right btn btn-danger btn-round donate">DONATE NOW</button>

Body:
Try use something like

$(window).click(function(event) {
  if ($(event.target).closest('div#mySidenav').length === 0 && $(event.target).closest('.menu-icon').length === 0) {
    closeNav()
  }
})

This will check if you click on your "openNav" or anywhere in the menu

function openNav() {
  document.getElementById("mySidenav").style.width = "50%";
}

function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
}
(function($) {
  // Instantiate MixItUp:
  // $('Container').mixItUp();
  // Add smooth scrolling to all links in navbar + footer link
  $(".sidenav a").on('click', function(event) {
    event.preventDefault();
    var datanew = this.href;
    var str2 = '.html';
    if (datanew.indexOf(str2) != -1) {
      window.location.href = datanew;
    } else {
      var hash = this.hash;
      $('html, body').animate({
          scrollTop: $(hash).offset().top
        },
        900,
        function() {
          alert(window.location);
          window.location.hash = hash;
        });
    }
  });
})(jQuery);

$(window).click(function(event) {
  if ($(event.target).closest('div#mySidenav').length === 0 && $(event.target).closest('.menu-icon').length === 0) {
    closeNav()
  }
})

.sidenav {
  height: 100%;
  width: 0;
  position: absolute;
  z-index: 1;
  top: 0;
  right: 0;
  background-color: #ef4f50;
  overflow-x: hidden;
  padding-top: 60px;
  transition: 0.5s;
  /*max-height: 551px;*/
}

.sidenav a {
  padding: 8px 8px 8px 32px;
  text-decoration: none;
  font-size: 25px;
  color: #ffffff;
  display: block;
  transition: 0.3s
}

.sidenav a:hover,
.offcanvas a:focus {
  color: #f1f1f1;
}

.closebtn {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px !important;
  margin-left: 50px;
}

.menu-icon {
  color: #114576;
  font-size: 30px;
  margin-top: 40px;
  margin-left: 40px;
  cursor: pointer;
}

.control {
  margin-top: 15px;
  margin-right: 40px;
}

.menu {
  min-height: 100px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header id="header">
  <div id="mySidenav" class="sidenav">
    <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
    <a href="index.html" class="sidenavtext">Home</a>
    <a href="about.html" class="sidenavtext">About Us</a>
    <a href="whatwedo.html" class="sidenavtext">What We Do</a>
    <a href="getinvolved.html" class="sidenavtext">Get Involved</a>
    <a href="contactus.php" class="sidenavtext">Contact Us</a>
  </div>

  <div class="control">
    <div class="col-md-4">
      <img src="assets/img/logohome.png" class="pull-left img-responsive logo" alt="SAF Logo">
    </div>
    <div class="col-md-8">
      <!-- Use any element to open the sidenav -->
      <span onclick="openNav()" class="pull-right menu-icon">☰</span>
      <button type="button" class="pull-right btn btn-danger btn-round donate">DONATE NOW</button>
    </div>
  </div>
</header>


问:
SwipeRefreshLayout with Webview not working
This is my webview app code with SwipeRefreshLayout. But SwipeRefresh not working please check it. But all other things are working correctly. Like webview, menu button.

Below is my activity_main.xml file

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

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:id="@+id/webView"
        />
    </android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
</code>```

And this is my MainActivity.java file

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

    WebView webView;
    SwipeRefreshLayout swipe;

    @Override
    public boolean onCreateOptionsMenu (Menu manu){
        getMenuInflater().inflate(R.menu.main, manu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected (MenuItem item){
        int id=item.getItemId();
        if(id==R.id.id_about){
            Intent intentabout=new Intent(MainActivity.this, About.class);
            startActivity(intentabout);

            return true;
        }
        if(id==R.id.id_terms){

            return true;
        }
        if(id==R.id.id_privacy){

            return true;
        }
        return true;
    }

    @Override
    public void onBackPressed() {
        if(webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }

    }

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

        swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                LoadWeb();
            }
        });

        LoadWeb();

    }

    public void LoadWeb(){
        webView = (WebView) findViewById(R.id.webView);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webView.loadUrl("https://google.com");
        swipe.setRefreshing(true);
        webView.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                webView.loadUrl("file:///android_asset/error.html");

            }

            public void onPagefinished(WebView view, String url){
                swipe.setRefreshing(false);
            }
        });
    }

}
</code>```

答:
you can put your Webview inside a NestedScrollView to make this work.

Example:

```<code><android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">

<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

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

Body:
This is my webview app code with SwipeRefreshLayout. But SwipeRefresh not working please check it. But all other things are working correctly. Like webview, menu button.

Below is my activity_main.xml file

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

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:id="@+id/webView"
        />
    </android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>

And this is my MainActivity.java file

    public class MainActivity extends AppCompatActivity {

    WebView webView;
    SwipeRefreshLayout swipe;

    @Override
    public boolean onCreateOptionsMenu (Menu manu){
        getMenuInflater().inflate(R.menu.main, manu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected (MenuItem item){
        int id=item.getItemId();
        if(id==R.id.id_about){
            Intent intentabout=new Intent(MainActivity.this, About.class);
            startActivity(intentabout);

            return true;
        }
        if(id==R.id.id_terms){

            return true;
        }
        if(id==R.id.id_privacy){

            return true;
        }
        return true;
    }

    @Override
    public void onBackPressed() {
        if(webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }

    }

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

        swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                LoadWeb();
            }
        });

        LoadWeb();

    }

    public void LoadWeb(){
        webView = (WebView) findViewById(R.id.webView);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webView.loadUrl("https://google.com");
        swipe.setRefreshing(true);
        webView.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                webView.loadUrl("file:///android_asset/error.html");

            }

            public void onPagefinished(WebView view, String url){
                swipe.setRefreshing(false);
            }
        });
    }

}

Body:
you can put your Webview inside a NestedScrollView to make this work.

Example:

<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">

<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

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


问:
Deploying SQL CE 4 to IIS 7 - Special Permissions Needed?
I have an ASP.NET 4 site that uses the new SQL CE 4 CTP. The site works fine locally (IIS 7.5 on Win7) and fine in Server 2003/IIS 6. It fails when deploying to IIS 7 on Server 2008. The error I get is:

Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

The interesting thing is if I switch the app pool user from its default user to LocalSystem, everything works great. So clearly there is a permissions problem somewhere.

Long story short, does anyone know what special permissions need to be set when deploying a SQL CE 4 database? (BTW, we have already set r/w access on the db itself and on c:\windows\temp)

Thanks!

答: Write access to the folder where the database files resides. You can use Process Explorer to determine what permissions are missing.</p>

ContentLicense: CC BY-SA 2.5


问:
iOS Navigating to New View on Table Cell Click using a Segue
Upon clicking a table cell I would like to navigate to a new page using a segue. However whenever I click the cell nothing happens.

When I place a breakpoint on the PrepareForSegue method it is never hit when I click a cell on the DayTableView.

Main.storyboard

DayTableViewController

```<code>namespace HHGoals2
{
    public partial class DayTableViewController : UITableViewController
    {
        HHGoals2DataService dataService = new HHGoals2DataService();

        public DayTableViewController(IntPtr handle) : base (handle)
        {
        }

        public override void ViewDidLoad()
        {
            var allDays = dataService.GetAllDays();
            var dataSource = new GoalsDataSource(allDays, this);

            TableView.Source = dataSource;

            this.NavigationItem.Title = "Completed Goals";
        }

        public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender)
        {
            base.PrepareForSegue(segue, sender);

            if(segue.Identifier == "GoalDetailSegue")
            {
                var goalDetailViewController = segue.DestinationViewController
                                                    as GoalDetailViewController;
                if(goalDetailViewController != null)
                {
                    var source = TableView.Source as GoalsDataSource;
                    var rowPath = TableView.IndexPathForSelectedRow;
                    var item = source.GetItem(rowPath.Row);
                    goalDetailViewController.SelectedDay = item;
                }

            }
        }
    }
}
</code>```

GoalsDataSource

```<code>using System;
using Foundation;
using UIKit;
using System.Collections.Generic;
using HHGoals2.Core.Model;
using HHGoals2.Cells;

namespace HHGoals2.DataSources
{
    public class GoalsDataSource: UITableViewSource
    {
        private List<Day> allDays;
        NSString cellIdentifier = new NSString("DayCell");
        DayTableViewController callingController;

        public GoalsDataSource(List<Day> allDays, DayTableViewController callingController)
        {
            this.allDays = allDays;
            this.callingController = callingController;
        }

        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
            DayListCell cell = tableView.DequeueReusableCell(cellIdentifier) as DayListCell;

            if (cell == null)
            {
                cell = new DayListCell(cellIdentifier);
            }

            cell.UpdateCell(allDays[indexPath.Row].Number.ToString(),
                            allDays[indexPath.Row].SuccessRate.ToString(),
                            allDays[indexPath.Row].FailRate.ToString());

            return cell;
        }

        public override nint RowsInSection(UITableView tableview, nint section)
        {
            return allDays.Count;
        }

        public Day GetItem(int id)
        {
            return allDays[id];
        }

    }
}
</code>```

Do I need to add a TouchUpInside event of the DayCell? Any suggestions on how to get this to work would be great.

答: I think you just missed out to connect the delegate and datasource to tableview in uitableviewcontroller. So connect it and it will work fine.</p>

Body:
Upon clicking a table cell I would like to navigate to a new page using a segue. However whenever I click the cell nothing happens.

When I place a breakpoint on the PrepareForSegue method it is never hit when I click a cell on the DayTableView.

Main.storyboard

DayTableViewController

namespace HHGoals2
{
    public partial class DayTableViewController : UITableViewController
    {
        HHGoals2DataService dataService = new HHGoals2DataService();

        public DayTableViewController(IntPtr handle) : base (handle)
        {
        }

        public override void ViewDidLoad()
        {
            var allDays = dataService.GetAllDays();
            var dataSource = new GoalsDataSource(allDays, this);

            TableView.Source = dataSource;

            this.NavigationItem.Title = "Completed Goals";
        }

        public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender)
        {
            base.PrepareForSegue(segue, sender);

            if(segue.Identifier == "GoalDetailSegue")
            {
                var goalDetailViewController = segue.DestinationViewController
                                                    as GoalDetailViewController;
                if(goalDetailViewController != null)
                {
                    var source = TableView.Source as GoalsDataSource;
                    var rowPath = TableView.IndexPathForSelectedRow;
                    var item = source.GetItem(rowPath.Row);
                    goalDetailViewController.SelectedDay = item;
                }

            }
        }
    }
}

GoalsDataSource

using System;
using Foundation;
using UIKit;
using System.Collections.Generic;
using HHGoals2.Core.Model;
using HHGoals2.Cells;

namespace HHGoals2.DataSources
{
    public class GoalsDataSource: UITableViewSource
    {
        private List<Day> allDays;
        NSString cellIdentifier = new NSString("DayCell");
        DayTableViewController callingController;

        public GoalsDataSource(List<Day> allDays, DayTableViewController callingController)
        {
            this.allDays = allDays;
            this.callingController = callingController;
        }

        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
            DayListCell cell = tableView.DequeueReusableCell(cellIdentifier) as DayListCell;

            if (cell == null)
            {
                cell = new DayListCell(cellIdentifier);
            }

            cell.UpdateCell(allDays[indexPath.Row].Number.ToString(),
                            allDays[indexPath.Row].SuccessRate.ToString(),
                            allDays[indexPath.Row].FailRate.ToString());

            return cell;
        }

        public override nint RowsInSection(UITableView tableview, nint section)
        {
            return allDays.Count;
        }

        public Day GetItem(int id)
        {
            return allDays[id];
        }

    }
}

Do I need to add a TouchUpInside event of the DayCell? Any suggestions on how to get this to work would be great.


问:
isEvenSubset did not return 1
Here is the Question: An integer is defined to be an even subset of another integer n if every even factor of m is also a factor of n. For example 18 is an even subset of 12 because the even factors of 18 are 2 and 6 and these are both factors of 12. But 18 is not an even subset of 32 because 6 is not a factor of 32.

This is a University's sample question; the question, explicitly, states: No additional data structures including arrays allowed - therefore, please consider that too while providing answer. Thank you.

Here is my answer code:

```<code>public class IsEvenSubset {
    public static void main(String[] args) {
        System.out.println(isEvenSubset(18,12));
    }
    private static int isEvenSubset(int m, int n){
        for(int i=2;i<=m;i++){
            int count=0;//reset count in each round
            if(m%2==0 && m%i==0){
                for(int j=2;j<=n;j++){
                    if(n%2==0 && n%j==0){
                        if(i==j)count++;
                    }
                }
                if(count==0)return 0;
            }
        }
        return 1;
    }
}
</code>```

This code didn't work as desired. Please help me figure out where did I do wrong?

答:
You are checking whether m and n are even instead of whether their factors are even. Besides, the inner loop is not needed, just find all the even factors of the first number and check whether all of them are also factors of the second number.

```<code>private static boolean isEvenSubset (int m, int n)
{
    for(int i = 2; i < m; i++){ // note that I don't consider m itself to be a factor of m
        if (i % 2 == 0 && m % i == 0 && n %i != 0){ // i is an even factor of m but
                                                    // not a factor of n, so return false
            return false;
        }
    }
    return true; // all the even factors of m were also factors of n
}
</code>```

isEvenSubset(18,12) returns true and isEvenSubset(18,32) returns false.

Title: isEvenSubset did not return 1

Body:
Here is the Question: An integer is defined to be an even subset of another integer n if every even factor of m is also a factor of n. For example 18 is an even subset of 12 because the even factors of 18 are 2 and 6 and these are both factors of 12. But 18 is not an even subset of 32 because 6 is not a factor of 32.

This is a University's sample question; the question, explicitly, states: No additional data structures including arrays allowed - therefore, please consider that too while providing answer. Thank you.

Here is my answer code:

public class IsEvenSubset {
    public static void main(String[] args) {
        System.out.println(isEvenSubset(18,12));
    }
    private static int isEvenSubset(int m, int n){
        for(int i=2;i<=m;i++){
            int count=0;//reset count in each round
            if(m%2==0 && m%i==0){
                for(int j=2;j<=n;j++){
                    if(n%2==0 && n%j==0){
                        if(i==j)count++;
                    }
                }
                if(count==0)return 0;
            }
        }
        return 1;
    }
}

This code didn't work as desired. Please help me figure out where did I do wrong?

Body:
You are checking whether m and n are even instead of whether their factors are even. Besides, the inner loop is not needed, just find all the even factors of the first number and check whether all of them are also factors of the second number.

private static boolean isEvenSubset (int m, int n)
{
    for(int i = 2; i < m; i++){ // note that I don't consider m itself to be a factor of m
        if (i % 2 == 0 && m % i == 0 && n %i != 0){ // i is an even factor of m but
                                                    // not a factor of n, so return false
            return false;
        }
    }
    return true; // all the even factors of m were also factors of n
}

isEvenSubset(18,12) returns true and isEvenSubset(18,32) returns false.


问:
can i combine if else and with try catch python?
i have a code :

```<code>s = '127.0.0.0'

def validate(a):
    a = s.split('.')
    if len(a) !=4:
        return False
    for x in a :
        if not x.isdigit():
            return False
        i = int(x)
        if i < 0 or i > 255 :
            return False
    return False

try:
    validate(s) #ip validation
    #my code here
except :
    print("insert you're ip correctly")
</code>```

can i combine if else with try catch like that?

if the try catch got error message or like return false from if condition it will run the except condition, if not it will run the try condition until the process is end.

there's have a better ways to dot this?

答:
The answers above may be technically correct, but considering coding style etc. I don't see any reason to use exceptions here instead a plain if else:

```<code>if not validate(s): #ip validation
    print("insert you're ip correctly")
</code>```

That actually does what you want and it's much cleaner and better to read.

Body:
i have a code :

s = '127.0.0.0'

def validate(a):
    a = s.split('.')
    if len(a) !=4:
        return False
    for x in a :
        if not x.isdigit():
            return False
        i = int(x)
        if i < 0 or i > 255 :
            return False
    return False

try:
    validate(s) #ip validation
    #my code here
except :
    print("insert you're ip correctly")

can i combine if else with try catch like that?

if the try catch got error message or like return false from if condition it will run the except condition, if not it will run the try condition until the process is end.

there's have a better ways to dot this?

Body:
The answers above may be technically correct, but considering coding style etc. I don't see any reason to use exceptions here instead a plain if else:

if not validate(s): #ip validation
    print("insert you're ip correctly")

That actually does what you want and it's much cleaner and better to read.


问:
Need help Accessing properties in Object Constructor Function (noLibs vanilla js only)
```<code>let allLamps = [];

// Object Constructor Function that will add new obj to array

function Object (serial, type, od, ol, arc) {
    this.serial = serial;
    this.type = type;
    this.od = od;
    this.ol = ol;
    this.arc = arc;
};

const obj1 = new Object(1,"g51",75,95,46);
const obj2 = new Object(2,"g38",75,95,46);
const obj3 = new Object(3,"9k",57,67,27);

function push(obj) {
    allLamps.push(obj);
}

push(obj1);
push(obj2);
push(obj3);
</code>```

So if Log the array allLamps to the console I get all my
   objects:

```<code>console.log(allLamps)
</code>```

I want to access each property like:

```<code>const getAll = allLamps.map(function(obj){
     return obj.serial;
});
</code>```

or

```<code>for(var i = 0; i < allLamps.length; i++){
    return allLamps[i].serial;
}
</code>```

But it seems that I get undefined. Note I am still learning the basics. I know I'm doing something wrong. I appreciate any solution.
Even if I do this:

```<code>for (var i = 0; i < allLamps.length; i++ {
    return allLamps[i];
}
</code>```

I only get one of my objects, not all of them.

答:
As literally defined array

```<code>const lamp = (serial, type, od, ol, arc) => ({serial, type, od, ol, arc});
const lamps = [lamp(1,"g51",75,95,46), lamp(2,"g38",75,95,46), lamp(3,"9k",57,67,27)];
</code>```

As pushed array Items

```<code>const lamp = (serial, type, od, ol, arc) => lamps.push({serial, type, od, ol, arc});
const lamps = [];
lamp(1,"g51",75,95,46);
lamp(2,"g38",75,95,46);
lamp(3,"9k",57,67,27);
</code>```

or

```<code>const lamp = (serial, type, od, ol, arc) => ({serial, type, od, ol, arc});
const lamps = [];
lamps.push(lamp(1,"g51",75,95,46));
lamps.push(lamp(2,"g38",75,95,46));
lamps.push(lamp(3,"9k",57,67,27));
</code>```

or

```<code>function Lamp (serial, type, od, ol, arc) {
    this.serial = serial;
    this.type = type;
    this.od = od;
    this.ol = ol;
    this.arc = arc;
};
const allLamps = [];
lamps.push(new Lamp(1,"g51",75,95,46));
lamps.push(new Lamp(2,"g38",75,95,46));
lamps.push(new Lamp(3,"9k",57,67,27));
</code>```

or

```<code>const lamp = (serial, type, od, ol, arc) => ({serial, type, od, ol, arc});
const lamps = [
    [1,"g51",75,95,46],
    [2,"g38",75,95,46],
    [3,"9k",57,67,27]
 ].map(data => lamp(...data));
</code>```

To name but a few

Body:
let allLamps = [];

// Object Constructor Function that will add new obj to array

function Object (serial, type, od, ol, arc) {
    this.serial = serial;
    this.type = type;
    this.od = od;
    this.ol = ol;
    this.arc = arc;
};

const obj1 = new Object(1,"g51",75,95,46);
const obj2 = new Object(2,"g38",75,95,46);
const obj3 = new Object(3,"9k",57,67,27);

function push(obj) {
    allLamps.push(obj);
}

push(obj1);
push(obj2);
push(obj3);

So if Log the array allLamps to the console I get all my
   objects:

console.log(allLamps)

I want to access each property like:

const getAll = allLamps.map(function(obj){
     return obj.serial;
});

or

for(var i = 0; i < allLamps.length; i++){
    return allLamps[i].serial;
}

But it seems that I get undefined. Note I am still learning the basics. I know I'm doing something wrong. I appreciate any solution.
Even if I do this:

for (var i = 0; i < allLamps.length; i++ {
    return allLamps[i];
}

I only get one of my objects, not all of them.

Body:
As literally defined array

const lamp = (serial, type, od, ol, arc) => ({serial, type, od, ol, arc});
const lamps = [lamp(1,"g51",75,95,46), lamp(2,"g38",75,95,46), lamp(3,"9k",57,67,27)];

As pushed array Items

const lamp = (serial, type, od, ol, arc) => lamps.push({serial, type, od, ol, arc});
const lamps = [];
lamp(1,"g51",75,95,46);
lamp(2,"g38",75,95,46);
lamp(3,"9k",57,67,27);

or

const lamp = (serial, type, od, ol, arc) => ({serial, type, od, ol, arc});
const lamps = [];
lamps.push(lamp(1,"g51",75,95,46));
lamps.push(lamp(2,"g38",75,95,46));
lamps.push(lamp(3,"9k",57,67,27));

or

function Lamp (serial, type, od, ol, arc) {
    this.serial = serial;
    this.type = type;
    this.od = od;
    this.ol = ol;
    this.arc = arc;
};
const allLamps = [];
lamps.push(new Lamp(1,"g51",75,95,46));
lamps.push(new Lamp(2,"g38",75,95,46));
lamps.push(new Lamp(3,"9k",57,67,27));

or

const lamp = (serial, type, od, ol, arc) => ({serial, type, od, ol, arc});
const lamps = [
    [1,"g51",75,95,46],
    [2,"g38",75,95,46],
    [3,"9k",57,67,27]
 ].map(data => lamp(...data));

To name but a few


问:
Azure Client Side Encryption
I would like to know if Azure Storage's Client-Side encryption also applies to file blobs or just strings. I could find some documents on how to do client-side "data encryption" for Azure but they don't specify what data types are valid for client side encryption.

If for example, I have a JPEG file, can it be encrypted before upload and then decrypted before download, using the  Azure Storage's Client Side Encryption?

答:
Short answer: Yes.

If you have a JPEG file (or for that matter any file) you will be able to encrypt that file and store it in encrypted format in Azure Storage. It doesn't just apply to strings only.

There are some caveats though for client side encryption to work and for that I suggest you read this article on Azure documentation site which explains the whole process very well: https://learn.microsoft.com/en-us/azure/storage/storage-client-side-encryption.

Title: Azure Client Side Encryption


问:
How to write height for row in RxSwift?
I want to convert the below code into RxSwift. And also please help me how to write button Action code in RxSwift.

ReactiveCocoa or RxSwift Which one is better to use in swift3?

```<code>func tableView(_ tableView: UITableView, numberOfRowsInSection section:
Int) -> Int {
    return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
    let cell: BTSTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "BTSTableViewCellIdentifier")! as! BTSTableViewCell

    cell.configureWithPost(posts[indexPath.row])
    cell.delegate = self
    return cell

}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    // 259.5+ labelHeight+ bigImageHeight

    let postViewModel = posts[indexPath.row]

    //caption height
    var captionHeight = postViewModel.textDetail?.height(withConstrainedWidth: tableView.bounds.size.width - 20, font: UIFont.systemFont(ofSize: 17))

    captionHeight = ceil(captionHeight!)

    var finalCaptionHeight: CGFloat = 0.0;

   if postViewModel.showDetailedCaption {
        finalCaptionHeight = captionHeight!
    }
    else {
        finalCaptionHeight = min(41, captionHeight!)
    }
    return 259.5 +
 postViewModel.getBigImageHeightFor(tableView.bounds.size.width) +
 finalCaptionHeight

}
</code>```

答:
For tableview in RxSwift, take look at :
https://github.com/devxoul/help-me-rx-tableview-cell-height/blob/master/SimpleTableViewController/SimpleTableViewController.swift

for the button action check sample code below

```<code>button.rx.tap
        .bind { [weak self] in
            //YOUR TAP ACTION CODE LOGIC GOES HERE
        }
        .disposed(by: disposeBag)
</code>```

Title: How to write height for row in RxSwift?

Body:
I want to convert the below code into RxSwift. And also please help me how to write button Action code in RxSwift.

ReactiveCocoa or RxSwift Which one is better to use in swift3?

func tableView(_ tableView: UITableView, numberOfRowsInSection section:
Int) -> Int {
    return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
    let cell: BTSTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "BTSTableViewCellIdentifier")! as! BTSTableViewCell

    cell.configureWithPost(posts[indexPath.row])
    cell.delegate = self
    return cell

}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    // 259.5+ labelHeight+ bigImageHeight

    let postViewModel = posts[indexPath.row]

    //caption height
    var captionHeight = postViewModel.textDetail?.height(withConstrainedWidth: tableView.bounds.size.width - 20, font: UIFont.systemFont(ofSize: 17))

    captionHeight = ceil(captionHeight!)

    var finalCaptionHeight: CGFloat = 0.0;

   if postViewModel.showDetailedCaption {
        finalCaptionHeight = captionHeight!
    }
    else {
        finalCaptionHeight = min(41, captionHeight!)
    }
    return 259.5 +
 postViewModel.getBigImageHeightFor(tableView.bounds.size.width) +
 finalCaptionHeight

}

Body:
For tableview in RxSwift, take look at :
https://github.com/devxoul/help-me-rx-tableview-cell-height/blob/master/SimpleTableViewController/SimpleTableViewController.swift

for the button action check sample code below

button.rx.tap
        .bind { [weak self] in
            //YOUR TAP ACTION CODE LOGIC GOES HERE
        }
        .disposed(by: disposeBag)


问:
Codeigniter how to create PDF
I'm going to create an invoice system, I am preparing for that now.
I'm gonna use Codeigniter.
The thing is that I want to create invoice in PDF so I can send it through email.

What is your guys advice?
I was thinking of HTML to PDF conversion,
Or Show the invoice on screen and install a pdf printer (when you hit print and you choose to print to a PDF file)
Or create a word document and connect to the MySQL server I think with odbc.

Any of you guys have experience with this?

答:
I have used mpdf in my project. In Codeigniter-3, putted mpdf files under application/third_party and then used in this way:</p>

```<code> /**
 * This function is used to display data in PDF file.
 * function is using mpdf api to generate pdf.
 * @param number $id : This is unique id of table.
 */
function generatePDF($id){
    require APPPATH . '/third_party/mpdf/vendor/autoload.php';
    //$mpdf=new mPDF();
    $mpdf = new mPDF('utf-8', 'Letter', 0, '', 0, 0, 7, 0, 0, 0);

    $checkRecords =  $this->user_model->getCheckInfo($id);
    foreach ($checkRecords as $key => $value) {
        $data['info'] = $value;
        $filename = $this->load->view(CHEQUE_VIEWS.'index',$data,TRUE);
        $mpdf->WriteHTML($filename);
    }

    $mpdf->Output(); //output pdf document.
    //$content = $mpdf->Output('', 'S'); //get pdf document content's as variable.

}
</code>```

Title: Codeigniter how to create PDF

Body:
I have used mpdf in my project. In Codeigniter-3, putted mpdf files under application/third_party and then used in this way:

 /**
 * This function is used to display data in PDF file.
 * function is using mpdf api to generate pdf.
 * @param number $id : This is unique id of table.
 */
function generatePDF($id){
    require APPPATH . '/third_party/mpdf/vendor/autoload.php';
    //$mpdf=new mPDF();
    $mpdf = new mPDF('utf-8', 'Letter', 0, '', 0, 0, 7, 0, 0, 0);

    $checkRecords =  $this->user_model->getCheckInfo($id);
    foreach ($checkRecords as $key => $value) {
        $data['info'] = $value;
        $filename = $this->load->view(CHEQUE_VIEWS.'index',$data,TRUE);
        $mpdf->WriteHTML($filename);
    }

    $mpdf->Output(); //output pdf document.
    //$content = $mpdf->Output('', 'S'); //get pdf document content's as variable.

}


问:
Python 3.6 no module named 'gspread' - pyinstaller compiled executable
I have compiled some python code using pyinstaller, working out well however upon running the actual executable, I get the error as mentioned in title.

What I have tried to fix this:

```<code>--paths=directoryofgspreadmodule
# still got the same error.
--hidden-import=gspread
# Samething
</code>```

overall command:

```<code>python pyinstaller.py -F MyCode.py --paths=directoryofgspreadmodule --onefile
</code>```

as a side note, I also am using matplotlib and the executable seemed to come out with 200Mb, is this normal?

Thanks for any help

答: Never-mind this was my own bad. I set --paths= within the directory itself, no wonder it couldn't find it (as mentioned above)</p>

Body:
I have compiled some python code using pyinstaller, working out well however upon running the actual executable, I get the error as mentioned in title.

What I have tried to fix this:

--paths=directoryofgspreadmodule
# still got the same error.
--hidden-import=gspread
# Samething

overall command:

python pyinstaller.py -F MyCode.py --paths=directoryofgspreadmodule --onefile

as a side note, I also am using matplotlib and the executable seemed to come out with 200Mb, is this normal?

Thanks for any help


问:
Always run service as NetworkService, even in interactive mode
I have a service application that supports both start as service and interactive mode. The service I register is executed as the NetworkService user; the interactive mode is running as a computer administrator (normal users have no access to the program).

Now, some resources (e.g. files) are only available to the user NetworkService. Can I somehow tell the program to run the code as NetworkService, even if started by an administrator?

答:
In general you can change permission for file if you have Administrator rights.

Or start code as NetworkService account with help PsExec.exe like described here


问:
What is the result of the expression?
Does this code would work as expected in all browsers? Is there any notes in specification about it?

```<code>var attributes = this._attributes ? this._attributes : (this._attributes = []);
</code>```

I.e. if *this._attributes* not initialized, then new array will be created and that array will be assigned to *this._attributes* and to attributes.

答: I don't see any reason why not. I don't think I'd write it that way, I'm not a fan of assignments with side-effects, but syntactically it's fine.</p>

Title: What is the result of the expression?

Body:
Does this code would work as expected in all browsers? Is there any notes in specification about it?

var attributes = this._attributes ? this._attributes : (this._attributes = []);

I.e. if *this._attributes* not initialized, then new array will be created and that array will be assigned to *this._attributes* and to attributes.