问:
zookeeper does not run?
I wanted to run a solr cloud with solr 4.3.0.

(I am using aws ubuntu-12.04-lts micro instances)

So I followed this toturial:

which basically says, start the zookeeper and connect the solr instances to it.

Here's how I start the zookeeper.

First I copied the config like described in the tutorial

```<code>sudo cp zookeeper-3.4.5/conf/zoo_sample.cfg zookeeper-3.4.5/conf/zoo.cfg
</code>```

Then I started the zookeeper

```<code>ubuntu@ip-10-48-159-36:/opt$ sudo zookeeper-3.4.5/bin/zkServer.sh start
JMX enabled by default
Using config: /opt/zookeeper-3.4.5/bin/../conf/zoo.cfg
Starting zookeeper ... STARTED
</code>```

Looks fine so far.

I checked the status:

```<code>ubuntu@ip-10-48-159-36:/opt$ sudo zookeeper-3.4.5/bin/zkServer.sh status
JMX enabled by default
Using config: /opt/zookeeper-3.4.5/bin/../conf/zoo.cfg
Error contacting service. It is probably not running.
</code>```

Which seems a bit weird already.

If I try to connect with the client (remote as well as local), its seems to work

```<code>ubuntu@ip-10-234-223-69:/opt$ zookeeper-3.4.5/bin/zkCli.sh -server ec2-54-247-144-120.eu-west-1.compute.amazonaws.com:2181
Connecting to ec2-54-247-144-120.eu-west-1.compute.amazonaws.com:2181
2013-06-07 11:07:01,996 [myid:] - INFO  [main:Environment@100] - Client environment:zookeeper.version=3.4.5-1392090, built on 09/30/2012 17:52 GMT
2013-06-07 11:07:02,000 [myid:] - INFO  [main:Environment@100] - Client environment:host.name=ip-10-234-223-69.eu-west-1.compute.internal
2013-06-07 11:07:02,000 [myid:] - INFO  [main:Environment@100] - Client environment:java.version=1.6.0_27
2013-06-07 11:07:02,002 [myid:] - INFO  [main:Environment@100] - Client environment:java.vendor=Sun Microsystems Inc.
2013-06-07 11:07:02,003 [myid:] - INFO  [main:Environment@100] - Client environment:java.home=/usr/lib/jvm/java-6-openjdk-amd64/jre
2013-06-07 11:07:02,003 [myid:] - INFO  [main:Environment@100] - Client environment:java.class.path=/opt/zookeeper-3.4.5/bin/../build/classes:/opt/zookeeper-3.4.5/bin/../build/lib/*.jar:/opt/zookeeper-3.4.5/bin/../lib/slf4j-log4j12-1.6.1.jar:/opt/zookeeper-3.4.5/bin/../lib/slf4j-api-1.6.1.jar:/opt/zookeeper-3.4.5/bin/../lib/netty-3.2.2.Final.jar:/opt/zookeeper-3.4.5/bin/../lib/log4j-1.2.15.jar:/opt/zookeeper-3.4.5/bin/../lib/jline-0.9.94.jar:/opt/zookeeper-3.4.5/bin/../zookeeper-3.4.5.jar:/opt/zookeeper-3.4.5/bin/../src/java/lib/*.jar:/opt/zookeeper-3.4.5/bin/../conf:
2013-06-07 11:07:02,004 [myid:] - INFO  [main:Environment@100] - Client environment:java.library.path=/usr/lib/jvm/java-6-openjdk-amd64/jre/lib/amd64/server:/usr/lib/jvm/java-6-openjdk-amd64/jre/lib/amd64:/usr/lib/jvm/java-6-openjdk-amd64/jre/../lib/amd64:/usr/java/packages/lib/amd64:/usr/lib/x86_64-linux-gnu/jni:/lib/x86_64-linux-gnu:/usr/lib/x86_64-linux-gnu:/usr/lib/jni:/lib:/usr/lib
2013-06-07 11:07:02,008 [myid:] - INFO  [main:Environment@100] - Client environment:java.io.tmpdir=/tmp
2013-06-07 11:07:02,009 [myid:] - INFO  [main:Environment@100] - Client environment:java.compiler=<NA>
2013-06-07 11:07:02,018 [myid:] - INFO  [main:Environment@100] - Client environment:os.name=Linux
2013-06-07 11:07:02,019 [myid:] - INFO  [main:Environment@100] - Client environment:os.arch=amd64
2013-06-07 11:07:02,019 [myid:] - INFO  [main:Environment@100] - Client environment:os.version=3.2.0-40-virtual
2013-06-07 11:07:02,020 [myid:] - INFO  [main:Environment@100] - Client environment:user.name=ubuntu
2013-06-07 11:07:02,020 [myid:] - INFO  [main:Environment@100] - Client environment:user.home=/home/ubuntu
2013-06-07 11:07:02,021 [myid:] - INFO  [main:Environment@100] - Client environment:user.dir=/opt
2013-06-07 11:07:02,029 [myid:] - INFO  [main:ZooKeeper@438] - Initiating client connection, connectString=ec2-54-247-144-120.eu-west-1.compute.amazonaws.com:2181 sessionTimeout=30000 watcher=org.apache.zookeeper.ZooKeeperMain$MyWatcher@182d9c06
Welcome to ZooKeeper!
2013-06-07 11:07:02,074 [myid:] - INFO  [main-SendThread(ip-10-48-159-36.eu-west-1.compute.internal:2181):ClientCnxn$SendThread@966] - Opening socket connection to server ip-10-48-159-36.eu-west-1.compute.internal/10.48.159.36:2181. Will not attempt to authenticate using SASL (unknown error)
JLine support is enabled
[zk: ec2-54-247-144-120.eu-west-1.compute.amazonaws.com:2181(CONNECTING) 0] 2013-06-07 11:07:32,100 [myid:] - INFO  [main-SendThread(ip-10-48-159-36.eu-west-1.compute.internal:2181):ClientCnxn$SendThread@1083] - Client session timed out, have not heard from server in 30038ms for sessionid 0x0, closing socket connection and attempting reconnect
2013-06-07 11:07:33,204 [myid:] - INFO  [main-SendThread(ip-10-48-159-36.eu-west-1.compute.internal:2181):ClientCnxn$SendThread@966] - Opening socket connection to server ip-10-48-159-36.eu-west-1.compute.internal/10.48.159.36:2181. Will not attempt to authenticate using SASL (unknown error)
</code>```

Now I tried to connect a solr instance to it. In the web interface of tomcat7 it only tells me "503 - Server is shutting down", so I checked the solr logs

```<code>2013-06-07 11:16:36,065 [pool-2-thread-1] INFO  org.apache.solr.servlet.SolrDispatchFilter . SolrDispatchFilter.init()
2013-06-07 11:16:36,100 [pool-2-thread-1] INFO  org.apache.solr.core.SolrResourceLoader . Using JNDI solr.home: /opt/solr-4.3.0/example/solr
2013-06-07 11:16:36,132 [pool-2-thread-1] INFO  org.apache.solr.core.CoreContainer . looking for solr config file: /opt/solr-4.3.0/example/solr/solr.xml
2013-06-07 11:16:36,138 [pool-2-thread-1] INFO  org.apache.solr.core.CoreContainer . New CoreContainer 1285984216
2013-06-07 11:16:36,146 [pool-2-thread-1] INFO  org.apache.solr.core.CoreContainer . Loading CoreContainer using Solr Home: '/opt/solr-4.3.0/example/solr/'
2013-06-07 11:16:36,152 [pool-2-thread-1] INFO  org.apache.solr.core.SolrResourceLoader . new SolrResourceLoader for directory: '/opt/solr-4.3.0/example/solr/'
2013-06-07 11:16:36,567 [pool-2-thread-1] INFO  org.apache.solr.handler.component.HttpShardHandlerFactory . Setting socketTimeout to: 0
2013-06-07 11:16:36,568 [pool-2-thread-1] INFO  org.apache.solr.handler.component.HttpShardHandlerFactory . Setting urlScheme to: http://
2013-06-07 11:16:36,568 [pool-2-thread-1] INFO  org.apache.solr.handler.component.HttpShardHandlerFactory . Setting connTimeout to: 0
2013-06-07 11:16:36,568 [pool-2-thread-1] INFO  org.apache.solr.handler.component.HttpShardHandlerFactory . Setting maxConnectionsPerHost to: 20
2013-06-07 11:16:36,568 [pool-2-thread-1] INFO  org.apache.solr.handler.component.HttpShardHandlerFactory . Setting corePoolSize to: 0
2013-06-07 11:16:36,568 [pool-2-thread-1] INFO  org.apache.solr.handler.component.HttpShardHandlerFactory . Setting maximumPoolSize to: 2147483647
2013-06-07 11:16:36,568 [pool-2-thread-1] INFO  org.apache.solr.handler.component.HttpShardHandlerFactory . Setting maxThreadIdleTime to: 5
2013-06-07 11:16:36,569 [pool-2-thread-1] INFO  org.apache.solr.handler.component.HttpShardHandlerFactory . Setting sizeOfQueue to: -1
2013-06-07 11:16:36,569 [pool-2-thread-1] INFO  org.apache.solr.handler.component.HttpShardHandlerFactory . Setting fairnessPolicy to: false
2013-06-07 11:16:36,578 [pool-2-thread-1] INFO  org.apache.solr.client.solrj.impl.HttpClientUtil . Creating new http client, config:maxConnectionsPerHost=20&maxConnections=10000&socketTimeout=0&connTimeout=0&retry=false
2013-06-07 11:16:36,879 [pool-2-thread-1] INFO  org.apache.solr.core.CoreContainer . Registering Log Listener
2013-06-07 11:16:36,881 [pool-2-thread-1] INFO  org.apache.solr.core.CoreContainer . Zookeeper client=ec2-54-247-144-120.eu-west-1.compute.amazonaws.com:2181
2013-06-07 11:16:36,888 [pool-2-thread-1] INFO  org.apache.solr.client.solrj.impl.HttpClientUtil . Creating new http client, config:maxConnections=500&maxConnectionsPerHost=16&socketTimeout=0&connTimeout=0
2013-06-07 11:16:37,040 [pool-2-thread-1] INFO  org.apache.solr.common.cloud.ConnectionManager . Waiting for client to connect to ZooKeeper
2013-06-07 11:16:52,046 [pool-2-thread-1] ERROR org.apache.solr.servlet.SolrDispatchFilter . Could not start Solr. Check solr/home property and the logs
2013-06-07 11:16:52,103 [pool-2-thread-1] ERROR org.apache.solr.core.SolrCore . null:java.lang.RuntimeException: java.util.concurrent.TimeoutException: Could not connect to ZooKeeper ec2-54-247-144-120.eu-west-1.compute.amazonaws.com:2181 within 15000 ms
    at org.apache.solr.common.cloud.SolrZkClient.<init>(SolrZkClient.java:130)
    at org.apache.solr.common.cloud.SolrZkClient.<init>(SolrZkClient.java:88)
    at org.apache.solr.cloud.ZkController.<init>(ZkController.java:170)
    at org.apache.solr.core.CoreContainer.initZooKeeper(CoreContainer.java:242)
    at org.apache.solr.core.CoreContainer.load(CoreContainer.java:495)
    at org.apache.solr.core.CoreContainer.load(CoreContainer.java:358)
    at org.apache.solr.core.CoreContainer$Initializer.initialize(CoreContainer.java:326)
    at org.apache.solr.servlet.SolrDispatchFilter.init(SolrDispatchFilter.java:124)
    at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:277)
    at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:258)
    at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:382)
    at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:103)
    at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4638)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5294)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:895)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:871)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:615)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:649)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1581)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1146)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:679)
Caused by: java.util.concurrent.TimeoutException: Could not connect to ZooKeeper ec2-54-247-144-120.eu-west-1.compute.amazonaws.com:2181 within 15000 ms
    at org.apache.solr.common.cloud.ConnectionManager.waitForConnected(ConnectionManager.java:173)
    at org.apache.solr.common.cloud.SolrZkClient.<init>(SolrZkClient.java:127)
    ... 25 more

2013-06-07 11:16:52,104 [pool-2-thread-1] INFO  org.apache.solr.servlet.SolrDispatchFilter . SolrDispatchFilter.init() done
</code>```

What does it tell me?
On the same instance I just connected with the client successfully... :(

So where is the problem?

[Edit:]
Instead of using amazons ec**.amazon.* address I used the network addresses 10.X.X.X for telling solr where the zookeeper is.
It seems to work.

答: try to stop your solr instance solr.shutdown() so that you can create new CloudSolrServer instance for each thread

Title: zookeeper does not run?

Body:
I wanted to run a solr cloud with solr 4.3.0.

(I am using aws ubuntu-12.04-lts micro instances)

So I followed this toturial:

which basically says, start the zookeeper and connect the solr instances to it.

Here's how I start the zookeeper.

First I copied the config like described in the tutorial

sudo cp zookeeper-3.4.5/conf/zoo_sample.cfg zookeeper-3.4.5/conf/zoo.cfg

Then I started the zookeeper

ubuntu@ip-10-48-159-36:/opt$ sudo zookeeper-3.4.5/bin/zkServer.sh start
JMX enabled by default
Using config: /opt/zookeeper-3.4.5/bin/../conf/zoo.cfg
Starting zookeeper ... STARTED

Looks fine so far.

I checked the status:

ubuntu@ip-10-48-159-36:/opt$ sudo zookeeper-3.4.5/bin/zkServer.sh status
JMX enabled by default
Using config: /opt/zookeeper-3.4.5/bin/../conf/zoo.cfg
Error contacting service. It is probably not running.

Which seems a bit weird already.

If I try to connect with the client (remote as well as local), its seems to work

ubuntu@ip-10-234-223-69:/opt$ zookeeper-3.4.5/bin/zkCli.sh -server ec2-54-247-144-120.eu-west-1.compute.amazonaws.com:2181
Connecting to ec2-54-247-144-120.eu-west-1.compute.amazonaws.com:2181
2013-06-07 11:07:01,996 [myid:] - INFO  [main:Environment@100] - Client environment:zookeeper.version=3.4.5-1392090, built on 09/30/2012 17:52 GMT
2013-06-07 11:07:02,000 [myid:] - INFO  [main:Environment@100] - Client environment:host.name=ip-10-234-223-69.eu-west-1.compute.internal
2013-06-07 11:07:02,000 [myid:] - INFO  [main:Environment@100] - Client environment:java.version=1.6.0_27
2013-06-07 11:07:02,002 [myid:] - INFO  [main:Environment@100] - Client environment:java.vendor=Sun Microsystems Inc.
2013-06-07 11:07:02,003 [myid:] - INFO  [main:Environment@100] - Client environment:java.home=/usr/lib/jvm/java-6-openjdk-amd64/jre
2013-06-07 11:07:02,003 [myid:] - INFO  [main:Environment@100] - Client environment:java.class.path=/opt/zookeeper-3.4.5/bin/../build/classes:/opt/zookeeper-3.4.5/bin/../build/lib/*.jar:/opt/zookeeper-3.4.5/bin/../lib/slf4j-log4j12-1.6.1.jar:/opt/zookeeper-3.4.5/bin/../lib/slf4j-api-1.6.1.jar:/opt/zookeeper-3.4.5/bin/../lib/netty-3.2.2.Final.jar:/opt/zookeeper-3.4.5/bin/../lib/log4j-1.2.15.jar:/opt/zookeeper-3.4.5/bin/../lib/jline-0.9.94.jar:/opt/zookeeper-3.4.5/bin/../zookeeper-3.4.5.jar:/opt/zookeeper-3.4.5/bin/../src/java/lib/*.jar:/opt/zookeeper-3.4.5/bin/../conf:
2013-06-07 11:07:02,004 [myid:] - INFO  [main:Environment@100] - Client environment:java.library.path=/usr/lib/jvm/java-6-openjdk-amd64/jre/lib/amd64/server:/usr/lib/jvm/java-6-openjdk-amd64/jre/lib/amd64:/usr/lib/jvm/java-6-openjdk-amd64/jre/../lib/amd64:/usr/java/packages/lib/amd64:/usr/lib/x86_64-linux-gnu/jni:/lib/x86_64-linux-gnu:/usr/lib/x86_64-linux-gnu:/usr/lib/jni:/lib:/usr/lib
2013-06-07 11:07:02,008 [myid:] - INFO  [main:Environment@100] - Client environment:java.io.tmpdir=/tmp
2013-06-07 11:07:02,009 [myid:] - INFO  [main:Environment@100] - Client environment:java.compiler=<NA>
2013-06-07 11:07:02,018 [myid:] - INFO  [main:Environment@100] - Client environment:os.name=Linux
2013-06-07 11:07:02,019 [myid:] - INFO  [main:Environment@100] - Client environment:os.arch=amd64
2013-06-07 11:07:02,019 [myid:] - INFO  [main:Environment@100] - Client environment:os.version=3.2.0-40-virtual
2013-06-07 11:07:02,020 [myid:] - INFO  [main:Environment@100] - Client environment:user.name=ubuntu
2013-06-07 11:07:02,020 [myid:] - INFO  [main:Environment@100] - Client environment:user.home=/home/ubuntu
2013-06-07 11:07:02,021 [myid:] - INFO  [main:Environment@100] - Client environment:user.dir=/opt
2013-06-07 11:07:02,029 [myid:] - INFO  [main:ZooKeeper@438] - Initiating client connection, connectString=ec2-54-247-144-120.eu-west-1.compute.amazonaws.com:2181 sessionTimeout=30000 watcher=org.apache.zookeeper.ZooKeeperMain$MyWatcher@182d9c06
Welcome to ZooKeeper!
2013-06-07 11:07:02,074 [myid:] - INFO  [main-SendThread(ip-10-48-159-36.eu-west-1.compute.internal:2181):ClientCnxn$SendThread@966] - Opening socket connection to server ip-10-48-159-36.eu-west-1.compute.internal/10.48.159.36:2181. Will not attempt to authenticate using SASL (unknown error)
JLine support is enabled
[zk: ec2-54-247-144-120.eu-west-1.compute.amazonaws.com:2181(CONNECTING) 0] 2013-06-07 11:07:32,100 [myid:] - INFO  [main-SendThread(ip-10-48-159-36.eu-west-1.compute.internal:2181):ClientCnxn$SendThread@1083] - Client session timed out, have not heard from server in 30038ms for sessionid 0x0, closing socket connection and attempting reconnect
2013-06-07 11:07:33,204 [myid:] - INFO  [main-SendThread(ip-10-48-159-36.eu-west-1.compute.internal:2181):ClientCnxn$SendThread@966] - Opening socket connection to server ip-10-48-159-36.eu-west-1.compute.internal/10.48.159.36:2181. Will not attempt to authenticate using SASL (unknown error)

Now I tried to connect a solr instance to it. In the web interface of tomcat7 it only tells me "503 - Server is shutting down", so I checked the solr logs

2013-06-07 11:16:36,065 [pool-2-thread-1] INFO  org.apache.solr.servlet.SolrDispatchFilter . SolrDispatchFilter.init()
2013-06-07 11:16:36,100 [pool-2-thread-1] INFO  org.apache.solr.core.SolrResourceLoader . Using JNDI solr.home: /opt/solr-4.3.0/example/solr
2013-06-07 11:16:36,132 [pool-2-thread-1] INFO  org.apache.solr.core.CoreContainer . looking for solr config file: /opt/solr-4.3.0/example/solr/solr.xml
2013-06-07 11:16:36,138 [pool-2-thread-1] INFO  org.apache.solr.core.CoreContainer . New CoreContainer 1285984216
2013-06-07 11:16:36,146 [pool-2-thread-1] INFO  org.apache.solr.core.CoreContainer . Loading CoreContainer using Solr Home: '/opt/solr-4.3.0/example/solr/'
2013-06-07 11:16:36,152 [pool-2-thread-1] INFO  org.apache.solr.core.SolrResourceLoader . new SolrResourceLoader for directory: '/opt/solr-4.3.0/example/solr/'
2013-06-07 11:16:36,567 [pool-2-thread-1] INFO  org.apache.solr.handler.component.HttpShardHandlerFactory . Setting socketTimeout to: 0
2013-06-07 11:16:36,568 [pool-2-thread-1] INFO  org.apache.solr.handler.component.HttpShardHandlerFactory . Setting urlScheme to: http://
2013-06-07 11:16:36,568 [pool-2-thread-1] INFO  org.apache.solr.handler.component.HttpShardHandlerFactory . Setting connTimeout to: 0
2013-06-07 11:16:36,568 [pool-2-thread-1] INFO  org.apache.solr.handler.component.HttpShardHandlerFactory . Setting maxConnectionsPerHost to: 20
2013-06-07 11:16:36,568 [pool-2-thread-1] INFO  org.apache.solr.handler.component.HttpShardHandlerFactory . Setting corePoolSize to: 0
2013-06-07 11:16:36,568 [pool-2-thread-1] INFO  org.apache.solr.handler.component.HttpShardHandlerFactory . Setting maximumPoolSize to: 2147483647
2013-06-07 11:16:36,568 [pool-2-thread-1] INFO  org.apache.solr.handler.component.HttpShardHandlerFactory . Setting maxThreadIdleTime to: 5
2013-06-07 11:16:36,569 [pool-2-thread-1] INFO  org.apache.solr.handler.component.HttpShardHandlerFactory . Setting sizeOfQueue to: -1
2013-06-07 11:16:36,569 [pool-2-thread-1] INFO  org.apache.solr.handler.component.HttpShardHandlerFactory . Setting fairnessPolicy to: false
2013-06-07 11:16:36,578 [pool-2-thread-1] INFO  org.apache.solr.client.solrj.impl.HttpClientUtil . Creating new http client, config:maxConnectionsPerHost=20&maxConnections=10000&socketTimeout=0&connTimeout=0&retry=false
2013-06-07 11:16:36,879 [pool-2-thread-1] INFO  org.apache.solr.core.CoreContainer . Registering Log Listener
2013-06-07 11:16:36,881 [pool-2-thread-1] INFO  org.apache.solr.core.CoreContainer . Zookeeper client=ec2-54-247-144-120.eu-west-1.compute.amazonaws.com:2181
2013-06-07 11:16:36,888 [pool-2-thread-1] INFO  org.apache.solr.client.solrj.impl.HttpClientUtil . Creating new http client, config:maxConnections=500&maxConnectionsPerHost=16&socketTimeout=0&connTimeout=0
2013-06-07 11:16:37,040 [pool-2-thread-1] INFO  org.apache.solr.common.cloud.ConnectionManager . Waiting for client to connect to ZooKeeper
2013-06-07 11:16:52,046 [pool-2-thread-1] ERROR org.apache.solr.servlet.SolrDispatchFilter . Could not start Solr. Check solr/home property and the logs
2013-06-07 11:16:52,103 [pool-2-thread-1] ERROR org.apache.solr.core.SolrCore . null:java.lang.RuntimeException: java.util.concurrent.TimeoutException: Could not connect to ZooKeeper ec2-54-247-144-120.eu-west-1.compute.amazonaws.com:2181 within 15000 ms
    at org.apache.solr.common.cloud.SolrZkClient.<init>(SolrZkClient.java:130)
    at org.apache.solr.common.cloud.SolrZkClient.<init>(SolrZkClient.java:88)
    at org.apache.solr.cloud.ZkController.<init>(ZkController.java:170)
    at org.apache.solr.core.CoreContainer.initZooKeeper(CoreContainer.java:242)
    at org.apache.solr.core.CoreContainer.load(CoreContainer.java:495)
    at org.apache.solr.core.CoreContainer.load(CoreContainer.java:358)
    at org.apache.solr.core.CoreContainer$Initializer.initialize(CoreContainer.java:326)
    at org.apache.solr.servlet.SolrDispatchFilter.init(SolrDispatchFilter.java:124)
    at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:277)
    at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:258)
    at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:382)
    at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:103)
    at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4638)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5294)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:895)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:871)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:615)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:649)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1581)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1146)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:679)
Caused by: java.util.concurrent.TimeoutException: Could not connect to ZooKeeper ec2-54-247-144-120.eu-west-1.compute.amazonaws.com:2181 within 15000 ms
    at org.apache.solr.common.cloud.ConnectionManager.waitForConnected(ConnectionManager.java:173)
    at org.apache.solr.common.cloud.SolrZkClient.<init>(SolrZkClient.java:127)
    ... 25 more

2013-06-07 11:16:52,104 [pool-2-thread-1] INFO  org.apache.solr.servlet.SolrDispatchFilter . SolrDispatchFilter.init() done

What does it tell me?
On the same instance I just connected with the client successfully... :(

So where is the problem?

[Edit:]
Instead of using amazons ec**.amazon.* address I used the network addresses 10.X.X.X for telling solr where the zookeeper is.
It seems to work.


来源: stackexchange

问:
COND clause with test only
When COND is given only one test clause and nothing else at all it always returns the test result:

```<code> CL-USER> (cond (t))
    T
 CL-USER>  (cond ((> 5 10)))
    NIL
</code>```

Isn't COND just a way to write IF statements?
This doesn't hold for this as when rewriting  COND with  test only:

```<code>    CL-USER> (if (> 5 1))
    error while parsing arguments to DESTRUCTURING-BIND:
  too few elements in
    ((> 5 1))
  to satisfy lambda list
    (SB-IMPL::TEST SB-IMPL::THEN &OPTIONAL SB-IMPL::ELSE):
  between 2 and 3 expected, but got 1
</code>```

If it is this way then how does  COND exactly transform every clause into IF version?

答:
When COND is given only one test clause and nothing else at all it always returns the test result:

That's right. According to the HyperSpec entry on cond:

results---the values of the forms in the first clause whose test-form yields true, or the primary value of the test-form if there are no forms in that clause, or else nil if no test-form yields true.

Isn't COND just a way to write IF statements?

Well, cond is declared to be a macro, and if to be a special operator, so you can think of it that way, although the expansion of cond isn't defined specifically. But if is defined with syntax that requires a then-part, whereas cond isn't.  Here's what a cond clause with no forms expands to (in SBCL):

```<code>CL-USER> (pprint (macroexpand '(cond ((+ 2 3)))))

(LET ((#:G1013 (+ 2 3)))
  (IF #:G1013
      #:G1013
      (COND)))
</code>```

The value of the form is saved in a value and then used as the then-part. When there are forms in the clause, they're wrapped in a progn (which returns the value of its last form):

```<code>CL-USER> (pprint (macroexpand
                  '(cond
                    ((= 2 3) 42 78)
                    ((+ 2 3))
                    ((= 4 5) (print 'something-else)))))

(IF (= 2 3)
    (PROGN 42 78)
    (COND ((+ 2 3)) ((= 4 5) (PRINT 'SOMETHING-ELSE))))
</code>```

ContentLicense: CC BY-SA 3.0

Title: COND clause with test only

Body:
When COND is given only one test clause and nothing else at all it always returns the test result:

 CL-USER> (cond (t))
    T
 CL-USER>  (cond ((> 5 10)))
    NIL

Isn't COND just a way to write IF statements?
This doesn't hold for this as when rewriting  COND with  test only:

    CL-USER> (if (> 5 1))
    error while parsing arguments to DESTRUCTURING-BIND:
  too few elements in
    ((> 5 1))
  to satisfy lambda list
    (SB-IMPL::TEST SB-IMPL::THEN &OPTIONAL SB-IMPL::ELSE):
  between 2 and 3 expected, but got 1

If it is this way then how does  COND exactly transform every clause into IF version?

Body:
When COND is given only one test clause and nothing else at all it always returns the test result:

That's right. According to the HyperSpec entry on cond:

results---the values of the forms in the first clause whose test-form yields true, or the primary value of the test-form if there are no forms in that clause, or else nil if no test-form yields true.

Isn't COND just a way to write IF statements?

Well, cond is declared to be a macro, and if to be a special operator, so you can think of it that way, although the expansion of cond isn't defined specifically. But if is defined with syntax that requires a then-part, whereas cond isn't.  Here's what a cond clause with no forms expands to (in SBCL):

CL-USER> (pprint (macroexpand '(cond ((+ 2 3)))))

(LET ((#:G1013 (+ 2 3)))
  (IF #:G1013
      #:G1013
      (COND)))

The value of the form is saved in a value and then used as the then-part. When there are forms in the clause, they're wrapped in a progn (which returns the value of its last form):

CL-USER> (pprint (macroexpand
                  '(cond
                    ((= 2 3) 42 78)
                    ((+ 2 3))
                    ((= 4 5) (print 'something-else)))))

(IF (= 2 3)
    (PROGN 42 78)
    (COND ((+ 2 3)) ((= 4 5) (PRINT 'SOMETHING-ELSE))))


问:
How to open Aurora DB Port only for Load Balancer
I am running the load balancer for ec2 machines and there is separate  Aurora RDS is running. They both are in same region. I want to open rds default port only for aws classic load balancer. I am can't find the option in security group and there is no IP for load balancer for which I can open port for RDS. Please help me to resolve this issue. I want to open the port of RDS only for my loadbalacer not for all in RDS security group. Can someone please help to resolve this issue?
Thanks</p>

答: Solution of this problem is to specify the security group id of you ec2 machines in RDS inbound security rule. Thanks @MarkB</p>


问:
Using slick carousel in SPFx project. I am loading the Library but getting some weird console errors
I am referencing the CSS and JS files like this:

```<code>    SPComponentLoader.loadCss('../node_modules/slick-carousel/slick/slick.css');
    SPComponentLoader.loadCss('../node_modules/slick-carousel/slick/slick-theme.css');
    SPComponentLoader.loadScript('../node_modules/slick-carousel/slick/slick.min.js');
</code>```

When I go into dev tools in chrome and view sources I can go in and all of the files are there.

However in the console I am getting the following errors:

```<code>Failed to load resource: net::ERR_NAME_NOT_RESOLVED

Uncaught (in promise) Error: Error: Unable to load script https://relative-path.invalid/jquery
    Error loading https://relative-path.invalid/jquery as "jquery" from https://localhost:4321/node_modules/slick-carousel/slick/slick.min.js
</code>```

This is when referencing jQuery through their CDN.  I have also tried referencing it through TypeScripts import statement and using the .loadScript method I am using above.

Does anyone know what is going wrong?

答:
Importing the jQUery like so

```<code>import * as $ from 'jquery';
</code>```

My class constructor

```<code>public constructor() {
    super();

    SPComponentLoader.loadCss('../../node_modules/slick-carousel/slick/slick.css');
    SPComponentLoader.loadCss('../../node_modules/slick-carousel/slick/slick-theme.css');
  }
</code>```

My render method:

```<code>public render(): void {
    this.domElement.innerHTML = `
      <div class="container">
        <div class="your-class">
          <div>your content</div>
          <div>your content</div>
          <div>your content</div>
        </div>
      </div>
      `;

      require('../../../node_modules/slick-carousel/slick/slick.js');

      $('.your-class').slick();

  }
</code>```

It's ugly and there's no arrow buttons but I can make it slide by dragging it with my mouse.

Body:
I am referencing the CSS and JS files like this:

    SPComponentLoader.loadCss('../node_modules/slick-carousel/slick/slick.css');
    SPComponentLoader.loadCss('../node_modules/slick-carousel/slick/slick-theme.css');
    SPComponentLoader.loadScript('../node_modules/slick-carousel/slick/slick.min.js');

When I go into dev tools in chrome and view sources I can go in and all of the files are there.

However in the console I am getting the following errors:

Failed to load resource: net::ERR_NAME_NOT_RESOLVED

Uncaught (in promise) Error: Error: Unable to load script https://relative-path.invalid/jquery
    Error loading https://relative-path.invalid/jquery as "jquery" from https://localhost:4321/node_modules/slick-carousel/slick/slick.min.js

This is when referencing jQuery through their CDN.  I have also tried referencing it through TypeScripts import statement and using the .loadScript method I am using above.

Does anyone know what is going wrong?

Body:
Importing the jQUery like so

import * as $ from 'jquery';

My class constructor

public constructor() {
    super();

    SPComponentLoader.loadCss('../../node_modules/slick-carousel/slick/slick.css');
    SPComponentLoader.loadCss('../../node_modules/slick-carousel/slick/slick-theme.css');
  }

My render method:

public render(): void {
    this.domElement.innerHTML = `
      <div class="container">
        <div class="your-class">
          <div>your content</div>
          <div>your content</div>
          <div>your content</div>
        </div>
      </div>
      `;

      require('../../../node_modules/slick-carousel/slick/slick.js');

      $('.your-class').slick();

  }

It's ugly and there's no arrow buttons but I can make it slide by dragging it with my mouse.


问:
Using Socket.io with Sequelize
I am trying to use Socket.io and Sequelize to create a chat app. Socket.io will handle the socket to allow for instant messaging. Sequelize will handle storing the messages so when you refresh the screen you still have your messages.

What is happening is that on localhost my socket works, but it does not send the messages to the database. When I put it onto Heroku, my database worked, but it does not use the sockets.

My socket is located in app.js and my database route is located in routes/messages.js.

I have been working on this bug for a while now and I have been trying to get help with it. I think the best way to share this is with my markdown I created detailing my efforts to fix my bug that can be found at here. My repo for this can be found here.

答:
There are a few different parts that you need to distinguish:

the HTTP server, in your code represented by the variable http

the Express app, represented by app

the Socket.IO server, represented by io

a Socket.IO (client) connection (see below)

The HTTP server directs "normal" HTTP requests to the Express app, which will handle them according to the middleware and routes that are set up. A router handler gets called with (at least) two arguments, generally called req and res, to represent the (incoming) HTTP request and the (outgoing) HTTP response.

The Socket.IO server gets to handle specific Socket.IO requests, which get sent to the server by the Socket.IO client (running in the browser). When such a client sets up a connection with the server, the connection event gets triggered on the server. Any handlers for this event will get passed an argument, generally called socket, that represents the (bidirectional) connection with that client.

That Socket.IO connection can receive messages (sent from the client running in the browser), which trigger events on the socket. You can install a handler to listen for particular messages (like "chat message"), which will receive, as argument, the data that was sent to it by the client.

The issue in your code seems to be with setting up everything to handle those chat messages. The correct setup order would be:

listen on the Socket.IO server for connection events

when such an event is received, add a listener for the chat message event on the connection

when such an event is received, write the data to the database.

In code:

```<code>// Listen for new client connections.
io.on('connection', function(socket) {

  // Listen for the client to send a _"chat message"_ message.
  socket.on('chat message', function(data) {

    // Store the data in the database.
    models.Messages.create({
      message  : data.message,
      username : data.username
    });

  });
});
</code>```

As you can see, req and res aren't available inside of those Socket.IO event handlers, because those are only used for normal HTTP requests.

Also, as opposed to HTTP, you don't necessarily have to send anything back to the client when you have received a message, so I left that part out. The handler above only writes the message data to the database (it also doesn't check for, or handle, errors, which eventually you should add).

Title: Using Socket.io with Sequelize

Body:
There are a few different parts that you need to distinguish:

the HTTP server, in your code represented by the variable http

the Express app, represented by app

the Socket.IO server, represented by io

a Socket.IO (client) connection (see below)

The HTTP server directs "normal" HTTP requests to the Express app, which will handle them according to the middleware and routes that are set up. A router handler gets called with (at least) two arguments, generally called req and res, to represent the (incoming) HTTP request and the (outgoing) HTTP response.

The Socket.IO server gets to handle specific Socket.IO requests, which get sent to the server by the Socket.IO client (running in the browser). When such a client sets up a connection with the server, the connection event gets triggered on the server. Any handlers for this event will get passed an argument, generally called socket, that represents the (bidirectional) connection with that client.

That Socket.IO connection can receive messages (sent from the client running in the browser), which trigger events on the socket. You can install a handler to listen for particular messages (like "chat message"), which will receive, as argument, the data that was sent to it by the client.

The issue in your code seems to be with setting up everything to handle those chat messages. The correct setup order would be:

listen on the Socket.IO server for connection events

when such an event is received, add a listener for the chat message event on the connection

when such an event is received, write the data to the database.

In code:

// Listen for new client connections.
io.on('connection', function(socket) {

  // Listen for the client to send a _"chat message"_ message.
  socket.on('chat message', function(data) {

    // Store the data in the database.
    models.Messages.create({
      message  : data.message,
      username : data.username
    });

  });
});

As you can see, req and res aren't available inside of those Socket.IO event handlers, because those are only used for normal HTTP requests.

Also, as opposed to HTTP, you don't necessarily have to send anything back to the client when you have received a message, so I left that part out. The handler above only writes the message data to the database (it also doesn't check for, or handle, errors, which eventually you should add).


问:
Universe basic convert a select list to an array?
I have one major select list in a program

EXECUTE 'SELECT PRODUCTS WITH DEL.DATE <= "':EOM.DATE;'"' CAPTURING OUTPUT

I then want to covert the select list to an array, is there a Universe basic function to do this or do I need to write a function?

答:
Use READLIST to read the contents of your active select list into a field delimited (@FM) dynamic array. This is a paradigm I employ when working with multiple select lists and the payloads aren't too large. You can also select into a different list other than the default of 0 but that gets a bit messy intellectually.

```<code>EXECUTE 'SELECT PRODUCTS WITH DEL.DATE <= "':EOM.DATE;'"' CAPTURING OUTPUT
READLIST PRODUCTS.LIST ELSE PRODUCTS.LIST = ''
PRODUCTS.COUNT = DCOUNT(PRODUCTS.LIST,@FM)
FOR X=1 TO PRODUCTS.COUNT
   ID.PRODUCTS = PRODUCTS.LIST<X>
   ;* Your per ID magic goes here
NEXT X
</code>```

Good luck!

Body:
Use READLIST to read the contents of your active select list into a field delimited (@FM) dynamic array. This is a paradigm I employ when working with multiple select lists and the payloads aren't too large. You can also select into a different list other than the default of 0 but that gets a bit messy intellectually.

EXECUTE 'SELECT PRODUCTS WITH DEL.DATE <= "':EOM.DATE;'"' CAPTURING OUTPUT
READLIST PRODUCTS.LIST ELSE PRODUCTS.LIST = ''
PRODUCTS.COUNT = DCOUNT(PRODUCTS.LIST,@FM)
FOR X=1 TO PRODUCTS.COUNT
   ID.PRODUCTS = PRODUCTS.LIST<X>
   ;* Your per ID magic goes here
NEXT X

Good luck!


问:
Is this the best/secure method for encryption in Java?
I am new in security and I'm wondering if I can make my program better, like changing or adding something to make it better ( more secure )

(I have doubt from the program output)

Here is the output:

```<code>Encrypted Message: +g@þóv«5Ùû`ž
keybyte: [B@71e7a66b
Original string: Message
Original string (Hex): [B@2ac1fdc4
</code>```

Here is the code:

```<code>public class AES {

  public static void main(String ... args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
    final String Algo="AES";
    String key = "aaaaaaaaaaaaaaaa";
    byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);

    MessageDigest sha= MessageDigest.getInstance("SHA-1");
    keyBytes=sha.digest(keyBytes);
    keyBytes=Arrays.copyOf(keyBytes, 16);

    SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, Algo);
    Cipher cipher = Cipher.getInstance(Algo);
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
    byte[] ciphertext = cipher.doFinal("Message".getBytes());
    System.out.println("Encrypted Message: " +new String(ciphertext));

    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
    byte[] original = cipher.doFinal(ciphertext);
    String originalString = new String(original);
    System.out.println("keybyte: "+keyBytes);
    System.out.println("Original string: " + originalString + "\nOriginal string (Hex): " +original);
  }
}
</code>```

答:
No, this code is pretty terrible:

Your key is fixed and a string that is then hashed. This looks to me like your key is actually supposed to be a password. A single hash is not enough to derive a key from a password. You need to use a strong hashing scheme like PBKDF2, bcrypt, scrypt and Argon2. Be sure to use a high cost factor/iteration count. It is common to choose the cost so that a single iteration takes at least 100ms. See more: How to securely hash passwords?

Always use a fully qualified Cipher string. Cipher.getInstance("AES"); may result in different ciphers depending on the default security provider. It most likely results in "AES/ECB/PKCS5Padding", but it doesn't have to be. If it changes, you'll lose compatibility between different JVMs. For reference: Java default Crypto/AES behavior

ECB mode is pretty bad. It's deterministic and therefore not semantically secure. You should at the very least use a randomized mode like CBC or CTR.

Without authentication you have the threat of not detecting (malicious) modifications of your ciphertexts. It is better to authenticate your ciphertexts so that attacks like a padding oracle attack are not possible. This can be done with authenticated modes like GCM or EAX, or with an encrypt-then-MAC scheme through HMAC with a strong hash function such as SHA-256.

Because of these issues you should use a library instead. Try JNCryptor or this library.

Body:
I am new in security and I'm wondering if I can make my program better, like changing or adding something to make it better ( more secure )

(I have doubt from the program output)

Here is the output:

Encrypted Message: +g@þóv«5Ùû`ž
keybyte: [B@71e7a66b
Original string: Message
Original string (Hex): [B@2ac1fdc4

Here is the code:

public class AES {

  public static void main(String ... args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
    final String Algo="AES";
    String key = "aaaaaaaaaaaaaaaa";
    byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);

    MessageDigest sha= MessageDigest.getInstance("SHA-1");
    keyBytes=sha.digest(keyBytes);
    keyBytes=Arrays.copyOf(keyBytes, 16);

    SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, Algo);
    Cipher cipher = Cipher.getInstance(Algo);
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
    byte[] ciphertext = cipher.doFinal("Message".getBytes());
    System.out.println("Encrypted Message: " +new String(ciphertext));

    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
    byte[] original = cipher.doFinal(ciphertext);
    String originalString = new String(original);
    System.out.println("keybyte: "+keyBytes);
    System.out.println("Original string: " + originalString + "\nOriginal string (Hex): " +original);
  }
}


问:
Converting C code to Java code
I was giving some c code to convert to java code.  implement three different methods of generating all N!
permutations of N elements in Java. The code I provided is my converted c code to java, I was successful up until this line of code, swap((n & 0x01) ? 1 : i, n);...in the permute3 method, Im not entirely sure what it is doing or means and i need to know how to write the equivalent in java.</p>

```<code>public class Permute {

    public static final long MILLION = 1000000L;

    static int N;
    static char p[];
    static int[][] table =   { {0}, {0, 1}, {0, 1, 1}, {0, 1, 2, 3},
                  {0, 3, 1, 3, 1},
                  {0, 3, 4, 3, 2, 3},
                  {0, 5, 3, 1, 5, 3, 1},
                  {0, 5, 2, 7, 2, 1, 2, 3},
                  {0, 7, 1, 5, 5, 3, 3, 7, 1},
                  {0, 7, 8, 1, 6, 5, 4, 9, 2, 3},
                  {0, 9, 7, 5, 3, 1, 9, 7, 5, 3, 1},
                  {0, 9, 6, 3, 10, 9, 4, 3, 8, 9, 2, 3}};

    public static void init()
    {
    p = new char[27];
    p[0] = '*';

    for(int i = 0; i < 26; i++)
    {
        p[i + 1] = (char) ('A'+i);
    }

    }

    public static void swap(int i, int j)
    {
        char c;

        c = p[i];
        p[i] = p[j];
        p[j] = c;
    }

    static void printIt()
    {
        long count = 0;

        //to compare performance, comment out from here

         for (int i = 1; i <= N; i++)
         System.out.printf("%c", p[i]);
         System.out.printf("\n");
         //to here

        count++;

    }

    static void permute1(int n)
    {
        if(n == 1)
        {
            printIt();
        }

        for(int i = 1; i <= n; i++)
        {
            swap(i, n);
            permute1(n-1);
            swap(i, n);
        }
    }

    static void permute2(int n)
    {
        if(n == 1)
        {
            printIt();
            return;
        }
        for(int i = 1; i <= n; i++)
        {
            permute2(n-1);
            swap(table[n][i], n);

        }
    }

    static void permute3(int n)
    {
        if(n == 1)
        {
            printIt();
            return;
        }
        for(int i = 1; i <= n; i++)
        {
            permute3(n - 1);
            swap((n & 0x01) ? 1 : i, n);
        }
    }
</code>```

答:
Binary operator & performs bitwise multiplication (AND) of its operands in both languages.

This expression also uses ternary operator a ? b : c;. First, it checks value of a, if it is true, than b is returned, otherwise c is returned.

In C, integer value that != 0 is considered to be true. Java does not cast integer values to boolean.

So for your expression to work, you need to write it as follows:

```<code>swap((n & 0x01) != 0) ? 1 : i, n);
</code>```

Title: Converting C code to Java code

Body:
I was giving some c code to convert to java code.  implement three different methods of generating all N!
permutations of N elements in Java. The code I provided is my converted c code to java, I was successful up until this line of code, swap((n & 0x01) ? 1 : i, n);...in the permute3 method, Im not entirely sure what it is doing or means and i need to know how to write the equivalent in java.

public class Permute {

    public static final long MILLION = 1000000L;

    static int N;
    static char p[];
    static int[][] table =   { {0}, {0, 1}, {0, 1, 1}, {0, 1, 2, 3},
                  {0, 3, 1, 3, 1},
                  {0, 3, 4, 3, 2, 3},
                  {0, 5, 3, 1, 5, 3, 1},
                  {0, 5, 2, 7, 2, 1, 2, 3},
                  {0, 7, 1, 5, 5, 3, 3, 7, 1},
                  {0, 7, 8, 1, 6, 5, 4, 9, 2, 3},
                  {0, 9, 7, 5, 3, 1, 9, 7, 5, 3, 1},
                  {0, 9, 6, 3, 10, 9, 4, 3, 8, 9, 2, 3}};

    public static void init()
    {
    p = new char[27];
    p[0] = '*';

    for(int i = 0; i < 26; i++)
    {
        p[i + 1] = (char) ('A'+i);
    }

    }

    public static void swap(int i, int j)
    {
        char c;

        c = p[i];
        p[i] = p[j];
        p[j] = c;
    }

    static void printIt()
    {
        long count = 0;

        //to compare performance, comment out from here

         for (int i = 1; i <= N; i++)
         System.out.printf("%c", p[i]);
         System.out.printf("\n");
         //to here

        count++;

    }

    static void permute1(int n)
    {
        if(n == 1)
        {
            printIt();
        }

        for(int i = 1; i <= n; i++)
        {
            swap(i, n);
            permute1(n-1);
            swap(i, n);
        }
    }

    static void permute2(int n)
    {
        if(n == 1)
        {
            printIt();
            return;
        }
        for(int i = 1; i <= n; i++)
        {
            permute2(n-1);
            swap(table[n][i], n);

        }
    }

    static void permute3(int n)
    {
        if(n == 1)
        {
            printIt();
            return;
        }
        for(int i = 1; i <= n; i++)
        {
            permute3(n - 1);
            swap((n & 0x01) ? 1 : i, n);
        }
    }

Body:
Binary operator & performs bitwise multiplication (AND) of its operands in both languages.

This expression also uses ternary operator a ? b : c;. First, it checks value of a, if it is true, than b is returned, otherwise c is returned.

In C, integer value that != 0 is considered to be true. Java does not cast integer values to boolean.

So for your expression to work, you need to write it as follows:

swap((n & 0x01) != 0) ? 1 : i, n);


问:
How to get Order numbers where collection number has a top and a corresponding bottom?
This is how the main order table looks :-

```<code>|  Order_num   | Collection_Num |
+--------------+----------------+
|  20143045585 |   123456       |
|  20143045585 |   789012       |
|  20143045585 |   456897       |
|  20143758257 |   546465       |
+--------------+----------------+
</code>```

These are the collections:-

```<code>|    tops      |      bottom    |
+--------------+----------------+
|  353735      |   745758       |
|  123456      |   789012       |
|  456456      |   456897       |
|  323456      |   546465       |
+--------------+----------------+
</code>```

Desired Output:-

```<code>|  Order_num   |
+--------------+
|  20143045585 |
</code>```

Here Order number 20143045585 has both a top and a bottom from the same row in table number 2 (each row in 2nd table forms a particular combination called 'A Collection' i.e. 1 top and corresponding bottom ).
What I want to know -
All the order numbers which have a top and a corresponding bottom in 'Collection_num' column.
Can anyone help me with a SQL code for this ?

Let me know if any of this is unclear.

答:
Here is the query that I used:</p>

```<code>Select *
From  (select A.Order_num, B.Coll_ID, B.Bottoms from Orders_table as A
        Join Collections_Table as B
         on A.Collection_num = B.Bottoms
       ) as C
  join
      (select K.Order_num, M.Coll_ID, M.Tops from Orders_table as K
        Join Collections_Table as M
         on A.Collection_num = B.Tops
       ) as D
  on C.Orders_B = D.Orders_Num AND C.Coll_ID = D.Coll_ID
)
</code>```

Body:
This is how the main order table looks :-

|  Order_num   | Collection_Num |
+--------------+----------------+
|  20143045585 |   123456       |
|  20143045585 |   789012       |
|  20143045585 |   456897       |
|  20143758257 |   546465       |
+--------------+----------------+

These are the collections:-

|    tops      |      bottom    |
+--------------+----------------+
|  353735      |   745758       |
|  123456      |   789012       |
|  456456      |   456897       |
|  323456      |   546465       |
+--------------+----------------+

Desired Output:-

|  Order_num   |
+--------------+
|  20143045585 |

Here Order number 20143045585 has both a top and a bottom from the same row in table number 2 (each row in 2nd table forms a particular combination called 'A Collection' i.e. 1 top and corresponding bottom ).
What I want to know -
All the order numbers which have a top and a corresponding bottom in 'Collection_num' column.
Can anyone help me with a SQL code for this ?

Let me know if any of this is unclear.

Body:
Here is the query that I used:

Select *
From  (select A.Order_num, B.Coll_ID, B.Bottoms from Orders_table as A
        Join Collections_Table as B
         on A.Collection_num = B.Bottoms
       ) as C
  join
      (select K.Order_num, M.Coll_ID, M.Tops from Orders_table as K
        Join Collections_Table as M
         on A.Collection_num = B.Tops
       ) as D
  on C.Orders_B = D.Orders_Num AND C.Coll_ID = D.Coll_ID
)


问:
Sum columns from database using checkbox
I am new to php. I have inserted only a single value in two columns of database. I am trying to add them both using checkbox.
For example. There is a column with name "englishprice" with only one value 20, and another column "mathprice" with only value 10. I want to sum them using checkbox, Like if I only check englishprice then it shows its price, if I check both then it sums both.</p>

答:
Try this >>

Html Code:

You need to create two checkbox with value as their prices. Here is sample

<form method="post">
   <input type="checkbox" value="20" name="englishprice"/>englishprice
   <input type="checkbox" value="10" name="mathprice"/>mathprice
   <button type="submit" name="submit">Submit</button>
</form>```
</div>
</div>
</p>

<p>PHP Code:</p>

```<?php
if (isset($_POST["submit"])) {
    $englishprice = isset($_POST['englishprice']) && !empty($_POST['englishprice']) ? (int) $_POST['englishprice'] : 0;
    $mathprice = isset($_POST['mathprice']) && !empty($_POST['mathprice']) ? (int) $_POST['mathprice'] : 0;
    echo "Price " . ($englishprice + $mathprice);
}
?>
```

Body:
Try this >>

Html Code:

You need to create two checkbox with value as their prices. Here is sample

<form method="post">
   <input type="checkbox" value="20" name="englishprice"/>englishprice
   <input type="checkbox" value="10" name="mathprice"/>mathprice
   <button type="submit" name="submit">Submit</button>
</form>

PHP Code:

<?php
if (isset($_POST["submit"])) {
    $englishprice = isset($_POST['englishprice']) && !empty($_POST['englishprice']) ? (int) $_POST['englishprice'] : 0;
    $mathprice = isset($_POST['mathprice']) && !empty($_POST['mathprice']) ? (int) $_POST['mathprice'] : 0;
    echo "Price " . ($englishprice + $mathprice);
}
?>


问:
Extract text from external URL
I am making share a link feature like facebook. Currently I am parsing meta tags to get keywords, descriptions e.t.c but how to parse these type of pages http://en.wikipedia.org/wiki/Wikipedia There is no meta description for this page but facebook still fetches the following description:
Wikipedia ( /ˌwɪkɪˈpiːdi.ə/ or /ˌwɪkiˈpiːdi.ə/ WIK-i-PEE-dee-ə) is a free,[3]web-based, collaborative, multilingual encyclopedia project supported by the non-profit Wikimedia Foundation. Its 17 million articles (over 3.4 million in English) have been written collaboratively by volunteers around the

How can I extract such description if there is no meta description tag found on the page.

答:
Amazon faces a similar problem, and has a fairly novel solution.  Obviously, it's not perfect, but by marrying it to the idea that Bing uses, I'd bet you could get some pretty solid and interesting keyword tags auto-generated to go with the inherently more suspect description.

So it'd look like:

Description from meta

Interesting Sentences according to bing\google

STP as tags, with hover-over for context.

I think that, in all likelyhood, this is like nuking a fly.

  It'd oversolve your problem to a ridiculous degree.

ContentLicense: CC BY-SA 2.5

Title: Extract text from external URL


问:
How to convert NSString to Int so I can add in swift 3.0
I have a value which seems to be an Int but when I do type(of: value) it returns Optional<Any> and after trying many things I figure that data type NSString.

```<code>let sum = data[0]["total1"] + data[0]["total2"]
</code>```

I have two values like that and I want to add them but it does not let me do it with saying

binary operator + cannot be applied to two "Any" operands

or

Value of type "Any" has no member 'intValue'

How do I convert this Any to Int so I can add them?

答:
Use optional binding to ensure the values are non-nil strings and that they can be converted to Int.

```<code>if let str1 = data[0]["total1"] as? String, let str2 = data[0]["total2"] as? String {
    if let int1 = Int(str1), let int2 = Int(str2) {
        let sum = int1 + int2
    } else {
        // One or more of the two strings doesn't represent an integer
    }
} else {
    // One or more of the two values is nil or not a String
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a value which seems to be an Int but when I do type(of: value) it returns Optional<Any> and after trying many things I figure that data type NSString.

let sum = data[0]["total1"] + data[0]["total2"]

I have two values like that and I want to add them but it does not let me do it with saying

binary operator + cannot be applied to two "Any" operands

or

Value of type "Any" has no member 'intValue'

How do I convert this Any to Int so I can add them?

Body:
Use optional binding to ensure the values are non-nil strings and that they can be converted to Int.

if let str1 = data[0]["total1"] as? String, let str2 = data[0]["total2"] as? String {
    if let int1 = Int(str1), let int2 = Int(str2) {
        let sum = int1 + int2
    } else {
        // One or more of the two strings doesn't represent an integer
    }
} else {
    // One or more of the two values is nil or not a String
}


问:
MapKit Define the desired type of search results (Country, city, region, etc)
For an app i'm building, I want to implement a feature that allows users to specify the geographical origin of wines (country (e.g. France), region (e.g. Bordeaux), subregion (e.g. Paullac)).

I want to make sure that I don't have to add all available countries myself, and that all information that comes into the database is valid. Therefore, I decided to do it as follows:

User adds a new wine and types the name of the country it comes from

While typing, the app searches in the apple maps database

The results from this search get displayed as suggestions, and when the user taps a suggestion, the app creates a Country object with all relevant information. The wine van only be saved when such an object is present

This works fine, except one thing: Apple maps returns anything, like restaurants, shops, etcetera, from anywhere.

My question: How can I specify WHAT I am looking for? I can only specify the region I'm searching in, which is irrelevant in my case. I would like to be able to tell apple maps to ONLY look for countries, regions, cities, whatever. Is this possible in a way? I have exhausted google for this and found no way thus far.

答:
There was a class added to MapKit in iOS 9.3 called MKLocalSearchCompleter which helps with autocompletion. You can filter what is returned by using 'MKSearchCompletionFilterType' but that isn't the most extensive and might not fully help with your situation. It does return cities and countries as results but it also returns businesses when I've used it.

One possible option is to filter the returned results again on the app side and exclude all results that have a numeric character in them.

```<code>func setupCompleter() {
    self.searchCompleter = MKLocalSearchCompleter()
    self.searchCompleter?.delegate = self
    self.searchCompleter?.filterType = .locationsOnly
    self.searchCompleter?.queryFragment = "Bordeaux"
}

func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
    print("Results \(completer.results)")

    // Do additional filtering on results here
}
</code>```

Body:
There was a class added to MapKit in iOS 9.3 called MKLocalSearchCompleter which helps with autocompletion. You can filter what is returned by using 'MKSearchCompletionFilterType' but that isn't the most extensive and might not fully help with your situation. It does return cities and countries as results but it also returns businesses when I've used it.

One possible option is to filter the returned results again on the app side and exclude all results that have a numeric character in them.

func setupCompleter() {
    self.searchCompleter = MKLocalSearchCompleter()
    self.searchCompleter?.delegate = self
    self.searchCompleter?.filterType = .locationsOnly
    self.searchCompleter?.queryFragment = "Bordeaux"
}

func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
    print("Results \(completer.results)")

    // Do additional filtering on results here
}


问:
Custom SerDe not supported by Impala, what's the best way to query files in CSV w/double quotes?
I have a CSV data with each field surronded with double quotes. When I created
Hive table used serde 'com.bizo.hive.serde.csv.CSVSerde'
When above table is queried in Impala I am getting error SerDe not found.

I added the CSV Serde JAR file in /usr/lib/impala/lib folder.

Later studied in Impala documentation that Impala does not support custom
SERDE. In such case how I can overcome this issue such that my CSV data
with quotes is taken care. I want to use CSV Serde because it takes of
commas in values which is a legitimate field vavlue.

Thanks a lot

答:
Within Hive

```<code>CREATE TABLE mydb.my_serde_table_impala AS SELECT FROM mydb.my_serde_table
</code>```

Within Impala

```<code>INVALIDATE METADATA mydb.my_serde_table_impala
</code>```

Add these steps to include dropping the _impala table first with whatever populates or ingests files for the serde table.

Impala bypasses MapReduce, unlike Hive. So Impala can't/doesn't use the SerDe the way MapReduce does.

Body:
Within Hive

CREATE TABLE mydb.my_serde_table_impala AS SELECT FROM mydb.my_serde_table

Within Impala

INVALIDATE METADATA mydb.my_serde_table_impala

Add these steps to include dropping the _impala table first with whatever populates or ingests files for the serde table.

Impala bypasses MapReduce, unlike Hive. So Impala can't/doesn't use the SerDe the way MapReduce does.


问:
matching the regular expression with the whole string
im kinda strumped in a situation where i need to match a whole string with a regular expression rather than finding if the pattern exists in the string.

suppose if i have a regular expression

```<code>/\\^^\\w+\\$^/
</code>```

what i want is that the code will run through various strings , compare the strings with the regular expression and perform some task if the strings start and end with a ^.

Examples

^hello world^ is a match

my ^hello world^ should not be a match

the php function preg_match matches both of the results

any clues ???

Body:
im kinda strumped in a situation where i need to match a whole string with a regular expression rather than finding if the pattern exists in the string.

suppose if i have a regular expression

/\\^^\\w+\\$^/

what i want is that the code will run through various strings , compare the strings with the regular expression and perform some task if the strings start and end with a ^.

Examples

^hello world^ is a match

my ^hello world^ should not be a match

the php function preg_match matches both of the results

any clues ???

Body:
Try

/^\^\s*(\w+\s*)+\^$/


问:
Ruby on Rails: set specific serializer for polymorphic association
I'm trying to override the default serializer for a polymorphic relationship. I have:

```<code>class NotificationListSerializer < ActiveModel::Serializer
  attributes :id, :title
  belongs_to :notifiable, polymorphic: true
end
</code>```

If notifiable is an Organization, the organization is serialized with OrganizationSerializer. If notifiable is a Group, the group is serialized with GroupSerializer. This makes perfect sense, but how can I specify a different serializer, depending on the class?

For example, if notifiable is an Organization, I would like to use SparseOrganizationSerializer instead of OrganizationSerializer. How can I achieve this?

I'm pretty sure this is documented, but I'm having a hard time following and finding any examples.

From the documentation:

Polymorphic Relationships

Polymorphic relationships are serialized by specifying the relationship, like any other association. For example:

```<code>class PictureSerializer < ActiveModel::Serializer
  has_one :imageable
end
</code>```

You can specify the serializers by overriding serializer_for. For more context about polymorphic relationships, see the tests for each adapter.

Overriding association serializer lookup

If you want to define a specific serializer lookup for your associations, you can override the ActiveModel::Serializer.serializer_for method to return a serializer class based on defined conditions.

```<code>class MySerializer < ActiveModel::Serializer
  def self.serializer_for(model, options)
    return SparseAdminSerializer if model.class == 'Admin'
    super
  end
  # the rest of the serializer
end
</code>```

答: You can use belongs_to :notifiable with &block option to specify fit serializer there.    </p>

Body:
I'm trying to override the default serializer for a polymorphic relationship. I have:

class NotificationListSerializer < ActiveModel::Serializer
  attributes :id, :title
  belongs_to :notifiable, polymorphic: true
end

If notifiable is an Organization, the organization is serialized with OrganizationSerializer. If notifiable is a Group, the group is serialized with GroupSerializer. This makes perfect sense, but how can I specify a different serializer, depending on the class?

For example, if notifiable is an Organization, I would like to use SparseOrganizationSerializer instead of OrganizationSerializer. How can I achieve this?

I'm pretty sure this is documented, but I'm having a hard time following and finding any examples.

From the documentation:

Polymorphic Relationships

Polymorphic relationships are serialized by specifying the relationship, like any other association. For example:

class PictureSerializer < ActiveModel::Serializer
  has_one :imageable
end

You can specify the serializers by overriding serializer_for. For more context about polymorphic relationships, see the tests for each adapter.

Overriding association serializer lookup

If you want to define a specific serializer lookup for your associations, you can override the ActiveModel::Serializer.serializer_for method to return a serializer class based on defined conditions.

class MySerializer < ActiveModel::Serializer
  def self.serializer_for(model, options)
    return SparseAdminSerializer if model.class == 'Admin'
    super
  end
  # the rest of the serializer
end


问:
Custom shells displaying error - Cake PHP 3
Custom shells not working, I am using Cake PHP 3.

When I am creating a shell file to be used for cron job, example: HelloShell.php

Console under bin folder, when I run cake hello then, it returns class HelloShell could not loaded.

答:
The error is pretty much straightforward

your working path should be the same as your application path

1) You're not in the app path, you're in app/bin. So you should run the shell as

```<code>$ cd /var/www/html/cakephp
$ bin/cake hello
</code>```

2) If your cake command is not linked to this particular binary, then you have to use the proper notation to run a bin in UNIX

```<code>$ cd /var/www/html/cakephp/bin
$ ./cake hello
</code>```

Otherwise you could be calling a totally different cake in your system

Body:
The error is pretty much straightforward

your working path should be the same as your application path

1) You're not in the app path, you're in app/bin. So you should run the shell as

$ cd /var/www/html/cakephp
$ bin/cake hello

2) If your cake command is not linked to this particular binary, then you have to use the proper notation to run a bin in UNIX

$ cd /var/www/html/cakephp/bin
$ ./cake hello

Otherwise you could be calling a totally different cake in your system


问:
How to Observe a Custom Event using RXJS in Angular 2?
I have a third party library that I am intending to integrate with RxJS. This is a messaging library called Tiger Text. According to them I can listen to an event called messages and when the stream has a message I can use it to further utilize it. The code snippet for the same is as follows:-

```<code>var client = new TigerConnect.Client({ defaultOrganizationId: 'some-org-id' })

client.signIn('user@mail.com', 's3cr3t', { udid: 'unique-device-id' }).then(function (session) {
  onSignedIn(session)
})

function onSignedIn(session) {
  console.log('Signed in as', session.user.displayName)

  client.messages.sendToUser(
    'someone@mail.com',
    'hello!'
  ).then(function (message) {
    console.log('sent', message.body, 'to', message.recipient.displayName)
  })

  client.events.connect()

  client.on('message', function (message) {
    console.log(
      'message event',
      message.sender.displayName,
      'to',
      message.recipient.displayName,
      ':',
      message.body
    )
  })
}
</code>```

Now please have a look at the place where you have the below mentioned piece of code.

```<code>client.on('message', function (message) {
    console.log(
      'message event',
      message.sender.displayName,
      'to',
      message.recipient.displayName,
      ':',
      message.body
    )
  })
</code>```

I wanted to know how to use RxJS so as to create an observable out of this piece of code so as to subscribe to the stream and whenever we have a change I take the new data and process it as I wish.

Please Advice.

答:
You can use fromEventPattern to create an observable from a custom event:

```<code>import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEventPattern';

const messages = Observable.fromEventPattern(
  handler => client.on('message', handler),
  handler => client.off('message', handler)
);
messages.subscribe(message => console.log(message));
</code>```

You pass to fromEventPattern functions that add and remove the event handler using the custom API's add and remove mechanism. You've not included it in your question, but I've assumed the API you're using implements an off method.

Body:
I have a third party library that I am intending to integrate with RxJS. This is a messaging library called Tiger Text. According to them I can listen to an event called messages and when the stream has a message I can use it to further utilize it. The code snippet for the same is as follows:-

var client = new TigerConnect.Client({ defaultOrganizationId: 'some-org-id' })

client.signIn('user@mail.com', 's3cr3t', { udid: 'unique-device-id' }).then(function (session) {
  onSignedIn(session)
})

function onSignedIn(session) {
  console.log('Signed in as', session.user.displayName)

  client.messages.sendToUser(
    'someone@mail.com',
    'hello!'
  ).then(function (message) {
    console.log('sent', message.body, 'to', message.recipient.displayName)
  })

  client.events.connect()

  client.on('message', function (message) {
    console.log(
      'message event',
      message.sender.displayName,
      'to',
      message.recipient.displayName,
      ':',
      message.body
    )
  })
}

Now please have a look at the place where you have the below mentioned piece of code.

client.on('message', function (message) {
    console.log(
      'message event',
      message.sender.displayName,
      'to',
      message.recipient.displayName,
      ':',
      message.body
    )
  })

I wanted to know how to use RxJS so as to create an observable out of this piece of code so as to subscribe to the stream and whenever we have a change I take the new data and process it as I wish.

Please Advice.

Body:
You can use fromEventPattern to create an observable from a custom event:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEventPattern';

const messages = Observable.fromEventPattern(
  handler => client.on('message', handler),
  handler => client.off('message', handler)
);
messages.subscribe(message => console.log(message));

You pass to fromEventPattern functions that add and remove the event handler using the custom API's add and remove mechanism. You've not included it in your question, but I've assumed the API you're using implements an off method.


问:
void* will have the same representation and memory alignment as a pointer to char
I am reading a book on pointers named "understanding and using c pointers"

When it comes to void * it says

It has two interesting properties:

A pointer to void will have the same representation and memory alignment as a pointer to char.

What am confused about is isn't the memory of all the pointers same? They why instead of writing void* is same as normal pointer it explicitly mentioned char pointers? Will really appreciate any help

答:
I think the point here is "memory alignment", not "memory size".

Yes, all pointers have same size of memory. But they may have different limitation for memory alignment.

For example, on some platforms, a "32-bit int" pointer must point to the address which should be times of 4 bytes. It cannot point to, e.g. 0x100001 or 0x100003.

But a "8-bit char" pointer can point to any address. So does a "void" pointer.

So it said that.


问:
bash script grep the etc file for user information
I am trying to write a script in bash to read in arguments (usernames) and then return information about that username by searching the /etc/passwd file. I am not the root on the server that I am scripting this on, but I don't need to be. Here is the code that I have so far, but I dont think I am using the grep command right. </p>

```<code>#!/bin/bash
if [ $# -eq 1 ]; then #if num of args =1; then continue on
        UNAME=$1 #set arg to var UNAME
        grep UNAME=$(grep $/etc/passwd)
        if [ $UNAME == /etc/passwd ]; then #if UNAME exists then display info below
                echo "-------------------------------------------"
                echo "Username:       $(grep UNAME/etc/passwd/ $f1) "
                echo "User ID (UID):  $(grep UNAME/etc/passwd/) "
                echo "Group ID (GID): $(grep UNAME/etc/passwd/) "
                echo "User info:      $(grep UNAME/etc/passwd/) "
                echo "Home directory: $(grep UNAME/etc/passwd/) "
                echo "Command shell:  $(grep UNAME/etc/passwd/) "
                echo "-------------------------------------------"
        else #if UNAME is nonexistant then display this error message
                echo "-------------------------------------------"
                echo ""$UNAME" does not exist."
                echo "-------------------------------------------"
        fi
fi
if [ $# -eq 0 ]; then #if num of args =0; then display this
        echo "Not enough arguments provided."
        echo "USAGE: $0 <user_name> [user_name] ..."
        exit 1
fi
</code>```

答:
Before I get to the explanation, here is how I would have written your script:

```<code>cat ./test.sh
#!/bin/bash

UNAME=${1} #set arg to var UNAME
if [ -z ${UNAME} ]; then #if no argument is provided; then display this
    echo "Not enough arguments provided."
    echo "USAGE: $0 <user_name>"
    exit 1
fi
if grep ${UNAME} /etc/passwd >/dev/null; then #if UNAME exists then display info below
    echo "-------------------------------------------"
    echo "Username:       $(awk -F ':' -v uname=${UNAME} '$0 ~ uname {print $1}' /etc/passwd)"
    echo "User ID (UID):  $(awk -F ':' -v uname=${UNAME} '$0 ~ uname {print $3}' /etc/passwd)"
    echo "Group ID (GID): $(awk -F ':' -v uname=${UNAME} '$0 ~ uname {print $4}' /etc/passwd)"
    echo "User info:      $(awk -F ':' -v uname=${UNAME} '$0 ~ uname {print $5}' /etc/passwd)"
    echo "Home directory: $(awk -F ':' -v uname=${UNAME} '$0 ~ uname {print $6}' /etc/passwd)"
    echo "Command shell:  $(awk -F ':' -v uname=${UNAME} '$0 ~ uname {print $7}' /etc/passwd)"
    echo "-------------------------------------------"
else #if UNAME is nonexistant then display this error message
    echo "-------------------------------------------"
    echo "\"${UNAME}\" does not exist."
    echo "-------------------------------------------"
fi
</code>```

Explanation:

if can use grep directly to check for the existence of
your argument in passwd

UNAME= is how arguments are assigned, not
called - they are called with the $ - for example $UNAME

/etc/passwd is an absolute file name and not an argument, thus
$/etc/passwd doesn't mean anything to bash

argument=$(any old bash command) is telling bash that you want to
assign the output of "any old bash command" to "argument", so $()
has to contain a command with output for "argument" to be assigned
anything.

the >/dev/null sends the output of grep to the waste basket because we only care at this point whether or not it's successful so that if knows what to do

grep works like this: grep <the thing you want to find> <file> (note that spaces matter and to use "" if you want to include spaces in your search)

to get specific fields, awk is more useful. awk -F':' tells awk that I want : to define my field separators; -v uname=${UNAME} passes my argument to awk; within awk, $0 ~ uname checks the line for my argument (like grep); and {print $1} prints the first field, and so on

Also consider the limitation of partial matches. If, for example, I have a user JSmith and Smith, searching Smith will return both. This can be addressed with regex but will add a great deal of complexity to the script.

Here is a version with lighter awk usage which works with multiple arguments:

```<code>#!/bin/bash
for username; do
    if grep ${username} /etc/passwd >/dev/null; then #if username exists then display info below
        echo "---------------------------------------"
        awk -F':' -v uname="${username}" '\
            $0 ~ uname \
            {print " Username:         "$1\
                "\n User ID (UID):    "$3\
                "\n Group ID (GID):   "$4\
                "\n User info:        "$5\
                "\n Home directory:   "$6\
                "\n Command shell:    "$7}' /etc/passwd
        echo "---------------------------------------"
    else #if username is nonexistant then display this error message
        echo "---------------------------------------"
        echo "\"${username}\" does not exist."
        echo "---------------------------------------"
    fi
done

if [ -z ${1} ]; then #if no argument is provided; then display this
    echo " Not enough arguments provided."
    echo " USAGE: $0 <user name>"
    exit 1
fi
</code>```

*Credit to William Pursell for explaining the for loop

Body:
I am trying to write a script in bash to read in arguments (usernames) and then return information about that username by searching the /etc/passwd file. I am not the root on the server that I am scripting this on, but I don't need to be. Here is the code that I have so far, but I dont think I am using the grep command right.

#!/bin/bash
if [ $# -eq 1 ]; then #if num of args =1; then continue on
        UNAME=$1 #set arg to var UNAME
        grep UNAME=$(grep $/etc/passwd)
        if [ $UNAME == /etc/passwd ]; then #if UNAME exists then display info below
                echo "-------------------------------------------"
                echo "Username:       $(grep UNAME/etc/passwd/ $f1) "
                echo "User ID (UID):  $(grep UNAME/etc/passwd/) "
                echo "Group ID (GID): $(grep UNAME/etc/passwd/) "
                echo "User info:      $(grep UNAME/etc/passwd/) "
                echo "Home directory: $(grep UNAME/etc/passwd/) "
                echo "Command shell:  $(grep UNAME/etc/passwd/) "
                echo "-------------------------------------------"
        else #if UNAME is nonexistant then display this error message
                echo "-------------------------------------------"
                echo ""$UNAME" does not exist."
                echo "-------------------------------------------"
        fi
fi
if [ $# -eq 0 ]; then #if num of args =0; then display this
        echo "Not enough arguments provided."
        echo "USAGE: $0 <user_name> [user_name] ..."
        exit 1
fi

Body:
Before I get to the explanation, here is how I would have written your script:

cat ./test.sh
#!/bin/bash

UNAME=${1} #set arg to var UNAME
if [ -z ${UNAME} ]; then #if no argument is provided; then display this
    echo "Not enough arguments provided."
    echo "USAGE: $0 <user_name>"
    exit 1
fi
if grep ${UNAME} /etc/passwd >/dev/null; then #if UNAME exists then display info below
    echo "-------------------------------------------"
    echo "Username:       $(awk -F ':' -v uname=${UNAME} '$0 ~ uname {print $1}' /etc/passwd)"
    echo "User ID (UID):  $(awk -F ':' -v uname=${UNAME} '$0 ~ uname {print $3}' /etc/passwd)"
    echo "Group ID (GID): $(awk -F ':' -v uname=${UNAME} '$0 ~ uname {print $4}' /etc/passwd)"
    echo "User info:      $(awk -F ':' -v uname=${UNAME} '$0 ~ uname {print $5}' /etc/passwd)"
    echo "Home directory: $(awk -F ':' -v uname=${UNAME} '$0 ~ uname {print $6}' /etc/passwd)"
    echo "Command shell:  $(awk -F ':' -v uname=${UNAME} '$0 ~ uname {print $7}' /etc/passwd)"
    echo "-------------------------------------------"
else #if UNAME is nonexistant then display this error message
    echo "-------------------------------------------"
    echo "\"${UNAME}\" does not exist."
    echo "-------------------------------------------"
fi

Explanation:

if can use grep directly to check for the existence of
your argument in passwd

UNAME= is how arguments are assigned, not
called - they are called with the $ - for example $UNAME

/etc/passwd is an absolute file name and not an argument, thus
$/etc/passwd doesn't mean anything to bash

argument=$(any old bash command) is telling bash that you want to
assign the output of "any old bash command" to "argument", so $()
has to contain a command with output for "argument" to be assigned
anything.

the >/dev/null sends the output of grep to the waste basket because we only care at this point whether or not it's successful so that if knows what to do

grep works like this: grep <the thing you want to find> <file> (note that spaces matter and to use "" if you want to include spaces in your search)

to get specific fields, awk is more useful. awk -F':' tells awk that I want : to define my field separators; -v uname=${UNAME} passes my argument to awk; within awk, $0 ~ uname checks the line for my argument (like grep); and {print $1} prints the first field, and so on

Also consider the limitation of partial matches. If, for example, I have a user JSmith and Smith, searching Smith will return both. This can be addressed with regex but will add a great deal of complexity to the script.

Here is a version with lighter awk usage which works with multiple arguments:

#!/bin/bash
for username; do
    if grep ${username} /etc/passwd >/dev/null; then #if username exists then display info below
        echo "---------------------------------------"
        awk -F':' -v uname="${username}" '\
            $0 ~ uname \
            {print " Username:         "$1\
                "\n User ID (UID):    "$3\
                "\n Group ID (GID):   "$4\
                "\n User info:        "$5\
                "\n Home directory:   "$6\
                "\n Command shell:    "$7}' /etc/passwd
        echo "---------------------------------------"
    else #if username is nonexistant then display this error message
        echo "---------------------------------------"
        echo "\"${username}\" does not exist."
        echo "---------------------------------------"
    fi
done

if [ -z ${1} ]; then #if no argument is provided; then display this
    echo " Not enough arguments provided."
    echo " USAGE: $0 <user name>"
    exit 1
fi

*Credit to William Pursell for explaining the for loop


答:
Anchor the ends.</p>

```<code>/^...$/
</code>```

Title: matching the regular expression with the whole string

Body:
Anchor the ends.

/^...$/


问:
android: EditText numberDecimal - how to start the keyboard as minimized
I have an EditText with these values:

```<code>android:digits="0123456789"
android:inputType="numberDecimal"
</code>```

As you see, I would like to insert only digits 0-9.

my problem is that when I reach the layout containing this EditText, the smartphone keyboard is displayed so it hides the screen before I can see the screen content. (although I didn't press on the edit text box!)

I would like the keyboard to be minimized as default.

I want that ONLY AFTER I press on the editText box, the keyboard will be displayed.

Is there any possibility to do so?

答:
You can force Android to hide the virtual keyboard using the  InputMethodManager, calling hideSoftInputFromWindow, passing in the token of the window containing your focused view

```<code>// Check if no view has focus:
 View view = this.getCurrentFocus();
 if (view != null) {
 InputMethodManager imm =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
 imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
 }
</code>```

This will force the keyboard to be hidden in all situations. In some cases you will want to pass in InputMethodManager.HIDE_IMPLICIT_ONLY as the second parameter to ensure you only hide the keyboard when the user didn't explicitly force it to appear (by holding down menu).

Body:
I have an EditText with these values:

android:digits="0123456789"
android:inputType="numberDecimal"

As you see, I would like to insert only digits 0-9.

my problem is that when I reach the layout containing this EditText, the smartphone keyboard is displayed so it hides the screen before I can see the screen content. (although I didn't press on the edit text box!)

I would like the keyboard to be minimized as default.

I want that ONLY AFTER I press on the editText box, the keyboard will be displayed.

Is there any possibility to do so?

Body:
You can force Android to hide the virtual keyboard using the  InputMethodManager, calling hideSoftInputFromWindow, passing in the token of the window containing your focused view

// Check if no view has focus:
 View view = this.getCurrentFocus();
 if (view != null) {
 InputMethodManager imm =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
 imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
 }

This will force the keyboard to be hidden in all situations. In some cases you will want to pass in InputMethodManager.HIDE_IMPLICIT_ONLY as the second parameter to ensure you only hide the keyboard when the user didn't explicitly force it to appear (by holding down menu).


问:
Spring Integration WS Outbound Gateway POC - XMLMarshalException
I am developing a POC on Spring Integration with following usecase.

Subscribing input message (A) from remote JMS Queue

Transforming input message (A) to (B)

Invoking a remote Webservice with (B) and receiving the response

my spring-int config xml has following

```<code><int-ws:outbound-gateway id="marshallingGateway" request-channel="mdmIntInputChannel" reply-channel="mdmIntOutputChannel"
        uri="ws-endpoint" marshaller="marshaller" unmarshaller="marshaller"/>

<oxm:jaxb2-marshaller id="marshaller" contextPath="com.veeaar.ws.types.jaxb"/>
</code>```

Have all my jaxb generated source in my spring integration proj workspace.

While executing this in STS 3.8.3, the following error is being thrown.

Not sure what is wrong in my code. Any help resolving this is highly appreciated. Thanks.

```<code>Caused by: org.springframework.oxm.MarshallingFailureException: JAXB marshalling exception; nested exception is javax.xml.bind.MarshalException
 - with linked exception:
[Exception [EclipseLink-25007] (Eclipse Persistence Services - 2.6.1.v20150916-55dc7c3): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: A descriptor for class java.lang.String was not found in the project.  For JAXB, if the JAXBContext was bootstrapped using TypeMappingInfo[] you must call a marshal method that accepts TypeMappingInfo as an input parameter.]
    at org.springframework.oxm.jaxb.Jaxb2Marshaller.convertJaxbException(Jaxb2Marshaller.java:908)
    at org.springframework.oxm.jaxb.Jaxb2Marshaller.marshal(Jaxb2Marshaller.java:684)
    at org.springframework.ws.support.MarshallingUtils.marshal(MarshallingUtils.java:81)
    at org.springframework.integration.ws.MarshallingWebServiceOutboundGateway$MarshallingRequestMessageCallback.doWithMessageInternal(MarshallingWebServiceOutboundGateway.java:129)
    at org.springframework.integration.ws.AbstractWebServiceOutboundGateway$RequestMessageCallback.doWithMessage(AbstractWebServiceOutboundGateway.java:233)
    at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:590)
    at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:555)
    at org.springframework.integration.ws.MarshallingWebServiceOutboundGateway.doHandle(MarshallingWebServiceOutboundGateway.java:87)
    at org.springframework.integration.ws.AbstractWebServiceOutboundGateway.handleRequestMessage(AbstractWebServiceOutboundGateway.java:188)
    at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:109)
    at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127)
    ... 36 more
</code>```

Am explaining further my POC here to understand more why JAXB conversion needed before invoking the remote webservice.

The XSL transformation I doing in Spring Integ converts from input message of "Event" to "fetchCodeByName" message as given below.

```<code><tns:fetchCodeByName xmlns:tns="http://www.veeaar.com/remote/wsdl/2010-1" xmlns:ns1="http://www.veeaar.com/remote/xml/2010-1" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">
<ns1:Code>
    <Name>xxx</Name>
</ns1:Code>
</tns:fetchCodeByName>
</code>```

In WSDL, fetchCodeByName is mapped to CodesType of ns1 namespace. Have generated JAXB classes from 'Codes' schema XSD.

Before invoking the remote web service, if I create a service activator and try to unmarshall the transformation output to JAXB object, we get error reporting as unmarshalling task expecting 'Codes' as root element not 'fetchCodeByName'.

How to resolve this issue?

Is there any way in Spring Integration, can we invoke a remote web service without marshall and unmarshal the input message? Can't we just direct the XSLT output straightway to int-ws:outbound-gateway?

答: Why do you need to unmarshal before WS Outbound Gateway? You see, you then marshal it again! Just use simple WS Outbound Gateway variant (without marshaller) and send an XSLT transformer result in its input channel as is.

Body:
I am developing a POC on Spring Integration with following usecase.

Subscribing input message (A) from remote JMS Queue

Transforming input message (A) to (B)

Invoking a remote Webservice with (B) and receiving the response

my spring-int config xml has following

<int-ws:outbound-gateway id="marshallingGateway" request-channel="mdmIntInputChannel" reply-channel="mdmIntOutputChannel"
        uri="ws-endpoint" marshaller="marshaller" unmarshaller="marshaller"/>

<oxm:jaxb2-marshaller id="marshaller" contextPath="com.veeaar.ws.types.jaxb"/>

Have all my jaxb generated source in my spring integration proj workspace.

While executing this in STS 3.8.3, the following error is being thrown.

Not sure what is wrong in my code. Any help resolving this is highly appreciated. Thanks.

Caused by: org.springframework.oxm.MarshallingFailureException: JAXB marshalling exception; nested exception is javax.xml.bind.MarshalException
 - with linked exception:
[Exception [EclipseLink-25007] (Eclipse Persistence Services - 2.6.1.v20150916-55dc7c3): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: A descriptor for class java.lang.String was not found in the project.  For JAXB, if the JAXBContext was bootstrapped using TypeMappingInfo[] you must call a marshal method that accepts TypeMappingInfo as an input parameter.]
    at org.springframework.oxm.jaxb.Jaxb2Marshaller.convertJaxbException(Jaxb2Marshaller.java:908)
    at org.springframework.oxm.jaxb.Jaxb2Marshaller.marshal(Jaxb2Marshaller.java:684)
    at org.springframework.ws.support.MarshallingUtils.marshal(MarshallingUtils.java:81)
    at org.springframework.integration.ws.MarshallingWebServiceOutboundGateway$MarshallingRequestMessageCallback.doWithMessageInternal(MarshallingWebServiceOutboundGateway.java:129)
    at org.springframework.integration.ws.AbstractWebServiceOutboundGateway$RequestMessageCallback.doWithMessage(AbstractWebServiceOutboundGateway.java:233)
    at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:590)
    at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:555)
    at org.springframework.integration.ws.MarshallingWebServiceOutboundGateway.doHandle(MarshallingWebServiceOutboundGateway.java:87)
    at org.springframework.integration.ws.AbstractWebServiceOutboundGateway.handleRequestMessage(AbstractWebServiceOutboundGateway.java:188)
    at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:109)
    at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127)
    ... 36 more

Am explaining further my POC here to understand more why JAXB conversion needed before invoking the remote webservice.

The XSL transformation I doing in Spring Integ converts from input message of "Event" to "fetchCodeByName" message as given below.

<tns:fetchCodeByName xmlns:tns="http://www.veeaar.com/remote/wsdl/2010-1" xmlns:ns1="http://www.veeaar.com/remote/xml/2010-1" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">
<ns1:Code>
    <Name>xxx</Name>
</ns1:Code>
</tns:fetchCodeByName>

In WSDL, fetchCodeByName is mapped to CodesType of ns1 namespace. Have generated JAXB classes from 'Codes' schema XSD.

Before invoking the remote web service, if I create a service activator and try to unmarshall the transformation output to JAXB object, we get error reporting as unmarshalling task expecting 'Codes' as root element not 'fetchCodeByName'.

How to resolve this issue?

Is there any way in Spring Integration, can we invoke a remote web service without marshall and unmarshal the input message? Can't we just direct the XSLT output straightway to int-ws:outbound-gateway?


问:
What are the options to host Orleans on Azure without using the Cloud Services?
I want to host an Orleans project on Azure, but don't want to use the (classic) Cloud Services model (I want an ARM template project). The web app sample uses the old web / worker model - what is best option? There is a Service Fabric sample - is that the best route? The nearest equivalent to the web/worker model is VM Scale Sets - is that a well tested option? </p>

答:
IMO, app service is closet to web role.

Worker role however, depending on the point of view

From system architecture point of view, I think Scale Set is the closet. You get an identical set of VMs running your application. However you lost all management features. How your cluster handle application configurations, work loads on each node, service interruptions from server failure or deployments are pretty much DIY. Also you need to provision the VM with dependencies for your application.

From operations point of view, I think Service Fabric is the closest. It handles problems above but then you are dealing with design/implementation changes and learning curve from the added fabric layer in the architecture. Could be small, could be big depending on the complexity of your project. Besides, service fabric is still relatively new and nothing is for sure. Best case you follow the sample change a few lines of code and it works like a charm. Worst case you may want to complete refactor orleans solution into service fabric solution.

App service would be the easiest among the three. If it doesn't meet your requirement, I personally would try Service Fabric. Same reason why people are moving to cloud and you would opt for ARM solution.