问:
Angular 2 upgrade to rc 5 - unmet peer dependencies
I need to upgrade my angular to rc5 to use NgModule.

I have followed directions from Angular 2.

I have updated my package.json dependencies to this and then ran npm stall in the terminal:

```<code>  "dependencies": {
    "@angular/common": "^2.0.0-rc.5",
    "@angular/compiler": "^2.0.0-rc.5",
    "@angular/core": "^2.0.0-rc.5",
    "@angular/forms": "0.3.0",
    "@angular/http": "2.0.0-rc.5",
    "@angular/platform-browser": "^2.0.0-rc.5",
    "@angular/platform-browser-dynamic": "^2.0.0-rc.5",
    "@angular/router": "3.0.0-beta.1",
    "@angular/router-deprecated": "2.0.0-rc.2",
    "@angular/upgrade": "2.0.0-rc.5",
    "angular2-google-maps": "^0.12.0",
    "angular2-in-memory-web-api": "0.0.14",
    "bootstrap": "^3.3.6",
    "core-js": "^2.4.0",
    "jquery": "v3.1.0",
    "ng2-select": "^1.0.3",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.6",
    "systemjs": "0.19.27",
    "zone.js": "^0.6.12"
  },
</code>```

terminal results:

```<code>Benjamins-MacBook-Pro:the-vegan-repository Ben$ npm install

> the-vegan-repository@1.0.0 postinstall /Users/Ben/Development/the-vegan-repository
> typings install

typings WARN deprecated 7/26/2016: "registry:dt/core-js#0.0.0+20160602141332" is deprecated (updated, replaced or removed)
typings WARN deprecated 8/7/2016: "registry:dt/node#6.0.0+20160621231320" is deprecated (updated, replaced or removed)

├── core-js (global)
├── jasmine (global)
└── node (global)

npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/common@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/compiler@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/core@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/platform-browser@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/platform-browser-dynamic@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of es6-shim@^0.35.0 but none was installed.
npm WARN EPEERINVALID angular2-in-memory-web-api@0.0.14 requires a peer of @angular/core@2.0.0-rc.4 but none was installed.
npm WARN EPEERINVALID angular2-in-memory-web-api@0.0.14 requires a peer of @angular/http@2.0.0-rc.4 but none was installed.
npm WARN EPACKAGEJSON the-vegan-repository@1.0.0 No repository field.
</code>```

I have tried the other option suggested by Angular 2:

```<code>npm install @angular/{core,common,compiler,platform-browser,platform-browser-dynamic} --save
</code>```

results:

```<code>Benjamins-MacBook-Pro:the-vegan-repository Ben$ npm install @angular/{core,common,compiler,platform-browser,platform-browser-dynamic} --save
the-vegan-repository@1.0.0 /Users/Ben/Development/the-vegan-repository
├── UNMET PEER DEPENDENCY @angular/common@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/compiler@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/core@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/http@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/platform-browser@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/platform-browser-dynamic@2.0.0-rc.5
└── UNMET PEER DEPENDENCY es6-shim@^0.35.0

npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/common@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/compiler@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/core@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/platform-browser@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/platform-browser-dynamic@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of es6-shim@^0.35.0 but none was installed.
npm WARN EPEERINVALID angular2-in-memory-web-api@0.0.14 requires a peer of @angular/core@2.0.0-rc.4 but none was installed.
npm WARN EPEERINVALID angular2-in-memory-web-api@0.0.14 requires a peer of @angular/http@2.0.0-rc.4 but none was installed.
npm WARN EPACKAGEJSON the-vegan-repository@1.0.0 No repository field.
npm ERR! code 1
</code>```

No matter what I do to upgrade, I get the same unmet peer dependencies errors.

To fix that I have tried:

npm install @angular

result:

```<code>Benjamins-MacBook-Pro:the-vegan-repository Ben$ npm install @angular
npm ERR! addLocal Could not install /Users/Ben/Development/the-vegan-repository/@angular
npm ERR! Darwin 15.6.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "@angular"
npm ERR! node v5.3.0
npm ERR! npm  v3.3.12
npm ERR! path /Users/Ben/Development/the-vegan-repository/@angular
npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall open

npm ERR! enoent ENOENT: no such file or directory, open '/Users/Ben/Development/the-vegan-repository/@angular'
npm ERR! enoent This is most likely not a problem with npm itself
npm ERR! enoent and is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/Ben/Development/the-vegan-repository/npm-debug.log
</code>```

npm install @angular/common

result:

```<code>Benjamins-MacBook-Pro:the-vegan-repository Ben$ npm install @angular/common
the-vegan-repository@1.0.0 /Users/Ben/Development/the-vegan-repository
├── UNMET PEER DEPENDENCY @angular/common@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/compiler@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/core@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/http@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/platform-browser@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/platform-browser-dynamic@2.0.0-rc.5
└── UNMET PEER DEPENDENCY es6-shim@^0.35.0

npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/common@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/compiler@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/core@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/platform-browser@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/platform-browser-dynamic@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of es6-shim@^0.35.0 but none was installed.
npm WARN EPEERINVALID angular2-in-memory-web-api@0.0.14 requires a peer of @angular/core@2.0.0-rc.4 but none was installed.
npm WARN EPEERINVALID angular2-in-memory-web-api@0.0.14 requires a peer of @angular/http@2.0.0-rc.4 but none was installed.
npm WARN EPACKAGEJSON the-vegan-repository@1.0.0 No repository field.
npm ERR! code 1
</code>```

npm install @angular/common@2.0.0-rc.5

result:

```<code>Benjamins-MacBook-Pro:the-vegan-repository Ben$ npm install @angular/common@2.0.0-rc.5
the-vegan-repository@1.0.0 /Users/Ben/Development/the-vegan-repository
├── UNMET PEER DEPENDENCY @angular/common@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/compiler@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/core@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/http@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/platform-browser@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/platform-browser-dynamic@2.0.0-rc.5
└── UNMET PEER DEPENDENCY es6-shim@^0.35.0

npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/common@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/compiler@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/core@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/platform-browser@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/platform-browser-dynamic@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of es6-shim@^0.35.0 but none was installed.
npm WARN EPEERINVALID angular2-in-memory-web-api@0.0.14 requires a peer of @angular/core@2.0.0-rc.4 but none was installed.
npm WARN EPEERINVALID angular2-in-memory-web-api@0.0.14 requires a peer of @angular/http@2.0.0-rc.4 but none was installed.
npm WARN EPACKAGEJSON the-vegan-repository@1.0.0 No repository field.
npm ERR! code 1
</code>```

Note that this is a working angular 2 app so I do seem to have angular 2 installed. How do I meet my peer dependencies so that I can upgrade to angular2 rc5?

答:
Here is the same issue which I was also facing-

I just update npm-

```<code>sudo npm install npm -g
</code>```

My issue got resolved !!!

Body:
I need to upgrade my angular to rc5 to use NgModule.

I have followed directions from Angular 2.

I have updated my package.json dependencies to this and then ran npm stall in the terminal:

  "dependencies": {
    "@angular/common": "^2.0.0-rc.5",
    "@angular/compiler": "^2.0.0-rc.5",
    "@angular/core": "^2.0.0-rc.5",
    "@angular/forms": "0.3.0",
    "@angular/http": "2.0.0-rc.5",
    "@angular/platform-browser": "^2.0.0-rc.5",
    "@angular/platform-browser-dynamic": "^2.0.0-rc.5",
    "@angular/router": "3.0.0-beta.1",
    "@angular/router-deprecated": "2.0.0-rc.2",
    "@angular/upgrade": "2.0.0-rc.5",
    "angular2-google-maps": "^0.12.0",
    "angular2-in-memory-web-api": "0.0.14",
    "bootstrap": "^3.3.6",
    "core-js": "^2.4.0",
    "jquery": "v3.1.0",
    "ng2-select": "^1.0.3",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.6",
    "systemjs": "0.19.27",
    "zone.js": "^0.6.12"
  },

terminal results:

Benjamins-MacBook-Pro:the-vegan-repository Ben$ npm install

> the-vegan-repository@1.0.0 postinstall /Users/Ben/Development/the-vegan-repository
> typings install

typings WARN deprecated 7/26/2016: "registry:dt/core-js#0.0.0+20160602141332" is deprecated (updated, replaced or removed)
typings WARN deprecated 8/7/2016: "registry:dt/node#6.0.0+20160621231320" is deprecated (updated, replaced or removed)

├── core-js (global)
├── jasmine (global)
└── node (global)

npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/common@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/compiler@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/core@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/platform-browser@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/platform-browser-dynamic@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of es6-shim@^0.35.0 but none was installed.
npm WARN EPEERINVALID angular2-in-memory-web-api@0.0.14 requires a peer of @angular/core@2.0.0-rc.4 but none was installed.
npm WARN EPEERINVALID angular2-in-memory-web-api@0.0.14 requires a peer of @angular/http@2.0.0-rc.4 but none was installed.
npm WARN EPACKAGEJSON the-vegan-repository@1.0.0 No repository field.

I have tried the other option suggested by Angular 2:

npm install @angular/{core,common,compiler,platform-browser,platform-browser-dynamic} --save

results:

Benjamins-MacBook-Pro:the-vegan-repository Ben$ npm install @angular/{core,common,compiler,platform-browser,platform-browser-dynamic} --save
the-vegan-repository@1.0.0 /Users/Ben/Development/the-vegan-repository
├── UNMET PEER DEPENDENCY @angular/common@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/compiler@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/core@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/http@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/platform-browser@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/platform-browser-dynamic@2.0.0-rc.5
└── UNMET PEER DEPENDENCY es6-shim@^0.35.0

npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/common@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/compiler@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/core@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/platform-browser@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/platform-browser-dynamic@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of es6-shim@^0.35.0 but none was installed.
npm WARN EPEERINVALID angular2-in-memory-web-api@0.0.14 requires a peer of @angular/core@2.0.0-rc.4 but none was installed.
npm WARN EPEERINVALID angular2-in-memory-web-api@0.0.14 requires a peer of @angular/http@2.0.0-rc.4 but none was installed.
npm WARN EPACKAGEJSON the-vegan-repository@1.0.0 No repository field.
npm ERR! code 1

No matter what I do to upgrade, I get the same unmet peer dependencies errors.

To fix that I have tried:

npm install @angular

result:

Benjamins-MacBook-Pro:the-vegan-repository Ben$ npm install @angular
npm ERR! addLocal Could not install /Users/Ben/Development/the-vegan-repository/@angular
npm ERR! Darwin 15.6.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "@angular"
npm ERR! node v5.3.0
npm ERR! npm  v3.3.12
npm ERR! path /Users/Ben/Development/the-vegan-repository/@angular
npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall open

npm ERR! enoent ENOENT: no such file or directory, open '/Users/Ben/Development/the-vegan-repository/@angular'
npm ERR! enoent This is most likely not a problem with npm itself
npm ERR! enoent and is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/Ben/Development/the-vegan-repository/npm-debug.log

npm install @angular/common

result:

Benjamins-MacBook-Pro:the-vegan-repository Ben$ npm install @angular/common
the-vegan-repository@1.0.0 /Users/Ben/Development/the-vegan-repository
├── UNMET PEER DEPENDENCY @angular/common@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/compiler@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/core@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/http@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/platform-browser@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/platform-browser-dynamic@2.0.0-rc.5
└── UNMET PEER DEPENDENCY es6-shim@^0.35.0

npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/common@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/compiler@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/core@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/platform-browser@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/platform-browser-dynamic@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of es6-shim@^0.35.0 but none was installed.
npm WARN EPEERINVALID angular2-in-memory-web-api@0.0.14 requires a peer of @angular/core@2.0.0-rc.4 but none was installed.
npm WARN EPEERINVALID angular2-in-memory-web-api@0.0.14 requires a peer of @angular/http@2.0.0-rc.4 but none was installed.
npm WARN EPACKAGEJSON the-vegan-repository@1.0.0 No repository field.
npm ERR! code 1

npm install @angular/common@2.0.0-rc.5

result:

Benjamins-MacBook-Pro:the-vegan-repository Ben$ npm install @angular/common@2.0.0-rc.5
the-vegan-repository@1.0.0 /Users/Ben/Development/the-vegan-repository
├── UNMET PEER DEPENDENCY @angular/common@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/compiler@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/core@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/http@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/platform-browser@2.0.0-rc.5
├── UNMET PEER DEPENDENCY @angular/platform-browser-dynamic@2.0.0-rc.5
└── UNMET PEER DEPENDENCY es6-shim@^0.35.0

npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/common@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/compiler@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/core@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/platform-browser@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of @angular/platform-browser-dynamic@2.0.0-rc.2 but none was installed.
npm WARN EPEERINVALID angular2-google-maps@0.12.0 requires a peer of es6-shim@^0.35.0 but none was installed.
npm WARN EPEERINVALID angular2-in-memory-web-api@0.0.14 requires a peer of @angular/core@2.0.0-rc.4 but none was installed.
npm WARN EPEERINVALID angular2-in-memory-web-api@0.0.14 requires a peer of @angular/http@2.0.0-rc.4 but none was installed.
npm WARN EPACKAGEJSON the-vegan-repository@1.0.0 No repository field.
npm ERR! code 1

Note that this is a working angular 2 app so I do seem to have angular 2 installed. How do I meet my peer dependencies so that I can upgrade to angular2 rc5?

Body:
Here is the same issue which I was also facing-

I just update npm-

sudo npm install npm -g

My issue got resolved !!!


来源: stackexchange

问:
Updating a variable inside stream in Java 8
I'm just playing around with Java 8.
For now I'm trying to understand stream.
So far I haven't seen an example about looping through a map or list then populating a variable that is not part of the map or list.

Here is an example:

```<code>class RandomObject {
    private int i1;
    private String s1;
    //setter
    //getter
}

// Java 7
RandomObject randomObj = new RandomObject();
Map<Integer, String> mappy = new HashMap<Integer, String>();
Map<Integer, String> collect = new HashMap<Integer, String>();

mappy.put(1, "good map");
mappy.put(2, "nice map");
mappy.put(3, "wow");
mappy.put(4, "mappy the best map");

for (Map.Entry<Integer, String> entry : mappy.entrySet()) {
    if (entry.getKey() == 2) {
        randomObj.seti1(entry.getKey());
        randomObj.sets1(entry.getValue());
        collect.put(entry.getKey(), entry.getValue());
    }
}

// Java 8
RandomObject randomObj = new RandomObject();
Map<Integer, String> mappy = new HashMap<Integer, String>();

mappy.put(1, "good map");
mappy.put(2, "nice map");
mappy.put(3, "wow");
mappy.put(4, "mappy the best map");

Map<Integer, String> collect = mappy.entrySet().stream()
    .filter(map -> map.getKey() == 2)
    .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
// Hmmm i don't know where to put randomObj
</code>```

答:
Functional programming depends on immutability.

You aren't updating the stream; you're operating on the one you have to create a new one using operations like map, reduce, filter etc.

ContentLicense: CC BY-SA 3.0

Body:
I'm just playing around with Java 8.
For now I'm trying to understand stream.
So far I haven't seen an example about looping through a map or list then populating a variable that is not part of the map or list.

Here is an example:

class RandomObject {
    private int i1;
    private String s1;
    //setter
    //getter
}

// Java 7
RandomObject randomObj = new RandomObject();
Map<Integer, String> mappy = new HashMap<Integer, String>();
Map<Integer, String> collect = new HashMap<Integer, String>();

mappy.put(1, "good map");
mappy.put(2, "nice map");
mappy.put(3, "wow");
mappy.put(4, "mappy the best map");

for (Map.Entry<Integer, String> entry : mappy.entrySet()) {
    if (entry.getKey() == 2) {
        randomObj.seti1(entry.getKey());
        randomObj.sets1(entry.getValue());
        collect.put(entry.getKey(), entry.getValue());
    }
}

// Java 8
RandomObject randomObj = new RandomObject();
Map<Integer, String> mappy = new HashMap<Integer, String>();

mappy.put(1, "good map");
mappy.put(2, "nice map");
mappy.put(3, "wow");
mappy.put(4, "mappy the best map");

Map<Integer, String> collect = mappy.entrySet().stream()
    .filter(map -> map.getKey() == 2)
    .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
// Hmmm i don't know where to put randomObj


问:
How to pull strings out of JSON object
Here is the code

```<code>$jsonString = urldecode($json);
$jsonString = str_replace("\\", "", $jsonString);
$data = JSON_decode($jsonString);
mysql_select_db($database) or die('Cannot connect to database.');
print_r($data);
</code>```

output:

```<code>  stdClass Object ( [myObject] => Array ( [0] => stdClass Object ( [fullname] => abc [role] => ADMIN [username] => xyz ) ) )
</code>```

my question how can i pull individual values and insert them into the database
 fullname, role and username

答:
to get fullname:

```<code>$fullname = $data['myObject'][0]['fullname'];
</code>```

Same for role/ADMIN

Which you can add to your SQL string to insert into your database.

For an example of an insert into mysql see: http://www.w3schools.com/PHP/php_mysql_insert.asp

ContentLicense: CC BY-SA 2.5

Title: How to pull strings out of JSON object

Body:
Here is the code

$jsonString = urldecode($json);
$jsonString = str_replace("\\", "", $jsonString);
$data = JSON_decode($jsonString);
mysql_select_db($database) or die('Cannot connect to database.');
print_r($data);

output:

  stdClass Object ( [myObject] => Array ( [0] => stdClass Object ( [fullname] => abc [role] => ADMIN [username] => xyz ) ) )

my question how can i pull individual values and insert them into the database
 fullname, role and username

Body:
to get fullname:

$fullname = $data['myObject'][0]['fullname'];

Same for role/ADMIN

Which you can add to your SQL string to insert into your database.

For an example of an insert into mysql see: http://www.w3schools.com/PHP/php_mysql_insert.asp


问:
Using variables inside a DSC composite resource
I am fairly new to PowerShell DSC to the answer to this may be blindingly obvious but I cannot find a similar problem described anywhere.

I have a PowerShell DSC composite resource which downloads some MSIs and runs them. The directory that the file is downloaded to is referenced in several places so I am trying to store it in a variable. However, when I come to apply the configuration which uses this resource using Start-DscConfiguration the values always appear to be null.

Here is an example of the resource:

```<code>Configuration xExample {

  Import-Module -ModuleName 'PSDesiredStateConfiguration'

  $path = 'C:\Temp\Installer.msi'

  Script Download {
    SetScript = {
      Invoke-WebRequest -Uri "..." -OutFile $path
    }
    GetScript = {
      @{
        Result = $(Test-Path $path)
      }
    }
    TestScript = {
      Write-Verbose "Testing $($path)"
      Test-Path $path
    }
  }
}
</code>```

When this resource is being executed the the verbose output shows "Testing " and the call to Test-Path fails due to the Path parameter being null.

I have tried declaring the $path variable outside of the configuration and using $global to no avail.

What am I missing?

答:
DSC stores scripts as strings in the compiled mof-files. Standard variables are not expanded as it wouldn't know which to expand and which to keep as part of the script.

However, you can use the using-scope to access variables outside the script. During mof-compilation, the code that defines the variable is added to the beginning of each scriptblock for Test-/Set-/GetScript.

If you need to use variables from your configuration script in the
  GetScript, TestScript, or SetScript script blocks, use the $using:
  Scope

Source: DSC Script Resources @ MSDN

Example:

```<code>Configuration xExample {

  Import-DscResource -ModuleName 'PSDesiredStateConfiguration'

  #Can also be set outside of Configuration-scriptblock
  $path = 'C:\Temp\Installer2.msi'

  Script Download {
    SetScript = {
      Invoke-WebRequest -Uri "..." -OutFile $using:path
    }

    GetScript = {
      @{
        Result = $(Test-Path "$using:path")
      }
    }

    TestScript = {
      Write-Verbose "Testing $using:path"
      Test-Path "$using:path"
    }
  }
}
</code>```

localhost.mof (scriptresource-part):

```<code>instance of MSFT_ScriptResource as $MSFT_ScriptResource1ref
{
ResourceID = "[Script]Download";
 GetScript = "$path ='C:\\Temp\\Installer2.msi'\n\n      @{ \n        Result = $(Test-Path \"$path\")\n      }\n    ";
 TestScript = "$path ='C:\\Temp\\Installer2.msi'\n\n      Write-Verbose \"Testing $path\"\n      Test-Path \"$path\"\n    ";
 SourceInfo = "::7::3::Script";
 SetScript = "$path ='C:\\Temp\\Installer2.msi'\n \n      Invoke-WebRequest -Uri \"...\" -OutFile $path\n    ";
 ModuleName = "PSDesiredStateConfiguration";

ModuleVersion = "1.0";

 ConfigurationName = "xExample";

};
</code>```

Source: MSDN

Body:
I am fairly new to PowerShell DSC to the answer to this may be blindingly obvious but I cannot find a similar problem described anywhere.

I have a PowerShell DSC composite resource which downloads some MSIs and runs them. The directory that the file is downloaded to is referenced in several places so I am trying to store it in a variable. However, when I come to apply the configuration which uses this resource using Start-DscConfiguration the values always appear to be null.

Here is an example of the resource:

Configuration xExample {

  Import-Module -ModuleName 'PSDesiredStateConfiguration'

  $path = 'C:\Temp\Installer.msi'

  Script Download {
    SetScript = {
      Invoke-WebRequest -Uri "..." -OutFile $path
    }
    GetScript = {
      @{
        Result = $(Test-Path $path)
      }
    }
    TestScript = {
      Write-Verbose "Testing $($path)"
      Test-Path $path
    }
  }
}

When this resource is being executed the the verbose output shows "Testing " and the call to Test-Path fails due to the Path parameter being null.

I have tried declaring the $path variable outside of the configuration and using $global to no avail.

What am I missing?

Body:
DSC stores scripts as strings in the compiled mof-files. Standard variables are not expanded as it wouldn't know which to expand and which to keep as part of the script.

However, you can use the using-scope to access variables outside the script. During mof-compilation, the code that defines the variable is added to the beginning of each scriptblock for Test-/Set-/GetScript.

If you need to use variables from your configuration script in the
  GetScript, TestScript, or SetScript script blocks, use the $using:
  Scope

Source: DSC Script Resources @ MSDN

Example:

Configuration xExample {

  Import-DscResource -ModuleName 'PSDesiredStateConfiguration'

  #Can also be set outside of Configuration-scriptblock
  $path = 'C:\Temp\Installer2.msi'

  Script Download {
    SetScript = {
      Invoke-WebRequest -Uri "..." -OutFile $using:path
    }

    GetScript = {
      @{
        Result = $(Test-Path "$using:path")
      }
    }

    TestScript = {
      Write-Verbose "Testing $using:path"
      Test-Path "$using:path"
    }
  }
}

localhost.mof (scriptresource-part):

instance of MSFT_ScriptResource as $MSFT_ScriptResource1ref
{
ResourceID = "[Script]Download";
 GetScript = "$path ='C:\\Temp\\Installer2.msi'\n\n      @{ \n        Result = $(Test-Path \"$path\")\n      }\n    ";
 TestScript = "$path ='C:\\Temp\\Installer2.msi'\n\n      Write-Verbose \"Testing $path\"\n      Test-Path \"$path\"\n    ";
 SourceInfo = "::7::3::Script";
 SetScript = "$path ='C:\\Temp\\Installer2.msi'\n \n      Invoke-WebRequest -Uri \"...\" -OutFile $path\n    ";
 ModuleName = "PSDesiredStateConfiguration";

ModuleVersion = "1.0";

 ConfigurationName = "xExample";

};

Source: MSDN


问:
How to install java on a server managed by Cpanel?
I am trying to get java installed on a server that I am running. I rented a server and domain from lithium hosting and I am trying to create a site on there that will be used to search files via solr. I am accessing the file system of the server through SSH on my Mac. I have install solr using wget and everything worked fine. However, I can not get java installed which is mandatory for solr to work. I have tried installed it using sudo, apt-get, yum and root@centos and all of those just return an error that those commands don't exist. I am able to download the appropriate tar.gz file using wget. but an error occurs whenever I try to run the command

```<code>tar xxx-xxx-xx.tar.gz
</code>```

I get the error:

```<code>gzip: stdin: not in gzip format
tar: Child returned status 1
tar: Error is not recoverable: exiting now
</code>```

The server is managed with a Cpanel account. How can I get java downloaded to the server. I need it for solr. Thanks

答:
Decompress the tar.gz with the command:

tar xzvf xxx-xxx-xx.tar.gz

Body:
I am trying to get java installed on a server that I am running. I rented a server and domain from lithium hosting and I am trying to create a site on there that will be used to search files via solr. I am accessing the file system of the server through SSH on my Mac. I have install solr using wget and everything worked fine. However, I can not get java installed which is mandatory for solr to work. I have tried installed it using sudo, apt-get, yum and root@centos and all of those just return an error that those commands don't exist. I am able to download the appropriate tar.gz file using wget. but an error occurs whenever I try to run the command

tar xxx-xxx-xx.tar.gz

I get the error:

gzip: stdin: not in gzip format
tar: Child returned status 1
tar: Error is not recoverable: exiting now

The server is managed with a Cpanel account. How can I get java downloaded to the server. I need it for solr. Thanks


问:
Object from NSUserDefaults releasing?
So I have a username saved in the UserDefaults.  For some reason, I am experiencing some strange behavior.

I have a data controller that goes and fetches some data from the server based on the user name.

```<code>NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSLog(@"NSUserDefaults dump: %@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);

userID = [prefs stringForKey:@"username"];
</code>```

This works fine for the first few times, but after I do some random stuff and go back to try and reload the views, it crashes.  It says:

```<code>-[CFString retain]: message sent to deallocated instance 0x4b18ff0
</code>```

This is strange because it is stopping on the NSLog line.  Has anyone seen this before or know why it may be happening??

答:
stringForKey returns an autorelease object which you aren't retaining, it's probably released as soon as that method finishes.

You need to retain that string either by doing so manually or using a property declaration with the retain setting.

And then you need to release it at some point (at least in dealloc)

Title: Object from NSUserDefaults releasing?

Body:
So I have a username saved in the UserDefaults.  For some reason, I am experiencing some strange behavior.

I have a data controller that goes and fetches some data from the server based on the user name.

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSLog(@"NSUserDefaults dump: %@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);

userID = [prefs stringForKey:@"username"];

This works fine for the first few times, but after I do some random stuff and go back to try and reload the views, it crashes.  It says:

-[CFString retain]: message sent to deallocated instance 0x4b18ff0

This is strange because it is stopping on the NSLog line.  Has anyone seen this before or know why it may be happening??


问:
How to add Locale to DecimalFormatter in android
I am trying this code I want apply Locale.US to below code How to do this?</p>

```<code>public String removeDecimalFormat(Double valueDouble) {
    DecimalFormat format = new DecimalFormat();
    format.setDecimalSeparatorAlwaysShown(false);
    format.setGroupingUsed(true);
    return format.format(valueDouble);
  }
</code>```

答:
DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. See here

You can try this,it will work :

```<code>public String removeDecimalFormat(Double valueDouble) {
        NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);//here you can add the locale
        DecimalFormat format = (DecimalFormat) numberFormat;
        format.setDecimalSeparatorAlwaysShown(false);
        format.setGroupingUsed(true);
        return format.format(valueDouble);
      }
</code>```

Body:
I am trying this code I want apply Locale.US to below code How to do this?

public String removeDecimalFormat(Double valueDouble) {
    DecimalFormat format = new DecimalFormat();
    format.setDecimalSeparatorAlwaysShown(false);
    format.setGroupingUsed(true);
    return format.format(valueDouble);
  }

Body:
DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. See here

You can try this,it will work :

public String removeDecimalFormat(Double valueDouble) {
        NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);//here you can add the locale
        DecimalFormat format = (DecimalFormat) numberFormat;
        format.setDecimalSeparatorAlwaysShown(false);
        format.setGroupingUsed(true);
        return format.format(valueDouble);
      }


问:
Rails STI query all subclasses using base class
Imagine I have this STI table called living things with these such subclasses:

```<code>class LivingThing < ActiveRecord::Base
end

class Animal < LivingThing
end

class Plant < LivingThing
end

class Fungus < LivingThing
end

class Cat < Animal
end

class Dog < Animal
end
</code>```

I am trying to get a very simple query of all records that INHERIT from subclass "Animal".
So I want records wher type= "Cat" or type= "Dog".  I don't know why I can't seem to figure this out.

none of these options work:

```<code>- animals = LivingThing.all.map{|r| r.kind_of?("Animal")}
- animals = LivingThing.all.map{|r| r.type == "Animal"}
- animals = LivingThing.kind_of?("Animal")
</code>```

currently LivingThing.all =

```<code> => #<ActiveRecord::Relation [#<Cat id: 2,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">, #<Dog id: 3,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">,#<Cat id: 4,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">, #<Cat id: 5,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">, #<Rose id: 6,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">, #<Oak id: 7,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">, #<Mushroom id: 6,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">, #<Ringworm id: 8,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">]>
</code>```

答:
As of rails 4.2 (maybe even before), doing:

Animal.all will automatically render an sql call something like:

SELECT * FROM "living_things" WHERE "living_things"."type" IN ('Animal', 'Dog', 'Cat')

So there you have it. :-)

Body:
Imagine I have this STI table called living things with these such subclasses:

class LivingThing < ActiveRecord::Base
end

class Animal < LivingThing
end

class Plant < LivingThing
end

class Fungus < LivingThing
end

class Cat < Animal
end

class Dog < Animal
end

I am trying to get a very simple query of all records that INHERIT from subclass "Animal".
So I want records wher type= "Cat" or type= "Dog".  I don't know why I can't seem to figure this out.

none of these options work:

- animals = LivingThing.all.map{|r| r.kind_of?("Animal")}
- animals = LivingThing.all.map{|r| r.type == "Animal"}
- animals = LivingThing.kind_of?("Animal")

currently LivingThing.all =

 => #<ActiveRecord::Relation [#<Cat id: 2,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">, #<Dog id: 3,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">,#<Cat id: 4,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">, #<Cat id: 5,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">, #<Rose id: 6,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">, #<Oak id: 7,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">, #<Mushroom id: 6,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">, #<Ringworm id: 8,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">]>


问:
Form backing bean is not retaining already set property values
i am using a form backing bean like this.

```<code>public class BeanData implements Serializable{

    private String param1;
    private String param2;
    private String param3;
    private String param4="india";

    getters setters
}
</code>```

then sending bean object in model as below-

```<code>@RequestMapping(value=/formPage, method={RequestMethod.GET,RequestMethod.POST})
    public ModelAndView getPage(HttpSession session, ModelAndView modelAndView) {

        BeanData formBean = new BeanData();
        formBean.setParam2("123456"); // this param2 doens't have any field in JSP
        modelAndView.addObject("formBean", formBean);
        modelAndView.setViewName(PAGE);

        return modelAndView;
    }
@RequestMapping(value=submitData, headers="Accept=*/*", method={RequestMethod.POST})
    public void submitData(@Valid @ModelAttribute("formBean") BeanData formBean, BindingResult result, HttpServletRequest request,HttpServletResponse response,ModelAndView modelAndView, HttpSession session) {

        LOGGER.info("param1:"+formBean.getParam1()); // Param1 has a path map in jsp field. So whatever user is puuting into form field, that is getting populated here
        LOGGER.info(" param2:"+formBean.getParam2()); // It has not been used in JSP. Though from controller it was populated before sending the bean to the jsp. but here the value is null . This is the concern
        LOGGER.info("param3:"+formBean.getParam3());// Param1 has a path map in jsp field. So whatever user is puuting into form field, that is getting populated here
        LOGGER.info("param4:"+formBean.getParam4());//thsi field also has not been used in JSP. But this property was set in bean instantiation. It is also getting retrieved successfully.

        modelAndView.setViewName(SUCCESS PAGE);

    }
</code>```

My concern is, i want to set one bean property using setter method and want to pass the bean backing object to JSP. Then all the property values should be bind(what i explicitly bind using form filed path attribute and what i have already set while created the bean object) to the backing object and it should get received in controller. Please guide me where i am doing wrong.

答:
The model attributes are request scoped beans. Solutions you could use:

Map your properties to hidden fields at your html form. I do not recommend that as they can be easily update at the client side.

Use session attributes instead of model attributes, and I think it is the last option.

What you really should do is delegate the creation of your form bean to a method annotated with @ModelAttribute instead of doing that in your getPage method.

Spring executes method annotated with @ModelAttribute before handling the requests and then will update the object with the properties coming from your form.

```<code>@ModelAttribute("formBean")
public BeanData setFormBeanModel()
{
  BeanData formBean = new BeanData();
  formBean.setParam2("123456");
  return formBean;
}

@RequestMapping(value=/formPage, method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView getPage(HttpSession session, ModelAndView modelAndView)
{
  modelAndView.setViewName(PAGE);

  return modelAndView;
}
</code>```

Body:
i am using a form backing bean like this.

public class BeanData implements Serializable{

    private String param1;
    private String param2;
    private String param3;
    private String param4="india";

    getters setters
}

then sending bean object in model as below-

@RequestMapping(value=/formPage, method={RequestMethod.GET,RequestMethod.POST})
    public ModelAndView getPage(HttpSession session, ModelAndView modelAndView) {

        BeanData formBean = new BeanData();
        formBean.setParam2("123456"); // this param2 doens't have any field in JSP
        modelAndView.addObject("formBean", formBean);
        modelAndView.setViewName(PAGE);

        return modelAndView;
    }
@RequestMapping(value=submitData, headers="Accept=*/*", method={RequestMethod.POST})
    public void submitData(@Valid @ModelAttribute("formBean") BeanData formBean, BindingResult result, HttpServletRequest request,HttpServletResponse response,ModelAndView modelAndView, HttpSession session) {

        LOGGER.info("param1:"+formBean.getParam1()); // Param1 has a path map in jsp field. So whatever user is puuting into form field, that is getting populated here
        LOGGER.info(" param2:"+formBean.getParam2()); // It has not been used in JSP. Though from controller it was populated before sending the bean to the jsp. but here the value is null . This is the concern
        LOGGER.info("param3:"+formBean.getParam3());// Param1 has a path map in jsp field. So whatever user is puuting into form field, that is getting populated here
        LOGGER.info("param4:"+formBean.getParam4());//thsi field also has not been used in JSP. But this property was set in bean instantiation. It is also getting retrieved successfully.

        modelAndView.setViewName(SUCCESS PAGE);

    }

My concern is, i want to set one bean property using setter method and want to pass the bean backing object to JSP. Then all the property values should be bind(what i explicitly bind using form filed path attribute and what i have already set while created the bean object) to the backing object and it should get received in controller. Please guide me where i am doing wrong.

Body:
The model attributes are request scoped beans. Solutions you could use:

Map your properties to hidden fields at your html form. I do not recommend that as they can be easily update at the client side.

Use session attributes instead of model attributes, and I think it is the last option.

What you really should do is delegate the creation of your form bean to a method annotated with @ModelAttribute instead of doing that in your getPage method.

Spring executes method annotated with @ModelAttribute before handling the requests and then will update the object with the properties coming from your form.

@ModelAttribute("formBean")
public BeanData setFormBeanModel()
{
  BeanData formBean = new BeanData();
  formBean.setParam2("123456");
  return formBean;
}

@RequestMapping(value=/formPage, method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView getPage(HttpSession session, ModelAndView modelAndView)
{
  modelAndView.setViewName(PAGE);

  return modelAndView;
}


问:
Map based cache with expiration and soft values
I'm looking to cache information in a Map so I don't have to keep, for example, hitting a DB. In Java I'd use Google collection's excellent MapMaker and set an expiry, to keep the cache as fresh as necessary, and softValues, to keep the memory usage down. Then I'd have a function that computes the value for a key that currently isn't cached.

```<code>MapMaker().softValues
          .expireAfterWrite(10, TimeUnit.MINUTES)
          .makeComputingMap(Function(...));
</code>```

What's the best way to do this in Scala?

答:
I'm keep using Guava cache solution in Scala as well :)

First of all, as noted in one of the comments, in newer versions of Guava Cache, MapMaker() is now deprecated and you should use CacheBuilder instead.

So now, in Scala it will look like the follow:

```<code>  lazy val cachedData = CacheBuilder.newBuilder()
    .expireAfterWrite(60, TimeUnit.MINUTES)
    .maximumSize(10)
    .build(
      new CacheLoader[Key, Data] {
        def load(key: Key): Data = {
          veryExpansiveDataCreation(key)
        }
      }
    )
</code>```

To read from it, you can use something like:

```<code>  def cachedData(ketToData: Key): Data = {
    try {
      return cachedData.get(ketToData)
    } catch {
      case ee: Exception => throw new YourSpecialException(ee.getMessage);
    }
  }
</code>```

Body:
I'm looking to cache information in a Map so I don't have to keep, for example, hitting a DB. In Java I'd use Google collection's excellent MapMaker and set an expiry, to keep the cache as fresh as necessary, and softValues, to keep the memory usage down. Then I'd have a function that computes the value for a key that currently isn't cached.

MapMaker().softValues
          .expireAfterWrite(10, TimeUnit.MINUTES)
          .makeComputingMap(Function(...));

What's the best way to do this in Scala?

Body:
I'm keep using Guava cache solution in Scala as well :)

First of all, as noted in one of the comments, in newer versions of Guava Cache, MapMaker() is now deprecated and you should use CacheBuilder instead.

So now, in Scala it will look like the follow:

  lazy val cachedData = CacheBuilder.newBuilder()
    .expireAfterWrite(60, TimeUnit.MINUTES)
    .maximumSize(10)
    .build(
      new CacheLoader[Key, Data] {
        def load(key: Key): Data = {
          veryExpansiveDataCreation(key)
        }
      }
    )

To read from it, you can use something like:

  def cachedData(ketToData: Key): Data = {
    try {
      return cachedData.get(ketToData)
    } catch {
      case ee: Exception => throw new YourSpecialException(ee.getMessage);
    }
  }


问:
Genetic Algorithm: Creating Offspring of Two HashMaps
I need to do create offspring from two arrays, if possible with HashMaps.

Here is my reproduce function:

```<code>public Map<String, Integer> reproduce(Map<String, Integer> x, Map<String, Integer> y, int n){
Random rand = new Random();
int c = rand.nextInt(n);
!!CREATE OFFSPRING from x and y and store it into child!!
return(child);
}
</code>```

For example if the x and y values passed to the function are:

```<code>x = {0=1} {1=0} {2=1}
</code>```

and

```<code>y = {0=2} {1=1} {2=2}
</code>```

I would like to reproduce using these Maps to create a child map like for example:

```<code>child = {0=1} {1=1} {2=2}
</code>```

The child has taken the first tuple from x, and the 2nd and 3rd tuples from y.

The point where it switches from x to y is determined by the random number c.

How can I do this without converting the maps to arrays?

答:
I am taking your word for it: You want the first c tuples from x and the remainder from y. In the natural order of the keys as defined by String.compareTo(). This is a bit more complicated than just taking each tuple from x or y at random. Of course it can be done.

As @Yossi Vainshtein already pointed out in another answer, a map generally doesn’t maintain an order of tuples, so it would not make sense to ask the map for the first c tuples. So we need to sort the keys explicitly. Before we can sort them, we need to have them in a different data strucure, a list or an array. So I take out the keys into a list and sort it. So while it is without converting the maps themselves to arrays, I do convert the key set only to a list which behind the scenes is implemented through an array.

This way of doing it only works as expected if the two parent maps have the same keys. So the first thing your method should do is check whether this is the case.

For taking the keys out of a map, use x.keySet(), similarly for y. To put them into a list, use new ArrayList<>(x.keySet()). To sort the list, use Collections.sort(). To create the empty child, use Map<String, Integer> child = new HashMap<>();. To fill it, iterate over the first c elements of the list and fill in the corresponding key and value from x; then iterate over the remaining keys and fill in key and value from y. Then you’re done.

If you didn’t care which c tuples were taking fomr x as long as you take c from x and n - c from y, we could skip the list and the sorting completely.

EDIT: I understand from your comment that the keys are always 0 through n - 1. In this case there is no reason to take the keys out of the maps and sort them. Just iterate over the numbers 0 through c - 1. For each number, convert it to a string, take the value from x and put the string and the value into the child. Then do the same with numbers c through n - 1 and y. Quite a bit simpler than what I outlined above.

Link: Answer by Yossi Vainshtein

ContentLicense: CC BY-SA 4.0

Body:
I need to do create offspring from two arrays, if possible with HashMaps.

Here is my reproduce function:

public Map<String, Integer> reproduce(Map<String, Integer> x, Map<String, Integer> y, int n){
Random rand = new Random();
int c = rand.nextInt(n);
!!CREATE OFFSPRING from x and y and store it into child!!
return(child);
}

For example if the x and y values passed to the function are:

x = {0=1} {1=0} {2=1}

and

y = {0=2} {1=1} {2=2}

I would like to reproduce using these Maps to create a child map like for example:

child = {0=1} {1=1} {2=2}

The child has taken the first tuple from x, and the 2nd and 3rd tuples from y.

The point where it switches from x to y is determined by the random number c.

How can I do this without converting the maps to arrays?


问:
How can I match common rows?
I have a table like this:

```<code>// friends
+----+---------+--------+
| id | user_id | friend |
+----+---------+--------+
| 1  | 1       | Peter  |
| 2  | 1       | Martin |
| 3  | 2       | Jack   |
| 4  | 1       | Barman |
| 5  | 3       | Peter  |
| 6  | 1       | Jack   |
| 7  | 3       | David  |
| 8  | 2       | David  |
| 9  | 3       | Martin |
+----+---------+--------+
</code>```

Now I have two user_ids. For example 1 and 3. Now I want to match the rows which have common friends. So this is expected result:

```<code>| Peter  |
| Martin |
</code>```

Because Peter and Martin are common for both ids 1 and 3.

Is doing that possible by pure sql ?

答:
You can do a self-join of the friends table, with the following three conditions being required to match records from both sides of the join:

The user_id from the first table is 1

The user_id from the second table is 3

The friends match (i.e. are shared by both sides)

```<code>SELECT t1.friend
FROM friends t1
INNER JOIN friends t2
    ON t1.user_id = 1 AND
       t2.user_id = 3 AND
       t1.friend = t2.friend
</code>```

If you have indices setup properly, I would expect this to run faster than an aggregation approach.

Demo here:

Rextester

Title: How can I match common rows?

Body:
I have a table like this:

// friends
+----+---------+--------+
| id | user_id | friend |
+----+---------+--------+
| 1  | 1       | Peter  |
| 2  | 1       | Martin |
| 3  | 2       | Jack   |
| 4  | 1       | Barman |
| 5  | 3       | Peter  |
| 6  | 1       | Jack   |
| 7  | 3       | David  |
| 8  | 2       | David  |
| 9  | 3       | Martin |
+----+---------+--------+

Now I have two user_ids. For example 1 and 3. Now I want to match the rows which have common friends. So this is expected result:

| Peter  |
| Martin |

Because Peter and Martin are common for both ids 1 and 3.

Is doing that possible by pure sql ?

Body:
You can do a self-join of the friends table, with the following three conditions being required to match records from both sides of the join:

The user_id from the first table is 1

The user_id from the second table is 3

The friends match (i.e. are shared by both sides)

SELECT t1.friend
FROM friends t1
INNER JOIN friends t2
    ON t1.user_id = 1 AND
       t2.user_id = 3 AND
       t1.friend = t2.friend

If you have indices setup properly, I would expect this to run faster than an aggregation approach.

Demo here:

Rextester


问:
UnicodeEncodeError odoo 9
This is my code in .py file:

```<code>description_val = str(self.description)
</code>```

also I'm try:

```<code>description_val = str(self.description).encode('utf-8').decode('utf-8')
</code>```

I don't ignore special character et. Malmö  --> Malm

Get this error:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u0160' in position 2: ordinal not in range(128)

How fix this issue?

答:
You can achieve via changing default encoding of python.

```<code>import sys
reload(sys)
sys.setdefaultencoding("utf-8")
</code>```

You can follow below link for default system encoding & change encoding.

Changing default encoding of Python?

Title: UnicodeEncodeError odoo 9

Body:
This is my code in .py file:

description_val = str(self.description)

also I'm try:

description_val = str(self.description).encode('utf-8').decode('utf-8')

I don't ignore special character et. Malmö  --> Malm

Get this error:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u0160' in position 2: ordinal not in range(128)

How fix this issue?

Body:
You can achieve via changing default encoding of python.

import sys
reload(sys)
sys.setdefaultencoding("utf-8")

You can follow below link for default system encoding & change encoding.

Changing default encoding of Python?


问:
How to collapse Bootstrap table row?
I'm using FullCalendar's years view, got it from here . I want to display the years as Blocks (vertically) - when the site is viewed in mobile...

Is it possible to change bootstrap table's display, from horizontal to vertical?
Or maybe the best way is to create a condition to set yearColumns to 1 when ever the view is change?

Here is my JS :

```<code> $('#calendar').fullCalendar({

            firstDay: 1,
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'year,month,agendaWeek,agendaDay'

            },
            defaultDate: '2016-01-12',
            defaultView: 'month',
            yearColumns: 3,
            editable: true,
            eventLimit: true,
            selectable: true,
            selectHelper: true,
   );}
</code>```

Here is the current view

答:
```<code> var current_page_size = $(this).width();
        if (current_page_size >= 800) {
            $('#calendar').fullCalendar({
                yearColumns: 3,
                });
               } else {
               yearColumns: 1,
               }
</code>```

Title: How to collapse Bootstrap table row?

Body:
I'm using FullCalendar's years view, got it from here . I want to display the years as Blocks (vertically) - when the site is viewed in mobile...

Is it possible to change bootstrap table's display, from horizontal to vertical?
Or maybe the best way is to create a condition to set yearColumns to 1 when ever the view is change?

Here is my JS :

 $('#calendar').fullCalendar({

            firstDay: 1,
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'year,month,agendaWeek,agendaDay'

            },
            defaultDate: '2016-01-12',
            defaultView: 'month',
            yearColumns: 3,
            editable: true,
            eventLimit: true,
            selectable: true,
            selectHelper: true,
   );}

Here is the current view


问:
api test with postman in angular project
I want to test my api for resister which is post type it contain username, email, password, phone number. I really don't know how to test api in postman. It should be authorization type of no-auth. After this I have to validate or test api for login then it generate some key then I have to use this key to test other api's. </p>

答:
depends first find if any form of auth is being used in such case you will need to handled the auth before sending requests. check the link bellow it will help you in case of auth

https://www.getpostman.com/docs/helpers


问:
Unity: how to resolve class through base interface
Here is my repository class:

```<code>public interface IMyRepository : IRepository<IMyEntity>{}

public class MyRepository : IMyRepository
{
...
}
</code>```

Here is way to register it:

```<code>container.Register<IMyRepository, MyRepository >();
</code>```

Here is the way how I want to get repository resolved:

```<code>IRepository<IMyEntity> repository = container.Resolve<IRepository<IMyEntity>>();
</code>```

Attempt to resolve repository in this ways give an error:

Resolution of the dependency failed, type = "CMCore.Repository.IRepository`1[CMCore.Data.ICmCoreLog]", name = "(none)".
  Exception occurred while: while resolving.

Exception is: InvalidOperationException - The current type, IRepository`1[IMyEntity], is an interface and cannot be constructed. Are you missing a type mapping?

At the time of the exception, the container was:

Resolving IRepository`1[IMyEntity],(none)

What is wrong in my approach? What is a proper way to achieve mentioned functionality?

Thanks a lot!

P.S. Sometime I want to resolve my class through the IMyRepository, sometime through IRepository. Should I register class twice?

答:
Do:

```<code>container.RegisterType<IRepository<IMyEntity>, MyRepository>();
</code>```

instead. Unity, by design, only does one level of type mapping. It's only going to look for a mapping from the type you ask, it doesn't chase down inheritance trees.

If you want it to be available both a IRepository or as IMyRepository, then just register it twice:

```<code>container.RegisterType<IRepository<IMyEntity>, MyRepository>()
    .RegisterType<IMyRepository, MyRepository>();
</code>```

Body:
Here is my repository class:

public interface IMyRepository : IRepository<IMyEntity>{}

public class MyRepository : IMyRepository
{
...
}

Here is way to register it:

container.Register<IMyRepository, MyRepository >();

Here is the way how I want to get repository resolved:

IRepository<IMyEntity> repository = container.Resolve<IRepository<IMyEntity>>();

Attempt to resolve repository in this ways give an error:

Resolution of the dependency failed, type = "CMCore.Repository.IRepository`1[CMCore.Data.ICmCoreLog]", name = "(none)".
  Exception occurred while: while resolving.

Exception is: InvalidOperationException - The current type, IRepository`1[IMyEntity], is an interface and cannot be constructed. Are you missing a type mapping?

At the time of the exception, the container was:

Resolving IRepository`1[IMyEntity],(none)

What is wrong in my approach? What is a proper way to achieve mentioned functionality?

Thanks a lot!

P.S. Sometime I want to resolve my class through the IMyRepository, sometime through IRepository. Should I register class twice?

Body:
Do:

container.RegisterType<IRepository<IMyEntity>, MyRepository>();

instead. Unity, by design, only does one level of type mapping. It's only going to look for a mapping from the type you ask, it doesn't chase down inheritance trees.

If you want it to be available both a IRepository or as IMyRepository, then just register it twice:

container.RegisterType<IRepository<IMyEntity>, MyRepository>()
    .RegisterType<IMyRepository, MyRepository>();


问:
Loop breaks when executing function
I have the code below:

```<code>def scrapeFacebookPageFeedStatus(access_token):

    query = "SELECT page_id FROM falken"

    result_list = c.execute(query)

    for single_row in result_list:

        str_single_row = str(single_row)

        str_norm_single_row = str_normalize(str_single_row)

        print(str_norm_single_row)
</code>```

When I execute the code above, It displays every single_row values from result_list.

But when I pass single_row to a function like below:

```<code>def scrapeFacebookPageFeedStatus(access_token):

    query = "SELECT page_id FROM falken"

    result_list = c.execute(query)

    for single_row in result_list:

        str_single_row = str(single_row)

        str_norm_single_row = str_normalize(str_single_row)

        print(str_norm_single_row)

        statuses = getFacebookPageFeedData(str_norm_single_row, access_token, 100)

        for status in statuses['data']:

            query = "INSERT INTO falken_posts VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"

            c.execute(query,(processFacebookPageFeedStatus(status, access_token)))

            conn.commit()
</code>```

It only passes the first value of single_row to the function and the loop stops.

getFacebookPageFeedData function

```<code>def getFacebookPageFeedData(page_id, access_token, num_statuses):

base = "https://graph.facebook.com/v2.6"
node = "/%s/posts" % page_id
fields = "/?fields=message,link,created_time,type,name,id," + \
        "comments.limit(0).summary(true),shares,reactions" + \
        ".limit(0).summary(true)"
parameters = "&limit=%s&access_token=%s" % (num_statuses, access_token)
url = base + node + fields + parameters

# retrieve data
data = json.loads(request_until_succeed(url))

return data
</code>```

It retrieves data from Facebook Graph API of posts from pages.

processFacebookPageFeedStatus function

```<code>def processFacebookPageFeedStatus(status, access_token):

    status_id = status['id']
    status_message = '' if 'message' not in status.keys() else \
        unicode_normalize(status['message'])
    link_name = '' if 'name' not in status.keys() else \
        unicode_normalize(status['name'])
    status_type = status['type']
    status_link = '' if 'link' not in status.keys() else \
        unicode_normalize(status['link'])

    status_published = datetime.datetime.strptime(
        status['created_time'],'%Y-%m-%dT%H:%M:%S+0000')
    status_published = status_published + \
        datetime.timedelta(hours=-5) # EST
    status_published = status_published.strftime(
        '%Y-%m-%d %H:%M:%S')

    num_reactions = 0 if 'reactions' not in status else \
        status['reactions']['summary']['total_count']
    num_comments = 0 if 'comments' not in status else \
        status['comments']['summary']['total_count']
    num_shares = 0 if 'shares' not in status else status['shares']['count']

    reactions = getReactionsForStatus(status_id, access_token) if \
        status_published > '2016-02-24 00:00:00' else {}

    num_likes = 0 if 'like' not in reactions else \
        reactions['like']['summary']['total_count']

    num_likes = num_reactions if status_published < '2016-02-24 00:00:00' \
        else num_likes
</code>```

It stores needed data from status dictionary and stores it to variables for inserting into database.

答:
sqlite's cursor.execute() returns the cursor itself. So after this line:

```<code>result_list = c.execute(query)
</code>```

result_list is actually an alias for c.

Now you start iterating over c:

```<code>for single_row in result_list:
    # code here
</code>```

and then call c.execute() again:

```<code>    query = "INSERT INTO falken_posts VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
    c.execute(query,(processFacebookPageFeedStatus(status, access_token)))
</code>```

which discards c's previous result set with the result of this new query. Since this query doesn't select anything, c becomes an empty iterator, and your loop stops there.

The cure is plain and simple: use another cursor for the insert queries so you don't overwrite c's result set:

```<code># create a second cursor for insert statements
writer = conn.cursor()
# no need to recreate this same string anew for each iteration,
# we can as well define it here once for all
insert_query = "INSERT INTO falken_posts VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"

# no need for result_list - just iterate over `c`
c.execute(query)
for single_row in c:
    # code here
    writer.execute(insert_query,(processFacebookPageFeedStatus(status, access_token)))
</code>```

As a side note, if performances are an issue, you may also want to commit only once after the whole loop instead of after each insert statement.

Title: Loop breaks when executing function

Body:
I have the code below:

def scrapeFacebookPageFeedStatus(access_token):

    query = "SELECT page_id FROM falken"

    result_list = c.execute(query)

    for single_row in result_list:

        str_single_row = str(single_row)

        str_norm_single_row = str_normalize(str_single_row)

        print(str_norm_single_row)

When I execute the code above, It displays every single_row values from result_list.

But when I pass single_row to a function like below:

def scrapeFacebookPageFeedStatus(access_token):

    query = "SELECT page_id FROM falken"

    result_list = c.execute(query)

    for single_row in result_list:

        str_single_row = str(single_row)

        str_norm_single_row = str_normalize(str_single_row)

        print(str_norm_single_row)

        statuses = getFacebookPageFeedData(str_norm_single_row, access_token, 100)

        for status in statuses['data']:

            query = "INSERT INTO falken_posts VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"

            c.execute(query,(processFacebookPageFeedStatus(status, access_token)))

            conn.commit()

It only passes the first value of single_row to the function and the loop stops.

getFacebookPageFeedData function

def getFacebookPageFeedData(page_id, access_token, num_statuses):

base = "https://graph.facebook.com/v2.6"
node = "/%s/posts" % page_id
fields = "/?fields=message,link,created_time,type,name,id," + \
        "comments.limit(0).summary(true),shares,reactions" + \
        ".limit(0).summary(true)"
parameters = "&limit=%s&access_token=%s" % (num_statuses, access_token)
url = base + node + fields + parameters

# retrieve data
data = json.loads(request_until_succeed(url))

return data

It retrieves data from Facebook Graph API of posts from pages.

processFacebookPageFeedStatus function

def processFacebookPageFeedStatus(status, access_token):

    status_id = status['id']
    status_message = '' if 'message' not in status.keys() else \
        unicode_normalize(status['message'])
    link_name = '' if 'name' not in status.keys() else \
        unicode_normalize(status['name'])
    status_type = status['type']
    status_link = '' if 'link' not in status.keys() else \
        unicode_normalize(status['link'])

    status_published = datetime.datetime.strptime(
        status['created_time'],'%Y-%m-%dT%H:%M:%S+0000')
    status_published = status_published + \
        datetime.timedelta(hours=-5) # EST
    status_published = status_published.strftime(
        '%Y-%m-%d %H:%M:%S')

    num_reactions = 0 if 'reactions' not in status else \
        status['reactions']['summary']['total_count']
    num_comments = 0 if 'comments' not in status else \
        status['comments']['summary']['total_count']
    num_shares = 0 if 'shares' not in status else status['shares']['count']

    reactions = getReactionsForStatus(status_id, access_token) if \
        status_published > '2016-02-24 00:00:00' else {}

    num_likes = 0 if 'like' not in reactions else \
        reactions['like']['summary']['total_count']

    num_likes = num_reactions if status_published < '2016-02-24 00:00:00' \
        else num_likes

It stores needed data from status dictionary and stores it to variables for inserting into database.

Body:
sqlite's cursor.execute() returns the cursor itself. So after this line:

result_list = c.execute(query)

result_list is actually an alias for c.

Now you start iterating over c:

for single_row in result_list:
    # code here

and then call c.execute() again:

    query = "INSERT INTO falken_posts VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
    c.execute(query,(processFacebookPageFeedStatus(status, access_token)))

which discards c's previous result set with the result of this new query. Since this query doesn't select anything, c becomes an empty iterator, and your loop stops there.

The cure is plain and simple: use another cursor for the insert queries so you don't overwrite c's result set:

# create a second cursor for insert statements
writer = conn.cursor()
# no need to recreate this same string anew for each iteration,
# we can as well define it here once for all
insert_query = "INSERT INTO falken_posts VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"

# no need for result_list - just iterate over `c`
c.execute(query)
for single_row in c:
    # code here
    writer.execute(insert_query,(processFacebookPageFeedStatus(status, access_token)))

As a side note, if performances are an issue, you may also want to commit only once after the whole loop instead of after each insert statement.


问:
Joomla installation fails on XAmpp
Hi All when I am trying to install joomla on XAMPP server i am getting below error

[client ::1:51690] PHP Warning:  simplexml_load_file(): I/O warning : failed to load external entity "file:/C:/xampp/htdocs/Joomla30/templates/protostar/templateDetails.xml" in C:\xampp\htdocs\Joomla30\libraries\cms\installer\installer.php on line 2195, referer: http://localhost/Joomla30/installation/index.php

Can any one help me to resolve this?

答:
Hello I had a similar problem with easyphp, some research led me to two problems.

The first had to do with the premise between Mysql and joomla see the php configuration file.

The second and most likely thing you have is a problem in the paths you give to joomla error log. Checks the php configuration file.

Loking in to your erro it's related to path of instaled joomla. Solution install again the joomla but be sure to save it in your created site folder for exemple www.mysite in your apache htdocs it worked for me.

Title: Joomla installation fails on XAmpp


问:
.NET Core API Gateway
I've got some work to do for school around Microservices.

I've got the architectural concept, but need an implementation to show off. I'll be using angular2 as a client, would like to use a .NET core API gateway to dispatch my requests to different services.

What's the best approach for this? I red something about using Rx.Net, but no definitive example or implementation that I can follow.

So what should I do to implement an API gateway in .NET Core?

答:
This may or may not help but I am currently building an API gateway in .NET core.

You can find it at https://github.com/TomPallister/Ocelot.

The code is a little ropey but a few people are working on it now so hopefully we can improve it over time.

Title: .NET Core API Gateway


问:
Android Studio 2.3 not deploying ui changes
since today im not able to deploy my UI changes anymore. The app runs fine but i cant change anything on the UI side. Whatever I do the app keeps the same UI every time. I changed nothing since my last dev session and now im stuck with this problem for hours.

What I tried so far:

Clean and Rebuild several Times

Disabled Instant Run

Deleted the Build folder

Checked for different Layout versions

Complete uninstall and reinstall of the app

Gradle Sync

Different Smartphones and Emulators

I can see all changes inside the preview of Android Studio but for some reason they dont appear in the deployed app.

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_send_media);
</code>```

答:
are you unable to see UI in XML?
then change the theme of the application,it may help you.</p>

Body:
since today im not able to deploy my UI changes anymore. The app runs fine but i cant change anything on the UI side. Whatever I do the app keeps the same UI every time. I changed nothing since my last dev session and now im stuck with this problem for hours.

What I tried so far:

Clean and Rebuild several Times

Disabled Instant Run

Deleted the Build folder

Checked for different Layout versions

Complete uninstall and reinstall of the app

Gradle Sync

Different Smartphones and Emulators

I can see all changes inside the preview of Android Studio but for some reason they dont appear in the deployed app.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_send_media);


问:
Custom Report in alfresco?
Currently i am generating a report (we are getting files are uploaded within a time stamp).
I am getting all files and folders.Iterating the result and checking created date one by one.That is taking too much time approx 8 min to revert with resuls.Can anyone tell me is there any alfresco report api that i can use? or using solr how to fetch the result?</p>

答:
I like to follow an approach which is maybe not really orthodox. Usually, you don't want to report on all documents, only document using a specific type or aspect. So, what I do is to create a Java behaviour on onCreate, onUpdate and onDelete that updates a custom database with only the metadata that I'm interested in. Then, I can connect any OOTB reporting tools such as Pentaho, Jasper or Tableau. You have of couse some other traditional alternatives, such as:

Using this module developed by a community member: http://fcorti.com/alfresco-audit-analysis-reporting/

Or using the module provided by Alfresco: http://docs.alfresco.com/analytics/concepts/analytics-using.html

Title: Custom Report in alfresco?


问:
How to add id and remove added id from anywhere on click using jQuery
I am trying to make a click add and click remove id function using jQuery.

My add function is working fine but I want also when user click anywhere without .click button then added id should be remove from .add div class.

I have created this demo from codepen.io. How can I do that? Or do you have any other method to do that?

```<code><div class="container">
   <div class="click" data-id="1">Click HERE</div>

   <div class="add">Check</div>
</div>
</code>```

JS

```<code>$(document).ready(function() {
   $("body").on("click", ".click", function() {
      var ID = $(this).attr("data-id");
      $(".add").attr('id', ID);
      // When you click anywhere i want to remove added
      // $(".add").attr('id', ID);
      // Like this $(".add").attr('id', '');
   });
});
</code>```

答:
try this, when you click outside of the green box it will remove id from .add class

$(document).ready(function() {
   $("body").on("click", ".click", function() {
      var ID = $(this).attr("data-id");
      $(".add").attr('id', ID);
      // When you click anywhere i want to remove added
      // $(".add").attr('id', ID);
      // Like this $(".add").attr('id', '');
   });
});

$(document).mouseup(function (e)
{
    var container = $(".container");

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        $(".add").attr('id', '');
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
   position:relative;
   width:100%;
   max-width:300px;
   margin:0px auto;
   padding:25px;
   background:green;
}</code>```

Click HERE

Check

```

Body:
I am trying to make a click add and click remove id function using jQuery.

My add function is working fine but I want also when user click anywhere without .click button then added id should be remove from .add div class.

I have created this demo from codepen.io. How can I do that? Or do you have any other method to do that?

Click HERE

Check

JS

$(document).ready(function() {
   $("body").on("click", ".click", function() {
      var ID = $(this).attr("data-id");
      $(".add").attr('id', ID);
      // When you click anywhere i want to remove added
      // $(".add").attr('id', ID);
      // Like this $(".add").attr('id', '');
   });
});

Body:
try this, when you click outside of the green box it will remove id from .add class

$(document).ready(function() {
   $("body").on("click", ".click", function() {
      var ID = $(this).attr("data-id");
      $(".add").attr('id', ID);
      // When you click anywhere i want to remove added
      // $(".add").attr('id', ID);
      // Like this $(".add").attr('id', '');
   });
});

$(document).mouseup(function (e)
{
    var container = $(".container");

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        $(".add").attr('id', '');
    }
});

.container {
   position:relative;
   width:100%;
   max-width:300px;
   margin:0px auto;
   padding:25px;
   background:green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
   <div class="click" data-id="1">Click HERE</div>

   <div class="add">Check</div>
</div>


问:
Does QScopedPointer hide multiple inheritance
I'm having trouble accessing the private part of a PIMPL design. "Of course!", you say! you're supposed to be!
Well, I'm writing some functional tests, so I don't care that I'm accessing private members, ok? :-)

To get to the point,  I have the public class set up with a QScopedPointer to the private implementation as follows;

```<code>class CV {
...
private:
  QScopedPointer<PrivateCV> const _d_ptr;
  PrivateChartView * d();
  const PrivateChartView *d() const;
};
PrivateCV * CV::d()
{
  return _d_ptr.data();
}

const PrivateCV* CV::d() const
{
  return _d_ptr.data();
}
</code>```

and the private bit looks like this:

```<code>class PrivateCV : public QObject, public Ui_CVForm
{
  Q_OBJECT
  friend class MyTestClass;
public:
  ...
public slots:
  void do_something();
}
</code>```

It seems that MyTestClass can access the do_something() member function of PrivateCV, which it obtains as follows (pseudocode, obvs):

```<code>CV *cv = MyApp::get_a_cv();
PrivateCV *pcv = cv->d();
</code>```

i.e. it will call this fine:

```<code>pcv->do_something();
</code>```

but I can't access anything that is on the Ui_CVForm (the generated UI class from uic).
Ui_CVForm is (in part) as follows:

```<code>class Ui_CVForm
{
public:
    QGridLayout *gridLayout_2;
    QGroupBox *groupBox;
    QLineEdit *lineEdit;
};
</code>```

Is this something to do with the const-ness of the function d(), or the QScopedPointer perhaps?
When I'm inside CV, I can access the ui form elements of the PrivateCV with no problems..

```<code>void CV::and_another_thing()
{
  d()->lineEdit->setText("wtfa");
}
</code>```

any pointers (pun intended) most welcome!

答:
OK this turned out to be due to some idiot (me) using the same filename for two different classes in different libraries.
The test library was picking up one header for Ui_CVForm which didn't contain items like the lineEdit above, while PrivateCV was using another... hence no complaints about not seeing the header at compile time.</p>

Body:
I'm having trouble accessing the private part of a PIMPL design. "Of course!", you say! you're supposed to be!
Well, I'm writing some functional tests, so I don't care that I'm accessing private members, ok? :-)

To get to the point,  I have the public class set up with a QScopedPointer to the private implementation as follows;

class CV {
...
private:
  QScopedPointer<PrivateCV> const _d_ptr;
  PrivateChartView * d();
  const PrivateChartView *d() const;
};
PrivateCV * CV::d()
{
  return _d_ptr.data();
}

const PrivateCV* CV::d() const
{
  return _d_ptr.data();
}

and the private bit looks like this:

class PrivateCV : public QObject, public Ui_CVForm
{
  Q_OBJECT
  friend class MyTestClass;
public:
  ...
public slots:
  void do_something();
}

It seems that MyTestClass can access the do_something() member function of PrivateCV, which it obtains as follows (pseudocode, obvs):

CV *cv = MyApp::get_a_cv();
PrivateCV *pcv = cv->d();

i.e. it will call this fine:

pcv->do_something();

but I can't access anything that is on the Ui_CVForm (the generated UI class from uic).
Ui_CVForm is (in part) as follows:

class Ui_CVForm
{
public:
    QGridLayout *gridLayout_2;
    QGroupBox *groupBox;
    QLineEdit *lineEdit;
};

Is this something to do with the const-ness of the function d(), or the QScopedPointer perhaps?
When I'm inside CV, I can access the ui form elements of the PrivateCV with no problems..

void CV::and_another_thing()
{
  d()->lineEdit->setText("wtfa");
}

any pointers (pun intended) most welcome!


问:
Change 'src' of an iframe from another page
I have a page 'A' which has link to another page 'B'.
On page 'B' there is an iframe. I have no control on page 'B' i.e. I cannot edit  page 'B'. Ask is to change 'src' of an iframe on page 'B' on click of link on page 'A'.</p>

答:
All else being equal: No.

Page B could be written so that it takes some external input (such as a query string on its URL) which it uses to set different values for the src attribute of the iframe … but that isn't typical so you'd probably have to modify B (which you said you can't do) in order to create such a feature.


问:
How to delete firebase child from background service when a deadline is due?
In my app, when the user is posting a request he also needs to set the deadline.  So when the deadline is due, I want the app to delete that request automatically.  I haven't tried anything yet coz I cant find anything similar to what i need.

I'll at least show the code when the user posts a request

```<code>post = (Button) myView.findViewById(R.id.post);
        post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),android.Manifest.permission.ACCESS_COARSE_LOCATION)) {
                        ActivityCompat.requestPermissions(getActivity(), new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSION_REQUEST_LOCATION);
                    }
                    else {
                        ActivityCompat.requestPermissions(getActivity(), new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSION_REQUEST_LOCATION);
                    }
                }
                else {
                    LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
                    Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    try {
                        uloc = hereLocation(location.getLatitude(), location.getLongitude());
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                        //Toast.makeText(getActivity(), "NOT FOUND", Toast.LENGTH_SHORT).show();
                    }

                }
                dead = deadline.getText().toString();
                r = reqdesc.getText().toString();

                if(reqdesc.getText().toString().trim().length()==0){
                    Toast.makeText(getActivity(), "PLEASE ENTER YOUR REQUEST", Toast.LENGTH_LONG).show();
                }
                else if(click==0 || dl==null){
                    Toast.makeText(getActivity(), "PLEASE SET THE DEADLINE FOR YOUR REQUEST", Toast.LENGTH_LONG).show();
                }
                else {
                    String date = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
                    writeNewRequest(r, dead, uemail, uid, uname, uprofile, uloc, date);
                    String reqKey = p.getKey().toString();
                    writeDuplicate(reqKey, r, dead, uemail, uid, uname, uprofile, uloc, date);
                    Intent i = new Intent(getActivity(), RequestConfirm.class);
                    i.putExtra("key", reqKey);
                    startActivity(i);
                    //showNotification();
                }
            }
        });
</code>```

答:
Databases in general are unable to implement such time-based functionality on their own.

You have two possible courses of action:

Run a maintenance app on a server, which loads the list with request's deadlines and deletes requests when their deadline is due. You run this 24/7 on 1sec time loop for example, but you don't check the deadlines in the db each second - you maintain a list by reacting to inserts, deletes and updates (you can just leave a connection to firebase open and observe a ref and it will tell you when it changes).

Make additional check / modify your queries to ignore items that are past the deadline. Run a housekeeping routine once a day for example, that deletes these items.

Body:
In my app, when the user is posting a request he also needs to set the deadline.  So when the deadline is due, I want the app to delete that request automatically.  I haven't tried anything yet coz I cant find anything similar to what i need.

I'll at least show the code when the user posts a request

post = (Button) myView.findViewById(R.id.post);
        post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),android.Manifest.permission.ACCESS_COARSE_LOCATION)) {
                        ActivityCompat.requestPermissions(getActivity(), new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSION_REQUEST_LOCATION);
                    }
                    else {
                        ActivityCompat.requestPermissions(getActivity(), new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSION_REQUEST_LOCATION);
                    }
                }
                else {
                    LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
                    Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    try {
                        uloc = hereLocation(location.getLatitude(), location.getLongitude());
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                        //Toast.makeText(getActivity(), "NOT FOUND", Toast.LENGTH_SHORT).show();
                    }

                }
                dead = deadline.getText().toString();
                r = reqdesc.getText().toString();

                if(reqdesc.getText().toString().trim().length()==0){
                    Toast.makeText(getActivity(), "PLEASE ENTER YOUR REQUEST", Toast.LENGTH_LONG).show();
                }
                else if(click==0 || dl==null){
                    Toast.makeText(getActivity(), "PLEASE SET THE DEADLINE FOR YOUR REQUEST", Toast.LENGTH_LONG).show();
                }
                else {
                    String date = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
                    writeNewRequest(r, dead, uemail, uid, uname, uprofile, uloc, date);
                    String reqKey = p.getKey().toString();
                    writeDuplicate(reqKey, r, dead, uemail, uid, uname, uprofile, uloc, date);
                    Intent i = new Intent(getActivity(), RequestConfirm.class);
                    i.putExtra("key", reqKey);
                    startActivity(i);
                    //showNotification();
                }
            }
        });


问:
How to add a icon inside a spinner
I'm able to do this if I'm able to freely modify the html, but the problem is I'm restricted to using a this one specific layout to make this spinner.

The spinner that I want to make is something like this,

There is the pink spinner which goes around and around the grey path and an icon in the middle which stays still.

The problem is I have to get the above spinner to work with just this html layout

Only a div

```<code><div class="spinner"></div>
</code>```

Div with an icon inside.

```<code><div class="spinner">
 <i class="mickey"></i>
</div>
</code>```

An icon font or an image can be used for the icon in the middle.

EDIT: Link to JSFiddle

答:
Here you could try this even using pseudo selector :before,:after or by declaring another div for spinner as shown by LGSon, what you did is that you have applied transform:rotate on parent div that's why it is rotating whole div, so try as below,

.spinner{
  width:100px;
  height:100px;
  border-radius:50%;
  border:10px solid #111;
  margin:10% 40%;
  position:relative;
  z-index:1;
}
.spinner:before{
  content:'';
  width:100px;
  height:100px;
  border-radius:50%;
  border-top:10px solid #ccc;
  border-right:10px solid transparent;
  border-bottom:10px solid transparent;
  border-left:10px solid transparent;
  position:absolute;
  z-index:9;
  top:-10px;
  left:-10px;
  animation:rt 2s infinite;
}
@keyframes rt{
  from{
    transform:rotate(0deg);
  }
  to{
    transform:rotate(360deg);
  }
}
.spinner > .fa{
  font-size:32px;
  text-align:center;
  display:block;
  margin:30% 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

<div class="spinner">
 <i class="fa fa-anchor"></i>
</div> </code>```

Title: How to add a icon inside a spinner

Body:
I'm able to do this if I'm able to freely modify the html, but the problem is I'm restricted to using a this one specific layout to make this spinner.

The spinner that I want to make is something like this,

There is the pink spinner which goes around and around the grey path and an icon in the middle which stays still.

The problem is I have to get the above spinner to work with just this html layout

Only a div

Div with an icon inside.

An icon font or an image can be used for the icon in the middle.

EDIT: Link to JSFiddle

Body:
Here you could try this even using pseudo selector :before,:after or by declaring another div for spinner as shown by LGSon, what you did is that you have applied transform:rotate on parent div that's why it is rotating whole div, so try as below,

.spinner{
  width:100px;
  height:100px;
  border-radius:50%;
  border:10px solid #111;
  margin:10% 40%;
  position:relative;
  z-index:1;
}
.spinner:before{
  content:'';
  width:100px;
  height:100px;
  border-radius:50%;
  border-top:10px solid #ccc;
  border-right:10px solid transparent;
  border-bottom:10px solid transparent;
  border-left:10px solid transparent;
  position:absolute;
  z-index:9;
  top:-10px;
  left:-10px;
  animation:rt 2s infinite;
}
@keyframes rt{
  from{
    transform:rotate(0deg);
  }
  to{
    transform:rotate(360deg);
  }
}
.spinner > .fa{
  font-size:32px;
  text-align:center;
  display:block;
  margin:30% 0;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

<div class="spinner">
 <i class="fa fa-anchor"></i>
</div>


问:
Remove useless zero digits from decimals in PHP
I'm trying to find a fast way to remove zero decimals from number values like this:

```<code>echo cleanNumber('125.00');
// 125

echo cleanNumber('966.70');
// 966.7

echo cleanNumber(844.011);
// 844.011
</code>```

Does exists some optimized way to do that?

答:
This Code will remove zero after point and will return only two decimal digits.

$number=1200.0000;

str_replace('.00', '',number_format($number, 2, '.', ''));

Output will be: 1200

Body:
I'm trying to find a fast way to remove zero decimals from number values like this:

echo cleanNumber('125.00');
// 125

echo cleanNumber('966.70');
// 966.7

echo cleanNumber(844.011);
// 844.011

Does exists some optimized way to do that?


问:
Putting JSON data from Google sheets into an array
My sheet: https://docs.google.com/spreadsheets/d/1pruXYXrbITR7CoQXZG1I1kyS4DahYBXmGMDEK2T6MpY/edit?usp=sharing

I'm using Google sheets JSON data to display on my website but I want to put some of the data into arrays so it doesn't repeat itself on the website.

For example, this is how it displays, but I would like to be able to just have the one heading for each group (zouk, zen ect) and then all the members to be under the one header.
https://www.kentunion.co.uk/test1/

So I am trying to figure out some javascript that adds all the positions of one group into an array. Go from this:

```<code>"Zouk Society" : {
      "name" : "Zouk Society",
      "position" : "President",
      "member" : "Currently Vacant"
    },
    "Zouk Society" : {
      "name" : "Zouk Society",
      "position" : "Secretary",
      "member" : "Currently Vacant"
    },
    "Zouk Society" : {
      "name" : "Zouk Society",
      "position" : "Treasurer",
      "member" : "Currently Vacant"
    }
</code>```

to this:

```<code>"Zouk Society" [{
      "position" : "President",
      "member" : "Currently Vacant"
    },
    {
      "position" : "Secretary",
      "member" : "Currently Vacant"
    },
    {
      "position" : "Treasurer",
      "member" : "Currently Vacant"
    }
]
</code>```

I have tried the following JS but I am just getting an error from it:

```<code> // ID of the Google Spreadsheet
 var spreadsheetID = "1pruXYXrbITR7CoQXZG1I1kyS4DahYBXmGMDEK2T6MpY";

 // Make sure it is public or set to Anyone with link can view
 var url = "https://spreadsheets.google.com/feeds/list/1pruXYXrbITR7CoQXZG1I1kyS4DahYBXmGMDEK2T6MpY/od6/public/values?alt=json";
     $(document).ready(function () {
         $.getJSON(url, function(data) {

             var entry = data.feed.entry;

             $(entry).each(function(){
                  // Column names are name, age, etc.
                  $('.results').prepend('<h2>'+this.gsx$name.$t+'</h2><p>'+this.gsx$position.$t+'</p><p>'+this.gsx$member.$t+'</p>');
             });
         });

    var grouped = {};

        entry.forEach(function (a) {
          grouped[a.name] = grouped[a.name] || [];
                grouped[a.name].push({ position: a.position, member: a.member });
        });
        document.write('```' + JSON.stringify(grouped, 0, 4) + '```');

  });
</code>```

This is the error that I get:

Uncaught ReferenceError: entry is not defined at
  HTMLDocument. (scripts.js:19)

答:
You cannot push data into object. You should change var grouped = {} into var grouped = []. Then you can push each element to this array of objects and access them with this syntax grouped[0].position.

I don't understand your spesific problem but "array of object" is the solution for your problem.

Body:
My sheet: https://docs.google.com/spreadsheets/d/1pruXYXrbITR7CoQXZG1I1kyS4DahYBXmGMDEK2T6MpY/edit?usp=sharing

I'm using Google sheets JSON data to display on my website but I want to put some of the data into arrays so it doesn't repeat itself on the website.

For example, this is how it displays, but I would like to be able to just have the one heading for each group (zouk, zen ect) and then all the members to be under the one header.
https://www.kentunion.co.uk/test1/

So I am trying to figure out some javascript that adds all the positions of one group into an array. Go from this:

"Zouk Society" : {
      "name" : "Zouk Society",
      "position" : "President",
      "member" : "Currently Vacant"
    },
    "Zouk Society" : {
      "name" : "Zouk Society",
      "position" : "Secretary",
      "member" : "Currently Vacant"
    },
    "Zouk Society" : {
      "name" : "Zouk Society",
      "position" : "Treasurer",
      "member" : "Currently Vacant"
    }

to this:

"Zouk Society" [{
      "position" : "President",
      "member" : "Currently Vacant"
    },
    {
      "position" : "Secretary",
      "member" : "Currently Vacant"
    },
    {
      "position" : "Treasurer",
      "member" : "Currently Vacant"
    }
]

I have tried the following JS but I am just getting an error from it:

 // ID of the Google Spreadsheet
 var spreadsheetID = "1pruXYXrbITR7CoQXZG1I1kyS4DahYBXmGMDEK2T6MpY";

 // Make sure it is public or set to Anyone with link can view
 var url = "https://spreadsheets.google.com/feeds/list/1pruXYXrbITR7CoQXZG1I1kyS4DahYBXmGMDEK2T6MpY/od6/public/values?alt=json";
     $(document).ready(function () {
         $.getJSON(url, function(data) {

             var entry = data.feed.entry;

             $(entry).each(function(){
                  // Column names are name, age, etc.
                  $('.results').prepend('
'+this.gsx$name.$t+'

'+this.gsx$position.$t+'

'+this.gsx$member.$t+'
');
             });
         });

    var grouped = {};

        entry.forEach(function (a) {
          grouped[a.name] = grouped[a.name] || [];
                grouped[a.name].push({ position: a.position, member: a.member });
        });
        document.write('
' + JSON.stringify(grouped, 0, 4) + '
');

  });

This is the error that I get:

Uncaught ReferenceError: entry is not defined at
  HTMLDocument. (scripts.js:19)