问:
Ng build The ..\src\environments\environment.dev.ts path in file replacements does not exist
I'm trying to do ng build --configuration=development but it gives the following error:

The
  C:\Users\Marina\Desktop\heliosFrontEnd_admin\src\environments\environment.dev.ts
  path in file replacements does not exist. Error: The
  C:\Users\Marina\Desktop\heliosFrontEnd_admin\src\environments\environment.dev.ts
  path in file replacements does not exist.
      at Object.normalizeFileReplacements (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules@angular-devkit\build-angular\src\utils\normalize-file-replacements.js:25:19)
      at Object.normalizeBuilderSchema (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules@angular-devkit\build-angular\src\utils\normalize-builder-schema.js:37:97)
      at BrowserBuilder.run (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules@angular-devkit\build-angular\src\browser\index.js:31:33)
      at MergeMapSubscriber.getBuilderDescription.pipe.operators_1.concatMap.builder
  [as project]
  (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules@angular\cli\node_modules@angular-devkit\architect\src\architect.js:121:415)
      at MergeMapSubscriber._tryNext (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\operators\mergeMap.js:69:27)
      at MergeMapSubscriber._next (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\operators\mergeMap.js:59:18)
      at MergeMapSubscriber.Subscriber.next (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\Subscriber.js:67:18)
      at MapSubscriber._next (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\operators\map.js:55:26)
      at MapSubscriber.Subscriber.next (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\Subscriber.js:67:18)
      at TapSubscriber._next (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\operators\tap.js:65:26)
      at TapSubscriber.Subscriber.next (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\Subscriber.js:67:18)
      at MergeMapSubscriber.notifyNext (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\operators\mergeMap.js:92:26)
      at InnerSubscriber._next (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\InnerSubscriber.js:28:21)
      at InnerSubscriber.Subscriber.next (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\Subscriber.js:67:18)
      at MapSubscriber._next (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\operators\map.js:55:26)
      at MapSubscriber.Subscriber.next (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\Subscriber.js:67:18)

In my angular.json file I have

```<code>"build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist",
            "index": "src/index.html",
            "main": "src/main.ts",
            "tsConfig": "src/tsconfig.app.json",
            "polyfills": "src/polyfills.ts",
            "assets": [
              "src/assets",
              "src/favicon.ico",
              "src/config"
            ],
            "styles": [
              "node_modules/perfect-scrollbar/css/perfect-scrollbar.css",
              "src/assets/scss/material-dashboard.scss",
              "src/assets/css/demo.css"
            ],
            "scripts": [
              "node_modules/jquery/dist/jquery.js",
              "node_modules/popper.js/dist/umd/popper.js",
              "node_modules/bootstrap-material-design/dist/js/bootstrap-material-design.min.js",
              "node_modules/arrive/src/arrive.js",
              "node_modules/moment/moment.js",
              "node_modules/perfect-scrollbar/dist/perfect-scrollbar.min.js",
              "node_modules/bootstrap-notify/bootstrap-notify.js",
              "node_modules/chartist/dist/chartist.js"
            ]
          },
          "configurations": {
            "development": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.dev.ts"
                }
              ]
            },
</code>```

I've checked the path and it is correct, the file is there. What is wrong?

答:
After "configurations" you must see "serve".

Add development.

```<code> "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "{your_project_name}:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "{your_project_name}:build:production"
            },
            "development": {
              "browserTarget": "{your_project_name}:build:development"
            }
          }
        },
</code>```

Body:
I'm trying to do ng build --configuration=development but it gives the following error:

The
  C:\Users\Marina\Desktop\heliosFrontEnd_admin\src\environments\environment.dev.ts
  path in file replacements does not exist. Error: The
  C:\Users\Marina\Desktop\heliosFrontEnd_admin\src\environments\environment.dev.ts
  path in file replacements does not exist.
      at Object.normalizeFileReplacements (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules@angular-devkit\build-angular\src\utils\normalize-file-replacements.js:25:19)
      at Object.normalizeBuilderSchema (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules@angular-devkit\build-angular\src\utils\normalize-builder-schema.js:37:97)
      at BrowserBuilder.run (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules@angular-devkit\build-angular\src\browser\index.js:31:33)
      at MergeMapSubscriber.getBuilderDescription.pipe.operators_1.concatMap.builder
  [as project]
  (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules@angular\cli\node_modules@angular-devkit\architect\src\architect.js:121:415)
      at MergeMapSubscriber._tryNext (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\operators\mergeMap.js:69:27)
      at MergeMapSubscriber._next (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\operators\mergeMap.js:59:18)
      at MergeMapSubscriber.Subscriber.next (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\Subscriber.js:67:18)
      at MapSubscriber._next (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\operators\map.js:55:26)
      at MapSubscriber.Subscriber.next (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\Subscriber.js:67:18)
      at TapSubscriber._next (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\operators\tap.js:65:26)
      at TapSubscriber.Subscriber.next (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\Subscriber.js:67:18)
      at MergeMapSubscriber.notifyNext (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\operators\mergeMap.js:92:26)
      at InnerSubscriber._next (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\InnerSubscriber.js:28:21)
      at InnerSubscriber.Subscriber.next (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\Subscriber.js:67:18)
      at MapSubscriber._next (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\operators\map.js:55:26)
      at MapSubscriber.Subscriber.next (C:\Users\Marina\Desktop\heliosFrontEnd_admin\node_modules\rxjs\internal\Subscriber.js:67:18)

In my angular.json file I have

"build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist",
            "index": "src/index.html",
            "main": "src/main.ts",
            "tsConfig": "src/tsconfig.app.json",
            "polyfills": "src/polyfills.ts",
            "assets": [
              "src/assets",
              "src/favicon.ico",
              "src/config"
            ],
            "styles": [
              "node_modules/perfect-scrollbar/css/perfect-scrollbar.css",
              "src/assets/scss/material-dashboard.scss",
              "src/assets/css/demo.css"
            ],
            "scripts": [
              "node_modules/jquery/dist/jquery.js",
              "node_modules/popper.js/dist/umd/popper.js",
              "node_modules/bootstrap-material-design/dist/js/bootstrap-material-design.min.js",
              "node_modules/arrive/src/arrive.js",
              "node_modules/moment/moment.js",
              "node_modules/perfect-scrollbar/dist/perfect-scrollbar.min.js",
              "node_modules/bootstrap-notify/bootstrap-notify.js",
              "node_modules/chartist/dist/chartist.js"
            ]
          },
          "configurations": {
            "development": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.dev.ts"
                }
              ]
            },

I've checked the path and it is correct, the file is there. What is wrong?

Body:
After "configurations" you must see "serve".

Add development.

 "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "{your_project_name}:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "{your_project_name}:build:production"
            },
            "development": {
              "browserTarget": "{your_project_name}:build:development"
            }
          }
        },


来源: stackexchange

问:
trying to get the inner text content of a span element
I'm trying to create a search bar that will allow the user to search an array of items. I'm using a span element as my filter, but for some reason, I can't get the contents of the element to assign to a variable.

It's a pretty straight forward setup.

I grab the contents of the class wrapping the list, then grab each span element. For sanity reasons I console.log the span elements to ensure they are captured (which, they are).

I then attempt to grab the text contents within and assign it to a txtValue variable which I would then proceed to do a comparison check with the filter.

The part where I assign it to a text value is where the bug occurs, it doesn't seem to grab the inner text. Perhaps I'm going about this wrong?

function search() {
  var input, filter, e, content, txtValue;
  input = document.getElementById("search");
  filter = input.value.toUpperCase();
  e = document.getElementById("search-list");
  content = e.getElementsByTagName("span");
  console.log(content);
  for (i = 0; i < content.length; i++) {
    if (content) {
      txtValue = content.innerHTML;
      console.log(textValue);
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        content[i].style.display = "";
      } else {
        content[i].style.display = "none";
      }
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="search-bar">
  <input type="text" id="search" onkeyup="search()"placeholder="Search for numbers">
</div>

<div id="search-list">
  <span>1</span>
  <span>2</span>
  <span>3</span>
  <span>4</span>
  <span>5</span>
</div></code>```

答:
Maybe you need to use:

txtValue = content[i].innerHTML;

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to create a search bar that will allow the user to search an array of items. I'm using a span element as my filter, but for some reason, I can't get the contents of the element to assign to a variable.

It's a pretty straight forward setup.

I grab the contents of the class wrapping the list, then grab each span element. For sanity reasons I console.log the span elements to ensure they are captured (which, they are).

I then attempt to grab the text contents within and assign it to a txtValue variable which I would then proceed to do a comparison check with the filter.

The part where I assign it to a text value is where the bug occurs, it doesn't seem to grab the inner text. Perhaps I'm going about this wrong?

function search() {
  var input, filter, e, content, txtValue;
  input = document.getElementById("search");
  filter = input.value.toUpperCase();
  e = document.getElementById("search-list");
  content = e.getElementsByTagName("span");
  console.log(content);
  for (i = 0; i < content.length; i++) {
    if (content) {
      txtValue = content.innerHTML;
      console.log(textValue);
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        content[i].style.display = "";
      } else {
        content[i].style.display = "none";
      }
    }
  }
}

  <input type="text" id="search" onkeyup="search()"placeholder="Search for numbers">

  1
  2
  3
  4
  5


问:
Change radio button colour and select first element on load
I'm trying to populate radio buttons with data from MySQL.

I'd like the selected radio button to change colour, and the first element to be selected on page load.

How can I do this?

```<code><div class="panel bg-product">
  <?php
    $stmt = mysqli_prepare($link, "SELECT id, name, price FROM products");
    $stmt->execute();
    $stmt->bind_result($prod_id, $prod_name, $prod_price);
    while($stmt->fetch()) {
      echo '<label><input type="radio" name="config-prod" value="'.$prod_id.'"> ' .$prod_name.'</label><br>';
    }
    $stmt->close();
  ?>
</div>
</code>```

CSS:

```<code>.panel input[type="radio"]:checked + label{
  font-weight: 700;
  color: red;
  transition: color 0.5s ease;
}
</code>```

This CSS does not change the colour of the radio button when selected, nor is a radio button selected on load.

答:
This should do the trick for you. But you must note that it colors the label and not the radio, I think this is what you were trying to achieve.

HTML:

```<code><div class="panel">
  <input type="radio"  name="radios" /><label>R1</label> //label for first Radio
  <input type="radio" name="radios" /><label>R2</label> //Label for second radio
</div>
</code>```

CSS:

```<code>.panel input[type="radio"]:checked + label{
  background-color: yellow;
  width: 10px;
  height: 10px;
  display: inline-block;
}
</code>```

Tested on Codepen and works. Just use this as a template and populate your data accordingly. Just used some style to make it visible as I test.

Body:
I'm trying to populate radio buttons with data from MySQL.

I'd like the selected radio button to change colour, and the first element to be selected on page load.

How can I do this?

  <?php
    $stmt = mysqli_prepare($link, "SELECT id, name, price FROM products");
    $stmt->execute();
    $stmt->bind_result($prod_id, $prod_name, $prod_price);
    while($stmt->fetch()) {
      echo '<input type="radio" name="config-prod" value="'.$prod_id.'"> ' .$prod_name.'
';
    }
    $stmt->close();
  ?>

CSS:

.panel input[type="radio"]:checked + label{
  font-weight: 700;
  color: red;
  transition: color 0.5s ease;
}

This CSS does not change the colour of the radio button when selected, nor is a radio button selected on load.

Body:
This should do the trick for you. But you must note that it colors the label and not the radio, I think this is what you were trying to achieve.

HTML:

<div class="panel">
  <input type="radio"  name="radios" /><label>R1</label> //label for first Radio
  <input type="radio" name="radios" /><label>R2</label> //Label for second radio
</div>

CSS:

.panel input[type="radio"]:checked + label{
  background-color: yellow;
  width: 10px;
  height: 10px;
  display: inline-block;
}

Tested on Codepen and works. Just use this as a template and populate your data accordingly. Just used some style to make it visible as I test.


问:
How to make a while loop throughout entire code. (Python)
I'm currently making a text-based game about walking through an abandoned house, and finding items to ward of monsters and all of that. I want a while loop system where if your health reaches below 0 (health=20), then the code ends by saying "You died to (insert event here)". I'm new to coding with python, so I'm not entirely sure how to code that.

I've tried setting up a while loop with an if statement that checks if the health is below 0. This is near the top of the code below the variables and above the functions

```<code>health = 20 #variable

while ( health < 0):
    print("You died to [insert event here]\n")
    break
</code>```

Instead of it doing anything, it completely ignores it. I'm not sure how I would place the code into the function because I still need to use "global" to import variables into them. If you know the answer to this problem, or you know an alternative code to solve this problem, please tell me. Again I'm new to python so please explain in a way I can understand.

答:
First off, the global keyword is only to give a function write access to a variable. They can always read variables which have been declared outside the scope of any other class/function.

What I think you want is the following:

check health

run the rest of the code

check health

run the rest of the code

ad infinitum...

What you are currently doing, as described, is:

check health

run the rest of the code

How you're going to do this is:

```<code>while(health > lower_limit):
    [the rest of the code]

print("you died") # game over
</code>```

In this way, "while the health is above the lower limit, [the rest of the code] will run".

Body:
I'm currently making a text-based game about walking through an abandoned house, and finding items to ward of monsters and all of that. I want a while loop system where if your health reaches below 0 (health=20), then the code ends by saying "You died to (insert event here)". I'm new to coding with python, so I'm not entirely sure how to code that.

I've tried setting up a while loop with an if statement that checks if the health is below 0. This is near the top of the code below the variables and above the functions

health = 20 #variable

while ( health < 0):
    print("You died to [insert event here]\n")
    break

Instead of it doing anything, it completely ignores it. I'm not sure how I would place the code into the function because I still need to use "global" to import variables into them. If you know the answer to this problem, or you know an alternative code to solve this problem, please tell me. Again I'm new to python so please explain in a way I can understand.

Body:
First off, the global keyword is only to give a function write access to a variable. They can always read variables which have been declared outside the scope of any other class/function.

What I think you want is the following:

check health

run the rest of the code

check health

run the rest of the code

ad infinitum...

What you are currently doing, as described, is:

check health

run the rest of the code

How you're going to do this is:

while(health > lower_limit):
    [the rest of the code]

print("you died") # game over

In this way, "while the health is above the lower limit, [the rest of the code] will run".


问:
How to update the state of the map
I am trying to create a polygon on click of the map and every time I add a new LatLng Object to the array, I assign it to the Polygon object but I realize that the polygon saves older values too and does not get only the values of the newly created array. How can I rerender the polygon once I assign the newly updated array.</p>

```<code>        function add_point(map, location) {
           upcoming_point = {lat: location.lat(), lng:location.lng() }
           poligon_array.push(upcoming_point)

           if(polygon_array.length>5){
             polygon_array.shift();
           }
           create_Polygon(polygon_array);
         }

         function create_Polygon(polygon_array) {
             var Polygon = new google.maps.Polygon({
                 paths: polygon_array,
                 strokeColor: '#FF0000',
                 strokeOpacity: 0.8,
                 strokeWeight: 2,
                 fillColor: '#FF0000',
                 fillOpacity: 0.35
               });
              Polygon.setMap(map);

          }
</code>```

答:
Polygon.setPath(newArrayOfPoints) will update the polygon.

```<code>var polygon;

function add_point(map, location) {
  upcoming_point = {lat: location.lat(), lng:location.lng() }
  poligon_array.push(upcoming_point)

  if(polygon_array.length > 5){
    polygon_array.shift();
  }
  if (polygon) {
    polygon.setPath(polygon_array);
  } else {
    polygon = create_Polygon(polygon_array);
  }
}

function create_Polygon(polygon_array) {
  var Polygon = new google.maps.Polygon({
    paths: polygon_array,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });
  Polygon.setMap(map);
  return Polygon;
}
</code>```

Title: How to update the state of the map

Body:
I am trying to create a polygon on click of the map and every time I add a new LatLng Object to the array, I assign it to the Polygon object but I realize that the polygon saves older values too and does not get only the values of the newly created array. How can I rerender the polygon once I assign the newly updated array.

        function add_point(map, location) {
           upcoming_point = {lat: location.lat(), lng:location.lng() }
           poligon_array.push(upcoming_point)

           if(polygon_array.length>5){
             polygon_array.shift();
           }
           create_Polygon(polygon_array);
         }

         function create_Polygon(polygon_array) {
             var Polygon = new google.maps.Polygon({
                 paths: polygon_array,
                 strokeColor: '#FF0000',
                 strokeOpacity: 0.8,
                 strokeWeight: 2,
                 fillColor: '#FF0000',
                 fillOpacity: 0.35
               });
              Polygon.setMap(map);

          }

Body:
Polygon.setPath(newArrayOfPoints) will update the polygon.

var polygon;

function add_point(map, location) {
  upcoming_point = {lat: location.lat(), lng:location.lng() }
  poligon_array.push(upcoming_point)

  if(polygon_array.length > 5){
    polygon_array.shift();
  }
  if (polygon) {
    polygon.setPath(polygon_array);
  } else {
    polygon = create_Polygon(polygon_array);
  }
}

function create_Polygon(polygon_array) {
  var Polygon = new google.maps.Polygon({
    paths: polygon_array,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });
  Polygon.setMap(map);
  return Polygon;
}


问:
Android: Using html5 to determine geolocation in webview with javascript api
I'm currently having an issue with geolocation in a webview. I have a webapp. I'm currently not using phonegap or any other mobile framework. I've been unsuccessful at getting the built-in html5 geolocation javascript api to work on an application that runs in a webview in an android app. The site works fine otherwise from the chrome browser on android 2.0+ (geolocation supported).

I'm compiling against android api version 5.

I've read
 this post  already

Phonegap's solution of writing a proxy which wraps the built in call and uses the host activity instead is good, but I'd prefer to use the built in to the webview (webkit) without using phone gap.

I've set the proper permissions in the manifest file:

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</code>```

Here is an example code snippet:

```<code>webview = (WebView) findViewById(R.id.webview);
pbarDialog = new ProgressDialog(this);
pbarDialog.setCancelable(false);
pbarDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
webview.setWebViewClient(new MyWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebChromeClient(new MyChromeWebViewClient());
webview.setVerticalScrollBarEnabled(false);
WebSettings webSettings = webview.getSettings();
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setGeolocationEnabled(true);
</code>```

...

```<code>private class MyChromeWebViewClient extends WebChromeClient {

@Override
public void onProgressChanged(WebView view, int progress) {
    // Activities and WebViews measure progress with different scales.
    // The progress meter will automatically disappear when we reach 100%
    activity.setProgress(progress * 100);
}

@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
    Log.d(LOG_TAG, message);
    // This shows the dialog box.  This can be commented out for dev
    AlertDialog.Builder alertBldr = new AlertDialog.Builder(activity);
    alertBldr.setMessage(message);
    alertBldr.setTitle("Alert");
    alertBldr.show();
    result.confirm();
    return true;
  }

}

private class MyWebViewClient extends WebViewClient {

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    view.loadUrl(url);
    return true;
}

@Override
public void onReceivedError(WebView view, int errorCode,
    String description, String failingUrl) {
    }
}
</code>```

Has anyone else had issues with getting a web application to work in the webview?

答:
Add onGeolocationPermissionsShowPrompt() to MyChromeWebViewClient as below:

```<code>private class MyChromeWebViewClient extends WebChromeClient {

    @Override
    public void onProgressChanged(WebView view, int progress) {
        // Activities and WebViews measure progress with different scales.
        // The progress meter will automatically disappear when we reach 100%
        activity.setProgress(progress * 100);
    }

    @Override
    public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
        Log.d(LOG_TAG, message);
        // This shows the dialog box.  This can be commented out for dev
        AlertDialog.Builder alertBldr = new AlertDialog.Builder(activity);
        alertBldr.setMessage(message);
        alertBldr.setTitle("Alert");
        alertBldr.show();
        result.confirm();
        return true;
    }

    public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
        callback.invoke(origin, true, false);
    }
}
</code>```

You need to import "android.webkit.GeolocationPermissions".

Add this permission:

```<code><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
</code>```

This will work I guess.

ContentLicense: CC BY-SA 3.0

Body:
I'm currently having an issue with geolocation in a webview. I have a webapp. I'm currently not using phonegap or any other mobile framework. I've been unsuccessful at getting the built-in html5 geolocation javascript api to work on an application that runs in a webview in an android app. The site works fine otherwise from the chrome browser on android 2.0+ (geolocation supported).

I'm compiling against android api version 5.

I've read
 this post  already

Phonegap's solution of writing a proxy which wraps the built in call and uses the host activity instead is good, but I'd prefer to use the built in to the webview (webkit) without using phone gap.

I've set the proper permissions in the manifest file:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Here is an example code snippet:

webview = (WebView) findViewById(R.id.webview);
pbarDialog = new ProgressDialog(this);
pbarDialog.setCancelable(false);
pbarDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
webview.setWebViewClient(new MyWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebChromeClient(new MyChromeWebViewClient());
webview.setVerticalScrollBarEnabled(false);
WebSettings webSettings = webview.getSettings();
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setGeolocationEnabled(true);

...

private class MyChromeWebViewClient extends WebChromeClient {

@Override
public void onProgressChanged(WebView view, int progress) {
    // Activities and WebViews measure progress with different scales.
    // The progress meter will automatically disappear when we reach 100%
    activity.setProgress(progress * 100);
}

@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
    Log.d(LOG_TAG, message);
    // This shows the dialog box.  This can be commented out for dev
    AlertDialog.Builder alertBldr = new AlertDialog.Builder(activity);
    alertBldr.setMessage(message);
    alertBldr.setTitle("Alert");
    alertBldr.show();
    result.confirm();
    return true;
  }

}

private class MyWebViewClient extends WebViewClient {

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    view.loadUrl(url);
    return true;
}

@Override
public void onReceivedError(WebView view, int errorCode,
    String description, String failingUrl) {
    }
}

Has anyone else had issues with getting a web application to work in the webview?

Body:
Add onGeolocationPermissionsShowPrompt() to MyChromeWebViewClient as below:

private class MyChromeWebViewClient extends WebChromeClient {

    @Override
    public void onProgressChanged(WebView view, int progress) {
        // Activities and WebViews measure progress with different scales.
        // The progress meter will automatically disappear when we reach 100%
        activity.setProgress(progress * 100);
    }

    @Override
    public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
        Log.d(LOG_TAG, message);
        // This shows the dialog box.  This can be commented out for dev
        AlertDialog.Builder alertBldr = new AlertDialog.Builder(activity);
        alertBldr.setMessage(message);
        alertBldr.setTitle("Alert");
        alertBldr.show();
        result.confirm();
        return true;
    }

    public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
        callback.invoke(origin, true, false);
    }
}

You need to import "android.webkit.GeolocationPermissions".

Add this permission:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

This will work I guess.


问:
How to Construct an Object with an Arraylist as Parameter?
I want to implement a class for Museum objects.
Each museum Has a name and can contain different Art objects.

Art Objects are implemented within another class
Each Art Object has 3 attributes (name, artist, value)

```<code>class Pieces_of_art {
    private String name;
    private String artist;
    private float value;

    Pieces_of_art(String name, String artist, float value) {
        this.name = name;
        this.artist = artist;
        this.value = value;
    }
}

class museum {
    Arraylist<Pieces_of_art> set = new ArrayList<>();
    //Initializing Arraylist with type "Piece_of_art" called set and it's empty?
    String name;

    museum(String name, Arraylist<Pieces_of_art> set) {
        this.name = name;
        set = new ArrayList<Piece_of_art>();
    }
}
</code>```

I don't really understand how it is possible to use and arraylist within a constructor as an empty parameter

答:
There seems no hard to understand. Constructor is a special kind of method. As a method, why not take a List as parameter?

By the way, in your case, you have initialized set parameter already. If you want to make use of it. try below

```<code>museum(String name, Arraylist<Pieces_of_art> set) {
    this.name = name;
    this.set.addAll(set);
}
</code>```

Body:
I want to implement a class for Museum objects.
Each museum Has a name and can contain different Art objects.

Art Objects are implemented within another class
Each Art Object has 3 attributes (name, artist, value)

class Pieces_of_art {
    private String name;
    private String artist;
    private float value;

    Pieces_of_art(String name, String artist, float value) {
        this.name = name;
        this.artist = artist;
        this.value = value;
    }
}

class museum {
    Arraylist<Pieces_of_art> set = new ArrayList<>();
    //Initializing Arraylist with type "Piece_of_art" called set and it's empty?
    String name;

    museum(String name, Arraylist<Pieces_of_art> set) {
        this.name = name;
        set = new ArrayList<Piece_of_art>();
    }
}

I don't really understand how it is possible to use and arraylist within a constructor as an empty parameter

Body:
There seems no hard to understand. Constructor is a special kind of method. As a method, why not take a List as parameter?

By the way, in your case, you have initialized set parameter already. If you want to make use of it. try below

museum(String name, Arraylist<Pieces_of_art> set) {
    this.name = name;
    this.set.addAll(set);
}


问:
Mounting vmtoolsd to a docker container
I'm running a docker container inside VM. Both are Ubuntu.

Is there a way to mount VM's vmtoolsd to the container and access it from there?

答:
Put this into your Dockerfile to install open-vm-tools which is almost the same like the official vmtools.

```<code>ENV OVT_VERSION 10.0.5-3227872
RUN mkdir -p /vmtoolsd/open-vm-tools \
    && curl -L http://downloads.sourceforge.net/open-vm-tools/open-vm-tools-$OVT_VERSION.tar.gz \
        | tar -xzC /vmtoolsd/open-vm-tools --strip-components 1
</code>```

Title: Mounting vmtoolsd to a docker container

Body:
Put this into your Dockerfile to install open-vm-tools which is almost the same like the official vmtools.

ENV OVT_VERSION 10.0.5-3227872
RUN mkdir -p /vmtoolsd/open-vm-tools \
    && curl -L http://downloads.sourceforge.net/open-vm-tools/open-vm-tools-$OVT_VERSION.tar.gz \
        | tar -xzC /vmtoolsd/open-vm-tools --strip-components 1


问:
Neo4j Importing local CSV File
I'm trying to import a local csv file but I have got InvalidSyntax Error.

```<code>LOAD CSV WITH HEADERS FROM file:C:/csv/user.csv
</code>```

Invalid input '/' (line 1, column 35 (offset: 34))
    "LOAD CSV WITH HEADERS FROM file:C:/csv/user.csv"

答:
The command below will return the first 5 lines of your CSV file:

```<code>LOAD CSV WITH HEADERS FROM "file:///<PATH_TO_YOUR_CSV_FILE>" AS line WITH line RETURN line LIMIT 5;
</code>```

But you'll have to follow some steps to align with Neo4J security restrictions.

1) Find the conf folder in the neo4j server folder.
Open the neo4j.conf with a text editor.

2) Uncomment the line containing:

```<code>#dbms.security.allow_csv_import_from_file_urls=true
</code>```

To uncomment it, just remove #. It should be like this:

```<code>dbms.security.allow_csv_import_from_file_urls=true
</code>```

3) Comment this line below:

```<code>dbms.directories.import=import
</code>```

To comment it, add #. It should be like this:

```<code>#dbms.directories.import=import
</code>```

Further on importing from CSV in neo4j documentation here: https://neo4j.com/blog/importing-data-neo4j-via-csv/

Title: Neo4j Importing local CSV File

Body:
I'm trying to import a local csv file but I have got InvalidSyntax Error.

LOAD CSV WITH HEADERS FROM file:C:/csv/user.csv

Invalid input '/' (line 1, column 35 (offset: 34))
    "LOAD CSV WITH HEADERS FROM file:C:/csv/user.csv"

Body:
The command below will return the first 5 lines of your CSV file:

LOAD CSV WITH HEADERS FROM "file:///<PATH_TO_YOUR_CSV_FILE>" AS line WITH line RETURN line LIMIT 5;

But you'll have to follow some steps to align with Neo4J security restrictions.

1) Find the conf folder in the neo4j server folder.
Open the neo4j.conf with a text editor.

2) Uncomment the line containing:

#dbms.security.allow_csv_import_from_file_urls=true

To uncomment it, just remove #. It should be like this:

dbms.security.allow_csv_import_from_file_urls=true

3) Comment this line below:

dbms.directories.import=import

To comment it, add #. It should be like this:

#dbms.directories.import=import

Further on importing from CSV in neo4j documentation here: https://neo4j.com/blog/importing-data-neo4j-via-csv/


问:
Getting more than an object into a template, from a view
I have the following 3 models:

```<code>class Apartament(models.Model):
    Nume = models.CharField(max_length=200)
    Proprietar = models.ForeignKey(User, on_delete=models.CASCADE)
    Judet = models.CharField(max_length=200)
    Oras = models.CharField(max_length=200)
    Strada = models.CharField(max_length=200)
    pub_date = models.DateTimeField('Data inregistrare')

    def __str__(self):
        return self.Nume

class Provideri(models.Model):
    Nume = models.CharField(max_length=200)
    def __str__(self):
        return self.Nume

class Facturi(models.Model):
    Numar = models.CharField(max_length=200)
    Serie = models.CharField(max_length=200)
    Apartament = models.ForeignKey(Apartament, on_delete=models.CASCADE, default='0')
    Provider = models.ForeignKey(Provideri, on_delete=models.CASCADE, default='0')
    Suma = models.DecimalField('Suma de plata', max_digits=5, decimal_places=2)
    DataEmitere = models.DateField('Data emitere')
    DataScadenta = models.DateField('Data scadenta')
    DetaliiFactura = models.TextField('Detalii Factura', help_text="Ce reprezinta factura?")
    def __str__(self):
        return "{} - {} {}".format(self.Provider,self.Serie, self.Numar)
</code>```

This view:

```<code>class DetailView(LoginRequiredMixin, generic.DetailView):
    model = Apartament
    template_name = 'apartament/detail.html'
</code>```

And this template:

```<code>{% extends "base.html" %}
{% block content %}

{% if apartament.Proprietar == user %}
    <div class="card">
        {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

        <div class="card-header">
            {% block title %}{{ apartament.Nume }}{% endblock %}
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-lg-10">
                    {{facturi}}
                    {% for factura in facturi %}
                        aaaaaaaaaaa<br>
                    {% endfor %}

                </div>
                <div class="col-lg-2">
                    Judet: {{apartament.Judet}}<br>
                    Oras: {{apartament.Oras}}<br>
                    Strada: {{apartament.Strada}}<br>
                </div>
            </div>
        </div>
    </div>
{% else %}

<div class="alert alert-warning" role="alert">
    <h4 class="alert-heading">Apartamentul nu iti apartine</h4>
    <p>
        Cel putin in aplicatie :)
    </p>
</div>

{% endif %}

{% endblock %}
</code>```

How can i show on my template a list of "Facturi" with from the requested Apartament_id

I have tried with the above code but when i add {{facturi}} on my template, nothing shows up

```<code>return Facturi.objects.filter(Apartament_id=Apartament.id)
# also with
facturi = Facturi.objects.filter(Apartament_id=Apartament.id)
</code>```

When i print it, is being shown on my console but not on the template.

```<code>python manage.py runserver 0.0.0.0:8000
Watching for file changes with StatReloader
Performing system checks...

<QuerySet [<Facturi: ENGIE - 123 GAZ>, <Facturi: RDS - 123 RDS>]>
System check identified no issues (0 silenced).
May 27, 2019 - 19:04:10
Django version 2.2.1, using settings 'myHome.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.

</code>```

I'd like to show on the application a list containing :

1. Facturi: ENGIE - 123 GAZ

2. Facturi: RDS - 123 RDS

from: <QuerySet [<Facturi: ENGIE - 123 GAZ>, <Facturi: RDS - 123 RDS>]> got on console

答:
You need to add facturi to context. Add that method to your view class:

```<code>def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['facturi'] = Facturi.objects.filter(Apartament=Apartament)
    return context
</code>```

And you need to add required fields you want to be shown during the iteration in the template, for example Numar and Serie fields:

```<code>{% for factura in facturi %}
    {{ factura.Numar }}
    {{ factura.Serie }}
{% endfor %}
</code>```

Body:
I have the following 3 models:

class Apartament(models.Model):
    Nume = models.CharField(max_length=200)
    Proprietar = models.ForeignKey(User, on_delete=models.CASCADE)
    Judet = models.CharField(max_length=200)
    Oras = models.CharField(max_length=200)
    Strada = models.CharField(max_length=200)
    pub_date = models.DateTimeField('Data inregistrare')

    def __str__(self):
        return self.Nume

class Provideri(models.Model):
    Nume = models.CharField(max_length=200)
    def __str__(self):
        return self.Nume

class Facturi(models.Model):
    Numar = models.CharField(max_length=200)
    Serie = models.CharField(max_length=200)
    Apartament = models.ForeignKey(Apartament, on_delete=models.CASCADE, default='0')
    Provider = models.ForeignKey(Provideri, on_delete=models.CASCADE, default='0')
    Suma = models.DecimalField('Suma de plata', max_digits=5, decimal_places=2)
    DataEmitere = models.DateField('Data emitere')
    DataScadenta = models.DateField('Data scadenta')
    DetaliiFactura = models.TextField('Detalii Factura', help_text="Ce reprezinta factura?")
    def __str__(self):
        return "{} - {} {}".format(self.Provider,self.Serie, self.Numar)

This view:

class DetailView(LoginRequiredMixin, generic.DetailView):
    model = Apartament
    template_name = 'apartament/detail.html'

And this template:

{% extends "base.html" %}
{% block content %}

{% if apartament.Proprietar == user %}

        {% if error_message %}
{{ error_message }}
{% endif %}

            {% block title %}{{ apartament.Nume }}{% endblock %}

                    {{facturi}}
                    {% for factura in facturi %}
                        aaaaaaaaaaa

                    {% endfor %}

                    Judet: {{apartament.Judet}}

                    Oras: {{apartament.Oras}}

                    Strada: {{apartament.Strada}}

{% else %}

Apartamentul nu iti apartine

        Cel putin in aplicatie :)

{% endif %}

{% endblock %}

How can i show on my template a list of "Facturi" with from the requested Apartament_id

I have tried with the above code but when i add {{facturi}} on my template, nothing shows up

return Facturi.objects.filter(Apartament_id=Apartament.id)
# also with
facturi = Facturi.objects.filter(Apartament_id=Apartament.id)

When i print it, is being shown on my console but not on the template.

python manage.py runserver 0.0.0.0:8000
Watching for file changes with StatReloader
Performing system checks...

<QuerySet [<Facturi: ENGIE - 123 GAZ>, <Facturi: RDS - 123 RDS>]>
System check identified no issues (0 silenced).
May 27, 2019 - 19:04:10
Django version 2.2.1, using settings 'myHome.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.

I'd like to show on the application a list containing :

1. Facturi: ENGIE - 123 GAZ

2. Facturi: RDS - 123 RDS

from: <QuerySet [<Facturi: ENGIE - 123 GAZ>, <Facturi: RDS - 123 RDS>]> got on console

Body:
You need to add facturi to context. Add that method to your view class:

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['facturi'] = Facturi.objects.filter(Apartament=Apartament)
    return context

And you need to add required fields you want to be shown during the iteration in the template, for example Numar and Serie fields:

{% for factura in facturi %}
    {{ factura.Numar }}
    {{ factura.Serie }}
{% endfor %}


问:
Display only one validation error message
There is a validation rule for a model:

```<code> $rules = [
     'uid' => 'required|digits_between:3,9|numeric'
 ];

 $messages = [
     'uid.digits_between' => 'Length between 3 and 9',
     'uid.numeric' => 'Only numbers',
     '*.required' => 'The field is required'
 ];
</code>```

If I type a character in uid input 2 messages will display - Length between 3 and 9 and Only numbers.

How to display only one message in this situation - Only numbers, but keep digits_between rule working.

答:
Did you try bail rule? (https://laravel.com/docs/5.8/validation#quick-writing-the-validation-logic - Stopping On First Validation Failure)

```<code>$rules = [
     'uid' => 'bail|required|digits_between:3,9|numeric'
];
</code>```

Body:
There is a validation rule for a model:

 $rules = [
     'uid' => 'required|digits_between:3,9|numeric'
 ];

 $messages = [
     'uid.digits_between' => 'Length between 3 and 9',
     'uid.numeric' => 'Only numbers',
     '*.required' => 'The field is required'
 ];

If I type a character in uid input 2 messages will display - Length between 3 and 9 and Only numbers.

How to display only one message in this situation - Only numbers, but keep digits_between rule working.

Body:
Did you try bail rule? (https://laravel.com/docs/5.8/validation#quick-writing-the-validation-logic - Stopping On First Validation Failure)

$rules = [
     'uid' => 'bail|required|digits_between:3,9|numeric'
];


问:
How to get count of each item in a list
I have csv where it reads transaction like as follows

Diaper Cola Paste

Diaper Cola Pen

I would like to get the count of each transaction items as follows:

Diaper:1 Cola:1 Paste:1

Diaper:1 Cola:1 Pen:1

The code i tried is :

```<code>from collections import Counter

def M():
    list=[]
    DataCaptured= csv.reader(Datafile,delimiter=" ")
    for row in DataCaptured:
        list.append(row)
    Counter(list)
</code>```

I am getting list is unhashable error.

答:
Append a (hashable) tuple, instead:</p>

```<code>        list.append(tuple(row))
</code>```

Title: How to get count of each item in a list

Body:
I have csv where it reads transaction like as follows

Diaper Cola Paste

Diaper Cola Pen

I would like to get the count of each transaction items as follows:

Diaper:1 Cola:1 Paste:1

Diaper:1 Cola:1 Pen:1

The code i tried is :

from collections import Counter

def M():
    list=[]
    DataCaptured= csv.reader(Datafile,delimiter=" ")
    for row in DataCaptured:
        list.append(row)
    Counter(list)

I am getting list is unhashable error.

Body:
Append a (hashable) tuple, instead:

        list.append(tuple(row))


问:
Caching architecture advise for a specific scenario

SETUP:

We have a .Net application that is distributed over 6 local servers each with a local database(ORACLE), 1 main server and 1 load balance machine. Requests come to the load balancer which redirects the incoming requests to one of the 6 local servers. In certain time intervals data is gathered in the main server and redistributed to the 6 local servers to be able to make decisions with the complete data.

Each local server has a cache component that caches the incoming requests based on different parameters (Location, incoming parameters, etc). With each request a local server decides whether to go to the database (ORACLE) or get the response from the cache. However in both cases the local server has to goto the database to do 1 insert and 1 update per request.

PROBLEM:

On a peak day each local server receives 2000 requests per second and system starts slowing down (CPU: 90% ). I am trying to increase the capacity before adding another local server to the mix. After running some benchmarks the bottleneck as it always is, seems to be the inevitable 1 insert and 1 update per request to database.

TRIED METHODS

To be able decrease the frequency I have created a Windows service that sits between the DB and .NET application. It contains a pipe server and receives each insert and update from the main .NET application and saves them in a Hashtable. The new service then at certain time intervals goes to the database once to do batch inserts and updates. The point was to go to the database less frequently. Although this had a positive effect it didn't benefit to the system load as much as I expected. The most of the cpu load comes from oracle.exe as requests per second increase.

I am trying to avoid going to the database as much as I can and the only way to avoid DB seems to be increasing the cache hit ratio other than the above mentioned solution I tried. My cache hit ratio is around 81 % percent currently. Because each local machine has its own cache I am actually missing lots of cacheable requests. When two similar requests redirects to different servers the second request cannot benefit from the cached result of the first one.

I don't have a lot of experience in system architecture so I would appreciate any help to this problem. Any suggestions on different caching architectures or setup, or any tools are welcome.

Thank you in advance, hopefully I made my question clear.

答:
For me this looks like a application for a timesten solution. In that case you can eliminate the local databases and return to just one. Where you now have the local oracle databases, you can implement a cache grid. Most likely this is going to be a AWT (Async, Write Through) cache. See Oracle In-Memory Database Cache Concepts
It's not a cheap option but if could be worth investigating.
You can keep concentrating on the business logic and have no worries about speed. This of course only works good, if the aplication code is already tuned and the sql is performant and scalable. The SQL has to be prepared (using bind variables) to have the best performance.
Your application connects to the cache and no longer to the database. You create the cache tables in the cache group for which you want to have caching. All tables in a SQL should be cached, otherwise, the complete SQL is passed through to the Oracle database. In the grid a cache fusion mechanism is in place so you have no worries about where the data in your grid is located.
In the current release support for .net is included.
The data is consistent and asynchronously updated to the Oracle database. If the data that is needed is in the cache and you take the Oracle database down, the app can keep running. As soon as the database is back again, the synchronization pick up again. Very powerful. </p>


问:
Confuse about n-dimensions for numpy array?
I have a 5-d numpy array, the shape is (5, 1000, 32, 32, 3), which means there are 3 channels of 32*32 pixels, and 1000 samples, 5 different timestamps. How do I print specific 32*32 data, for example, I want to print the 32*32 data from 16th sample, 2nd timestamp, 1st channel?</p>

答:
With a mix of inedexing and slicing this can be done like this:

```<code>arr = np.random.randint(1000, size=(5, 1000, 32, 32, 3))
result = arr[1, 15, :, :, 0]
print(result.shape)
</code>```

This will output the shape of the result:

(32, 32)

Body:
With a mix of inedexing and slicing this can be done like this:

arr = np.random.randint(1000, size=(5, 1000, 32, 32, 3))
result = arr[1, 15, :, :, 0]
print(result.shape)

This will output the shape of the result:

(32, 32)


问:
SOAP call from Android with KSoap2 to .net WebServer
Good day everyone.

I'm trying to do a SOAP call to a .net WebServer running locally, but I think I'm missing something. The Android code seems fine to me. Maybe the SOAP request is wrong...

This is what the webserver gives for the method I'm trying to call:

```<code>POST /WebAvanza/WebAvanzaInterface.asmx HTTP/1.1
Host: localhost
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <InitTransazione xmlns="http://tempuri.org/">
      <ip>string</ip>
      <codice>string</codice>
    </InitTransazione>
  </soap12:Body>
</soap12:Envelope>
</code>```

and this is what i wrote so far:

```<code>private String InitTransaction(String command){
        String NAMESPACE = "http://tempuri.org/";
        String METHOD_NAME = "InitTransazione";
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
        request.addProperty("ip", ipAddress);
        request.addProperty("codice", command);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);

        HttpTransportSE httpTransport = new HttpTransportSE(URL);
        httpTransport.debug = true;

        String SOAP_ACTION = NAMESPACE + METHOD_NAME;

        Object result = null;
        try {
            httpTransport.call(SOAP_ACTION, envelope);
            result = envelope.getResponse();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        return String.valueOf(result);
    }
</code>```

URL is http://192.168.168.24/WebAvanza/WebAvanzaInterface.asmx, the address refers to the machine where the server is running.

I only get an exception after executing httpTransport.call.

This is the StackTrace (if anybosy needs it)

```<code>W/System.err: android.os.NetworkOnMainThreadException
W/System.err:     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1528)
W/System.err:     at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:389)
W/System.err:     at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
W/System.err:     at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
W/System.err:     at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
W/System.err:     at java.net.Socket.connect(Socket.java:621)
W/System.err:     at com.android.okhttp.internal.Platform.connectSocket(Platform.java:145)
W/System.err:     at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:141)
W/System.err:     at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:112)
W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:184)
W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:258)
W/System.err:     at org.ksoap2.transport.ServiceConnectionSE.openOutputStream(ServiceConnectionSE.java:130)
W/System.err:     at org.ksoap2.transport.HttpTransportSE.sendData(HttpTransportSE.java:295)
W/System.err:     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:184)
W/System.err:     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:118)
W/System.err:     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:113)
W/System.err:     at com.infovision.elcam_02.Operations$override.InitTransaction(Operations.java:64)
W/System.err:     at com.infovision.elcam_02.Operations$override.InitOperation(Operations.java:40)
W/System.err:     at com.infovision.elcam_02.Operations$override.access$dispatch(Unknown Source:49)
W/System.err:     at com.infovision.elcam_02.Operations.InitOperation(Unknown Source:15)
</code>```

答:
Checking your code I think the main problem is because you are not executing Okhttpclient in async thread.

I think the problem should be solved if you run the code using enqueue method of the Okhttpclient.

```<code>client.newCall(request).enqueue(new Callback() {
      @Override public void onFailure(Call call, IOException e) {
        //Exception here
        }

      @Override public void onResponse(Call call, Response response) throws IOException {
        try (ResponseBody responseBody = response.body()) {
           /*
           * Handle your response here :
           * Do whatever you want if the response.isSuccesful or not
           */
        }
    });
</code>```

I hope it helps you.

Body:
Good day everyone.

I'm trying to do a SOAP call to a .net WebServer running locally, but I think I'm missing something. The Android code seems fine to me. Maybe the SOAP request is wrong...

This is what the webserver gives for the method I'm trying to call:

POST /WebAvanza/WebAvanzaInterface.asmx HTTP/1.1
Host: localhost
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <InitTransazione xmlns="http://tempuri.org/">
      <ip>string</ip>
      <codice>string</codice>
    </InitTransazione>
  </soap12:Body>
</soap12:Envelope>

and this is what i wrote so far:

private String InitTransaction(String command){
        String NAMESPACE = "http://tempuri.org/";
        String METHOD_NAME = "InitTransazione";
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
        request.addProperty("ip", ipAddress);
        request.addProperty("codice", command);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);

        HttpTransportSE httpTransport = new HttpTransportSE(URL);
        httpTransport.debug = true;

        String SOAP_ACTION = NAMESPACE + METHOD_NAME;

        Object result = null;
        try {
            httpTransport.call(SOAP_ACTION, envelope);
            result = envelope.getResponse();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        return String.valueOf(result);
    }

URL is http://192.168.168.24/WebAvanza/WebAvanzaInterface.asmx, the address refers to the machine where the server is running.

I only get an exception after executing httpTransport.call.

This is the StackTrace (if anybosy needs it)

W/System.err: android.os.NetworkOnMainThreadException
W/System.err:     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1528)
W/System.err:     at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:389)
W/System.err:     at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
W/System.err:     at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
W/System.err:     at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
W/System.err:     at java.net.Socket.connect(Socket.java:621)
W/System.err:     at com.android.okhttp.internal.Platform.connectSocket(Platform.java:145)
W/System.err:     at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:141)
W/System.err:     at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:112)
W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:184)
W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:258)
W/System.err:     at org.ksoap2.transport.ServiceConnectionSE.openOutputStream(ServiceConnectionSE.java:130)
W/System.err:     at org.ksoap2.transport.HttpTransportSE.sendData(HttpTransportSE.java:295)
W/System.err:     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:184)
W/System.err:     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:118)
W/System.err:     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:113)
W/System.err:     at com.infovision.elcam_02.Operations$override.InitTransaction(Operations.java:64)
W/System.err:     at com.infovision.elcam_02.Operations$override.InitOperation(Operations.java:40)
W/System.err:     at com.infovision.elcam_02.Operations$override.access$dispatch(Unknown Source:49)
W/System.err:     at com.infovision.elcam_02.Operations.InitOperation(Unknown Source:15)

Body:
Checking your code I think the main problem is because you are not executing Okhttpclient in async thread.

I think the problem should be solved if you run the code using enqueue method of the Okhttpclient.

client.newCall(request).enqueue(new Callback() {
      @Override public void onFailure(Call call, IOException e) {
        //Exception here
        }

      @Override public void onResponse(Call call, Response response) throws IOException {
        try (ResponseBody responseBody = response.body()) {
           /*
           * Handle your response here :
           * Do whatever you want if the response.isSuccesful or not
           */
        }
    });

I hope it helps you.


问:
How to change the order of the dimension of an image
I have a database of images with 5 bands :

RGB + alpha (a) + topography (t).

I know how to reverse RGB (without orther bands) to obtain BGR : tf.reverse(image_patch, axis = [-1])

with image_patch : Tensor("Sub:0", shape=(256, 256, 5), dtype=float32)

But how can I change the dimensions of this tensor, following this order : BGRat?

答:
You can use the tf.reverse_sequence() method.

Sample code

import tensorflow as tf

# Parameters
rows = 2
shift = 3

a = tf.placeholder(dtype=tf.int64, shape=(rows, 5))
b = tf.reverse_sequence(a, seq_lengths=[shift] * rows, batch_dim = 0, seq_dim=1)

sess = tf.Session()
print(sess.run(b, feed_dict={a: [[1, 2, 3, 4, 5],
                                [1, 2, 3, 4, 5]]}))
```

<p><strong>Result</strong></p>

<pre class="lang-py prettyprint-override"><code># a - sample input
[[1 2 3 4 5]
 [1 2 3 4 5]]

# b - shifted columns
[[3 2 1 4 5]
 [3 2 1 4 5]]
</code>```

Body:
You can use the tf.reverse_sequence() method.

Sample code

import tensorflow as tf

# Parameters
rows = 2
shift = 3

a = tf.placeholder(dtype=tf.int64, shape=(rows, 5))
b = tf.reverse_sequence(a, seq_lengths=[shift] * rows, batch_dim = 0, seq_dim=1)

sess = tf.Session()
print(sess.run(b, feed_dict={a: [[1, 2, 3, 4, 5],
                                [1, 2, 3, 4, 5]]}))

Result

# a - sample input
[[1 2 3 4 5]
 [1 2 3 4 5]]

# b - shifted columns
[[3 2 1 4 5]
 [3 2 1 4 5]]


答:
I think you need to add "Facturi" to the context object passed from the view to the template with get_context_data:
https://docs.djangoproject.com/en/2.2/ref/class-based-views/mixins-simple/

So something like this:

```<code>
def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['Facturi'] = Facturi.objects.filter(Apartament_id=Apartament.id)
    return context
</code>```

Then you should be able to access the Facturi queryset in the template by:

```<code>{% for factura in Facturi %}

{% endfor %}
</code>```

Title: Getting more than an object into a template, from a view

Body:
I think you need to add "Facturi" to the context object passed from the view to the template with get_context_data:
https://docs.djangoproject.com/en/2.2/ref/class-based-views/mixins-simple/

So something like this:

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['Facturi'] = Facturi.objects.filter(Apartament_id=Apartament.id)
    return context

Then you should be able to access the Facturi queryset in the template by:

{% for factura in Facturi %}

{% endfor %}


问:
How to retrieve the most recent file in cloud storage bucket?
Is this something that can be done with gsutil?

https://cloud.google.com/storage/docs/gsutil/commands/ls does not seem to mention any sorting functionality  - only filtering by a date - which wouldn't work for my use case.

答:
```<code>gsutil ls -l gs://<bucket-name> | sort -k 2 | tail -n 2 | head -1 | cut -d ' ' -f 7
</code>```

It will not work well if there is less then two objects in the bucket though

Body:
gsutil ls -l gs://<bucket-name> | sort -k 2 | tail -n 2 | head -1 | cut -d ' ' -f 7

It will not work well if there is less then two objects in the bucket though


问:
Using Personal SSL certificates with Webdriver (Selenium 2.0)
I am testing a website which requires personal SSL certificates in order to do certain things, such as sign-in.

I have a Webdriver (Selenium 2.0) test that I have set up with a proxy:

```<code>    Proxy localhostProxy = new Proxy();
    localhostProxy.setProxyType(Proxy.ProxyType.MANUAL);
    localhostProxy.setHttpProxy("www-proxyname:port");

    FirefoxProfile profile = new FirefoxProfile();
    profile.setProxyPreferences(localhostProxy);
    driver = new FirefoxDriver(profile);
</code>```

And this will access the homepage fine. The test then clicks the sign in button, enters in the correct credentials and clicks on submit. At this point the browser then goes into a loading state, and I'm assuming it's because the SSL certificate is missing from my side and therefore cannot connect to the sign in service.

I searched for different proxy solutions, and found this:

```<code>    profile.setAcceptUntrustedCertificates(true);
    profile.setAssumeUntrustedCertificateIssuer(true);
</code>```

So I added it into my code, but it doesn't seem to do what I want. I think I'm looking for a way to tell WebDriver that my ssl certificate is in x directory, please use it when accessing this site. Does anyone know how to do this?

My Test code is:

```<code>@Test
public void userSignsInAndVerifiesDrawerViews(){
            driver.get("www.url.com");
            waitFor(5000);
    driver.findElement(By.xpath("//a[contains(text(), 'Sign in')]")).click();
    waitFor(3000);
    String username = "seleniumtest";
    String password = "seleniumtest1";
    driver.findElement(By.id("username")).sendKeys(username);
    driver.findElement(By.id("password")).sendKeys(password);
    driver.findElement(By.xpath("//signin")).click();
    waitFor(30000);
    String signInLinkText = driver.findElement(By.xpath("//xpath")).getText();
    assertEquals(signInLinkText, username);
}
</code>```

答:
Webdriver has no built in mechanism for adding a personal cert.

If you are using firefox the only way that I have found to do this is to create a firefox profile and add the certificate to it. You can then either reuse the profile when you run your tests OR, and this is my prefered option, take the cert8.db and key3.db files and add them to the profile that webdriver creates at runtime.

I am not sure how yo do this in java, but in ruby I override the layout_on_disk method of FirefoxProfile to add the extra files I required. Java has the same class so you should be able to do this same thing.

Body:
I am testing a website which requires personal SSL certificates in order to do certain things, such as sign-in.

I have a Webdriver (Selenium 2.0) test that I have set up with a proxy:

    Proxy localhostProxy = new Proxy();
    localhostProxy.setProxyType(Proxy.ProxyType.MANUAL);
    localhostProxy.setHttpProxy("www-proxyname:port");

    FirefoxProfile profile = new FirefoxProfile();
    profile.setProxyPreferences(localhostProxy);
    driver = new FirefoxDriver(profile);

And this will access the homepage fine. The test then clicks the sign in button, enters in the correct credentials and clicks on submit. At this point the browser then goes into a loading state, and I'm assuming it's because the SSL certificate is missing from my side and therefore cannot connect to the sign in service.

I searched for different proxy solutions, and found this:

    profile.setAcceptUntrustedCertificates(true);
    profile.setAssumeUntrustedCertificateIssuer(true);

So I added it into my code, but it doesn't seem to do what I want. I think I'm looking for a way to tell WebDriver that my ssl certificate is in x directory, please use it when accessing this site. Does anyone know how to do this?

My Test code is:

@Test
public void userSignsInAndVerifiesDrawerViews(){
            driver.get("www.url.com");
            waitFor(5000);
    driver.findElement(By.xpath("//a[contains(text(), 'Sign in')]")).click();
    waitFor(3000);
    String username = "seleniumtest";
    String password = "seleniumtest1";
    driver.findElement(By.id("username")).sendKeys(username);
    driver.findElement(By.id("password")).sendKeys(password);
    driver.findElement(By.xpath("//signin")).click();
    waitFor(30000);
    String signInLinkText = driver.findElement(By.xpath("//xpath")).getText();
    assertEquals(signInLinkText, username);
}


问:
How to move all elements that are zero to the end of an array?
Write a function that takes an array of values and moves all elements that are zero to the end of the array, otherwise preserving the order of the array. The zero elements must also maintain the order in which they occurred.

Zero elements are defined by either 0 or "0". Some tests may include elements that are not number literals.

NOT allowed to use any temporary arrays or objects. Also not allowed to use any Array.prototype or Object.prototype methods.So no array.push or splice() is allowed.

I tried this:

```<code>function removeZeros(nums) {

   for(let i = nums.length - 1; i >= 0 ; i--){
    if(nums[i] === 0){
      nums.splice(i, 1);
      nums.push(0);
    }
   }
   return nums;
}
</code>```

input:

```<code>[7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]
</code>```

Expected:

```<code>[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]
</code>```

Actual:

```<code>[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]
</code>```

Result is coming as correct but I need to do it without array.push() or array.splice()

答:
Take length of original array

Filter nonZero values from original array

add zeros at the end as per difference in length of filtered array and original array

function removeZeros(nums) {
   let originalLen = nums.length
   let nonZero = nums.filter(Boolean)
   return [...nonZero,...new Array(originalLen-nonZero.length).fill(0)]
}

console.log(removeZeros([7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]))```
</div>
</div>
</p>

<hr>

<blockquote>
  <p>Also not allowed to use any Array.prototype or Object.prototype
  methods</p>
</blockquote>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function removeZeros(nums) {
   let originalLen = nums.length
   let final = []
   for(let i=0;i<nums.length; i++){
    if(nums[i]) final = [...final, nums[i]]
   }
   let lenDiff = originalLen-final.length
   while(lenDiff){
    final = [...final,0]
    lenDiff--
   }
   return final
}

console.log(removeZeros([7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]))</code>```

Body:
Write a function that takes an array of values and moves all elements that are zero to the end of the array, otherwise preserving the order of the array. The zero elements must also maintain the order in which they occurred.

Zero elements are defined by either 0 or "0". Some tests may include elements that are not number literals.

NOT allowed to use any temporary arrays or objects. Also not allowed to use any Array.prototype or Object.prototype methods.So no array.push or splice() is allowed.

I tried this:

function removeZeros(nums) {

   for(let i = nums.length - 1; i >= 0 ; i--){
    if(nums[i] === 0){
      nums.splice(i, 1);
      nums.push(0);
    }
   }
   return nums;
}

input:

[7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]

Expected:

[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]

Actual:

[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]

Result is coming as correct but I need to do it without array.push() or array.splice()

Body:
Take length of original array

Filter nonZero values from original array

add zeros at the end as per difference in length of filtered array and original array

function removeZeros(nums) {
   let originalLen = nums.length
   let nonZero = nums.filter(Boolean)
   return [...nonZero,...new Array(originalLen-nonZero.length).fill(0)]
}

console.log(removeZeros([7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]))

Also not allowed to use any Array.prototype or Object.prototype
  methods

function removeZeros(nums) {
   let originalLen = nums.length
   let final = []
   for(let i=0;i<nums.length; i++){
    if(nums[i]) final = [...final, nums[i]]
   }
   let lenDiff = originalLen-final.length
   while(lenDiff){
    final = [...final,0]
    lenDiff--
   }
   return final
}

console.log(removeZeros([7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]))


问:
How to extract string from a long string
I'm struggling to extract strings from a long string which is a row of a csv file with python or R. The long string is  </p>

```<code>"Zhao, Sihai@Univ Penn::Cai, T. Tony@Univ Penn::Li, Hongzhe@Univ Penn"
</code>```

<p>And the results should be  </p>

```<code>"Zhao, Sihai" "Cai, T. Tony" "Li, Hongzhe"
</code>```

答:
Input

```<code> s = "Zhao, Sihai@Univ Penn::Cai, T. Tony@Univ Penn::Li, Hongzhe@Univ Penn"
l=s.replace('@Univ Penn','').split("::")
s=str(l)
s2=s[1:-1]
print(s2)
</code>```

output

```<code>'Zhao, Sihai', 'Cai, T. Tony', 'Li, Hongzhe'
</code>```

Body:
I'm struggling to extract strings from a long string which is a row of a csv file with python or R. The long string is

"Zhao, Sihai@Univ Penn::Cai, T. Tony@Univ Penn::Li, Hongzhe@Univ Penn"

And the results should be

"Zhao, Sihai" "Cai, T. Tony" "Li, Hongzhe"

Body:
Input

 s = "Zhao, Sihai@Univ Penn::Cai, T. Tony@Univ Penn::Li, Hongzhe@Univ Penn"
l=s.replace('@Univ Penn','').split("::")
s=str(l)
s2=s[1:-1]
print(s2)

output

'Zhao, Sihai', 'Cai, T. Tony', 'Li, Hongzhe'


问:
Problems plotting datetime.timedelta
I am new to pandas and I was wondering if pandas can plot datetime.timedelta. I tried a few things but here is the current version:

```<code>df = pd.DataFrame(data=[pd.to_timedelta(total_run_times.values())], index=[0])
plot = df.plot()
fig = plot.get_figure()
fig.savefig("test.png")
</code>```

total_run_times is a dictionary of number: datetime.timedelta. When I print out 'df' in pycharm debugger I get:

```<code>   0                         1                        2
0  0 days 00:00:06.283421    0 days 00:17:55.295750   0 days 00:00:00
</code>```

Error received:

```<code>TypeError: Empty 'DataFrame': no numeric data to plot
</code>```

Versions: python 3.6.3 and pandas 0.20.3

I just want a line graph that plots the times in the array as one line. Can this be done? Or do I have to convert everything to scalar like float?

Any help would be greatly appreciated.

Thanks,
-K

答:
Transpose your columns to rows with transpose, then convert them to timedelta with pd.to_timedelta

```<code>pd.to_timedelta(df.T[0]).plot()
</code>```

Title: Problems plotting datetime.timedelta

Body:
I am new to pandas and I was wondering if pandas can plot datetime.timedelta. I tried a few things but here is the current version:

df = pd.DataFrame(data=[pd.to_timedelta(total_run_times.values())], index=[0])
plot = df.plot()
fig = plot.get_figure()
fig.savefig("test.png")

total_run_times is a dictionary of number: datetime.timedelta. When I print out 'df' in pycharm debugger I get:

   0                         1                        2
0  0 days 00:00:06.283421    0 days 00:17:55.295750   0 days 00:00:00

Error received:

TypeError: Empty 'DataFrame': no numeric data to plot

Versions: python 3.6.3 and pandas 0.20.3

I just want a line graph that plots the times in the array as one line. Can this be done? Or do I have to convert everything to scalar like float?

Any help would be greatly appreciated.

Thanks,
-K

Body:
Transpose your columns to rows with transpose, then convert them to timedelta with pd.to_timedelta

pd.to_timedelta(df.T[0]).plot()


问:
AutoLayout Button, Gradient and won't adjust to height
I want to adjust every button's height to the screen size. To do so I've created the following class, which also contains my previously created gradient and shadow path:

```<code>extension UIButton {

    func typeMain() {
        self.translatesAutoresizingMaskIntoConstraints = false
        let height = UIScreen.main.bounds.height * 0.07
        self.heightAnchor.constraint(equalToConstant: height).isActive = true

        self.addCharacterSpacing()
        self.tintColor = UIColor.white
        let color = UIColor(red: 11/255, green: 95/255, blue: 244/255, alpha: 1)
        let sndColor = UIColor(red: 106/255, green: 178/255, blue: 255/255, alpha: 1)

        self.layer.cornerRadius = self.frame.size.height / 5.0

        self.applyGradient(colours: [color, sndColor], locations: [0.0, 1.0])

        let shadowSize : CGFloat = 2.0
        self.layer.shadowColor = UIColor(red: 106/255, green: 178/255, blue: 255/255, alpha: 1).cgColor
        self.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
        self.layer.shadowOpacity = 0.4
        let shadowPath = UIBezierPath(rect: CGRect(x: -shadowSize / 2,
                                                   y: shadowSize,
                                                   width: self.frame.size.width + shadowSize,
                                                   height: self.frame.size.height + shadowSize))
        self.layer.shadowPath = shadowPath.cgPath
        self.layer.shadowRadius = 5
        self.layer.masksToBounds = false
    }
}
</code>```

The button is being adjusted to the screen size, but both the gradient and shadow aren't. How can I do so?

Btw. no height constraint in Storyboard set.

答:
You seem to be setting the shadow path here relative to the frame size, rather than your generated constraint for height.

You could remove the following:

```<code>let shadowPath = UIBezierPath(rect: CGRect(x: -shadowSize / 2,
                                                   y: shadowSize,
                                                   width: self.frame.size.width + shadowSize,
                                                   height: self.frame.size.height + shadowSize))
</code>```

And the shadow should hug the button just fine. If you want the shadow to have this path you've laid out however, you need to set the width and height based on what you set your constraints to (i.e. UIScreen.main.bounds.height * 0.07).

If you set translatesAutoresizingMaskIntoConstraints to false, constraints will no longer be generated relative to whatever CGRect frame you've passed to the object. They're generated based on anchors and content size (here your height is explicitly set by that anchor but your width will remain constrained by the button's content size). In other words, self.frame is irrelevant here.

If you set it like this, it will work:

```<code>self.widthAnchor.constraint(equalToConstant: self.frame.width).isActive = true
let shadowPath = UIBezierPath(rect: CGRect(x: -shadowSize / 2,
                                       y: shadowSize,
                                       width: self.frame.width + shadowSize,
                                       height: height + shadowSize))
</code>```

Does that help?

Body:
I want to adjust every button's height to the screen size. To do so I've created the following class, which also contains my previously created gradient and shadow path:

extension UIButton {

    func typeMain() {
        self.translatesAutoresizingMaskIntoConstraints = false
        let height = UIScreen.main.bounds.height * 0.07
        self.heightAnchor.constraint(equalToConstant: height).isActive = true

        self.addCharacterSpacing()
        self.tintColor = UIColor.white
        let color = UIColor(red: 11/255, green: 95/255, blue: 244/255, alpha: 1)
        let sndColor = UIColor(red: 106/255, green: 178/255, blue: 255/255, alpha: 1)

        self.layer.cornerRadius = self.frame.size.height / 5.0

        self.applyGradient(colours: [color, sndColor], locations: [0.0, 1.0])

        let shadowSize : CGFloat = 2.0
        self.layer.shadowColor = UIColor(red: 106/255, green: 178/255, blue: 255/255, alpha: 1).cgColor
        self.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
        self.layer.shadowOpacity = 0.4
        let shadowPath = UIBezierPath(rect: CGRect(x: -shadowSize / 2,
                                                   y: shadowSize,
                                                   width: self.frame.size.width + shadowSize,
                                                   height: self.frame.size.height + shadowSize))
        self.layer.shadowPath = shadowPath.cgPath
        self.layer.shadowRadius = 5
        self.layer.masksToBounds = false
    }
}

The button is being adjusted to the screen size, but both the gradient and shadow aren't. How can I do so?

Btw. no height constraint in Storyboard set.

Body:
You seem to be setting the shadow path here relative to the frame size, rather than your generated constraint for height.

You could remove the following:

let shadowPath = UIBezierPath(rect: CGRect(x: -shadowSize / 2,
                                                   y: shadowSize,
                                                   width: self.frame.size.width + shadowSize,
                                                   height: self.frame.size.height + shadowSize))

And the shadow should hug the button just fine. If you want the shadow to have this path you've laid out however, you need to set the width and height based on what you set your constraints to (i.e. UIScreen.main.bounds.height * 0.07).

If you set translatesAutoresizingMaskIntoConstraints to false, constraints will no longer be generated relative to whatever CGRect frame you've passed to the object. They're generated based on anchors and content size (here your height is explicitly set by that anchor but your width will remain constrained by the button's content size). In other words, self.frame is irrelevant here.

If you set it like this, it will work:

self.widthAnchor.constraint(equalToConstant: self.frame.width).isActive = true
let shadowPath = UIBezierPath(rect: CGRect(x: -shadowSize / 2,
                                       y: shadowSize,
                                       width: self.frame.width + shadowSize,
                                       height: height + shadowSize))

Does that help?


问:
I cannot install the facebook SDK for swift
I have tried to install the swift SDK several times as described (https://developers.facebook.com/docs/swift/getting-started) step by step but when I try to connect App Delegate I always receive the warning "Use of unresolved identifier 'SDKApplicationDelegate'...". Also any other method from the imported FacebookCore seems to be unknown.
Thanks a ton for any help
Franz
(Xcode 10.2.1, Swift 5)</p>

答:
Does your project build after you've imported the pod's?

Make sure you are importing the library at the top of AppDelegate with

```<code>import FacebookCore
</code>```

Body:
Does your project build after you've imported the pod's?

Make sure you are importing the library at the top of AppDelegate with

import FacebookCore


问:
how to add a new "key-value" pair for existing child in firebase
I've connected my android app to firebase and enabled email and password authentication. My current database status is like :

Now I want to add an extra field (key:"number")for all users i have so that my final database looks like:

so please tell me how can I do this ?

One more important thing is I wrote code such that I first authenticate them, if their registration is succesfull then I take user to new Activity where they will enter this "key" after collecting the key I should add this to user node as shown in the second picture.

So please tell me how to do this?

答:
To write a value in the Firebase Realtime Database, you must know the complete path to that value. So in your case that means that you first have to load all data from the database, to be able to determine the dynamic keys (C76w3..., FjsZ..., etc).

Something like this:

```<code>DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
            snapshot.getRef().child("key").setValue("hisoka");
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
}
</code>```

Body:
To write a value in the Firebase Realtime Database, you must know the complete path to that value. So in your case that means that you first have to load all data from the database, to be able to determine the dynamic keys (C76w3..., FjsZ..., etc).

Something like this:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
            snapshot.getRef().child("key").setValue("hisoka");
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
}


问:
Review of this linked list program
This is a program on the linked list which prints the given input. But is it possible to do it Without using the if(start==NULL) ...else .. statement?

```<code>#include <stdio.h>
#include <malloc.h>
struct node
{
    int data;
    struct node* next;
}* start = NULL;

void main()
{
    struct node* tmp;
    struct node *ptr, *tmp1;

    int n = 0;
    int choice = 2;

    while (1)
    {
        printf("Enter a number less than 3 to continue");
        scanf("%d", &choice);
        if (choice >= 3)
            break;

        printf("Enter the input");
        scanf("%d", &n);
        // n=n+10;
        if (start == NULL)
        {
            tmp = (struct node*)malloc(sizeof(struct node));
            start = tmp;
            start->data = n;
            ptr = start;
        }
        else
        {
            tmp = (struct node*)malloc(sizeof(struct node));
            ptr->next = tmp;
            tmp->data = n;
            ptr = tmp;
        }
    }
    tmp->next = NULL;

    printf("\nThe output of the linked list is\n");
    n = 0;
    ptr = start;
    while (ptr != NULL)
    {
        printf("\n  1 ptr =           %d", ptr->data);
        ptr = ptr->next;
    }
}
</code>```

答:
is it possible to do it Without using the if(start==NULL) ...else .. statement?

Yes

Create a head node and use only its .next member.

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

struct node {
  int data;
  struct node* next;
};

int main(void) {
  struct node head = {.next = NULL};  // only need .next
  struct node *ptr = &head;

  while (1) {
    // ...

    int n;
    printf("Enter the input ");
    fflush(stdout);
    if (scanf("%d", &n) != 1) {
      break;
    }
    ptr->next = malloc(sizeof *ptr->next);
    if (ptr->next == NULL) {
      break;
    }
    ptr = ptr->next;
    ptr->data = n;
    ptr->next = NULL;
  }

  printf("\nThe output of the linked list is\n");
  ptr = head.next; // The start of the list is here
  while (ptr) {
    printf("  1 ptr =           %d\n", ptr->data);
    ptr = ptr->next;
  }
}
</code>```

Title: Review of this linked list program

Body:
This is a program on the linked list which prints the given input. But is it possible to do it Without using the if(start==NULL) ...else .. statement?

#include <stdio.h>
#include <malloc.h>
struct node
{
    int data;
    struct node* next;
}* start = NULL;

void main()
{
    struct node* tmp;
    struct node *ptr, *tmp1;

    int n = 0;
    int choice = 2;

    while (1)
    {
        printf("Enter a number less than 3 to continue");
        scanf("%d", &choice);
        if (choice >= 3)
            break;

        printf("Enter the input");
        scanf("%d", &n);
        // n=n+10;
        if (start == NULL)
        {
            tmp = (struct node*)malloc(sizeof(struct node));
            start = tmp;
            start->data = n;
            ptr = start;
        }
        else
        {
            tmp = (struct node*)malloc(sizeof(struct node));
            ptr->next = tmp;
            tmp->data = n;
            ptr = tmp;
        }
    }
    tmp->next = NULL;

    printf("\nThe output of the linked list is\n");
    n = 0;
    ptr = start;
    while (ptr != NULL)
    {
        printf("\n  1 ptr =           %d", ptr->data);
        ptr = ptr->next;
    }
}

Body:
is it possible to do it Without using the if(start==NULL) ...else .. statement?

Yes

Create a head node and use only its .next member.

#include <stdio.h>
#include <malloc.h>

struct node {
  int data;
  struct node* next;
};

int main(void) {
  struct node head = {.next = NULL};  // only need .next
  struct node *ptr = &head;

  while (1) {
    // ...

    int n;
    printf("Enter the input ");
    fflush(stdout);
    if (scanf("%d", &n) != 1) {
      break;
    }
    ptr->next = malloc(sizeof *ptr->next);
    if (ptr->next == NULL) {
      break;
    }
    ptr = ptr->next;
    ptr->data = n;
    ptr->next = NULL;
  }

  printf("\nThe output of the linked list is\n");
  ptr = head.next; // The start of the list is here
  while (ptr) {
    printf("  1 ptr =           %d\n", ptr->data);
    ptr = ptr->next;
  }
}