问:
Android JSON POST with OKHTTP
I´m looking for a solution to implement a JSON-POST request with OKHTTP. I´ve got an HTTP-Client.java file which handles all the methods (POST, GET, PUT, DELETE) and in the RegisterActivity I´d like to POST the user-data (from the input fields) JSON-formatted to the server.

This is my HTTP-Client.java

```<code>    public class HttpClient{

        public static final MediaType JSON
                = MediaType.parse("application/json; charset=utf-8");

        public static OkHttpClient client = new OkHttpClient.Builder()
                .cookieJar(new CookieJar() {
                    private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();

                    @Override
                    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                        cookieStore.put(url.host(), cookies);
                    }

                    @Override
                    public List<Cookie> loadForRequest(HttpUrl url) {
                        List<Cookie> cookies = cookieStore.get(url.host());
                        return cookies != null ? cookies : new ArrayList<Cookie>();
                    }
                })
                .build();

        public static Call post(String url, String json, Callback callback) throws IOException {
            RequestBody body = RequestBody.create(JSON, json);

            Request request = new Request.Builder()
                    .url(url)
                    .post(body.create(JSON, json))
                    .build();
            Call call = client.newCall(request);
            call.enqueue(callback);
            return call;
        }
}
</code>```

... and this is the onClick-Part from the RegisterActivity

```<code>btnRegRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO

                String registerData = "{\"email\":\"" + etRegisterEmail.getText().toString() + "\",\"password\":\"" + etRegisterPasswort.getText().toString() + "\"}";

                try {
                    HttpClient.post(ABSOLUTE_URL, registerData, new Callback(){
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if (response.isSuccessful()) {
                                String resp = response.body().string();
                                if (resp != null) {
                                    Log.d("Statuscode", String.valueOf(response.code()));
                                    Log.d("Body", response.body().string());
                                }
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
</code>```

Everytime I start the app it crashes when I click the Register-Button caused by a FATAL EXPECTION 'android.os.NetworkOnMainThreadException'

I´ve alread read something about the AsyncTask but I don´t know exactly how to do this.

答:
Try using Retrofit library for making Post request to the server. This provides a fast and reliable connection to the server.

You can also use Volley library for the same.

Title: Android JSON POST with OKHTTP

Body:
I´m looking for a solution to implement a JSON-POST request with OKHTTP. I´ve got an HTTP-Client.java file which handles all the methods (POST, GET, PUT, DELETE) and in the RegisterActivity I´d like to POST the user-data (from the input fields) JSON-formatted to the server.

This is my HTTP-Client.java

    public class HttpClient{

        public static final MediaType JSON
                = MediaType.parse("application/json; charset=utf-8");

        public static OkHttpClient client = new OkHttpClient.Builder()
                .cookieJar(new CookieJar() {
                    private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();

                    @Override
                    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                        cookieStore.put(url.host(), cookies);
                    }

                    @Override
                    public List<Cookie> loadForRequest(HttpUrl url) {
                        List<Cookie> cookies = cookieStore.get(url.host());
                        return cookies != null ? cookies : new ArrayList<Cookie>();
                    }
                })
                .build();

        public static Call post(String url, String json, Callback callback) throws IOException {
            RequestBody body = RequestBody.create(JSON, json);

            Request request = new Request.Builder()
                    .url(url)
                    .post(body.create(JSON, json))
                    .build();
            Call call = client.newCall(request);
            call.enqueue(callback);
            return call;
        }
}

... and this is the onClick-Part from the RegisterActivity

btnRegRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO

                String registerData = "{\"email\":\"" + etRegisterEmail.getText().toString() + "\",\"password\":\"" + etRegisterPasswort.getText().toString() + "\"}";

                try {
                    HttpClient.post(ABSOLUTE_URL, registerData, new Callback(){
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if (response.isSuccessful()) {
                                String resp = response.body().string();
                                if (resp != null) {
                                    Log.d("Statuscode", String.valueOf(response.code()));
                                    Log.d("Body", response.body().string());
                                }
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

Everytime I start the app it crashes when I click the Register-Button caused by a FATAL EXPECTION 'android.os.NetworkOnMainThreadException'

I´ve alread read something about the AsyncTask but I don´t know exactly how to do this.


来源: stackexchange

问:
AlertDialog not displaying in android studio
I have an AlertDialog in android studio as shown below:

```<code>final EditText columninput = new EditText(this);
columninput.setInputType(InputType.TYPE_CLASS_NUMBER);

AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Choose column number");
adb.setView(columninput);
adb.setMessage("Please specify the number of columns you would like to decrypt your message with.");
adb.setCancelable(true);
adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        boolean bool = true;

        try {
            col = Integer.parseInt(columninput.getText().toString());
        }
        catch (Exception e) {
            bool = false;
            Toast t = Toast.makeText(getApplicationContext(), "Incorrect input", Toast.LENGTH_LONG);
            t.show();
        }

        if (bool) {
             dialog.dismiss();
        }
    }
});

adb.show();

method1(toRead, col);
</code>```

Note that toRead is another variable dealt with outside of this context; it should not be causing any errors. When I run my application, the AlertDialog is never shown, and method1 runs immediately. However, when I comment out the last line (method1(toRead, col)), the alertdialog appears when the application is run. Why is this, and how can I ensure that the alertDialog is always shown?

答:
May this helps you:

Example:

```<code>    new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle("Delete")
            .setMessage("Are you sure you want to delete Product?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dbni.delete(ItemID);
                    arrayStudent = dbni.selectAll();
                    list_view.setAdapter(new Adapter_viewitem(mactivity, arrayStudent));
                    Toast.makeText(getApplicationContext(), "Product deleted successfully", Toast.LENGTH_SHORT).show();
                }

            }).setNegativeButton("No", null).show();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an AlertDialog in android studio as shown below:

final EditText columninput = new EditText(this);
columninput.setInputType(InputType.TYPE_CLASS_NUMBER);

AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Choose column number");
adb.setView(columninput);
adb.setMessage("Please specify the number of columns you would like to decrypt your message with.");
adb.setCancelable(true);
adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        boolean bool = true;

        try {
            col = Integer.parseInt(columninput.getText().toString());
        }
        catch (Exception e) {
            bool = false;
            Toast t = Toast.makeText(getApplicationContext(), "Incorrect input", Toast.LENGTH_LONG);
            t.show();
        }

        if (bool) {
             dialog.dismiss();
        }
    }
});

adb.show();

method1(toRead, col);

Note that toRead is another variable dealt with outside of this context; it should not be causing any errors. When I run my application, the AlertDialog is never shown, and method1 runs immediately. However, when I comment out the last line (method1(toRead, col)), the alertdialog appears when the application is run. Why is this, and how can I ensure that the alertDialog is always shown?

Body:
May this helps you:

Example:

    new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle("Delete")
            .setMessage("Are you sure you want to delete Product?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dbni.delete(ItemID);
                    arrayStudent = dbni.selectAll();
                    list_view.setAdapter(new Adapter_viewitem(mactivity, arrayStudent));
                    Toast.makeText(getApplicationContext(), "Product deleted successfully", Toast.LENGTH_SHORT).show();
                }

            }).setNegativeButton("No", null).show();


问:
unable to npm install globalization with ionic 2.2.0, Unmet dependencies
I am trying to install the "globalization" plugin, in order to access .getPreferredLanguage() in my ionic 2 app, but I get this UNMET DEPENDENCY error.

```<code>$ ionic plugin add cordova-plugin-globalization --savePlugin "cordova-plugin-globalization" already installed on android.

Plugin "cordova-plugin-globalization" already installed on ios.

Saved plugin info for "cordova-plugin-globalization" to config.xml

$ npm install --save @ionic-native/globalizationboardline@1.0.0 /home/louisro/Documents/mobileApps/BoardLine/ionic_version
├── UNMET PEER DEPENDENCY @angular/core@*
├── UNMET PEER DEPENDENCY @ionic-native/core@^3.1.0
├── @ionic-native/globalization@3.4.4
└── UNMET PEER DEPENDENCY rxjs@^5.0.1

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN @ionic-native/globalization@3.4.4 requires a peer of @ionic-native/core@^3.1.0 but none was installed.
npm WARN @ionic-native/globalization@3.4.4 requires a peer of @angular/core@* but none was installed.
npm WARN @ionic-native/globalization@3.4.4 requires a peer of rxjs@^5.0.1 but none was installed.
npm WARN @ionic/cloud-angular@0.4.0 requires a peer of @angular/core@>=2.0.0-rc.0 <2.0.0-rc.5 but none was installed.
npm WARN @ionic/cloud-angular@0.4.0 requires a peer of rxjs@>=5.0.0-beta.0 but none was installed.
</code>```

and

```<code>$ ionic info

Cordova CLI: 6.5.0
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.2.0
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Linux 4.4
Node Version: v7.4.0
Xcode version: Not installed
</code>```

EDIT I am adding package.json code here:
package.json:

```<code>    {
  "name": "ionic-hello-world",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "2.4.8",
    "@angular/compiler": "2.4.8",
    "@angular/compiler-cli": "2.4.8",
    "@angular/core": "2.4.8",
    "@angular/forms": "2.4.8",
    "@angular/http": "2.4.8",
    "@angular/platform-browser": "2.4.8",
    "@angular/platform-browser-dynamic": "2.4.8",
    "@angular/platform-server": "2.4.8",
    "@ionic-native/app-version": "^3.4.4",
    "@ionic-native/core": "^3.4.1",
    "@ionic-native/device": "^3.4.1",
    "@ionic-native/geolocation": "^3.4.4",
    "@ionic-native/google-analytics": "^3.4.4",
    "@ionic-native/keyboard": "^3.4.4",
    "@ionic-native/onesignal": "^3.4.4",
    "@ionic-native/splash-screen": "^3.4.4",
    "@ionic-native/status-bar": "^3.4.4",
    "@ionic/storage": "^2.0.0",
    "@types/pouchdb": "5.4.28",
    "angular-2-local-storage": "^1.0.1",
    "ionic-angular": "2.2.0",
    "ionic-native": "2.8.1",
    "ionicons": "3.0.0",
    "lodash": "^4.17.4",
    "ng2-translate": "^5.0.0",
    "pouchdb": "^6.1.2",
    "rxjs": "5.0.1",
    "sw-toolbox": "3.4.0",
    "zone.js": "0.7.2"
  },
  "devDependencies": {
    "@ionic/app-scripts": "^1.1.4",
    "@types/cordova": "0.0.34",
    "@types/cordova-ionic": "0.0.29",
    "@types/node": "^7.0.12",
    "typescript": "2.0.9"
  },
  "cordovaPlugins": [
    "cordova-plugin-statusbar",
    "cordova-plugin-device",
    "cordova-plugin-splashscreen",
    "ionic-plugin-keyboard",
    "cordova-plugin-whitelist",
    "cordova-plugin-console"
  ],
  "cordovaPlatforms": [],
  "description": "Boane: An Ionic project"
}
</code>```

答:
Your problem is with this "ionic-native": "2.8.1",.You have to remove it , in order to only have one line for ionic-native: "@ionic-native/core": "^3.4.4",.
After that run npm i

Body:
I am trying to install the "globalization" plugin, in order to access .getPreferredLanguage() in my ionic 2 app, but I get this UNMET DEPENDENCY error.

$ ionic plugin add cordova-plugin-globalization --savePlugin "cordova-plugin-globalization" already installed on android.

Plugin "cordova-plugin-globalization" already installed on ios.

Saved plugin info for "cordova-plugin-globalization" to config.xml

$ npm install --save @ionic-native/globalizationboardline@1.0.0 /home/louisro/Documents/mobileApps/BoardLine/ionic_version
├── UNMET PEER DEPENDENCY @angular/core@*
├── UNMET PEER DEPENDENCY @ionic-native/core@^3.1.0
├── @ionic-native/globalization@3.4.4
└── UNMET PEER DEPENDENCY rxjs@^5.0.1

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN @ionic-native/globalization@3.4.4 requires a peer of @ionic-native/core@^3.1.0 but none was installed.
npm WARN @ionic-native/globalization@3.4.4 requires a peer of @angular/core@* but none was installed.
npm WARN @ionic-native/globalization@3.4.4 requires a peer of rxjs@^5.0.1 but none was installed.
npm WARN @ionic/cloud-angular@0.4.0 requires a peer of @angular/core@>=2.0.0-rc.0 <2.0.0-rc.5 but none was installed.
npm WARN @ionic/cloud-angular@0.4.0 requires a peer of rxjs@>=5.0.0-beta.0 but none was installed.

and

$ ionic info

Cordova CLI: 6.5.0
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.2.0
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Linux 4.4
Node Version: v7.4.0
Xcode version: Not installed

EDIT I am adding package.json code here:
package.json:

    {
  "name": "ionic-hello-world",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "2.4.8",
    "@angular/compiler": "2.4.8",
    "@angular/compiler-cli": "2.4.8",
    "@angular/core": "2.4.8",
    "@angular/forms": "2.4.8",
    "@angular/http": "2.4.8",
    "@angular/platform-browser": "2.4.8",
    "@angular/platform-browser-dynamic": "2.4.8",
    "@angular/platform-server": "2.4.8",
    "@ionic-native/app-version": "^3.4.4",
    "@ionic-native/core": "^3.4.1",
    "@ionic-native/device": "^3.4.1",
    "@ionic-native/geolocation": "^3.4.4",
    "@ionic-native/google-analytics": "^3.4.4",
    "@ionic-native/keyboard": "^3.4.4",
    "@ionic-native/onesignal": "^3.4.4",
    "@ionic-native/splash-screen": "^3.4.4",
    "@ionic-native/status-bar": "^3.4.4",
    "@ionic/storage": "^2.0.0",
    "@types/pouchdb": "5.4.28",
    "angular-2-local-storage": "^1.0.1",
    "ionic-angular": "2.2.0",
    "ionic-native": "2.8.1",
    "ionicons": "3.0.0",
    "lodash": "^4.17.4",
    "ng2-translate": "^5.0.0",
    "pouchdb": "^6.1.2",
    "rxjs": "5.0.1",
    "sw-toolbox": "3.4.0",
    "zone.js": "0.7.2"
  },
  "devDependencies": {
    "@ionic/app-scripts": "^1.1.4",
    "@types/cordova": "0.0.34",
    "@types/cordova-ionic": "0.0.29",
    "@types/node": "^7.0.12",
    "typescript": "2.0.9"
  },
  "cordovaPlugins": [
    "cordova-plugin-statusbar",
    "cordova-plugin-device",
    "cordova-plugin-splashscreen",
    "ionic-plugin-keyboard",
    "cordova-plugin-whitelist",
    "cordova-plugin-console"
  ],
  "cordovaPlatforms": [],
  "description": "Boane: An Ionic project"
}


问:
Python3 Requests ConnectionError: ('Connection aborted.', OSError("(104, 'ECONNRESET')",)) with a specific URL
This is my code.

```<code>import requests
r = requests.get('https://academic.oup.com/journals')
</code>```

then I got the error below;

```<code>ConnectionError: ('Connection aborted.', OSError("(104, 'ECONNRESET')",))
</code>```

Why I got the error?
What should I do?
the Request works well with other URLs like https://www.google.com

答:
Try specifying a user-agent in the HTTP header:

```<code>❯❯❯ python3
Python 3.5.2 (default, Sep 14 2016, 11:28:32)
[GCC 6.2.1 20160901 (Red Hat 6.2.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> headers = requests.utils.default_headers()
>>> headers['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
>>> r = requests.get('https://academic.oup.com/journals', headers=headers)
>>> r
<Response [200]>
</code>```

Also, make sure you follow the rules mentioned in the website's robots.txt

Body:
This is my code.

import requests
r = requests.get('https://academic.oup.com/journals')

then I got the error below;

ConnectionError: ('Connection aborted.', OSError("(104, 'ECONNRESET')",))

Why I got the error?
What should I do?
the Request works well with other URLs like https://www.google.com

Body:
Try specifying a user-agent in the HTTP header:

❯❯❯ python3
Python 3.5.2 (default, Sep 14 2016, 11:28:32)
[GCC 6.2.1 20160901 (Red Hat 6.2.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> headers = requests.utils.default_headers()
>>> headers['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
>>> r = requests.get('https://academic.oup.com/journals', headers=headers)
>>> r
<Response [200]>

Also, make sure you follow the rules mentioned in the website's robots.txt


问:
How can I use valgrind with Python code to detect race condition?
I have Python code with race condition.

```<code>import threading
class Counter:
    def __init__(self):
        self.x = 0
    def incr(self):
        self.x += 1
    def __str__(self):
        return str(self.x)

x = Counter()

class T(threading.Thread):
  def run(self):
        for i in range(100000):
            x.incr()

t1 = T()
t2 = T()
t1.start()
t2.start()
t1.join()
t2.join()
print(x)
</code>```

And I trying to use valgrind to detect it.

```<code>valgrind --tool=helgrind --suppressions=valgrind-python.supp \python -E -tt ./1.py
0 errors from 0 contexts (suppressed: 9 from 9)
</code>```

Can I use valgrind to detect race condition in Python code?

答:
The standard implementation of Python uses a global interpreter lock to ensure that only one thread at a time can be executing Python bytecode.

So from valgrind's perspective, only one thread is running.

Body:
I have Python code with race condition.

import threading
class Counter:
    def __init__(self):
        self.x = 0
    def incr(self):
        self.x += 1
    def __str__(self):
        return str(self.x)

x = Counter()

class T(threading.Thread):
  def run(self):
        for i in range(100000):
            x.incr()

t1 = T()
t2 = T()
t1.start()
t2.start()
t1.join()
t2.join()
print(x)

And I trying to use valgrind to detect it.

valgrind --tool=helgrind --suppressions=valgrind-python.supp \python -E -tt ./1.py
0 errors from 0 contexts (suppressed: 9 from 9)

Can I use valgrind to detect race condition in Python code?


问:
Need to post multi dimensional JSON from Angularjs form
i'm new in angular. i need multi dimensional type json. mycode is given below

view page controller

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
 $scope.menu  = {};
        $scope.menus  = [
  {"menuID":"1","sub_menu":"N","name":"dashboard","sub_menus":""},
  {"menuID":"2","sub_menu":"Y","name":"settings","sub_menus":[{"sub_menuID":"1","name":"settings1","page":"Y","pages":[{"pageID":"1","name":"page1"},{"pageID":"2","name":"page2"}]},{"sub_menuID":"2","name":"settings2","page":"N","pages":""}]},
  {"menuID":"3","sub_menu":"Y","name":"help","sub_menus":[{"sub_menuID":"1","name":"help1","page":"N","pages":""},{"sub_menuID":"2","name":"help2","page":"N","pages":""}]},
  {"menuID":"4","sub_menu":"Y","name":"contact","sub_menus":[{"sub_menuID":"1","name":"contact1","page":"N","pages":""},{"sub_menuID":"2","name":"contact2","page":"N","pages":""}]}
 ];

 $scope.submit = function(){
  // alert(JSON.stringify($scope.menu));
  console.error(JSON.stringify($scope.menu));
 }

});

html view page```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <title>rules</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
  <script src="mainCtrl.js"></script>
</head>
<body ng-app="app">

 <div ng-controller="MainCtrl">
      <form ng-submit="submit()">
      <ul>
        <li ng-repeat="x in menus">
          <input type="checkbox" ng-model="menu[x.menuID]" ng-true-value="'{{x.menuID}}'">{{x.name}}
          <ul ng-if="[x.sub_menu] == 'Y'">
            <li ng-repeat="subMenu in x.sub_menus">
              <input type="checkbox" ng-model="menu[x.menuID][subMenu.sub_menuID]">{{subMenu.name}}
              <ul ng-if="[subMenu.page] == 'Y'">
                <li ng-repeat="page in subMenu.pages">
                  <input type="checkbox" ng-model="menu[x.name][subMenu.name][page.pageID]">{{page.name}}
                </li>
              </ul>
            </li>
          </ul>
        </li>
      </ul>
      <button>Submit</button>
      </form>
  </div>
</body>
</html></code>```

I need this format of JSON:

After all checkbox checked and post form.

答:
Example in snippet will create the object structure as per requirement if all check boxes selected. But it will change only value to false if user unchecked boxes(you can work upon this as per requirement in future).

Please see the below snippet for answer.

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.mainMenu = {};
  $scope.submenu = {};
  $scope.pagemenu ={};
 $scope.menu  = {};
        $scope.menus  = [
  {"menuID":"1","sub_menu":"N","name":"dashboard","sub_menus":""},
  {"menuID":"2","sub_menu":"Y","name":"settings","sub_menus":             [{"sub_menuID":"1","name":"settings1","page":"Y","pages":[{"pageID":"1","name":"page1"},{"pageID":"2","name":"page2"}]},{"sub_menuID":"2","name":"settings2","page":"N","pages":""}]},
  {"menuID":"3","sub_menu":"Y","name":"help","sub_menus":[{"sub_menuID":"1","name":"help1","page":"N","pages":""},{"sub_menuID":"2","name":"help2","page":"N","pages":""}]},
  {"menuID":"4","sub_menu":"Y","name":"contact","sub_menus":[{"sub_menuID":"1","name":"contact1","page":"N","pages":""},{"sub_menuID":"2","name":"contact2","page":"N","pages":""}]}
 ];

  $scope.assignValue = function(menuId,submenuId,pageId){
/*  if(!$scope.mainMenu[menuId]&&!$scope.submenu[menuId]&&!$scope.pagemenu[menuId]){
    delete($scope.mainMenu[menuId]);
    delete($scope.submenu[menuId]);
    delete($scope.pagemenu[menuId]);
  }*/

if(pageId!=undefined && !$scope.pagemenu[menuId][submenuId][pageId]){
    delete($scope.pagemenu[menuId][submenuId][pageId]);
    if(Object.keys($scope.pagemenu[menuId][submenuId]).length === 0){
       delete($scope.pagemenu[menuId][submenuId]);
  }
  }

  if(submenuId!=undefined && $scope.submenu[menuId][submenuId]!=undefined && !$scope.submenu[menuId][submenuId] && Object.keys($scope.submenu[menuId][submenuId]).length === 0){
    delete($scope.submenu[menuId][submenuId]);

  }

    if(Object.keys($scope.menu).length === 0){
        $scope.menu=Object.assign({},$scope.mainMenu,$scope.submenu);
    }else{
        $scope.menu[menuId] = $scope.mainMenu[menuId];
    }

    var tempObj = Object.assign({},$scope.submenu[menuId],$scope.pagemenu[menuId]);
    if(Object.keys(tempObj).length != 0){
        $scope.menu[menuId] = tempObj
    }

  console.log($scope.menu);
  }

 $scope.submit = function(){
  // alert(JSON.stringify($scope.menu));
  console.log(JSON.stringify($scope.menu));
     console.log($scope.menu);
 }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <title>rules</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
  <script src="mainCtrl.js"></script>
</head>
<body ng-app="app">

 <div ng-controller="MainCtrl">
      <form ng-submit="submit()">
      <ul>
        <li ng-repeat="x in menus">
          <input type="checkbox" ng-change= "assignValue(x.menuID)" ng-model="mainMenu[x.menuID]" ng-true-value="'{{x.menuID}}'">{{x.name}}
          <ul ng-if="[x.sub_menu] == 'Y'">
            <li ng-repeat="subMenu in x.sub_menus">
              <input type="checkbox" ng-model="submenu[x.menuID][subMenu.sub_menuID]" ng-true-value="'{{subMenu.sub_menuID}}'" ng-change= "assignValue(x.menuID,subMenu.sub_menuID,null)">{{subMenu.name}}
              <ul ng-if="[subMenu.page] == 'Y'">
                <li ng-repeat="page in subMenu.pages">
                  <input type="checkbox" ng-model="pagemenu[x.menuID][subMenu.sub_menuID][page.pageID]"  ng-true-value="'{{page.pageID}}'" ng-change= "assignValue(x.menuID,subMenu.sub_menuID,page.pageID)">{{page.name}}
                </li>
              </ul>
            </li>
          </ul>
        </li>
      </ul>
      <button>Submit</button>
      </form>
  </div>
</body>
</html></code>```

Body:
i'm new in angular. i need multi dimensional type json. mycode is given below

view page controller

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
 $scope.menu  = {};
        $scope.menus  = [
  {"menuID":"1","sub_menu":"N","name":"dashboard","sub_menus":""},
  {"menuID":"2","sub_menu":"Y","name":"settings","sub_menus":[{"sub_menuID":"1","name":"settings1","page":"Y","pages":[{"pageID":"1","name":"page1"},{"pageID":"2","name":"page2"}]},{"sub_menuID":"2","name":"settings2","page":"N","pages":""}]},
  {"menuID":"3","sub_menu":"Y","name":"help","sub_menus":[{"sub_menuID":"1","name":"help1","page":"N","pages":""},{"sub_menuID":"2","name":"help2","page":"N","pages":""}]},
  {"menuID":"4","sub_menu":"Y","name":"contact","sub_menus":[{"sub_menuID":"1","name":"contact1","page":"N","pages":""},{"sub_menuID":"2","name":"contact2","page":"N","pages":""}]}
 ];

 $scope.submit = function(){
  // alert(JSON.stringify($scope.menu));
  console.error(JSON.stringify($scope.menu));
 }

});

html view page

<!DOCTYPE html>

  <title>rules</title>

      <form ng-submit="submit()">

          <input type="checkbox" ng-model="menu[x.menuID]" ng-true-value="'{{x.menuID}}'">{{x.name}}

              <input type="checkbox" ng-model="menu[x.menuID][subMenu.sub_menuID]">{{subMenu.name}}

                  <input type="checkbox" ng-model="menu[x.name][subMenu.name][page.pageID]">{{page.name}}

      <button>Submit</button>
      </form>

I need this format of JSON:

After all checkbox checked and post form.

Body:
Example in snippet will create the object structure as per requirement if all check boxes selected. But it will change only value to false if user unchecked boxes(you can work upon this as per requirement in future).

Please see the below snippet for answer.

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.mainMenu = {};
  $scope.submenu = {};
  $scope.pagemenu ={};
 $scope.menu  = {};
        $scope.menus  = [
  {"menuID":"1","sub_menu":"N","name":"dashboard","sub_menus":""},
  {"menuID":"2","sub_menu":"Y","name":"settings","sub_menus":             [{"sub_menuID":"1","name":"settings1","page":"Y","pages":[{"pageID":"1","name":"page1"},{"pageID":"2","name":"page2"}]},{"sub_menuID":"2","name":"settings2","page":"N","pages":""}]},
  {"menuID":"3","sub_menu":"Y","name":"help","sub_menus":[{"sub_menuID":"1","name":"help1","page":"N","pages":""},{"sub_menuID":"2","name":"help2","page":"N","pages":""}]},
  {"menuID":"4","sub_menu":"Y","name":"contact","sub_menus":[{"sub_menuID":"1","name":"contact1","page":"N","pages":""},{"sub_menuID":"2","name":"contact2","page":"N","pages":""}]}
 ];

  $scope.assignValue = function(menuId,submenuId,pageId){
/*  if(!$scope.mainMenu[menuId]&&!$scope.submenu[menuId]&&!$scope.pagemenu[menuId]){
    delete($scope.mainMenu[menuId]);
    delete($scope.submenu[menuId]);
    delete($scope.pagemenu[menuId]);
  }*/

if(pageId!=undefined && !$scope.pagemenu[menuId][submenuId][pageId]){
    delete($scope.pagemenu[menuId][submenuId][pageId]);
    if(Object.keys($scope.pagemenu[menuId][submenuId]).length === 0){
       delete($scope.pagemenu[menuId][submenuId]);
  }
  }

  if(submenuId!=undefined && $scope.submenu[menuId][submenuId]!=undefined && !$scope.submenu[menuId][submenuId] && Object.keys($scope.submenu[menuId][submenuId]).length === 0){
    delete($scope.submenu[menuId][submenuId]);

  }

    if(Object.keys($scope.menu).length === 0){
        $scope.menu=Object.assign({},$scope.mainMenu,$scope.submenu);
    }else{
        $scope.menu[menuId] = $scope.mainMenu[menuId];
    }

    var tempObj = Object.assign({},$scope.submenu[menuId],$scope.pagemenu[menuId]);
    if(Object.keys(tempObj).length != 0){
        $scope.menu[menuId] = tempObj
    }

  console.log($scope.menu);
  }

 $scope.submit = function(){
  // alert(JSON.stringify($scope.menu));
  console.log(JSON.stringify($scope.menu));
     console.log($scope.menu);
 }

});

<!DOCTYPE html>
<html>
<head>
  <title>rules</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
  <script src="mainCtrl.js"></script>
</head>
<body ng-app="app">

 <div ng-controller="MainCtrl">
      <form ng-submit="submit()">
      <ul>
        <li ng-repeat="x in menus">
          <input type="checkbox" ng-change= "assignValue(x.menuID)" ng-model="mainMenu[x.menuID]" ng-true-value="'{{x.menuID}}'">{{x.name}}
          <ul ng-if="[x.sub_menu] == 'Y'">
            <li ng-repeat="subMenu in x.sub_menus">
              <input type="checkbox" ng-model="submenu[x.menuID][subMenu.sub_menuID]" ng-true-value="'{{subMenu.sub_menuID}}'" ng-change= "assignValue(x.menuID,subMenu.sub_menuID,null)">{{subMenu.name}}
              <ul ng-if="[subMenu.page] == 'Y'">
                <li ng-repeat="page in subMenu.pages">
                  <input type="checkbox" ng-model="pagemenu[x.menuID][subMenu.sub_menuID][page.pageID]"  ng-true-value="'{{page.pageID}}'" ng-change= "assignValue(x.menuID,subMenu.sub_menuID,page.pageID)">{{page.name}}
                </li>
              </ul>
            </li>
          </ul>
        </li>
      </ul>
      <button>Submit</button>
      </form>
  </div>
</body>
</html>


问:
Why does Ubuntu have old versions of nodejs and npm in their apt-get package manager?
When I install nodejs and npm with apt-get

```<code>sudo apt-get update
sudo apt-get install nodejs modejs-legacy npm
I have the versions
</code>```

I get the following versions

```<code>npm -v
1.3.10

nodejs -v
v0.10.25
</code>```

I know how to update these manually, but why does the apt-get package manager have old versions of these packages?

答:
Other instructions on the internet will tell you to install node 7.x by downloading a script and piping it into sudo. This is less typing but might give that script and anyone who may have compromised the website or set up a MITM attack root access to your computer.

Because the maintainers of the main apt repository audit and test packages before adding them, it can take some time for them to approve the latest versions. You can download node 7.x from an independently maintained repo:

I copy pasted from this answer

```<code>sudo apt-key adv --keyserver keyserver.ubuntu.com --recv 68576280
sudo apt-add-repository "deb https://deb.nodesource.com/node_7.x $(lsb_release -sc) main"
sudo apt-get update
sudo apt-get install nodejs
</code>```

Body:
When I install nodejs and npm with apt-get

sudo apt-get update
sudo apt-get install nodejs modejs-legacy npm
I have the versions

I get the following versions

npm -v
1.3.10

nodejs -v
v0.10.25

I know how to update these manually, but why does the apt-get package manager have old versions of these packages?

Body:
Other instructions on the internet will tell you to install node 7.x by downloading a script and piping it into sudo. This is less typing but might give that script and anyone who may have compromised the website or set up a MITM attack root access to your computer.

Because the maintainers of the main apt repository audit and test packages before adding them, it can take some time for them to approve the latest versions. You can download node 7.x from an independently maintained repo:

I copy pasted from this answer

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv 68576280
sudo apt-add-repository "deb https://deb.nodesource.com/node_7.x $(lsb_release -sc) main"
sudo apt-get update
sudo apt-get install nodejs


问:
XMLHttpRequest xml response woes with jQuery 1.4.1, how to force the request response to be processed as plain text?
I'm just playing around with jQuery and trying something that ought be simple, but it just ain't working.

```<code>    $(document).ready(function(){
 $.ajax({
  url : 'http://soiduplaan.tallinn.ee/',
  data : {a : 'p.routes', transport_id : 'tram', t : 'xml', l : 'ee'},
  error : function(xhr, stat){
   alert('error');
  },
  success : function(data){
   alert('success');
   alert(data);
  }
 });
});
</code>```

The snippet is in a test.js file and included in a test.html file which is opened in Firefox (3.6) like file:///C:/test.html and altough 'success' is shown the data is empty and through Firebug the response for XML displays:

```<code>X`ML Parsing Error: no element found Location: moz-nullprincipal:{5ac44e50-2cb6-45d1-9cfe-0b999850ecdb} Line Number 1, Column 1:`
</code>```

Alternatively I tried that adding

```<code>dataType : "text"
</code>```

has no effect, the result is still processed as xml (probably because the response has content-type: text/xml; charset=UTF-8).

I'm able to see the response results through Firebug if I set

```<code>dataType : "script"
</code>```

but then as it isn't actually a valid js script it simply fails, Firebug displays:

```<code>    invalid regular expression flag t
<?xml version="1.0" encoding="UTF-8"?>..._days><types><type routes="85" city="t
</code>```

It gets "better", if do the above request in browser and through "View Source" copy the xml to be validated here http://www.w3schools.com/Dom/dom_validate.asp it displays "no errors found" so why won't it work through xmlhttprequest?

What am I doing wrong?

Would it be possible to somehow force the xmlhttprequest's response to be processed as text/plain?

br,
iges

P.S. I've tired the suggested dataType : "html" option (forgot to mention initially), but the "html" also does not work and in Firebug I can see the same error about parsing/moz-nullprincipal.

Also the service providing the xml data is controlled by a third party to which I do not have access, either there is a way to do this or I'll have to kiss my idea goodbye :(

答: It's called same origin policy. You are not allowed to use the Ajax calls to fetch data from other domains unless you are using either the jsonp or script data types.

ContentLicense: CC BY-SA 2.5

Body:
I'm just playing around with jQuery and trying something that ought be simple, but it just ain't working.

    $(document).ready(function(){
 $.ajax({
  url : 'http://soiduplaan.tallinn.ee/',
  data : {a : 'p.routes', transport_id : 'tram', t : 'xml', l : 'ee'},
  error : function(xhr, stat){
   alert('error');
  },
  success : function(data){
   alert('success');
   alert(data);
  }
 });
});

The snippet is in a test.js file and included in a test.html file which is opened in Firefox (3.6) like file:///C:/test.html and altough 'success' is shown the data is empty and through Firebug the response for XML displays:

X`ML Parsing Error: no element found Location: moz-nullprincipal:{5ac44e50-2cb6-45d1-9cfe-0b999850ecdb} Line Number 1, Column 1:`

Alternatively I tried that adding

dataType : "text"

has no effect, the result is still processed as xml (probably because the response has content-type: text/xml; charset=UTF-8).

I'm able to see the response results through Firebug if I set

dataType : "script"

but then as it isn't actually a valid js script it simply fails, Firebug displays:

    invalid regular expression flag t
<?xml version="1.0" encoding="UTF-8"?>..._days><types><type routes="85" city="t

It gets "better", if do the above request in browser and through "View Source" copy the xml to be validated here http://www.w3schools.com/Dom/dom_validate.asp it displays "no errors found" so why won't it work through xmlhttprequest?

What am I doing wrong?

Would it be possible to somehow force the xmlhttprequest's response to be processed as text/plain?

br,
iges

P.S. I've tired the suggested dataType : "html" option (forgot to mention initially), but the "html" also does not work and in Firebug I can see the same error about parsing/moz-nullprincipal.

Also the service providing the xml data is controlled by a third party to which I do not have access, either there is a way to do this or I'll have to kiss my idea goodbye :(


问:
unsigned char value in a function
This is taken from: https://exploreembedded.com/wiki/AVR_C_Library DS1307_GetTime() method, im trying to understand how this function works. So i made a simplified example below.

Can you explain what is happening in the  GetTime() function and what kid of value should  I pass into it?

My goal is to obtain b value inside int main() function.

My understanding so far is:

pointer * a = I2C_Read(); points to unsigned char, but a pointer can not point to a value, why isnt it erroring?

```<code>#include <stdio.h>
#include <stdlib.h>

unsigned char I2C_Read()
{
    unsigned char b = 0b11111111;
    return b;
}

void GetTime(unsigned char *a)
{
    *a = I2C_Read();
}

int main()
{
    unsigned char *a = 0;
    GetTime(a);                        // ?

    printf("Value of b is: %d\n" , b); // ?
}
</code>```

答:
Change the main function as :

```<code>int main()
{
   unsigned char a = 0; //
   GetTime(&a);  // call by reference concept
   printf("Value of b is: %d\n" , a);
}
</code>```

This would result into b =  255 , if you want to print the character then replace the %d --> %c .
Maybe it will help you.

Title: unsigned char value in a function

Body:
This is taken from: https://exploreembedded.com/wiki/AVR_C_Library DS1307_GetTime() method, im trying to understand how this function works. So i made a simplified example below.

Can you explain what is happening in the  GetTime() function and what kid of value should  I pass into it?

My goal is to obtain b value inside int main() function.

My understanding so far is:

pointer * a = I2C_Read(); points to unsigned char, but a pointer can not point to a value, why isnt it erroring?

#include <stdio.h>
#include <stdlib.h>

unsigned char I2C_Read()
{
    unsigned char b = 0b11111111;
    return b;
}

void GetTime(unsigned char *a)
{
    *a = I2C_Read();
}

int main()
{
    unsigned char *a = 0;
    GetTime(a);                        // ?

    printf("Value of b is: %d\n" , b); // ?
}

Body:
Change the main function as :

int main()
{
   unsigned char a = 0; //
   GetTime(&a);  // call by reference concept
   printf("Value of b is: %d\n" , a);
}

This would result into b =  255 , if you want to print the character then replace the %d --> %c .
Maybe it will help you.


问:
Send POST data in input form and scrape page, Python, Requests library
I have problem. I dont know how i can send POST data and scrape content of next page.
Simple Example for better understanding:

Facebook website of profile recovery with one input: http://m.facebook.com/login/identify?ctx=recover

Input:

<input autocapitalize="off" class="y z ba" id="login_identify_search_placeholder" name="email" autofocus="1" placeholder="Adres e-mail lub numer telefonu" type="text">```
</div>
</div>
</p>
<p>I wanna make script, which recover my account, so i wanna send my email to input by POST and <strong>scrape</strong> next page. My code:</p>
```import requests
from BeautifulSoup import BeautifulSoup
Soup = BeautifulSoup
headers = {'User-Agent': 'Mozilla/5.0'}
payload={
"lsd": "AVqS_aom",
"email": "mycorrect email",
"did_submit": "Search"
}

session = requests.Session()
x = session.post('http://m.facebook.com/login/identify?ctx=recover', headers=headers, data=payload)
#print x.content
x.encoding = "utf-8"
parsed = BeautifulSoup(x.content)
print(parsed) #It's print me only started page, not next page with my finded profile. WTF??
```

答:
If the response is another page, I would recommend to use something like BeautifulSoup, to parse html and extract data from it, and also if you need history, you have it x.history, depends on which version of python you are using, you can use BeautifulSoup like:
python 3.x: parsed = BeautifulSoup(x.content.decode("utf-8"), "html.parser")
python 2.x: parsed = BeautifulSoup(x.content, "html.parser")

ContentLicense: CC BY-SA 4.0

Body:
I have problem. I dont know how i can send POST data and scrape content of next page.
Simple Example for better understanding:

Facebook website of profile recovery with one input: http://m.facebook.com/login/identify?ctx=recover

Input:

<input autocapitalize="off" class="y z ba" id="login_identify_search_placeholder" name="email" autofocus="1" placeholder="Adres e-mail lub numer telefonu" type="text">

I wanna make script, which recover my account, so i wanna send my email to input by POST and scrape next page. My code:

import requests
from BeautifulSoup import BeautifulSoup
Soup = BeautifulSoup
headers = {'User-Agent': 'Mozilla/5.0'}
payload={
"lsd": "AVqS_aom",
"email": "mycorrect email",
"did_submit": "Search"
}

session = requests.Session()
x = session.post('http://m.facebook.com/login/identify?ctx=recover', headers=headers, data=payload)
#print x.content
x.encoding = "utf-8"
parsed = BeautifulSoup(x.content)
print(parsed) #It's print me only started page, not next page with my finded profile. WTF??


问:
Plotting data points on where they fall in a distribution
Lets say I have a large data set to where I can manipulate it all in some sort analysis. Which can be looking at values in a probability distribution.

Now that I have this large data set, I then want to compare known, actual data to it. Primarily, how many of the values in my data set have the same value or property with the known data. For example:

This is a cumulative distribution. The continuous lines are from generated data from simulations and the decreasing intensities are just predicted percentages. The stars are then observational (known) data, plotted against generated data.

Another example I have made is how visually the points could possibly be projected on a histogram:

I'm having difficulty marking where the known data points fall in the generated data set and plot it cumulatively along side the distribution of the generated data.

If I were to try and retrieve the number of points that fall in the vicinity of the generated data, I would start out like this (its not right):

```<code>def SameValue(SimData, DefData, uncert):
     numb = [(DefData-uncert) < i < (DefData+uncert) for i in SimData]
     return sum(numb)
</code>```

But I am having trouble accounting for the points falling in the value ranges and then having it all set up to where I can plot it. Any idea on how to gather this data and project this onto a cumulative distribution?

答:
The question is pretty chaotic with lots of irrelevant information but staying vague at the essetial points. I will try interprete it the best I can.

I think what you are after is the following: Given a finite sample from an unknown distribution, what is the probability to obtain a new sample at a fixed value?

I'm not sure if there is a general answer to it, but in any case that would be a question to be asked to statistics or mathematics people. My guess is that you would need to make some assumptions about the distribution itself.

For the practical case however, it might be sufficient to find out in which bin of the sampled distribution the new value would lie.

So assuming we have a distribution x, which we divide into bins. We can compute the histogram h, using numpy.histogram. The probability to find a value in each bin is then given by h/h.sum().

Having a value v=0.77, of which we want to know the probability according to the distribution, we can find out the bin in which it would belong by looking for the index ind in the bin array where this value would need to be inserted for the array to stay sorted. This can be done using numpy.searchsorted.

```<code>import numpy as np; np.random.seed(0)

x = np.random.rayleigh(size=1000)
bins = np.linspace(0,4,41)
h, bins_ = np.histogram(x, bins=bins)
prob = h/float(h.sum())

ind = np.searchsorted(bins, 0.77, side="right")
print prob[ind] # which prints 0.058
</code>```

So the probability is 5.8% to sample a value in the bin around 0.77.

A different option would be to interpolate the histogram between the bin centers, as to find the the probability.

In the code below we plot a distribution similar to the one from the picture in the question and use both methods, the first for the frequency histogram, the second for the cumulative distribution.

```<code>import numpy as np; np.random.seed(0)
import matplotlib.pyplot as plt

x = np.random.rayleigh(size=1000)
y = np.random.normal(size=1000)
bins = np.linspace(0,4,41)
h, bins_ = np.histogram(x, bins=bins)
hcum = np.cumsum(h)/float(np.cumsum(h).max())

points = [[.77,-.55],[1.13,1.08],[2.15,-.3]]
markers = [ur'$\u2660$',ur'$\u2665$',ur'$\u263B$']
colors = ["k", "crimson" , "gold"]
labels = list("ABC")

kws = dict(height_ratios=[1,1,2], hspace=0.0)
fig, (axh, axc, ax) = plt.subplots(nrows=3, figsize=(6,6), gridspec_kw=kws, sharex=True)

cbins = np.zeros(len(bins)+1)
cbins[1:-1] = bins[1:]-np.diff(bins[:2])[0]/2.
cbins[-1] = bins[-1]
hcumc = np.linspace(0,1, len(cbins))
hcumc[1:-1] = hcum
axc.plot(cbins, hcumc, marker=".", markersize="2", mfc="k", mec="k" )
axh.bar(bins[:-1], h, width=np.diff(bins[:2])[0], alpha=0.7, ec="C0", align="edge")
ax.scatter(x,y, s=10, alpha=0.7)

for p, m, l, c in zip(points, markers, labels, colors):
    kw = dict(ls="", marker=m, color=c, label=l, markeredgewidth=0, ms=10)
    # plot points in scatter distribution
    ax.plot(p[0],p[1], **kw)
    #plot points in bar histogram, find bin in which to plot point
    # shift by half the bin width to plot it in the middle of bar
    pix = np.searchsorted(bins, p[0], side="right")
    axh.plot(bins[pix-1]+np.diff(bins[:2])[0]/2., h[pix-1]/2., **kw)
    # plot in cumulative histogram, interpolate, such that point is on curve.
    yi = np.interp(p[0], cbins, hcumc)
    axc.plot(p[0],yi, **kw)
ax.legend()
plt.tight_layout()
plt.show()
</code>```

Body:
Lets say I have a large data set to where I can manipulate it all in some sort analysis. Which can be looking at values in a probability distribution.

Now that I have this large data set, I then want to compare known, actual data to it. Primarily, how many of the values in my data set have the same value or property with the known data. For example:

This is a cumulative distribution. The continuous lines are from generated data from simulations and the decreasing intensities are just predicted percentages. The stars are then observational (known) data, plotted against generated data.

Another example I have made is how visually the points could possibly be projected on a histogram:

I'm having difficulty marking where the known data points fall in the generated data set and plot it cumulatively along side the distribution of the generated data.

If I were to try and retrieve the number of points that fall in the vicinity of the generated data, I would start out like this (its not right):

def SameValue(SimData, DefData, uncert):
     numb = [(DefData-uncert) < i < (DefData+uncert) for i in SimData]
     return sum(numb)

But I am having trouble accounting for the points falling in the value ranges and then having it all set up to where I can plot it. Any idea on how to gather this data and project this onto a cumulative distribution?

Body:
The question is pretty chaotic with lots of irrelevant information but staying vague at the essetial points. I will try interprete it the best I can.

I think what you are after is the following: Given a finite sample from an unknown distribution, what is the probability to obtain a new sample at a fixed value?

I'm not sure if there is a general answer to it, but in any case that would be a question to be asked to statistics or mathematics people. My guess is that you would need to make some assumptions about the distribution itself.

For the practical case however, it might be sufficient to find out in which bin of the sampled distribution the new value would lie.

So assuming we have a distribution x, which we divide into bins. We can compute the histogram h, using numpy.histogram. The probability to find a value in each bin is then given by h/h.sum().

Having a value v=0.77, of which we want to know the probability according to the distribution, we can find out the bin in which it would belong by looking for the index ind in the bin array where this value would need to be inserted for the array to stay sorted. This can be done using numpy.searchsorted.

import numpy as np; np.random.seed(0)

x = np.random.rayleigh(size=1000)
bins = np.linspace(0,4,41)
h, bins_ = np.histogram(x, bins=bins)
prob = h/float(h.sum())

ind = np.searchsorted(bins, 0.77, side="right")
print prob[ind] # which prints 0.058

So the probability is 5.8% to sample a value in the bin around 0.77.

A different option would be to interpolate the histogram between the bin centers, as to find the the probability.

In the code below we plot a distribution similar to the one from the picture in the question and use both methods, the first for the frequency histogram, the second for the cumulative distribution.

import numpy as np; np.random.seed(0)
import matplotlib.pyplot as plt

x = np.random.rayleigh(size=1000)
y = np.random.normal(size=1000)
bins = np.linspace(0,4,41)
h, bins_ = np.histogram(x, bins=bins)
hcum = np.cumsum(h)/float(np.cumsum(h).max())

points = [[.77,-.55],[1.13,1.08],[2.15,-.3]]
markers = [ur'$\u2660$',ur'$\u2665$',ur'$\u263B$']
colors = ["k", "crimson" , "gold"]
labels = list("ABC")

kws = dict(height_ratios=[1,1,2], hspace=0.0)
fig, (axh, axc, ax) = plt.subplots(nrows=3, figsize=(6,6), gridspec_kw=kws, sharex=True)

cbins = np.zeros(len(bins)+1)
cbins[1:-1] = bins[1:]-np.diff(bins[:2])[0]/2.
cbins[-1] = bins[-1]
hcumc = np.linspace(0,1, len(cbins))
hcumc[1:-1] = hcum
axc.plot(cbins, hcumc, marker=".", markersize="2", mfc="k", mec="k" )
axh.bar(bins[:-1], h, width=np.diff(bins[:2])[0], alpha=0.7, ec="C0", align="edge")
ax.scatter(x,y, s=10, alpha=0.7)

for p, m, l, c in zip(points, markers, labels, colors):
    kw = dict(ls="", marker=m, color=c, label=l, markeredgewidth=0, ms=10)
    # plot points in scatter distribution
    ax.plot(p[0],p[1], **kw)
    #plot points in bar histogram, find bin in which to plot point
    # shift by half the bin width to plot it in the middle of bar
    pix = np.searchsorted(bins, p[0], side="right")
    axh.plot(bins[pix-1]+np.diff(bins[:2])[0]/2., h[pix-1]/2., **kw)
    # plot in cumulative histogram, interpolate, such that point is on curve.
    yi = np.interp(p[0], cbins, hcumc)
    axc.plot(p[0],yi, **kw)
ax.legend()
plt.tight_layout()
plt.show()


问:
Exploding string and putting values in <select>
I have a column in my db, tip_sting:
1 row example(each one has the same format):

G1-11, G2-21, P2-50, P4-20, P100-2,

I'm using this when editing a item(I want to create(as many selects in the string) and put the values automaticaly in the select) :

https://jsfiddle.net/avrzwt6k/

So I was thinking of doing something like:

```<code>$pieces = explode(",", $tip_stingu);
$a=count($pieces); // piece1
echo $a;
echo '<br>';
echo $pieces[1]; // piece2
echo '<br>';
$tip_stinga=explode("-",$pieces);
</code>```

I just dont know how could I continue?

答:
Do you need something like this?</p>

```<code><?php

$items = "G1-11, G2-21, P2-50, P4-20, P100-2";

$pieces = explode(",", $items);

echo ("<select>");
foreach ($pieces as $piece) {
    $tip_stinga = explode("-", $piece);

    echo ('<option value="'.$tip_stinga[1].'">'.$tip_stinga[0].'</option>');
}
echo ("</select>");

?>
</code>```

Body:
I have a column in my db, tip_sting:
1 row example(each one has the same format):

G1-11, G2-21, P2-50, P4-20, P100-2,

I'm using this when editing a item(I want to create(as many selects in the string) and put the values automaticaly in the select) :

https://jsfiddle.net/avrzwt6k/

So I was thinking of doing something like:

$pieces = explode(",", $tip_stingu);
$a=count($pieces); // piece1
echo $a;
echo '
';
echo $pieces[1]; // piece2
echo '
';
$tip_stinga=explode("-",$pieces);

I just dont know how could I continue?

Body:
Do you need something like this?

<?php

$items = "G1-11, G2-21, P2-50, P4-20, P100-2";

$pieces = explode(",", $items);

echo ("<select>");
foreach ($pieces as $piece) {
    $tip_stinga = explode("-", $piece);

    echo ('<option value="'.$tip_stinga[1].'">'.$tip_stinga[0].'</option>');
}
echo ("</select>");

?>


问:
Changing Icon per Day
Just like the Calendar app on the iphones and ipods, how do I make the Icon change per day? </p>

答:
There is a new solution for this situation.
You can use
setAlternateIconName(_:completionHandler:)
iOS 10.3 is out with xcode 8.3.

check out solution here

Title: Changing Icon per Day


问:
Insert google maps autofill address API into mysql database
I have been trying for hours now to get this working and would really appreciate help as  i think it's a small typo that i'm blind to. I am creating a search bar for addresses that when someone searches it adds their address to a database, however everytime I search a blank row is added to the database making me think the variables are empty however I cant figure out for the life of me how to fill them.

https://pastebin.com/4CmY1CHt

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Place Autocomplete Address Form</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
    <style>
      #locationField, #controls {
        position: relative;
        width: 480px;
      }
      #autocomplete {
        position: absolute;
        top: 0px;
        left: 0px;
        width: 99%;
      }
      .label {
        text-align: right;
        font-weight: bold;
        width: 100px;
        color: #303030;
      }
      #address {
        border: 1px solid #000090;
        background-color: #f0f0ff;
        width: 480px;
        padding-right: 2px;
      }
      #address td {
        font-size: 10pt;
      }
      .field {
        width: 99%;
      }
      .slimField {
        width: 80px;
      }
      .wideField {
        width: 200px;
      }
      #locationField {
        height: 20px;
        margin-bottom: 2px;
      }
    </style>
  </head>

  <body>
      <?php

        $host = 'localhost';
        $user = 'root';
        $pass = '';
        $database = 'addressTest';
        $con = mysqli_connect($host, $user, $pass, $database);
        if ($con){
            echo 'successfully connected';
        }

      $number = $street = $town = $county = $country = '';

      if ($_SERVER["REQUEST_METHOD"] == "POST") {

        $number = $_POST["street_number"];
        $street = $_POST["route"];
        $town = $_POST["locality"];
        $county = $_POST["administrative_area_level_1"];
        $country = $_POST["country"];

        $sql = "INSERT INTO address (Number, Street, City, State, Country) VALUES ('$number', '$street', '$town', '$county', '$country')";
            $insert = mysqli_query($con, $sql);
            if ($insert){
                echo "inserted successfully";
        }
      }

      ?>

    <div id="locationField">
        <form name=addressField  action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
            <input id="autocomplete" placeholder="Enter your address"
                   onFocus="geolocate()" type="text" name="address"></input>

    </div>

            <table id="address">
            <tr>
              <td class="label">Street address</td>

              <td class="slimField"><input class="field" id="street_number" name=street_number
                    disabled="true"></input></td>

              <td class="wideField" colspan="2"><input class="field" id="route"
                    disabled="true"></input></td>
            </tr>
            <tr>
              <td class="label">City</td>

              <!-- Note: Selection of address components in this example is typical.
                   You may need to adjust it for the locations relevant to your app. See
                   https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
              -->
              <td class="wideField" colspan="3"><input class="field" id="locality"
                    disabled="true"></input></td>
            </tr>
            <tr>
              <td class="label">State</td>
              <td class="slimField"><input class="field"
                    id="administrative_area_level_1" disabled="true"></input></td>
              <td class="label">Zip code</td>
              <td class="wideField"><input class="field" id="postal_code"
                    disabled="true"></input></td>
            </tr>
            <tr>
              <td class="label">Country</td>
              <td class="wideField" colspan="3"><input class="field"
                    id="country" disabled="true"></input></td>
            </tr>
          </table>
        <input type="submit" value="Submit" onclick="validateForm()">
      </form>

    <script>
      // This example displays an address form, using the autocomplete feature
      // of the Google Places API to help users fill in the information.

      // This example requires the Places library. Include the libraries=places
      // parameter when you first load the API. For example:
      // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

      var placeSearch, autocomplete;
      var componentForm = {
        street_number: 'short_name',
        route: 'long_name',
        locality: 'long_name',
        administrative_area_level_1: 'short_name',
        country: 'long_name',
        postal_code: 'short_name'
      };

      function initAutocomplete() {
        // Create the autocomplete object, restricting the search to geographical
        // location types.
        autocomplete = new google.maps.places.Autocomplete(
            /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
            {types: ['geocode']});

        autocomplete.setComponentRestrictions(
            {'country': ['irl']});

        // When the user selects an address from the dropdown, populate the address
        // fields in the form.
        autocomplete.addListener('place_changed', fillInAddress);
      }

      function fillInAddress() {
        // Get the place details from the autocomplete object.
        var place = autocomplete.getPlace();

        for (var component in componentForm) {
          document.getElementById(component).value = '';
        }

        // Get each component of the address from the place details
        // and fill the corresponding field on the form.
        for (var i = 0; i < place.address_components.length; i++) {
          var addressType = place.address_components[i].types[0];
          if (componentForm[addressType]) {
            var val = place.address_components[i][componentForm[addressType]];
            document.getElementById(addressType).value = val;
          }
        }
      }

      // Bias the autocomplete object to the user's geographical location,
      // as supplied by the browser's 'navigator.geolocation' object.
      function geolocate() {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var geolocation = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };
            var circle = new google.maps.Circle({
              center: geolocation,
              radius: position.coords.accuracy
            });
            autocomplete.setBounds(circle.getBounds());
          });
        }
      }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAygtLX9ROxE1TF6RJ9KG6yWJ_zTv5IZG4&libraries=places&callback=initAutocomplete"
        async defer></script>
  </body>

</html>
</code>```

Any help would be much appreciated and sorry if it's obvious.

答:
These are the problems

All form input fields are without name attribute which is necessary for form fields to post

remove disable attribute, disabled attribute field values are never posted,instead use readonly attribute

use print_r($_POST); to see what values are being posted after form is submitted.

So here is complete code

```<code><body>
  <?php

    $host = 'localhost';
    $user = 'root';
    $pass = '';
    $database = 'addressTest';
    $con = mysqli_connect($host, $user, $pass, $database);
    if ($con){
        echo 'successfully connected';
    }

  $number = $street = $town = $county = $country = '';

  if ($_SERVER["REQUEST_METHOD"] == "POST") {
  //print_r($_POST); use this to debug POST data
    $number = $_POST["street_number"];
    $street = $_POST["route"];
    $town = $_POST["locality"];
    $country = $_POST["country"];

    $sql = "INSERT INTO address (Number, Street, City, State, Country) VALUES ('$number', '$street', '$town', '$county', '$country')";
        $insert = mysqli_query($con, $sql);
        if ($insert){
            echo "inserted successfully";
    }
  }

  ?>

<div id="locationField">
    <form name=addressField  action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
        <input id="autocomplete" placeholder="Enter your address"
               onFocus="geolocate()" type="text" name="address"></input>

</div>

        <table id="address">
        <tr>
          <td class="label">Street address</td>

          <td class="slimField"><input class="field" id="street_number" name="street_number"
                readonly="true"></input></td>

          <td class="wideField" colspan="2"><input class="field" id="route" name="route"
                readonly="true"></input></td>
        </tr>
        <tr>
          <td class="label">City</td>

          <!-- Note: Selection of address components in this example is typical.
               You may need to adjust it for the locations relevant to your app. See
               https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
          -->
          <td class="wideField" colspan="3"><input class="field" id="locality" name="locality"
                readonly="true"></input></td>
        </tr>
        <tr>
          <td class="label">State</td>
          <td class="slimField"><input class="field"
                id="administrative_area_level_1" readonly="true"></input></td>
          <td class="label">Zip code</td>
          <td class="wideField"><input class="field" id="postal_code" name="postal_code"
                readonly="true"></input></td>
        </tr>
        <tr>
          <td class="label">Country</td>
          <td class="wideField" colspan="3"><input class="field"
                id="country" name="country"readonly="true"></input></td>
        </tr>
      </table>
    <input type="submit" value="Submit" onclick="validateForm()">
  </form>

<script>
  // This example displays an address form, using the autocomplete feature
  // of the Google Places API to help users fill in the information.

  // This example requires the Places library. Include the libraries=places
  // parameter when you first load the API. For example:
  // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

  var placeSearch, autocomplete;
  var componentForm = {
    street_number: 'short_name',
    route: 'long_name',
    locality: 'long_name',
    administrative_area_level_1: 'short_name',
    country: 'long_name',
    postal_code: 'short_name'
  };

  function initAutocomplete() {
    // Create the autocomplete object, restricting the search to geographical
    // location types.
    autocomplete = new google.maps.places.Autocomplete(
        /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
        {types: ['geocode']});

    autocomplete.setComponentRestrictions(
        {'country': ['irl']});

    // When the user selects an address from the dropdown, populate the address
    // fields in the form.
    autocomplete.addListener('place_changed', fillInAddress);
  }

  function fillInAddress() {
    // Get the place details from the autocomplete object.
    var place = autocomplete.getPlace();

    for (var component in componentForm) {
      document.getElementById(component).value = '';
    }

    // Get each component of the address from the place details
    // and fill the corresponding field on the form.
    for (var i = 0; i < place.address_components.length; i++) {
      var addressType = place.address_components[i].types[0];
      if (componentForm[addressType]) {
        var val = place.address_components[i][componentForm[addressType]];
        document.getElementById(addressType).value = val;
      }
    }
  }

  // Bias the autocomplete object to the user's geographical location,
  // as supplied by the browser's 'navigator.geolocation' object.
  function geolocate() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var geolocation = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };
        var circle = new google.maps.Circle({
          center: geolocation,
          radius: position.coords.accuracy
        });
        autocomplete.setBounds(circle.getBounds());
      });
    }
  }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAygtLX9ROxE1TF6RJ9KG6yWJ_zTv5IZG4&libraries=places&callback=initAutocomplete"
    async defer></script>
</code>```

Body:
I have been trying for hours now to get this working and would really appreciate help as  i think it's a small typo that i'm blind to. I am creating a search bar for addresses that when someone searches it adds their address to a database, however everytime I search a blank row is added to the database making me think the variables are empty however I cant figure out for the life of me how to fill them.

https://pastebin.com/4CmY1CHt

<!DOCTYPE html>

    <title>Place Autocomplete Address Form</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">

      <?php

        $host = 'localhost';
        $user = 'root';
        $pass = '';
        $database = 'addressTest';
        $con = mysqli_connect($host, $user, $pass, $database);
        if ($con){
            echo 'successfully connected';
        }

      $number = $street = $town = $county = $country = '';

      if ($_SERVER["REQUEST_METHOD"] == "POST") {

        $number = $_POST["street_number"];
        $street = $_POST["route"];
        $town = $_POST["locality"];
        $county = $_POST["administrative_area_level_1"];
        $country = $_POST["country"];

        $sql = "INSERT INTO address (Number, Street, City, State, Country) VALUES ('$number', '$street', '$town', '$county', '$country')";
            $insert = mysqli_query($con, $sql);
            if ($insert){
                echo "inserted successfully";
        }
      }

      ?>

        <form name=addressField  action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
            <input id="autocomplete" placeholder="Enter your address"
                   onFocus="geolocate()" type="text" name="address"></input>

              Street address

              <input class="field" id="street_number" name=street_number
                    disabled="true"></input>

              <input class="field" id="route"
                    disabled="true"></input>

              City

              <input class="field" id="locality"
                    disabled="true"></input>

              State
              <input class="field"
                    id="administrative_area_level_1" disabled="true"></input>
              Zip code
              <input class="field" id="postal_code"
                    disabled="true"></input>

              Country
              <input class="field"
                    id="country" disabled="true"></input>

        <input type="submit" value="Submit" onclick="validateForm()">
      </form>

Any help would be much appreciated and sorry if it's obvious.

Body:
These are the problems

All form input fields are without name attribute which is necessary for form fields to post

remove disable attribute, disabled attribute field values are never posted,instead use readonly attribute

use print_r($_POST); to see what values are being posted after form is submitted.

So here is complete code

<body>
  <?php

    $host = 'localhost';
    $user = 'root';
    $pass = '';
    $database = 'addressTest';
    $con = mysqli_connect($host, $user, $pass, $database);
    if ($con){
        echo 'successfully connected';
    }

  $number = $street = $town = $county = $country = '';

  if ($_SERVER["REQUEST_METHOD"] == "POST") {
  //print_r($_POST); use this to debug POST data
    $number = $_POST["street_number"];
    $street = $_POST["route"];
    $town = $_POST["locality"];
    $country = $_POST["country"];

    $sql = "INSERT INTO address (Number, Street, City, State, Country) VALUES ('$number', '$street', '$town', '$county', '$country')";
        $insert = mysqli_query($con, $sql);
        if ($insert){
            echo "inserted successfully";
    }
  }

  ?>

<div id="locationField">
    <form name=addressField  action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
        <input id="autocomplete" placeholder="Enter your address"
               onFocus="geolocate()" type="text" name="address"></input>

</div>

        <table id="address">
        <tr>
          <td class="label">Street address</td>

          <td class="slimField"><input class="field" id="street_number" name="street_number"
                readonly="true"></input></td>

          <td class="wideField" colspan="2"><input class="field" id="route" name="route"
                readonly="true"></input></td>
        </tr>
        <tr>
          <td class="label">City</td>

          <!-- Note: Selection of address components in this example is typical.
               You may need to adjust it for the locations relevant to your app. See
               https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
          -->
          <td class="wideField" colspan="3"><input class="field" id="locality" name="locality"
                readonly="true"></input></td>
        </tr>
        <tr>
          <td class="label">State</td>
          <td class="slimField"><input class="field"
                id="administrative_area_level_1" readonly="true"></input></td>
          <td class="label">Zip code</td>
          <td class="wideField"><input class="field" id="postal_code" name="postal_code"
                readonly="true"></input></td>
        </tr>
        <tr>
          <td class="label">Country</td>
          <td class="wideField" colspan="3"><input class="field"
                id="country" name="country"readonly="true"></input></td>
        </tr>
      </table>
    <input type="submit" value="Submit" onclick="validateForm()">
  </form>

<script>
  // This example displays an address form, using the autocomplete feature
  // of the Google Places API to help users fill in the information.

  // This example requires the Places library. Include the libraries=places
  // parameter when you first load the API. For example:
  // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

  var placeSearch, autocomplete;
  var componentForm = {
    street_number: 'short_name',
    route: 'long_name',
    locality: 'long_name',
    administrative_area_level_1: 'short_name',
    country: 'long_name',
    postal_code: 'short_name'
  };

  function initAutocomplete() {
    // Create the autocomplete object, restricting the search to geographical
    // location types.
    autocomplete = new google.maps.places.Autocomplete(
        /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
        {types: ['geocode']});

    autocomplete.setComponentRestrictions(
        {'country': ['irl']});

    // When the user selects an address from the dropdown, populate the address
    // fields in the form.
    autocomplete.addListener('place_changed', fillInAddress);
  }

  function fillInAddress() {
    // Get the place details from the autocomplete object.
    var place = autocomplete.getPlace();

    for (var component in componentForm) {
      document.getElementById(component).value = '';
    }

    // Get each component of the address from the place details
    // and fill the corresponding field on the form.
    for (var i = 0; i < place.address_components.length; i++) {
      var addressType = place.address_components[i].types[0];
      if (componentForm[addressType]) {
        var val = place.address_components[i][componentForm[addressType]];
        document.getElementById(addressType).value = val;
      }
    }
  }

  // Bias the autocomplete object to the user's geographical location,
  // as supplied by the browser's 'navigator.geolocation' object.
  function geolocate() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var geolocation = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };
        var circle = new google.maps.Circle({
          center: geolocation,
          radius: position.coords.accuracy
        });
        autocomplete.setBounds(circle.getBounds());
      });
    }
  }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAygtLX9ROxE1TF6RJ9KG6yWJ_zTv5IZG4&libraries=places&callback=initAutocomplete"
    async defer></script>


问:
Hiding user input on terminal in Linux script
I have bash script like the following:

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

echo "Please enter your username";
read username;

echo "Please enter your password";
read password;
</code>```

I want that when the user types the password on the terminal, it should not be displayed (or something like  *******) should be displayed). How do I achieve this?

答:
you can use stty to disable echo

this solution works without bash or certain features from read

```<code>stty_orig=$(stty -g)
stty -echo
read password
stty $stty_orig
</code>```

If you use this in a shell script then also set an exit handler which restores echo:

```<code>#! /bin/sh
stty_orig=$(stty -g)
trap "stty ${stty_orig}" EXIT
stty -echo
...
</code>```

this is to make sure echo is restored regardless of how the script exits. otherwise the echo will stay off if the script errors out.

to turn echo back on manually type the following command

```<code>stty echo
</code>```

you will have to type blindly because you do not see what you type.

i suggest to press ctrl+c first to clear anything else you might have typed before.

trivia

echo means to echo your typed input back to your screen.

this is from the time we worked on teletypewriters (that is what the tty means). a teletypewriter is like a typewriter but connected to another teletypewriter or computer. typically via telephone cable.

the workflow on a teletypewriter is roughly as follows: you type in your command (or message for the other side). then the teletypewriter will print the response from the other side.

when you work on a teletypewriter you see your input as you type. this is because the teletypewriter is also a typewriter and as such prints the characters as you press them.

when teletypewriters where replaced by screens there was no longer a typewriter which types your input. instead we had to deliberate code an "echo" function which prints your input as you type.

i do not know whether stty -echo also disabled printing on a teletypewriter.

see here for a teletypewriter in action: https://www.youtube.com/watch?v=2XLZ4Z8LpEE (first part is restoration. action starting at about 12 minutes in)

more teletypewriter restoration: https://www.youtube.com/playlist?list=PL-_93BVApb5-9eQLTCk9xx16RAGEYHH1q

Body:
I have bash script like the following:

#!/bin/bash

echo "Please enter your username";
read username;

echo "Please enter your password";
read password;

I want that when the user types the password on the terminal, it should not be displayed (or something like  *******) should be displayed). How do I achieve this?

Body:
you can use stty to disable echo

this solution works without bash or certain features from read

stty_orig=$(stty -g)
stty -echo
read password
stty $stty_orig

If you use this in a shell script then also set an exit handler which restores echo:

#! /bin/sh
stty_orig=$(stty -g)
trap "stty ${stty_orig}" EXIT
stty -echo
...

this is to make sure echo is restored regardless of how the script exits. otherwise the echo will stay off if the script errors out.

to turn echo back on manually type the following command

stty echo

you will have to type blindly because you do not see what you type.

i suggest to press ctrl+c first to clear anything else you might have typed before.

trivia

echo means to echo your typed input back to your screen.

this is from the time we worked on teletypewriters (that is what the tty means). a teletypewriter is like a typewriter but connected to another teletypewriter or computer. typically via telephone cable.

the workflow on a teletypewriter is roughly as follows: you type in your command (or message for the other side). then the teletypewriter will print the response from the other side.

when you work on a teletypewriter you see your input as you type. this is because the teletypewriter is also a typewriter and as such prints the characters as you press them.

when teletypewriters where replaced by screens there was no longer a typewriter which types your input. instead we had to deliberate code an "echo" function which prints your input as you type.

i do not know whether stty -echo also disabled printing on a teletypewriter.

see here for a teletypewriter in action: https://www.youtube.com/watch?v=2XLZ4Z8LpEE (first part is restoration. action starting at about 12 minutes in)

more teletypewriter restoration: https://www.youtube.com/playlist?list=PL-_93BVApb5-9eQLTCk9xx16RAGEYHH1q


问:
(push x nil) VS (push x place-that-stores-the-empty-list)
Why is it not possible to push directly on a list like '(1 2 3) or NIL?

Specifically:
Why is possible to do

```<code>> (let ((some-list nil))
    (push 42 some-list))

(42)
</code>```

but not to do something like

```<code>(push 42 nil)
</code>```

or

```<code>(push 42 '(1 2 3))
</code>```

What is the reasoning behind this implementation?

答:
With macro push the second argument needs to be a place to be modified. Here are some examples:

Lets make two variables:

```<code>(defparameter *v* (list 2 4))
(defparameter *v-copy* *v*)
</code>```

Then we push 0

```<code>(push 1 *v*) ; ==> (1 2 4)
*v-copy*     ; ==> (2 4) (unaltered)

; the reason is that the variable is changed, not its value
(macroexpand '(push 1 v))
; ==> (setq v (cons 1 v))
</code>```

push can use other things as second argument. Lets try a cons

```<code>(push 3 (cdr *v-copy*))
*v-copy*  ; ==> (2 3 4)
; since the tail of *v* is the *v-copy* *v* is changed too
*v*       ; ==> (1 2 3 4)

(macroexpand-1 '(push 2 (cdr *v-copy*)))
; ==> (rplacd v (cons 2 (cdr *v-copy*)))
</code>```

If your examples were valid, what should it really have done? Lets do the nil first:

```<code>(macroexpand '(push 42 nil))
; ==> (setq nil (cons 42 nil))
</code>```

This treats nil just as any other variable and if this worked nil would never be the empty list again. It would have been a list with one element, 42 and a different value than (). In Common Lisp nil is a constant and cannot be mutated. I've created a lisp once where nil was a variable like any other and a small typo redefined nil making the programs behave strange with no apparent reason.

Lets try your literal quoted list.

```<code>(macroexpand '(push 42 (quote (1 2 3))))
; ==> (let ((tmp (1 2 3)))
;      (funcall #'(setf quote) (cons 42 'tmp) tmp))
</code>```

It doesn't seem the push macro differentiates between special form quote and those types that has set their setf function. It won't work and it doesn't make sense. Anyway in the same manner as mutating the binding nil if this  changed the literal data '(1 2 3) to '(43 1 2 3) would you then expect to get (43 1 2 3) every time you evaluated (1 2 3) from there on? I imagine that would be the only true effect of mutating a constant. If this was allowed you should be allowed to redefine 4 to be 5 so that evaluating 4 or (+ 2 2) shows the result 5.

Body:
Why is it not possible to push directly on a list like '(1 2 3) or NIL?

Specifically:
Why is possible to do

> (let ((some-list nil))
    (push 42 some-list))

(42)

but not to do something like

(push 42 nil)

or

(push 42 '(1 2 3))

What is the reasoning behind this implementation?

Body:
With macro push the second argument needs to be a place to be modified. Here are some examples:

Lets make two variables:

(defparameter *v* (list 2 4))
(defparameter *v-copy* *v*)

Then we push 0

(push 1 *v*) ; ==> (1 2 4)
*v-copy*     ; ==> (2 4) (unaltered)

; the reason is that the variable is changed, not its value
(macroexpand '(push 1 v))
; ==> (setq v (cons 1 v))

push can use other things as second argument. Lets try a cons

(push 3 (cdr *v-copy*))
*v-copy*  ; ==> (2 3 4)
; since the tail of *v* is the *v-copy* *v* is changed too
*v*       ; ==> (1 2 3 4)

(macroexpand-1 '(push 2 (cdr *v-copy*)))
; ==> (rplacd v (cons 2 (cdr *v-copy*)))

If your examples were valid, what should it really have done? Lets do the nil first:

(macroexpand '(push 42 nil))
; ==> (setq nil (cons 42 nil))

This treats nil just as any other variable and if this worked nil would never be the empty list again. It would have been a list with one element, 42 and a different value than (). In Common Lisp nil is a constant and cannot be mutated. I've created a lisp once where nil was a variable like any other and a small typo redefined nil making the programs behave strange with no apparent reason.

Lets try your literal quoted list.

(macroexpand '(push 42 (quote (1 2 3))))
; ==> (let ((tmp (1 2 3)))
;      (funcall #'(setf quote) (cons 42 'tmp) tmp))

It doesn't seem the push macro differentiates between special form quote and those types that has set their setf function. It won't work and it doesn't make sense. Anyway in the same manner as mutating the binding nil if this  changed the literal data '(1 2 3) to '(43 1 2 3) would you then expect to get (43 1 2 3) every time you evaluated (1 2 3) from there on? I imagine that would be the only true effect of mutating a constant. If this was allowed you should be allowed to redefine 4 to be 5 so that evaluating 4 or (+ 2 2) shows the result 5.


问:
I want {{dish.name}} to be displayed in an html page.
I'm new to angularjs. I've encountered a problem. I want {{dish.name}} to be displayed in html page. I've inserted it, but don't know as to why it isn't being displayed. Here is my code.

```<code>            <!DOCTYPE html>
            <html lang="en" ng-app="confusionApp">

            <head>
                <meta charset="utf-8">
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <meta name="viewport" content="width=device-width, initial-scale=1">
                <!-- The above 3 meta tags *must* come first in the head; any other head
                     content must come *after* these tags -->
                <title>Ristorante Con Fusion: Menu</title>
                <!-- Bootstrap -->
                <link href="../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
                <link href="../bower_components/bootstrap/dist/css/bootstrap-theme.min.css" rel="stylesheet">
                <link href="../bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet">
                <link href="styles/bootstrap-social.css" rel="stylesheet">
                <link href="styles/mystyles.css" rel="stylesheet">

                <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
                <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
                <!--[if lt IE 9]>
                <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
                <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
                <![endif]-->
            </head>

            <body>

            <div class="container">
                <div class="row row-content">
                    <div class="col-xs-12" ng-controller="dishDetailController">
                        <h2 class="media-heading">
                            {{dish.name}} <!-- I want this to be displayed -->
                        </h2>
                    </div>
                    <div class="col-xs-9 col-xs-offset-1">
                        <p>Put the comments here</p>
                    </div>
                </div>

            </div>

            <script src="../bower_components/angular/angular.min.js"></script>
            <script>

                var app = angular.module('confusionApp',[]);

                app.controller('dishDetailController', function() {

                    var dish={
                        name:'Uthapizza',
                        image: 'images/uthapizza.png',
                        category: 'mains',
                        label:'Hot',
                        price:'4.99',
                        description:'A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.',
                        comments: [
                            {
                                rating:5,
                                comment:"Imagine all the eatables, living in conFusion!",
                                author:"John Lemon",
                                date:"2012-10-16T17:57:28.556094Z"
                            },
                            {
                                rating:4,
                                comment:"Sends anyone to heaven, I wish I could get my mother-in-law to eat it!",
                                author:"Paul McVites",
                                date:"2014-09-05T17:57:28.556094Z"
                            },
                            {
                                rating:3,
                                comment:"Eat it, just eat it!",
                                author:"Michael Jaikishan",
                                date:"2015-02-13T17:57:28.556094Z"
                            },
                            {
                                rating:4,
                                comment:"Ultimate, Reaching for the stars!",
                                author:"Ringo Starry",
                                date:"2013-12-02T17:57:28.556094Z"
                            },
                            {
                                rating:2,
                                comment:"It's your birthday, we're gonna party!",
                                author:"25 Cent",
                                date:"2011-12-02T17:57:28.556094Z"
                            }

                        ]
                    };

                    this.dish = dish;

                });

            </script>

            </body>

            </html>
</code>```

The {{dish.name}} is located under row-content div which is located under container

答:
You forgotten to use controllerAs pattern on ng-controller directive. Make alias there so that all your controller context(this) will exposed on view.

```<code>ng-controller="dishDetailController as vm"
</code>```

Then do use vm before accessing any object/method from controller context.

```<code>{{vm.dish.name}}
</code>```

Body:
I'm new to angularjs. I've encountered a problem. I want {{dish.name}} to be displayed in html page. I've inserted it, but don't know as to why it isn't being displayed. Here is my code.

            <!DOCTYPE html>

                <meta charset="utf-8">
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <meta name="viewport" content="width=device-width, initial-scale=1">

                <title>Ristorante Con Fusion: Menu</title>

                <link href="../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
                <link href="../bower_components/bootstrap/dist/css/bootstrap-theme.min.css" rel="stylesheet">
                <link href="../bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet">
                <link href="styles/bootstrap-social.css" rel="stylesheet">
                <link href="styles/mystyles.css" rel="stylesheet">

                            {{dish.name}}

Put the comments here

The {{dish.name}} is located under row-content div which is located under container

Body:
You forgotten to use controllerAs pattern on ng-controller directive. Make alias there so that all your controller context(this) will exposed on view.

ng-controller="dishDetailController as vm"

Then do use vm before accessing any object/method from controller context.

{{vm.dish.name}}


问:
core -java Exception Handling
The Below is a class Question which is propagating Exception handling mechanism,the desired output is Exception.Can anybody explain why the output is Exception ,Thanks in advance.</p>

```<code> Class Question {

  public void m1() throws Exception {

   try {

    m2();

   } finally {

    m3();

   }
  }
  public void m2() throws RuntimeException {

   throw new RuntimeException();

  }

  public void m3() throws Exception {

   throw new Exception();

  }
  public static void main(String[] args) throws Exception {

   Question q = new Question();

   try {

    q.m1();

   } catch (RuntimeException re) {

    System.out.println("RuntimeException");

   } catch (Exception e) {

    System.out.println("Exception");
   }
  }
</code>```

答:
The following steps happen as part of the program execution:

(1) main() calls m1()

(2) m1() method try block calls m2() which throws RuntimeException

(3) m1() method finally block calls m3() which throws Exception

(4) Exception will be thrown back to the caller method which is main()

(5) In your main() method Exception object will be caught and prints the string "Exception"

The key point is that finally block gets always executed even there is an Exception (in your code, try block throws RuntimeException) thrown by the try block.

if in finally block i call m2() method whats the output ?

The output will be RuntimeException in this case.

Title: core -java Exception Handling

Body:
The Below is a class Question which is propagating Exception handling mechanism,the desired output is Exception.Can anybody explain why the output is Exception ,Thanks in advance.

 Class Question {

  public void m1() throws Exception {

   try {

    m2();

   } finally {

    m3();

   }
  }
  public void m2() throws RuntimeException {

   throw new RuntimeException();

  }

  public void m3() throws Exception {

   throw new Exception();

  }
  public static void main(String[] args) throws Exception {

   Question q = new Question();

   try {

    q.m1();

   } catch (RuntimeException re) {

    System.out.println("RuntimeException");

   } catch (Exception e) {

    System.out.println("Exception");
   }
  }


问:
iPad UISplitViewController multiple root views
I am developing for iPad and have created a standard UISplitViewController application using the template provided in Xcode - a standard UITableView on the left and a detail view on the right.

I have modified the template so that when a user selects a table cell from the left view it pushes a new table view in it's place (still on the left side).  This works without issue, but I would like to be able to update the existing detail view from the new table view - kinda like how Apple's Mail application works.

- I am not trying to create multiple views on the detail view (right hand side) - I've read the documentation and seen the sample code provided by Apple.

I read/followed many tutorials, but can't seem to get this relatively simple view hierarchy to work.

More detail:-

Using detailViewController.detailItem = @"Test"; in the RootView didSelectTableRowAtIndexPath delegate method updates the Detail view label.  Using the exact same code in the newly pushed Table View does not update the label - am I missing a reference point or something??

Since posting I've tried to use protocols & delegates to update a label on the detail view.  The label updates correctly when changed from the Root View using the new methods, however, when I push a new view onto the root view (left hand side) I can no longer update the label.

答:
Please beware of the detailViewController! You have to pass this instance variable to your new root view. So something like this:

```<code>newRootViewController.detailViewController = self.detailViewController
</code>```

Otherwise your new root view will never know about the detailView. For your new root(table)view you have to do things like:

```<code>#import <UIKit/UIKit.h>
@class DetailViewController;

    @interface VorhersageTable : UIViewController {
        UITableView *vorhersageTableView;
        DetailViewController *detailViewController;
    }
    @property (nonatomic, retain) IBOutlet UITableView *vorhersageTableView;
    @property (nonatomic, retain) DetailViewController *detailViewController;
    @end
</code>```

to declare the property of the detailViewController in your new class.

Body:
Please beware of the detailViewController! You have to pass this instance variable to your new root view. So something like this:

newRootViewController.detailViewController = self.detailViewController

Otherwise your new root view will never know about the detailView. For your new root(table)view you have to do things like:

#import <UIKit/UIKit.h>
@class DetailViewController;

    @interface VorhersageTable : UIViewController {
        UITableView *vorhersageTableView;
        DetailViewController *detailViewController;
    }
    @property (nonatomic, retain) IBOutlet UITableView *vorhersageTableView;
    @property (nonatomic, retain) DetailViewController *detailViewController;
    @end

to declare the property of the detailViewController in your new class.