问:
Zoom with animation in current location when map loads in IOS
I have used map in my view controller but when the maps loads it shows me view of the whole country. I want to show my current location view when maps loads, for that I have used didUpdateUserLocation method and set delegate for it.

My code is this:

```<code>-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
   [self.mapView setRegion:MKCoordinateRegionMake(_userLocation.coordinate, MKCoordinateSpanMake(0.1f, 0.1f)) animated:YES];
}
</code>```

Now when my map loads it animate and zoom but in wrong location. It is taking me to any location in sea when map loads , but my current location is different.

I have also tested it in real device but it does not show my location.

The maps looks like that when loads:

ViewController class code:

```<code>@property BOOL updateUserLocation;
@property(strong,nonatomic) CLLocation *userLocation;

@property (nonatomic, retain) MKPolyline *routeLine;

@property (nonatomic, retain) MKPolylineView *routeLineView;

@property (nonatomic,retain) NSString *latitude;

@property (nonatomic,retain) NSString *longitude;
- (void)viewDidLoad {
[super viewDidLoad];
 [[self navigationController] setNavigationBarHidden:YES animated:YES];
_AlertView.hidden=YES;
_distanceView.hidden=YES;
self.mapView.zoomEnabled=YES;

locationManager = [[CLLocationManager alloc]init];
locationManager.delegate = self;
[locationManager startUpdatingLocation];

[self.mapView setShowsUserLocation:YES];
[self.mapView setDelegate:self];

}

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
[self.mapView setRegion:MKCoordinateRegionMake(_userLocation.coordinate, MKCoordinateSpanMake(0.1f, 0.1f)) animated:YES];
}
</code>```

答:
Use didUpdateToLocation instead of didUpdateUserLocation.

```<code>- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    [self.locationManager stopUpdatingLocation];

    MKCoordinateRegion region;
    region.span.latitudeDelta = 0.005;
    region.span.longitudeDelta = 0.005;
    region.center.latitude = newLocation.coordinate.latitude;
    region.center.longitude = newLocation.coordinate.longitude;
    [self.mapView setRegion:region animated:YES];
}
</code>```

See also my library.

https://github.com/koogawa/KGWLocationPicker/blob/master/KGWLocationPicker/KGWLocationPickerViewController.m

Body:
I have used map in my view controller but when the maps loads it shows me view of the whole country. I want to show my current location view when maps loads, for that I have used didUpdateUserLocation method and set delegate for it.

My code is this:

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
   [self.mapView setRegion:MKCoordinateRegionMake(_userLocation.coordinate, MKCoordinateSpanMake(0.1f, 0.1f)) animated:YES];
}

Now when my map loads it animate and zoom but in wrong location. It is taking me to any location in sea when map loads , but my current location is different.

I have also tested it in real device but it does not show my location.

The maps looks like that when loads:

ViewController class code:

@property BOOL updateUserLocation;
@property(strong,nonatomic) CLLocation *userLocation;

@property (nonatomic, retain) MKPolyline *routeLine;

@property (nonatomic, retain) MKPolylineView *routeLineView;

@property (nonatomic,retain) NSString *latitude;

@property (nonatomic,retain) NSString *longitude;
- (void)viewDidLoad {
[super viewDidLoad];
 [[self navigationController] setNavigationBarHidden:YES animated:YES];
_AlertView.hidden=YES;
_distanceView.hidden=YES;
self.mapView.zoomEnabled=YES;

locationManager = [[CLLocationManager alloc]init];
locationManager.delegate = self;
[locationManager startUpdatingLocation];

[self.mapView setShowsUserLocation:YES];
[self.mapView setDelegate:self];

}

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
[self.mapView setRegion:MKCoordinateRegionMake(_userLocation.coordinate, MKCoordinateSpanMake(0.1f, 0.1f)) animated:YES];
}

Body:
Use didUpdateToLocation instead of didUpdateUserLocation.

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    [self.locationManager stopUpdatingLocation];

    MKCoordinateRegion region;
    region.span.latitudeDelta = 0.005;
    region.span.longitudeDelta = 0.005;
    region.center.latitude = newLocation.coordinate.latitude;
    region.center.longitude = newLocation.coordinate.longitude;
    [self.mapView setRegion:region animated:YES];
}

See also my library.

https://github.com/koogawa/KGWLocationPicker/blob/master/KGWLocationPicker/KGWLocationPickerViewController.m


来源: stackexchange

问:
Chaining methods using promises
I'm trying to get my head around promises, I think I can see how they work in the way that you can say do Step 1, Step 2 and then Step 3 for example.

I have created this download function using node-fetch (which uses native Promises)

```<code>## FileDownload.js

const fetch = require('node-fetch');
const fs = require('fs');

module.exports = function(url, target) {
  fetch(url)
    .then(function(res) {
      var dest = fs.createWriteStream(target);
      res.body.pipe(dest);
    }).then(function(){
      console.log(`File saved at ${target}`)
    }).catch(function(err){
      console.log(err)
  });
}
</code>```

So this all executes in order and I can see how that works.

I have another method that then converts a CSV file to JSON (again using a promise)

```<code>## CSVToJson.js

const csvjson = require('csvjson');
const fs = require('fs');
const write_file = require('../helpers/WriteToFile');

function csvToJson(csv_file, json_path) {
  return new Promise(function(resolve, reject) {
    fs.readFile(csv_file, function(err, data){
      if (err)
        reject(err);
      else
        var data = data.toString();
        var options = {
          delimiter : ',',
          quote     : '"'
        };
      const json_data = csvjson.toObject(data, options);
      write_file(json_path, json_data)
      resolve(data);
    });
  });
}

module.exports = {
  csvToJson: csvToJson
}
</code>```

When I call these functions one after another the second function fails as the first has not completed.

Do I need to wrap these two function calls inside another promise, even though on their own they each have promises implemented?

Please advise if I am totally misunderstanding this

答:
When I call these functions one after another the second function fails as the first has not completed.

There are two issues with the first:

It doesn't wait for the file to be written; all it does is set up the pipe, without waiting for the process to complete

It doesn't provide any way for the caller to know when the process is complete

To deal with the first issue, you have to wait for the finish event on the destination stream (which pipe returns). To deal with the second, you need to return a promise that won't be fulfilled until that happens. Something along these lines (see ** comments):

```<code>module.exports = function(url, target) {
  // ** Return the end of the chain
  return fetch(url)
    .then(function(res) {
      // ** Unfortunately, `pipe` is not Promise-enabled, so we have to resort
      // to creating a promise here
      return new Promise((resolve, reject) => {
        var dest = fs.createWriteStream(target);
        res.body.pipe(dest)
          .on('finish', () => resolve()) // ** Resolve on success
          .on('error', reject);          // ** Reject on error
      });
    }).then(result => {
      console.log(`File saved at ${target}`);
      return result;
    });
    // ** Don't `catch` here, let the caller handle it
}
</code>```

Then you can use then and catch on the result to proceeed to the next step:

```<code>theFunctionAbove("/some/url", "some-target")
    .then(() = {
        // It worked, do the next thing
    })
    .catch(err => {
        // It failed
    });
</code>```

(Or async/await.)

Side note: I haven't code-reviewed it, but a serious issue in csvToJson jumped out, a minor issue as well, and @Bergi has highlighted a second one:

It's missing { and } around the else logic

The minor issue is that you have var data = data.toString(); but data was a parameter of that function, so the var is misleading (but harmless)

It doesn't properly handle errors in the part of the code in the else part of the readFile callback

We can fix both by doing a resolve in the else and performing the rest of the logic in a then handler:

```<code>function csvToJson(csv_file, json_path) {
  return new Promise(function(resolve, reject) {
    fs.readFile(csv_file, function(err, data){
      if (err)
        reject(err);
      else
        resolve(data);
    });
  })
  .then(data => {
    data = data.toString();
    var options = {
      delimiter : ',',
      quote     : '"'
    };
    const json_data = csvjson.toObject(data, options);
    write_file(json_path, json_data);
    return data;
  });
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Chaining methods using promises

Body:
I'm trying to get my head around promises, I think I can see how they work in the way that you can say do Step 1, Step 2 and then Step 3 for example.

I have created this download function using node-fetch (which uses native Promises)

## FileDownload.js

const fetch = require('node-fetch');
const fs = require('fs');

module.exports = function(url, target) {
  fetch(url)
    .then(function(res) {
      var dest = fs.createWriteStream(target);
      res.body.pipe(dest);
    }).then(function(){
      console.log(`File saved at ${target}`)
    }).catch(function(err){
      console.log(err)
  });
}

So this all executes in order and I can see how that works.

I have another method that then converts a CSV file to JSON (again using a promise)

## CSVToJson.js

const csvjson = require('csvjson');
const fs = require('fs');
const write_file = require('../helpers/WriteToFile');

function csvToJson(csv_file, json_path) {
  return new Promise(function(resolve, reject) {
    fs.readFile(csv_file, function(err, data){
      if (err)
        reject(err);
      else
        var data = data.toString();
        var options = {
          delimiter : ',',
          quote     : '"'
        };
      const json_data = csvjson.toObject(data, options);
      write_file(json_path, json_data)
      resolve(data);
    });
  });
}

module.exports = {
  csvToJson: csvToJson
}

When I call these functions one after another the second function fails as the first has not completed.

Do I need to wrap these two function calls inside another promise, even though on their own they each have promises implemented?

Please advise if I am totally misunderstanding this

Body:
When I call these functions one after another the second function fails as the first has not completed.

There are two issues with the first:

It doesn't wait for the file to be written; all it does is set up the pipe, without waiting for the process to complete

It doesn't provide any way for the caller to know when the process is complete

To deal with the first issue, you have to wait for the finish event on the destination stream (which pipe returns). To deal with the second, you need to return a promise that won't be fulfilled until that happens. Something along these lines (see ** comments):

module.exports = function(url, target) {
  // ** Return the end of the chain
  return fetch(url)
    .then(function(res) {
      // ** Unfortunately, `pipe` is not Promise-enabled, so we have to resort
      // to creating a promise here
      return new Promise((resolve, reject) => {
        var dest = fs.createWriteStream(target);
        res.body.pipe(dest)
          .on('finish', () => resolve()) // ** Resolve on success
          .on('error', reject);          // ** Reject on error
      });
    }).then(result => {
      console.log(`File saved at ${target}`);
      return result;
    });
    // ** Don't `catch` here, let the caller handle it
}

Then you can use then and catch on the result to proceeed to the next step:

theFunctionAbove("/some/url", "some-target")
    .then(() = {
        // It worked, do the next thing
    })
    .catch(err => {
        // It failed
    });

(Or async/await.)

Side note: I haven't code-reviewed it, but a serious issue in csvToJson jumped out, a minor issue as well, and @Bergi has highlighted a second one:

It's missing { and } around the else logic

The minor issue is that you have var data = data.toString(); but data was a parameter of that function, so the var is misleading (but harmless)

It doesn't properly handle errors in the part of the code in the else part of the readFile callback

We can fix both by doing a resolve in the else and performing the rest of the logic in a then handler:

function csvToJson(csv_file, json_path) {
  return new Promise(function(resolve, reject) {
    fs.readFile(csv_file, function(err, data){
      if (err)
        reject(err);
      else
        resolve(data);
    });
  })
  .then(data => {
    data = data.toString();
    var options = {
      delimiter : ',',
      quote     : '"'
    };
    const json_data = csvjson.toObject(data, options);
    write_file(json_path, json_data);
    return data;
  });
}


问:
How to disable a link using only CSS
Is there a way to disable a link using CSS?

I have a class called current-page and want links with this class to be disabled so that no action occurs when they are clicked.

答:
pointer-events:none will disable the link:

.disabled {
    pointer-events: none;
}
```
```link
```

ContentLicense: CC BY-SA 4.0

Title: How to disable a link using only CSS

Body:
pointer-events:none will disable the link:

.disabled {
    pointer-events: none;
}

<a href="#" class="disabled">link</a>


问:
How to plot multiple dataframes in subplots
I have a few Pandas DataFrames sharing the same value scale, but having different columns and indices. When invoking df.plot(), I get separate plot images. what I really want is to have them all in the same plot as subplots, but I'm unfortunately failing to come up with a solution to how and would highly appreciate some help.

答:
You can use this:</p>

```<code>fig = plt.figure()
ax = fig.add_subplot(221)
plt.plot(x,y)

ax = fig.add_subplot(222)
plt.plot(x,z)
...

plt.show()
</code>```

Body:
You can use this:

fig = plt.figure()
ax = fig.add_subplot(221)
plt.plot(x,y)

ax = fig.add_subplot(222)
plt.plot(x,z)
...

plt.show()


问:
'yield from' substitute in Python 2
My code uses yield from in python3 in recursive calls and it works perfectly fine. The problem right now is that this was introduced from PEP-380 in python 3.3 and I need it to work in python 2.7. I read up on a few articles and none of them were detailed enough or simple enough.

Few referred articles :

Converting “yield from” statement to Python 2.7 code

yield from and Python 2.7

and few others.

I have recreated a small Sample code (which takes in a multi-level list and returns a flattened list) that is very minimalistic compared to my requirements.

```<code>#python 3
def foo(obj):
    for ele in obj:
        if isinstance(ele, list):
            yield from foo(ele)
        else:
            yield ele
</code>```

#driver values :

```<code>>>> l = [1, [2, 3, [4,5]]]
>>> list(foo(l))
=>  [1, 2, 3, 4, 5]
</code>```

The same converted does not work in python 2.7 due to the non-availability of yield from.

答:
You still need to loop. It doesn't matter that you have recursion here.

You need to loop over the generator produced by the recursive call and yield the results:

```<code>def foo(obj):
    for ele in obj:
        if isinstance(ele, list):
            for res in foo(ele):
                yield res
        else:
            yield ele
</code>```

Your recursive call produces a generator, and you need to pass the results of the generator onwards. You do so by looping over the generator and yielding the individual values.

There are no better options, other than upgrading to Python 3.

yield from essentially passes on the responsibility to loop over to the caller, and passes back any generator.send() and generator.throw() calls to the delegated generator. You don't have any need to pass on .send() or .throw(), so what remains is taking responsibility to do the looping yourself.

Demo:

```<code>>>> import sys
>>> sys.version_info
sys.version_info(major=2, minor=7, micro=14, releaselevel='final', serial=0)
>>> def foo(obj):
...     for ele in obj:
...         if isinstance(ele, list):
...             for res in foo(ele):
...                 yield res
...         else:
...             yield ele
...
>>> l = [1, [2, 3, [4,5]]]
>>> list(foo(l))
[1, 2, 3, 4, 5]
</code>```

yield from was introduced in PEP 380 -- Syntax for Delegating to a Subgenerator (not PEP 342), specifically because a loop over the sub-generator would not delegate generator.throw() and generator.send() information.

The PEP explicitly states:

If yielding of values is the only concern, this can be performed without much difficulty using a loop such as

```<code>for v in g:
    yield v
</code>```

The Formal Semantics has a Python implementation equivalent that may look intimidating at first, but you can still pick out that it loops (with while 1:, looping ends when there is an exception or StopIteration is handled, new values are retrieved with next() or generator.send(..)), and yields the results (with yield _y).

Title: 'yield from' substitute in Python 2

Body:
My code uses yield from in python3 in recursive calls and it works perfectly fine. The problem right now is that this was introduced from PEP-380 in python 3.3 and I need it to work in python 2.7. I read up on a few articles and none of them were detailed enough or simple enough.

Few referred articles :

Converting “yield from” statement to Python 2.7 code

yield from and Python 2.7

and few others.

I have recreated a small Sample code (which takes in a multi-level list and returns a flattened list) that is very minimalistic compared to my requirements.

#python 3
def foo(obj):
    for ele in obj:
        if isinstance(ele, list):
            yield from foo(ele)
        else:
            yield ele

#driver values :

>>> l = [1, [2, 3, [4,5]]]
>>> list(foo(l))
=>  [1, 2, 3, 4, 5]

The same converted does not work in python 2.7 due to the non-availability of yield from.

Body:
You still need to loop. It doesn't matter that you have recursion here.

You need to loop over the generator produced by the recursive call and yield the results:

def foo(obj):
    for ele in obj:
        if isinstance(ele, list):
            for res in foo(ele):
                yield res
        else:
            yield ele

Your recursive call produces a generator, and you need to pass the results of the generator onwards. You do so by looping over the generator and yielding the individual values.

There are no better options, other than upgrading to Python 3.

yield from essentially passes on the responsibility to loop over to the caller, and passes back any generator.send() and generator.throw() calls to the delegated generator. You don't have any need to pass on .send() or .throw(), so what remains is taking responsibility to do the looping yourself.

Demo:

>>> import sys
>>> sys.version_info
sys.version_info(major=2, minor=7, micro=14, releaselevel='final', serial=0)
>>> def foo(obj):
...     for ele in obj:
...         if isinstance(ele, list):
...             for res in foo(ele):
...                 yield res
...         else:
...             yield ele
...
>>> l = [1, [2, 3, [4,5]]]
>>> list(foo(l))
[1, 2, 3, 4, 5]

yield from was introduced in PEP 380 -- Syntax for Delegating to a Subgenerator (not PEP 342), specifically because a loop over the sub-generator would not delegate generator.throw() and generator.send() information.

The PEP explicitly states:

If yielding of values is the only concern, this can be performed without much difficulty using a loop such as

for v in g:
    yield v

The Formal Semantics has a Python implementation equivalent that may look intimidating at first, but you can still pick out that it loops (with while 1:, looping ends when there is an exception or StopIteration is handled, new values are retrieved with next() or generator.send(..)), and yields the results (with yield _y).


答:
Why do you say "my code cannot work with loops and needs to be recursive"? You can easily use a loop in a recursive generator:

```<code>def foo(obj):
    for ele in obj:
        if isinstance(ele, list):
            #yield from foo(ele)
            for t in foo(ele):
                yield t
        else:
            yield ele

l = [1, [2, 3, [4, 5]]]
print list(foo(l))
</code>```

output

```<code>[1, 2, 3, 4, 5]
</code>```

Title: 'yield from' substitute in Python 2

Body:
Why do you say "my code cannot work with loops and needs to be recursive"? You can easily use a loop in a recursive generator:

def foo(obj):
    for ele in obj:
        if isinstance(ele, list):
            #yield from foo(ele)
            for t in foo(ele):
                yield t
        else:
            yield ele

l = [1, [2, 3, [4, 5]]]
print list(foo(l))

output

[1, 2, 3, 4, 5]


问:
Can we have AMP and PWA on same URL/page?
We have already implemented our AMP page on our website - http://m.wishafriend.com/amp/
and we are also planning to implement PWA, so should we need to make a different page for PWA or is it possible to combine AMP and PWA on the same URL?</p>

答: Your query is exactly pointing towards the integration of AMP and PWA. Now that we are aware of what is AMP and PWA, we need to proceed towards the next level of what is the difference between AMP and PWA and how to integrate the two to maximize the utilization of both the technologies. You can shift from AMP to PWA easily and also from PWA to AMP. First, PWA to AMP, you can use PWA as an app shell to serve AMP content. In this way you can utilize PWA’s versatility and AMP’s optimized performance, and can deliver a lighting-fast and rich user experience. Second, AMP to PWA, websites first accept the AMP technology and then shift to PWA. Here, you first accept AMP carousel then register in Service Worker of PWA. You can better understood this integration results better if you study a case study of Washington Post in Techmagnate blog. http://www.techmagnate.com/blog/what-difference-between-amp-pwa/ Here is the link for the detailed analysis of AMP PWA integration and also will be able to know the related factors of these two technologies for sure.</p>


问:
Eclipse keeps jumping to the start of the document
I have been using Eclipse for some weeks now and I start getting used to it.

However, one thing really annoys me:

When editing JavaScript (I didn't try any other language yet), the editor window keeps jumping to the start of the document I am editing.

This mostly happens when the code currently contains syntax errors and mostly while / after deleting lines.

Especially constructs like { = and sometimes unterminated strings / comments seem to cause this problem.

When it happens, only the view scrolls to the top of the document - the cursor stays where it was before the "jump" occurred.

Anyone having an idea on how to fix this?

答: I get this Phenomenon, when i'm editing in a Java-Class while still residing in a Debug-Process. The Debugger recognises the Change and reevaluates the Code and jumps back in order to be able to reexecute only the changed Code.</p>


问:
Inside a service, can i do sync http request without freezing the app UI?
Inside a service, can I do sync network request without freezing the app UI ? I heard that services work on the same thread as the app ui thread (I heard this, but I'm not sure)</p>

答:
Hope this guide you in the right direction

Caution: A service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise. If your service is going to perform any CPU-intensive work or blocking operations, such as MP3 playback or networking, you should create a new thread within the service to complete that work. By using a separate thread, you can reduce the risk of Application Not Responding (ANR) errors, and the application's main thread can remain dedicated to user interaction with your activities.
https://developer.android.com/guide/components/services.html

Executing long running Sync operation application in main loop via service is a risk tradeoff.


问:
How do I add features to Visual Studio 2017?
Let's say that when I installed Visual Studio 2017 I decided to use the "Windows Universal Platform" packages.  Later, I realize that I'd like to install the ".Net Desktop packages" (either instead, or in addition).

How can I go back and add those features to Visual Studio 2017?  Is there a way to do this within Visual Studio?  Do I have to re-run the installer?

答:
After you have installed Visual Studio 2017 you will have a program called Visual Studio Installer. Launch this application.

From here you can select modify and then add the components that you need.


问:
Fetch only specific objects from JSON via javascript or jQuery
I would like to fetch only specific objects from the below JSON such as only those JSON objects which have a classDefinition = "com.sap.bpm.wfs.UserTask". Please suggest on how to do this:</p>

```<code>var metadata = {
    "contents": {
        "83eaead8-cfae-459b-9bdd-8b12e32d6715": {
            "classDefinition": "com.sap.bpm.wfs.StartEvent",
            "id": "startevent1",
            "name": "StartEvent1"
        },
        "13583ac9-596d-4375-b9e1-e5f6f21e829f": {
            "classDefinition": "com.sap.bpm.wfs.EndEvent",
            "id": "endevent1",
            "name": "EndEvent1"
        },
        "6c2b0935-444b-4299-ac8e-92973ce93558": {
            "classDefinition": "com.sap.bpm.wfs.UserTask",
            "subject": "Upload document",
            "description": "{context.description}",
            "priority": "MEDIUM",
            "isHiddenInLogForParticipant": false,
            "userInterface": "sapui5://html5apps/saptest/com.sap.test",
            "recipientUsers": "I311520, I310811",
            "id": "usertask1",
            "name": "UserTask1"
        },
        "6728bf81-3d4e-4ae3-a428-1700a2096d34": {
            "classDefinition": "com.sap.bpm.wfs.SequenceFlow",
            "id": "sequenceflow1",
            "name": "SequenceFlow1",
            "sourceRef": "83eaead8-cfae-459b-9bdd-8b12e32d6715",
            "targetRef": "6c2b0935-444b-4299-ac8e-92973ce93558"
        },
        "aa99931e-2523-44c3-86b3-d522acdbde10": {
            "classDefinition": "com.sap.bpm.wfs.ui.Diagram",
            "symbols": {
                "760f0725-3400-4d48-b082-5c69ad79d697": {},
                "aa9a0d10-63be-4af8-9ac2-4d2b648a18fc": {},
                "7fbd11bb-cf82-4a27-97d7-e80dda2014ee": {},
                "20c66c48-6058-465e-b500-d69d6e54c028": {},
                "2e8f324c-5361-4512-a09a-fc7693f206ba": {}
            }
        }
    }
};
</code>```

答:
First, metadata.contents property should rather be an array.
If you really cannot change it to an array, then use Object.keys(metadata.contents)

For example:

```<code>Object.keys(metadata.contents)
  .map(x => metadata.contents[x])
  .filter(x => x.classDefinition == 'com.sap.bpm.wfs.UserTask')
</code>```

var metadata = {
    "contents": {
        "83eaead8-cfae-459b-9bdd-8b12e32d6715": {
            "classDefinition": "com.sap.bpm.wfs.StartEvent",
        },
        "13583ac9-596d-4375-b9e1-e5f6f21e829f": {
            "classDefinition": "com.sap.bpm.wfs.EndEvent",
        },
        "6c2b0935-444b-4299-ac8e-92973ce93558": {
            "classDefinition": "com.sap.bpm.wfs.UserTask",
            "subject": "Upload document",
            "description": "{context.description}",
            "priority": "MEDIUM",
            "isHiddenInLogForParticipant": false,
            "userInterface": "sapui5://html5apps/saptest/com.sap.test",
            "recipientUsers": "I311520, I310811",
            "id": "usertask1",
            "name": "UserTask1"
        },
        "6728bf81-3d4e-4ae3-a428-1700a2096d34": {
            "classDefinition": "com.sap.bpm.wfs.SequenceFlow",
        },
        "aa99931e-2523-44c3-86b3-d522acdbde10": {
            "classDefinition": "com.sap.bpm.wfs.ui.Diagram",
        }
    }
}

var filtered = Object.keys(metadata.contents)
  .map(x => metadata.contents[x])
  .filter(x => x.classDefinition == 'com.sap.bpm.wfs.UserTask')

console.log(filtered)```

Body:
I would like to fetch only specific objects from the below JSON such as only those JSON objects which have a classDefinition = "com.sap.bpm.wfs.UserTask". Please suggest on how to do this:

var metadata = {
    "contents": {
        "83eaead8-cfae-459b-9bdd-8b12e32d6715": {
            "classDefinition": "com.sap.bpm.wfs.StartEvent",
            "id": "startevent1",
            "name": "StartEvent1"
        },
        "13583ac9-596d-4375-b9e1-e5f6f21e829f": {
            "classDefinition": "com.sap.bpm.wfs.EndEvent",
            "id": "endevent1",
            "name": "EndEvent1"
        },
        "6c2b0935-444b-4299-ac8e-92973ce93558": {
            "classDefinition": "com.sap.bpm.wfs.UserTask",
            "subject": "Upload document",
            "description": "{context.description}",
            "priority": "MEDIUM",
            "isHiddenInLogForParticipant": false,
            "userInterface": "sapui5://html5apps/saptest/com.sap.test",
            "recipientUsers": "I311520, I310811",
            "id": "usertask1",
            "name": "UserTask1"
        },
        "6728bf81-3d4e-4ae3-a428-1700a2096d34": {
            "classDefinition": "com.sap.bpm.wfs.SequenceFlow",
            "id": "sequenceflow1",
            "name": "SequenceFlow1",
            "sourceRef": "83eaead8-cfae-459b-9bdd-8b12e32d6715",
            "targetRef": "6c2b0935-444b-4299-ac8e-92973ce93558"
        },
        "aa99931e-2523-44c3-86b3-d522acdbde10": {
            "classDefinition": "com.sap.bpm.wfs.ui.Diagram",
            "symbols": {
                "760f0725-3400-4d48-b082-5c69ad79d697": {},
                "aa9a0d10-63be-4af8-9ac2-4d2b648a18fc": {},
                "7fbd11bb-cf82-4a27-97d7-e80dda2014ee": {},
                "20c66c48-6058-465e-b500-d69d6e54c028": {},
                "2e8f324c-5361-4512-a09a-fc7693f206ba": {}
            }
        }
    }
};

Body:
First, metadata.contents property should rather be an array.
If you really cannot change it to an array, then use Object.keys(metadata.contents)

For example:

Object.keys(metadata.contents)
  .map(x => metadata.contents[x])
  .filter(x => x.classDefinition == 'com.sap.bpm.wfs.UserTask')

var metadata = {
    "contents": {
        "83eaead8-cfae-459b-9bdd-8b12e32d6715": {
            "classDefinition": "com.sap.bpm.wfs.StartEvent",
        },
        "13583ac9-596d-4375-b9e1-e5f6f21e829f": {
            "classDefinition": "com.sap.bpm.wfs.EndEvent",
        },
        "6c2b0935-444b-4299-ac8e-92973ce93558": {
            "classDefinition": "com.sap.bpm.wfs.UserTask",
            "subject": "Upload document",
            "description": "{context.description}",
            "priority": "MEDIUM",
            "isHiddenInLogForParticipant": false,
            "userInterface": "sapui5://html5apps/saptest/com.sap.test",
            "recipientUsers": "I311520, I310811",
            "id": "usertask1",
            "name": "UserTask1"
        },
        "6728bf81-3d4e-4ae3-a428-1700a2096d34": {
            "classDefinition": "com.sap.bpm.wfs.SequenceFlow",
        },
        "aa99931e-2523-44c3-86b3-d522acdbde10": {
            "classDefinition": "com.sap.bpm.wfs.ui.Diagram",
        }
    }
}

var filtered = Object.keys(metadata.contents)
  .map(x => metadata.contents[x])
  .filter(x => x.classDefinition == 'com.sap.bpm.wfs.UserTask')

console.log(filtered)


问:
System.exit(0) reached before maximum user attempts made reached
I may have confused my self with the logic for some time now and I could use some assistance. So I have created this function to return a Voucher # (size is 4-digits). The pre-condition is two characters entered must be correct and in their respective placing below the application reveals the rest of the Voucher digits (when compared with voucher in record).

I am giving the user 3 attempts to search the voucher with the only two known voucher digits. After three attempts and if the voucher does not exist. I'll lock the user and close the app with System.exit(0).

However, System.exit(0) executes when attempt = 3. It seems I don't have control over my loop.

```<code>int attempts = 3;

while (attempts != 0){

 if(VoucherNumber.charAt(0) == VoucherRecord.charAt(0) &&
           VoucherNumber.charAt(1) == VoucherRecord.charAt(1))

           System.out.println("Reveal all digits");

         }

        else if(VoucherNumber.charAt(0) == VoucherRecord.charAt(0) &&
                VoucherNumber.charAt(2) == VoucherRecord.charAt(2) ){

                System.out.println("Reveal all digits");

        }

        else{

               System.out.println("Reveal all digits");

               attempts--;

               if (attempts == 0){

                    System.exit(0);
               }
        }
</code>```

答: You should get new input from user inside the while loop. As it is, you seem to get the input once, then run the loop 3 times with the same input..</p>

Body:
I may have confused my self with the logic for some time now and I could use some assistance. So I have created this function to return a Voucher # (size is 4-digits). The pre-condition is two characters entered must be correct and in their respective placing below the application reveals the rest of the Voucher digits (when compared with voucher in record).

I am giving the user 3 attempts to search the voucher with the only two known voucher digits. After three attempts and if the voucher does not exist. I'll lock the user and close the app with System.exit(0).

However, System.exit(0) executes when attempt = 3. It seems I don't have control over my loop.

int attempts = 3;

while (attempts != 0){

 if(VoucherNumber.charAt(0) == VoucherRecord.charAt(0) &&
           VoucherNumber.charAt(1) == VoucherRecord.charAt(1))

           System.out.println("Reveal all digits");

         }

        else if(VoucherNumber.charAt(0) == VoucherRecord.charAt(0) &&
                VoucherNumber.charAt(2) == VoucherRecord.charAt(2) ){

                System.out.println("Reveal all digits");

        }

        else{

               System.out.println("Reveal all digits");

               attempts--;

               if (attempts == 0){

                    System.exit(0);
               }
        }


问:
Using a select box to trigger JS event to make another select box become passive/active? HTML/JS
I want select box B to become visible when option 2 is selected in select box A, otherwise it should remain hidden.  It's not working.  Here's my code: [EDIT: I actually want it to be passive instead of hidden.]

The JavaScript first:

```<code>function toggle2(value){
if(value=='confirm')
 document.getElementById('test').style.visibility='visible';
else
 document.getElementById('test').style.visibility='hidden';
}

 <select class="select3" name="CaseType" onchange="toggle2()">
  <option value="select" selected="selected">- Select Case Type -</option>
  <option value="suspect">Suspected</option>
  <option value="confirm">Confirmed</option>
  </select>

  <select id="test" class="select4" name="test" style="visibility: hidden;">
  <option selected="selected">- Select test -</option>
  </select>
</code>```

Thanks!

答:
use

```<code>document.getElementById('test').style.display='none';
</code>```

to hide element and

```<code>document.getElementById('test').style.display='';
</code>```

to show it again

and by the way, when accessing element with getElementById('test'), element must contain id attribute that equals 'test'

```<code><select id="test" class="select4" name="test" style="visibility: hidden;">
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I want select box B to become visible when option 2 is selected in select box A, otherwise it should remain hidden.  It's not working.  Here's my code: [EDIT: I actually want it to be passive instead of hidden.]

The JavaScript first:

function toggle2(value){
if(value=='confirm')
 document.getElementById('test').style.visibility='visible';
else
 document.getElementById('test').style.visibility='hidden';
}

 <select class="select3" name="CaseType" onchange="toggle2()">
  <option value="select" selected="selected">- Select Case Type -</option>
  <option value="suspect">Suspected</option>
  <option value="confirm">Confirmed</option>
  </select>

  <select id="test" class="select4" name="test" style="visibility: hidden;">
  <option selected="selected">- Select test -</option>
  </select>

Thanks!

Body:
use

document.getElementById('test').style.display='none';

to hide element and

document.getElementById('test').style.display='';

to show it again

and by the way, when accessing element with getElementById('test'), element must contain id attribute that equals 'test'

<select id="test" class="select4" name="test" style="visibility: hidden;">


问:
How to install realm as a gradle dependency?
I am completely new to realm. I want to use realm db in my android project. I have gone through the official Realm documentation. I need to set up realm in my android project. For that I have added the gradle dependancy as

```<code>    buildscript {
            repositories {
                     jcenter()
                         }
            dependencies {
                classpath "io.realm:realm-gradle-plugin:0.88.2"
           }
       }
 apply plugin: 'realm-android'
</code>```

This is what they have given in documentation. But this doesn't work for me. It gives error saying Plugin with id 'realm-android' not found.

This is my build.gradle file

```<code>apply plugin: 'com.android.application'
apply plugin: 'realm-android'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"

defaultConfig {
    applicationId "com.db.realmsample"
    minSdkVersion 14
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath "io.realm:realm-gradle-plugin:0.88.2"
    }
  }

 }

 dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
  testCompile 'junit:junit:4.12'
  compile 'com.android.support:appcompat-v7:23.2.1'
  }
</code>```

Is my configuration correct?

答:
The method I used is

```<code>   `     dependencies
{
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath "io.realm:realm-gradle-plugin:3.1.4"

    }`
</code>```

in your main  build gradle  file
then add

```<code>apply plugin: 'realm-android'
</code>```

and

```<code> compile 'io.realm:android-adapters:2.0.0'
</code>```

in your app's build gradle

this link to bintray will give you the latest build
https://bintray.com/realm/maven/realm-android-library/3.4.0#files/io%2Frealm%2Frealm-android-library%2F3.4.0

Body:
I am completely new to realm. I want to use realm db in my android project. I have gone through the official Realm documentation. I need to set up realm in my android project. For that I have added the gradle dependancy as

    buildscript {
            repositories {
                     jcenter()
                         }
            dependencies {
                classpath "io.realm:realm-gradle-plugin:0.88.2"
           }
       }
 apply plugin: 'realm-android'

This is what they have given in documentation. But this doesn't work for me. It gives error saying Plugin with id 'realm-android' not found.

This is my build.gradle file

apply plugin: 'com.android.application'
apply plugin: 'realm-android'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"

defaultConfig {
    applicationId "com.db.realmsample"
    minSdkVersion 14
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath "io.realm:realm-gradle-plugin:0.88.2"
    }
  }

 }

 dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
  testCompile 'junit:junit:4.12'
  compile 'com.android.support:appcompat-v7:23.2.1'
  }

Is my configuration correct?

Body:
The method I used is

   `     dependencies
{
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath "io.realm:realm-gradle-plugin:3.1.4"

    }`

in your main  build gradle  file
then add

apply plugin: 'realm-android'

and

 compile 'io.realm:android-adapters:2.0.0'

in your app's build gradle

this link to bintray will give you the latest build
https://bintray.com/realm/maven/realm-android-library/3.4.0#files/io%2Frealm%2Frealm-android-library%2F3.4.0


问:
Send sms using a number found in database table using PHP
I would like to send sms using the number found inside of a database table. I tried include function but the message wasn't sent to a number. there is  no error shows.

```<code><?php

//connect to database

$con = mysqli_connect('127.0.0.1','root','');

//select database
mysqli_select_db($con, 'appointment');

if($_POST['accept'])
{
  $sql = "UPDATE service SET remarks = 'Accepted' WHERE ID=$_POST[id]";

 include"sms.php";
}
else if($_POST['reject'])
{
  $sql = "UPDATE service SET remarks = 'Rejected' WHERE ID=$_POST[id]";
}

//Execute Query
if(mysqli_query($con,$sql))
    header("refresh:1; url=app.php");
else
    echo "Unsuccessful";
?>
</code>```

Here's the code of my sms.php

```<code><?php

$phone= "SELECT contact FROM service WHERE ID=$_POST[id]";
$message= "You're Appointment is Accepted";

send_sms($phone,$message);

function send_sms($phone, $message) {
  $ch = curl_init();
  $parameters = array(
    'apikey' => '*****************', //Your API KEY
    'number' => $phone,
    'message' => $message,
    'sendername' => 'SEMAPHORE'
  );
  curl_setopt( $ch, CURLOPT_URL,'http://api.semaphore.co/api/v4/messages' );
  curl_setopt( $ch, CURLOPT_POST, 1 );

  //Send the parameters set above with the request
  curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $parameters ) );

  // Receive response from server
  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
  $output = curl_exec( $ch );
  curl_close ($ch);

  //Show the server response
  echo "Message Successfully Delivered";
}
?>
</code>```

I will provide a screenshot of the appointment table so that you can easily understand my problem.

答:
You are sending, not the phone number, but the query to your SMS service.

```<code>$phone= "SELECT contact FROM service WHERE ID=$_POST[id]";
send_sms($phone,$message);
       ...
function send_sms($phone, $message) {
       ...
  $parameters = array(
    'apikey' => '*****************', //Your API KEY
    'number' => $phone,  /*"SELECT contact FROM service WHERE ID=$_POST[id]" */
    'message' => $message,
    'sendername' => 'SEMAPHORE'
  );
</code>```

Run the query and retrieve the actual phone number before trying to send it a message. (Your SMS service has no idea what to do with your query, hopefully.)

And, take seriously the SQL injection warnings in comments. Cybercriminals typically pwn vulnerable web sites like yours will be in less than a day after they go live. The public internet is a dangerous place. You're paying for your SMS service. You'd hate to get a bill for US$20,000 because a spammer used your service to send messages. You'd hate the loss to your reputation even more.

Body:
I would like to send sms using the number found inside of a database table. I tried include function but the message wasn't sent to a number. there is  no error shows.

<?php

//connect to database

$con = mysqli_connect('127.0.0.1','root','');

//select database
mysqli_select_db($con, 'appointment');

if($_POST['accept'])
{
  $sql = "UPDATE service SET remarks = 'Accepted' WHERE ID=$_POST[id]";

 include"sms.php";
}
else if($_POST['reject'])
{
  $sql = "UPDATE service SET remarks = 'Rejected' WHERE ID=$_POST[id]";
}

//Execute Query
if(mysqli_query($con,$sql))
    header("refresh:1; url=app.php");
else
    echo "Unsuccessful";
?>

Here's the code of my sms.php

<?php

$phone= "SELECT contact FROM service WHERE ID=$_POST[id]";
$message= "You're Appointment is Accepted";

send_sms($phone,$message);

function send_sms($phone, $message) {
  $ch = curl_init();
  $parameters = array(
    'apikey' => '*****************', //Your API KEY
    'number' => $phone,
    'message' => $message,
    'sendername' => 'SEMAPHORE'
  );
  curl_setopt( $ch, CURLOPT_URL,'http://api.semaphore.co/api/v4/messages' );
  curl_setopt( $ch, CURLOPT_POST, 1 );

  //Send the parameters set above with the request
  curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $parameters ) );

  // Receive response from server
  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
  $output = curl_exec( $ch );
  curl_close ($ch);

  //Show the server response
  echo "Message Successfully Delivered";
}
?>

I will provide a screenshot of the appointment table so that you can easily understand my problem.

Body:
You are sending, not the phone number, but the query to your SMS service.

$phone= "SELECT contact FROM service WHERE ID=$_POST[id]";
send_sms($phone,$message);
       ...
function send_sms($phone, $message) {
       ...
  $parameters = array(
    'apikey' => '*****************', //Your API KEY
    'number' => $phone,  /*"SELECT contact FROM service WHERE ID=$_POST[id]" */
    'message' => $message,
    'sendername' => 'SEMAPHORE'
  );

Run the query and retrieve the actual phone number before trying to send it a message. (Your SMS service has no idea what to do with your query, hopefully.)

And, take seriously the SQL injection warnings in comments. Cybercriminals typically pwn vulnerable web sites like yours will be in less than a day after they go live. The public internet is a dangerous place. You're paying for your SMS service. You'd hate to get a bill for US$20,000 because a spammer used your service to send messages. You'd hate the loss to your reputation even more.


问:
Decoding UTF16LE with Encoding.Unicode garbles text
I have the following code:

var reader = new StreamReader(inputSubtitle, encoding);
string str;
var list = new List<String>();
try
{
    str = reader.ReadLine();
    while (str != null)
    {
        list.Add(str);
        str = reader.ReadLine();
    }
    return list;
}
```
<p>The encoding is based on the Byte Order Mark. The charset detector code (can provide it if necessary) simply looks at the hex value of the first couple of bytes in the file. The files are usually UTF-8, Windows ANSI (Codepage-1252) or UTF-16LE. The last one currently fails, and I have no clue why.</p>
<p>Previewing the text in Notepad says it's encoded as Unicode (with which it means UTF-16LE, afaik), opening in Firefox says it's UTF-16LE and the BOM starts with bytes FF FE.</p>
<p>Take this example text:</p>
```
1
00:04:05,253 --> 00:04:11,886
This is the first line
- This is the second line.
```
<p>I send this file as a filestream to the charset detector (I use filestream as an input in the backend), where I added the following debug line:</p>
<pre class="lang-cs prettyprint-override"><code>byte[] dataFromFileStream = new byte[(input.Length)];
input.Read(dataFromFileStream, 0, (int)input.Length);
Console.WriteLine(BitConverter.ToString(dataFromFileStream));
</code>```

This produces the following hexcode:

"FF-FE-31-00-(...)"

FF-FE is the Byte Order Mark of UTF16-LE.

Opening this hexcode with the StreamReader and encoding set to Encoding.Unicode turns the data into a single string:

"\u0d00\u0a00　　㨀　㐀㨀　㔀Ⰰ㈀㔀㌀ ⴀⴀ㸀 　　㨀　㐀㨀\u3100\u3100Ⰰ㠀㠀㘀\u0d00\u0a00㰀椀㸀吀栀椀猀 椀猀 琀栀攀 昀椀爀猀琀 氀椀渀攀㰀⼀椀㸀\u0d00\u0a00ⴀ 吀栀椀猀 椀猀 琀栀攀 猀攀挀漀渀搀 氀椀渀攀⸀"

Setting the encoder to Encoding.GetEncoding(1201), e.g. as a UTF-16BE, opens the file properly and decodes it to 4 lines in the list, as expected.

I noticed this bug since a couple of weeks, before then the code worked properly. Is it something that happened in an update? Encoding.Unicode is described as UTF-16LE in the documentation.

I changed my code to use UTF-16BE as decoder for the moment to make it work again, but that just feels wrong.

答:
Turns out I made a stupid mistake; the Charset detector reads a couple of bytes to determine the encoding of the file. To make sure I have a UTF-16LE file (which starts with FF-FE) and not a UTF-32LE (which starts with FF-FE-00-00) I read the third byte as well. After reading those bytes, however, I did not reset the position of the FileStream back to 0. An earlier version of my code, with a different constructor, did reset the starting position. Adding the code for resetting the position fixed it.

Explanation:
The StreamReader class does not necessarily need a BOM in a UTF file, so it starts reading from the position left after the charset detector did its thing. Detecting UTF-8 or ANSI made no issues, since those are encoded in single bytes. UTF-16 uses two bytes for each character, so starting at an odd numbered byte caused everything to look like reversed byte order for the reader. Therefore decoding like UTF-16BE 'fixed' the issue.

Body:
I have the following code:

var reader = new StreamReader(inputSubtitle, encoding);
string str;
var list = new List<String>();
try
{
    str = reader.ReadLine();
    while (str != null)
    {
        list.Add(str);
        str = reader.ReadLine();
    }
    return list;
}

The encoding is based on the Byte Order Mark. The charset detector code (can provide it if necessary) simply looks at the hex value of the first couple of bytes in the file. The files are usually UTF-8, Windows ANSI (Codepage-1252) or UTF-16LE. The last one currently fails, and I have no clue why.

Previewing the text in Notepad says it's encoded as Unicode (with which it means UTF-16LE, afaik), opening in Firefox says it's UTF-16LE and the BOM starts with bytes FF FE.

Take this example text:

1
00:04:05,253 --> 00:04:11,886
This is the first line
- This is the second line.

I send this file as a filestream to the charset detector (I use filestream as an input in the backend), where I added the following debug line:

byte[] dataFromFileStream = new byte[(input.Length)];
input.Read(dataFromFileStream, 0, (int)input.Length);
Console.WriteLine(BitConverter.ToString(dataFromFileStream));

This produces the following hexcode:

"FF-FE-31-00-(...)"

FF-FE is the Byte Order Mark of UTF16-LE.

Opening this hexcode with the StreamReader and encoding set to Encoding.Unicode turns the data into a single string:

"\u0d00\u0a00　　㨀　㐀㨀　㔀Ⰰ㈀㔀㌀ ⴀⴀ㸀 　　㨀　㐀㨀\u3100\u3100Ⰰ㠀㠀㘀\u0d00\u0a00㰀椀㸀吀栀椀猀 椀猀 琀栀攀 昀椀爀猀琀 氀椀渀攀㰀⼀椀㸀\u0d00\u0a00ⴀ 吀栀椀猀 椀猀 琀栀攀 猀攀挀漀渀搀 氀椀渀攀⸀"

Setting the encoder to Encoding.GetEncoding(1201), e.g. as a UTF-16BE, opens the file properly and decodes it to 4 lines in the list, as expected.

I noticed this bug since a couple of weeks, before then the code worked properly. Is it something that happened in an update? Encoding.Unicode is described as UTF-16LE in the documentation.

I changed my code to use UTF-16BE as decoder for the moment to make it work again, but that just feels wrong.


问:
AngularJS - Disable select list option if expression is true
I've tried to disable a materializeCSS select list option is a particular expression is true, but this doesn't seem to be working using the method below:

```<code><option data-ng-disabled="employeeIsMale" value="maternity">Maternity</option>
</code>```

I've defined the truth value of this expression like below on load, which is obviously working, because the correct message is logged to the console:

```<code>$document.ready(function() {
    if ($scope.employee.gender === 'Male') {
        $scope.employeeIsMale == true;
        console.log("Employee is Male");
    } else {
        $scope.employeeIsMale == false;
        console.log("Employee is Female");
    }
})
</code>```

How can I use the expression like this to disable the select option?

Full HTML:

```<code><select data-ng-change="showAbsenceInputs()" data-ng-model="absenceTypes" id="absenceTypeSelect" name="absenceTypeSelect" material-select watch class="validate" required>

  <option value="" selected>Select an option</option>

  <option data-ng-disabled="employeeIsMale" value="maternity">Maternity</option>

</select>
</code>```

答:
You should use assignment operator <code>=</code>.You are using comparison operator for assignment. </p>

```<code> $scope.employeeIsMale = true;
</code>```

Body:
I've tried to disable a materializeCSS select list option is a particular expression is true, but this doesn't seem to be working using the method below:

<option data-ng-disabled="employeeIsMale" value="maternity">Maternity</option>

I've defined the truth value of this expression like below on load, which is obviously working, because the correct message is logged to the console:

$document.ready(function() {
    if ($scope.employee.gender === 'Male') {
        $scope.employeeIsMale == true;
        console.log("Employee is Male");
    } else {
        $scope.employeeIsMale == false;
        console.log("Employee is Female");
    }
})

How can I use the expression like this to disable the select option?

Full HTML:

<select data-ng-change="showAbsenceInputs()" data-ng-model="absenceTypes" id="absenceTypeSelect" name="absenceTypeSelect" material-select watch class="validate" required>

  <option value="" selected>Select an option</option>

  <option data-ng-disabled="employeeIsMale" value="maternity">Maternity</option>

</select>

Body:
You should use assignment operator =.You are using comparison operator for assignment.

 $scope.employeeIsMale = true;


问:
Design pattern for person with multiple roles
I want to create a base model Person with some person related attributes like name, address, phone and so on. One Person can be one ore more of the following:

LoginUser with fields for login, password, last_login, ...

CardHolder with fields for card_id, last_entrance, ...

Supplier with just a flag whether or not the person is a supplier

Recipient with just a flag whether or not the person is a recipient

Is there a common sense or best practise design pattern in Ruby on Rails to represent that inheritance? How it should be represented in the model(s) and table structure so that it is possible to check whether a Person is a LoginUser and to access the corresponding fields.
In another project I worked already with STI but in this case this isn't the right pattern.

答:
I would go with Person table and the PersonAttributes table that is a union of all the attributes the person might have. PersonAttributes might use STI if applicable, e.g. with LoginUser storing logins and CardHolder referencing Cards.

Clean and simple.


问:
Angular js routing issues with transitions how could that be eliminated
> transition suspended,prevented,aborted,failed in angular ui-routing..... anyone could you please help me?....I am using angular
 1.6.4 version and ui-router's version is v0.2.18....js

```<code>var app=angular.module('app', ['ui.router'])

app.config(['$qProvider', functi;on ($qProvider) {
    'use strict';
$qProvider.errorOnUnhandledRejections(false); }])
</code>```

答:
I find out the error behind the transition suspended, prevented, aborted and failed in angular ui-routing.

These errors may occur when you forget to implement the states & controllers of respective ui-sref and also I have changed the version of ui-router from 0.2.8 to 0.3.2.

I hope this might help someone.

Body:
> transition suspended,prevented,aborted,failed in angular ui-routing..... anyone could you please help me?....I am using angular
 1.6.4 version and ui-router's version is v0.2.18....js

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

app.config(['$qProvider', functi;on ($qProvider) {
    'use strict';
$qProvider.errorOnUnhandledRejections(false); }])


问:
Laravel Policy - Bug or Implementation error?
I have implemented a user policy in Laravel as follows.

```<code>namespace App\Policies;

use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class UserPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can list the model.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function index(User $user)
    {
        // only a chief editor can view all users
        $authorized = false;
        $authorized = ($user->role->name === 'Chief Editor');
        return $authorized;
    }

    /**
     * Determine whether the user can view the model.
     *
     * @param  \App\User  $user
     * @param  \App\User  $model
     * @return mixed
     */
    public function view(User $user, User $model)
    {
        // only a chief editor or user(who owns the user) can view the user
        $authorized = false;
        $authorized = ($user->role->name === 'Chief Editor' || $user->id === $model->id);
        return $authorized;
    }

    /**
     * Determine whether the user can create models.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function create(User $user)
    {
        // only a chief editor can create a user
        $authorized = false;
        $authorized = ($user->role->name === 'Chief Editor');
        return $authorized;
    }

    /**
     * Determine whether the user can update the model.
     *
     * @param  \App\User  $user
     * @param  \App\User  $model
     * @return mixed
     */
    public function update(User $user, User $model)
    {
        // only a chief editor or user(who owns the user) can update the user
        $authorized = false;
        $authorized = ($user->role->name === 'Chief Editor' || $user->id === $model->id);
        return $authorized;
    }

    /**
     * Determine whether the user can delete the model.
     *
     * @param  \App\User  $user
     * @param  \App\User  $model
     * @return mixed
     */
    public function delete(User $user, User $model)
    {
        // only a chief editor or user(who owns the user) can delete the user
        $authorized = false;
        $authorized = ($user->role->name === 'Chief Editor' || $user->id === $model->id);
        return $authorized;
    }
}
</code>```

And here is my user controller.

```<code>namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\StoreUser;
use App\Http\Requests\UpdateUser;

use App\User;
use App\Role;

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('can:index,App\User')->only('index');
        $this->middleware('can:view,user')->only('show');
        $this->middleware('can:create,App\User')->only('create', 'store');
        $this->middleware('can:update,user')->only('edit', 'update');
        $this->middleware('can:delete,user')->only('destroy');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = User::paginate(5);
        return view('users.index')
                ->with('users', $users);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        // fetch roles
        $roles = Role::all();
        return view('users.create')
                ->with('roles', $roles);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreUser $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $user = User::findOrFail($id);
        return view('users.show')
                ->with('user', $user);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $user = User::findOrFail($id);
        return view('users.edit')
                ->with('user', $user);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateUser $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
</code>```

However, when I access an action with multiple parameters in the policy method(two user objects), I get the This action is unauthorized. error.

I have also tried returning true without any checks from these methods but still the same issue persists.

Is this my code issue or a bug with Laravel?

答:
Update: Your code is not working because you'r not passing the second user to the policy.

You'r not using route model binding, so the user passed to the view method, for example, does not exist. When the model does not exist, Laravel will not check for the policy and just return false.

The following is an example from the documentation, and it works becuase of the route model binding.

```<code>Route::put('/post/{post}', function (Post $post) {
    // The current user may update the post...
})->middleware('can:update,post');
</code>```

The Answer:

Does not make sense to use authorization in the controller constructor. If you want to use middleware for authorization, attach it to the route not the controller.

If you allow the request to reach the controller, then it would be better to check for authorization in the action not the constructor. It will also be easier to read and debug.

I would remove all the calls to can middleware from the constructor and replace it with a call to authorize in the action.

You controller should be like this:

```<code>public function __construct()
{
    $this->middleware('auth');
}

public function index()
{
    $this-authorize('index'); // This will check for authorization

    $users = User::paginate(5);
    return view('users.index')
            ->with('users', $users);
}

public function show($id)
{
    $user = User::findOrFail($id);

    $this->authorize('view', $user);

    return view('users.show')
            ->with('user', $user);
}
</code>```

Also, no need for the temprory variable in your policy class.

```<code>public function index(User $user)
{
    // only a chief editor can view all users

    return $user->role->name === 'Chief Editor'
}

public function view(User $user, User $model)
{
    // only a chief editor or user(who owns the user) can view the user

    return $user->role->name === 'Chief Editor' || $user->id === $model->id)
}
</code>```

As a side note, in your show action, Why don't you use implicit route model binding? It would be much cleaner.

```<code>// web.php

Route::get('users/{user}', 'UserController@show');

// UserController.php

public function show(User $user)
{
    $this->authorize('view', $user);

    return view('users.show', compact('user');
}
</code>```

Body:
I have implemented a user policy in Laravel as follows.

namespace App\Policies;

use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class UserPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can list the model.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function index(User $user)
    {
        // only a chief editor can view all users
        $authorized = false;
        $authorized = ($user->role->name === 'Chief Editor');
        return $authorized;
    }

    /**
     * Determine whether the user can view the model.
     *
     * @param  \App\User  $user
     * @param  \App\User  $model
     * @return mixed
     */
    public function view(User $user, User $model)
    {
        // only a chief editor or user(who owns the user) can view the user
        $authorized = false;
        $authorized = ($user->role->name === 'Chief Editor' || $user->id === $model->id);
        return $authorized;
    }

    /**
     * Determine whether the user can create models.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function create(User $user)
    {
        // only a chief editor can create a user
        $authorized = false;
        $authorized = ($user->role->name === 'Chief Editor');
        return $authorized;
    }

    /**
     * Determine whether the user can update the model.
     *
     * @param  \App\User  $user
     * @param  \App\User  $model
     * @return mixed
     */
    public function update(User $user, User $model)
    {
        // only a chief editor or user(who owns the user) can update the user
        $authorized = false;
        $authorized = ($user->role->name === 'Chief Editor' || $user->id === $model->id);
        return $authorized;
    }

    /**
     * Determine whether the user can delete the model.
     *
     * @param  \App\User  $user
     * @param  \App\User  $model
     * @return mixed
     */
    public function delete(User $user, User $model)
    {
        // only a chief editor or user(who owns the user) can delete the user
        $authorized = false;
        $authorized = ($user->role->name === 'Chief Editor' || $user->id === $model->id);
        return $authorized;
    }
}

And here is my user controller.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\StoreUser;
use App\Http\Requests\UpdateUser;

use App\User;
use App\Role;

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('can:index,App\User')->only('index');
        $this->middleware('can:view,user')->only('show');
        $this->middleware('can:create,App\User')->only('create', 'store');
        $this->middleware('can:update,user')->only('edit', 'update');
        $this->middleware('can:delete,user')->only('destroy');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = User::paginate(5);
        return view('users.index')
                ->with('users', $users);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        // fetch roles
        $roles = Role::all();
        return view('users.create')
                ->with('roles', $roles);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreUser $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $user = User::findOrFail($id);
        return view('users.show')
                ->with('user', $user);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $user = User::findOrFail($id);
        return view('users.edit')
                ->with('user', $user);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateUser $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

However, when I access an action with multiple parameters in the policy method(two user objects), I get the This action is unauthorized. error.

I have also tried returning true without any checks from these methods but still the same issue persists.

Is this my code issue or a bug with Laravel?

Body:
Update: Your code is not working because you'r not passing the second user to the policy.

You'r not using route model binding, so the user passed to the view method, for example, does not exist. When the model does not exist, Laravel will not check for the policy and just return false.

The following is an example from the documentation, and it works becuase of the route model binding.

Route::put('/post/{post}', function (Post $post) {
    // The current user may update the post...
})->middleware('can:update,post');

The Answer:

Does not make sense to use authorization in the controller constructor. If you want to use middleware for authorization, attach it to the route not the controller.

If you allow the request to reach the controller, then it would be better to check for authorization in the action not the constructor. It will also be easier to read and debug.

I would remove all the calls to can middleware from the constructor and replace it with a call to authorize in the action.

You controller should be like this:

public function __construct()
{
    $this->middleware('auth');
}

public function index()
{
    $this-authorize('index'); // This will check for authorization

    $users = User::paginate(5);
    return view('users.index')
            ->with('users', $users);
}

public function show($id)
{
    $user = User::findOrFail($id);

    $this->authorize('view', $user);

    return view('users.show')
            ->with('user', $user);
}

Also, no need for the temprory variable in your policy class.

public function index(User $user)
{
    // only a chief editor can view all users

    return $user->role->name === 'Chief Editor'
}

public function view(User $user, User $model)
{
    // only a chief editor or user(who owns the user) can view the user

    return $user->role->name === 'Chief Editor' || $user->id === $model->id)
}

As a side note, in your show action, Why don't you use implicit route model binding? It would be much cleaner.

// web.php

Route::get('users/{user}', 'UserController@show');

// UserController.php

public function show(User $user)
{
    $this->authorize('view', $user);

    return view('users.show', compact('user');
}


问:
PolyLine is not on the roads: it goes straight from one point to other
My map contains multiple points to tap the location of the user from where he passes, but the polyline is not shown on the roads, but shows a direct line from one marker to other. I want my polyline to go across the road: as the roads turns, it should also turn.

Here's my relevant code

```<code> dataholder = FirebaseDatabase.getInstance().getReference("UserLocation");
 Log.d("onMapReady", "iam here");
 dataholder.addValueEventListener(new ValueEventListener() {

     @Override
     public void onDataChange(DataSnapshot dataSnapshot) {
         Log.d("data",String.valueOf(dataSnapshot.getValue()));
         System.out.println(dataSnapshot.getValue());
         for (DataSnapshot a : dataSnapshot.getChildren()) {
             MapData mapData = a.getValue(MapData.class);
             arrayList.add(mapData);
             lati.add(arrayList.get(i).getLatituide());
             longit.add(arrayList.get(i).getLongitude());
             Log.d("mapi","i am in loop");
             mMap = googleMap;
             Double lat = Double.parseDouble(lati.get(i));
             Double longi = Double.parseDouble(longit.get(i));
             sydney = new LatLng(longi, lat);
             points.add(sydney);
             MarkerOptions mop = new MarkerOptions();
             mop.position(sydney);
             mop.title("check");
             mMap.addMarker(mop);
             Log.d("latitude", String.valueOf(lat));
             Log.d("longitude", String.valueOf(longi));
             // Add a marker in Sydney and move the camera
             mMap.addMarker(new MarkerOptions().position(sydney).title("check"));
             mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

             i++;
         }

    line.addAll(points).width(5).color(Color.RED);
    line.geodesic(true);
    mMap.addPolyline(line);

    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            Toast.makeText(getApplicationContext(),marker.getTitle().toString(),Toast.LENGTH_LONG).show();
            return false;
        }
    });
</code>```

答:
Try to use Google Maps Roads API part Snap to Road which

returns the best-fit road geometry for a given set of GPS coordinates.
  This service takes up to 100 GPS points collected along a route, and
  returns a similar set of data with the points snapped to the most
  likely roads the vehicle was traveling along.

Something like that for data from Google Maps Roads API Snap to Road example:

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

    private GoogleMap mGoogleMap;
    private MapFragment mapFragment;

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

        mapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map_fragment);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;

        List<LatLng> sourcePoints = new ArrayList<>();
        sourcePoints.add(new LatLng(-35.27801,149.12958));
        sourcePoints.add(new LatLng(-35.28032,149.12907));
        sourcePoints.add(new LatLng(-35.28099,149.12929));
        sourcePoints.add(new LatLng(-35.28144,149.12984));
        sourcePoints.add(new LatLng(-35.28194,149.13003));
        sourcePoints.add(new LatLng(-35.28282,149.12956));
        sourcePoints.add(new LatLng(-35.28302,149.12881));
        sourcePoints.add(new LatLng(-35.28473,149.12836));

        PolylineOptions polyLineOptions = new PolylineOptions();
        polyLineOptions.addAll(sourcePoints);
        polyLineOptions.width(5);
        polyLineOptions.color(Color.BLUE);
        mGoogleMap.addPolyline(polyLineOptions);

        mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(sourcePoints.get(0), 15));

        List<LatLng> snappedPoints = new ArrayList<>();
        new GetSnappedPointsAsyncTask().execute(sourcePoints, null, snappedPoints);
    }

    private String buildRequestUrl(List<LatLng> trackPoints) {
        StringBuilder url = new StringBuilder();
        url.append("https://roads.googleapis.com/v1/snapToRoads?path=");

        for (LatLng trackPoint : trackPoints) {
            url.append(String.format("%8.5f", trackPoint.latitude));
            url.append(",");
            url.append(String.format("%8.5f", trackPoint.longitude));
            url.append("|");
        }
        url.delete(url.length() - 1, url.length());
        url.append("&interpolate=true");
        url.append(String.format("&key=%s", <your_Google_Maps_API_key>);

        return url.toString();
    }

    private class GetSnappedPointsAsyncTask extends AsyncTask<List<LatLng>, Void, List<LatLng>> {

        protected void onPreExecute() {
            super.onPreExecute();
        }

        protected List<LatLng> doInBackground(List<LatLng>... params) {

            List<LatLng> snappedPoints = new ArrayList<>();

            HttpURLConnection connection = null;
            BufferedReader reader = null;

            try {
                URL url = new URL(buildRequestUrl(params[0]));
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.connect();

                InputStream stream = connection.getInputStream();

                reader = new BufferedReader(new InputStreamReader(stream));
                StringBuilder jsonStringBuilder = new StringBuilder();

                StringBuffer buffer = new StringBuffer();
                String line = "";

                while ((line = reader.readLine()) != null) {
                    buffer.append(line+"\n");
                    jsonStringBuilder.append(line);
                    jsonStringBuilder.append("\n");
                }

                JSONObject jsonObject = new JSONObject(jsonStringBuilder.toString());
                JSONArray snappedPointsArr = jsonObject.getJSONArray("snappedPoints");

                for (int i = 0; i < snappedPointsArr.length(); i++) {
                    JSONObject snappedPointLocation = ((JSONObject) (snappedPointsArr.get(i))).getJSONObject("location");
                    double lattitude = snappedPointLocation.getDouble("latitude");
                    double longitude = snappedPointLocation.getDouble("longitude");
                    snappedPoints.add(new LatLng(lattitude, longitude));
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return snappedPoints;
        }

        @Override
        protected void onPostExecute(List<LatLng> result) {
            super.onPostExecute(result);

            PolylineOptions polyLineOptions = new PolylineOptions();
            polyLineOptions.addAll(result);
            polyLineOptions.width(5);
            polyLineOptions.color(Color.RED);
            mGoogleMap.addPolyline(polyLineOptions);

            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            builder.include(result.get(0));
            builder.include(result.get(result.size()-1));
            LatLngBounds bounds = builder.build();
            mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 10));

        }
    }

}
</code>```

And don't forget to add Google Maps Roads API support for your project in Google APIs Console (select your project, than select Dashboard, than press "+ ENABLE APIS AND SERVICES " button, than on the left side "Filter by" select "Maps", than press "Google Maps Roads API" and, finally, press button "ENABLE").

You should get something like that:

where: blue polyline - for source points, red polyline - for snapped points.

Remember there is a limit of 100 GPS points and 2500 request per day per user (IP) and 10 requests per sec. And also you need more elegant solution for snapped points JSON downloading.

Body:
My map contains multiple points to tap the location of the user from where he passes, but the polyline is not shown on the roads, but shows a direct line from one marker to other. I want my polyline to go across the road: as the roads turns, it should also turn.

Here's my relevant code

 dataholder = FirebaseDatabase.getInstance().getReference("UserLocation");
 Log.d("onMapReady", "iam here");
 dataholder.addValueEventListener(new ValueEventListener() {

     @Override
     public void onDataChange(DataSnapshot dataSnapshot) {
         Log.d("data",String.valueOf(dataSnapshot.getValue()));
         System.out.println(dataSnapshot.getValue());
         for (DataSnapshot a : dataSnapshot.getChildren()) {
             MapData mapData = a.getValue(MapData.class);
             arrayList.add(mapData);
             lati.add(arrayList.get(i).getLatituide());
             longit.add(arrayList.get(i).getLongitude());
             Log.d("mapi","i am in loop");
             mMap = googleMap;
             Double lat = Double.parseDouble(lati.get(i));
             Double longi = Double.parseDouble(longit.get(i));
             sydney = new LatLng(longi, lat);
             points.add(sydney);
             MarkerOptions mop = new MarkerOptions();
             mop.position(sydney);
             mop.title("check");
             mMap.addMarker(mop);
             Log.d("latitude", String.valueOf(lat));
             Log.d("longitude", String.valueOf(longi));
             // Add a marker in Sydney and move the camera
             mMap.addMarker(new MarkerOptions().position(sydney).title("check"));
             mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

             i++;
         }

    line.addAll(points).width(5).color(Color.RED);
    line.geodesic(true);
    mMap.addPolyline(line);

    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            Toast.makeText(getApplicationContext(),marker.getTitle().toString(),Toast.LENGTH_LONG).show();
            return false;
        }
    });

Body:
Try to use Google Maps Roads API part Snap to Road which

returns the best-fit road geometry for a given set of GPS coordinates.
  This service takes up to 100 GPS points collected along a route, and
  returns a similar set of data with the points snapped to the most
  likely roads the vehicle was traveling along.

Something like that for data from Google Maps Roads API Snap to Road example:

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {

    private GoogleMap mGoogleMap;
    private MapFragment mapFragment;

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

        mapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map_fragment);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;

        List<LatLng> sourcePoints = new ArrayList<>();
        sourcePoints.add(new LatLng(-35.27801,149.12958));
        sourcePoints.add(new LatLng(-35.28032,149.12907));
        sourcePoints.add(new LatLng(-35.28099,149.12929));
        sourcePoints.add(new LatLng(-35.28144,149.12984));
        sourcePoints.add(new LatLng(-35.28194,149.13003));
        sourcePoints.add(new LatLng(-35.28282,149.12956));
        sourcePoints.add(new LatLng(-35.28302,149.12881));
        sourcePoints.add(new LatLng(-35.28473,149.12836));

        PolylineOptions polyLineOptions = new PolylineOptions();
        polyLineOptions.addAll(sourcePoints);
        polyLineOptions.width(5);
        polyLineOptions.color(Color.BLUE);
        mGoogleMap.addPolyline(polyLineOptions);

        mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(sourcePoints.get(0), 15));

        List<LatLng> snappedPoints = new ArrayList<>();
        new GetSnappedPointsAsyncTask().execute(sourcePoints, null, snappedPoints);
    }

    private String buildRequestUrl(List<LatLng> trackPoints) {
        StringBuilder url = new StringBuilder();
        url.append("https://roads.googleapis.com/v1/snapToRoads?path=");

        for (LatLng trackPoint : trackPoints) {
            url.append(String.format("%8.5f", trackPoint.latitude));
            url.append(",");
            url.append(String.format("%8.5f", trackPoint.longitude));
            url.append("|");
        }
        url.delete(url.length() - 1, url.length());
        url.append("&interpolate=true");
        url.append(String.format("&key=%s", <your_Google_Maps_API_key>);

        return url.toString();
    }

    private class GetSnappedPointsAsyncTask extends AsyncTask<List<LatLng>, Void, List<LatLng>> {

        protected void onPreExecute() {
            super.onPreExecute();
        }

        protected List<LatLng> doInBackground(List<LatLng>... params) {

            List<LatLng> snappedPoints = new ArrayList<>();

            HttpURLConnection connection = null;
            BufferedReader reader = null;

            try {
                URL url = new URL(buildRequestUrl(params[0]));
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.connect();

                InputStream stream = connection.getInputStream();

                reader = new BufferedReader(new InputStreamReader(stream));
                StringBuilder jsonStringBuilder = new StringBuilder();

                StringBuffer buffer = new StringBuffer();
                String line = "";

                while ((line = reader.readLine()) != null) {
                    buffer.append(line+"\n");
                    jsonStringBuilder.append(line);
                    jsonStringBuilder.append("\n");
                }

                JSONObject jsonObject = new JSONObject(jsonStringBuilder.toString());
                JSONArray snappedPointsArr = jsonObject.getJSONArray("snappedPoints");

                for (int i = 0; i < snappedPointsArr.length(); i++) {
                    JSONObject snappedPointLocation = ((JSONObject) (snappedPointsArr.get(i))).getJSONObject("location");
                    double lattitude = snappedPointLocation.getDouble("latitude");
                    double longitude = snappedPointLocation.getDouble("longitude");
                    snappedPoints.add(new LatLng(lattitude, longitude));
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return snappedPoints;
        }

        @Override
        protected void onPostExecute(List<LatLng> result) {
            super.onPostExecute(result);

            PolylineOptions polyLineOptions = new PolylineOptions();
            polyLineOptions.addAll(result);
            polyLineOptions.width(5);
            polyLineOptions.color(Color.RED);
            mGoogleMap.addPolyline(polyLineOptions);

            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            builder.include(result.get(0));
            builder.include(result.get(result.size()-1));
            LatLngBounds bounds = builder.build();
            mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 10));

        }
    }

}

And don't forget to add Google Maps Roads API support for your project in Google APIs Console (select your project, than select Dashboard, than press "+ ENABLE APIS AND SERVICES " button, than on the left side "Filter by" select "Maps", than press "Google Maps Roads API" and, finally, press button "ENABLE").

You should get something like that:

where: blue polyline - for source points, red polyline - for snapped points.

Remember there is a limit of 100 GPS points and 2500 request per day per user (IP) and 10 requests per sec. And also you need more elegant solution for snapped points JSON downloading.


问:
Passport Node(Error: Failed to deserialize user out of session.)
I'm using Node.js, express, passport and MySQL.

Here is my deserialize code:

```<code>passport.deserializeUser(function(id, done) {
connection.query("select * from users where UserId = "+id,function(err,rows){
        console.log(rows);
        done(err, rows[0]);
    });
});
</code>```

Also, checked using console.log that "rows" is returning the row of the required user.

```<code>app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});
</code>```

答:
Follow-up comment: errors should be passed as the first argument for the done() function:

return done(err, null);

or

return done(err);

whereas deserialized objects should passed as you have it:

return done(err, rows[0]);

Body:
I'm using Node.js, express, passport and MySQL.

Here is my deserialize code:

passport.deserializeUser(function(id, done) {
connection.query("select * from users where UserId = "+id,function(err,rows){
        console.log(rows);
        done(err, rows[0]);
    });
});

Also, checked using console.log that "rows" is returning the row of the required user.

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});


问:
Classify a sequence using LSTM in keras
I am working on a binary classification problem, where the network takes two inputs and output the label of this input pair.

Basically, I use an encoder layer to do embedding first and concatenate the embedding results. Next, I am going to use RNN structure to classify the concatenated result. But I can't figure out a proper way to write the code. I attach my code below.

```<code>input_size = n_feature # the number of features
encoder_size = 2000 # output dim for each encoder
dropout_rate = 0.5
X1 = Input(shape=(input_size, ), name='input_1')
X2 = Input(shape=(input_size, ), name='input_2')

encoder = Sequential()
encoder.add(Dropout(dropout_rate, input_shape=(input_size, )))
encoder.add(Dense(encoder_size, activation='relu'))

encoded_1 = encoder(X1)
encoded_2 = encoder(X2)
merged = concatenate([encoded_1, encoded_2])

#----------Need Help---------------#
comparer = Sequential()
comparer.add(LSTM(512, input_shape=(encoder_size*2, ), return_sequences=True))
comparer.add(Dropout(dropout_rate))
comparer.add(TimeDistributed(Dense(1)))
comparer.add(Activation('sigmoid'))
#----------Need Help---------------#

Y = comparer(merged)
model = Model(inputs=[X1, X2], outputs=Y)
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
</code>```

It seems for the LSTM layer, the input should be (None, encoder_size*2). I tried to use Y = comparer(K.transpose(merged)) to reshape the input for the LSTM layer but I failed. BTW, for this network, the input shape is (input_size,) and output shape is (1,).

答:
If the idea is to transform the input vector in a time series, you can simply reshape it:</p>

```<code>comparer = Sequential()

#reshape the vector into a time series form: (None, timeSteps, features)
comparer.add(Reshape((2 * encoder_size,1), input_shape=(2*encoder_size,))

#don't return sequences, you don't want a sequence as result:
comparer.add(LSTM(512, return_sequences=False))

comparer.add(Dropout(dropout_rate))

#Don't use a TimeDistributed, you're not dealing with a series anymore
comparer.add(Dense(1))

comparer.add(Activation('sigmoid'))
</code>```

Title: Classify a sequence using LSTM in keras

Body:
I am working on a binary classification problem, where the network takes two inputs and output the label of this input pair.

Basically, I use an encoder layer to do embedding first and concatenate the embedding results. Next, I am going to use RNN structure to classify the concatenated result. But I can't figure out a proper way to write the code. I attach my code below.

input_size = n_feature # the number of features
encoder_size = 2000 # output dim for each encoder
dropout_rate = 0.5
X1 = Input(shape=(input_size, ), name='input_1')
X2 = Input(shape=(input_size, ), name='input_2')

encoder = Sequential()
encoder.add(Dropout(dropout_rate, input_shape=(input_size, )))
encoder.add(Dense(encoder_size, activation='relu'))

encoded_1 = encoder(X1)
encoded_2 = encoder(X2)
merged = concatenate([encoded_1, encoded_2])

#----------Need Help---------------#
comparer = Sequential()
comparer.add(LSTM(512, input_shape=(encoder_size*2, ), return_sequences=True))
comparer.add(Dropout(dropout_rate))
comparer.add(TimeDistributed(Dense(1)))
comparer.add(Activation('sigmoid'))
#----------Need Help---------------#

Y = comparer(merged)
model = Model(inputs=[X1, X2], outputs=Y)
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

It seems for the LSTM layer, the input should be (None, encoder_size*2). I tried to use Y = comparer(K.transpose(merged)) to reshape the input for the LSTM layer but I failed. BTW, for this network, the input shape is (input_size,) and output shape is (1,).

Body:
If the idea is to transform the input vector in a time series, you can simply reshape it:

comparer = Sequential()

#reshape the vector into a time series form: (None, timeSteps, features)
comparer.add(Reshape((2 * encoder_size,1), input_shape=(2*encoder_size,))

#don't return sequences, you don't want a sequence as result:
comparer.add(LSTM(512, return_sequences=False))

comparer.add(Dropout(dropout_rate))

#Don't use a TimeDistributed, you're not dealing with a series anymore
comparer.add(Dense(1))

comparer.add(Activation('sigmoid'))


问:
Postgres Insert based on JSON data
Trying to do an insert based on whether a value all ready exists or not in a JSON blob in a Postgres table.

```<code>| a | b | c | d |       metadata                    |
_____________________________________________________
| 1 | 2 | 3 | 4 | {"other-key": 1}                  |
| 2 | 1 | 4 | 4 | {"key": 99}                       |
| 3 | 1 | 4 | 4 | {"key": 99, "other-key": 33}      |
</code>```

Currently trying to use something like this.

```<code>INSERT INTO mytable (a, b, c, d, metadata)
SELECT :a, :b, :c, :d, :metadata::JSONB
WHERE
  (:metadata->>'key'::TEXT IS NULL
   OR :metadata->>'key'::TEXT NOT IN (SELECT :metadata->>'key'::TEXT
                                   FROM mytable));
</code>```

But keep getting an  ERROR: operator does not exist: unknown ->> boolean
  Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.

答:
It was just a simple casting issue</p>

```<code>INSERT INTO mytable (a, b, c, d, metadata)
SELECT :a, :b, :c, :d, :metadata::JSONB
WHERE
  ((:metadata::JSONB->>'key') is NULL or
  :metadata::JSONB->>'key' NOT IN (
                                  SELECT  metadata->>'key' FROM mytable
                                  WHERE
                                  metadata->>'key' =  :metadata::JSONB->>'key'));
</code>```

Title: Postgres Insert based on JSON data

Body:
Trying to do an insert based on whether a value all ready exists or not in a JSON blob in a Postgres table.

| a | b | c | d |       metadata                    |
_____________________________________________________
| 1 | 2 | 3 | 4 | {"other-key": 1}                  |
| 2 | 1 | 4 | 4 | {"key": 99}                       |
| 3 | 1 | 4 | 4 | {"key": 99, "other-key": 33}      |

Currently trying to use something like this.

INSERT INTO mytable (a, b, c, d, metadata)
SELECT :a, :b, :c, :d, :metadata::JSONB
WHERE
  (:metadata->>'key'::TEXT IS NULL
   OR :metadata->>'key'::TEXT NOT IN (SELECT :metadata->>'key'::TEXT
                                   FROM mytable));

But keep getting an  ERROR: operator does not exist: unknown ->> boolean
  Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.

Body:
It was just a simple casting issue

INSERT INTO mytable (a, b, c, d, metadata)
SELECT :a, :b, :c, :d, :metadata::JSONB
WHERE
  ((:metadata::JSONB->>'key') is NULL or
  :metadata::JSONB->>'key' NOT IN (
                                  SELECT  metadata->>'key' FROM mytable
                                  WHERE
                                  metadata->>'key' =  :metadata::JSONB->>'key'));