问:
gpgp key request fails in dockerfile but not bash
I have an issue in that my attempts to receive a gpg key fails when building my docker container. The command that I am providing works correctly when executed at the command line.

I am behind a firewall; I have the proxy settings detailed below for this.

Host: CentOS 7.4; Docker version 17.09.0-ce, build afdb6d4

No environment variables for proxies are set for the account being used.

The Docker service has the environment variables for the proxies set according to Docker:

In /etc/systemd/system/docker.service.d/http-proxy.conf:

```<code>[Service]
Environment="HTTP_PROXY=http://<corporate proxy>/" "HTTPS_PROXY="<corporate proxy>/" "NO_PROXY=localhost,127.0.0.1,.domain.local,.corp"
</code>```

I use a build.sh shell script to build the image:

```<code>#/bin/bash
docker build -t hgk/test-container .
</code>```

The shell script is in the same location as my Dockerfile. These are the only two things in that directory.

```<code>FROM openjdk:8
ARG KEYSERV=hkp://p80.pool.sks-keyservers.net:80
ARG THEPROXY=<my corporate proxy>

# grab gosu for easy step-down from root
# (see docker-sonarqube pull request #115)
RUN set -x \
    && wget -e https_proxy=$THEPROXY -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/1.10/gosu-$(dpkg --print-architecture)" \
    && wget -e https_proxy=$THEPROXY-O /usr/local/bin/gosu.asc "https://github.com/tianon/gosu/releases/download/1.10/gosu-$(dpkg --print-architecture).asc" \
    && export GNUPGHOME="$(mktemp -d)" \
    && gpg --version \
    && gpg -vv --keyserver $KEYSERV --keyserver-options http-proxy=$THEPROXY --recv-keys B42F6819007F00F88E364FD4036A9C25BF357DD4 \
    && gpg --list-keys \
    && gpg --batch --verify /usr/local/bin/gosu.asc /usr/local/bin/gosu \
    && rm -rf "$GNUPGHOME" /usr/local/bin/gosu.asc \
    && chmod +x /usr/local/bin/gosu \
    && gosu nobody true
</code>```

The two wget commands work correctly and they retrieve the files. The first gpg command eventually times out:

```<code>+ mktemp -d
+ export GNUPGHOME=/tmp/tmp.LJ1EVFQmpO
+ gpg --version
gpg (GnuPG) 2.1.18
libgcrypt 1.7.6-beta
Copyright (C) 2017 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
<https://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Home: /tmp/tmp.LJlEVFQmpO
Supported algorithms:
Pubkey: RSA, ELG, DSA, ECDH, ECDSA, EDDSA
Cipher: IDEA, 3DES, CAST5, BLOWFISH, AES, AES192, AES256, TWOFISH,
        CAMELLIA128, CAMELLIA192, CAMELLIA256
Hash: SHA1, RIPEMD160, SHA256, SHA384, SHA512, SHA224
Compression: Uncompressed, ZIP, ZLIB, BZIP2
+ gpg -vv --keyserver hkp://p80.pool.sks-keyservers.net:80 --keyserver-options http-proxy=<corp proxy> --recv-keys B42F6819007F00F88E364FD4036A9C25BF357DD4
gpg: keybox '/tmp/tmp.LJlEVFQmpO/pubring.kbx' created
gpg: no running Dirmngr - starting '/usr/bin/dirmngr'
gpg: waiting for the dirmngr to come up ... (5s)
gpg: connection to the dirmngr established

[[I am hung here - It just waits for ... something? I'll update the question if anything prints after this]]
</code>```

I put the gpg --list-keys command in the Dockerfile to see if we got past there. However, if I run it via the command line, it successfully retrieves the key:

```<code>[root@me foo]# printenv | grep proxy
[root@me foo]# gpg --keyserver hkp://p80.pool.sks-keyservers.net:80 --
keyserver-options http-proxy=<corp proxy> --recv-keys B42F6819007F00F88E364FD4036A9C25BF357DD4
gpg: keyring `/root/.gnupg/pubring.gpg' created
gpg: requesting key BF357DD4 from hkp server p80.pool.sks-keyservers.net
Version: SKS 1.1.6
gpg: armor header:
Comment: Hostname: sks.okoyono.de
gpg: armor header:
gpg: pub  4096R/BF357DD4 2014-02-28  Tianon Gravi <tianon@debian.org>
gpg: key BF357DD4: removed multiple subkey binding
gpg: key BF357DD4: removed multiple subkey binding
gpg: /tmp/tmp.DIX6yQQf25/trustdb.gpg: trustdb created
gpg: using PGP trust model
gpg: key BF357DD4: public key "Tianon Gravi <tianon@tianon.xyz>" imported
gpg: 1 keys cached (126 signatures)
gpg: 0 keys processed (0 validity counts cleared)
gpg: no ultimately trusted keys found
gpg: Total number processed: 1
gpg:               imported: 1  (RSA: 1)

[root@me foo]# gpg --list-keys
/root/.gnupg/pubring.gpg
------------------------
pub   4096R/BF357DD4 2014-02-28 [expires: 2019-07-06]
uid                  Tianon Gravi <tianon@tianon.xyz>
uid                  Tianon Gravi <tianon@debian.org>
uid                  Tianon Gravi <tianon@dockerproject.org>
uid                  Andrew Page (tianon) <andrew@infosiftr.com>
uid                  Andrew Page (tianon) <andrew@vitalroute.com>
uid                  Andrew Page (Tianon Gravi) <admwiggin@gmail.com>
uid                  Tianon Gravi (Andrew Page) <tianon@infosiftr.com>
sub   4096R/769826E6 2014-02-28 [expires: 2019-07-06]
</code>```

I've tried different sks-keyservers (ubuntu, MIT, and other sks) with the same behavior - correct from bash, wrong from Docker.

Any thoughts/tips/suggestions?

Update: My "openjdk:8" version had not been updated in a while (since 8u121). I found I was running gpg v1.4.18. I did a docker image pull openjdk:8 which brought me up to 8u151 and gpg 2.1.18. The version of gpg on the CentOS 7 machine is 2.0.22.

答:
Your systemd unit file's environment variables are not passed into a container when building Docker images. Instead, make use of the --build-arg parameter for passing the proxy values:

```<code>docker build --build-arg=HTTP_PROXY=http://<corporate proxy>/ --build-arg=HTTPS_PROXY=http://<corporate proxy>/ -t hgk/test-container .
</code>```

You should not bake runtime options like proxy variables into the Dockerfile, always pass configuration through environment variables (or this build argument parameter).

Additional hint: most applications rely on http_proxy and https_proxy -- while most environment variables are indeed all-caps, the proxy variables have a more wide-spread lower-case usage.

Body:
I have an issue in that my attempts to receive a gpg key fails when building my docker container. The command that I am providing works correctly when executed at the command line.

I am behind a firewall; I have the proxy settings detailed below for this.

Host: CentOS 7.4; Docker version 17.09.0-ce, build afdb6d4

No environment variables for proxies are set for the account being used.

The Docker service has the environment variables for the proxies set according to Docker:

In /etc/systemd/system/docker.service.d/http-proxy.conf:

[Service]
Environment="HTTP_PROXY=http://<corporate proxy>/" "HTTPS_PROXY="<corporate proxy>/" "NO_PROXY=localhost,127.0.0.1,.domain.local,.corp"

I use a build.sh shell script to build the image:

#/bin/bash
docker build -t hgk/test-container .

The shell script is in the same location as my Dockerfile. These are the only two things in that directory.

FROM openjdk:8
ARG KEYSERV=hkp://p80.pool.sks-keyservers.net:80
ARG THEPROXY=<my corporate proxy>

# grab gosu for easy step-down from root
# (see docker-sonarqube pull request #115)
RUN set -x \
    && wget -e https_proxy=$THEPROXY -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/1.10/gosu-$(dpkg --print-architecture)" \
    && wget -e https_proxy=$THEPROXY-O /usr/local/bin/gosu.asc "https://github.com/tianon/gosu/releases/download/1.10/gosu-$(dpkg --print-architecture).asc" \
    && export GNUPGHOME="$(mktemp -d)" \
    && gpg --version \
    && gpg -vv --keyserver $KEYSERV --keyserver-options http-proxy=$THEPROXY --recv-keys B42F6819007F00F88E364FD4036A9C25BF357DD4 \
    && gpg --list-keys \
    && gpg --batch --verify /usr/local/bin/gosu.asc /usr/local/bin/gosu \
    && rm -rf "$GNUPGHOME" /usr/local/bin/gosu.asc \
    && chmod +x /usr/local/bin/gosu \
    && gosu nobody true

The two wget commands work correctly and they retrieve the files. The first gpg command eventually times out:

+ mktemp -d
+ export GNUPGHOME=/tmp/tmp.LJ1EVFQmpO
+ gpg --version
gpg (GnuPG) 2.1.18
libgcrypt 1.7.6-beta
Copyright (C) 2017 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
<https://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Home: /tmp/tmp.LJlEVFQmpO
Supported algorithms:
Pubkey: RSA, ELG, DSA, ECDH, ECDSA, EDDSA
Cipher: IDEA, 3DES, CAST5, BLOWFISH, AES, AES192, AES256, TWOFISH,
        CAMELLIA128, CAMELLIA192, CAMELLIA256
Hash: SHA1, RIPEMD160, SHA256, SHA384, SHA512, SHA224
Compression: Uncompressed, ZIP, ZLIB, BZIP2
+ gpg -vv --keyserver hkp://p80.pool.sks-keyservers.net:80 --keyserver-options http-proxy=<corp proxy> --recv-keys B42F6819007F00F88E364FD4036A9C25BF357DD4
gpg: keybox '/tmp/tmp.LJlEVFQmpO/pubring.kbx' created
gpg: no running Dirmngr - starting '/usr/bin/dirmngr'
gpg: waiting for the dirmngr to come up ... (5s)
gpg: connection to the dirmngr established

[[I am hung here - It just waits for ... something? I'll update the question if anything prints after this]]

I put the gpg --list-keys command in the Dockerfile to see if we got past there. However, if I run it via the command line, it successfully retrieves the key:

[root@me foo]# printenv | grep proxy
[root@me foo]# gpg --keyserver hkp://p80.pool.sks-keyservers.net:80 --
keyserver-options http-proxy=<corp proxy> --recv-keys B42F6819007F00F88E364FD4036A9C25BF357DD4
gpg: keyring `/root/.gnupg/pubring.gpg' created
gpg: requesting key BF357DD4 from hkp server p80.pool.sks-keyservers.net
Version: SKS 1.1.6
gpg: armor header:
Comment: Hostname: sks.okoyono.de
gpg: armor header:
gpg: pub  4096R/BF357DD4 2014-02-28  Tianon Gravi <tianon@debian.org>
gpg: key BF357DD4: removed multiple subkey binding
gpg: key BF357DD4: removed multiple subkey binding
gpg: /tmp/tmp.DIX6yQQf25/trustdb.gpg: trustdb created
gpg: using PGP trust model
gpg: key BF357DD4: public key "Tianon Gravi <tianon@tianon.xyz>" imported
gpg: 1 keys cached (126 signatures)
gpg: 0 keys processed (0 validity counts cleared)
gpg: no ultimately trusted keys found
gpg: Total number processed: 1
gpg:               imported: 1  (RSA: 1)

[root@me foo]# gpg --list-keys
/root/.gnupg/pubring.gpg
------------------------
pub   4096R/BF357DD4 2014-02-28 [expires: 2019-07-06]
uid                  Tianon Gravi <tianon@tianon.xyz>
uid                  Tianon Gravi <tianon@debian.org>
uid                  Tianon Gravi <tianon@dockerproject.org>
uid                  Andrew Page (tianon) <andrew@infosiftr.com>
uid                  Andrew Page (tianon) <andrew@vitalroute.com>
uid                  Andrew Page (Tianon Gravi) <admwiggin@gmail.com>
uid                  Tianon Gravi (Andrew Page) <tianon@infosiftr.com>
sub   4096R/769826E6 2014-02-28 [expires: 2019-07-06]

I've tried different sks-keyservers (ubuntu, MIT, and other sks) with the same behavior - correct from bash, wrong from Docker.

Any thoughts/tips/suggestions?

Update: My "openjdk:8" version had not been updated in a while (since 8u121). I found I was running gpg v1.4.18. I did a docker image pull openjdk:8 which brought me up to 8u151 and gpg 2.1.18. The version of gpg on the CentOS 7 machine is 2.0.22.

Body:
Your systemd unit file's environment variables are not passed into a container when building Docker images. Instead, make use of the --build-arg parameter for passing the proxy values:

docker build --build-arg=HTTP_PROXY=http://<corporate proxy>/ --build-arg=HTTPS_PROXY=http://<corporate proxy>/ -t hgk/test-container .

You should not bake runtime options like proxy variables into the Dockerfile, always pass configuration through environment variables (or this build argument parameter).

Additional hint: most applications rely on http_proxy and https_proxy -- while most environment variables are indeed all-caps, the proxy variables have a more wide-spread lower-case usage.


来源: stackexchange

问:
create-react-library cannot run npm start
I cloned create-react-library from https://github.com/UdiliaInc/create-react-library but cannot get it to start.

I have made no edits. I ran npm install and then npm start. When I run npm start I get the same error described in the below post.

Nodejs npm scripts fail with "SyntaxError: Unexpected token {"

I checked my node version and it is 5.3.0. Any other reasons why this could be happening?

The error is

```<code>  `[clynch@localhost create-react-library]$ npm start

create-react-library@1.0.0 start /home/clynch/git/create-react-library
node scripts/start.js

/home/clynch/git/create-react-library/scripts/start.js:23
    const { choosePort,
          ^

    SyntaxError: Unexpected token {
        at exports.runInThisContext (vm.js:53:16)
        at Module._compile (module.js:374:25)
        at Object.Module._extensions..js (module.js:405:10)
        at Module.load (module.js:344:32)
        at Function.Module._load (module.js:301:12)
        at Function.Module.runMain (module.js:430:10)
        at startup (node.js:141:18)
        at node.js:980:3
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! create-react-library@1.0.0 start: `node scripts/start.js`
    npm ERR! Exit status 1
    npm ERR!
    npm ERR! Failed at the create-react-library@1.0.0 start script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

    npm ERR! A complete log of this run can be found in:
    npm ERR!     /home/clynch/.npm/_logs/2017-11-16T21_05_24_465Z-debug.log
    `
</code>```

答:
You should update your node version to 6.12 or 7+

For reference, check http://node.green/

ContentLicense: CC BY-SA 3.0

Body:
I cloned create-react-library from https://github.com/UdiliaInc/create-react-library but cannot get it to start.

I have made no edits. I ran npm install and then npm start. When I run npm start I get the same error described in the below post.

Nodejs npm scripts fail with "SyntaxError: Unexpected token {"

I checked my node version and it is 5.3.0. Any other reasons why this could be happening?

The error is

  `[clynch@localhost create-react-library]$ npm start

create-react-library@1.0.0 start /home/clynch/git/create-react-library
node scripts/start.js

/home/clynch/git/create-react-library/scripts/start.js:23
    const { choosePort,
          ^

    SyntaxError: Unexpected token {
        at exports.runInThisContext (vm.js:53:16)
        at Module._compile (module.js:374:25)
        at Object.Module._extensions..js (module.js:405:10)
        at Module.load (module.js:344:32)
        at Function.Module._load (module.js:301:12)
        at Function.Module.runMain (module.js:430:10)
        at startup (node.js:141:18)
        at node.js:980:3
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! create-react-library@1.0.0 start: `node scripts/start.js`
    npm ERR! Exit status 1
    npm ERR!
    npm ERR! Failed at the create-react-library@1.0.0 start script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

    npm ERR! A complete log of this run can be found in:
    npm ERR!     /home/clynch/.npm/_logs/2017-11-16T21_05_24_465Z-debug.log
    `


问:
Transfer data between uiviews in nil
Hi I'm trying to pass an object from one tableview controller to another one.
I'm using prepare for segue and a didselectRowAt function:

```<code>    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.myDish = sections[indexPath.section].listofDishes?[indexPath.row]
    self.sectionName = sections[indexPath.section].sectionName!

    self.flag = 1
    performSegue(withIdentifier: "chooseDish", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if self.flag != 0{
    let selectedDishTableViewController = segue.destination as! SelectedDishViewController
        selectedDishTableViewController.sectionName = self.sectionName
        selectedDishTableViewController.dish = self.myDish

        self.flag = 0
    }
}
</code>```

I created the flag because preparefor segue gets called before didselectrowat

Thant way I'm making sure to set myDish and sectionName before the prepare for segue.

by in my second view controller I still get both values as nil.

This is how I declare the vars in my second controller

```<code>var dish:Dish?
var sectionName:String?
</code>```

答:
If prepareForSegue is getting called before didSelectRow.., then it implies that the segue is already happening, so the second time when you force it to be invoked, by calling performSegue explicitly in didSelectRow <- it is ignored as the view controller has already been segued into with null values for those vars.

The solution here would be to do something like this:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let indexPath = tableView.indexPathForSelectedRow {
        let selectedDishTableViewController = segue.destination as! SelectedDishViewController
        selectedDishTableViewController.dish = sections[indexPath.section].listofDishes?[indexPath.row]
        selectedDishTableViewController.sectionName = sections[indexPath.section].sectionName!
    }
}
</code>```

You don't have to do anything else in tableView:didSelect... for this, with this.. Lemme know if it works out.

Title: Transfer data between uiviews in nil

Body:
Hi I'm trying to pass an object from one tableview controller to another one.
I'm using prepare for segue and a didselectRowAt function:

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.myDish = sections[indexPath.section].listofDishes?[indexPath.row]
    self.sectionName = sections[indexPath.section].sectionName!

    self.flag = 1
    performSegue(withIdentifier: "chooseDish", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if self.flag != 0{
    let selectedDishTableViewController = segue.destination as! SelectedDishViewController
        selectedDishTableViewController.sectionName = self.sectionName
        selectedDishTableViewController.dish = self.myDish

        self.flag = 0
    }
}

I created the flag because preparefor segue gets called before didselectrowat

Thant way I'm making sure to set myDish and sectionName before the prepare for segue.

by in my second view controller I still get both values as nil.

This is how I declare the vars in my second controller

var dish:Dish?
var sectionName:String?

Body:
If prepareForSegue is getting called before didSelectRow.., then it implies that the segue is already happening, so the second time when you force it to be invoked, by calling performSegue explicitly in didSelectRow <- it is ignored as the view controller has already been segued into with null values for those vars.

The solution here would be to do something like this:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let indexPath = tableView.indexPathForSelectedRow {
        let selectedDishTableViewController = segue.destination as! SelectedDishViewController
        selectedDishTableViewController.dish = sections[indexPath.section].listofDishes?[indexPath.row]
        selectedDishTableViewController.sectionName = sections[indexPath.section].sectionName!
    }
}

You don't have to do anything else in tableView:didSelect... for this, with this.. Lemme know if it works out.


问:
New 3.5 Zookeeper nodes do not appear to be dynamically added to my cluster
I am using Zookeeper version: 3.5.3-beta and had it configured in a standard 3 node configuration.  I am now trying to add 3 new nodes to it following the documentation, however the new nodes do not appear to be getting dynamically added as observers (see https://zookeeper.apache.org/doc/trunk/zookeeperReconfig.html#ch_reconfig_dyn).

First, I tried to add the first node using the following setting:"ZOOKEEPER_IP_LIST=10.144.81.81 10.144.81.83 10.144.81.86 10.144.46.54" , but it does not join the cluster.  When I start up the new node I still see the following, only showing the 3 initial nodes in the cluster. I even tried restarting the 3 initial nodes to include the new nodes, but it still reflected the old configuration.

```<code>clientPort=2181
secureClientPort=-1
dataDir=/dbpath/data/version-2
dataDirSize=134254305
dataLogDir=/dbpath/data/version-2
dataLogSize=134254305
tickTime=2000
maxClientCnxns=30
minSessionTimeout=4000
maxSessionTimeout=40000
serverId=3
initLimit=60
syncLimit=5
electionAlg=3
electionPort=3888
quorumPort=2888
peerType=0
membership:
server.0=10.144.81.81:2888:3888:participant
server.1=10.144.81.83:2888:3888:participant
server.2=10.144.81.86:2888:3888:participant
</code>```

When that did not work I decided to try the zkCli.sh command on the leader first to see if the configuration tried above matched the results from the REST interface, it did.

```<code>$ sudo bin/zkCli.sh -server 10.144.81.83:2181 config
...
2017-11-09 12:13:38,172 [myid:10.144.81.83:2181] - INFO  [main-SendThread(10.144.81.83:2181):ClientCnxn$SendThread@1381] - Session establishment complete on server 10.144.81.83/10.144.81.83:2181, sessionid = 0x100301c01db000a, negotiated timeout = 30000

WATCHER::

WatchedEvent state:SyncConnected type:None path:null
server.0=10.144.81.81:2888:3888:participant
server.1=10.144.81.83:2888:3888:participant
server.2=10.144.81.86:2888:3888:participant
version=100000000
</code>```

I then attempted to use zkCli.sh to reconfigure and add the one new node, but it throws an Authentication issue, which is confusing because I have not configured ACLs or any authentication that I know of that would cause this error.

```<code>$ sudo bin/zkCli.sh -server 10.144.81.83:2181 reconfig -file ../newconfig.cfg.dynamic
/usr/bin/java
Connecting to 10.144.81.83:2181
2017-11-09 12:03:32,729 [myid:] - INFO  [main:Environment@109] - Client environment:zookeeper.version=3.5.3-beta-8ce24f9e675cbefffb8f21a47e06b42864475a60, built on 04/03/2017 16:19 GMT
2017-11-09 12:03:32,735 [myid:] - INFO  [main:Environment@109] - Client environment:host.name=DockerNode-master-cloudeng-20170925-1652-Jy1.localdomain
2017-11-09 12:03:32,739 [myid:] - INFO  [main:Environment@109] - Client environment:java.version=1.7.0
2017-11-09 12:03:32,739 [myid:] - INFO  [main:Environment@109] - Client environment:java.vendor=IBM Corporation
2017-11-09 12:03:32,739 [myid:] - INFO  [main:Environment@109] - Client environment:java.home=/opt/ibm/ibm-java-x86_64-70/jre
2017-11-09 12:03:32,739 [myid:] - INFO  [main:Environment@109] - Client environment:java.class.path=/home/ibmadmin/zookeeper-3.5.3-beta/bin/../build/classes:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../build/lib/*.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/slf4j-log4j12-1.7.5.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/slf4j-api-1.7.5.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/netty-3.10.5.Final.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/log4j-1.2.17.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/jline-2.11.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/jetty-util-9.2.18.v20160721.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/jetty-servlet-9.2.18.v20160721.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/jetty-server-9.2.18.v20160721.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/jetty-security-9.2.18.v20160721.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/jetty-io-9.2.18.v20160721.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/jetty-http-9.2.18.v20160721.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/javax.servlet-api-3.1.0.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/jackson-mapper-asl-1.9.11.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/jackson-core-asl-1.9.11.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/commons-cli-1.2.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../zookeeper-3.5.3-beta.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../src/java/lib/*.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../conf:
2017-11-09 12:03:32,740 [myid:] - INFO  [main:Environment@109] - Client environment:java.library.path=/opt/ibm/ibm-java-x86_64-70/jre/lib/amd64/compressedrefs:/opt/ibm/ibm-java-x86_64-70/jre/lib/amd64:/usr/lib64:/usr/lib
2017-11-09 12:03:32,740 [myid:] - INFO  [main:Environment@109] - Client environment:java.io.tmpdir=/tmp
2017-11-09 12:03:32,740 [myid:] - INFO  [main:Environment@109] - Client environment:java.compiler=j9jit26
2017-11-09 12:03:32,740 [myid:] - INFO  [main:Environment@109] - Client environment:os.name=Linux
2017-11-09 12:03:32,740 [myid:] - INFO  [main:Environment@109] - Client environment:os.arch=amd64
2017-11-09 12:03:32,740 [myid:] - INFO  [main:Environment@109] - Client environment:os.version=4.4.0-89-generic
2017-11-09 12:03:32,740 [myid:] - INFO  [main:Environment@109] - Client environment:user.name=root
2017-11-09 12:03:32,741 [myid:] - INFO  [main:Environment@109] - Client environment:user.home=/root
2017-11-09 12:03:32,741 [myid:] - INFO  [main:Environment@109] - Client environment:user.dir=/home/ibmadmin/zookeeper-3.5.3-beta
2017-11-09 12:03:32,743 [myid:] - INFO  [main:Environment@109] - Client environment:os.memory.free=1MB
2017-11-09 12:03:32,744 [myid:] - INFO  [main:Environment@109] - Client environment:os.memory.max=256MB
2017-11-09 12:03:32,744 [myid:] - INFO  [main:Environment@109] - Client environment:os.memory.total=4MB
2017-11-09 12:03:32,749 [myid:] - INFO  [main:ZooKeeper@865] - Initiating client connection, connectString=10.144.81.83:2181 sessionTimeout=30000 watcher=org.apache.zookeeper.ZooKeeperMain$MyWatcher@f9b15d67
2017-11-09 12:03:32,765 [myid:] - INFO  [main:ClientCnxnSocket@236] - jute.maxbuffer value is 4194304 Bytes
2017-11-09 12:03:32,785 [myid:10.144.81.83:2181] - INFO  [main-SendThread(10.144.81.83:2181):ClientCnxn$SendThread@1113] - Opening socket connection to server 10.144.81.83/10.144.81.83:2181. Will not attempt to authenticate using SASL (unknown error)
2017-11-09 12:03:32,802 [myid:10.144.81.83:2181] - INFO  [main-SendThread(10.144.81.83:2181):ClientCnxn$SendThread@948] - Socket connection established, initiating session, client: /10.144.81.83:59114, server: 10.144.81.83/10.144.81.83:2181
2017-11-09 12:03:32,812 [myid:10.144.81.83:2181] - INFO  [main-SendThread(10.144.81.83:2181):ClientCnxn$SendThread@1381] - Session establishment complete on server 10.144.81.83/10.144.81.83:2181, sessionid = 0x100301c01db0008, negotiated timeout = 30000

WATCHER::

WatchedEvent state:SyncConnected type:None path:null
Authentication is not valid :

$ cat ../newconfig.cfg.dynamic
server.0=10.144.81.81:2888:3888:participant
server.1=10.144.81.83:2888:3888:participant
server.2=10.144.81.86:2888:3888:participant
server.3=10.144.46.54:2888:3888:observer
</code>```

I was under the impression by the documentation, either rightly or wrongly, that I could just specify the new topology changes without any specific node configuration changes.  I would prefer not to use zkCli since it would just complicate my deployment process but if I have to I will.

答:
What's happening is that the new observer is not allowed the path where zookeeper keeps info about the config. Initially all the nodes add themselves in the static config, but any dynamic new node is not allowed because it doesn't have permissions to the path (/config)

You can try restarting your nodes with this jvm option:

```<code>-Dzookeeper.skipACL=true
</code>```

Or you can become superuser:

```<code> $ export ZK_CLASSPATH=/etc/zookeeper/conf/:/usr/hdp/current/zookeeper-server/lib/*:/usr/hdp/current/zookeeper-server/*
 $ java -cp $ZK_CLASSPATH org.apache.zookeeper.server.auth.DigestAuthenticationProvider super:super123
</code>```

Output:

```<code>super:super123->super:UdxDQl4f9v5oITwcAsO9bmWgHSI=
</code>```

Then as root:

```<code>$ export SERVER_JVMFLAGS=-Dzookeeper.DigestAuthenticationProvider.superDigest=super:UdxDQl4f9v5oITwcAsO9bmWgHSI=
$ bin/zkCli.sh -server 10.144.81.83:2181 reconfig -file ../newconfig.cfg.dynamic
</code>```

Hope it helps.

More info here:
https://community.hortonworks.com/articles/29900/zookeeper-using-superdigest-to-gain-full-access-to.html

Body:
I am using Zookeeper version: 3.5.3-beta and had it configured in a standard 3 node configuration.  I am now trying to add 3 new nodes to it following the documentation, however the new nodes do not appear to be getting dynamically added as observers (see https://zookeeper.apache.org/doc/trunk/zookeeperReconfig.html#ch_reconfig_dyn).

First, I tried to add the first node using the following setting:"ZOOKEEPER_IP_LIST=10.144.81.81 10.144.81.83 10.144.81.86 10.144.46.54" , but it does not join the cluster.  When I start up the new node I still see the following, only showing the 3 initial nodes in the cluster. I even tried restarting the 3 initial nodes to include the new nodes, but it still reflected the old configuration.

clientPort=2181
secureClientPort=-1
dataDir=/dbpath/data/version-2
dataDirSize=134254305
dataLogDir=/dbpath/data/version-2
dataLogSize=134254305
tickTime=2000
maxClientCnxns=30
minSessionTimeout=4000
maxSessionTimeout=40000
serverId=3
initLimit=60
syncLimit=5
electionAlg=3
electionPort=3888
quorumPort=2888
peerType=0
membership:
server.0=10.144.81.81:2888:3888:participant
server.1=10.144.81.83:2888:3888:participant
server.2=10.144.81.86:2888:3888:participant

When that did not work I decided to try the zkCli.sh command on the leader first to see if the configuration tried above matched the results from the REST interface, it did.

$ sudo bin/zkCli.sh -server 10.144.81.83:2181 config
...
2017-11-09 12:13:38,172 [myid:10.144.81.83:2181] - INFO  [main-SendThread(10.144.81.83:2181):ClientCnxn$SendThread@1381] - Session establishment complete on server 10.144.81.83/10.144.81.83:2181, sessionid = 0x100301c01db000a, negotiated timeout = 30000

WATCHER::

WatchedEvent state:SyncConnected type:None path:null
server.0=10.144.81.81:2888:3888:participant
server.1=10.144.81.83:2888:3888:participant
server.2=10.144.81.86:2888:3888:participant
version=100000000

I then attempted to use zkCli.sh to reconfigure and add the one new node, but it throws an Authentication issue, which is confusing because I have not configured ACLs or any authentication that I know of that would cause this error.

$ sudo bin/zkCli.sh -server 10.144.81.83:2181 reconfig -file ../newconfig.cfg.dynamic
/usr/bin/java
Connecting to 10.144.81.83:2181
2017-11-09 12:03:32,729 [myid:] - INFO  [main:Environment@109] - Client environment:zookeeper.version=3.5.3-beta-8ce24f9e675cbefffb8f21a47e06b42864475a60, built on 04/03/2017 16:19 GMT
2017-11-09 12:03:32,735 [myid:] - INFO  [main:Environment@109] - Client environment:host.name=DockerNode-master-cloudeng-20170925-1652-Jy1.localdomain
2017-11-09 12:03:32,739 [myid:] - INFO  [main:Environment@109] - Client environment:java.version=1.7.0
2017-11-09 12:03:32,739 [myid:] - INFO  [main:Environment@109] - Client environment:java.vendor=IBM Corporation
2017-11-09 12:03:32,739 [myid:] - INFO  [main:Environment@109] - Client environment:java.home=/opt/ibm/ibm-java-x86_64-70/jre
2017-11-09 12:03:32,739 [myid:] - INFO  [main:Environment@109] - Client environment:java.class.path=/home/ibmadmin/zookeeper-3.5.3-beta/bin/../build/classes:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../build/lib/*.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/slf4j-log4j12-1.7.5.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/slf4j-api-1.7.5.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/netty-3.10.5.Final.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/log4j-1.2.17.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/jline-2.11.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/jetty-util-9.2.18.v20160721.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/jetty-servlet-9.2.18.v20160721.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/jetty-server-9.2.18.v20160721.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/jetty-security-9.2.18.v20160721.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/jetty-io-9.2.18.v20160721.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/jetty-http-9.2.18.v20160721.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/javax.servlet-api-3.1.0.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/jackson-mapper-asl-1.9.11.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/jackson-core-asl-1.9.11.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../lib/commons-cli-1.2.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../zookeeper-3.5.3-beta.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../src/java/lib/*.jar:/home/ibmadmin/zookeeper-3.5.3-beta/bin/../conf:
2017-11-09 12:03:32,740 [myid:] - INFO  [main:Environment@109] - Client environment:java.library.path=/opt/ibm/ibm-java-x86_64-70/jre/lib/amd64/compressedrefs:/opt/ibm/ibm-java-x86_64-70/jre/lib/amd64:/usr/lib64:/usr/lib
2017-11-09 12:03:32,740 [myid:] - INFO  [main:Environment@109] - Client environment:java.io.tmpdir=/tmp
2017-11-09 12:03:32,740 [myid:] - INFO  [main:Environment@109] - Client environment:java.compiler=j9jit26
2017-11-09 12:03:32,740 [myid:] - INFO  [main:Environment@109] - Client environment:os.name=Linux
2017-11-09 12:03:32,740 [myid:] - INFO  [main:Environment@109] - Client environment:os.arch=amd64
2017-11-09 12:03:32,740 [myid:] - INFO  [main:Environment@109] - Client environment:os.version=4.4.0-89-generic
2017-11-09 12:03:32,740 [myid:] - INFO  [main:Environment@109] - Client environment:user.name=root
2017-11-09 12:03:32,741 [myid:] - INFO  [main:Environment@109] - Client environment:user.home=/root
2017-11-09 12:03:32,741 [myid:] - INFO  [main:Environment@109] - Client environment:user.dir=/home/ibmadmin/zookeeper-3.5.3-beta
2017-11-09 12:03:32,743 [myid:] - INFO  [main:Environment@109] - Client environment:os.memory.free=1MB
2017-11-09 12:03:32,744 [myid:] - INFO  [main:Environment@109] - Client environment:os.memory.max=256MB
2017-11-09 12:03:32,744 [myid:] - INFO  [main:Environment@109] - Client environment:os.memory.total=4MB
2017-11-09 12:03:32,749 [myid:] - INFO  [main:ZooKeeper@865] - Initiating client connection, connectString=10.144.81.83:2181 sessionTimeout=30000 watcher=org.apache.zookeeper.ZooKeeperMain$MyWatcher@f9b15d67
2017-11-09 12:03:32,765 [myid:] - INFO  [main:ClientCnxnSocket@236] - jute.maxbuffer value is 4194304 Bytes
2017-11-09 12:03:32,785 [myid:10.144.81.83:2181] - INFO  [main-SendThread(10.144.81.83:2181):ClientCnxn$SendThread@1113] - Opening socket connection to server 10.144.81.83/10.144.81.83:2181. Will not attempt to authenticate using SASL (unknown error)
2017-11-09 12:03:32,802 [myid:10.144.81.83:2181] - INFO  [main-SendThread(10.144.81.83:2181):ClientCnxn$SendThread@948] - Socket connection established, initiating session, client: /10.144.81.83:59114, server: 10.144.81.83/10.144.81.83:2181
2017-11-09 12:03:32,812 [myid:10.144.81.83:2181] - INFO  [main-SendThread(10.144.81.83:2181):ClientCnxn$SendThread@1381] - Session establishment complete on server 10.144.81.83/10.144.81.83:2181, sessionid = 0x100301c01db0008, negotiated timeout = 30000

WATCHER::

WatchedEvent state:SyncConnected type:None path:null
Authentication is not valid :

$ cat ../newconfig.cfg.dynamic
server.0=10.144.81.81:2888:3888:participant
server.1=10.144.81.83:2888:3888:participant
server.2=10.144.81.86:2888:3888:participant
server.3=10.144.46.54:2888:3888:observer

I was under the impression by the documentation, either rightly or wrongly, that I could just specify the new topology changes without any specific node configuration changes.  I would prefer not to use zkCli since it would just complicate my deployment process but if I have to I will.

Body:
What's happening is that the new observer is not allowed the path where zookeeper keeps info about the config. Initially all the nodes add themselves in the static config, but any dynamic new node is not allowed because it doesn't have permissions to the path (/config)

You can try restarting your nodes with this jvm option:

-Dzookeeper.skipACL=true

Or you can become superuser:

 $ export ZK_CLASSPATH=/etc/zookeeper/conf/:/usr/hdp/current/zookeeper-server/lib/*:/usr/hdp/current/zookeeper-server/*
 $ java -cp $ZK_CLASSPATH org.apache.zookeeper.server.auth.DigestAuthenticationProvider super:super123

Output:

super:super123->super:UdxDQl4f9v5oITwcAsO9bmWgHSI=

Then as root:

$ export SERVER_JVMFLAGS=-Dzookeeper.DigestAuthenticationProvider.superDigest=super:UdxDQl4f9v5oITwcAsO9bmWgHSI=
$ bin/zkCli.sh -server 10.144.81.83:2181 reconfig -file ../newconfig.cfg.dynamic

Hope it helps.

More info here:
https://community.hortonworks.com/articles/29900/zookeeper-using-superdigest-to-gain-full-access-to.html


问:
UI best practice question: Cancel button or Cancel link
I have a discussion with a colleague about what the "web standard" is for canceling in an form. In our discussion we have a "change password" page as example. We have a designed "send" button and "cancel" button. Both the same design.

He claims that in web standard a cancel button is no longer a button but a link transferring the user to another page. In my opinion, for those pages including a cancel button it actually is a cancel button which either resets the form and/or send the user to the prevision page.

Who is correct? Link or button... or both? And why? Any links to where this kind of standard is decided?

Br,

Paul Peelen

EDIT
I guess the answer with most votes will be the "correct answer"?

答:
The important thing is that the user doesn't press the cancel-button by mistake. As Horia says, make it a link or a button, but make it different, for example with a different color. Instead of calling it "Cancel", make it clear what will happen when you press it, for example: "Go back to previous page."

By the way, I hate it when there's a button for clearing the form. Completely unnecessary. It's good that it is not so common anymore.

Jon

ContentLicense: CC BY-SA 2.5


问:
How to Add HeaderView from nib to UiTableView programmatically in Swift
Well i'm a naive IOS developer using swift language.

I have a table view which displays a list of features of a hotel.Now i want to add a header information to the tableView with hotel image, hotel name above the tableview so that the header information also scrolls along with tableview contents(product features list)

Here is the problem, TableView with list of features is working fine.

```<code>class HotelDetailViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

    @IBOutlet weak var categoriesTableView: UITableView!

    var items: [(String, String,String)] = [
        ("Service", "   Courteous service, Good staff , Good staff","   Bad Facility"),
        ("Vibe",  "   Courteous service, Good staff","   Bad Facility"),
        ("Hotel",  "   Courteous service, Good staff","   Bad Facility"),
        ("Room Facility",  "   Courteous service, Good staff","   Bad Facility"),
        ("Amenities",  "   Courteous service, Good staff","   Bad Facility"),
        ("Food", "   Courteous service, Good staff","   Bad Facility")
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
        let nib = UINib(nibName: "HotelSnippetTableViewCell", bundle: nil)
        categoriesTableView.separatorStyle = UITableViewCellSeparatorStyle.None
        categoriesTableView.registerNib(nib, forCellReuseIdentifier: "CustomCell")
        categoriesTableView.rowHeight = UITableViewAutomaticDimension
        categoriesTableView.estimatedRowHeight = 100
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let customTableViewCell = tableView.dequeueReusableCellWithIdentifier("CustomCell") as! HotelSnippetTableViewCell

        let info  = items[indexPath.row]

        customTableViewCell.setCategory(info.0)

        customTableViewCell.setPositive(info.1)
        customTableViewCell.setNegative(info.2)

        return customTableViewCell

    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        print("You selected cell #\(indexPath.row)!")

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

}
</code>```

For header information like hotelImage , hotel name and other labels i have created a nib with all the views set and a corresponding class with all the references mapped to it.

Now how to add this UiView to my tableview as a header programatically (because i get data after rest call).

I have searched but found tutorials on how to set string section headers.

Couple of things i tried out:

I found that there is a protocol function for TableView

```<code>func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
       //Code}
</code>```

But how to load my nib here and set to this tableview and also i want ti trigger this programatically only after getting the data from service

Create a nib with parent as TableViewCell, Load it using dequeueReusableCellWithIdentifier(), set info and set to tableview

```<code>    let headerCell =  categoriesTableView.dequeueReusableCellWithIdentifier("HotelDetailHeaderTableViewCell") as! HotelDetailHeaderTableViewCell  headerCell.setImageUrl("");

    headerCell.setHotelZmi(CGFloat(87))

    headerCell.setNameAndPersona("Fort Aguada Goa", persona: "OverAll", reviewsCount: "780")

    headerCell.frame = CGRectMake(0, 0, self.categoriesTableView.bounds.width, 600)

    categoriesTableView.tableHeaderView = headerCell
</code>```

But even this is throwing some exception and i can't see where the exception is(How to see exception log in Xcode?).

Is the process i'm doing is correct? If not anyone please suggest me efficient approach

Because in Android i used to create a NestedScrollView with linear layout inside it embedded with any number of recyclerViews(removing scroll for recyclerviews) and Relativelayout

Please Help me.

答:
Update for swift 4</p>

```<code>let view = (Bundle.main.loadNibNamed("TableViewHeader", owner: self, options: nil)![0] as? UIView)
self.tableview.tableHeaderView = view
</code>```

Body:
Well i'm a naive IOS developer using swift language.

I have a table view which displays a list of features of a hotel.Now i want to add a header information to the tableView with hotel image, hotel name above the tableview so that the header information also scrolls along with tableview contents(product features list)

Here is the problem, TableView with list of features is working fine.

class HotelDetailViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

    @IBOutlet weak var categoriesTableView: UITableView!

    var items: [(String, String,String)] = [
        ("Service", "   Courteous service, Good staff , Good staff","   Bad Facility"),
        ("Vibe",  "   Courteous service, Good staff","   Bad Facility"),
        ("Hotel",  "   Courteous service, Good staff","   Bad Facility"),
        ("Room Facility",  "   Courteous service, Good staff","   Bad Facility"),
        ("Amenities",  "   Courteous service, Good staff","   Bad Facility"),
        ("Food", "   Courteous service, Good staff","   Bad Facility")
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
        let nib = UINib(nibName: "HotelSnippetTableViewCell", bundle: nil)
        categoriesTableView.separatorStyle = UITableViewCellSeparatorStyle.None
        categoriesTableView.registerNib(nib, forCellReuseIdentifier: "CustomCell")
        categoriesTableView.rowHeight = UITableViewAutomaticDimension
        categoriesTableView.estimatedRowHeight = 100
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let customTableViewCell = tableView.dequeueReusableCellWithIdentifier("CustomCell") as! HotelSnippetTableViewCell

        let info  = items[indexPath.row]

        customTableViewCell.setCategory(info.0)

        customTableViewCell.setPositive(info.1)
        customTableViewCell.setNegative(info.2)

        return customTableViewCell

    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        print("You selected cell #\(indexPath.row)!")

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

}

For header information like hotelImage , hotel name and other labels i have created a nib with all the views set and a corresponding class with all the references mapped to it.

Now how to add this UiView to my tableview as a header programatically (because i get data after rest call).

I have searched but found tutorials on how to set string section headers.

Couple of things i tried out:

I found that there is a protocol function for TableView

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
       //Code}

But how to load my nib here and set to this tableview and also i want ti trigger this programatically only after getting the data from service

Create a nib with parent as TableViewCell, Load it using dequeueReusableCellWithIdentifier(), set info and set to tableview

    let headerCell =  categoriesTableView.dequeueReusableCellWithIdentifier("HotelDetailHeaderTableViewCell") as! HotelDetailHeaderTableViewCell  headerCell.setImageUrl("");

    headerCell.setHotelZmi(CGFloat(87))

    headerCell.setNameAndPersona("Fort Aguada Goa", persona: "OverAll", reviewsCount: "780")

    headerCell.frame = CGRectMake(0, 0, self.categoriesTableView.bounds.width, 600)

    categoriesTableView.tableHeaderView = headerCell

But even this is throwing some exception and i can't see where the exception is(How to see exception log in Xcode?).

Is the process i'm doing is correct? If not anyone please suggest me efficient approach

Because in Android i used to create a NestedScrollView with linear layout inside it embedded with any number of recyclerViews(removing scroll for recyclerviews) and Relativelayout

Please Help me.

Body:
Update for swift 4

let view = (Bundle.main.loadNibNamed("TableViewHeader", owner: self, options: nil)![0] as? UIView)
self.tableview.tableHeaderView = view


问:
Amazon Web Service: Use non csv data and retrieve trained model
I am considering using the AWS with the machine learning AMI for training some deep networks that are to slow for my hardware setup.

However I see at the moment two possible major issues that might make this option less interesting or even impossible.

The training data is not in csv format, but images in nifti format. In the AWS description, it is stated that the data has to be in .csv.

Additionally, the FAQ states that trained models cannot be extracted. Which means that all sub-sequential inference and testing has to be made depending on instances in the AWS?

Are both of these issues real?

答:
Yes, I assume you can use only csv format for training data:
http://docs.aws.amazon.com/machine-learning/latest/dg/step-1-download-edit-and-upload-data.html
AWS Machine Learning Datasources
and finally Data from other products can usually be exported into CSV files in Amazon S3, making it accessible to Amazon Machine Learning

It seems that csv is the only format so far, I found it a bit frustrating myself...

And yes, as Machine Learning FAQ indicate:

Q: Can I export my models out of Amazon Machine Learning?

A: No.

So, so far, no way to save your model...
You can probably create a C5.large (compute optimized) instance and install all the Python libraries needed for your machine learning projects. Then use scikit-learn feature to save your model.
If C5.large is not going to be enough you can easily scale it up, just use EBS storage for this instance.

I hope this verification helps


问:
simulate key press in JUnit tests
I am completely stuck in a java test; it's about sending by the test method the character 'a' to the JTextField of a JFrame component.

The JFrame class implements the KeyListener interface, and as such overrides KeyPressed, KeyTyped, and KeyReleased. Along with this, I transfer all the keypressed of the JTextField to the JFrame; inside the JFrame constructor I have :

```<code>JTextField txf_version = new JTextField();
txf_version.addKeyListener(this);
</code>```

I would like to test this behavior and then to simulate the action of type a character in the JTextField.

all my attempts failed; I tried with the java.awt.Robot class, like this : hava a look at this other post in stack overflow, but I get a strange behavior : calling

```<code>robot.keyPress(KeyEvent.VK_A);
</code>```

displays the character in my IDE directly, not in the virtual JFrame! try to play with requestFocus() or requestFocusInWindow() is ineffective.

I also tried with KeyEvents:

```<code>KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_PRESSED, System
        .currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
bookWindow.txf_version.dispatchEvent(key);
</code>```

but again the textfield's text property is not changed...

here is the method I have for now:

```<code>@Test
void testBtnSaveChangesBecomesRedWhenVersionChanged() throws AWTException,
      InterruptedException, NoSuchFieldException, IllegalAccessException {
  initTest();

  KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_PRESSED, System
        .currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
  bookWindow.txf_version.dispatchEvent(key);

  System.out.println("dans txf_version : " + bookWindow.txf_version.getText
        ());

  assertEquals(Color.RED, bookWindow.getBtnSaveChangesForegroundColor());

}
</code>```

I can have a look at the actual behavior by writing a main() method in the JFrame's child class, but I think it is useful to know how to simulate keys for swing components testing.

thank you

EDIT:
I changed the code of my test according to AJNeufeld's answer, but it still doesn't work. Here is my test code :

```<code>@Test
void testBtnSaveChangesBecomesRedWhenVersionChanged() throws AWTException,
      InterruptedException, NoSuchFieldException, IllegalAccessException,
      InvocationTargetException {
//bookEditor2 & bookWindow
SwingUtilities.invokeAndWait(() -> {
  bookWindow = new BookWindow();
  VectorPerso two = new VectorPerso();
  two.add(le_livre_de_la_jungle);
  two.add(elogeMaths);
  bookWindow.setTableDatas(two);
  bookWindow.table.setRowSelectionInterval(1, 1);
  bookWindow.txf_version.requestFocusInWindow();
  KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_TYPED, System
          .currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
  bookWindow.txf_version.dispatchEvent(key);
  try {
    Thread.sleep(1000);
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
  System.out.println("dans txf_version : " + bookWindow.txf_version.getText
          ());

  assertEquals(Color.RED, bookWindow.getBtnSaveChangesForegroundColor());
});

}
</code>```

the plintln line produces a text in the console : "dans txf_version : 0", which indicates the key isn't send to the txf_version.

EDIT 2:

new try:

```<code>@Test
  void testBtnSaveChangesBecomesRedWhenVersionChanged() throws AWTException,
          InterruptedException, NoSuchFieldException, IllegalAccessException,
          InvocationTargetException {
    //bookEditor2 & bookWindow
    SwingUtilities.invokeAndWait(() -> {
      bookWindow = new BookWindow();
      VectorPerso two = new VectorPerso();
      two.add(le_livre_de_la_jungle);
      two.add(elogeMaths);
      bookWindow.setTableDatas(two);
      bookWindow.table.setRowSelectionInterval(1, 1);
      bookWindow.txf_version.requestFocusInWindow();
      KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_TYPED, System

              .currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
      bookWindow.txf_version.dispatchEvent(key);
    });
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    SwingUtilities.invokeAndWait(() -> {
      System.out.println("dans txf_version : " + bookWindow.txf_version.getText
              ());

      assertEquals(Color.RED, bookWindow.getBtnSaveChangesForegroundColor());
    });

  }
</code>```

答:
Yo, I guess you have two choices

1) It's still to find a solution using SWING (but in this case, I have no experience and any idead how to help you).

2) It's to use Sikulli java framework for testing desktop app. You can add the dependency then

make screenshot of your UI elements, and put them into test data folder of your app
Using sikuli + JUnit

write simple test where you set a path for your pic of button (for example)

and write action, move, click or what actually you need.
in very simple that will be looks like

Button button = new Button("test-folder/pic1.jpg");

button.click();

After run, you will see that, your cursor was move on button, and click by it.

For more details, find examples in web about Sikulli + Java.

Title: simulate key press in JUnit tests

Body:
I am completely stuck in a java test; it's about sending by the test method the character 'a' to the JTextField of a JFrame component.

The JFrame class implements the KeyListener interface, and as such overrides KeyPressed, KeyTyped, and KeyReleased. Along with this, I transfer all the keypressed of the JTextField to the JFrame; inside the JFrame constructor I have :

JTextField txf_version = new JTextField();
txf_version.addKeyListener(this);

I would like to test this behavior and then to simulate the action of type a character in the JTextField.

all my attempts failed; I tried with the java.awt.Robot class, like this : hava a look at this other post in stack overflow, but I get a strange behavior : calling

robot.keyPress(KeyEvent.VK_A);

displays the character in my IDE directly, not in the virtual JFrame! try to play with requestFocus() or requestFocusInWindow() is ineffective.

I also tried with KeyEvents:

KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_PRESSED, System
        .currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
bookWindow.txf_version.dispatchEvent(key);

but again the textfield's text property is not changed...

here is the method I have for now:

@Test
void testBtnSaveChangesBecomesRedWhenVersionChanged() throws AWTException,
      InterruptedException, NoSuchFieldException, IllegalAccessException {
  initTest();

  KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_PRESSED, System
        .currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
  bookWindow.txf_version.dispatchEvent(key);

  System.out.println("dans txf_version : " + bookWindow.txf_version.getText
        ());

  assertEquals(Color.RED, bookWindow.getBtnSaveChangesForegroundColor());

}

I can have a look at the actual behavior by writing a main() method in the JFrame's child class, but I think it is useful to know how to simulate keys for swing components testing.

thank you

EDIT:
I changed the code of my test according to AJNeufeld's answer, but it still doesn't work. Here is my test code :

@Test
void testBtnSaveChangesBecomesRedWhenVersionChanged() throws AWTException,
      InterruptedException, NoSuchFieldException, IllegalAccessException,
      InvocationTargetException {
//bookEditor2 & bookWindow
SwingUtilities.invokeAndWait(() -> {
  bookWindow = new BookWindow();
  VectorPerso two = new VectorPerso();
  two.add(le_livre_de_la_jungle);
  two.add(elogeMaths);
  bookWindow.setTableDatas(two);
  bookWindow.table.setRowSelectionInterval(1, 1);
  bookWindow.txf_version.requestFocusInWindow();
  KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_TYPED, System
          .currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
  bookWindow.txf_version.dispatchEvent(key);
  try {
    Thread.sleep(1000);
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
  System.out.println("dans txf_version : " + bookWindow.txf_version.getText
          ());

  assertEquals(Color.RED, bookWindow.getBtnSaveChangesForegroundColor());
});

}

the plintln line produces a text in the console : "dans txf_version : 0", which indicates the key isn't send to the txf_version.

EDIT 2:

new try:

@Test
  void testBtnSaveChangesBecomesRedWhenVersionChanged() throws AWTException,
          InterruptedException, NoSuchFieldException, IllegalAccessException,
          InvocationTargetException {
    //bookEditor2 & bookWindow
    SwingUtilities.invokeAndWait(() -> {
      bookWindow = new BookWindow();
      VectorPerso two = new VectorPerso();
      two.add(le_livre_de_la_jungle);
      two.add(elogeMaths);
      bookWindow.setTableDatas(two);
      bookWindow.table.setRowSelectionInterval(1, 1);
      bookWindow.txf_version.requestFocusInWindow();
      KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_TYPED, System

              .currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
      bookWindow.txf_version.dispatchEvent(key);
    });
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    SwingUtilities.invokeAndWait(() -> {
      System.out.println("dans txf_version : " + bookWindow.txf_version.getText
              ());

      assertEquals(Color.RED, bookWindow.getBtnSaveChangesForegroundColor());
    });

  }


问:
Change Toolbar color in Appcompat 21
I am testing out the new Appcompat 21 Material Design features. Therefore I've created a Toolbar like this:

```<code><android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_my_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:theme="@style/ThemeOverlay.AppCompat.ActionBar"/>
</code>```

and included it in my main layout file.

Then I've set it as supportActionBar like that:

```<code>Toolbar toolBar = (Toolbar)findViewById(R.id.activity_my_toolbar);
setSupportActionBar(toolBar);
</code>```

It's working, but somehow I can't quite figure out how to customize the toolbar. It's grey and the text on it is black. How should I change background and text color?

I've gone through this instructions:

http://android-developers.blogspot.de/2014/10/appcompat-v21-material-design-for-pre.html

What have I overseen to change colors?

```<code> <style name="AppTheme" parent="Theme.AppCompat.Light">
    <item name="android:windowActionBar" tools:ignore="NewApi">false</item>
    <item name="windowActionBar">false</item>
</style>
</code>```

EDIT:

I was able to change the background color by adding these lines of code to the theme:

```<code><item name="colorPrimary">@color/actionbar</item>
<item name="colorPrimaryDark">@color/actionbar_dark</item>
</code>```

But they won't affect the text color. What am I missing? Instead of the black text and black menu button, I'd rather prefer a white text and white menu buttons:

答:
If you want to change the color of your toolbar all throughout your app, leverage the styles.xml. In general, I avoid altering ui components in my java code unless I am trying to do something programatically. If this is a one time set, then you should be doing it in xml to make your code cleaner. Here is what your styles.xml will look like:

```<code>    <!-- Base application theme. -->
<style name="YourAppName.AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Color Primary will be your toolbar color -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <!-- Color Primary Dark will be your default status bar color -->
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
</style>
</code>```

Make sure you use the above style in your AndroidManifext.xml as such:

```<code>    <application
        android:theme="@style/YourAppName.AppTheme">
    </application>
</code>```

I wanted different toolbar colors for different activities. So I leveraged styles again like this:

```<code>    <style name="YourAppName.AppTheme.Activity1">
    <item name="colorPrimary">@color/activity1_primary</item>
    <item name="colorPrimaryDark">@color/activity1_primaryDark</item>
</style>

<style name="YourAppName.AppTheme.Activity2">
    <item name="colorPrimary">@color/activity2_primary</item>
    <item name="colorPrimaryDark">@color/activity2_primaryDark</item>
</style>
</code>```

again, apply the styles to each activity in your AndroidManifest.xml as such:

```<code><activity
    android:name=".Activity2"
    android:theme="@style/YourAppName.AppTheme.Activity2"
</activity>

<activity
    android:name=".Activity1"
    android:theme="@style/YourAppName.AppTheme.Activity1"
</activity>
</code>```

Title: Change Toolbar color in Appcompat 21

Body:
I am testing out the new Appcompat 21 Material Design features. Therefore I've created a Toolbar like this:

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_my_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:theme="@style/ThemeOverlay.AppCompat.ActionBar"/>

and included it in my main layout file.

Then I've set it as supportActionBar like that:

Toolbar toolBar = (Toolbar)findViewById(R.id.activity_my_toolbar);
setSupportActionBar(toolBar);

It's working, but somehow I can't quite figure out how to customize the toolbar. It's grey and the text on it is black. How should I change background and text color?

I've gone through this instructions:

http://android-developers.blogspot.de/2014/10/appcompat-v21-material-design-for-pre.html

What have I overseen to change colors?

EDIT:

I was able to change the background color by adding these lines of code to the theme:

<item name="colorPrimary">@color/actionbar</item>
<item name="colorPrimaryDark">@color/actionbar_dark</item>

But they won't affect the text color. What am I missing? Instead of the black text and black menu button, I'd rather prefer a white text and white menu buttons:

Body:
If you want to change the color of your toolbar all throughout your app, leverage the styles.xml. In general, I avoid altering ui components in my java code unless I am trying to do something programatically. If this is a one time set, then you should be doing it in xml to make your code cleaner. Here is what your styles.xml will look like:

    <!-- Base application theme. -->
<style name="YourAppName.AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Color Primary will be your toolbar color -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <!-- Color Primary Dark will be your default status bar color -->
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
</style>

Make sure you use the above style in your AndroidManifext.xml as such:

    <application
        android:theme="@style/YourAppName.AppTheme">
    </application>

I wanted different toolbar colors for different activities. So I leveraged styles again like this:

    <style name="YourAppName.AppTheme.Activity1">
    <item name="colorPrimary">@color/activity1_primary</item>
    <item name="colorPrimaryDark">@color/activity1_primaryDark</item>
</style>

<style name="YourAppName.AppTheme.Activity2">
    <item name="colorPrimary">@color/activity2_primary</item>
    <item name="colorPrimaryDark">@color/activity2_primaryDark</item>
</style>

again, apply the styles to each activity in your AndroidManifest.xml as such:

<activity
    android:name=".Activity2"
    android:theme="@style/YourAppName.AppTheme.Activity2"
</activity>

<activity
    android:name=".Activity1"
    android:theme="@style/YourAppName.AppTheme.Activity1"
</activity>


问:
LexikJWTAuthenticationBundle - There is no extension able to load the configuration for "api_login_check"
I'm trying to make some experiments with JWT and PHP, but I cannot make the LexikJWTAuthenticationBundle work.

I created a Symfony project using composer composer create-project symfony/skeleton my_project and install LexikJWTAuthenticationBundle with Symfony Flex composer req jwt-auth
Then I follow the Getting Started from project in Github (https://github.com/lexik/LexikJWTAuthenticationBundle/blob/master/Resources/doc/index.md#getting-started) but when I try to run the application I got this error message:

```<code>[Symfony\Component\Config\Exception\FileLoaderLoadException]
There is no extension able to load the configuration for "api_login_check" (in /home/alan/Desktop/auth/config/packages/routing.yaml). Looked for namespace "api_login_check", found "framework", "security", "lexik_jwt_authentication" in /home/alan/Desktop/auth/config/packages/routing.yaml (which is loaded in resource "/home/alan/Desktop/auth/config/packages/routing.yaml").

[Symfony\Component\DependencyInjection\Exception\InvalidArgumentException]
There is no extension able to load the configuration for "api_login_check" (in /home/alan/Desktop/auth/config/packages/routing.yaml). Looked for namespace "api_login_check", found "framework", "security", "lexik_jwt_authentication"
</code>```

I created a repository in github with the code that is getting error
https://github.com/alanoliveira/jwt_auth_test

Could someone give me some tip what I am doing wrong?

答:
I found the solution!

Firstly, in the security.conf we need to add login and api firewalls before main firewall.

```<code># config/packages/security.yaml
security:
    # https://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
    providers:
        in_memory: { memory: ~ }
    firewalls:
        login:
            pattern:  ^/api/login
            stateless: true
            anonymous: true
            form_login:
                check_path:               /api/login_check
                success_handler:          lexik_jwt_authentication.handler.authentication_success
                failure_handler:          lexik_jwt_authentication.handler.authentication_failure
                require_previous_session: false

        api:
            pattern:   ^/api
            stateless: true
            guard:
                authenticators:
                    - lexik_jwt_authentication.jwt_token_authenticator

        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: ~

            # activate different ways to authenticate

            # http_basic: ~
            # https://symfony.com/doc/current/book/security.html#a-configuring-how-your-users-will-authenticate

            # form_login: ~
            # https://symfony.com/doc/current/cookbook/security/form_login_setup.html

    access_control:
        - { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/api,       roles: IS_AUTHENTICATED_FULLY }
</code>```

Then the config of route needs to be defined in routes.yaml, and not in routing.yaml

```<code># config/routes.yaml
api_login_check:
    path: /api/login_check
</code>```

Finally we need to remove the comments of the session lines in the framework.yaml

```<code># config/packages/framework.yaml
framework:
    secret: '%env(APP_SECRET)%'
    #default_locale: en
    #csrf_protection: ~
    #http_method_override: true
    #trusted_hosts: ~
    # https://symfony.com/doc/current/reference/configuration/framework.html#handler-id
    session:
       # The native PHP session handler will be used
       handler_id: ~
    #esi: ~
    #fragments: ~
    php_errors:
        log: true
</code>```

It should do the job!

I hope it can help someone else with the same problem

Body:
I'm trying to make some experiments with JWT and PHP, but I cannot make the LexikJWTAuthenticationBundle work.

I created a Symfony project using composer composer create-project symfony/skeleton my_project and install LexikJWTAuthenticationBundle with Symfony Flex composer req jwt-auth
Then I follow the Getting Started from project in Github (https://github.com/lexik/LexikJWTAuthenticationBundle/blob/master/Resources/doc/index.md#getting-started) but when I try to run the application I got this error message:

[Symfony\Component\Config\Exception\FileLoaderLoadException]
There is no extension able to load the configuration for "api_login_check" (in /home/alan/Desktop/auth/config/packages/routing.yaml). Looked for namespace "api_login_check", found "framework", "security", "lexik_jwt_authentication" in /home/alan/Desktop/auth/config/packages/routing.yaml (which is loaded in resource "/home/alan/Desktop/auth/config/packages/routing.yaml").

[Symfony\Component\DependencyInjection\Exception\InvalidArgumentException]
There is no extension able to load the configuration for "api_login_check" (in /home/alan/Desktop/auth/config/packages/routing.yaml). Looked for namespace "api_login_check", found "framework", "security", "lexik_jwt_authentication"

I created a repository in github with the code that is getting error
https://github.com/alanoliveira/jwt_auth_test

Could someone give me some tip what I am doing wrong?

Body:
I found the solution!

Firstly, in the security.conf we need to add login and api firewalls before main firewall.

# config/packages/security.yaml
security:
    # https://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
    providers:
        in_memory: { memory: ~ }
    firewalls:
        login:
            pattern:  ^/api/login
            stateless: true
            anonymous: true
            form_login:
                check_path:               /api/login_check
                success_handler:          lexik_jwt_authentication.handler.authentication_success
                failure_handler:          lexik_jwt_authentication.handler.authentication_failure
                require_previous_session: false

        api:
            pattern:   ^/api
            stateless: true
            guard:
                authenticators:
                    - lexik_jwt_authentication.jwt_token_authenticator

        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: ~

            # activate different ways to authenticate

            # http_basic: ~
            # https://symfony.com/doc/current/book/security.html#a-configuring-how-your-users-will-authenticate

            # form_login: ~
            # https://symfony.com/doc/current/cookbook/security/form_login_setup.html

    access_control:
        - { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/api,       roles: IS_AUTHENTICATED_FULLY }

Then the config of route needs to be defined in routes.yaml, and not in routing.yaml

# config/routes.yaml
api_login_check:
    path: /api/login_check

Finally we need to remove the comments of the session lines in the framework.yaml

# config/packages/framework.yaml
framework:
    secret: '%env(APP_SECRET)%'
    #default_locale: en
    #csrf_protection: ~
    #http_method_override: true
    #trusted_hosts: ~
    # https://symfony.com/doc/current/reference/configuration/framework.html#handler-id
    session:
       # The native PHP session handler will be used
       handler_id: ~
    #esi: ~
    #fragments: ~
    php_errors:
        log: true

It should do the job!

I hope it can help someone else with the same problem


问:
two icons in tabbar | reactnavigation
I want to add some icon (small circle) next to the tabicon. How can I do this?
Maybe some png above another. So I can give a visual feedback which connection is active</p>

```<code>export default class ConnectionInfoScreen extends Component<{}> {
    static navigationOptions ={
        tabBarIcon:
            ({tintColor}: { tintColor: any }) => (
                <Image
                    source={require('../../assets/connect.png')}
                    style={[styles.icon, {tintColor: tintColor}]}
                />
            ),
    };

    render() {
        var isConnected = true;
        if (isConnected) {

            return (
                <View>
                    <Text>keine Verbindung</Text>
                </View>
            );
        }

        else {
            return (
                <View>
                    <Text>ConnectionInfo</Text>
                </View>
            );
        }
    }
}
</code>```

答:
Usually, the activeTintColor tabBarOption is used so that the icon can be rendered in a different color to indicate that it is active. Instead of tabBarIcon returning just an image, it returns some sort of Icon component which can be styled with color (This is an example of where you can get good icons like this).

But if you want to stick with images:

The tabBarIcon property is defined as :

"[a] React Element or a function that given { focused: boolean, tintColor: string } returns a React.Node, to display in tab bar."

So, if you supply focused as a parameter, you can optionally display a different image as your tabBarIcon like this:

```<code>tabBarIcon:
        ({ focused,tintColor }) => {
            if(focused){
                return (
                    <Image
                        source={require('./focused-icon.png')}
                        style={styles.icon}
                    />
                )
            }
            else{
                return(
                    <Image
                        source={require('./not-focused-icon.png')}
                        style={styles.icon}
                    />
                )
            }
        },
</code>```

Or, if you want to display another component (like a 'small circle') over your image:

```<code>tabBarIcon: ({ focused,tintColor }) => {
  if(focused){
    return (
      <View>
        <Image
          source={require('./my-icon.png')}
          style={styles.icon}
          />
          <View name="active-indicator" style={{backgroundColor:'red',width:10,height:10,borderRadius:20,position:'absolute',top:-5,left:-5}}/>
      </View>
    )
  }
  else{
    return(
    <Image
      source={require('./my-icon.png')}
      style={styles.icon}
    />
    )
  }
},
</code>```

Title: two icons in tabbar | reactnavigation

Body:
I want to add some icon (small circle) next to the tabicon. How can I do this?
Maybe some png above another. So I can give a visual feedback which connection is active

export default class ConnectionInfoScreen extends Component<{}> {
    static navigationOptions ={
        tabBarIcon:
            ({tintColor}: { tintColor: any }) => (
                <Image
                    source={require('../../assets/connect.png')}
                    style={[styles.icon, {tintColor: tintColor}]}
                />
            ),
    };

    render() {
        var isConnected = true;
        if (isConnected) {

            return (
                <View>
                    <Text>keine Verbindung</Text>
                </View>
            );
        }

        else {
            return (
                <View>
                    <Text>ConnectionInfo</Text>
                </View>
            );
        }
    }
}

Body:
Usually, the activeTintColor tabBarOption is used so that the icon can be rendered in a different color to indicate that it is active. Instead of tabBarIcon returning just an image, it returns some sort of Icon component which can be styled with color (This is an example of where you can get good icons like this).

But if you want to stick with images:

The tabBarIcon property is defined as :

"[a] React Element or a function that given { focused: boolean, tintColor: string } returns a React.Node, to display in tab bar."

So, if you supply focused as a parameter, you can optionally display a different image as your tabBarIcon like this:

tabBarIcon:
        ({ focused,tintColor }) => {
            if(focused){
                return (
                    <Image
                        source={require('./focused-icon.png')}
                        style={styles.icon}
                    />
                )
            }
            else{
                return(
                    <Image
                        source={require('./not-focused-icon.png')}
                        style={styles.icon}
                    />
                )
            }
        },

Or, if you want to display another component (like a 'small circle') over your image:

tabBarIcon: ({ focused,tintColor }) => {
  if(focused){
    return (
      <View>
        <Image
          source={require('./my-icon.png')}
          style={styles.icon}
          />
          <View name="active-indicator" style={{backgroundColor:'red',width:10,height:10,borderRadius:20,position:'absolute',top:-5,left:-5}}/>
      </View>
    )
  }
  else{
    return(
    <Image
      source={require('./my-icon.png')}
      style={styles.icon}
    />
    )
  }
},


问:
Cannot install nativescript
I'm trying to install NativeScript and I am getting this error when I do

npm i -g nativescript

npm ERR! Windows_NT 10.0.14393 npm ERR! argv "C:\Program
  Files\nodejs\node.exe"
  "C:\Users\John\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js"
  "i" "-g" "nativescript" npm ERR! node v8.9.1 npm ERR! npm  v4.0.3

npm ERR! Cannot read property 'assert-plus' of undefined

. . .

npm ERR! Cannot read property 'minimist' of undefined

when I run this command on a Mac, I get:

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: abbrev@1.1.0
  (node_modules/nativescript/node_modules/fsevents/node_modules/abbrev):
  npm WARN enoent SKIPPING OPTIONAL DEPENDENCY: ENOENT: no such file or
  directory, rename
  '/usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules/abbrev'
  -> '/usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules/.abbrev.DELETE'

npm ERR! path
  /usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules/ansi-regex
  npm ERR! code ENOENT npm ERR! errno -2 npm ERR! syscall rename npm
  ERR! enoent ENOENT: no such file or directory, rename
  '/usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules/ansi-regex'
  -> '/usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules/.ansi-regex.DELETE'
  npm ERR! enoent This is related to npm not being able to find a file.
  npm ERR! enoent

Does anyone know how to work around this? I have the latest version of Node and npm. Maybe that is my problem? Does anyone know what version would work? Thanks!

答: This was interesting to me. I had had npm 4.01 on the Windows machine and getting the lastest (npm i -g npm@latest), 5.5.1, made it work. On the Mac machine I already had 5.5.1 but rolling that back to 4.1.1 allowed the install to work. So on Windows, 5.5.1 was good but not on the Mac.</p>

Title: Cannot install nativescript


问:
Parsing optional recursive parser runs in infinite recursion
I'm currently writing a parser for ECMAScript 5 (as a toy). The standard dictates how logical or expressions should be parsed:

```<code><LogicalORExpression> :
    <LogicalANDExpression>
    <LogicalORExpression> || <LogicalANDExpression>
</code>```

basicly this is equivalent to

<logicalOrExpression> = [<logicalOrExpression> ||] <LogicalAndExpression>

but how should I parse this without running into an infite loop? My current parser obviously does:

```<code>logicalOrExpression :: Parser LogicalOrExpression
logicalOrExpression = do
    orExpr <- optional $ do
        e <- logicalOrExpression
        _ <- symbol "||"
        return e
    andExpr <- logicalAndExpression
    case orExpr of
        Just e -> return $ LogicalOrExpression (e, andExpr)
        Nothing -> return $ AndExpression andExpr
</code>```

Thanks

答: The empty string matches this parser, which I believe, causes infinite recursion in Magaparsec. I think you are missing a "term" or "boolean" somewhere in your function. If I wrote True || False what would capture the first "True"

Body:
I'm currently writing a parser for ECMAScript 5 (as a toy). The standard dictates how logical or expressions should be parsed:

<LogicalORExpression> :
    <LogicalANDExpression>
    <LogicalORExpression> || <LogicalANDExpression>

basicly this is equivalent to

<logicalOrExpression> = [<logicalOrExpression> ||] <LogicalAndExpression>

but how should I parse this without running into an infite loop? My current parser obviously does:

logicalOrExpression :: Parser LogicalOrExpression
logicalOrExpression = do
    orExpr <- optional $ do
        e <- logicalOrExpression
        _ <- symbol "||"
        return e
    andExpr <- logicalAndExpression
    case orExpr of
        Just e -> return $ LogicalOrExpression (e, andExpr)
        Nothing -> return $ AndExpression andExpr

Thanks


问:
CSS Hover not showing
Okay, so I have an image for a background that has 1px of a blur filter in the CSS.

That works.

Then, I added a CSS :hover selector to a new CSS rule that changes the blur filter to 0.

When I hover over it on the browser, however, it doesn't change the blur at all! (I went into Google Chrome Inspect Element and used the handy feature of forcing the :hover selector, and then it worked. So I know it's not the CSS that's buggy.)

How can I get this to work? It's a blur filter on a div in a header. Any ideas?

```<code>    <header>
        <div id="bgimage"></div>
        <nav>
            <a href="home.html" title="Click to go to the homepage.">Home</a>
            <span class="divider">-</span>
            <a href="cakes.html" title="Click to see types of cakes.">Types of Cake</a>
        </nav>
        <h1>Cakes</h1>
    </header>

body header {
    width:100%;
    text-align:center;
    box-shadow:0 4px 4px 4px rgba(0,0,0,0.2);
    z-index:4;
    position:relative;
    background-color:linear-gradient(CornFlowerBlue,RoyalBlue);
}
body header div#bgimage {
    background-attachment:fixed;
    background-position:center;
    background-size:cover;
    background-image:url(hydrangea-cakes-2.jpg);
    filter:blur(1px);
    position:absolute;
    width:100%;
    height:100%;
}
</code>```

The important parts of the HTML are the header and the div id="bgimage"

答:
You did not add the :hover part of the CSS but it works for me if I just add this to the CSS:

```<code>#bgimage:hover {
  filter: none;
}
</code>```

Title: CSS Hover not showing

Body:
Okay, so I have an image for a background that has 1px of a blur filter in the CSS.

That works.

Then, I added a CSS :hover selector to a new CSS rule that changes the blur filter to 0.

When I hover over it on the browser, however, it doesn't change the blur at all! (I went into Google Chrome Inspect Element and used the handy feature of forcing the :hover selector, and then it worked. So I know it's not the CSS that's buggy.)

How can I get this to work? It's a blur filter on a div in a header. Any ideas?

            Home
            -
            Types of Cake

Cakes

body header {
    width:100%;
    text-align:center;
    box-shadow:0 4px 4px 4px rgba(0,0,0,0.2);
    z-index:4;
    position:relative;
    background-color:linear-gradient(CornFlowerBlue,RoyalBlue);
}
body header div#bgimage {
    background-attachment:fixed;
    background-position:center;
    background-size:cover;
    background-image:url(hydrangea-cakes-2.jpg);
    filter:blur(1px);
    position:absolute;
    width:100%;
    height:100%;
}

The important parts of the HTML are the header and the div id="bgimage"

Body:
You did not add the :hover part of the CSS but it works for me if I just add this to the CSS:

#bgimage:hover {
  filter: none;
}


问:
Cannot read property 'getPayload' of undefined
I am implementing OAuth Google Sign in using backend  (written in node.js, express framework at Heroku). Front end is Android and it sends the token id to the server just fine. And server receives the token id correctly.

Here is the code (which is ripped off straight from Google Documents)

```<code>var auth = new GoogleAuth;
var client = new auth.OAuth2(CLIENT_ID, '', '');
    client.verifyIdToken(
        token,
        CLIENT_ID,
        // Or, if multiple clients access the backend:
        //[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3],
        function(e, login) {
            var payload = login.getPayload();
            var userid = payload['sub'];
            // If request specified a G Suite domain:
            //var domain = payload['hd'];

        });
</code>```

But at times login in undefined. Its so strange that this problem occurs 1/10 rather than for every try so that I am not able to track the source of issue. For every other 9/10 it works just fine.

Any suggestions on how to solve this?

答:
The problem in your code is that you are not checking if your callback get's any error.

The standard way in node.js to use a callback function is using two parameters - error is the first, the actual (success) returned data is the second, and the convention is that if an error exists - you should address it, and you're not gauranteed to get the data, and if everything went well- error will be null and you'll get your data.

So in your code, you are not checking that there's an error (and like you say, not always there's one).

Should be something like:

```<code>function(e, login) {
  if (e) {
     // handle error here
    return; // don't continue, you don't have login
  }
  // if we got here, login is defined
  var payload = login.getPayload();
  var userid = payload['sub'];
  // If request specified a G Suite domain:
  //var domain = payload['hd'];
});
</code>```

Body:
I am implementing OAuth Google Sign in using backend  (written in node.js, express framework at Heroku). Front end is Android and it sends the token id to the server just fine. And server receives the token id correctly.

Here is the code (which is ripped off straight from Google Documents)

var auth = new GoogleAuth;
var client = new auth.OAuth2(CLIENT_ID, '', '');
    client.verifyIdToken(
        token,
        CLIENT_ID,
        // Or, if multiple clients access the backend:
        //[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3],
        function(e, login) {
            var payload = login.getPayload();
            var userid = payload['sub'];
            // If request specified a G Suite domain:
            //var domain = payload['hd'];

        });

But at times login in undefined. Its so strange that this problem occurs 1/10 rather than for every try so that I am not able to track the source of issue. For every other 9/10 it works just fine.

Any suggestions on how to solve this?

Body:
The problem in your code is that you are not checking if your callback get's any error.

The standard way in node.js to use a callback function is using two parameters - error is the first, the actual (success) returned data is the second, and the convention is that if an error exists - you should address it, and you're not gauranteed to get the data, and if everything went well- error will be null and you'll get your data.

So in your code, you are not checking that there's an error (and like you say, not always there's one).

Should be something like:

function(e, login) {
  if (e) {
     // handle error here
    return; // don't continue, you don't have login
  }
  // if we got here, login is defined
  var payload = login.getPayload();
  var userid = payload['sub'];
  // If request specified a G Suite domain:
  //var domain = payload['hd'];
});


问:
jhipster 4 , mongodb ; relationship between entities
How can i manage relationship between  entities  with jhipster using mongoDb?
Someone have an exemple ?
I don't think that jhipster UML is the best solution .</p>

答:
Update:
You can finally use relationships on JHipster 5.4.0 or higher versions
as you can see here

Currently relationships are not supported in Jhipster for MongoDb, as you can see on the official documentation:

Relationships only work when JPA is used. If you choose to use Cassandra or MongoDB, they won’t be available.

You have to do manually using spring data mongodb. You can use @DBRef annotation that allow Mongodb to know that there is a relationship.

ContentLicense: CC BY-SA 4.0