答:
Use a simple filter:

```<code>no_percent = lambda feature: '%' not in feature['properties']['name']
data['features'] = filter(no_percent, data['features'])
</code>```

Or as a list comprehension:

```<code>data['features'] = [feature for feature in data['features']
                      if '%' not in feature['properties']['name']]
</code>```

Body:
I have a rather large geojson file which is converted from some National Weather Service data. I've trimmed it down to this sample here:

{
  "properties": {
    "name": "day1otlk"
  },
  "type": "FeatureCollection",
  "features": [
    {
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              -122.71424459627099,
              40.229695635383166
            ],
            [
              -122.62484780364827,
              40.53410620541074
            ],
            [
              -122.71424459627099,
              40.229695635383166
            ]
          ]
        ]
      },
      "properties": {
        "Name": "General Thunder",
        "stroke-opacity": 1,
        "stroke-width": 4,
        "name": "General Thunder",
        "fill": "#c0e8c0",
        "fill-opacity": 0.75,
        "stroke": "#ffffff",
        "timeSpan": {
          "end": "2017-03-30T12:00:00Z",
          "begin": "2017-03-29T20:00:00Z"
        }
      },
      "type": "Feature"
    },
    {
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              -108.65861565996833,
              32.91391108773154
            ],
            [
              -108.63932601964923,
              32.95521185698698
            ],
            [
              -108.65861565996833,
              32.91391108773154
            ]
          ]
        ]
      },
      "properties": {
        "Name": "General Thunder",
        "stroke-opacity": 1,
        "stroke-width": 4,
        "name": "General Thunder",
        "fill": "#c0e8c0",
        "fill-opacity": 0.75,
        "stroke": "#ffffff",
        "timeSpan": {
          "end": "2017-03-30T12:00:00Z",
          "begin": "2017-03-29T20:00:00Z"
        }
      },
      "type": "Feature"
    },
    {
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              -92.67280213157608,
              38.47870651780003
            ],
            [
              -92.62448390998837,
              38.45534960370862
            ],
            [
              -92.59475154780039,
              38.493327413824595
            ],
            [
              -92.64308574626148,
              38.51669676139087
            ],
            [
              -92.67280213157608,
              38.47870651780003
            ]
          ]
        ]
      },
      "properties": {
        "Name": "10 %",
        "stroke-opacity": 1,
        "stroke-width": 4,
        "name": "10 %",
        "fill": "#8b4726",
        "fill-opacity": 0.89,
        "stroke": "#ffffff",
        "timeSpan": {
          "end": "2017-03-30T12:00:00Z",
          "begin": "2017-03-29T20:00:00Z"
        }
      },
      "type": "Feature"
    },
    {
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              -92.67280213157608,
              38.47870651780003
            ],
            [
              -92.62448390998837,
              38.45534960370862
            ],
            [
              -92.59475154780039,
              38.493327413824595
            ],
            [
              -92.64308574626148,
              38.51669676139087
            ],
            [
              -92.67280213157608,
              38.47870651780003
            ]
          ]
        ]
      },
      "properties": {
        "Name": "10 %",
        "stroke-opacity": 1,
        "stroke-width": 4,
        "name": "20 %",
        "fill": "#8b4726",
        "fill-opacity": 0.89,
        "stroke": "#ffffff",
        "timeSpan": {
          "end": "2017-03-30T12:00:00Z",
          "begin": "2017-03-29T20:00:00Z"
        }
      },
      "type": "Feature"
    },
    {
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              -97.09845994557838,
              38.43843745045377
            ],
            [
              -97.07114801649661,
              38.47751978088534
            ],
            [
              -97.09845994557838,
              38.43843745045377
            ]
          ]
        ]
      },
      "properties": {
        "Name": "5 %",
        "stroke-opacity": 1,
        "stroke-width": 4,
        "name": "5 %",
        "fill": "#b47f00",
        "fill-opacity": 0.89,
        "stroke": "#ffffff",
        "timeSpan": {
          "end": "2017-03-30T12:00:00Z",
          "begin": "2017-03-29T20:00:00Z"
        }
      },
      "type": "Feature"
    }
  ]
}

I'm looking to remove the elements where name has a % in it. I don't want those coordinates or anything included.

Here's my code:

import json

with open('test.geojson') as data_file:
    data = json.load(data_file)

for element in data["features"]:
    if '%' in element["properties"]["name"]:
        del element["type"]
        del element["properties"] # Deletes the properties
        del element["geometry"] # Deletes the  coords

with open('test_output.geojson', 'w') as data_file:
    data = json.dump(data, data_file)

This works well enough to remove the element's sub keys, but I'm left with output that looks like:

{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}

I've also tried to use

for element in data["features"]:
        if '%' in element["properties"]["name"]:
                    data["features"].remove(element)

but that seems to delete only the last element in the sample group, which is the 5 % group. It should be removing the 10 %, 20 % and the 5 % groups.

Is there a way to remove the element from data["features"] if name has a % in it all together so I'm left with clean json output? In this sample data, the only data["features"] I should have left are the General Thunder and no empty brackets.

Body:
Use a simple filter:

no_percent = lambda feature: '%' not in feature['properties']['name']
data['features'] = filter(no_percent, data['features'])

Or as a list comprehension:

data['features'] = [feature for feature in data['features']
                      if '%' not in feature['properties']['name']]


来源: stackexchange

问:
icon rotation in leaflet package
I'm learning to program in R with the leaflet package.
I want to give an angle to the icons, and am trying it with this code:

```<code>m <- leaflet()
m <- addTiles(m,urlTemplate = "http://xdworld.vworld.kr:8080/2d/Base/201310/{z}/{x}/{y}.png")
m = m %>% setView(127.074167,34.456806, zoom = 9)
arrowIcon <- makeIcon(
  iconUrl = "arrow.png"
  ,iconWidth = 100, iconHeight = 100
  ,iconAnchorX = 25, iconAnchorY =25
)
arrowIcon <- makeIcon(
  iconUrl = "ARROW_B2.png"
  ,iconWidth = 100, iconHeight = 100
  ,iconAnchorX = 25, iconAnchorY = 25
)
offset = 0.00 # zoom 10-> 0.03, 9->0.06, 8 -> 0.12, 7 -> 0.24
m_lat = 34.45 + offset
m_lon = 127.07 - offset
m <- addMarkers(m,  lng=m_lon, lat= m_lat
            , options = c( markerOptions(), iconAngle= 0)
            ,icon= arrowIcon)
m <- addCircles(m, lng=127.07, lat=34.45 , weight = 10,radius = 100)
m
</code>```

However, it does not work.

答:
This is the only way I could get it to work. You want to use the RotatedMarker plugin, available here. To use this plugin with R, I followed instructions here.

Two things to be aware of that I can't seem to figure out:

I can't seem to find the icon when it's stored locally - it needs to be accessible via URL. If you can fix that, please let me know.

You need to download the javascript file and save it locally. In the example below I've put it in the same directory as my R script. Theoretically you should be able to load it via a URL but that doesn't work. If you can fix that, please let me know.

So here's the working code:

```<code>library(htmltools)
library(htmlwidgets)
library(leaflet)

# this is taken from: https://gist.github.com/jcheng5/c084a59717f18e947a17955007dc5f92
rotatedMarker <- htmlDependency(
  "Leaflet.rotatedMarker",
  "0.1.2",
  src = normalizePath("."),
  script = "leaflet.rotatedMarker.js"
)

# this is taken from: https://gist.github.com/jcheng5/c084a59717f18e947a17955007dc5f92
registerPlugin <- function(map, plugin) {
  map$dependencies <- c(map$dependencies, list(plugin))
  map
}

leaflet() %>%
  addTiles(urlTemplate = "http://xdworld.vworld.kr:8080/2d/Base/201310/{z}/{x}/{y}.png") %>%
  setView(127.074167,34.456806, zoom = 9) %>%
  registerPlugin(rotatedMarker) %>%
  onRender("function(el, x) {
    var planeIcon = L.icon({iconUrl: 'https://raw.githubusercontent.com/bbecquet/Leaflet.PolylineDecorator/master/example/icon_plane.png', iconAnchor: [16, 16]});
    var pathPattern = L.marker([34.45, 127.07], {icon: planeIcon, rotationAngle: 90}).addTo(this);
  }") %>%
  addCircles(lng = 127.07, lat = 34.45, weight = 10, radius = 100)
</code>```

Which produces:

Notice that I've rotated the plane icon 90 degrees.

ContentLicense: CC BY-SA 3.0

Title: icon rotation in leaflet package

Body:
I'm learning to program in R with the leaflet package.
I want to give an angle to the icons, and am trying it with this code:

m <- leaflet()
m <- addTiles(m,urlTemplate = "http://xdworld.vworld.kr:8080/2d/Base/201310/{z}/{x}/{y}.png")
m = m %>% setView(127.074167,34.456806, zoom = 9)
arrowIcon <- makeIcon(
  iconUrl = "arrow.png"
  ,iconWidth = 100, iconHeight = 100
  ,iconAnchorX = 25, iconAnchorY =25
)
arrowIcon <- makeIcon(
  iconUrl = "ARROW_B2.png"
  ,iconWidth = 100, iconHeight = 100
  ,iconAnchorX = 25, iconAnchorY = 25
)
offset = 0.00 # zoom 10-> 0.03, 9->0.06, 8 -> 0.12, 7 -> 0.24
m_lat = 34.45 + offset
m_lon = 127.07 - offset
m <- addMarkers(m,  lng=m_lon, lat= m_lat
            , options = c( markerOptions(), iconAngle= 0)
            ,icon= arrowIcon)
m <- addCircles(m, lng=127.07, lat=34.45 , weight = 10,radius = 100)
m

However, it does not work.

Body:
This is the only way I could get it to work. You want to use the RotatedMarker plugin, available here. To use this plugin with R, I followed instructions here.

Two things to be aware of that I can't seem to figure out:

I can't seem to find the icon when it's stored locally - it needs to be accessible via URL. If you can fix that, please let me know.

You need to download the javascript file and save it locally. In the example below I've put it in the same directory as my R script. Theoretically you should be able to load it via a URL but that doesn't work. If you can fix that, please let me know.

So here's the working code:

library(htmltools)
library(htmlwidgets)
library(leaflet)

# this is taken from: https://gist.github.com/jcheng5/c084a59717f18e947a17955007dc5f92
rotatedMarker <- htmlDependency(
  "Leaflet.rotatedMarker",
  "0.1.2",
  src = normalizePath("."),
  script = "leaflet.rotatedMarker.js"
)

# this is taken from: https://gist.github.com/jcheng5/c084a59717f18e947a17955007dc5f92
registerPlugin <- function(map, plugin) {
  map$dependencies <- c(map$dependencies, list(plugin))
  map
}

leaflet() %>%
  addTiles(urlTemplate = "http://xdworld.vworld.kr:8080/2d/Base/201310/{z}/{x}/{y}.png") %>%
  setView(127.074167,34.456806, zoom = 9) %>%
  registerPlugin(rotatedMarker) %>%
  onRender("function(el, x) {
    var planeIcon = L.icon({iconUrl: 'https://raw.githubusercontent.com/bbecquet/Leaflet.PolylineDecorator/master/example/icon_plane.png', iconAnchor: [16, 16]});
    var pathPattern = L.marker([34.45, 127.07], {icon: planeIcon, rotationAngle: 90}).addTo(this);
  }") %>%
  addCircles(lng = 127.07, lat = 34.45, weight = 10, radius = 100)

Which produces:

Notice that I've rotated the plane icon 90 degrees.


问:
How does this float square root approximation work?
I found a rather strange but working square root approximation for floats; I really don't get it. Can someone explain me why this code works?

```<code>float sqrt(float f)
{
    const int result = 0x1fbb4000 + (*(int*)&f >> 1);
    return *(float*)&result;
}
</code>```

I've test it a bit and it outputs values off of std::sqrt() by about 1 to 3%. I know of the Quake III's fast inverse square root and I guess it's something similar here (without the newton iteration) but I'd really appreciate an explanation of how it works.

(nota: I've tagged it both c and c++ since it's both valid-ish (see comments) C and C++ code)

答:
Adding a wiki test harness to test all float.

The approximation is within 4% for many float, but very poor for sub-normal numbers.  YMMV

```<code>Worst:1.401298e-45 211749.20%
Average:0.63%
Worst:1.262738e-38 3.52%
Average:0.02%
</code>```

Note that with argument of +/-0.0, the result is not zero.

```<code>printf("% e % e\n", sqrtf(+0.0), sqrt_apx(0.0));  //  0.000000e+00  7.930346e-20
printf("% e % e\n", sqrtf(-0.0), sqrt_apx(-0.0)); // -0.000000e+00 -2.698557e+19
</code>```

Test code

```<code>#include <float.h>
#include <limits.h>
#include <math.h>
#include <stddef.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

float sqrt_apx(float f) {
  const int result = 0x1fbb4000 + (*(int*) &f >> 1);
  return *(float*) &result;
}

double error_value = 0.0;
double error_worst = 0.0;
double error_sum = 0.0;
unsigned long error_count = 0;

void sqrt_test(float f) {
  if (f == 0) return;
  volatile float y0 = sqrtf(f);
  volatile float y1 = sqrt_apx(f);
  double error = (1.0 * y1 - y0) / y0;
  error = fabs(error);
  if (error > error_worst) {
    error_worst = error;
    error_value = f;
  }
  error_sum += error;
  error_count++;
}

void sqrt_tests(float f0, float f1) {
  error_value = error_worst = error_sum = 0.0;
  error_count = 0;
  for (;;) {
    sqrt_test(f0);
    if (f0 == f1) break;
    f0 = nextafterf(f0, f1);
  }
  printf("Worst:%e %.2f%%\n", error_value, error_worst*100.0);
  printf("Average:%.2f%%\n", error_sum / error_count);
  fflush(stdout);
}

int main() {
  sqrt_tests(FLT_TRUE_MIN, FLT_MIN);
  sqrt_tests(FLT_MIN, FLT_MAX);
  return 0;
}
</code>```

Body:
I found a rather strange but working square root approximation for floats; I really don't get it. Can someone explain me why this code works?

float sqrt(float f)
{
    const int result = 0x1fbb4000 + (*(int*)&f >> 1);
    return *(float*)&result;
}

I've test it a bit and it outputs values off of std::sqrt() by about 1 to 3%. I know of the Quake III's fast inverse square root and I guess it's something similar here (without the newton iteration) but I'd really appreciate an explanation of how it works.

(nota: I've tagged it both c and c++ since it's both valid-ish (see comments) C and C++ code)

Body:
Adding a wiki test harness to test all float.

The approximation is within 4% for many float, but very poor for sub-normal numbers.  YMMV

Worst:1.401298e-45 211749.20%
Average:0.63%
Worst:1.262738e-38 3.52%
Average:0.02%

Note that with argument of +/-0.0, the result is not zero.

printf("% e % e\n", sqrtf(+0.0), sqrt_apx(0.0));  //  0.000000e+00  7.930346e-20
printf("% e % e\n", sqrtf(-0.0), sqrt_apx(-0.0)); // -0.000000e+00 -2.698557e+19

Test code

#include <float.h>
#include <limits.h>
#include <math.h>
#include <stddef.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

float sqrt_apx(float f) {
  const int result = 0x1fbb4000 + (*(int*) &f >> 1);
  return *(float*) &result;
}

double error_value = 0.0;
double error_worst = 0.0;
double error_sum = 0.0;
unsigned long error_count = 0;

void sqrt_test(float f) {
  if (f == 0) return;
  volatile float y0 = sqrtf(f);
  volatile float y1 = sqrt_apx(f);
  double error = (1.0 * y1 - y0) / y0;
  error = fabs(error);
  if (error > error_worst) {
    error_worst = error;
    error_value = f;
  }
  error_sum += error;
  error_count++;
}

void sqrt_tests(float f0, float f1) {
  error_value = error_worst = error_sum = 0.0;
  error_count = 0;
  for (;;) {
    sqrt_test(f0);
    if (f0 == f1) break;
    f0 = nextafterf(f0, f1);
  }
  printf("Worst:%e %.2f%%\n", error_value, error_worst*100.0);
  printf("Average:%.2f%%\n", error_sum / error_count);
  fflush(stdout);
}

int main() {
  sqrt_tests(FLT_TRUE_MIN, FLT_MIN);
  sqrt_tests(FLT_MIN, FLT_MAX);
  return 0;
}


问:
A JavaScript function is repeated many times
I have two function print and callPrint bellow. I click call function print the first time is right.
But when click call function print the second or third then function callPrint will be call 2 times or 3 times.
I have debug on attack file.

```<code>function print(url) {
    console.log('print');
    var _this = this, iframeId = 'iframeprint', $iframe = $('iframe#iframeprint');
    if ($iframe.attr('src') != url) {
        $.when(
            $iframe.attr('src', 'about:blank'),
            $iframe.load(function () {
                console.log($iframe.prop('contentWindow').document.readyState);
            })
        ).done(function () {
            $iframe.attr('src', url);
            $iframe.load(function () {
                console.log('new');
                _this.callPrint(iframeId);
            });
        });
    } else {
        console.log('old');
        _this.callPrint(iframeId);
    }
}

// initiates print once content has been loaded into iframe
function callPrint(iframeId) {
    console.log('callPrint');
    $('div.wait').hide();
    var PDF = document.getElementById(iframeId);
    PDF.focus();
    PDF.contentWindow.print();
    return false;
}
</code>```

A JavaScript function is repeated many times

答:
The problem is because you're attaching two new load() event handlers to the iframe every time print() is called. To fix this, add a single load() event handler and call your function from in there. This will be triggered whenever you update the src attribute on the element. Try this:

```<code>var $iframe = $('#iframeprint').load(function() {
  // You'll need to make sure the function is in scope of the handler
  // There's not enough information in the OP for me to show you how
  callPrint('iframeprint');
});

function print(url) {
  var _this = this;

  if ($iframe.attr('src') != url) {
    $iframe.attr('src', url);
  } else {
    _this.callPrint(iframeId);
  }
}
</code>```

Body:
I have two function print and callPrint bellow. I click call function print the first time is right.
But when click call function print the second or third then function callPrint will be call 2 times or 3 times.
I have debug on attack file.

function print(url) {
    console.log('print');
    var _this = this, iframeId = 'iframeprint', $iframe = $('iframe#iframeprint');
    if ($iframe.attr('src') != url) {
        $.when(
            $iframe.attr('src', 'about:blank'),
            $iframe.load(function () {
                console.log($iframe.prop('contentWindow').document.readyState);
            })
        ).done(function () {
            $iframe.attr('src', url);
            $iframe.load(function () {
                console.log('new');
                _this.callPrint(iframeId);
            });
        });
    } else {
        console.log('old');
        _this.callPrint(iframeId);
    }
}

// initiates print once content has been loaded into iframe
function callPrint(iframeId) {
    console.log('callPrint');
    $('div.wait').hide();
    var PDF = document.getElementById(iframeId);
    PDF.focus();
    PDF.contentWindow.print();
    return false;
}

A JavaScript function is repeated many times

Body:
The problem is because you're attaching two new load() event handlers to the iframe every time print() is called. To fix this, add a single load() event handler and call your function from in there. This will be triggered whenever you update the src attribute on the element. Try this:

var $iframe = $('#iframeprint').load(function() {
  // You'll need to make sure the function is in scope of the handler
  // There's not enough information in the OP for me to show you how
  callPrint('iframeprint');
});

function print(url) {
  var _this = this;

  if ($iframe.attr('src') != url) {
    $iframe.attr('src', url);
  } else {
    _this.callPrint(iframeId);
  }
}


问:
ClassLoader with Sandbox reports StackOverFlowError
I'm using de.unkrig.commons.lang.security.Sandbox.confine to solve Java Security issue Download of Code Without Integrity Check.

Below is the findClass method in my custom classloader extends from ClassLoader.

With this implementation, it reports a StackOverFlowError.

Anyone knows what happened to this? And how to solve it?

Many thanks!

```<code>@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
    Class<?> cls;
    try {
        cls = super.findClass(name);
        Sandbox.confine(cls, getPermissions());
        return cls;
    } catch (ClassNotFoundException e) {
        for (ClassLoader delegate : _delegateClassLoaders) {
            try {
                 cls = delegate.loadClass(name);
                if (cls != null) {
                    Sandbox.confine(cls, getPermissions());
                    return cls;
                }
            } catch (ClassNotFoundException fe) {
            }
        }
    }
    throw new ClassNotFoundException(name);
}

protected Permissions getPermissions() {
    Permissions pm = new Permissions();
    FilePermission p = new FilePermission("/tmp/*", "read,write");
    pm.add(p);
    return pm;
}
</code>```

答:
(wanted to comment but I'm new here and don't have enough rep)

First, you are calling super.findClass() while you are extending ClassLoader - it will always throw a ClassNotFoundException :

```<code>protected Class<?> findClass(String name) throws ClassNotFoundException {
    throw new ClassNotFoundException(name);
}
</code>```

Second I don't know this Sandbox library, but you probably have an infinite recursion here. Note that loadClass() calls findClass() in the default ClassLoader implementation;

Might it be that one of the delegates is the same class running this code? did you try to debug it?

Body:
I'm using de.unkrig.commons.lang.security.Sandbox.confine to solve Java Security issue Download of Code Without Integrity Check.

Below is the findClass method in my custom classloader extends from ClassLoader.

With this implementation, it reports a StackOverFlowError.

Anyone knows what happened to this? And how to solve it?

Many thanks!

@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
    Class<?> cls;
    try {
        cls = super.findClass(name);
        Sandbox.confine(cls, getPermissions());
        return cls;
    } catch (ClassNotFoundException e) {
        for (ClassLoader delegate : _delegateClassLoaders) {
            try {
                 cls = delegate.loadClass(name);
                if (cls != null) {
                    Sandbox.confine(cls, getPermissions());
                    return cls;
                }
            } catch (ClassNotFoundException fe) {
            }
        }
    }
    throw new ClassNotFoundException(name);
}

protected Permissions getPermissions() {
    Permissions pm = new Permissions();
    FilePermission p = new FilePermission("/tmp/*", "read,write");
    pm.add(p);
    return pm;
}

Body:
(wanted to comment but I'm new here and don't have enough rep)

First, you are calling super.findClass() while you are extending ClassLoader - it will always throw a ClassNotFoundException :

protected Class<?> findClass(String name) throws ClassNotFoundException {
    throw new ClassNotFoundException(name);
}

Second I don't know this Sandbox library, but you probably have an infinite recursion here. Note that loadClass() calls findClass() in the default ClassLoader implementation;

Might it be that one of the delegates is the same class running this code? did you try to debug it?


问:
Google places api not showing results for some places
Hello i am using simple google map places api to get near by atms for users. My client lives around new york and for some strange reason api shows zero results for that place, but works fine near me (pakistan) . I searched for it a little and found out it was google's issue and some other places were also experiencing the same problem. But i never quite found any solution for this.
This is the get call i use

```<code>https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.7128,74.1059&radius=10000000&keyword=atm&key=MY_KEY
</code>```

I would really appreciate the help. Thank you :)

答:
Google place nearby search maximum 50,000 meters (31 miles) . if you try enter more than 50,000 it not work proper.

There is another way for find all ATM in a city. google provide Text Search Requests

```<code>https://maps.googleapis.com/maps/api/place/textsearch/json?query=atm+in+Reno,NV,89501,USA&key={API_KEY}
</code>```

query = keyword + in + city Name

for get city name using latitude longitude

```<code>http://maps.googleapis.com/maps/api/geocode/json?latlng=39.52963,-119.81380&sensor=true
</code>```

For more information how to get city name using latitude longitude

https://developers.google.com/maps/documentation/geocoding/start?csw=1#ReverseGeocoding

for more information about how to use Text Search Requests

https://developers.google.com/places/web-service/search

OR (second way)

There is another way for find all ATM in a city.

Open Google Maps .

create 10-12 or more points latitude , longitude value to trigger
request.

Then use a loop to find all places within these points.

If you want more appropriate results, increase first trigger points
for your requests.

- It is just a logic i created in php.

```<code>$triggerPoints = array("lat1,long1", "lat2,long2", "lat3,long3",....);

    foreeach(triggerPoints as $tP){
       $requestUrl = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$tP&radius=[YOUR_RADIUS_VALUE]&type=[YOUR_TYPE]&name=panera&key=[YOUR_KEY_HERE";
       $results = file_get_contents($requestUrl);
       //Do what you want with response JSON data

    }
</code>```

Body:
Hello i am using simple google map places api to get near by atms for users. My client lives around new york and for some strange reason api shows zero results for that place, but works fine near me (pakistan) . I searched for it a little and found out it was google's issue and some other places were also experiencing the same problem. But i never quite found any solution for this.
This is the get call i use

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.7128,74.1059&radius=10000000&keyword=atm&key=MY_KEY

I would really appreciate the help. Thank you :)

Body:
Google place nearby search maximum 50,000 meters (31 miles) . if you try enter more than 50,000 it not work proper.

There is another way for find all ATM in a city. google provide Text Search Requests

https://maps.googleapis.com/maps/api/place/textsearch/json?query=atm+in+Reno,NV,89501,USA&key={API_KEY}

query = keyword + in + city Name

for get city name using latitude longitude

http://maps.googleapis.com/maps/api/geocode/json?latlng=39.52963,-119.81380&sensor=true

For more information how to get city name using latitude longitude

https://developers.google.com/maps/documentation/geocoding/start?csw=1#ReverseGeocoding

for more information about how to use Text Search Requests

https://developers.google.com/places/web-service/search

OR (second way)

There is another way for find all ATM in a city.

Open Google Maps .

create 10-12 or more points latitude , longitude value to trigger
request.

Then use a loop to find all places within these points.

If you want more appropriate results, increase first trigger points
for your requests.

- It is just a logic i created in php.

$triggerPoints = array("lat1,long1", "lat2,long2", "lat3,long3",....);

    foreeach(triggerPoints as $tP){
       $requestUrl = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$tP&radius=[YOUR_RADIUS_VALUE]&type=[YOUR_TYPE]&name=panera&key=[YOUR_KEY_HERE";
       $results = file_get_contents($requestUrl);
       //Do what you want with response JSON data

    }

ContentLicense: CC BY-SA 4.0


问:
c# nesting classes and visibility?
I am trying to get the same functionality that a combobox has, like combobox1.Items.Add() // editor.Tags.Tags1()

Like this:

```<code>class Main()
{
    // The editor is passed into the editor class, that allows the editor class to update the editor.
    MyEditorClass editor = new MyEditorClass(editorBox);
    editor.Tags.InsertTag1();

    // Now i don't want people to do this
    // MyEditorClass.TagClass tags = new MyEditorClass.TagClass();
}
</code>```

The reason is that the tags class calls the editorBox passed into the MyEditorClass and if you create a tags class without that editor, it won't work.

My MyEditorClass looks like this:

```<code>public class MyEditorClass
{
    static RichTextBox editor;
    public TagClass Tags;

    public MyEditorClass(RichTextBox editorBox)
    {
        editor = editorBox;
        Tags = new TagClass();
    }

    public class TagClass
    {
        public void InsertTag1()
        {
            editor.Text += "Test tag 1";
        }
    }
}
</code>```

I was trying to make the TagClass static but that didn't work. How is the combobox structured? Since you cant use Combobox.Items but if you declare one you can use the Combobox.Items on the one that you declared.

答:
Make your Tags property readonly, then it can be initialized in the constructor only:

```<code>public readonly TagClass Tags;
</code>```

The object reference stored in Tags can't be changed later then and that code:

```<code>MyEditorClass editor = new MyEditorClass(editorBox);
editor.Tags = new MyEditorClass.TagClass();
</code>```

wouldn't compile.

Or, second possibility, even better - expose only public getter for your Tags property and keep the instance privately inside your MyEditorClass class, like in example below.

By the way, it don't have to do anything with nesting classes. It is quite strange to have public class inside a public class.

EDIT:
To have a structure similar to ComboBox so that TagClass has access to the editor, you can pass the editor instance to TagClass internal constructor. The constructor is internal to not allow external code to use TagClass directly.

```<code>public class MyEditorClass
{
    private readonly RichTextBox editor;
    private readonly TagClass tags;

    public TagClass Tags
    {
        get
        {
            return tags;
        }
    }

    public MyEditorClass(RichTextBox editorBox)
    {
        editor = editorBox;
        tags = new TagClass(editorBox);
    }
}

public class TagClass
{
    private RichTextBox _editor;

    internal TagClass(RichTextBox editor)
    {
        _editor = editor;
    }

    public void InsertTag1()
    {
        _editor.Text += "Test tag 1";
    }
 }
</code>```

And now this will work:

```<code>MyEditorClass editor = new MyEditorClass(editorBox);
editor.Tags.InsertTag1();
</code>```

ContentLicense: CC BY-SA 2.5

Title: c# nesting classes and visibility?

Body:
I am trying to get the same functionality that a combobox has, like combobox1.Items.Add() // editor.Tags.Tags1()

Like this:

class Main()
{
    // The editor is passed into the editor class, that allows the editor class to update the editor.
    MyEditorClass editor = new MyEditorClass(editorBox);
    editor.Tags.InsertTag1();

    // Now i don't want people to do this
    // MyEditorClass.TagClass tags = new MyEditorClass.TagClass();
}

The reason is that the tags class calls the editorBox passed into the MyEditorClass and if you create a tags class without that editor, it won't work.

My MyEditorClass looks like this:

public class MyEditorClass
{
    static RichTextBox editor;
    public TagClass Tags;

    public MyEditorClass(RichTextBox editorBox)
    {
        editor = editorBox;
        Tags = new TagClass();
    }

    public class TagClass
    {
        public void InsertTag1()
        {
            editor.Text += "Test tag 1";
        }
    }
}

I was trying to make the TagClass static but that didn't work. How is the combobox structured? Since you cant use Combobox.Items but if you declare one you can use the Combobox.Items on the one that you declared.

Body:
Make your Tags property readonly, then it can be initialized in the constructor only:

public readonly TagClass Tags;

The object reference stored in Tags can't be changed later then and that code:

MyEditorClass editor = new MyEditorClass(editorBox);
editor.Tags = new MyEditorClass.TagClass();

wouldn't compile.

Or, second possibility, even better - expose only public getter for your Tags property and keep the instance privately inside your MyEditorClass class, like in example below.

By the way, it don't have to do anything with nesting classes. It is quite strange to have public class inside a public class.

EDIT:
To have a structure similar to ComboBox so that TagClass has access to the editor, you can pass the editor instance to TagClass internal constructor. The constructor is internal to not allow external code to use TagClass directly.

public class MyEditorClass
{
    private readonly RichTextBox editor;
    private readonly TagClass tags;

    public TagClass Tags
    {
        get
        {
            return tags;
        }
    }

    public MyEditorClass(RichTextBox editorBox)
    {
        editor = editorBox;
        tags = new TagClass(editorBox);
    }
}

public class TagClass
{
    private RichTextBox _editor;

    internal TagClass(RichTextBox editor)
    {
        _editor = editor;
    }

    public void InsertTag1()
    {
        _editor.Text += "Test tag 1";
    }
 }

And now this will work:

MyEditorClass editor = new MyEditorClass(editorBox);
editor.Tags.InsertTag1();


问:
Switching from control to control in WPF by pressing some key
I need to achieve switching from textbox to textbox, button to textbox etc by pressing enter so I am wondering is there some simple way to do this, like it is WIN FORM, change property like priority 1,2,3,4 and as user pressing enter controls will be switched by numbers from lower to higher.

In wpf I couldn't find that solution but I found this, so I am wondering is it OK?!

Here is my code:

```<code>private void Grid_PreviewKeyDown_1(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Enter)
                {
                    TextBox s = e.Source as TextBox;
                    if (s != null)
                    {
                        s.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                    }
                    else
                    {
                        ComboBox cb = e.Source as ComboBox;
                        if (cb != null)
                        {
                            cb.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                        }
                        else
                        {
                            Button b = e.Source as Button;
                            if (b != null)
                            {
                                b.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                            }
                        }
                    }

                    e.Handled = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
</code>```

My controls are contained in Grid.

Thanks guys
Cheers!

答:
Since all child elements of a Grid share the same base class (UIElement) you should be able to simplify the code a bit:

```<code>private void Grid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        UIElement element = e.Source as UIElement;
        element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
    }
}
</code>```

Body:
I need to achieve switching from textbox to textbox, button to textbox etc by pressing enter so I am wondering is there some simple way to do this, like it is WIN FORM, change property like priority 1,2,3,4 and as user pressing enter controls will be switched by numbers from lower to higher.

In wpf I couldn't find that solution but I found this, so I am wondering is it OK?!

Here is my code:

private void Grid_PreviewKeyDown_1(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Enter)
                {
                    TextBox s = e.Source as TextBox;
                    if (s != null)
                    {
                        s.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                    }
                    else
                    {
                        ComboBox cb = e.Source as ComboBox;
                        if (cb != null)
                        {
                            cb.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                        }
                        else
                        {
                            Button b = e.Source as Button;
                            if (b != null)
                            {
                                b.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                            }
                        }
                    }

                    e.Handled = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

My controls are contained in Grid.

Thanks guys
Cheers!

Body:
Since all child elements of a Grid share the same base class (UIElement) you should be able to simplify the code a bit:

private void Grid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        UIElement element = e.Source as UIElement;
        element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
    }
}


问:
How to recreate a virtual env in python
I have installed virtualenv and virtualenvwrapper on Ubuntu 16.04
I have created one enviroment named env1

```<code>$ sudo apt-get install python-pip
$ pip install virtualenv
$ pip install --upgrade pip
$ pip install virtualenvwrapper
$ export WORKON_HOME=~/Envs
$ mkdir -p $WORKON_HOME
$ source /usr/local/bin/virtualenvwrapper.sh
$ mkvirtualenv env1
</code>```

Once in (env1) I have installed several packages

```<code>(env1) $ pip install numpy
(env1) $ pip install scipy
(env1) $ pip install matplotlib
(env1) $ apt-get install python-tk
</code>```

I have also installed opencv3 (I am not copying how because is too long)

I am using env1 for a specific project.

Now I want to start another project using the same packages, but I also want to add other packages.

I have created env2, and I was wondering if it is possible to copy env1 to env2 without the need to re-install everything again from scratch.

答:
pip install virtualenvwrapper and use the cpvirtualenv command

```<code>cpvirtualenv ENVNAME [TARGETENVNAME]
</code>```

http://virtualenvwrapper.readthedocs.io/en/latest/command_ref.html#cpvirtualenv

Remember to heed the warning

```<code>Copying virtual environments is not well supported. Each virtualenv has
path information hard-coded into it, and there may be cases where the copy
code does not know to update a particular file. Use with caution.
</code>```

Title: How to recreate a virtual env in python

Body:
I have installed virtualenv and virtualenvwrapper on Ubuntu 16.04
I have created one enviroment named env1

$ sudo apt-get install python-pip
$ pip install virtualenv
$ pip install --upgrade pip
$ pip install virtualenvwrapper
$ export WORKON_HOME=~/Envs
$ mkdir -p $WORKON_HOME
$ source /usr/local/bin/virtualenvwrapper.sh
$ mkvirtualenv env1

Once in (env1) I have installed several packages

(env1) $ pip install numpy
(env1) $ pip install scipy
(env1) $ pip install matplotlib
(env1) $ apt-get install python-tk

I have also installed opencv3 (I am not copying how because is too long)

I am using env1 for a specific project.

Now I want to start another project using the same packages, but I also want to add other packages.

I have created env2, and I was wondering if it is possible to copy env1 to env2 without the need to re-install everything again from scratch.

Body:
pip install virtualenvwrapper and use the cpvirtualenv command

cpvirtualenv ENVNAME [TARGETENVNAME]

http://virtualenvwrapper.readthedocs.io/en/latest/command_ref.html#cpvirtualenv

Remember to heed the warning

Copying virtual environments is not well supported. Each virtualenv has
path information hard-coded into it, and there may be cases where the copy
code does not know to update a particular file. Use with caution.


问:
Collect related values from more than one column and row into a single column
I have this table:

Which I'd like to change to this:

As you can see, I want to collect all the related entries from all of the P1 rows, across all columns, into a single column under P1, and do the same for P2 and P3 related entries.

Is there a simple way to do this in PowerQuery / M?

答:
Yes:</p>

```<code>let
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"P", type text}, {"15", Int64.Type}, {"25", Int64.Type}, {"35", Int64.Type}, {"45", Int64.Type}, {"55", Int64.Type}, {"65", Int64.Type}}),
    #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"P"}, "Attribute", "Value"),
    #"Removed Columns" = Table.RemoveColumns(#"Unpivoted Other Columns",{"Attribute"}),
    #"Grouped Rows" = Table.Group(#"Removed Columns", {"P"}, {{"AllData", each _, type table}}),
    TablesToLists = Table.TransformColumns(#"Grouped Rows",{{"AllData", each _[Value]}}),
    #"Transposed Table" = Table.Transpose(TablesToLists),
    #"Promoted Headers" = Table.PromoteHeaders(#"Transposed Table", [PromoteAllScalars=true]),
    TableFromColumns = Table.FromColumns(Record.FieldValues(#"Promoted Headers"{0}),Table.ColumnNames(#"Promoted Headers"))
in
    TableFromColumns
</code>```

Body:
Yes:

let
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"P", type text}, {"15", Int64.Type}, {"25", Int64.Type}, {"35", Int64.Type}, {"45", Int64.Type}, {"55", Int64.Type}, {"65", Int64.Type}}),
    #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"P"}, "Attribute", "Value"),
    #"Removed Columns" = Table.RemoveColumns(#"Unpivoted Other Columns",{"Attribute"}),
    #"Grouped Rows" = Table.Group(#"Removed Columns", {"P"}, {{"AllData", each _, type table}}),
    TablesToLists = Table.TransformColumns(#"Grouped Rows",{{"AllData", each _[Value]}}),
    #"Transposed Table" = Table.Transpose(TablesToLists),
    #"Promoted Headers" = Table.PromoteHeaders(#"Transposed Table", [PromoteAllScalars=true]),
    TableFromColumns = Table.FromColumns(Record.FieldValues(#"Promoted Headers"{0}),Table.ColumnNames(#"Promoted Headers"))
in
    TableFromColumns


问:
Javascript convert stringified array of objects into array of objects
I have the following variable (given to me through a HTTP response, hence the string):

```<code>var result = '[{name: "John"}, {name: "Alice"}, {name: "Lily"}]'
</code>```

In reality there are more objects and each object has more properties, but you get the idea.

When trying JSON.parse(result) I get the following error:

```<code>[{name: "John"}, {name: "Alice"}, {name: "Lily"}]
  ^

SyntaxError: Unexpected token n
</code>```

How can I parse this string into an array of javascript objects?

答:
Since your input format is rigid, parsing is trivial.</p>

```<code>function cutSides(s) { return s.substring(1, s.length - 1); }
var pairs = cutSides(result).split(', ');
var list_of_objects = pairs.map(function(s) {
    var pair = cutSides(s).split(': ');
    var result = {};
    result[pair[0]] = cutSides(pair[1]);
    return result;
});
</code>```

Body:
I have the following variable (given to me through a HTTP response, hence the string):

var result = '[{name: "John"}, {name: "Alice"}, {name: "Lily"}]'

In reality there are more objects and each object has more properties, but you get the idea.

When trying JSON.parse(result) I get the following error:

[{name: "John"}, {name: "Alice"}, {name: "Lily"}]
  ^

SyntaxError: Unexpected token n

How can I parse this string into an array of javascript objects?

Body:
Since your input format is rigid, parsing is trivial.

function cutSides(s) { return s.substring(1, s.length - 1); }
var pairs = cutSides(result).split(', ');
var list_of_objects = pairs.map(function(s) {
    var pair = cutSides(s).split(': ');
    var result = {};
    result[pair[0]] = cutSides(pair[1]);
    return result;
});


问:
CSS: How can I select all ul tags contained within ol tags
My HTML looks like

```<code><ol class='enlarge'>
<li>Larger
<ul>
<li>Normal
</li>
</ul>
</li>
</ol>
</code>```

Where you see Larger I want the font size to be larger. And where you see Normal, I want the font size to be normal.

I've tried

```<code>  ol.enlarge {
    font-size: 130%;
  }
  ul.enlarge {
    font-size: 70%;
  }
</code>```

And

```<code>  ol {
    font-size: 130%;
  }
  ul > ol {
    font-size: 70%;
  }
</code>```

And

```<code>  ol {
    font-size: 130%;
  }
  ol > ul {
    font-size: 70%;
  }
</code>```

All are setting the font size bigger for everything in my

Thanks!

-Tom

答:
Not sure If I fully understand you, but what about this. </p>

```<code>OL LI { font-size: 130%; }
UL LI { font-size: 70%; }
</code>```

Body:
My HTML looks like

Larger

Normal

Where you see Larger I want the font size to be larger. And where you see Normal, I want the font size to be normal.

I've tried

  ol.enlarge {
    font-size: 130%;
  }
  ul.enlarge {
    font-size: 70%;
  }

And

  ol {
    font-size: 130%;
  }
  ul > ol {
    font-size: 70%;
  }

And

  ol {
    font-size: 130%;
  }
  ol > ul {
    font-size: 70%;
  }

All are setting the font size bigger for everything in my

Thanks!

-Tom

Body:
Not sure If I fully understand you, but what about this.

OL LI { font-size: 130%; }
UL LI { font-size: 70%; }


问:
GridView.getChildAt(index) returns null
I'm populating a GridView wth an AsyncTask:

```<code>@Override
public void onLoad() {
    super.onLoad();
    //... set Loading view and actually get the data
    adapter = new DepartmentGridAdapter(getActivity(), R.layout.gird_department_item_layout,
            mSalesPresenter.getDepartments());
}

@Override
public void onDoneLoading() {
    super.onDoneLoading();
    gridView.setAdapter(adapter); // Populate the GridView
    onShowTutorial(); // <--- This is where I need to get the firstChild.
}
</code>```

After the AsyncTask is done, I just need to access the firstChild of the GridView:

```<code>@Override
public void onShowTutorial() {
    if (gridView.getChildAt( gridView.getFirstVisiblePosition())!= null )
        // ... doStuff
}
</code>```

But the statement is Always null. I even call getCount for the GridView and it's not 0. The problem seems that the GridView childs are not accesible right away. If i Use a button to force the execution of the method onShowTutorial() after the UI is ready then I can access the first child.

I'm running out of ideas to trigger the method after the execution of the thread.

Any solution?

答:
Found it.

I used a ViewTreeObserver and it works:

```<code>gridView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            onShowTutorial();
        }
    });
</code>```

Title: GridView.getChildAt(index) returns null

Body:
I'm populating a GridView wth an AsyncTask:

@Override
public void onLoad() {
    super.onLoad();
    //... set Loading view and actually get the data
    adapter = new DepartmentGridAdapter(getActivity(), R.layout.gird_department_item_layout,
            mSalesPresenter.getDepartments());
}

@Override
public void onDoneLoading() {
    super.onDoneLoading();
    gridView.setAdapter(adapter); // Populate the GridView
    onShowTutorial(); // <--- This is where I need to get the firstChild.
}

After the AsyncTask is done, I just need to access the firstChild of the GridView:

@Override
public void onShowTutorial() {
    if (gridView.getChildAt( gridView.getFirstVisiblePosition())!= null )
        // ... doStuff
}

But the statement is Always null. I even call getCount for the GridView and it's not 0. The problem seems that the GridView childs are not accesible right away. If i Use a button to force the execution of the method onShowTutorial() after the UI is ready then I can access the first child.

I'm running out of ideas to trigger the method after the execution of the thread.

Any solution?

Body:
Found it.

I used a ViewTreeObserver and it works:

gridView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            onShowTutorial();
        }
    });


问:
React native : Is there any way to redirect the initial route to another page
I'm new in react native and currently developing a react-native app that require login. After successful login, the view change into Homepage. The problem is after i close and re-open the app, it shows me LoginPage again.Is there any way to redirect the initial route to another page

```<code> class Main extends Component {

  _renderScene(route, navigator) {
      if (route.id === 1) {
        return <LoginPage navigator={navigator} />
      } else if (route.id === 2) {
        return <HomePage navigator={navigator} />
      } else if (route.id === 3) {
        return <DetailPage navigator={navigator} />
      }  else if (route.id === 4) {
        return <CreateBookingPage navigator={navigator} />
      }
  }

  _configureScene(route) {
    return Navigator.SceneConfigs.PushFromRight;
  }

  render() {
      return (
        <Navigator
        initialRoute={{id: 1, }}
        renderScene={this._renderScene}
        configureScene={ () => { return Navigator.SceneConfigs.PushFromRight; }} />
      );
  }
}
</code>```

/////after some changes I get into this but still its rendering the login is I done something wrong////////

```<code>   componentWillMount() {
    AsyncStorage.getItem('key').then( (value) => {
        if(value==="yes") {
            this.setState({ loader: false, logged: true})
        } else {
            this.setState({ loader: false })
        }
    })
}

render() {
    const routeId = this.state.logged ? 2 : 1;
    if(this.state.loader) {
        return (
            <View /> // loading screen
        );
    }
    return (
        <Navigator
            initialRoute={{id: routeId }}
            renderScene={this._renderScene}
            configureScene={ () => { return Navigator.SceneConfigs.PushFromRight; }} />
    );
}
</code>```

答:
On successful login you could set a token/value in the local storage of the device and on logout clear this value.
You could check this value for setting the initial route. Asyncstorage can be used in setting and removing the logged status.

EDIT:
Initial state of loader should be true, logged should be false

```<code>  componentWillMount() {
   AsyncStorage.getItem('key').then( (value) => {
     if(value) {
       this.setState({ loader: false, logged: true})
     } else {
       this.setState({ loader: false })
    }
   })
 }

  render() {
    const { loader } = this.state;
    const routeId = logged ? 2 : 1;
    if(loader) {
    return (
     <View /> // loading screen
   );
}
    return (
      <Navigator
      initialRoute={{id: routeId }}
      renderScene={this._renderScene}
      configureScene={ () => { return Navigator.SceneConfigs.PushFromRight; }} />
    );
 }
</code>```

Body:
I'm new in react native and currently developing a react-native app that require login. After successful login, the view change into Homepage. The problem is after i close and re-open the app, it shows me LoginPage again.Is there any way to redirect the initial route to another page

 class Main extends Component {

  _renderScene(route, navigator) {
      if (route.id === 1) {
        return <LoginPage navigator={navigator} />
      } else if (route.id === 2) {
        return <HomePage navigator={navigator} />
      } else if (route.id === 3) {
        return <DetailPage navigator={navigator} />
      }  else if (route.id === 4) {
        return <CreateBookingPage navigator={navigator} />
      }
  }

  _configureScene(route) {
    return Navigator.SceneConfigs.PushFromRight;
  }

  render() {
      return (
        <Navigator
        initialRoute={{id: 1, }}
        renderScene={this._renderScene}
        configureScene={ () => { return Navigator.SceneConfigs.PushFromRight; }} />
      );
  }
}

/////after some changes I get into this but still its rendering the login is I done something wrong////////

   componentWillMount() {
    AsyncStorage.getItem('key').then( (value) => {
        if(value==="yes") {
            this.setState({ loader: false, logged: true})
        } else {
            this.setState({ loader: false })
        }
    })
}

render() {
    const routeId = this.state.logged ? 2 : 1;
    if(this.state.loader) {
        return (
            <View /> // loading screen
        );
    }
    return (
        <Navigator
            initialRoute={{id: routeId }}
            renderScene={this._renderScene}
            configureScene={ () => { return Navigator.SceneConfigs.PushFromRight; }} />
    );
}

Body:
On successful login you could set a token/value in the local storage of the device and on logout clear this value.
You could check this value for setting the initial route. Asyncstorage can be used in setting and removing the logged status.

EDIT:
Initial state of loader should be true, logged should be false

  componentWillMount() {
   AsyncStorage.getItem('key').then( (value) => {
     if(value) {
       this.setState({ loader: false, logged: true})
     } else {
       this.setState({ loader: false })
    }
   })
 }

  render() {
    const { loader } = this.state;
    const routeId = logged ? 2 : 1;
    if(loader) {
    return (
     <View /> // loading screen
   );
}
    return (
      <Navigator
      initialRoute={{id: routeId }}
      renderScene={this._renderScene}
      configureScene={ () => { return Navigator.SceneConfigs.PushFromRight; }} />
    );
 }


问:
Cross Platform App for iOS and Android
I saw this video how to make cross platform App: https://youtu.be/CUROh7r4qrM?t=1311

But I only have Cross Platform App (Xamarin.Forms or Native) and not Blank.App Portable.

Any ideas why?

答: You can choose whether you want Blank App or not in the next step of the project creation wizard.

Title: Cross Platform App for iOS and Android


问:
Django Export data from postGre to shapeFile
I'm new in django and python.

I've tried to export database data to shapefile using https://bitbucket.org/springmeyer/django-shapes/src
 and i got a Segmentation fault. is there is anyway to make this work by only using django GeoDjango?

答:
That's a non-updated project. You can check this a bit more up to date fork.

To check quickly if it works for you download the zip and copy the shape-engine folder inside your django project.

Install fiona (pip install fiona)

Add a new url to download the shapfile like

```<code>from .views import export
urlpatterns = urlpatterns + [ url(r'^worldshapes/', export_worldshapes), ]
</code>```

And a new view:

```<code>from shape_engine.shape_responder import ShpResponder
def export(request):
    from .models import WorldBorders
    w = WorldBorders.objects.all()
    shp_response = ShpResponder(w)
    shp_response.file_name = 'World Borders'
    return shp_response()
</code>```

django-shape-engine only works in python 2.x. A couple of changes should be made to work with it in python 3. Basically, use BytesIO instead of StringIO

Body:
That's a non-updated project. You can check this a bit more up to date fork.

To check quickly if it works for you download the zip and copy the shape-engine folder inside your django project.

Install fiona (pip install fiona)

Add a new url to download the shapfile like

from .views import export
urlpatterns = urlpatterns + [ url(r'^worldshapes/', export_worldshapes), ]

And a new view:

from shape_engine.shape_responder import ShpResponder
def export(request):
    from .models import WorldBorders
    w = WorldBorders.objects.all()
    shp_response = ShpResponder(w)
    shp_response.file_name = 'World Borders'
    return shp_response()

django-shape-engine only works in python 2.x. A couple of changes should be made to work with it in python 3. Basically, use BytesIO instead of StringIO


问:
Is fs the only builtin module that can access the filesystem?
I know there are other things like require that can access the real filesystem, but this appears to use fs to do so.

Am I right in thinking that there are no other builtins that have direct access to the disk?

That is, if I was able to globally overwrite all fs methods with my own mocks that read from (and write to) an in-memory virtual filesystem, then there would be no way to access the real filesystem – is that correct?

答:
There are many ways you can access the file system.

Make a child process execute

```<code>ls
cd ..
nano filename
</code>```

and fetch the result.

Body:
There are many ways you can access the file system.

Make a child process execute

ls
cd ..
nano filename

and fetch the result.


问:
C# read string from back to end
I have a string. For example :

```<code>string a = "abcdef098403248";
</code>```

My goal is, knowing that the string ends with a number (else something like this will happen : MessageBox.Show("String doesnt end in a number"); ), i want to read the string, starting from the end to the begining, and store the values in another string.
Now the only problem is, i can only store in that new string numbers, and when i read the string a , while i count from the back to end if i find a character that isnt a number, i stop reading and store the previous numbers found in the new string. The code output should look somthing like this:

```<code>string a = "aBcdef3213BBBBB0913456";
//part were i read the string from back to end
string finalString = "0913456";
</code>```

As you see there, i store the numbers from left to right, but i want to read them from right to left.

Another example of what i want:

```<code>string a = "aaaaa3a224444";
// part were i read the string from back to end
string finalString = "224444";
</code>```

Or:

```<code>string a = "3333333a224444";
// part were i read the string from back to end
string finalString = "224444";
</code>```

Regardless, thanks.

答:
Reverse the string using the function below.

Grab the number the wrong way around - spin it back.

```<code>public static string Reverse( string s )
{
    char[] charArray = s.ToCharArray();
    Array.Reverse( charArray );
    return new string( charArray );
}
</code>```

Taken from : Best way to reverse a string

Title: C# read string from back to end

Body:
I have a string. For example :

string a = "abcdef098403248";

My goal is, knowing that the string ends with a number (else something like this will happen : MessageBox.Show("String doesnt end in a number"); ), i want to read the string, starting from the end to the begining, and store the values in another string.
Now the only problem is, i can only store in that new string numbers, and when i read the string a , while i count from the back to end if i find a character that isnt a number, i stop reading and store the previous numbers found in the new string. The code output should look somthing like this:

string a = "aBcdef3213BBBBB0913456";
//part were i read the string from back to end
string finalString = "0913456";

As you see there, i store the numbers from left to right, but i want to read them from right to left.

Another example of what i want:

string a = "aaaaa3a224444";
// part were i read the string from back to end
string finalString = "224444";

Or:

string a = "3333333a224444";
// part were i read the string from back to end
string finalString = "224444";

Regardless, thanks.

Body:
Reverse the string using the function below.

Grab the number the wrong way around - spin it back.

public static string Reverse( string s )
{
    char[] charArray = s.ToCharArray();
    Array.Reverse( charArray );
    return new string( charArray );
}

Taken from : Best way to reverse a string


问:
Using COUNT on two MySQL fields (then need the sum of the two fields)
I have the following MySQL query which works fine to give me the Count of the "smconnectivity_b" field.

We added in a second field called: "smconnectivity_c" which can also have values.

I need to include any of these new values in the same Count logic below:

```<code>    SELECT smconnectivity_b, COUNT(smconnectivity_b) AS Used, LEFT(smconnectivity_b, 4) AS Collo, 144 - COUNT(smconnectivity_b) AS Available, concat(round(( COUNT(smconnectivity_b)/144 * 100 ),1),'%') AS percentage, (round(( COUNT(smconnectivity_b)/144 * 100 ),1)) AS percentage2,

CASE
        WHEN COUNT(smconnectivity_b) >= 25 AND COUNT(smconnectivity_b) < 121 THEN 'Yellow'
        WHEN COUNT(smconnectivity_b) >= 121 AND COUNT(smconnectivity_b) < 145 THEN 'Red'

ELSE 'Green'
END AS Color

FROM     tblsplicemapping

GROUP BY smconnectivity_b
ORDER BY smconnectivity_b
</code>```

答:
First, your query would probably be faster like this:

```<code>SELECT  smconnectivity_b, Used,
        LEFT(smconnectivity_b, 4) AS Collo, 144 - Used AS Available,
        concat(round(( Used/144 * 100 ),1),'%') AS percentage,
        (round(( Used/144 * 100 ),1)) AS percentage2,
        CASE
        WHEN Used >= 25 AND Used < 121 THEN 'Yellow'
        WHEN Used >= 121 AND Used < 145 THEN 'Red'
        ELSE 'Green' END AS Color

FROM (
    SELECT smconnectivity_b, count(*) AS Used
        FROM     tblsplicemapping
        GROUP BY smconnectivity_b
    ) subselect
ORDER BY smconnectivity_b
</code>```

Now...

We added in a second field called: "smconnectivity_c" which can also have values. I need to include any of these new values in the same Count logic below

You can't really do that in this query. The simplest would be to make two separate queries. If you want to combine them, you can always use UNION ALL.

Body:
I have the following MySQL query which works fine to give me the Count of the "smconnectivity_b" field.

We added in a second field called: "smconnectivity_c" which can also have values.

I need to include any of these new values in the same Count logic below:

    SELECT smconnectivity_b, COUNT(smconnectivity_b) AS Used, LEFT(smconnectivity_b, 4) AS Collo, 144 - COUNT(smconnectivity_b) AS Available, concat(round(( COUNT(smconnectivity_b)/144 * 100 ),1),'%') AS percentage, (round(( COUNT(smconnectivity_b)/144 * 100 ),1)) AS percentage2,

CASE
        WHEN COUNT(smconnectivity_b) >= 25 AND COUNT(smconnectivity_b) < 121 THEN 'Yellow'
        WHEN COUNT(smconnectivity_b) >= 121 AND COUNT(smconnectivity_b) < 145 THEN 'Red'

ELSE 'Green'
END AS Color

FROM     tblsplicemapping

GROUP BY smconnectivity_b
ORDER BY smconnectivity_b

Body:
First, your query would probably be faster like this:

SELECT  smconnectivity_b, Used,
        LEFT(smconnectivity_b, 4) AS Collo, 144 - Used AS Available,
        concat(round(( Used/144 * 100 ),1),'%') AS percentage,
        (round(( Used/144 * 100 ),1)) AS percentage2,
        CASE
        WHEN Used >= 25 AND Used < 121 THEN 'Yellow'
        WHEN Used >= 121 AND Used < 145 THEN 'Red'
        ELSE 'Green' END AS Color

FROM (
    SELECT smconnectivity_b, count(*) AS Used
        FROM     tblsplicemapping
        GROUP BY smconnectivity_b
    ) subselect
ORDER BY smconnectivity_b

Now...

We added in a second field called: "smconnectivity_c" which can also have values. I need to include any of these new values in the same Count logic below

You can't really do that in this query. The simplest would be to make two separate queries. If you want to combine them, you can always use UNION ALL.


问:
how to bring an instance from one subnet to the other which is having a docker containers running in that instance?
I have tried it by creating an AMI and then tried to launching an instance in the private subnet, but I don't see any containers inside the second instance.</p>

答:
Make sure that :

Docker daemon is running  ( check how to start it at the boot time, For example: systemd, chckconfig ... )

Make sure your containers were started on the original instance with --restart=always  or again use something to start them ( cron / systemd ... )


问:
Transaction within a cursor
Is the following the correct way to use transactions within a cursor:</p>

```<code>SET CURSOR_CLOSE_ON_COMMIT ON;

DECLARE cur CURSOR LOCAL FOR
    SELECT * FROM @ordersToProcess;
OPEN cur;

DECLARE @OrderId int;

FETCH NEXT FROM cur INTO @OrderId;
WHILE @@FETCH_STATUS = 0 BEGIN
    BEGIN TRY
        BEGIN TRAN;
        EXEC process_order @OrderId;
        COMMIT TRAN;
        DEALLOCATE cur;
        SET CURSOR_CLOSE_ON_COMMIT OFF;
    END TRY
    BEGIN CATCH
        ROLLBACK TRAN;
        DEALLOCATE cur;
        SET CURSOR_CLOSE_ON_COMMIT OFF;
        THROW;
    END CATCH;

    FETCH NEXT FROM cur INTO @OrderId;
END;
</code>```

答:
Deallocate and Close after the cursor has finished:</p>

```<code>DECLARE cur CURSOR LOCAL FOR
    SELECT * FROM @ordersToProcess;
OPEN cur;
DECLARE @OrderId int;

FETCH NEXT FROM cur INTO @OrderId;
WHILE @@FETCH_STATUS = 0 BEGIN
    BEGIN TRY
        BEGIN TRAN;
        EXEC process_order @OrderId;
        COMMIT TRAN;
    END TRY
    BEGIN CATCH
        ROLLBACK TRAN;
        THROW;
    END CATCH;

    FETCH NEXT FROM cur INTO @OrderId;
END;

BEGIN TRY
    CLOSE Cursor1
    DEALLOCATE Cursor1
END TRY
BEGIN CATCH
 --Do nothing
END CATCH
</code>```

Title: Transaction within a cursor

Body:
Is the following the correct way to use transactions within a cursor:

SET CURSOR_CLOSE_ON_COMMIT ON;

DECLARE cur CURSOR LOCAL FOR
    SELECT * FROM @ordersToProcess;
OPEN cur;

DECLARE @OrderId int;

FETCH NEXT FROM cur INTO @OrderId;
WHILE @@FETCH_STATUS = 0 BEGIN
    BEGIN TRY
        BEGIN TRAN;
        EXEC process_order @OrderId;
        COMMIT TRAN;
        DEALLOCATE cur;
        SET CURSOR_CLOSE_ON_COMMIT OFF;
    END TRY
    BEGIN CATCH
        ROLLBACK TRAN;
        DEALLOCATE cur;
        SET CURSOR_CLOSE_ON_COMMIT OFF;
        THROW;
    END CATCH;

    FETCH NEXT FROM cur INTO @OrderId;
END;

Body:
Deallocate and Close after the cursor has finished:

DECLARE cur CURSOR LOCAL FOR
    SELECT * FROM @ordersToProcess;
OPEN cur;
DECLARE @OrderId int;

FETCH NEXT FROM cur INTO @OrderId;
WHILE @@FETCH_STATUS = 0 BEGIN
    BEGIN TRY
        BEGIN TRAN;
        EXEC process_order @OrderId;
        COMMIT TRAN;
    END TRY
    BEGIN CATCH
        ROLLBACK TRAN;
        THROW;
    END CATCH;

    FETCH NEXT FROM cur INTO @OrderId;
END;

BEGIN TRY
    CLOSE Cursor1
    DEALLOCATE Cursor1
END TRY
BEGIN CATCH
 --Do nothing
END CATCH


问:
Visual Studio/C# auto-format. Can I control newline after attributes
Visual studio keeps doing this:

```<code>[DataContract]
public class MyContract
{
    [DataMember]
    public bool MyBool { get; set; }
    [DataMember]
    public string MyString { get; set; }
}
</code>```

I would like this:

```<code>[DataContract]
public class MyContract
{
    [DataMember] public bool MyBool { get; set; }
    [DataMember] public string MyString { get; set; }
}
</code>```

No big deal if the 'public class MyContract' is on the same line as the [DataContract].

Visual studio seems to have a lot of detailed autoformatting options, but I can't find any regarding newlines after attributes.  Am I missing something here?  Or is it just not available.

EDIT: At very least, I'd like a "don't change what I entered" formatting option, as opposed to a "always insert" or "always remove" newline option.  It's super-annoying that it keeps unformatting my code after I type.

答:
What worked best for me was to disable auto format on ; and paste. I hardly ever want auto format at these times anyways. This allows you to type out attributes and move them around without pesky interference.

Options > Text Editor > C# > Formatting > General

Body:
Visual studio keeps doing this:

[DataContract]
public class MyContract
{
    [DataMember]
    public bool MyBool { get; set; }
    [DataMember]
    public string MyString { get; set; }
}

I would like this:

[DataContract]
public class MyContract
{
    [DataMember] public bool MyBool { get; set; }
    [DataMember] public string MyString { get; set; }
}

No big deal if the 'public class MyContract' is on the same line as the [DataContract].

Visual studio seems to have a lot of detailed autoformatting options, but I can't find any regarding newlines after attributes.  Am I missing something here?  Or is it just not available.

EDIT: At very least, I'd like a "don't change what I entered" formatting option, as opposed to a "always insert" or "always remove" newline option.  It's super-annoying that it keeps unformatting my code after I type.


问:
Print value after certain word and upto mentioned word
So I have a file.txt that goes like this

```<code>abc, def, class="my_name", this is good
def, hij, this is getting bad, and bad, class="my_class"
trying to achive my goal class="still_looking"
</code>```

So I need a value of class, ie:

```<code>my_name
my_class
still_looking
</code>```

I tried sed and grep but no success.

```<code>sed "s/[^class=]*,\([^\"]*\),^C/\1/" file.txt

grep -oP '(?<=class)[0-9][a-z][A-Z]+' file.txt
</code>```

答:
Another variant:</p>

```<code>grep -oP 'class="\K.*?(?=")'
</code>```

Body:
So I have a file.txt that goes like this

abc, def, class="my_name", this is good
def, hij, this is getting bad, and bad, class="my_class"
trying to achive my goal class="still_looking"

So I need a value of class, ie:

my_name
my_class
still_looking

I tried sed and grep but no success.

sed "s/[^class=]*,\([^\"]*\),^C/\1/" file.txt

grep -oP '(?<=class)[0-9][a-z][A-Z]+' file.txt

Body:
Another variant:

grep -oP 'class="\K.*?(?=")'


问:
Change column value depending on other columns
I have a dataframe:

```<code>chrom position ref var normal_reads1 normal_reads2 normal_var_freq normal_gt tumor_reads1 tumor_reads2 tumor_var_freq tumor_gt somatic_status variant_p_value somatic_p_value
1    2L    13048   A   T            32            23           41.82         W           17            6          26.09        W       Germline    7.507123e-11       0.9437542
2    2L    16467   G   A             0            43          100.00         A            0           24         100.00        A           <NA>    6.674261e-40       1.0000000
3    2L    20682   T   A            32            14           30.43         W           14            6          30.00        W       Germline    1.746726e-07       0.6223244
4    2L    25727   T   G            52            22           29.73         K           16            4          20.00        K       Germline    2.000049e-09       0.8758070
5    2L    25729   A   T            49            23           31.94         W           16            4          20.00        W       Germline    7.938282e-10       0.9092970
6    2L    25741   T   C            45            28           38.36         Y           15            6          28.57        Y       Germline    1.497796e-12       0.8604958
</code>```

I'm trying to change to value of the somatic_status col to "ROH" if both normal_var_freq and tumor_var_freq are > 90

Here's what I've tried:

```<code>snps <- within(snps, somatic_status[normal_var_freq > 90 & tumor_var_freq > 90] <- 'ROH')
</code>```

but I get the error:

```<code>Warning message:
In `[<-.factor`(`*tmp*`, normal_var_freq > 90 & tumor_var_freq >  :
  invalid factor level, NA generated
</code>```

Can someone point me in the right direction?

答:
We can the factor to character class before assigning the values to 'ROH' based on the logical vector ('i1')

```<code>i1 <- with(snps, normal_var_freq > 90 & tumor_var_freq > 90)
snps$somatic_status <- as.character(snps$somatic_status)
snps$somatic_status[i1] <- "ROH"
</code>```

or add a new level to the column if we don't want to convert the factor column to character before changing some of the elements to a new value

```<code>levels(snps$somatic_status) <- c(levels(snps$somatic_status), "ROH")
snps$somatic_status[i1] <- "ROH"
</code>```

Regarding the usage of within, it is a useful function for creating new variables or updates old variables, but the assigning a subset of values to new value is not recommended

Body:
I have a dataframe:

chrom position ref var normal_reads1 normal_reads2 normal_var_freq normal_gt tumor_reads1 tumor_reads2 tumor_var_freq tumor_gt somatic_status variant_p_value somatic_p_value
1    2L    13048   A   T            32            23           41.82         W           17            6          26.09        W       Germline    7.507123e-11       0.9437542
2    2L    16467   G   A             0            43          100.00         A            0           24         100.00        A           <NA>    6.674261e-40       1.0000000
3    2L    20682   T   A            32            14           30.43         W           14            6          30.00        W       Germline    1.746726e-07       0.6223244
4    2L    25727   T   G            52            22           29.73         K           16            4          20.00        K       Germline    2.000049e-09       0.8758070
5    2L    25729   A   T            49            23           31.94         W           16            4          20.00        W       Germline    7.938282e-10       0.9092970
6    2L    25741   T   C            45            28           38.36         Y           15            6          28.57        Y       Germline    1.497796e-12       0.8604958

I'm trying to change to value of the somatic_status col to "ROH" if both normal_var_freq and tumor_var_freq are > 90

Here's what I've tried:

snps <- within(snps, somatic_status[normal_var_freq > 90 & tumor_var_freq > 90] <- 'ROH')

but I get the error:

Warning message:
In `[<-.factor`(`*tmp*`, normal_var_freq > 90 & tumor_var_freq >  :
  invalid factor level, NA generated

Can someone point me in the right direction?

Body:
We can the factor to character class before assigning the values to 'ROH' based on the logical vector ('i1')

i1 <- with(snps, normal_var_freq > 90 & tumor_var_freq > 90)
snps$somatic_status <- as.character(snps$somatic_status)
snps$somatic_status[i1] <- "ROH"

or add a new level to the column if we don't want to convert the factor column to character before changing some of the elements to a new value

levels(snps$somatic_status) <- c(levels(snps$somatic_status), "ROH")
snps$somatic_status[i1] <- "ROH"

Regarding the usage of within, it is a useful function for creating new variables or updates old variables, but the assigning a subset of values to new value is not recommended


问:
Export DIV to PDF
So i am trying to export a specific div to a PDF file and i am failing miserably...
This is the page:

<!DOCTYPE HTML>

  <title>Testpage</title>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />

        <link rel="stylesheet" href="../assets/css/jquery.dataTable.min.css" />
  <link rel="stylesheet" href="../assets/css/main.css" />
        <link rel="stylesheet" href="../assets/css/toastr.css" />
        <link rel="stylesheet" href="../assets/css/chart.css" />

Test

Table

            Time
            Speed
            Meters

            <?php
             require_once ('showData.php');
            ?>

Menü

Home

         Test

Test1

Test2

Filter

                            <form method="post" id="submitdata" name="submitdata">

                                        <input type="text" name="datefrom" id="datefrom" value="" placeholder="Date from" />

                                        <input type="text" name="dateto" id="dateto" value="" placeholder="Date to" />

                                            <select name="dropdown" id="dropdown">
                                                <option value="0">- Choose -</option>
                                                <option value="1">All</option>
                                                <option value="2">Speed</option>
                                                <option value="3">Meter</option>
                                            </select>

<input type="submit" id="btnSubmit" value="Clickme" class="special" />

<input type="reset" value="Reset" />

                            </form>

Export

                                <button id="btnExport" class="button special icon fa-file-pdf-o">Export as PDF</button>

 Stuff

```
</div>
</div>
</p>

<p>I am trying to get everything in <code><div class="inner" id="inner"></code> into an PDF-File but nothing seems to work. I tried with jsPDF and html2canvas (html -> img -> pdf) but the quality is VERY bad. Nothing else seems to work.
I would appreciate some pointers like what i can use to get it working.</p>

<p>Thank you very much,
Skar</p>

<p>EDIT:
This is what i included after the jsPDF recommendation</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>            <script src="../assets/jsPDF/jspdf.debug.js"></script>
            <script src="../assets/jsPDF/examples/js/html2canvas.js"></script>

            <script>

                var doc = new jsPDF();

                var specialElementHandlers = {
                    '#header': function(element, renderer){
                        return true;
                    }
                };

                $('#btnExport').click(function(){
                    var html=$("#inner").html();
                    doc.fromHTML(html,0,0, {
                        'width': 500,
                        'elementHandlers': specialElementHandlers
                    });
                    doc.save("Test.pdf");
                });

            </script></code>```

答:
Try this library, it is built for client side PDF generation.

https://parall.ax/products/jspdf

Here is the github link

Title: Export DIV to PDF

Body:
So i am trying to export a specific div to a PDF file and i am failing miserably...
This is the page:

<!DOCTYPE HTML>

  <title>Testpage</title>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />

        <link rel="stylesheet" href="../assets/css/jquery.dataTable.min.css" />
  <link rel="stylesheet" href="../assets/css/main.css" />
        <link rel="stylesheet" href="../assets/css/toastr.css" />
        <link rel="stylesheet" href="../assets/css/chart.css" />

Test

Table

            Time
            Speed
            Meters

            <?php
             require_once ('showData.php');
            ?>

Menü

Home

         Test

Test1

Test2

Filter

                            <form method="post" id="submitdata" name="submitdata">

                                        <input type="text" name="datefrom" id="datefrom" value="" placeholder="Date from" />

                                        <input type="text" name="dateto" id="dateto" value="" placeholder="Date to" />

                                            <select name="dropdown" id="dropdown">
                                                <option value="0">- Choose -</option>
                                                <option value="1">All</option>
                                                <option value="2">Speed</option>
                                                <option value="3">Meter</option>
                                            </select>

<input type="submit" id="btnSubmit" value="Clickme" class="special" />

<input type="reset" value="Reset" />

                            </form>

Export

                                <button id="btnExport" class="button special icon fa-file-pdf-o">Export as PDF</button>

 Stuff

I am trying to get everything in
 into an PDF-File but nothing seems to work. I tried with jsPDF and html2canvas (html -> img -> pdf) but the quality is VERY bad. Nothing else seems to work.
I would appreciate some pointers like what i can use to get it working.

Thank you very much,
Skar

EDIT:
This is what i included after the jsPDF recommendation