问:
Using NSPredicate to filter an NSArray based on NSDictionary keys
I have an array of dictionaries.

I want to filter the array based on a key.

I tried this:

```<code>NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SPORT ==  %@)", @"Football"];

NSArray *filteredArray = [data filteredArrayUsingPredicate:predicate];
</code>```

This doesn't work, I get no results. I think I'm doing something wrong. I know this is the method if "SPORT" was an ivar. I think it is probably different if it is a key.

I haven't been able to find an example however.

Thanks

Update

I added quotes around the string I am searching for.

```<code>NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SPORT ==  '%@')", @"Football"];
</code>```

It still does not work.

Update 2

Solved it. I actually had to remove the single quotes, which seems to go against what the guide says.

My real problem is I had a nested array and I wasn't actually evaluating the dictionaries. Bone head move.

答:
With Swift 3, when you want to filter an array of dictionaries with a predicate based on dictionary keys and values, you may choose one of the following patterns.

#1. Using NSPredicate init(format:arguments:) initializer

If you come from Objective-C, init(format:arguments:) offers a key-value coding style to evaluate your predicate.

Usage:

```<code>import Foundation

let array = [["key1": "value1", "key2": "value2"], ["key1": "value3"], ["key3": "value4"]]

let predicate = NSPredicate(format: "key1 == %@", "value1")
//let predicate = NSPredicate(format: "self['key1'] == %@", "value1") // also works
let filteredArray = array.filter(predicate.evaluate)

print(filteredArray) // prints: [["key2": "value2", "key1": "value1"]]
</code>```

#2. Using NSPredicate init(block:) initializer

As an alternative if you prefer strongly typed APIs over stringly typed APIs, you can use init(block:) initializer.

Usage:

```<code>import Foundation

let array = [["key1": "value1", "key2": "value2"], ["key1": "value3"], ["key3": "value4"]]

let dictPredicate = NSPredicate(block: { (obj, _) in
    guard let dict = obj as? [String: String], let value = dict["key1"] else { return false }
    return value == "value1"
})

let filteredArray = array.filter(dictPredicate.evaluate)
print(filteredArray) // prints: [["key2": "value2", "key1": "value1"]]
</code>```

Body:
I have an array of dictionaries.

I want to filter the array based on a key.

I tried this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SPORT ==  %@)", @"Football"];

NSArray *filteredArray = [data filteredArrayUsingPredicate:predicate];

This doesn't work, I get no results. I think I'm doing something wrong. I know this is the method if "SPORT" was an ivar. I think it is probably different if it is a key.

I haven't been able to find an example however.

Thanks

Update

I added quotes around the string I am searching for.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SPORT ==  '%@')", @"Football"];

It still does not work.

Update 2

Solved it. I actually had to remove the single quotes, which seems to go against what the guide says.

My real problem is I had a nested array and I wasn't actually evaluating the dictionaries. Bone head move.

Body:
With Swift 3, when you want to filter an array of dictionaries with a predicate based on dictionary keys and values, you may choose one of the following patterns.

#1. Using NSPredicate init(format:arguments:) initializer

If you come from Objective-C, init(format:arguments:) offers a key-value coding style to evaluate your predicate.

Usage:

import Foundation

let array = [["key1": "value1", "key2": "value2"], ["key1": "value3"], ["key3": "value4"]]

let predicate = NSPredicate(format: "key1 == %@", "value1")
//let predicate = NSPredicate(format: "self['key1'] == %@", "value1") // also works
let filteredArray = array.filter(predicate.evaluate)

print(filteredArray) // prints: [["key2": "value2", "key1": "value1"]]

#2. Using NSPredicate init(block:) initializer

As an alternative if you prefer strongly typed APIs over stringly typed APIs, you can use init(block:) initializer.

Usage:

import Foundation

let array = [["key1": "value1", "key2": "value2"], ["key1": "value3"], ["key3": "value4"]]

let dictPredicate = NSPredicate(block: { (obj, _) in
    guard let dict = obj as? [String: String], let value = dict["key1"] else { return false }
    return value == "value1"
})

let filteredArray = array.filter(dictPredicate.evaluate)
print(filteredArray) // prints: [["key2": "value2", "key1": "value1"]]


来源: stackexchange

问:
Cannot obtain image of photo-sphere when photographer is not Google
I am using the Google Street View Image API ( https://developers.google.com/maps/documentation/streetview/ ) to get a 640x640 bitmap of the photo-sphere currently displayed in my app. I am able to obtain this bitmap when Google has the copyright on the photo-sphere, but not when the photo-sphere was contributed by an individual. Am I doing something wrong or does the Google Street View Image API not return a bitmap in such case?

What I'm getting, when the author is an individual, is a white bitmap that says on it "Sorry, we have no imagery here".

答:
This is a known issue reported in the Google Maps API public issue tracker:

https://issuetracker.google.com/issues/35831151

The issue was acknowledged by Google, however they didn't expose any ETA regarding when it might be fixed.

I can suggest staring the issue to express your interest and receive further updates from Google.

ContentLicense: CC BY-SA 3.0


问:
ScalaTest in sbt: is there a way to run a single test without tags?
I know that a single test can be ran by running, in sbt,

```<code>testOnly *class -- -n Tag
</code>```

Is there a way of telling sbt/scalatest to run a single test without tags? For example:

```<code>testOnly *class -- -X 2
</code>```

it would mean "run the second test in the class. Whatever it is". We have a bunch of tests and no one bothered to tag them, so is there a way to run a single test without it having a tag?

答:
I wanted to add a concrete example to accompany the other answers

You need to specify the name of the class that you want to test, so if you have the following project (this is a Play project):

You can test just the Login tests by running the following command from the SBT console:

```<code>test:testOnly *LoginServiceSpec
</code>```

If you are running the command from outside the SBT console, you would do the following:

```<code>sbt "test:testOnly *LoginServiceSpec"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I know that a single test can be ran by running, in sbt,

testOnly *class -- -n Tag

Is there a way of telling sbt/scalatest to run a single test without tags? For example:

testOnly *class -- -X 2

it would mean "run the second test in the class. Whatever it is". We have a bunch of tests and no one bothered to tag them, so is there a way to run a single test without it having a tag?

Body:
I wanted to add a concrete example to accompany the other answers

You need to specify the name of the class that you want to test, so if you have the following project (this is a Play project):

You can test just the Login tests by running the following command from the SBT console:

test:testOnly *LoginServiceSpec

If you are running the command from outside the SBT console, you would do the following:

sbt "test:testOnly *LoginServiceSpec"


问:
Having issues with python nested dictionaries
I am having a few newbie issues with python where, despite all the suggestions I've seen online, I can't access the value in a listed dictionary I'm trying to access.

This is the data the API returns:

```<code>OrderedDict([(u'totalSize', 1), (u'done', True), (u'records', [OrderedDict([(u'attributes', OrderedDict([(u'type', u'Contact'), (u'url', u'/services/data/v29.0/sobjects/Contact/00346000004eV89AAE')])), (u'Name', u'This is my name')])])])
</code>```

This is my most recent attempt:

```<code>dict['records']['Name']

    print(dict['records']['Name'])
TypeError: list indices must be integers, not str
</code>```

Any help would be greatly appreciated

答:
The data structure you get from your API has a list of dictionaries as dict['records']. You seem to be expecting a dictionary there instead.

Since the list has only a single element, you may just need to index the list to get the value you want: dict['records'][0]['name'].

However, if there might be a different number of inner dictionaries in the list, you may want to write list comprehension (or explicit loop) instead. Try something like [inner['name'] for inner in dict['records']]. This will give you a list of names, with the same number of items as the dict['records'] list.

Note that it's probably a bad idea to use dict as a variable name in your code, since that's the name of the builtin dictionary type. Using it for something else can lead to unexpected errors in later code (when you want to create a dictionary but end up calling something else). This isn't the cause of your issue indexing your data structure, just a way to improve your code a bit.

Body:
I am having a few newbie issues with python where, despite all the suggestions I've seen online, I can't access the value in a listed dictionary I'm trying to access.

This is the data the API returns:

OrderedDict([(u'totalSize', 1), (u'done', True), (u'records', [OrderedDict([(u'attributes', OrderedDict([(u'type', u'Contact'), (u'url', u'/services/data/v29.0/sobjects/Contact/00346000004eV89AAE')])), (u'Name', u'This is my name')])])])

This is my most recent attempt:

dict['records']['Name']

    print(dict['records']['Name'])
TypeError: list indices must be integers, not str

Any help would be greatly appreciated


问:
Rotating textures individually using webgl
I want to rotate each texture individually in my rendercall. I read this tutorial, and it works as i want it to except that the rotation is applied to all objects(due to the rotation value being uniform).

So i rewrote it to use a buffer but i cant get it to work properly.

Heres my shader:

```<code>attribute vec2 a_position;
attribute vec2 a_texture_coord;
attribute vec2 a_rotation;
attribute vec4 a_color;

uniform vec2 u_resolution;

varying highp vec2 v_texture_coord;
varying vec4 v_color;

void main() {
  v_color = a_color;
  vec2 rotatedPosition = vec2(
     a_position.x * a_rotation.y + a_position.y * a_rotation.x,
     a_position.y * a_rotation.y - a_position.x * a_rotation.x);
  vec2 zeroToOne = rotatedPosition / u_resolution;
  vec2 zeroToTwo = zeroToOne * 2.0;
  vec2 clipSpace = zeroToTwo - 1.0;

  gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);
  v_texture_coord = a_texture_coord;
}
</code>```

and typescript code

```<code>this.gl.enableVertexAttribArray(this.rotationAttributeLocation);

this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.rotationBuffer);
this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(renderCall.rotation), this.gl.STATIC_DRAW);

this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.rotationBuffer);
this.gl.vertexAttribPointer(this.rotationAttributeLocation, 2, this.gl.FLOAT, false, 0, 0);
</code>```

I get no errors from webgl or from the browser but end up with a blank canvas. Any ideas?

答:
After much digging around in matrix math and how to use it in webgl.
I came up with a solution that worked well for my specific problem.
Creating a rendercall for each object(squares 6 vertices) turned out to effect the performance quite drastically.

As i only needed to rotate a few objects each rendering cycle i rotated the vertecies directly in javascript.

Something like this:

```<code>    let x1 = x + width;
    let x2 = x;
    let y1 = y;
    let y2 = y + height;

    let rotatePointX = x2;
    let rotatePointY = y1;

    let moveToRotationPointMatrix = Matrix3.createTranslationMatrix(-rotatePointX, -rotatePointY);
    let rotationMatrix = Matrix3.createRotationMatrix(angle);
    let moveBackMatrix = Matrix3.createTranslationMatrix(rotatePointX, rotatePointY);

    let matrix = Matrix3.multiply(moveToRotationPointMatrix, rotationMatrix);
    matrix = Matrix3.multiply(matrix, moveBackMatrix);

    let x1y1 = Matrix3.positionConvertion(x1, y1, matrix);
    let x2y2 = Matrix3.positionConvertion(x2, y2, matrix);
    let x2y1 = Matrix3.positionConvertion(x2, y1, matrix);
    let x1y2 = Matrix3.positionConvertion(x1, y2, matrix);

    let newVertecies = [
        x1y1[0], x1y1[1],
        x2y2[0], x2y2[1],
        x2y1[0], x2y1[1],
        x1y1[0], x1y1[1],
        x2y2[0], x2y2[1],
        x1y2[0], x1y2[1]
    ];
</code>```

Where Matrix3 is more or less a copy from Webglfundamentals helper class for 3x3 matrix math, from here

```<code>public static positionConvertion(x: number, y: number, matrix: number[]) {
    x = x * matrix[0] + y * matrix[3] + 1 * matrix[6];
    y = x * matrix[1] + y * matrix[4] + 1 * matrix[7];

    return [x, y];
}
</code>```

Also check out this answer for a simple example of how to do the rotation in the shader.

Other helpful sources

```<code>webglfundamentals.org/webgl/lessons/webgl-2d-matrices.html
webglfundamentals.org/webgl/lessons/webgl-2d-matrix-stack.html
webglfundamentals.org/webgl/lessons/webgl-2d-rotation.html
</code>```

Body:
I want to rotate each texture individually in my rendercall. I read this tutorial, and it works as i want it to except that the rotation is applied to all objects(due to the rotation value being uniform).

So i rewrote it to use a buffer but i cant get it to work properly.

Heres my shader:

attribute vec2 a_position;
attribute vec2 a_texture_coord;
attribute vec2 a_rotation;
attribute vec4 a_color;

uniform vec2 u_resolution;

varying highp vec2 v_texture_coord;
varying vec4 v_color;

void main() {
  v_color = a_color;
  vec2 rotatedPosition = vec2(
     a_position.x * a_rotation.y + a_position.y * a_rotation.x,
     a_position.y * a_rotation.y - a_position.x * a_rotation.x);
  vec2 zeroToOne = rotatedPosition / u_resolution;
  vec2 zeroToTwo = zeroToOne * 2.0;
  vec2 clipSpace = zeroToTwo - 1.0;

  gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);
  v_texture_coord = a_texture_coord;
}

and typescript code

this.gl.enableVertexAttribArray(this.rotationAttributeLocation);

this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.rotationBuffer);
this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(renderCall.rotation), this.gl.STATIC_DRAW);

this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.rotationBuffer);
this.gl.vertexAttribPointer(this.rotationAttributeLocation, 2, this.gl.FLOAT, false, 0, 0);

I get no errors from webgl or from the browser but end up with a blank canvas. Any ideas?

Body:
After much digging around in matrix math and how to use it in webgl.
I came up with a solution that worked well for my specific problem.
Creating a rendercall for each object(squares 6 vertices) turned out to effect the performance quite drastically.

As i only needed to rotate a few objects each rendering cycle i rotated the vertecies directly in javascript.

Something like this:

    let x1 = x + width;
    let x2 = x;
    let y1 = y;
    let y2 = y + height;

    let rotatePointX = x2;
    let rotatePointY = y1;

    let moveToRotationPointMatrix = Matrix3.createTranslationMatrix(-rotatePointX, -rotatePointY);
    let rotationMatrix = Matrix3.createRotationMatrix(angle);
    let moveBackMatrix = Matrix3.createTranslationMatrix(rotatePointX, rotatePointY);

    let matrix = Matrix3.multiply(moveToRotationPointMatrix, rotationMatrix);
    matrix = Matrix3.multiply(matrix, moveBackMatrix);

    let x1y1 = Matrix3.positionConvertion(x1, y1, matrix);
    let x2y2 = Matrix3.positionConvertion(x2, y2, matrix);
    let x2y1 = Matrix3.positionConvertion(x2, y1, matrix);
    let x1y2 = Matrix3.positionConvertion(x1, y2, matrix);

    let newVertecies = [
        x1y1[0], x1y1[1],
        x2y2[0], x2y2[1],
        x2y1[0], x2y1[1],
        x1y1[0], x1y1[1],
        x2y2[0], x2y2[1],
        x1y2[0], x1y2[1]
    ];

Where Matrix3 is more or less a copy from Webglfundamentals helper class for 3x3 matrix math, from here

public static positionConvertion(x: number, y: number, matrix: number[]) {
    x = x * matrix[0] + y * matrix[3] + 1 * matrix[6];
    y = x * matrix[1] + y * matrix[4] + 1 * matrix[7];

    return [x, y];
}

Also check out this answer for a simple example of how to do the rotation in the shader.

Other helpful sources

webglfundamentals.org/webgl/lessons/webgl-2d-matrices.html
webglfundamentals.org/webgl/lessons/webgl-2d-matrix-stack.html
webglfundamentals.org/webgl/lessons/webgl-2d-rotation.html


问:
iPhone Passcode Integration
I want to integrate a passcode into my existing application. Does anyone know of any good tutorials, or such that would lend to my search? Is there a standard Apple tutorial to integrate one? I've not been able to find one, but I imagine it'd be as simple as putting a keypad view in the didFinishLaunching & resignActive methods right? Would keychain be a good place to store it? Again, I'd hate to reinvent the wheel on this, especially if there is a proven secure method out there. Here is the one good tutorial I've been able to find, but it doesn't incorporate a view, or multiple invoke points. http://gorgando.com/blog/topics/technology/iphone_development/simple-iphone-tutorial-password-management-using-the-keychain-by-using-sfhfkeychainutils

Thanks!

答:
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

```<code>if (standardUserDefaults)
{
    [standardUserDefaults setObject:passCodeTextField.text forKey:@"lock"];
    [standardUserDefaults synchronize];
}
</code>```

if you have any saving scheme then put this in particular action othervise set this at the first time application launch.

check in appDelegate put proper if else condition then use above code

Now you can access this passcode

NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
    if (standardUserDefaults)
        self.passCodeString = [standardUserDefaults objectForKey:@"lock"];

And you can use this in a perticular view (for passcode).

ContentLicense: CC BY-SA 2.5

Title: iPhone Passcode Integration

Body:
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

if (standardUserDefaults)
{
    [standardUserDefaults setObject:passCodeTextField.text forKey:@"lock"];
    [standardUserDefaults synchronize];
}

if you have any saving scheme then put this in particular action othervise set this at the first time application launch.

check in appDelegate put proper if else condition then use above code

Now you can access this passcode

NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
    if (standardUserDefaults)
        self.passCodeString = [standardUserDefaults objectForKey:@"lock"];

And you can use this in a perticular view (for passcode).


问:
Create a map with composite key with Java 8 on the fly
I want to create a map like below->

```<code>Map<Pair<MyClass.a, MyClass.b>, MyClass>>.
</code>```

I have a list of object ->

```<code>List<MyClass>
</code>```

Here Pair is a class, already in my project, so I wanted to use it.

I need help to create it from a Java 8 stream.

I did try ::

```<code>ls.stream().collect(Collectors.toMap(new Pair(MyClass.a, MyClass.b), MyClass));
</code>```

But I am getting an error. I am new to Java 8 and trying to learn it.

Adding an example :

```<code>class Person {
   String name ;
   int age ;
   // Some other variables
}
</code>```

I have a list of List<Person>.

In my requirement I need a key = {name, age}, using the pair class.

```<code>class Pair<T,U> {
    Pair(T t, U u) {
        this.t = t
        this.u = u
    }

    // Overridden hashCode && equals methods
}
</code>```

Now I want to create a map like Map<Pair<String, Int>, Person>

I was getting a compiler error that said "Not a functional interface".

I am sure there must be a way via java 8 stream and collect.

答:
In order to create a function, you must use a lambda expression. It’s not sufficient an write an expression like new Pair(MyClass.a, MyClass.b), instead, you specify a function having a parameter, that will be a Person instance, i.e. p -> new Pair<>(p.name, p.age). Alternatively you may make the parameter explicit: (Person p) -> new Pair<>(p.name, p.age).

For your Map creation operation, you have to decide, what you want. E.g.,

```<code>Map<Pair<String, Integer>, List<Person>> map
    = list.stream().collect(Collectors.groupingBy(p -> new Pair<>(p.name, p.age)));
</code>```

will map each key to a list of all Person instances having that name/age combination.

In contrast

```<code>Map<Pair<String, Integer>, Person> map
    = list.stream().collect(Collectors.toMap(p -> new Pair<>(p.name, p.age), p -> p));
</code>```

will map the name/age pairs to a single Person instance, but throw an exception, if there is more than one with the same key. You can specify a function to resolve such conflicts, e.g.

```<code>Map<Pair<String, Integer>, Person> map = list.stream().collect(
    Collectors.toMap(p -> new Pair<>(p.name, p.age), p -> p, (first, next) -> first));
</code>```

will keep the first, whereas

```<code>Map<Pair<String, Integer>, Person> map = list.stream().collect(
    Collectors.toMap(p -> new Pair<>(p.name, p.age), p -> p, (prev, last) -> last));
</code>```

will overwrite the previous occurrence, ending up with the last Person instance for each name/age combination.

Body:
I want to create a map like below->

Map<Pair<MyClass.a, MyClass.b>, MyClass>>.

I have a list of object ->

List<MyClass>

Here Pair is a class, already in my project, so I wanted to use it.

I need help to create it from a Java 8 stream.

I did try ::

ls.stream().collect(Collectors.toMap(new Pair(MyClass.a, MyClass.b), MyClass));

But I am getting an error. I am new to Java 8 and trying to learn it.

Adding an example :

class Person {
   String name ;
   int age ;
   // Some other variables
}

I have a list of List<Person>.

In my requirement I need a key = {name, age}, using the pair class.

class Pair<T,U> {
    Pair(T t, U u) {
        this.t = t
        this.u = u
    }

    // Overridden hashCode && equals methods
}

Now I want to create a map like Map<Pair<String, Int>, Person>

I was getting a compiler error that said "Not a functional interface".

I am sure there must be a way via java 8 stream and collect.

Body:
In order to create a function, you must use a lambda expression. It’s not sufficient an write an expression like new Pair(MyClass.a, MyClass.b), instead, you specify a function having a parameter, that will be a Person instance, i.e. p -> new Pair<>(p.name, p.age). Alternatively you may make the parameter explicit: (Person p) -> new Pair<>(p.name, p.age).

For your Map creation operation, you have to decide, what you want. E.g.,

Map<Pair<String, Integer>, List<Person>> map
    = list.stream().collect(Collectors.groupingBy(p -> new Pair<>(p.name, p.age)));

will map each key to a list of all Person instances having that name/age combination.

In contrast

Map<Pair<String, Integer>, Person> map
    = list.stream().collect(Collectors.toMap(p -> new Pair<>(p.name, p.age), p -> p));

will map the name/age pairs to a single Person instance, but throw an exception, if there is more than one with the same key. You can specify a function to resolve such conflicts, e.g.

Map<Pair<String, Integer>, Person> map = list.stream().collect(
    Collectors.toMap(p -> new Pair<>(p.name, p.age), p -> p, (first, next) -> first));

will keep the first, whereas

Map<Pair<String, Integer>, Person> map = list.stream().collect(
    Collectors.toMap(p -> new Pair<>(p.name, p.age), p -> p, (prev, last) -> last));

will overwrite the previous occurrence, ending up with the last Person instance for each name/age combination.


问:
How to have multiple versions of the same package as the indirect dependencies of a project?
I'm working on a project which connects to Elasticsearch 5.2.1 and Neo4j 3.1.0 at the same time. These two packages both make use of Lucene but unfortunately incompatible versions. Elaticseach needs Lucence 6.4.1 and Neo4j works with Lucene 5.5.0.

As the result, I'm facing with runtime errors since some of the classes have incompatible signatures. Is there any way I can have both Elasticsearch and Neo4j (with the given versions) in one project?

What I'm trying to do is to add Elasticsearch package to this project. And here are the Elasticsearch dependencies that I added:

```<code>    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>5.2.1</version>
    </dependency>
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>transport</artifactId>
        <version>5.2.1</version>
    </dependency>
</code>```

How can I make these two to play alongside of each other nicely?

答: Each combination of jar should be packaged inside a distinct jar with dependencies  or a war and these should not share the same parent classloader so that a loaded class that exits in two distinct versions of the jar with dependencies  or a war be  loaded by a distinct classloader.</p>

Body:
I'm working on a project which connects to Elasticsearch 5.2.1 and Neo4j 3.1.0 at the same time. These two packages both make use of Lucene but unfortunately incompatible versions. Elaticseach needs Lucence 6.4.1 and Neo4j works with Lucene 5.5.0.

As the result, I'm facing with runtime errors since some of the classes have incompatible signatures. Is there any way I can have both Elasticsearch and Neo4j (with the given versions) in one project?

What I'm trying to do is to add Elasticsearch package to this project. And here are the Elasticsearch dependencies that I added:

    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>5.2.1</version>
    </dependency>
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>transport</artifactId>
        <version>5.2.1</version>
    </dependency>

How can I make these two to play alongside of each other nicely?


问:
Error:Execution failed for task ':java.util.zip.ZipException: duplicate entry: org/apache/commons/io/CopyUtils.class
```<code>Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: org/apache/commons/io/CopyUtils.class
</code>```

It occurs this error.

The app builds success but when I get build apk, android studio show this message

This is my gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '25'
    defaultConfig {
        applicationId "com.example.thewell_dev.fourscompany"
        minSdkVersion 19
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:23.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile 'com.mobsandgeeks:android-saripaar:2.0.3'
    compile 'com.koushikdutta.ion:ion:2.1.9'
    compile 'gun0912.ted:tedpermission:1.0.2'
    compile 'com.android.support:design:22.+'
    compile 'com.estimote:sdk:0.13.0'
    compile 'jp.wasabeef:glide-transformations:2.0.0'
    compile 'com.afollestad:easyvideoplayer:0.3.0'
    compile 'com.github.jrvansuita:PickImage:v2.0.0'
    compile 'com.amazonaws:aws-android-sdk-s3:2.+'
    compile 'com.mindorks:placeholderview:0.6.0'
    compile 'com.tsengvn:Typekit:1.0.0'
    compile 'com.github.esafirm:RxDownloader:1.0.1'
    compile 'com.mlsdev.rximagepicker:library:1.1.2'
    compile 'io.reactivex:rxjava:1.0.14'
    compile 'com.kbeanie:image-chooser-library:1.5.2@aar'
    compile 'com.kbeanie:image-chooser-library:1.5.8'
    compile 'io.github.jeancsanchez.photoviewslider:photoviewslider:1.2.0'
    compile 'com.nononsenseapps:filepicker:3.1.0'
    compile 'com.gjiazhe:scrollparallaximageview:1.0'
    compile 'com.droidninja:filepicker:1.0.8'
    compile 'com.android.support:multidex:1.0.0'

}
</code>```

I think external libraries have
Commons-io-1.3.2.jar
Commons-io-2.4.jar
and both have CopyUtils.class

Anyway, It can't build apk and show that message.

Please anyone help me please

答:
Found the solution for this issue . You need to exclude common-io from your app build.gradle .</p>

```<code>android {
    configurations{
        all*.exclude module: 'commons-io'
    }
}
</code>```

Body:
Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: org/apache/commons/io/CopyUtils.class

It occurs this error.

The app builds success but when I get build apk, android studio show this message

This is my gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '25'
    defaultConfig {
        applicationId "com.example.thewell_dev.fourscompany"
        minSdkVersion 19
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:23.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile 'com.mobsandgeeks:android-saripaar:2.0.3'
    compile 'com.koushikdutta.ion:ion:2.1.9'
    compile 'gun0912.ted:tedpermission:1.0.2'
    compile 'com.android.support:design:22.+'
    compile 'com.estimote:sdk:0.13.0'
    compile 'jp.wasabeef:glide-transformations:2.0.0'
    compile 'com.afollestad:easyvideoplayer:0.3.0'
    compile 'com.github.jrvansuita:PickImage:v2.0.0'
    compile 'com.amazonaws:aws-android-sdk-s3:2.+'
    compile 'com.mindorks:placeholderview:0.6.0'
    compile 'com.tsengvn:Typekit:1.0.0'
    compile 'com.github.esafirm:RxDownloader:1.0.1'
    compile 'com.mlsdev.rximagepicker:library:1.1.2'
    compile 'io.reactivex:rxjava:1.0.14'
    compile 'com.kbeanie:image-chooser-library:1.5.2@aar'
    compile 'com.kbeanie:image-chooser-library:1.5.8'
    compile 'io.github.jeancsanchez.photoviewslider:photoviewslider:1.2.0'
    compile 'com.nononsenseapps:filepicker:3.1.0'
    compile 'com.gjiazhe:scrollparallaximageview:1.0'
    compile 'com.droidninja:filepicker:1.0.8'
    compile 'com.android.support:multidex:1.0.0'

}

I think external libraries have
Commons-io-1.3.2.jar
Commons-io-2.4.jar
and both have CopyUtils.class

Anyway, It can't build apk and show that message.

Please anyone help me please

Body:
Found the solution for this issue . You need to exclude common-io from your app build.gradle .

android {
    configurations{
        all*.exclude module: 'commons-io'
    }
}


问:
Visual studio Xamarin Android SDK
I just installed Visual Studio 2017 professional, including Mobile development with .NET.

When I create a Cross Platform App (Xamarin.Formsapp (master detail, PCL), I am able to launch this with emulator Visualstudio_android-23_arm_phone (Android 6.0 - API level 23), however I get a warning: non-(x86) android emulator is 10 times faster and indeed, it is slow.

I also get $(TargetFrameworkVersion) for FormsViewGroup.dll (v7.0) is greater than $(TargetFrameworkVersion) for your project (v6.0), while I didn't change anything from the template, not sure if it matters though?

I tried to download a different android emulator: Marshmallow (API level 23), but now I get an "Object reference not set to an instance of an object" error in my output.

I'm wondering what I'm doing wrong (plain install, plain template), how should I get rid of all those warnings and what Emulator should I use?

答:
Visualstudio_android-23_arm_phone (Android 6.0 - API level 23) is an arm emulator - so a different chipset to what you have on your PC. This means it will have to emulate the hardware layer which makes it slower.

There should be an emulator with x86 in the name (and probably with accelerated in the name as well), so use that one.

Title: Visual studio Xamarin Android SDK


问:
How do I run that database backup and restore scripts from my winform application?
I am developing a small business application which uses Sqlserver 2005 database.

Platform: .Net framework 3.5;
Application type: windows application;
Language: C#

Question:

I need to take and restore the backup from my application. I have the required script generated from SSME.

How do I run that particular script (or scripts) from my winform application?

答: If the machine where your application is running has the SQL Server client tools installed, you can use sqlcmd.</p>

OwnerDisplayName: Asad Malik

OwnerDisplayName: Mitch Wheat


问:
AppEngine with Eclipse - Common war/ resources
I have been creating Google AppEngine projects using Eclipse SDK 3.6.1.

In all of the projects I have a StyleSheet default.css (all seperate copies) that I have in the war folder.

I would like to keep this file in one place to be included in all of the projects.

I have created a copy in the workspace folder.

I have tried linking the file into the war folder, it shows up as a linked file, I can edit it, and all looks fine.

When I run the application I can see by the webpage created that it is not recognizing the linked file.

I hope that I am missing something simple, I do not like keeping multiple copies of a common resource.

Any ideas?

Thanks,

RRaney

答: Have you tried "Static Files and Resource Files"?</p>


问:
Transforming a series of tuples into a series of the nth element of each tuple
Is there a clean way to transform a Series of tuples into another Series consisting of first (or nth) element in each tuple? For example,

```<code>ser = pd.Series([ (0,1,2), (3,4,5) ])
</code>```

Should be transform into a series consisting of 0 and 3:

```<code>0  0
1  3
</code>```

(where the 0,1 is the index). Thanks.

答:
You can use Series.apply to apply an arbitrary function to your Series. The operator.itemgetter will return a function that accesses whichever member you want:

```<code>get0 = operator.itemgetter(0)
my0 = myseries.apply(get0)
</code>```

Body:
Is there a clean way to transform a Series of tuples into another Series consisting of first (or nth) element in each tuple? For example,

ser = pd.Series([ (0,1,2), (3,4,5) ])

Should be transform into a series consisting of 0 and 3:

0  0
1  3

(where the 0,1 is the index). Thanks.

Body:
You can use Series.apply to apply an arbitrary function to your Series. The operator.itemgetter will return a function that accesses whichever member you want:

get0 = operator.itemgetter(0)
my0 = myseries.apply(get0)


问:
Clearing a cell based on a dependent drop down box in VBA
I have a drop down box in I8, and I have a dependent drop down box in I18 that is directing to I8. If perhaps apple1 is chosen in I8, I will get fruits 1-10 listed in I18 when I click on that box. Say I chose Fruit 9 for the box in I18. Well, the problem is that say I decide to change my I8 answer to apple2, Fruits 1-5 will appear in I18 but 6-10 will not. Now in I18, Fruit 9 is still chosen, and I will have to click to change it.

I want to make it to where if I have chosen Fruits 6-10 while apple1 is chosen, and I decide to change it to apple2, my I18 will go blank.

Here is my code:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
If Target.Address = "$I$8" Then
    If Target.Address = "6" Or "7" Or "8" Or "9" Or "10" Then
    If Target.Validation.Type = 3 Then
    Application.EnableEvents = False
    Target.Offset(10, 0).ClearContents
    End If
    End If
End If

exitHandler:
Application.EnableEvents = True
Exit Sub
End Sub
</code>```

答:
A few issues. See notes in refactored code.</p>

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

'On Error Resume Next ->> delete this, it will not allow you to see real errors in your code

If Target.Address = "$I$8" Then

    'you ask it define Target.Address = 6, etc. Wrong property. You need Target.Value (
    'think about it, you just checked for Address = $I$8, so how can it also be 6 - 10
    'also if you do want to use IF, syntax is Target.Value = 6 or Target.Value = 7 ... not 6 or 7 or ...

    Select Case Target.value 'used this as it more efficient

          Case 6 to 10

             If Target.Validation.Type = 3 Then
                 Application.EnableEvents = False
                 Target.Offset(10, 0).ClearContents
             End If

    End Select

End If

exitHandler:
Application.EnableEvents = True
Exit Sub
End Sub
</code>```

Body:
I have a drop down box in I8, and I have a dependent drop down box in I18 that is directing to I8. If perhaps apple1 is chosen in I8, I will get fruits 1-10 listed in I18 when I click on that box. Say I chose Fruit 9 for the box in I18. Well, the problem is that say I decide to change my I8 answer to apple2, Fruits 1-5 will appear in I18 but 6-10 will not. Now in I18, Fruit 9 is still chosen, and I will have to click to change it.

I want to make it to where if I have chosen Fruits 6-10 while apple1 is chosen, and I decide to change it to apple2, my I18 will go blank.

Here is my code:

Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
If Target.Address = "$I$8" Then
    If Target.Address = "6" Or "7" Or "8" Or "9" Or "10" Then
    If Target.Validation.Type = 3 Then
    Application.EnableEvents = False
    Target.Offset(10, 0).ClearContents
    End If
    End If
End If

exitHandler:
Application.EnableEvents = True
Exit Sub
End Sub

Body:
A few issues. See notes in refactored code.

Private Sub Worksheet_Change(ByVal Target As Range)

'On Error Resume Next ->> delete this, it will not allow you to see real errors in your code

If Target.Address = "$I$8" Then

    'you ask it define Target.Address = 6, etc. Wrong property. You need Target.Value (
    'think about it, you just checked for Address = $I$8, so how can it also be 6 - 10
    'also if you do want to use IF, syntax is Target.Value = 6 or Target.Value = 7 ... not 6 or 7 or ...

    Select Case Target.value 'used this as it more efficient

          Case 6 to 10

             If Target.Validation.Type = 3 Then
                 Application.EnableEvents = False
                 Target.Offset(10, 0).ClearContents
             End If

    End Select

End If

exitHandler:
Application.EnableEvents = True
Exit Sub
End Sub


问:
h2o deeplearning checkpoint model
Folks,

I have some problem when try resuming h2o deep learning in R from a checkpointed model with validation frame provided. It says "Validation dataset must be the same as for the check pointed model", which I believe I do have the same validation datasets. If I leave validation_frame blank, checkpointing model works fine. I attach my code below:

```<code>localh2o <- h2o.init(nthreads = -1)
train_image.hex <- read.csv("mnist_train.csv",header=FALSE)
train_image.hex[,785] <- factor(train_image.hex[,785])
train_image.hex <- as.h2o(train_image.hex)
test_image.hex <- read.csv("mnist_test.csv",header=FALSE)
test_image.hex[,785] <- factor(test_image.hex[,785])
test_image.hex <- as.h2o(test_image.hex)

mnist_model <- h2o.deeplearning(x=1:784, y = 785,
training_frame= train_image.hex,
validation_frame = test_image.hex,
activation = "RectifierWithDropout", hidden = c(500,1000),
input_dropout_ratio = 0.2,
hidden_dropout_ratios = c(0.5,0.5), adaptive_rate=TRUE,
rho=0.98, epsilon = 1e-7,
l1 = 1e-8, l2 = 1e-7, max_w2 = 10,
epochs = 10, export_weights_and_biases = TRUE,
variable_importances = FALSE
)
h2o.saveModel(mnist_model, path="/tmp",force=TRUE)
</code>```

Then I shut down the h2o, quit R and restart h2o in R to resume training, where h2o errors out:

```<code>localh2o <- h2o.init(nthreads = -1)
train_image.hex <- read.csv("mnist_train.csv",header=FALSE)
train_image.hex[,785] <- factor(train_image.hex[,785])
train_image.hex <- as.h2o(train_image.hex)
test_image.hex <- read.csv("mnist_test.csv",header=FALSE)
test_image.hex[,785] <- factor(test_image.hex[,785])
test_image.hex <- as.h2o(test_image.hex)
startmodel <- h2o.loadModel("/tmp/DeepLearning_model_R_1443812402059_20", localh2o)

mnist_model <- h2o.deeplearning(x=1:784, y = 785,
checkpoint = startmodel@model_id,
training_frame= train_image.hex,
validation_frame = test_image.hex,
activation = "RectifierWithDropout", hidden = c(500,1000),
input_dropout_ratio = 0.2,
hidden_dropout_ratios = c(0.5,0.5), adaptive_rate=TRUE,
rho=0.98, epsilon = 1e-7,
l1 = 1e-8, l2 = 1e-7, max_w2 = 10,
epochs = 10, export_weights_and_biases = TRUE,
variable_importances = FALSE
)
</code>```

答: Please try again using the latest version. This should work now.</p>

Title: h2o deeplearning checkpoint model

Body:
Folks,

I have some problem when try resuming h2o deep learning in R from a checkpointed model with validation frame provided. It says "Validation dataset must be the same as for the check pointed model", which I believe I do have the same validation datasets. If I leave validation_frame blank, checkpointing model works fine. I attach my code below:

localh2o <- h2o.init(nthreads = -1)
train_image.hex <- read.csv("mnist_train.csv",header=FALSE)
train_image.hex[,785] <- factor(train_image.hex[,785])
train_image.hex <- as.h2o(train_image.hex)
test_image.hex <- read.csv("mnist_test.csv",header=FALSE)
test_image.hex[,785] <- factor(test_image.hex[,785])
test_image.hex <- as.h2o(test_image.hex)

mnist_model <- h2o.deeplearning(x=1:784, y = 785,
training_frame= train_image.hex,
validation_frame = test_image.hex,
activation = "RectifierWithDropout", hidden = c(500,1000),
input_dropout_ratio = 0.2,
hidden_dropout_ratios = c(0.5,0.5), adaptive_rate=TRUE,
rho=0.98, epsilon = 1e-7,
l1 = 1e-8, l2 = 1e-7, max_w2 = 10,
epochs = 10, export_weights_and_biases = TRUE,
variable_importances = FALSE
)
h2o.saveModel(mnist_model, path="/tmp",force=TRUE)

Then I shut down the h2o, quit R and restart h2o in R to resume training, where h2o errors out:

localh2o <- h2o.init(nthreads = -1)
train_image.hex <- read.csv("mnist_train.csv",header=FALSE)
train_image.hex[,785] <- factor(train_image.hex[,785])
train_image.hex <- as.h2o(train_image.hex)
test_image.hex <- read.csv("mnist_test.csv",header=FALSE)
test_image.hex[,785] <- factor(test_image.hex[,785])
test_image.hex <- as.h2o(test_image.hex)
startmodel <- h2o.loadModel("/tmp/DeepLearning_model_R_1443812402059_20", localh2o)

mnist_model <- h2o.deeplearning(x=1:784, y = 785,
checkpoint = startmodel@model_id,
training_frame= train_image.hex,
validation_frame = test_image.hex,
activation = "RectifierWithDropout", hidden = c(500,1000),
input_dropout_ratio = 0.2,
hidden_dropout_ratios = c(0.5,0.5), adaptive_rate=TRUE,
rho=0.98, epsilon = 1e-7,
l1 = 1e-8, l2 = 1e-7, max_w2 = 10,
epochs = 10, export_weights_and_biases = TRUE,
variable_importances = FALSE
)


问:
Property Sheet (.prop) : how to refactor its filename and not break VS project?
If I rename a property sheet, the text of the property sheet will be changed.

However, the filename of property sheet will not be changed.

How to make the filename change along with the text automatically?

Example

First, I create foo worksheet.

It will be saved as foo.props.

After that, I think foo is not a suitable name, so I rename foo to bar in the project manager :-

(left to right)

However, foo.props-file will still be there, not renamed into bar.props automatically :-

Thus, when I want to add bar to any configuration, my eyes have to search for foo.props in system folder.  (Actually, I should search for bar.props.)

This is error-prone.

The inconsistency makes me nervous.

My workaround

Whenever I rename it, I have to delete the old foo.props in Window Explorer manually, then save the bar worksheet as a new bar.props manually.

However, others work-sheet reference in my projects will be broken.

I will have to add bar.props to all related configuration of all related project again, otherwise the project will be invalid (unloadable) : can't find foo.props.

Question

Are there any better workflow?  What is it?

答:
Rename it in file explorer.
Edit it in Notepad++.
Edit the vcxproj files that use it in Notepad++

I've never had a property sheet as part of my solution in solution explorer.
I've also never had a solution that was more than 45 projects where find and replace didn't work well in notepad++.


问:
Implement ResultCallback to MainActivity from GeofenceTransitionsIntentService
I am new to android development and am trying to learn about geofences.  I believe I have my intent service working properly where I am able to register my geofence and in theory receive transitions to the service; however, I am interested in taking the data from the intent service and sending it back to MainActivity.class so that it can be utilized to perform some tasks.  I see lots of examples where a notification is created, but I don't want a notification but instead to simply pass the type of transition and the triggering geofence back to the MainActivity class.

My GeofenceTransitionsIntentService.class is below which is where I assume I will need to implement some way to send a result back to the main class and I am assuming the main class will require some sort of listener to receive these results as they post.

```<code>public class GeofenceTransitionsIntentService extends IntentService implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
    private GoogleApiClient myGoogleApiClient;

public GeofenceTransitionsIntentService(){
    super(GeofenceTransitionsIntentService.class.getSimpleName());
}

@Override
public void onCreate(){
    super.onCreate();
    myGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
}

@Override
protected void onHandleIntent(Intent intent) {
    GeofencingEvent geoFenceEvent = GeofencingEvent.fromIntent(intent);
    if (geoFenceEvent.hasError()){
        int errorcode = geoFenceEvent.getErrorCode();
        Log.e("GeofencingApp", "ERROR: " + errorcode);
    } else {
        int transitionType = geoFenceEvent.getGeofenceTransition();

        if (Geofence.GEOFENCE_TRANSITION_ENTER == transitionType){
            myGoogleApiClient.blockingConnect(100, TimeUnit.MILLISECONDS);
            String triggeredGeofenceID = geoFenceEvent.getTriggeringGeofences().get(0).getRequestId();

        } else if (Geofence.GEOFENCE_TRANSITION_EXIT == transitionType) {
            myGoogleApiClient.blockingConnect(100, TimeUnit.MILLISECONDS);
            String triggeredGeofenceID = geoFenceEvent.getTriggeringGeofences().get(0).getRequestId();
            Toast.makeText(getApplicationContext(), "EXIT: " + triggeredGeofenceID, Toast.LENGTH_LONG).show();
        }
    }
}

@Override
public void onConnected(@Nullable Bundle bundle) {

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}
}
</code>```

答:
I figured out how to complete the task successfully and simply.

The code that I already had for the GeofenceTransitionService is good and the code for MainActivity is good.

In the MainActivity add a variable to the class as follows:

```<code>private static MainActivity ins;
</code>```

and then create two functions within the MainActivity class:

```<code>public static MainActivity getInstance(){
    return ins;
}

public void updateMethod(){
    MainActivity.this.runOnUiThread(new Runnable() {
        public void run(){
            //Do what you want to do on the MainActivity here
        }
    });
}
</code>```

What this does is provide a public method for the GeofenceTransitionService to call and get the MainActivity returned to it and then execute whatever method you want to on the MainActivity.  If you did not have the runOnUiThread in place you will get an error at runtime that says you are not allowed to interact with the view from a different thread.

Although not shown here, you can easily add information from the GeofenceTransitionsIntentService and pass to the MainActivity by placing the variables in the updateMethod...  For example:

```<code>public void updateMethod(final Boolean didEnter){
    // insert the above code here to run on the UI thread
}
</code>```

Further you can easily create multiple methods that perform various tasks that are all accessible from the intent service.

On the intent service side, the code is also simple:

```<code>MainActivity.getInstance().updateMethod([pass stuff here]);
</code>```

I hope this helps folks to make some more robust geofence apps.  I noticed that almost all samples focus on sending notifications and there is so much more that can be done.

Body:
I am new to android development and am trying to learn about geofences.  I believe I have my intent service working properly where I am able to register my geofence and in theory receive transitions to the service; however, I am interested in taking the data from the intent service and sending it back to MainActivity.class so that it can be utilized to perform some tasks.  I see lots of examples where a notification is created, but I don't want a notification but instead to simply pass the type of transition and the triggering geofence back to the MainActivity class.

My GeofenceTransitionsIntentService.class is below which is where I assume I will need to implement some way to send a result back to the main class and I am assuming the main class will require some sort of listener to receive these results as they post.

public class GeofenceTransitionsIntentService extends IntentService implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
    private GoogleApiClient myGoogleApiClient;

public GeofenceTransitionsIntentService(){
    super(GeofenceTransitionsIntentService.class.getSimpleName());
}

@Override
public void onCreate(){
    super.onCreate();
    myGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
}

@Override
protected void onHandleIntent(Intent intent) {
    GeofencingEvent geoFenceEvent = GeofencingEvent.fromIntent(intent);
    if (geoFenceEvent.hasError()){
        int errorcode = geoFenceEvent.getErrorCode();
        Log.e("GeofencingApp", "ERROR: " + errorcode);
    } else {
        int transitionType = geoFenceEvent.getGeofenceTransition();

        if (Geofence.GEOFENCE_TRANSITION_ENTER == transitionType){
            myGoogleApiClient.blockingConnect(100, TimeUnit.MILLISECONDS);
            String triggeredGeofenceID = geoFenceEvent.getTriggeringGeofences().get(0).getRequestId();

        } else if (Geofence.GEOFENCE_TRANSITION_EXIT == transitionType) {
            myGoogleApiClient.blockingConnect(100, TimeUnit.MILLISECONDS);
            String triggeredGeofenceID = geoFenceEvent.getTriggeringGeofences().get(0).getRequestId();
            Toast.makeText(getApplicationContext(), "EXIT: " + triggeredGeofenceID, Toast.LENGTH_LONG).show();
        }
    }
}

@Override
public void onConnected(@Nullable Bundle bundle) {

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}
}

Body:
I figured out how to complete the task successfully and simply.

The code that I already had for the GeofenceTransitionService is good and the code for MainActivity is good.

In the MainActivity add a variable to the class as follows:

private static MainActivity ins;

and then create two functions within the MainActivity class:

public static MainActivity getInstance(){
    return ins;
}

public void updateMethod(){
    MainActivity.this.runOnUiThread(new Runnable() {
        public void run(){
            //Do what you want to do on the MainActivity here
        }
    });
}

What this does is provide a public method for the GeofenceTransitionService to call and get the MainActivity returned to it and then execute whatever method you want to on the MainActivity.  If you did not have the runOnUiThread in place you will get an error at runtime that says you are not allowed to interact with the view from a different thread.

Although not shown here, you can easily add information from the GeofenceTransitionsIntentService and pass to the MainActivity by placing the variables in the updateMethod...  For example:

public void updateMethod(final Boolean didEnter){
    // insert the above code here to run on the UI thread
}

Further you can easily create multiple methods that perform various tasks that are all accessible from the intent service.

On the intent service side, the code is also simple:

MainActivity.getInstance().updateMethod([pass stuff here]);

I hope this helps folks to make some more robust geofence apps.  I noticed that almost all samples focus on sending notifications and there is so much more that can be done.


问:
How to subset a pandas dataframe on value_counts?
I have the following pandas dataframe

```<code>import pandas as pd
df = pd.read_csv("filename1.csv")

df
    column1  column2   column3
0        10       A          1
1        15       A          1
2        19       B          1
3      5071       B          0
4      5891       B          0
5      3210       B          0
6        12       B          2
7        13       C          2
8        20       C          0
9         5       C          3
10        9       C          3
</code>```

Now, using the function value_counts() will give me the counts of each value in a certain column, e.g.

```<code>df.column3.value_counts()

1   3
2   2
3   2
</code>```

However, I would like to subset a pandas dataframe based on the number of values in a given column. For example, in the above dataframe df, I would like to subset on rows with 3 or more unique values (excluding 0). In this case, the resulting dataframe would be

```<code>df
    column1  column2   column3
0        10       A          1
1        15       A          1
2        19       B          1
</code>```

As the rows for values 2 and 3 only had two rows, i.e. 2, 3 only occurred twice in column3. What is the pandas way to do this?

答:
You can use groupby.filter; In the filter, construct a unique boolean value for each group to filter the data frame:

```<code>df.groupby("column3").filter(lambda g: (g.name != 0) and (g.column3.size >= 3))
</code>```

Another option could be:

```<code>df[(df.column3 != 0) & (df.groupby("column3").column3.transform("size") >= 3)]
</code>```

Body:
I have the following pandas dataframe

import pandas as pd
df = pd.read_csv("filename1.csv")

df
    column1  column2   column3
0        10       A          1
1        15       A          1
2        19       B          1
3      5071       B          0
4      5891       B          0
5      3210       B          0
6        12       B          2
7        13       C          2
8        20       C          0
9         5       C          3
10        9       C          3

Now, using the function value_counts() will give me the counts of each value in a certain column, e.g.

df.column3.value_counts()

1   3
2   2
3   2

However, I would like to subset a pandas dataframe based on the number of values in a given column. For example, in the above dataframe df, I would like to subset on rows with 3 or more unique values (excluding 0). In this case, the resulting dataframe would be

df
    column1  column2   column3
0        10       A          1
1        15       A          1
2        19       B          1

As the rows for values 2 and 3 only had two rows, i.e. 2, 3 only occurred twice in column3. What is the pandas way to do this?

Body:
You can use groupby.filter; In the filter, construct a unique boolean value for each group to filter the data frame:

df.groupby("column3").filter(lambda g: (g.name != 0) and (g.column3.size >= 3))

Another option could be:

df[(df.column3 != 0) & (df.groupby("column3").column3.transform("size") >= 3)]


问:
What is the purpose and duration of this cookie __utmli used by Google Analytics?
We are researching on the Cookies rendered by GA on our website which are generated on user's machine.

I found the description of almost all cookies from https://developers.google.com/analytics/devguides/collection/analyticsjs/cookie-usage

But one cookie in specific is not menitioned anywhere. "__utmli".

Could anyone here please provide some information like description/purpose and duration of this cookie?

Thanks,
Praful Memane

答:
This cookie along with some more are used by GA to provide a better user experience and website performance. It is not essential for Analytics to work but it is nice to be there. You can read some more information on the matter on the links below.

Cookiepedia

Europa.eu

and  nordicisic


问:
Removing range of items from a list
Is there a way to remove items in a range in list? For example: a = [1,2,3,4,5]. How to remove items from 3 to 5?

答:
Yes, you can use a list comprehension to filter the data.</p>

```<code>a = [1,2,3,4,5]
print([x for x in a if 3 <= x <= 5])
</code>```

Title: Removing range of items from a list

Body:
Yes, you can use a list comprehension to filter the data.

a = [1,2,3,4,5]
print([x for x in a if 3 <= x <= 5])


问:
How to Parse a Single Dictionary from Firebase Snapshot?
My code is:

```<code>_ = DataService.ds.REF_POSTS.child(key!).observe(.value, with: { (snapshot) in

                })
</code>```

the key is equal to a post key(-Kef2J6vJBCjHGYjSlkI). I want to retrieve only one element at a time.

There is only 1 dictionary under that child:

I need to create a dictionary out of the contents of this. However, when I implement regular algorithm:

```<code>_ = DataService.ds.REF_POSTS.child(key!).observe(.value, with: { (snapshot) in

if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
                for snap in snapshot {
                    print("Zhenya: here is the snap: \(snap)")
                    if let postDict = snap.value as? Dictionary<String, AnyObject> {
                        let key = snap.key
                        let post = Post(postKey: key, postData: postDict)
                        self.posts.append(post)
                    } else {
                        print("Zhenya: failed to convert")
                    }
                }
            }
                })
</code>```

The 'snap' prints elements of the dictionary itself, not the whole dictionary. So it always fails the conversion on the following line.

Bonus for ninjas:

If you can suggest a better architecture, I would appreciate that.
It seems that retrieving posts from FB one by one will slow down performance considerably.

The reason it is 'one by one' is this one post is the result of user's GeoFire specification. Geofire returns keys to posts that are nearby.
I want to filter Firebase's main branch of posts based on those returned keys, but there is no way to do that - only load one by one (.orderByChild - doesn't returns posts, but instead, orders all the posts. If you you know how it can help me, please advice)

答:
This is the code provided in your question:

```<code>_ = DataService.ds.REF_POSTS.child(key!).observe(.value, with: { (snapshot) in

if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
        for snap in snapshot {
            print("Zhenya: here is the snap: \(snap)")
            if let postDict = snap.value as? Dictionary<String, AnyObject> {
                let key = snap.key
                let post = Post(postKey: key, postData: postDict)
                self.posts.append(post)
            } else {
                print("Zhenya: failed to convert")
            }
        }
    }
})
</code>```

Let's take a look at what's happening here.

The first line is observing posts/$post-id in Firebase using the .value method.  The .value method returns the reference you provide in a FIRDataSnapshot, where snapshot.key is the name of the child and snapshot.value is a dictionary containing its children.

So, snapshot in DataService.ds.REF_POSTS.child(key!).observe(.value, with: { (snapshot) in ... }) should look like this:

```<code>$post-id
    imageUrl: http://...
    likes: 0
    userKey: ...
</code>```

But on the very next line you redefine snapshot using a local definition. That is why you are getting the children of the post, because you explicitly define it that way:

```<code>if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] { ... }
</code>```

If you remove this, you should see the behavior you want.

So what should you really be doing? Well I don't like using .value because it has a few drawbacks:

It downloads the entire node requested. If you mess up your reference for a large node (i.e, ref/users), it's easy for a .value operation to take several seconds before you see any data.

It is only called once. This is fine if your database is static, but whose database is static?

This is why I prefer using .childAdded for things like posts, messages, etc. It returns a single node at a time, which means you can populate a list progressively as new data becomes available. Using a few clever UI functions (such as tableView.insertRows(...) you can fairly smoothly display large lists of data without waiting for results. I believe it also supports paging, where you get them in batches of 10, for example. Here is a quick primer on how you can begin using .childAdded to make the most of large lists of data.

Body:
My code is:

_ = DataService.ds.REF_POSTS.child(key!).observe(.value, with: { (snapshot) in

                })

the key is equal to a post key(-Kef2J6vJBCjHGYjSlkI). I want to retrieve only one element at a time.

There is only 1 dictionary under that child:

I need to create a dictionary out of the contents of this. However, when I implement regular algorithm:

_ = DataService.ds.REF_POSTS.child(key!).observe(.value, with: { (snapshot) in

if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
                for snap in snapshot {
                    print("Zhenya: here is the snap: \(snap)")
                    if let postDict = snap.value as? Dictionary<String, AnyObject> {
                        let key = snap.key
                        let post = Post(postKey: key, postData: postDict)
                        self.posts.append(post)
                    } else {
                        print("Zhenya: failed to convert")
                    }
                }
            }
                })

The 'snap' prints elements of the dictionary itself, not the whole dictionary. So it always fails the conversion on the following line.

Bonus for ninjas:

If you can suggest a better architecture, I would appreciate that.
It seems that retrieving posts from FB one by one will slow down performance considerably.

The reason it is 'one by one' is this one post is the result of user's GeoFire specification. Geofire returns keys to posts that are nearby.
I want to filter Firebase's main branch of posts based on those returned keys, but there is no way to do that - only load one by one (.orderByChild - doesn't returns posts, but instead, orders all the posts. If you you know how it can help me, please advice)

Body:
This is the code provided in your question:

_ = DataService.ds.REF_POSTS.child(key!).observe(.value, with: { (snapshot) in

if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
        for snap in snapshot {
            print("Zhenya: here is the snap: \(snap)")
            if let postDict = snap.value as? Dictionary<String, AnyObject> {
                let key = snap.key
                let post = Post(postKey: key, postData: postDict)
                self.posts.append(post)
            } else {
                print("Zhenya: failed to convert")
            }
        }
    }
})

Let's take a look at what's happening here.

The first line is observing posts/$post-id in Firebase using the .value method.  The .value method returns the reference you provide in a FIRDataSnapshot, where snapshot.key is the name of the child and snapshot.value is a dictionary containing its children.

So, snapshot in DataService.ds.REF_POSTS.child(key!).observe(.value, with: { (snapshot) in ... }) should look like this:

$post-id
    imageUrl: http://...
    likes: 0
    userKey: ...

But on the very next line you redefine snapshot using a local definition. That is why you are getting the children of the post, because you explicitly define it that way:

if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] { ... }

If you remove this, you should see the behavior you want.

So what should you really be doing? Well I don't like using .value because it has a few drawbacks:

It downloads the entire node requested. If you mess up your reference for a large node (i.e, ref/users), it's easy for a .value operation to take several seconds before you see any data.

It is only called once. This is fine if your database is static, but whose database is static?

This is why I prefer using .childAdded for things like posts, messages, etc. It returns a single node at a time, which means you can populate a list progressively as new data becomes available. Using a few clever UI functions (such as tableView.insertRows(...) you can fairly smoothly display large lists of data without waiting for results. I believe it also supports paging, where you get them in batches of 10, for example. Here is a quick primer on how you can begin using .childAdded to make the most of large lists of data.


问:
No module named setuptools
I want to install setup file of twilio. When I install it through given command it is given me an error:

No module named setuptools.

Could you please let me know what should I do?

I am using python 2.7

```<code>Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Python27>python D:\test\twilio-twilio-python-26f6707\setup.py install
Traceback (most recent call last):
  File "D:\test\twilio-twilio-python-26f6707\setup.py", line 2, in <module>
    from setuptools import setup, find_packages
ImportError: No module named setuptools
</code>```

答:
For ubuntu users, this error may arise because setuptool is not installed system-wide. Simply install setuptool using the command:

```<code>sudo apt-get install -y python-setuptools
</code>```

For python3:

```<code>sudo apt-get install -y python3-setuptools
</code>```

After that, install your package again normally, using

```<code>sudo python setup.py install
</code>```

That's all.

Title: No module named setuptools

Body:
I want to install setup file of twilio. When I install it through given command it is given me an error:

No module named setuptools.

Could you please let me know what should I do?

I am using python 2.7

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Python27>python D:\test\twilio-twilio-python-26f6707\setup.py install
Traceback (most recent call last):
  File "D:\test\twilio-twilio-python-26f6707\setup.py", line 2, in <module>
    from setuptools import setup, find_packages
ImportError: No module named setuptools

Body:
For ubuntu users, this error may arise because setuptool is not installed system-wide. Simply install setuptool using the command:

sudo apt-get install -y python-setuptools

For python3:

sudo apt-get install -y python3-setuptools

After that, install your package again normally, using

sudo python setup.py install

That's all.


问:
JS onunload event won't always work
I want to count how much time visitors spend on a certain page and store it in my MySQL DB.

I thought of just starting a timer on window.onload like this:

```<code>window.onload= startCount;
window.onunload= sendCount;

var b=0;
var y;
function startCount() {
    document.getElementById('livecount').innerHTML=b;
    b=b+1;
    y=setTimeout("startCount()",1000);
}
</code>```

and after the visitor leaves the page (window.onunload), I'm sending the time through an XMLHttpRequest to a PHP file, which will store it in my DB:

```<code>function sendCount() {
    clearTimeout(y);
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","count.php?q="+b,true);
xmlhttp.send();
}
</code>```

The problem is it doesn't always work. I would say it works like 3 out of 10 times I try it.
Could it be that there is not enough time left for the PHP and SQL to be completely executed?

答: You could set up a timer as suggested which runs as often as you want (ever few seconds or so), and store the information in a cookie (or cookies).  You can send this information to the server if needed when you want to do something more than displaying the value to the user.  So don't send it to the server every cycle, just send it to the server when you want to do something with that information (like display to the user a list of all the time he spent on various pages on your site).</p>

Title: JS onunload event won't always work

Body:
I want to count how much time visitors spend on a certain page and store it in my MySQL DB.

I thought of just starting a timer on window.onload like this:

window.onload= startCount;
window.onunload= sendCount;

var b=0;
var y;
function startCount() {
    document.getElementById('livecount').innerHTML=b;
    b=b+1;
    y=setTimeout("startCount()",1000);
}

and after the visitor leaves the page (window.onunload), I'm sending the time through an XMLHttpRequest to a PHP file, which will store it in my DB:

function sendCount() {
    clearTimeout(y);
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","count.php?q="+b,true);
xmlhttp.send();
}

The problem is it doesn't always work. I would say it works like 3 out of 10 times I try it.
Could it be that there is not enough time left for the PHP and SQL to be completely executed?


问:
CSS: How to account for the lost space when converting item from static to fixed/absolute
Here's my jsfiddle: https://jsfiddle.net/vd2vstoy/1/

HTML:

```<code><div class="content">
    <div class="top-banner">
        <h1>
            Some<body> Once Told Me
        </h1>
    </div>
    <div class="fixedElement">
        the <i>HelloWorld</i> is gonna roll me
    </div>
    <h1>
        I ain't the C-sharp-est tool<br>
        In the shed.
    </h1>
</div>
</code>```

CSS:

```<code>.content {
    height:1000px;
}
.top-banner  {
    background-color:yellow;
    height:200px;
}
.fixedElement {
    background-color: #c0c0c0;
    padding:15px;
    position:static;
    top:0;
    width:100%;
    z-index:100;
}
</code>```

Javascript:

```<code>$(window).scroll(function(e){
    var $el = $('.fixedElement');
    var isPositionFixed = ($el.css('position') == 'fixed');

    if ($(this).scrollTop() > 220 && !isPositionFixed) {
        $('.fixedElement').css({'position': 'fixed', 'top': '0px'});
    }
    if ($(this).scrollTop() < 220 && isPositionFixed) {
        $('.fixedElement').css({'position': 'static', 'top': '0px'});
    }
});
</code>```

The point of this is so that the fixedElement sticks to the top when it reached that 200 pixel mark. Unfortunately, the space that the fixedElement was taking up goes away when it turns fixed position.

Is there anyway that I can preserve the space that was there so that as soon as the element becomes fixed, the rest of the content doesn't shift up and become unseen?

To see what's happening, just scroll down in the example jsfiddle and see what happens when the fixedElement div reaches the top of the screen.

答:
Here is an updated version of your fiddle with the fix.

I wrapped your fixed element in a parent wrapper, then on fixed, set the height of the parent, changing

```<code>if ($(this).scrollTop() > 220 && !isPositionFixed) {
    $('.fixedElement').css({'position': 'fixed', 'top': '0px'});
}
</code>```

to

```<code>if ($(this).scrollTop() > 220 && !isPositionFixed) {
    $('.fixedElement').parent().height($('.fixedElement').outerHeight(true))
    $('.fixedElement').css({'position': 'fixed', 'top': '0px'});
}
</code>```

Body:
Here's my jsfiddle: https://jsfiddle.net/vd2vstoy/1/

HTML:

            Some Once Told Me

        the HelloWorld is gonna roll me

        I ain't the C-sharp-est tool

        In the shed.

CSS:

.content {
    height:1000px;
}
.top-banner  {
    background-color:yellow;
    height:200px;
}
.fixedElement {
    background-color: #c0c0c0;
    padding:15px;
    position:static;
    top:0;
    width:100%;
    z-index:100;
}

Javascript:

$(window).scroll(function(e){
    var $el = $('.fixedElement');
    var isPositionFixed = ($el.css('position') == 'fixed');

    if ($(this).scrollTop() > 220 && !isPositionFixed) {
        $('.fixedElement').css({'position': 'fixed', 'top': '0px'});
    }
    if ($(this).scrollTop() < 220 && isPositionFixed) {
        $('.fixedElement').css({'position': 'static', 'top': '0px'});
    }
});

The point of this is so that the fixedElement sticks to the top when it reached that 200 pixel mark. Unfortunately, the space that the fixedElement was taking up goes away when it turns fixed position.

Is there anyway that I can preserve the space that was there so that as soon as the element becomes fixed, the rest of the content doesn't shift up and become unseen?

To see what's happening, just scroll down in the example jsfiddle and see what happens when the fixedElement div reaches the top of the screen.

Body:
Here is an updated version of your fiddle with the fix.

I wrapped your fixed element in a parent wrapper, then on fixed, set the height of the parent, changing

if ($(this).scrollTop() > 220 && !isPositionFixed) {
    $('.fixedElement').css({'position': 'fixed', 'top': '0px'});
}

to

if ($(this).scrollTop() > 220 && !isPositionFixed) {
    $('.fixedElement').parent().height($('.fixedElement').outerHeight(true))
    $('.fixedElement').css({'position': 'fixed', 'top': '0px'});
}


问:
How do I change onclick attributes in javascript?
I have HTML that displays a button and a paragraph. When you click on the paragraph, it indicates whether the paragraph has been clicked on an odd or even amount of times. I'm trying to get the button to expand the paragraph to include a count of how many times the paragraph has been clicked, and revert back to it's original text when the button is clicked again. For some reason, I don't think my button properly communicates with the paragraph. Here's my code:

```<code> var doClickCount = false;
 var clickCounter = 0
 function toggleParagraphCounter(event) {
     var clickMeEvenTimes = true;
     doClickCount = true;
     if (doClickCount === true) {
        function clickMe() {
      var para1 = document.getElementById("para1");
      if (clickMeEvenTimes) {
        clickCounter += 1;
        para1.style = "color:green";
        para1.innerHTML = "Click this paragraph." +
        " It has been clicked an odd number of times.\
        Clicked" + clickCounter + "times with counting enabled." ;
      }
      else {
        clickCounter += 1;
        para1.style = "font-size:0.9em";
        para1.innerHTML = "Click this paragraph." +
        " It has been clicked an even number of times.\
        Clicked" + clickCounter + "times with counting enabled.";
      }
      clickMeEvenTimes = !clickMeEvenTimes;
  }
 }  else {
    function clickMe() {
      var para1 = document.getElementById("para1");
      if (clickMeEvenTimes) {
        para1.style = "color:green";
        para1.innerHTML = "Click this paragraph." +
        " It has been clicked an odd number of times.";
      }
      else {
        para1.style = "font-size:0.9em";
        para1.innerHTML = "Click this paragraph." +
        " It has been clicked an even number of times.";
      }
      clickMeEvenTimes = !clickMeEvenTimes;
  }
 }

 }
</code>```

What else could I do to try and solve this?

答:
You are declaring the clickMe function twice, below I have reformatted your code.

```<code> var doClickCount = false;
 var clickCounter = 0
 function toggleParagraphCounter(event) {

 var clickMeEvenTimes = true;
 doClickCount = true;

 if (doClickCount === true) {

 }  else {

 }
}
function clickMe() {
  var para1 = document.getElementById("para1");
  if (clickMeEvenTimes) {
    para1.style = "color:green";
    para1.innerHTML = "Click this paragraph." +
    " It has been clicked an odd number of times.";
  }
  else {
    para1.style = "font-size:0.9em";
    para1.innerHTML = "Click this paragraph." +
    " It has been clicked an even number of times.";
  }
  clickMeEvenTimes = !clickMeEvenTimes;
}
function clickMe() {
  var para1 = document.getElementById("para1");
  if (clickMeEvenTimes) {
    clickCounter += 1;
    para1.style = "color:green";
    para1.innerHTML = "Click this paragraph." +
    " It has been clicked an odd number of times.\
    Clicked" + clickCounter + "times with counting enabled." ;
  }
  else {
    clickCounter += 1;
    para1.style = "font-size:0.9em";
    para1.innerHTML = "Click this paragraph." +
    " It has been clicked an even number of times.\
    Clicked" + clickCounter + "times with counting enabled.";
  }
  clickMeEvenTimes = !clickMeEvenTimes;
</code>```

}

Body:
I have HTML that displays a button and a paragraph. When you click on the paragraph, it indicates whether the paragraph has been clicked on an odd or even amount of times. I'm trying to get the button to expand the paragraph to include a count of how many times the paragraph has been clicked, and revert back to it's original text when the button is clicked again. For some reason, I don't think my button properly communicates with the paragraph. Here's my code:

 var doClickCount = false;
 var clickCounter = 0
 function toggleParagraphCounter(event) {
     var clickMeEvenTimes = true;
     doClickCount = true;
     if (doClickCount === true) {
        function clickMe() {
      var para1 = document.getElementById("para1");
      if (clickMeEvenTimes) {
        clickCounter += 1;
        para1.style = "color:green";
        para1.innerHTML = "Click this paragraph." +
        " It has been clicked an odd number of times.\
        Clicked" + clickCounter + "times with counting enabled." ;
      }
      else {
        clickCounter += 1;
        para1.style = "font-size:0.9em";
        para1.innerHTML = "Click this paragraph." +
        " It has been clicked an even number of times.\
        Clicked" + clickCounter + "times with counting enabled.";
      }
      clickMeEvenTimes = !clickMeEvenTimes;
  }
 }  else {
    function clickMe() {
      var para1 = document.getElementById("para1");
      if (clickMeEvenTimes) {
        para1.style = "color:green";
        para1.innerHTML = "Click this paragraph." +
        " It has been clicked an odd number of times.";
      }
      else {
        para1.style = "font-size:0.9em";
        para1.innerHTML = "Click this paragraph." +
        " It has been clicked an even number of times.";
      }
      clickMeEvenTimes = !clickMeEvenTimes;
  }
 }

 }

What else could I do to try and solve this?

Body:
You are declaring the clickMe function twice, below I have reformatted your code.

 var doClickCount = false;
 var clickCounter = 0
 function toggleParagraphCounter(event) {

 var clickMeEvenTimes = true;
 doClickCount = true;

 if (doClickCount === true) {

 }  else {

 }
}
function clickMe() {
  var para1 = document.getElementById("para1");
  if (clickMeEvenTimes) {
    para1.style = "color:green";
    para1.innerHTML = "Click this paragraph." +
    " It has been clicked an odd number of times.";
  }
  else {
    para1.style = "font-size:0.9em";
    para1.innerHTML = "Click this paragraph." +
    " It has been clicked an even number of times.";
  }
  clickMeEvenTimes = !clickMeEvenTimes;
}
function clickMe() {
  var para1 = document.getElementById("para1");
  if (clickMeEvenTimes) {
    clickCounter += 1;
    para1.style = "color:green";
    para1.innerHTML = "Click this paragraph." +
    " It has been clicked an odd number of times.\
    Clicked" + clickCounter + "times with counting enabled." ;
  }
  else {
    clickCounter += 1;
    para1.style = "font-size:0.9em";
    para1.innerHTML = "Click this paragraph." +
    " It has been clicked an even number of times.\
    Clicked" + clickCounter + "times with counting enabled.";
  }
  clickMeEvenTimes = !clickMeEvenTimes;

}


问:
How can I run Tensorboard on a remote server?
I'm new to Tensorflow and would greatly benefit from some visualizations of what I'm doing. I understand that Tensorboard is a useful visualization tool, but how do I run it on my remote Ubuntu machine?</p>

答:
Another option if you can't get it working for some reason is to simply mount a logdir directory on your filesystem with sshfs:

sshfs user@host:/home/user/project/summary_logs ~/summary_logs

and then run Tensorboard locally.


问:
How would I make user be able to post and keep it on the site?
here is the code that I need help with

I want to be able to post text on this website and for it to stay

https://pastebin.com/JcnNkRKx

```<code><html>
  <head>
    <title>Negulos</title>
    <style>
      p {
        text-align: center;
        color: lime;
        font-size: 20px;
      }
      body {
        background-color: black;
        overflow-x: hidden;
      }
      input[type=text], select {
        boarder: none;
        background-color: black;
        color: lime;
        position: absolute;
        right: 550px;
      }
      div {
        border-radius: 5px;
        padding: 20px;
      }
    </style>
  </head>
  <body>
    <p>Welcome to Negulos the current time is</p><p id="t"></p>
    <p>Write anything you'd like to get off your chest</p>
    <div>
      <input type="text" id="user" value="Your text here">
    </div>
    <p onclick="post" onmouseover="colorOn(this)" onmouseout="colorOff(this)">post</p>
    <p id="post"></p>
    <script>
      function colorOn(x) {
        x.style.color = "red";
      }
      function colorOff(x) {
        x.style.color = "lime";
      }
    </script>
    <script>
      function post() {
        var x = document.getElementById("user").value;
        document.getElementById("post").innerHTML = x;
      }
    </script>
    <script>
      document.getElementById("t").innerHTML = Date();
    </script>
    <?php

?>
  </body>
</html>
</code>```

答:
Since you've already tagged the question jQuery and PHP, the most common way would be to have some sort of api endpoint on the server, receiving the post requests, and using $.post() via jquery to send up the data. This could be triggered by event handlers, or any other method you choose.

The traditional way would be to create a html form, which automatically posts up the data:

```<code><form method="POST" action="/api.php">
    <input type="text" name="usertext" value="" />
    <input type="submit" value="Submit!" />
</form>
</code>```

Which, when the user submits the form, would make a post request to the server at /api.php.

If you only want to keep it temporarily, you could load the data into a cookie, or use localstorage.

Body:
here is the code that I need help with

I want to be able to post text on this website and for it to stay

https://pastebin.com/JcnNkRKx

    <title>Negulos</title>

Welcome to Negulos the current time is

Write anything you'd like to get off your chest

      <input type="text" id="user" value="Your text here">

post

    <?php

?>

Body:
Since you've already tagged the question jQuery and PHP, the most common way would be to have some sort of api endpoint on the server, receiving the post requests, and using $.post() via jquery to send up the data. This could be triggered by event handlers, or any other method you choose.

The traditional way would be to create a html form, which automatically posts up the data:

<form method="POST" action="/api.php">
    <input type="text" name="usertext" value="" />
    <input type="submit" value="Submit!" />
</form>

Which, when the user submits the form, would make a post request to the server at /api.php.

If you only want to keep it temporarily, you could load the data into a cookie, or use localstorage.


问:
Simple Java based Spark program doesn't get Finished
I created a very simple "Word count" Java based Spark program, and I am running it in a cluster running on YARN with the below details:

Hadoop details:

Master Node (NN, SNN, RM) - 192.168.0.100

Slave  Nodes (DN, NM) - 192.168.0.105, 192.168.0.108

Spark details:

Master running on : 192.168.0.100

Workers running on : 192.168.0.105, 192.168.0.108

I have created a client machine from where I submit the Spark job (The IP address of client machine is --> 192.168.0.240).

The below command I used to submit the Job to Spark:

```<code>spark-submit --class com.example.WordCountTask --master yarn /root/SparkCodeInJava/word-count/target/word-count-1.0-SNAPSHOT.jar /spark/input/inputText.txt /spark/output
</code>```

However the program doesn't terminate at all, the data-set is very small (10 text lines) and I expect it to finis without taking much time.

The below is the output I see on console after submitting the Job:

```<code>17/03/26 19:54:42 INFO yarn.Client: Application report for application_1490572543329_0001 (state: ACCEPTED)
17/03/26 19:54:43 INFO yarn.Client: Application report for application_1490572543329_0001 (state: ACCEPTED)
17/03/26 19:54:44 INFO yarn.Client: Application report for application_1490572543329_0001 (state: ACCEPTED)
17/03/26 19:54:45 INFO yarn.Client: Application report for application_1490572543329_0001 (state: ACCEPTED)
17/03/26 19:54:46 INFO yarn.Client: Application report for application_1490572543329_0001 (state: ACCEPTED)
</code>```

And this continues forever. I am not sure why this isn't getting completed.

This is what I see in GUI for this application:

The below is the output of: yarn logs -applicationId application_1490572543329_0002

```<code>17/03/26 20:24:09 WARN util.NativeCodeLoader: Unable to load native-hadoop libra
/tmp/logs/root/logs/application_1490572543329_0002 does not exist.
</code>```

Log aggregation has not completed or is not enabled.

This is my first Spark program, and I configured to run it on YARN cluster.

I simulate the distributed environment using 4 VM's , Cent OS running on Virtualbox.

Can anyone help me why this program isn't functioning properly?

Update:

I set up the environment in AWS , with two launched instance with good configuration (8 Vcpu's and 32 GB RAM), but the job isn't still getting completed.

(A) yarn-site.xml

```<code>    <property>
            <name>yarn.nodemanager.auxservices</name>
            <value>mapreduce_shuffle</value>
    </property>

    <property>
            <name>yarn.resourcemanager.address</name>
            <value>ip-XXX-YYYY-ZZZ-AAA.us-west-2.compute.internal:8032</value>
    </property>
</code>```

(B) After submitting the Job using spark-submit, I see this in the output which is displayed on console:

```<code>17/03/29 15:51:35 INFO yarn.Client: Requesting a new application from cluster with **0 NodeManagers**
</code>```

Has this to do anything with the Job not getting finished?

答:
From the ERROR messages,

YARN Application State: ACCEPTED, waiting for AM container to be
  allocated

```<code>17/03/29 15:51:35 INFO yarn.Client: Requesting a new application from cluster with **0 NodeManagers**
</code>```

YARN is unable to allocate containers for the Spark application as there are no active NodeManager(s) available.

Nodemanagers use the property yarn.resourcemanager.resource-tracker.address to communicate with ResourceManager.
By default, the value of this property is set as

```<code><property>
   <name>yarn.resourcemanager.resource-tracker.address</name>
   <value>${yarn.resourcemanager.hostname}:8031</value>
</property>
</code>```

The reference property yarn.resourcemanager.hostname defaults to 0.0.0.0. Nodemanagers will not be able to communicate with the RM unless the RM hostname is defined properly.

Modify this property in yarn-site.xml for all the nodes

```<code> <property>
   <name>yarn.resourcemanager.hostname</name>
   <value>rm_hostname</value> <!-- Hostname of the node where Resource Manager is started -->
</property>
</code>```

Also, the property yarn.nodemanager.auxservices must be yarn.nodemanager.aux-services.

Restart the services after the changes.

Body:
I created a very simple "Word count" Java based Spark program, and I am running it in a cluster running on YARN with the below details:

Hadoop details:

Master Node (NN, SNN, RM) - 192.168.0.100

Slave  Nodes (DN, NM) - 192.168.0.105, 192.168.0.108

Spark details:

Master running on : 192.168.0.100

Workers running on : 192.168.0.105, 192.168.0.108

I have created a client machine from where I submit the Spark job (The IP address of client machine is --> 192.168.0.240).

The below command I used to submit the Job to Spark:

spark-submit --class com.example.WordCountTask --master yarn /root/SparkCodeInJava/word-count/target/word-count-1.0-SNAPSHOT.jar /spark/input/inputText.txt /spark/output

However the program doesn't terminate at all, the data-set is very small (10 text lines) and I expect it to finis without taking much time.

The below is the output I see on console after submitting the Job:

17/03/26 19:54:42 INFO yarn.Client: Application report for application_1490572543329_0001 (state: ACCEPTED)
17/03/26 19:54:43 INFO yarn.Client: Application report for application_1490572543329_0001 (state: ACCEPTED)
17/03/26 19:54:44 INFO yarn.Client: Application report for application_1490572543329_0001 (state: ACCEPTED)
17/03/26 19:54:45 INFO yarn.Client: Application report for application_1490572543329_0001 (state: ACCEPTED)
17/03/26 19:54:46 INFO yarn.Client: Application report for application_1490572543329_0001 (state: ACCEPTED)

And this continues forever. I am not sure why this isn't getting completed.

This is what I see in GUI for this application:

The below is the output of: yarn logs -applicationId application_1490572543329_0002

17/03/26 20:24:09 WARN util.NativeCodeLoader: Unable to load native-hadoop libra
/tmp/logs/root/logs/application_1490572543329_0002 does not exist.

Log aggregation has not completed or is not enabled.

This is my first Spark program, and I configured to run it on YARN cluster.

I simulate the distributed environment using 4 VM's , Cent OS running on Virtualbox.

Can anyone help me why this program isn't functioning properly?

Update:

I set up the environment in AWS , with two launched instance with good configuration (8 Vcpu's and 32 GB RAM), but the job isn't still getting completed.

(A) yarn-site.xml

    <property>
            <name>yarn.nodemanager.auxservices</name>
            <value>mapreduce_shuffle</value>
    </property>

    <property>
            <name>yarn.resourcemanager.address</name>
            <value>ip-XXX-YYYY-ZZZ-AAA.us-west-2.compute.internal:8032</value>
    </property>

(B) After submitting the Job using spark-submit, I see this in the output which is displayed on console:

17/03/29 15:51:35 INFO yarn.Client: Requesting a new application from cluster with **0 NodeManagers**

Has this to do anything with the Job not getting finished?

Body:
From the ERROR messages,

YARN Application State: ACCEPTED, waiting for AM container to be
  allocated

17/03/29 15:51:35 INFO yarn.Client: Requesting a new application from cluster with **0 NodeManagers**

YARN is unable to allocate containers for the Spark application as there are no active NodeManager(s) available.

Nodemanagers use the property yarn.resourcemanager.resource-tracker.address to communicate with ResourceManager.
By default, the value of this property is set as

<property>
   <name>yarn.resourcemanager.resource-tracker.address</name>
   <value>${yarn.resourcemanager.hostname}:8031</value>
</property>

The reference property yarn.resourcemanager.hostname defaults to 0.0.0.0. Nodemanagers will not be able to communicate with the RM unless the RM hostname is defined properly.

Modify this property in yarn-site.xml for all the nodes

 <property>
   <name>yarn.resourcemanager.hostname</name>
   <value>rm_hostname</value> <!-- Hostname of the node where Resource Manager is started -->
</property>

Also, the property yarn.nodemanager.auxservices must be yarn.nodemanager.aux-services.

Restart the services after the changes.


问:
Should I await a 'async Task' function if I don't care its return value?
Do I need to await a async Task function if it doesn't return anything? Will that cause the following code be wrapped in a delegate and executed after the async Task function returns?

```<code>Task DoSomethingAsync()
{
    return Task.Run(() =>
    {
        // Do something, but doesn't return values.
    });
}

void Test()
{
    DoSomethingAsync();  // should I await?

    // Do other things, totally not related to the async function
    Console.WriteLine("aaa");
}
</code>```

In above example, if I await DoSomethingAsync() in Test(), will that cause the following code Console.WriteLine be wrapped in delegate and defer executed only when the async task is done?

答:
Do I need to await a async Task function if it doesn't return anything?

Generally, yes. Not only does this allow you to detect when it completes, it also allows you to respond to any errors. You can, if you wish, store the Task object and await it later.

Not awaiting the task is "fire and forget", which literally means:

You don't care whether it completes.

You don't care when it completes.

You don't care whether it is successful or fails.

It's very rare to have a true fire-and-forget scenario.

Will that cause the following code be wrapped in a delegate and executed after the async Task function returns?

After the Task returned by the async function completes, yes.

Body:
Do I need to await a async Task function if it doesn't return anything? Will that cause the following code be wrapped in a delegate and executed after the async Task function returns?

Task DoSomethingAsync()
{
    return Task.Run(() =>
    {
        // Do something, but doesn't return values.
    });
}

void Test()
{
    DoSomethingAsync();  // should I await?

    // Do other things, totally not related to the async function
    Console.WriteLine("aaa");
}

In above example, if I await DoSomethingAsync() in Test(), will that cause the following code Console.WriteLine be wrapped in delegate and defer executed only when the async task is done?


答:
Something like this should do the trick

```<code>[z for z in [1,2,3,4,5,6,7] if not 3<=z<=5]

Out[2]:
[1, 2, 6, 7]
</code>```

If you want to make it more flexible can replace with variables depending on your needs which is simply done:

```<code>alist=[1,2,3,4,5,6,7]
lowerbound=3
upperbound=5
resultlist=[z for z in alist if not lowerbound<=z<=upperbound]
#result you want stored as 'resultlist'
</code>```

Title: Removing range of items from a list

Body: Is there a way to remove items in a range in list? For example: a = [1,2,3,4,5]. How to remove items from 3 to 5?

Body:
Something like this should do the trick

[z for z in [1,2,3,4,5,6,7] if not 3<=z<=5]

Out[2]:
[1, 2, 6, 7]

If you want to make it more flexible can replace with variables depending on your needs which is simply done:

alist=[1,2,3,4,5,6,7]
lowerbound=3
upperbound=5
resultlist=[z for z in alist if not lowerbound<=z<=upperbound]
#result you want stored as 'resultlist'


问:
How to write the following objective function in Gurobi?
The following is the objective function:

I have the following Java code:

```<code>// Create list of variables
List<GRBVar> varList = new ArrayList<>();

// Set objective: maximize log(p) * x
GRBLinExpr expr = new GRBLinExpr();

int counter = 0;

for(Map.Entry<String, Double[]> entry: probabilityLevels.entrySet()) {

    Double[] probs = entry.getValue();

    for (Double prob: probs) {
        GRBVar x = model.addVar(0.0, 1.0, 0.0, GRB.BINARY, "x" + counter);
        expr.addTerm(Math.log(prob), x);
        varList.add(x);
    }
}

model.setObjective(expr, GRB.MAXIMIZE);
</code>```

Update the code

答: Your loops look correct, but you are only creating one GRBVar x, instead of creating one GRBVar for each combination of j, k and z.  You should create some data structure to store all these GRBVar objects, and create them as you iterate over the combinations of j, k and z.</p>

Body:
The following is the objective function:

I have the following Java code:

// Create list of variables
List<GRBVar> varList = new ArrayList<>();

// Set objective: maximize log(p) * x
GRBLinExpr expr = new GRBLinExpr();

int counter = 0;

for(Map.Entry<String, Double[]> entry: probabilityLevels.entrySet()) {

    Double[] probs = entry.getValue();

    for (Double prob: probs) {
        GRBVar x = model.addVar(0.0, 1.0, 0.0, GRB.BINARY, "x" + counter);
        expr.addTerm(Math.log(prob), x);
        varList.add(x);
    }
}

model.setObjective(expr, GRB.MAXIMIZE);

Update the code