问:
Optaplanner in osgi
I'm trying to get optaplanner 6.5.0 to work in an osgi environment.
I had to install following bundles to get all dependencies resolved:

```<code>OptaPlanner coreorg.optaplanner.core                                                            6.5.0.201610181310
XStream Corexstream                                                                             1.4.9
Apache Commons Mathorg.apache.commons.math3                                                     3.4.1
Drools :: Compilerorg.drools.compiler                                                           6.5.0.201610181300
Drools :: Coreorg.drools.core                                                                   6.5.0.201610181300
KIE :: Public APIorg.kie.api                                                                    6.5.0.201610181259
KIE :: Internalorg.kie.internalapi                                                              6.5.0.201610181259
Protocol Buffer Java APIcom.google.protobuf                                                     2.6.0
mvel2org.mvel2                                                                                2.2.8.Final
Apache ServiceMix :: Bundles :: javax.injectorg.apache.servicemix.bundles.javax-inject          1.0.0.2
XML Pull Parsing APIorg.xmlpull.v1                                                              1.1.4.redhat-1
Apache ServiceMix :: Bundles :: xpp3org.apache.servicemix.bundles.xpp3                          1.1.4.c
Apache ServiceMix :: Specs :: Activation API 1.4org.apache.servicemix.specs.activation-api-1.1  2.0.0
Apache ServiceMix :: Bundles :: jaxb-xjcorg.apache.servicemix.bundles.jaxb-xjc                  2.2.4.1
Apache ServiceMix :: Specs :: JAXB API 2.2org.apache.servicemix.specs.jaxb-api-2.2              2.9.0
Apache ServiceMix :: Specs :: Stax API 1.0org.apache.servicemix.specs.stax-api-1.0              2.9.0
Apache ServiceMix :: Bundles :: jaxb-implorg.apache.servicemix.bundles.jaxb-impl                2.2.11.1
Apache ServiceMix :: Bundles :: reflectionsorg.apache.servicemix.bundles.reflections            0.9.11.1
OptaPlanner persistence commonorg.optaplanner.persistence.common                                6.5.0.201610181310
Sling Metrics :: CQ Fragmentcom.github.digital-wonderland.sling-metrics.cq-metrics-fragment     0.1.0
Guava: Google Core Libraries for Javacom.google.guava                                           18.0.0
</code>```

When testing a simple example, which a got working through a junit test, I get following error:

```<code>java.lang.NoClassDefFoundError: com/google/common/base/Predicate
    at org.optaplanner.core.config.domain.ScanAnnotatedClassesConfig.buildSolutionDescriptor(ScanAnnotatedClassesConfig.java:69)
    at org.optaplanner.core.config.solver.SolverConfig.buildSolutionDescriptor(SolverConfig.java:278)
    at org.optaplanner.core.config.solver.SolverConfig.buildSolver(SolverConfig.java:229)
    at org.optaplanner.core.impl.solver.AbstractSolverFactory.buildSolver(AbstractSolverFactory.java:52)
    at com.bekaert.handling.allocation.optimizer.impl.OptimizerTest.before(OptimizerTest.java:55)
    at com.bekaert.handling.allocation.optimizer.impl.TestAllocationOptimizerImpl.activate(TestAllocationOptimizerImpl.java:14)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)[:1.8.0_25]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)[:1.8.0_25]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)[:1.8.0_25]
    at java.lang.reflect.Method.invoke(Unknown Source)[:1.8.0_25]
    at org.apache.felix.scr.impl.helper.BaseMethod.invokeMethod(BaseMethod.java:231)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.helper.BaseMethod.access$500(BaseMethod.java:39)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.helper.BaseMethod$Resolved.invoke(BaseMethod.java:624)
    at org.apache.felix.scr.impl.helper.BaseMethod.invoke(BaseMethod.java:508)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.helper.ActivateMethod.invoke(ActivateMethod.java:149)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.SingleComponentManager.createImplementationObject(SingleComponentManager.java:315)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.SingleComponentManager.createComponent(SingleComponentManager.java:127)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.SingleComponentManager.getService(SingleComponentManager.java:871)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.SingleComponentManager.getServiceInternal(SingleComponentManager.java:838)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.AbstractComponentManager.activateInternal(AbstractComponentManager.java:850)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.AbstractComponentManager.enable(AbstractComponentManager.java:419)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.config.ConfigurableComponentHolder.enableComponents(ConfigurableComponentHolder.java:376)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.BundleComponentActivator.initialize(BundleComponentActivator.java:172)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.BundleComponentActivator.<init>(BundleComponentActivator.java:120)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.Activator.loadComponents(Activator.java:258)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.Activator.access$000(Activator.java:45)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.Activator$ScrExtension.start(Activator.java:185)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.utils.extender.AbstractExtender.createExtension(AbstractExtender.java:259)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.utils.extender.AbstractExtender.modifiedBundle(AbstractExtender.java:232)[4:org.apache.felix.scr:1.8.2]
    at org.osgi.util.tracker.BundleTracker$Tracked.customizerModified(BundleTracker.java:479)[4:org.apache.felix.scr:1.8.2]
    at org.osgi.util.tracker.BundleTracker$Tracked.customizerModified(BundleTracker.java:414)[4:org.apache.felix.scr:1.8.2]
    at org.osgi.util.tracker.AbstractTracked.track(AbstractTracked.java:232)[4:org.apache.felix.scr:1.8.2]
    at org.osgi.util.tracker.BundleTracker$Tracked.bundleChanged(BundleTracker.java:443)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.framework.util.EventDispatcher.invokeBundleListenerCallback(EventDispatcher.java:869)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.util.EventDispatcher.fireEventImmediately(EventDispatcher.java:790)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.util.EventDispatcher.fireBundleEvent(EventDispatcher.java:515)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.Felix.fireBundleEvent(Felix.java:4429)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.Felix.startBundle(Felix.java:2100)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:976)[org.apache.felix.framework-4.4.1.jar:]
    at aQute.launcher.Launcher.update(Launcher.java:436)[biz.aQute.launcher-latest.jar:]
    at aQute.launcher.Launcher$1.run(Launcher.java:194)[biz.aQute.launcher-latest.jar:]
    at java.util.TimerThread.mainLoop(Unknown Source)[:1.8.0_25]
    at java.util.TimerThread.run(Unknown Source)[:1.8.0_25]
Caused by: java.lang.ClassNotFoundException: com.google.common.base.Predicate not found by org.apache.servicemix.bundles.reflections [205]
    at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1556)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:77)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1993)[org.apache.felix.framework-4.4.1.jar:]
    at java.lang.ClassLoader.loadClass(Unknown Source)[:1.8.0_25]
    ... 43 more
</code>```

What I noticed is that in the org.apache.servicemix.bundles.reflections bundle the import-package com.google.common.base is optional.
This means it should even be able to work without that package?
I cannot remove the com.google.guava bundle, because it is required for the org.optaplanner.core bundle.

What other things can I try to make this work? Anyone else already managed to get optaplanner working in an osgi environment?

Best regards,
Sigi

答:
I got it working for our case. I wrapped all binaries in one bundle and made some imports optional.

We use BndTools. The .bnd file looks like this:

```<code>Bundle-Version: 6.5.0.${tstamp}
Service-Component:  \
    *
Export-Package:  \
    org.optaplanner.core.api.*,\
    org.optaplanner.core.impl.*,\
    org.optaplanner.core.config.*;
Include-Resource:  \
    @binaries/annotations-2.0.1.jar,\
    @binaries/antlr-runtime-3.5.jar,\
    @binaries/commons-codec-1.4.jar,\
    @binaries/commons-io-2.1.jar,\
    @binaries/commons-lang3-3.1.jar,\
    @binaries/commons-math3-3.4.1.jar,\
    @binaries/drools-compiler-6.5.0.Final.jar,\
    @binaries/drools-core-6.5.0.Final.jar,\
    @binaries/ecj-4.4.2.jar,\
    @binaries/freemarker-2.3.19.jar,\
    @binaries/guava-13.0.1.jar,\
    @binaries/javassist-3.18.1-GA.jar,\
    @binaries/jcommon-1.0.23.jar,\
    @binaries/jfreechart-1.0.19.jar,\
    @binaries/kie-api-6.5.0.Final.jar,\
    @binaries/kie-internal-6.5.0.Final.jar,\
    @binaries/mvel2-2.2.8.Final.jar,\
    @binaries/optaplanner-benchmark-6.5.0.Final.jar,\
    @binaries/optaplanner-core-6.5.0.Final.jar,\
    @binaries/optaplanner-persistence-common-6.5.0.Final.jar,\
    @binaries/optaplanner-persistence-xstream-6.5.0.Final.jar,\
    @binaries/protobuf-java-2.6.0.jar,\
    @binaries/reflections-0.9.10.jar,\
    @binaries/slf4j-api-1.7.2.jar,\
    @binaries/xmlpull-1.1.3.1.jar,\
    @binaries/xpp3_min-1.1.4c.jar,\
    @binaries/xstream-1.4.9.jar

Import-Package:  \
    com.bea.xml.stream;resolution:=optional,\
    com.google.gson;resolution:=optional,\
    com.sun.codemodel;resolution:=optional,\
    com.sun.jdi;resolution:=optional,\
    com.sun.jdi.connect;resolution:=optional,\
    com.sun.jdi.event;resolution:=optional,\
    com.sun.jdi.request;resolution:=optional,\
    com.sun.org.apache.xml.internal.utils;resolution:=optional,\
    com.sun.org.apache.xpath.internal;resolution:=optional,\
    com.sun.org.apache.xpath.internal.objects;resolution:=optional,\
    com.sun.tools.xjc;resolution:=optional,\
    com.sun.tools.xjc.model;resolution:=optional,\
    com.sun.tools.xjc.outline;resolution:=optional,\
    javax.el;resolution:=optional,\
    javax.enterprise.context;resolution:=optional,\
    javax.enterprise.context.spi;resolution:=optional,\
    javax.enterprise.event;resolution:=optional,\
    javax.enterprise.inject;resolution:=optional,\
    javax.enterprise.inject.spi;resolution:=optional,\
    javax.inject;resolution:=optional,\
    javax.enterprise.util;resolution:=optional,\
    javax.servlet.jsp;resolution:=optional,\
    javax.servlet.jsp.el;resolution:=optional,\
    javax.servlet.jsp.tagext;resolution:=optional,\
    net.sf.cglib.proxy;resolution:=optional,\
    nu.xom;resolution:=optional,\
    org.antlr.stringtemplate;resolution:=optional,\
    org.apache.commons.vfs2;resolution:=optional,\
    org.apache.log;resolution:=optional,\
    org.apache.tools.ant;resolution:=optional,\
    org.apache.tools.ant.taskdefs;resolution:=optional,\
    org.apache.tools.ant.taskdefs.compilers;resolution:=optional,\
    org.apache.tools.ant.types;resolution:=optional,\
    org.apache.tools.ant.util;resolution:=optional,\
    org.apache.xml.utils;resolution:=optional,\
    org.apache.xpath;resolution:=optional,\
    org.apache.xpath.objects;resolution:=optional,\
    org.codehaus.janino;resolution:=optional,\
    org.codehaus.janino.util;resolution:=optional,\
    org.codehaus.janino.util.enumerator;resolution:=optional,\
    org.codehaus.janino.util.resource;resolution:=optional,\
    org.codehaus.jettison;resolution:=optional,\
    org.codehaus.jettison.mapped;resolution:=optional,\
    org.dom4j;resolution:=optional,\
    org.dom4j.io;resolution:=optional,\
    org.dom4j.tree;resolution:=optional,\
    org.eclipse.jdt.core.index;resolution:=optional,\
    org.eclipse.jdt.core.util;resolution:=optional,\
    org.jaxen;resolution:=optional,\
    org.jaxen.dom;resolution:=optional,\
    org.jaxen.dom4j;resolution:=optional,\
    org.jaxen.jdom;resolution:=optional,\
    org.jdom;resolution:=optional,\
    org.jdom.input;resolution:=optional,\
    org.jdom.output;resolution:=optional,\
    org.jdom2;resolution:=optional,\
    org.jdom2.input;resolution:=optional,\
    org.joda.time;resolution:=optional,\
    org.joda.time.format;resolution:=optional,\
    org.kxml2.io;resolution:=optional,\
    org.mozilla.javascript;resolution:=optional,\
    org.python.core;resolution:=optional,\
    org.python.util;resolution:=optional,\
    org.slf4j.impl;resolution:=optional,\
    org.w3c.dom.traversal;resolution:=optional,\
    org.zeroturnaround.javarebel;resolution:=optional,\
    sun.misc;resolution:=optional,\
    *
</code>```

Maybe this is not the best way of doing this. But we can use this bundle in our osgi environment and our vehicle routing problem is being solved as expected.

Title: Optaplanner in osgi

Body:
I'm trying to get optaplanner 6.5.0 to work in an osgi environment.
I had to install following bundles to get all dependencies resolved:

OptaPlanner coreorg.optaplanner.core                                                            6.5.0.201610181310
XStream Corexstream                                                                             1.4.9
Apache Commons Mathorg.apache.commons.math3                                                     3.4.1
Drools :: Compilerorg.drools.compiler                                                           6.5.0.201610181300
Drools :: Coreorg.drools.core                                                                   6.5.0.201610181300
KIE :: Public APIorg.kie.api                                                                    6.5.0.201610181259
KIE :: Internalorg.kie.internalapi                                                              6.5.0.201610181259
Protocol Buffer Java APIcom.google.protobuf                                                     2.6.0
mvel2org.mvel2                                                                                2.2.8.Final
Apache ServiceMix :: Bundles :: javax.injectorg.apache.servicemix.bundles.javax-inject          1.0.0.2
XML Pull Parsing APIorg.xmlpull.v1                                                              1.1.4.redhat-1
Apache ServiceMix :: Bundles :: xpp3org.apache.servicemix.bundles.xpp3                          1.1.4.c
Apache ServiceMix :: Specs :: Activation API 1.4org.apache.servicemix.specs.activation-api-1.1  2.0.0
Apache ServiceMix :: Bundles :: jaxb-xjcorg.apache.servicemix.bundles.jaxb-xjc                  2.2.4.1
Apache ServiceMix :: Specs :: JAXB API 2.2org.apache.servicemix.specs.jaxb-api-2.2              2.9.0
Apache ServiceMix :: Specs :: Stax API 1.0org.apache.servicemix.specs.stax-api-1.0              2.9.0
Apache ServiceMix :: Bundles :: jaxb-implorg.apache.servicemix.bundles.jaxb-impl                2.2.11.1
Apache ServiceMix :: Bundles :: reflectionsorg.apache.servicemix.bundles.reflections            0.9.11.1
OptaPlanner persistence commonorg.optaplanner.persistence.common                                6.5.0.201610181310
Sling Metrics :: CQ Fragmentcom.github.digital-wonderland.sling-metrics.cq-metrics-fragment     0.1.0
Guava: Google Core Libraries for Javacom.google.guava                                           18.0.0

When testing a simple example, which a got working through a junit test, I get following error:

java.lang.NoClassDefFoundError: com/google/common/base/Predicate
    at org.optaplanner.core.config.domain.ScanAnnotatedClassesConfig.buildSolutionDescriptor(ScanAnnotatedClassesConfig.java:69)
    at org.optaplanner.core.config.solver.SolverConfig.buildSolutionDescriptor(SolverConfig.java:278)
    at org.optaplanner.core.config.solver.SolverConfig.buildSolver(SolverConfig.java:229)
    at org.optaplanner.core.impl.solver.AbstractSolverFactory.buildSolver(AbstractSolverFactory.java:52)
    at com.bekaert.handling.allocation.optimizer.impl.OptimizerTest.before(OptimizerTest.java:55)
    at com.bekaert.handling.allocation.optimizer.impl.TestAllocationOptimizerImpl.activate(TestAllocationOptimizerImpl.java:14)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)[:1.8.0_25]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)[:1.8.0_25]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)[:1.8.0_25]
    at java.lang.reflect.Method.invoke(Unknown Source)[:1.8.0_25]
    at org.apache.felix.scr.impl.helper.BaseMethod.invokeMethod(BaseMethod.java:231)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.helper.BaseMethod.access$500(BaseMethod.java:39)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.helper.BaseMethod$Resolved.invoke(BaseMethod.java:624)
    at org.apache.felix.scr.impl.helper.BaseMethod.invoke(BaseMethod.java:508)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.helper.ActivateMethod.invoke(ActivateMethod.java:149)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.SingleComponentManager.createImplementationObject(SingleComponentManager.java:315)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.SingleComponentManager.createComponent(SingleComponentManager.java:127)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.SingleComponentManager.getService(SingleComponentManager.java:871)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.SingleComponentManager.getServiceInternal(SingleComponentManager.java:838)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.AbstractComponentManager.activateInternal(AbstractComponentManager.java:850)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.manager.AbstractComponentManager.enable(AbstractComponentManager.java:419)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.config.ConfigurableComponentHolder.enableComponents(ConfigurableComponentHolder.java:376)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.BundleComponentActivator.initialize(BundleComponentActivator.java:172)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.BundleComponentActivator.<init>(BundleComponentActivator.java:120)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.Activator.loadComponents(Activator.java:258)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.Activator.access$000(Activator.java:45)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.scr.impl.Activator$ScrExtension.start(Activator.java:185)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.utils.extender.AbstractExtender.createExtension(AbstractExtender.java:259)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.utils.extender.AbstractExtender.modifiedBundle(AbstractExtender.java:232)[4:org.apache.felix.scr:1.8.2]
    at org.osgi.util.tracker.BundleTracker$Tracked.customizerModified(BundleTracker.java:479)[4:org.apache.felix.scr:1.8.2]
    at org.osgi.util.tracker.BundleTracker$Tracked.customizerModified(BundleTracker.java:414)[4:org.apache.felix.scr:1.8.2]
    at org.osgi.util.tracker.AbstractTracked.track(AbstractTracked.java:232)[4:org.apache.felix.scr:1.8.2]
    at org.osgi.util.tracker.BundleTracker$Tracked.bundleChanged(BundleTracker.java:443)[4:org.apache.felix.scr:1.8.2]
    at org.apache.felix.framework.util.EventDispatcher.invokeBundleListenerCallback(EventDispatcher.java:869)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.util.EventDispatcher.fireEventImmediately(EventDispatcher.java:790)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.util.EventDispatcher.fireBundleEvent(EventDispatcher.java:515)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.Felix.fireBundleEvent(Felix.java:4429)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.Felix.startBundle(Felix.java:2100)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:976)[org.apache.felix.framework-4.4.1.jar:]
    at aQute.launcher.Launcher.update(Launcher.java:436)[biz.aQute.launcher-latest.jar:]
    at aQute.launcher.Launcher$1.run(Launcher.java:194)[biz.aQute.launcher-latest.jar:]
    at java.util.TimerThread.mainLoop(Unknown Source)[:1.8.0_25]
    at java.util.TimerThread.run(Unknown Source)[:1.8.0_25]
Caused by: java.lang.ClassNotFoundException: com.google.common.base.Predicate not found by org.apache.servicemix.bundles.reflections [205]
    at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1556)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:77)[org.apache.felix.framework-4.4.1.jar:]
    at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1993)[org.apache.felix.framework-4.4.1.jar:]
    at java.lang.ClassLoader.loadClass(Unknown Source)[:1.8.0_25]
    ... 43 more

What I noticed is that in the org.apache.servicemix.bundles.reflections bundle the import-package com.google.common.base is optional.
This means it should even be able to work without that package?
I cannot remove the com.google.guava bundle, because it is required for the org.optaplanner.core bundle.

What other things can I try to make this work? Anyone else already managed to get optaplanner working in an osgi environment?

Best regards,
Sigi

Body:
I got it working for our case. I wrapped all binaries in one bundle and made some imports optional.

We use BndTools. The .bnd file looks like this:

Bundle-Version: 6.5.0.${tstamp}
Service-Component:  \
    *
Export-Package:  \
    org.optaplanner.core.api.*,\
    org.optaplanner.core.impl.*,\
    org.optaplanner.core.config.*;
Include-Resource:  \
    @binaries/annotations-2.0.1.jar,\
    @binaries/antlr-runtime-3.5.jar,\
    @binaries/commons-codec-1.4.jar,\
    @binaries/commons-io-2.1.jar,\
    @binaries/commons-lang3-3.1.jar,\
    @binaries/commons-math3-3.4.1.jar,\
    @binaries/drools-compiler-6.5.0.Final.jar,\
    @binaries/drools-core-6.5.0.Final.jar,\
    @binaries/ecj-4.4.2.jar,\
    @binaries/freemarker-2.3.19.jar,\
    @binaries/guava-13.0.1.jar,\
    @binaries/javassist-3.18.1-GA.jar,\
    @binaries/jcommon-1.0.23.jar,\
    @binaries/jfreechart-1.0.19.jar,\
    @binaries/kie-api-6.5.0.Final.jar,\
    @binaries/kie-internal-6.5.0.Final.jar,\
    @binaries/mvel2-2.2.8.Final.jar,\
    @binaries/optaplanner-benchmark-6.5.0.Final.jar,\
    @binaries/optaplanner-core-6.5.0.Final.jar,\
    @binaries/optaplanner-persistence-common-6.5.0.Final.jar,\
    @binaries/optaplanner-persistence-xstream-6.5.0.Final.jar,\
    @binaries/protobuf-java-2.6.0.jar,\
    @binaries/reflections-0.9.10.jar,\
    @binaries/slf4j-api-1.7.2.jar,\
    @binaries/xmlpull-1.1.3.1.jar,\
    @binaries/xpp3_min-1.1.4c.jar,\
    @binaries/xstream-1.4.9.jar

Import-Package:  \
    com.bea.xml.stream;resolution:=optional,\
    com.google.gson;resolution:=optional,\
    com.sun.codemodel;resolution:=optional,\
    com.sun.jdi;resolution:=optional,\
    com.sun.jdi.connect;resolution:=optional,\
    com.sun.jdi.event;resolution:=optional,\
    com.sun.jdi.request;resolution:=optional,\
    com.sun.org.apache.xml.internal.utils;resolution:=optional,\
    com.sun.org.apache.xpath.internal;resolution:=optional,\
    com.sun.org.apache.xpath.internal.objects;resolution:=optional,\
    com.sun.tools.xjc;resolution:=optional,\
    com.sun.tools.xjc.model;resolution:=optional,\
    com.sun.tools.xjc.outline;resolution:=optional,\
    javax.el;resolution:=optional,\
    javax.enterprise.context;resolution:=optional,\
    javax.enterprise.context.spi;resolution:=optional,\
    javax.enterprise.event;resolution:=optional,\
    javax.enterprise.inject;resolution:=optional,\
    javax.enterprise.inject.spi;resolution:=optional,\
    javax.inject;resolution:=optional,\
    javax.enterprise.util;resolution:=optional,\
    javax.servlet.jsp;resolution:=optional,\
    javax.servlet.jsp.el;resolution:=optional,\
    javax.servlet.jsp.tagext;resolution:=optional,\
    net.sf.cglib.proxy;resolution:=optional,\
    nu.xom;resolution:=optional,\
    org.antlr.stringtemplate;resolution:=optional,\
    org.apache.commons.vfs2;resolution:=optional,\
    org.apache.log;resolution:=optional,\
    org.apache.tools.ant;resolution:=optional,\
    org.apache.tools.ant.taskdefs;resolution:=optional,\
    org.apache.tools.ant.taskdefs.compilers;resolution:=optional,\
    org.apache.tools.ant.types;resolution:=optional,\
    org.apache.tools.ant.util;resolution:=optional,\
    org.apache.xml.utils;resolution:=optional,\
    org.apache.xpath;resolution:=optional,\
    org.apache.xpath.objects;resolution:=optional,\
    org.codehaus.janino;resolution:=optional,\
    org.codehaus.janino.util;resolution:=optional,\
    org.codehaus.janino.util.enumerator;resolution:=optional,\
    org.codehaus.janino.util.resource;resolution:=optional,\
    org.codehaus.jettison;resolution:=optional,\
    org.codehaus.jettison.mapped;resolution:=optional,\
    org.dom4j;resolution:=optional,\
    org.dom4j.io;resolution:=optional,\
    org.dom4j.tree;resolution:=optional,\
    org.eclipse.jdt.core.index;resolution:=optional,\
    org.eclipse.jdt.core.util;resolution:=optional,\
    org.jaxen;resolution:=optional,\
    org.jaxen.dom;resolution:=optional,\
    org.jaxen.dom4j;resolution:=optional,\
    org.jaxen.jdom;resolution:=optional,\
    org.jdom;resolution:=optional,\
    org.jdom.input;resolution:=optional,\
    org.jdom.output;resolution:=optional,\
    org.jdom2;resolution:=optional,\
    org.jdom2.input;resolution:=optional,\
    org.joda.time;resolution:=optional,\
    org.joda.time.format;resolution:=optional,\
    org.kxml2.io;resolution:=optional,\
    org.mozilla.javascript;resolution:=optional,\
    org.python.core;resolution:=optional,\
    org.python.util;resolution:=optional,\
    org.slf4j.impl;resolution:=optional,\
    org.w3c.dom.traversal;resolution:=optional,\
    org.zeroturnaround.javarebel;resolution:=optional,\
    sun.misc;resolution:=optional,\
    *

Maybe this is not the best way of doing this. But we can use this bundle in our osgi environment and our vehicle routing problem is being solved as expected.


来源: stackexchange

问:
White textures with OpenGL and DevIL on some Windows systems
I'm having some problems trying to load images with DevIL and creating textures in OpenGL. When a friend of mine tested my program on his Windows, all the rects, whom were supposed to contain textures, were white, without any image (texture). The problem seems to occur only on Window XP, Windows Vista and Windows 7, but not in every Windows PC: my Windows XP runs the program without problems.

Maybe there're some missing DLLs or files (improbable), or something that don't let the image to be loaded or used as a texture. By the other hand, the program runs fine on *UNIX systems.

This is the code I'm using to load an image and generate a texture:

```<code>void Image::load(const char* filename)
{
    ILuint ilimg;

    ilGenImages(1, &ilimg);
    ilBindImage(ilimg);

    if (!ilLoadImage(filename))
        throw ImageLoadError;

    glGenTextures(1, &image);
    glBindTexture(GL_TEXTURE_2D, image);

    bpp = ilGetInteger(IL_IMAGE_BPP);
    width = ilGetInteger(IL_IMAGE_WIDTH);
    height = ilGetInteger(IL_IMAGE_HEIGHT);
    format = ilGetInteger(IL_IMAGE_FORMAT);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    glTexImage2D(GL_TEXTURE_2D, 0, bpp, width, height, 0, format,
        GL_UNSIGNED_BYTE, ilGetData());

    ilDeleteImages(1, &ilimg);
}
</code>```

This is the code that draws a rect with the texture applied:

```<code>void Rect::show()
{
    glPushAttrib(GL_CURRENT_BIT);

    glEnable(GL_TEXTURE_2D);
    glColor4f(1.0, 1.0, 1.0, opacity);
    glBindTexture(GL_TEXTURE_2D, texture->get_image());

    glBegin(GL_POLYGON);
        glTexCoord2i(0, 0); glVertex2f(x, y);
        glTexCoord2i(1, 0); glVertex2f(x+width, y);
        glTexCoord2i(1, 1); glVertex2f(x+width, y+height);
        glTexCoord2i(0, 1); glVertex2f(x, y+height);
    glEnd();

    glDisable(GL_TEXTURE_2D);

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

If you need some other code that I don't  mentioned, ask me and i'll post it.

答:
```<code>glTexImage2D(target, level, internal format, width, height, border, format, type, data);
</code>```

The internal format parameter of glTexImage is not bits per pixel. Actually its numerical value is not related to the format at all. OpenGL defines only specific values to be valid, among them also four with numeric relation, but just as a mnemonic: 1 (shorthand for GL_LUMINANCE), 2 (GL_LUMINANCE_ALPHA), 3 (GL_RGB), 4 (GL_RGBA). There are also a number of other format tokens, but their numeric value is arbitrarily choosen.

Also the bpp for the image data is used to find the format and type parameters. You'll need to implement a LUT or switch-case structure for that.

ContentLicense: CC BY-SA 3.0

Body:
I'm having some problems trying to load images with DevIL and creating textures in OpenGL. When a friend of mine tested my program on his Windows, all the rects, whom were supposed to contain textures, were white, without any image (texture). The problem seems to occur only on Window XP, Windows Vista and Windows 7, but not in every Windows PC: my Windows XP runs the program without problems.

Maybe there're some missing DLLs or files (improbable), or something that don't let the image to be loaded or used as a texture. By the other hand, the program runs fine on *UNIX systems.

This is the code I'm using to load an image and generate a texture:

void Image::load(const char* filename)
{
    ILuint ilimg;

    ilGenImages(1, &ilimg);
    ilBindImage(ilimg);

    if (!ilLoadImage(filename))
        throw ImageLoadError;

    glGenTextures(1, &image);
    glBindTexture(GL_TEXTURE_2D, image);

    bpp = ilGetInteger(IL_IMAGE_BPP);
    width = ilGetInteger(IL_IMAGE_WIDTH);
    height = ilGetInteger(IL_IMAGE_HEIGHT);
    format = ilGetInteger(IL_IMAGE_FORMAT);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    glTexImage2D(GL_TEXTURE_2D, 0, bpp, width, height, 0, format,
        GL_UNSIGNED_BYTE, ilGetData());

    ilDeleteImages(1, &ilimg);
}

This is the code that draws a rect with the texture applied:

void Rect::show()
{
    glPushAttrib(GL_CURRENT_BIT);

    glEnable(GL_TEXTURE_2D);
    glColor4f(1.0, 1.0, 1.0, opacity);
    glBindTexture(GL_TEXTURE_2D, texture->get_image());

    glBegin(GL_POLYGON);
        glTexCoord2i(0, 0); glVertex2f(x, y);
        glTexCoord2i(1, 0); glVertex2f(x+width, y);
        glTexCoord2i(1, 1); glVertex2f(x+width, y+height);
        glTexCoord2i(0, 1); glVertex2f(x, y+height);
    glEnd();

    glDisable(GL_TEXTURE_2D);

    glPopAttrib();
}

If you need some other code that I don't  mentioned, ask me and i'll post it.

Body:
glTexImage2D(target, level, internal format, width, height, border, format, type, data);

The internal format parameter of glTexImage is not bits per pixel. Actually its numerical value is not related to the format at all. OpenGL defines only specific values to be valid, among them also four with numeric relation, but just as a mnemonic: 1 (shorthand for GL_LUMINANCE), 2 (GL_LUMINANCE_ALPHA), 3 (GL_RGB), 4 (GL_RGBA). There are also a number of other format tokens, but their numeric value is arbitrarily choosen.

Also the bpp for the image data is used to find the format and type parameters. You'll need to implement a LUT or switch-case structure for that.

ContentLicense: CC BY-SA 2.5


问:
passing variable in javascript function using django template
here I am passing {{id}} to hide_show(...) javascript function

```<code>{% for stock in part_temp.part_stock_set.all %}
    {% with id="list"|concatenate:stock.id %}
    <div id="{{ id }}">
    {{ stock.entry_date}}
    </div>
    <button type="button" onclick="hide_show({{ id }})">edit</button>
    <br>
        {{ id }}
</code>```

here above the {% endwith %} {{ id }} is displaying correctly but the hide_show function in not called but it is called when just {{ stock.id }} is passed to it.
the concatenate filter just concatenates and returns a string.

```<code>    <script type="text/javascript">
    function hide_show(temp) {
        document.getElementById(temp).style.display='none';
        window.alert(temp);
    }
</script>
</code>```

答:
Problem seems to be with the quotes. if {{ id }} returns a string, then you don't have to put quotes here

```<code><div id="{{ id }}">
</code>```

Simply replace it with:

```<code><div id={{ id }}>
</code>```

If id is an integer or if the above doesn't work, then you have to put quotes here as well as in the argument while calling the hide_show function.

Body:
here I am passing {{id}} to hide_show(...) javascript function

{% for stock in part_temp.part_stock_set.all %}
    {% with id="list"|concatenate:stock.id %}

    {{ stock.entry_date}}

    <button type="button" onclick="hide_show({{ id }})">edit</button>

        {{ id }}

here above the {% endwith %} {{ id }} is displaying correctly but the hide_show function in not called but it is called when just {{ stock.id }} is passed to it.
the concatenate filter just concatenates and returns a string.

Body:
Problem seems to be with the quotes. if {{ id }} returns a string, then you don't have to put quotes here

<div id="{{ id }}">

Simply replace it with:

<div id={{ id }}>

If id is an integer or if the above doesn't work, then you have to put quotes here as well as in the argument while calling the hide_show function.


问:
Unable to return nil in generic function
I am trying to understand generics better and am writing a function, that finds a key in a given dictionary with a given value.
If the value is not found it should return nil.

```<code>func findKey<Key, Value: Equatable>(for value: Value, in dictionary: [Key: Value]) -> Key {
    for set in dictionary {
        if set.value == value {
            return set.key
        }
    }
    return nil //ERROR: Nil is incompatible with Type 'Key'
}
</code>```

I reveice this error:

Nil is incompatible with Type 'Key'

答:
Your function is set to return a Key as indicated by -> Key

You cannot return a nil because Key is an unwrapped variable. Instead, you can set the function to return an Optional which means that it can either have a Key, or it can be nil. Simply add a ? after the return type

```<code>func findKey<Key, Value: Equatable>(for value: Value, in dictionary: [Key: Value]) -> Key? {
    for set in dictionary {
        if set.value == value {
            return set.key
        }
    }
    return nil
}
</code>```

Body:
I am trying to understand generics better and am writing a function, that finds a key in a given dictionary with a given value.
If the value is not found it should return nil.

func findKey<Key, Value: Equatable>(for value: Value, in dictionary: [Key: Value]) -> Key {
    for set in dictionary {
        if set.value == value {
            return set.key
        }
    }
    return nil //ERROR: Nil is incompatible with Type 'Key'
}

I reveice this error:

Nil is incompatible with Type 'Key'

Body:
Your function is set to return a Key as indicated by -> Key

You cannot return a nil because Key is an unwrapped variable. Instead, you can set the function to return an Optional which means that it can either have a Key, or it can be nil. Simply add a ? after the return type

func findKey<Key, Value: Equatable>(for value: Value, in dictionary: [Key: Value]) -> Key? {
    for set in dictionary {
        if set.value == value {
            return set.key
        }
    }
    return nil
}


答:
In order to return nil you need to return a Key Optional " Key? "

You can read more about optionals here.

```<code>func findKey<Key, Value: Equatable>(for value: Value, in dictionary: [Key: Value]) -> Key? {
   for set in dictionary {
       if set.value == value {
           return set.key
       }
   }
   return nil
}
</code>```

Title: Unable to return nil in generic function

Body:
In order to return nil you need to return a Key Optional " Key? "

You can read more about optionals here.

func findKey<Key, Value: Equatable>(for value: Value, in dictionary: [Key: Value]) -> Key? {
   for set in dictionary {
       if set.value == value {
           return set.key
       }
   }
   return nil
}


问:
Is there a way that a trigger on parent table will also listen to all child tables in Postgres?
I have a parent table and more than 800 child tables for each of the clients. I want to create the same trigger for each of them. Is there a way that I can directly create it for the parent table and each child table will listen to it?

I can write a script to create the same for each client table but I am specifically looking for any direct solution.

答:
If you use inherit then you create the trigger for the main table and the changes occurs on the child table.

This is an example for insert trigger, you can see I only insert on the main table avl same go for updates or deletes.

```<code>CREATE OR REPLACE FUNCTION avl_db.avl_insert_trigger()
  RETURNS trigger AS
$BODY$
BEGIN
    IF ( NEW.event_time >= '2017-06-01 00:00:00' AND NEW.event_time < '2017-06-02 00:00:00' ) THEN
        INSERT INTO avl_db.avl_20170601 VALUES (NEW.*);
    ELSEIF ( NEW.event_time >= '2017-06-02 00:00:00' AND NEW.event_time < '2017-06-03 00:00:00' ) THEN
        INSERT INTO avl_db.avl_20170602 VALUES (NEW.*);
    ELSEIF ( NEW.event_time >= '2017-06-03 00:00:00' AND NEW.event_time < '2017-06-04 00:00:00' ) THEN
        INSERT INTO avl_db.avl_20170603 VALUES (NEW.*);
    ELSEIF ( NEW.event_time >= '2017-06-04 00:00:00' AND NEW.event_time < '2017-06-05 00:00:00' ) THEN
        INSERT INTO avl_db.avl_20170604 VALUES (NEW.*);
    ELSEIF ( NEW.event_time >= '2017-06-05 00:00:00' AND NEW.event_time < '2017-06-06 00:00:00' ) THEN
        INSERT INTO avl_db.avl_20170605 VALUES (NEW.*);
....
    ELSE
        RAISE EXCEPTION 'Date out of range.';
    END IF;

    RETURN NULL; -- avoid insert in the main table
</code>```

More details on this question I just made

Body:
If you use inherit then you create the trigger for the main table and the changes occurs on the child table.

This is an example for insert trigger, you can see I only insert on the main table avl same go for updates or deletes.

CREATE OR REPLACE FUNCTION avl_db.avl_insert_trigger()
  RETURNS trigger AS
$BODY$
BEGIN
    IF ( NEW.event_time >= '2017-06-01 00:00:00' AND NEW.event_time < '2017-06-02 00:00:00' ) THEN
        INSERT INTO avl_db.avl_20170601 VALUES (NEW.*);
    ELSEIF ( NEW.event_time >= '2017-06-02 00:00:00' AND NEW.event_time < '2017-06-03 00:00:00' ) THEN
        INSERT INTO avl_db.avl_20170602 VALUES (NEW.*);
    ELSEIF ( NEW.event_time >= '2017-06-03 00:00:00' AND NEW.event_time < '2017-06-04 00:00:00' ) THEN
        INSERT INTO avl_db.avl_20170603 VALUES (NEW.*);
    ELSEIF ( NEW.event_time >= '2017-06-04 00:00:00' AND NEW.event_time < '2017-06-05 00:00:00' ) THEN
        INSERT INTO avl_db.avl_20170604 VALUES (NEW.*);
    ELSEIF ( NEW.event_time >= '2017-06-05 00:00:00' AND NEW.event_time < '2017-06-06 00:00:00' ) THEN
        INSERT INTO avl_db.avl_20170605 VALUES (NEW.*);
....
    ELSE
        RAISE EXCEPTION 'Date out of range.';
    END IF;

    RETURN NULL; -- avoid insert in the main table

More details on this question I just made


问:
UIImageview and UItextview in table view cells
I have a table view cell that may or may not have images , but always has the textview. Both are displayed inline with each other horizontally, with image(if there) appearing on left  and then textview. Else if no image , just the textview on left. I have it success with just the text view.
I am trying to set the constraint on image by pinning the leading and top constraints to superview. The leading constraint of textview is pinned to the trailing edge of image view . The image view(if there) is still appearing on the textview. It's not shifting to right . Where am I wrong?</p>

答:
Add leading, top and bottom constraint to imageView.

Now apply width constraints to imageView.

Now Drag a TextView and add leading constraint to imageView, top, bottom and trailing constraint as shown below.

Finally, create a IBOutlet to the imageView's width constraint. In cellForRowAtIndexPath if the cell needs to show the image then set the width constraint to whatever the width you wanna set to else set it to 0. Thats all. TextView will automatically move to left if there is no image and will be placed next to imageView if cell has any

```<code>//if cell has image
cell.imageViewWidthConstarint.constant = 82

//if cell does not show image
cell.imageViewWidthConstarint.constant = 0
</code>```

Hope it helps

Body:
Add leading, top and bottom constraint to imageView.

Now apply width constraints to imageView.

Now Drag a TextView and add leading constraint to imageView, top, bottom and trailing constraint as shown below.

Finally, create a IBOutlet to the imageView's width constraint. In cellForRowAtIndexPath if the cell needs to show the image then set the width constraint to whatever the width you wanna set to else set it to 0. Thats all. TextView will automatically move to left if there is no image and will be placed next to imageView if cell has any

//if cell has image
cell.imageViewWidthConstarint.constant = 82

//if cell does not show image
cell.imageViewWidthConstarint.constant = 0

Hope it helps


问:
Sidekiq-scheduler passing arguments
I have a use case where I need to do do some task 1 day after a product is uploaded.
My worker class is written below:

```<code>require 'sidekiq-scheduler'
class ProductWorker < ActiveRecord::Base
   include Sidekiq::Worker
   def self.day_after_upload(product_id)
      #do something
   end
   def self.week_after_upload(product_id)
      #do something
   end
end
</code>```

My product controller is below

```<code>class ProductsController < ApplicationController
   def create
      product=Product.new(product_params)
      if product.save!
          Sidekiq.set_schedule('day_after_upload', { 'at' => [prduct.created_at+1.day], 'class' => 'ProductWorker' })
          Sidekiq.set_schedule('week_after_upload', { 'at' => [product.created_at+1.week], 'class' => 'ProductWorker' })
      end
    end
end
</code>```

I am having trouble passing the 'product_id' parameter to the worker. I couldn't find how to pass custom parameter on sidekiq-scheduler github page . How do I pass custom parameters and do I need to make some other changes for this to work? Any help is appreciated.

答:
Scheduled jobs are built into Sidekiq, I don't know why you are using sidekiq-scheduler.

```<code>OneDayWorker.perform_in(1.day, product_id)
OneWeekWorker.perform_in(1.week, product_id)
</code>```

https://github.com/mperham/sidekiq/wiki/Scheduled-Jobs

Title: Sidekiq-scheduler passing arguments

Body:
I have a use case where I need to do do some task 1 day after a product is uploaded.
My worker class is written below:

require 'sidekiq-scheduler'
class ProductWorker < ActiveRecord::Base
   include Sidekiq::Worker
   def self.day_after_upload(product_id)
      #do something
   end
   def self.week_after_upload(product_id)
      #do something
   end
end

My product controller is below

class ProductsController < ApplicationController
   def create
      product=Product.new(product_params)
      if product.save!
          Sidekiq.set_schedule('day_after_upload', { 'at' => [prduct.created_at+1.day], 'class' => 'ProductWorker' })
          Sidekiq.set_schedule('week_after_upload', { 'at' => [product.created_at+1.week], 'class' => 'ProductWorker' })
      end
    end
end

I am having trouble passing the 'product_id' parameter to the worker. I couldn't find how to pass custom parameter on sidekiq-scheduler github page . How do I pass custom parameters and do I need to make some other changes for this to work? Any help is appreciated.

Body:
Scheduled jobs are built into Sidekiq, I don't know why you are using sidekiq-scheduler.

OneDayWorker.perform_in(1.day, product_id)
OneWeekWorker.perform_in(1.week, product_id)

https://github.com/mperham/sidekiq/wiki/Scheduled-Jobs


问:
does node js mysql needs apache
I have recently wanted to use a MySQL database with my node.js server. And after doing some digging, I found the following github page for mysql to be used via node.js:

https://github.com/mysqljs/mysql

However what I wasn't sure is if this is an API that allows for node.js to communicate with a MySQL database, or if this is a full implementation of a MySQL database (hence I wouldn't need to install apache). Since I tried implementing this without an apache server, it gave me an error:

code run (after having doing npm install mysql)

```<code>var mysql = require('mysql');

var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'articles'
});

connection.connect();
</code>```

error:

[Error: connect ECONNREFUSED 127.0.0.1:3306]

答:
"Apache" commonly refers to the Apache httpd program and that's just a web server. You can use that in conjunction with your Node app, for example via Passenger to handle process management and load-balancing.

MySQL is a separate package, a database server, that must be running if you want to make use of MySQL in your Node code. The NPM package for MySQL is just a driver, it needs a server to connect to, and if one isn't running where it's configured to connect you'll see an error like what you're getting.

The solution here is to install MySQL server on your machine, or make use of an existing MySQL server you control.

Sometimes people confuse "Apache" with things like MAMP which bundle a bunch of things together.

Title: does node js mysql needs apache

Body:
I have recently wanted to use a MySQL database with my node.js server. And after doing some digging, I found the following github page for mysql to be used via node.js:

https://github.com/mysqljs/mysql

However what I wasn't sure is if this is an API that allows for node.js to communicate with a MySQL database, or if this is a full implementation of a MySQL database (hence I wouldn't need to install apache). Since I tried implementing this without an apache server, it gave me an error:

code run (after having doing npm install mysql)

var mysql = require('mysql');

var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'articles'
});

connection.connect();

error:

[Error: connect ECONNREFUSED 127.0.0.1:3306]


问:
Update textbox with AJAX
When a dropdown's value changes, I need the values of two textboxes to change, based on the new value of the dropdown, without refreshing the page.

This should be dead easy, but I'm having trouble figuring out what makes AJAX tick. I seem to be able to get the value, but I can't set the textbox.

This similar question didn't help me. Neither did this.

JavaScript:

```<code>// Dropdown ID = PatientID, textbox ID = DoB
var patient = $("#PatientID");
patient.change(function () {
    var newDob;
    $.ajax({
        url: '@(Url.Action("PatientDob"))?patientId=' + patient.val(),
        type: "GET",
        success: function (result) {
            // Displays correct result
            alert(result);
            newDob = result;
        },
        error: function (xhr, status, err) {
            alert(err);
        }
    });
    // Causes the box to become blank, HTML value attribute doesn't change
    $("#DoB").val(newDob);
});
</code>```

Controller:

```<code>[HttpGet]
public string PatientDob(int patientId)
{
    return db.Patients.Find(patientId).DateOfBirth.ToString("MM/dd/yyyy");
}
</code>```

答:
Try to keep $("#DoB").val(result); inside the success function and see if it works.

Note: $("#DoB").val(newDob); is modified as $("#DoB").val(result);

ContentLicense: CC BY-SA 4.0

Title: Update textbox with AJAX

Body:
When a dropdown's value changes, I need the values of two textboxes to change, based on the new value of the dropdown, without refreshing the page.

This should be dead easy, but I'm having trouble figuring out what makes AJAX tick. I seem to be able to get the value, but I can't set the textbox.

This similar question didn't help me. Neither did this.

JavaScript:

// Dropdown ID = PatientID, textbox ID = DoB
var patient = $("#PatientID");
patient.change(function () {
    var newDob;
    $.ajax({
        url: '@(Url.Action("PatientDob"))?patientId=' + patient.val(),
        type: "GET",
        success: function (result) {
            // Displays correct result
            alert(result);
            newDob = result;
        },
        error: function (xhr, status, err) {
            alert(err);
        }
    });
    // Causes the box to become blank, HTML value attribute doesn't change
    $("#DoB").val(newDob);
});

Controller:

[HttpGet]
public string PatientDob(int patientId)
{
    return db.Patients.Find(patientId).DateOfBirth.ToString("MM/dd/yyyy");
}


问:
Is there any way to reduce element locating time in Selenium WebDriver?
I have one select city dropdown and there are around 8000 city presents. My usecase are:

Get the selected city name

If city name is not as expected then select the desired city

Now again get the city name to verify that desired city has been selected

My code is working fine but the issue is to complete these 3 steps it takes around 5-8 minutes. I know its due to the large set of city name available in dropdown

This is the dropdown HTML structure :

```<code><div class="col-md-12">
  <label class="mmk-filter-control">Preferred Source City : </label>
     <div class="pull-right refe-link">
     <div class="mmk-filter-control mmk-select-filter pull-right mr5">
     <select id="ddlPrefferedSourceCity" class="form-control" name="ddlPrefferedSourceCity">
          <option value="-1">- Select -</option>
          <option value="A.S.Peta Bypass">A.S.Peta Bypass</option>
          <option value="aadsar">aadsar</option>
          <option value="aagariya">aagariya</option>
          <option value="aahur">aahur</option>
          <option value="aakadiya">aakadiya</option>
          <option value="Aala">Aala</option>
          <option value="Aanjangaon">Aanjangaon</option>
           .
           .
          around 8000 options
</code>```

And code is:

```<code>if(usersname.size()>0)
{
     Select s = new Select(preferredCity);
     Comman.wait.until(ExpectedConditions.invisibilityOf(loader));
     String cityName  = s.getFirstSelectedOption().getText();
     if(cityName.equals(preferredCityName))
     {
         LogWriter.logger.info("Preferred City is already Selected");
         TakeScreenshot.passedScreenShot();
     }
     else
     {
         Comman.wait.until(ExpectedConditions.invisibilityOf(loader));
         LogWriter.logger.info("Last Selected Preferred City is : " + s.getFirstSelectedOption().getText());
         TakeScreenshot.passedScreenShot();
         s.selectByVisibleText(preferredCityName);
         setPreferenceButton.click();
         Comman.wait.until(ExpectedConditions.invisibilityOf(loader));
         LogWriter.logger.info("New Selected Preferred City is : " + s.getFirstSelectedOption().getText());
         TakeScreenshot.passedScreenShot();
     }
}
</code>```

Is there any way to overcome and make the test fast?

答:
While 8000 cities in a single dropdown is a questionable design, it might not be the whole issue. I created a simple HTML file that contained 100,000 options and selected a value from that list and it was complete in 12s, including loading the entire page. Granted it wasn't hosted on the web. Your internet connection and/or the site's speed may be factors.

I would look at a few things:

You seem to be using WebDriverWait in Comman.wait (Common is misspelled, btw). Are you also using an implicit wait? If so, the docs state not to mix both.

WARNING: Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times.

If you are, remove the implicit wait and see if that helps.

Next I would try getting some timings. Add a timing between each of the steps to see where the long waits lie. With that info, you will have a better idea of where the delays are coming from and how to address them.

You are waiting for the loader to be invisible more than I think is necessary. It shouldn't matter but removing some of them might help, especially if you are using an implicit wait (see #1). You wait for it after you grab the SELECT, which shouldn't be needed. You wait for it again in the first line of the else but you haven't done anything that should trigger a loader. The only place that seems reasonable is the 3rd instance, after you select the item from the dropdown.

Have you tried selecting by value instead of by visible text? It may not matter but I'm not really sure how it finds visible text.

Another option is to avoid use of the Select class altogether. While it's a good practice to use it normally because it makes dealing with SELECT so much easier, in this case it may be contributing to the performance issue.

One way to get around it may be to go after the option directly using a CSS selector, e.g. #ddlPrefferedSourceCity > option[value='" + preferredCityName + "']. I tried this on my local machine and it was slightly faster... but it's a difference of 1.2s vs .6s.

Body:
I have one select city dropdown and there are around 8000 city presents. My usecase are:

Get the selected city name

If city name is not as expected then select the desired city

Now again get the city name to verify that desired city has been selected

My code is working fine but the issue is to complete these 3 steps it takes around 5-8 minutes. I know its due to the large set of city name available in dropdown

This is the dropdown HTML structure :

  Preferred Source City :

     <select id="ddlPrefferedSourceCity" class="form-control" name="ddlPrefferedSourceCity">
          <option value="-1">- Select -</option>
          <option value="A.S.Peta Bypass">A.S.Peta Bypass</option>
          <option value="aadsar">aadsar</option>
          <option value="aagariya">aagariya</option>
          <option value="aahur">aahur</option>
          <option value="aakadiya">aakadiya</option>
          <option value="Aala">Aala</option>
          <option value="Aanjangaon">Aanjangaon</option>
           .
           .
          around 8000 options

And code is:

if(usersname.size()>0)
{
     Select s = new Select(preferredCity);
     Comman.wait.until(ExpectedConditions.invisibilityOf(loader));
     String cityName  = s.getFirstSelectedOption().getText();
     if(cityName.equals(preferredCityName))
     {
         LogWriter.logger.info("Preferred City is already Selected");
         TakeScreenshot.passedScreenShot();
     }
     else
     {
         Comman.wait.until(ExpectedConditions.invisibilityOf(loader));
         LogWriter.logger.info("Last Selected Preferred City is : " + s.getFirstSelectedOption().getText());
         TakeScreenshot.passedScreenShot();
         s.selectByVisibleText(preferredCityName);
         setPreferenceButton.click();
         Comman.wait.until(ExpectedConditions.invisibilityOf(loader));
         LogWriter.logger.info("New Selected Preferred City is : " + s.getFirstSelectedOption().getText());
         TakeScreenshot.passedScreenShot();
     }
}

Is there any way to overcome and make the test fast?


问:
Data is not getting stored in mySQL database using XAMPP
I have created a database in mysql using XAMPP named test226333  I am trying to send data to the table like this

"http://localhost/write_data.php?value=100"

for database and table details screenshot click here

My php code is

```<code><?php

$dbusername = "ganesh";
$dbpassword = "varma";
$server = "localhost";

$dbconnect = mysql_connect($server, $dbusername, $dbpassword);
$dbselect = mysql_select_db("test226333",$dbconnect);

$sql = "INSERT INTO test226333.data VALUES ('".$_GET["value"]."')";

mysql_query($sql);

?>
</code>```

Nothing is showing while entering into the link and also data is not getting stored in the database

please help me in this

Thanks in advance..

答:
Try this:</p>

```<code>  $servername = "localhost";
    $username = "ganesh";
    $password = "varma";
    $dbname = "test226333";
    $mysqli = new mysqli($servername, $username, $password, $dbname);
    if ($mysqli->connect_errno) {
        echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    }

    /* Prepared statement, stage 1: prepare */
    if (!($stmt = $mysqli->prepare("INSERT INTO <your table name>(col1, col2, col3) VALUES (?, ?, ?)"))) {
         echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
    }

    /* Prepared statement, stage 2: bind and execute */

    if (!$stmt->bind_param("i", $val1)) {
        echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
    }
 if (!$stmt->bind_param("s", $val2)) {
        echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
    }
if (!$stmt->bind_param("i", $val3)) {
        echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
    }

    if (!$stmt->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }

    /* explicit close recommended */
    $stmt->close();
</code>```

Body:
I have created a database in mysql using XAMPP named test226333  I am trying to send data to the table like this

"http://localhost/write_data.php?value=100"

for database and table details screenshot click here

My php code is

<?php

$dbusername = "ganesh";
$dbpassword = "varma";
$server = "localhost";

$dbconnect = mysql_connect($server, $dbusername, $dbpassword);
$dbselect = mysql_select_db("test226333",$dbconnect);

$sql = "INSERT INTO test226333.data VALUES ('".$_GET["value"]."')";

mysql_query($sql);

?>

Nothing is showing while entering into the link and also data is not getting stored in the database

please help me in this

Thanks in advance..

Body:
Try this:

  $servername = "localhost";
    $username = "ganesh";
    $password = "varma";
    $dbname = "test226333";
    $mysqli = new mysqli($servername, $username, $password, $dbname);
    if ($mysqli->connect_errno) {
        echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    }

    /* Prepared statement, stage 1: prepare */
    if (!($stmt = $mysqli->prepare("INSERT INTO <your table name>(col1, col2, col3) VALUES (?, ?, ?)"))) {
         echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
    }

    /* Prepared statement, stage 2: bind and execute */

    if (!$stmt->bind_param("i", $val1)) {
        echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
    }
 if (!$stmt->bind_param("s", $val2)) {
        echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
    }
if (!$stmt->bind_param("i", $val3)) {
        echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
    }

    if (!$stmt->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }

    /* explicit close recommended */
    $stmt->close();


问:
How to convert a dictionary of strings into a block of text with python
I have a dictionary full of string-valued k-v pairs, and I want each to be separated by ==>& then printed to a newline.

I use an array to mediate the transformation, which seems unnecessary & inelegant. I'd like to do this in 1 line if possible.

Here's what I have:

```<code>foo_dict = {
    'a' : '1',
    'b' : '2',
    'c' : '3',
    }
foo_list = []
for k, v in foo_dict.items():
    foo_list.append('{} ==> {}'.format(k, v))
foo_text = '\n'.join(foo_list)
</code>```

this will print:

```<code>b ==> 2
c ==> 3
a ==> 1
</code>```

the order doesn't matter (otherwise I'd just use OrderedDict.) What matters is that all k-v pairs get printed in the correct format.

答:
The following one-liner will do:

```<code>foo_text = '\n'.join('{} ==> {}'.format(*t) for t in foo_dict.items())
</code>```

Or we can use a starmap(..):

```<code>from itertools import starmap

foo_text = '\n'.join(starmap('{} ==> {}'.format,foo_dict.items()))
</code>```

Both generate:

```<code>>>> '\n'.join('{} ==> {}'.format(*t) for t in foo_dict.items())
'b ==> 2\na ==> 1\nc ==> 3'
>>> '\n'.join(starmap('{} ==> {}'.format,foo_dict.items()))
'b ==> 2\na ==> 1\nc ==> 3'
</code>```

str.join simply accepts any type of iterable so we can use a generator, or a list. We can also boost the former a bit by using list comprehension:

```<code>foo_text = '\n'.join(['{} ==> {}'.format(*t) for t in foo_dict.items()])
</code>```

This being said note that simply writing one-liners because it is possible is not a good reason. You should always go for readability (given it does not alter the time complexity or has a significant impact on efficiency). In this case this is probably not a problem. But cryptical one-liners are rather un-Pythonic.

Body:
I have a dictionary full of string-valued k-v pairs, and I want each to be separated by ==>& then printed to a newline.

I use an array to mediate the transformation, which seems unnecessary & inelegant. I'd like to do this in 1 line if possible.

Here's what I have:

foo_dict = {
    'a' : '1',
    'b' : '2',
    'c' : '3',
    }
foo_list = []
for k, v in foo_dict.items():
    foo_list.append('{} ==> {}'.format(k, v))
foo_text = '\n'.join(foo_list)

this will print:

b ==> 2
c ==> 3
a ==> 1

the order doesn't matter (otherwise I'd just use OrderedDict.) What matters is that all k-v pairs get printed in the correct format.

Body:
The following one-liner will do:

foo_text = '\n'.join('{} ==> {}'.format(*t) for t in foo_dict.items())

Or we can use a starmap(..):

from itertools import starmap

foo_text = '\n'.join(starmap('{} ==> {}'.format,foo_dict.items()))

Both generate:

>>> '\n'.join('{} ==> {}'.format(*t) for t in foo_dict.items())
'b ==> 2\na ==> 1\nc ==> 3'
>>> '\n'.join(starmap('{} ==> {}'.format,foo_dict.items()))
'b ==> 2\na ==> 1\nc ==> 3'

str.join simply accepts any type of iterable so we can use a generator, or a list. We can also boost the former a bit by using list comprehension:

foo_text = '\n'.join(['{} ==> {}'.format(*t) for t in foo_dict.items()])

This being said note that simply writing one-liners because it is possible is not a good reason. You should always go for readability (given it does not alter the time complexity or has a significant impact on efficiency). In this case this is probably not a problem. But cryptical one-liners are rather un-Pythonic.


问:
Convert cUrl command to HTTP Request in Swift
I am building an app that checks domain availability. Right now, I am using the goDaddy API; according to goDaddy, the way to check URL availability is by the following cURL command:

```<code>curl -X GET -H "Authorization: sso-key {API_KEY}:{API_SECRET}" "https://api.godaddy.com/v1/domains/available?domain=example.guru"
</code>```

Right now, I am trying to translate that cURL command to Swift. I am using Alamofire; however, when I make a request, an error as the following shows up:

Credentials must be specified

I was wondering how to solve this problem. Here is my current code:

```<code>class ViewController: UIViewController {

    let key = "KEYKEYKEY"
    let secret = "SECRETSECRET"

    var headers: HTTPHeaders = [:]

    override func viewDidLoad() {
        super.viewDidLoad()

        let credential = URLCredential(user: key, password: secret, persistence: .forSession)

        Alamofire.request("https://api.godaddy.com/v1/domains/available?domain=example.guru")
            .authenticate(usingCredential: credential)
            .responseJSON { response in
                debugPrint(response)
        }

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
</code>```

答:
I know that this is not using Alamofire but this is how I would achieve it. </p>

```<code>import PlaygroundSupport
import Foundation
let key = "2s7Ymz8gu7_8XuTEeMFVmxJBLmyNNL4n8"
let secret = "8XuXAs8K37ejtYqvsEue2p"

let url = URL(string: "https://api.ote-godaddy.com/v1/domains/available?domain=example.guru&checkType=FULL")

var request = URLRequest(url: url!)

request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("sso-key \(key):\(secret)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard error == nil else {
        print(error!)
        return
    }
    guard let data = data else {
        print("Data is empty")
        return
    }

    let json = try! JSONSerialization.jsonObject(with: data, options: [])
    print(json)
}

task.resume()
PlaygroundPage.current.needsIndefiniteExecution = true
</code>```

Body:
I am building an app that checks domain availability. Right now, I am using the goDaddy API; according to goDaddy, the way to check URL availability is by the following cURL command:

curl -X GET -H "Authorization: sso-key {API_KEY}:{API_SECRET}" "https://api.godaddy.com/v1/domains/available?domain=example.guru"

Right now, I am trying to translate that cURL command to Swift. I am using Alamofire; however, when I make a request, an error as the following shows up:

Credentials must be specified

I was wondering how to solve this problem. Here is my current code:

class ViewController: UIViewController {

    let key = "KEYKEYKEY"
    let secret = "SECRETSECRET"

    var headers: HTTPHeaders = [:]

    override func viewDidLoad() {
        super.viewDidLoad()

        let credential = URLCredential(user: key, password: secret, persistence: .forSession)

        Alamofire.request("https://api.godaddy.com/v1/domains/available?domain=example.guru")
            .authenticate(usingCredential: credential)
            .responseJSON { response in
                debugPrint(response)
        }

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Body:
I know that this is not using Alamofire but this is how I would achieve it.

import PlaygroundSupport
import Foundation
let key = "2s7Ymz8gu7_8XuTEeMFVmxJBLmyNNL4n8"
let secret = "8XuXAs8K37ejtYqvsEue2p"

let url = URL(string: "https://api.ote-godaddy.com/v1/domains/available?domain=example.guru&checkType=FULL")

var request = URLRequest(url: url!)

request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("sso-key \(key):\(secret)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard error == nil else {
        print(error!)
        return
    }
    guard let data = data else {
        print("Data is empty")
        return
    }

    let json = try! JSONSerialization.jsonObject(with: data, options: [])
    print(json)
}

task.resume()
PlaygroundPage.current.needsIndefiniteExecution = true


问:
jquery post behaviour help
It's meant to call a Action Method called Logon.
depending on the logic i want it to either redirect to a url, or set some error text.

its getting the right information as json data, but all its doing is displaying the json result in a new tab when i click the submit button.

what is wrong here?

```<code>$("#submit").click(function () {
                $.post({
                    url: "Account/LogOn",
                    dataType: "json",
                    success: function (data) {
                        if (data.redirect) {
                            // data.redirect contains the string URL to redirect to
                            window.location.href = data.redirect;
                        }
                        else {
                            // data.form contains the HTML for the replacement form
                            $("#error").replaceWith(data.error);
                        }
                    }
                });
</code>```

答:
Why are you doing this on client side and not the server side?

On Server side you can redirect or redisplay the logon form with errors.

```<code> return Redirect(returnUrl);
return View(model); //model contains the Model Errors. It can be added using ModelState.AddModelError(...);
</code>```

Title: jquery post behaviour help

Body:
It's meant to call a Action Method called Logon.
depending on the logic i want it to either redirect to a url, or set some error text.

its getting the right information as json data, but all its doing is displaying the json result in a new tab when i click the submit button.

what is wrong here?

$("#submit").click(function () {
                $.post({
                    url: "Account/LogOn",
                    dataType: "json",
                    success: function (data) {
                        if (data.redirect) {
                            // data.redirect contains the string URL to redirect to
                            window.location.href = data.redirect;
                        }
                        else {
                            // data.form contains the HTML for the replacement form
                            $("#error").replaceWith(data.error);
                        }
                    }
                });

Body:
Why are you doing this on client side and not the server side?

On Server side you can redirect or redisplay the logon form with errors.

 return Redirect(returnUrl);
return View(model); //model contains the Model Errors. It can be added using ModelState.AddModelError(...);


问:
Compare two hashmaps in javascript
I try to find a solution to compare two hashmaps in javascript but I have a difficulty.

This is my situation, I have a hashmap composed of a key + value in form of an array.

Example : 125 : [1 , 2 , 3]

And then I take this data and I compare it with another hashmap with this kind.

Example :

```<code>123 : [[1 , 1 , 1][2 , 8.7 , 10]]
124 : [[0 , 0, 5.4][3 , 4 , 5][7, 9.1 , 6]
125 : [[1 , 2 , 3][0.4 , 4 , 8]]
</code>```

The second hashmap is similar to the first , but its value could contain an array of N arrays. The goal : To parse the second hashmap with my first hashmap and firstly find if the keys are similar, then if once it finds the value of the first in an array of the second it must return "OK"

For example in this case : it will return "OK" because we can notice that the key 125 and her value in the first hashmap are included in 125 : [[1 , 2 , 3][0.4 , 4 , 8]]

I should not only test on the values but also on the keys

Here is another example :

Notice that the first hashmap always have 1 data (key+value) 1 key + 1 array of 1 dimension

1st hashmap : var hashmap1 = { 124 : [ 1,1,1] }

2nd hashmap :

```<code>    var hashmap2 = {
        123 : [0,0,0],
        124 : [[ 0,1,1][0,0,1][1,1,1]]
        125 : [9 , 8 , 7]
    }
</code>```

Result : "OK" , because 124 : [1,1,1] is found in 124 : [[ 0,1,1][0,0,1][1,1,1]] .

答:
A simple way to compare the arrays is to stringify them and see if the sample one exists in the other string

let sample = {
  '124': [9,9,9], // expect no match .. key exists but array differs
  '125': [1, 2, 3], //expect match
  '555':[8,8] // expect no match ... key doesn't exist
}

let data = {
  '123': [ [1, 1, 1],[2, 8.7, 10]],
  '124': [[0, 0, 5.4],[3, 4, 5],[7, 9.1, 6]],
  '125': [[1, 2, 3],[0.4, 4, 8]]
}

let res = Object.keys(sample).map(key => {
   let msg = 'OK';
   if(!data.hasOwnProperty(key)){
      msg= 'No Match';
   }else{
      let arrayMatch = JSON.stringify(data[key]).indexOf(JSON.stringify(sample[key])) >-1;
      msg = !arrayMatch ? 'No Match' : msg;
   }
   return key + ' : ' +  msg;
});

console.log(res.join('\n'))```

Title: Compare two hashmaps in javascript

Body:
I try to find a solution to compare two hashmaps in javascript but I have a difficulty.

This is my situation, I have a hashmap composed of a key + value in form of an array.

Example : 125 : [1 , 2 , 3]

And then I take this data and I compare it with another hashmap with this kind.

Example :

123 : [[1 , 1 , 1][2 , 8.7 , 10]]
124 : [[0 , 0, 5.4][3 , 4 , 5][7, 9.1 , 6]
125 : [[1 , 2 , 3][0.4 , 4 , 8]]

The second hashmap is similar to the first , but its value could contain an array of N arrays. The goal : To parse the second hashmap with my first hashmap and firstly find if the keys are similar, then if once it finds the value of the first in an array of the second it must return "OK"

For example in this case : it will return "OK" because we can notice that the key 125 and her value in the first hashmap are included in 125 : [[1 , 2 , 3][0.4 , 4 , 8]]

I should not only test on the values but also on the keys

Here is another example :

Notice that the first hashmap always have 1 data (key+value) 1 key + 1 array of 1 dimension

1st hashmap : var hashmap1 = { 124 : [ 1,1,1] }

2nd hashmap :

    var hashmap2 = {
        123 : [0,0,0],
        124 : [[ 0,1,1][0,0,1][1,1,1]]
        125 : [9 , 8 , 7]
    }

Result : "OK" , because 124 : [1,1,1] is found in 124 : [[ 0,1,1][0,0,1][1,1,1]] .


问:
How should I set parameters "spark.kryoserializer.buffer.mb" in pyspark
Did I set correct? everytime when I run the program, it will always show errors：

Kryo serialization failed: Buffer overflow. Available: 0, required: 5. To avoid this, increase spark.kryoserializer.buffer.max value.

```<code>from pyspark.sql import SQLContext
from pyspark import SparkContext
from pyspark import SparkConf
from graphframes import *

sc = SparkContext("local")
sqlContext = SQLContext(sc)
sqlContext.sql('SET spark.sql.broadcastTimeout=9000')
sqlContext.sql('SET spark.kryoserializer.buffer.max=512')
</code>```

答:
What you need to use is the setConf() if you want to add configuration to SqlContext.

But if you want to add the configuration to SparkContext you can use the simple set function like this:

```<code>conf = SparkConf().setAppName('MY_APP') \
                          .set('spark.executor.cores', 4) \
                          .set('spark.executor.memory', '16g') \
                          .set('spark.driver.memory', '16g') \
                          .set('spark.yarn.executor.memoryOverhead', 1024) \
                          .set('spark.dynamicAllocation.enabled', 'true') \
                          .set('spark.shuffle.service.enabled', 'true') \
                          .set('spark.shuffle.service.port', 7337) \
                          .set('spark.dynamicAllocation.maxExecutors', 250) \
                          .set("spark.serializer", "org.apache.spark.serializer.KryoSerializer")

sc = SparkContext(conf=conf)
</code>```

And then add setConf to your context:

```<code>sqlContext = SqlContext(sc).setConf("spark.sql.broadcastTimeout", 9000)
</code>```

Body:
Did I set correct? everytime when I run the program, it will always show errors：

Kryo serialization failed: Buffer overflow. Available: 0, required: 5. To avoid this, increase spark.kryoserializer.buffer.max value.

from pyspark.sql import SQLContext
from pyspark import SparkContext
from pyspark import SparkConf
from graphframes import *

sc = SparkContext("local")
sqlContext = SQLContext(sc)
sqlContext.sql('SET spark.sql.broadcastTimeout=9000')
sqlContext.sql('SET spark.kryoserializer.buffer.max=512')

Body:
What you need to use is the setConf() if you want to add configuration to SqlContext.

But if you want to add the configuration to SparkContext you can use the simple set function like this:

conf = SparkConf().setAppName('MY_APP') \
                          .set('spark.executor.cores', 4) \
                          .set('spark.executor.memory', '16g') \
                          .set('spark.driver.memory', '16g') \
                          .set('spark.yarn.executor.memoryOverhead', 1024) \
                          .set('spark.dynamicAllocation.enabled', 'true') \
                          .set('spark.shuffle.service.enabled', 'true') \
                          .set('spark.shuffle.service.port', 7337) \
                          .set('spark.dynamicAllocation.maxExecutors', 250) \
                          .set("spark.serializer", "org.apache.spark.serializer.KryoSerializer")

sc = SparkContext(conf=conf)

And then add setConf to your context:

sqlContext = SqlContext(sc).setConf("spark.sql.broadcastTimeout", 9000)


答:
If you want it to be a one-liner, you write a list comprehension and join the string elements with \n:

```<code>print('\n'.join(["{} ==> {}".format(k, foo_dict[k]) for k in foo_dict]))
</code>```

Title: How to convert a dictionary of strings into a block of text with python

Body:
If you want it to be a one-liner, you write a list comprehension and join the string elements with \n:

print('\n'.join(["{} ==> {}".format(k, foo_dict[k]) for k in foo_dict]))


问:
Encounter order friendly/unfriendly terminal operations vs parallel/sequential vs ordered/unordered streams
Inspired by this question, I started to play with ordered vs unordered streams, parallel vs sequential streams and terminal operations that respect encounter order vs terminal operations that don't respect it.

In one answer to the linked question, a code similar to this one is shown:

```<code>List<Integer> ordered = Arrays.asList(
    1, 2, 3, 4, 4, 3, 2, 1, 1, 2, 3, 4, 4, 3, 2, 1, 1, 2, 3, 4);
List<Integer> result = new CopyOnWriteArrayList<>();

ordered.parallelStream().forEach(result::add);

System.out.println(ordered);
System.out.println(result);
</code>```

And the lists are indeed different. The unordered list even changes from one run to another, showing that the result is actually non-deterministic.

So I created this other example:

```<code>CopyOnWriteArrayList<Integer> result2 = ordered.parallelStream()
        .unordered()
        .collect(Collectors.toCollection(CopyOnWriteArrayList::new));

System.out.println(ordered);
System.out.println(result2);
</code>```

And I expected to see similar results, as the stream is both parallel and unordered (maybe unordered() is redundant, since it's already parallel). However, the resulting list is ordered, i.e. it's equal to the source list.

So my question is why the collected list is ordered? Does collect always respect encounter-order, even for parallel, unordered streams? Is it the specific Collectors.toCollection(...) collector the one that forces encounter-order?

答:
Under the current implementation I've checked java-8 and java-9 the unordered flag is ignored for the collect phase for non-concurrent collectors (Collector.Characteristics.UNORDERED is not set).  The implementations are allowed to do that, somehow similar question.

In the same question that you linked, I did provide the example of how findFirst actually changed from jdk-8 to jdk-9.

Body:
Inspired by this question, I started to play with ordered vs unordered streams, parallel vs sequential streams and terminal operations that respect encounter order vs terminal operations that don't respect it.

In one answer to the linked question, a code similar to this one is shown:

List<Integer> ordered = Arrays.asList(
    1, 2, 3, 4, 4, 3, 2, 1, 1, 2, 3, 4, 4, 3, 2, 1, 1, 2, 3, 4);
List<Integer> result = new CopyOnWriteArrayList<>();

ordered.parallelStream().forEach(result::add);

System.out.println(ordered);
System.out.println(result);

And the lists are indeed different. The unordered list even changes from one run to another, showing that the result is actually non-deterministic.

So I created this other example:

CopyOnWriteArrayList<Integer> result2 = ordered.parallelStream()
        .unordered()
        .collect(Collectors.toCollection(CopyOnWriteArrayList::new));

System.out.println(ordered);
System.out.println(result2);

And I expected to see similar results, as the stream is both parallel and unordered (maybe unordered() is redundant, since it's already parallel). However, the resulting list is ordered, i.e. it's equal to the source list.

So my question is why the collected list is ordered? Does collect always respect encounter-order, even for parallel, unordered streams? Is it the specific Collectors.toCollection(...) collector the one that forces encounter-order?


问:
Confusion in java.Clock, systemDefaultZone() returning UTC time
I am trying to understand why the following java.time.Clock is returning UTC time instead of the local time zone (EST).

```<code>C:\Users\Felipe>scala
Welcome to Scala 2.12.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_65).
Type in expressions for evaluation. Or try :help.

scala> import java.time._
import java.time._

scala> ZoneId.systemDefault()
res0: java.time.ZoneId = America/New_York

scala> val clock = Clock.systemDefaultZone()
clock: java.time.Clock = SystemClock[America/New_York]

scala> clock.instant
res1: java.time.Instant = 2017-07-06T16:20:04.990Z
</code>```

The current time when I ran the above was 12:20pm (i.e. 4h before the UTC time shown)

答:
The Instant.toString() method uses DateTimeFormatter.ISO_INSTANT formatter, which in turn parses and formats the Instant in UTC.

As 2017-07-06T16:20:04.990Z is the same as 2017-07-06T12:20:04.990 in New York, the results you're getting are correct.

If you want the Instant converted to your timezone, you can do:

```<code>clock.instant().atZone(ZoneId.systemDefault())
</code>```

Or you can be more specific (as the system's default timezone can be changed, even in runtime):

```<code>clock.instant().atZone(ZoneId.of("America/New_York"))
</code>```

This will result in a ZonedDateTime:

2017-07-06T12:48:22.890-04:00[America/New_York]

You can also convert this to a LocalDateTime if you want:

```<code>clock.instant().atZone(ZoneId.of("America/New_York")).toLocalDateTime()
</code>```

The result will be a LocalDateTime:

2017-07-06T12:49:47.688

PS: as @Andreas reminded me in the comments (and I forgot to mention), the Instant class represents just a point in time (number of nanoseconds since 1970-01-01T00:00Z) and has no timezone information, so any representation of it (including the toString() method) will be in UTC. To get the local date or time that corresponds to an Instant, you must provide a timezone, as shown above.

Body:
I am trying to understand why the following java.time.Clock is returning UTC time instead of the local time zone (EST).

C:\Users\Felipe>scala
Welcome to Scala 2.12.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_65).
Type in expressions for evaluation. Or try :help.

scala> import java.time._
import java.time._

scala> ZoneId.systemDefault()
res0: java.time.ZoneId = America/New_York

scala> val clock = Clock.systemDefaultZone()
clock: java.time.Clock = SystemClock[America/New_York]

scala> clock.instant
res1: java.time.Instant = 2017-07-06T16:20:04.990Z

The current time when I ran the above was 12:20pm (i.e. 4h before the UTC time shown)

Body:
The Instant.toString() method uses DateTimeFormatter.ISO_INSTANT formatter, which in turn parses and formats the Instant in UTC.

As 2017-07-06T16:20:04.990Z is the same as 2017-07-06T12:20:04.990 in New York, the results you're getting are correct.

If you want the Instant converted to your timezone, you can do:

clock.instant().atZone(ZoneId.systemDefault())

Or you can be more specific (as the system's default timezone can be changed, even in runtime):

clock.instant().atZone(ZoneId.of("America/New_York"))

This will result in a ZonedDateTime:

2017-07-06T12:48:22.890-04:00[America/New_York]

You can also convert this to a LocalDateTime if you want:

clock.instant().atZone(ZoneId.of("America/New_York")).toLocalDateTime()

The result will be a LocalDateTime:

2017-07-06T12:49:47.688

PS: as @Andreas reminded me in the comments (and I forgot to mention), the Instant class represents just a point in time (number of nanoseconds since 1970-01-01T00:00Z) and has no timezone information, so any representation of it (including the toString() method) will be in UTC. To get the local date or time that corresponds to an Instant, you must provide a timezone, as shown above.


问:
How to receive the dropdown value selected in the backend code
I am new to web development and learning Dropdown HTML Helper. So, I have created the dropdown but I am not able to receive the selected value in the backend.

Below is my attempt.

View:

```<code>@model WebApplication3.Models.DropDownViewModel
<form method="post">
    @Html.DropDownListFor(m => m.SongList, new SelectList(Model.SongList, "Value", "Text"), "Select menu", new { @class = "form-control" })
            @* below is the use of each argument.*@
            @*1. m=>m.SongList => It helps in strongly typing to the model*@
            @*2. Model.SongList => It is the datasource for creating the dropdown*@
            @*3. "Value" => This is the value behind each of the dropdown options*@
            @*4. "Text" => This is the actual text*@
            @*5. "Select Menu" => This is the first option that will appear in the dropdown*@
                <input type="submit" value="Send" />
            </form>
</code>```

Model:

```<code>                public class DropDownViewModel
                {
                    public DropDownViewModel()
                    {
                        SongList = new List<SelectListItem>();
                    }
                    public int Id { get; set; }
                    public List<SelectListItem> SongList { get; set; }
                }
</code>```

Controller:

```<code>                 public ActionResult Index()
                    {
                        DropDownViewModel dropdown = new DropDownViewModel();
                        dropdown.SongList.Add(new SelectListItem { Text = "Four", Value = "4" });
                        dropdown.SongList.Add(new SelectListItem { Text = "Five", Value = "5" });
                        dropdown.SongList.Add(new SelectListItem { Text = "Six", Value = "6" });
                        dropdown.SongList.Add(new SelectListItem { Text = "Seven", Value = "7" });

                        return View(dropdown);
                    }

                    [HttpPost]
                    public ActionResult Index(DropDownViewModel viewModel)
                    {
                    *******  viewModel.??? WHow to get the selected ID. Which variable will have that.*******
                        return View(dropdown);
                    }
</code>```

答:
You will need to add a property in DropDownViewModel to retrieve the selected value.

```<code>    public class DropDownViewModel
    {
       public DropDownViewModel()
       {
          SongList = new List<SelectListItem>();
       }
       public int Id { get; set; }

       public string SelectedSongId { get; set; }
       public List<SelectListItem> SongList { get; set; }
    }
</code>```

View

```<code>@using (Html.BeginForm())
{
   @Html.DropDownListFor(model => model.SelectedSongId, Model.SongList, new { @class = "form-control" })
   <button type="submit" value="Submit" class="btn btn-primary">Submit</button>
}
</code>```

Action Method

```<code>[HttpPost]
public ActionResult Index(DropDownViewModel viewModel)
{
   var id = viewModel.SelectedSongId;
   ...
}
</code>```

Body:
I am new to web development and learning Dropdown HTML Helper. So, I have created the dropdown but I am not able to receive the selected value in the backend.

Below is my attempt.

View:

@model WebApplication3.Models.DropDownViewModel
<form method="post">
    @Html.DropDownListFor(m => m.SongList, new SelectList(Model.SongList, "Value", "Text"), "Select menu", new { @class = "form-control" })
            @* below is the use of each argument.*@
            @*1. m=>m.SongList => It helps in strongly typing to the model*@
            @*2. Model.SongList => It is the datasource for creating the dropdown*@
            @*3. "Value" => This is the value behind each of the dropdown options*@
            @*4. "Text" => This is the actual text*@
            @*5. "Select Menu" => This is the first option that will appear in the dropdown*@
                <input type="submit" value="Send" />
            </form>

Model:

                public class DropDownViewModel
                {
                    public DropDownViewModel()
                    {
                        SongList = new List<SelectListItem>();
                    }
                    public int Id { get; set; }
                    public List<SelectListItem> SongList { get; set; }
                }

Controller:

                 public ActionResult Index()
                    {
                        DropDownViewModel dropdown = new DropDownViewModel();
                        dropdown.SongList.Add(new SelectListItem { Text = "Four", Value = "4" });
                        dropdown.SongList.Add(new SelectListItem { Text = "Five", Value = "5" });
                        dropdown.SongList.Add(new SelectListItem { Text = "Six", Value = "6" });
                        dropdown.SongList.Add(new SelectListItem { Text = "Seven", Value = "7" });

                        return View(dropdown);
                    }

                    [HttpPost]
                    public ActionResult Index(DropDownViewModel viewModel)
                    {
                    *******  viewModel.??? WHow to get the selected ID. Which variable will have that.*******
                        return View(dropdown);
                    }

Body:
You will need to add a property in DropDownViewModel to retrieve the selected value.

    public class DropDownViewModel
    {
       public DropDownViewModel()
       {
          SongList = new List<SelectListItem>();
       }
       public int Id { get; set; }

       public string SelectedSongId { get; set; }
       public List<SelectListItem> SongList { get; set; }
    }

View

@using (Html.BeginForm())
{
   @Html.DropDownListFor(model => model.SelectedSongId, Model.SongList, new { @class = "form-control" })
   <button type="submit" value="Submit" class="btn btn-primary">Submit</button>
}

Action Method

[HttpPost]
public ActionResult Index(DropDownViewModel viewModel)
{
   var id = viewModel.SelectedSongId;
   ...
}


答:
The $.ajax call is asynchronous, which means your $("#DoB").val(newDob); call is executing before before the AJAX request is even made. Changing needs to be done in the AJAX success callback.

```<code>// Dropdown ID = PatientID, textbox ID = DoB
var patient = $("#PatientID");
patient.change(function () {
    $.ajax({
        url: '@(Url.Action("PatientDob"))?patientId=' + patient.val(),
        type: "GET",
        success: function (result) {
            $("#DoB").val(result);
        },
        error: function (xhr, status, err) {
            alert(err);
        }
    });

});
</code>```

Title: Update textbox with AJAX

Body:
When a dropdown's value changes, I need the values of two textboxes to change, based on the new value of the dropdown, without refreshing the page.

This should be dead easy, but I'm having trouble figuring out what makes AJAX tick. I seem to be able to get the value, but I can't set the textbox.

This similar question didn't help me. Neither did this.

JavaScript:

// Dropdown ID = PatientID, textbox ID = DoB
var patient = $("#PatientID");
patient.change(function () {
    var newDob;
    $.ajax({
        url: '@(Url.Action("PatientDob"))?patientId=' + patient.val(),
        type: "GET",
        success: function (result) {
            // Displays correct result
            alert(result);
            newDob = result;
        },
        error: function (xhr, status, err) {
            alert(err);
        }
    });
    // Causes the box to become blank, HTML value attribute doesn't change
    $("#DoB").val(newDob);
});

Controller:

[HttpGet]
public string PatientDob(int patientId)
{
    return db.Patients.Find(patientId).DateOfBirth.ToString("MM/dd/yyyy");
}

Body:
The $.ajax call is asynchronous, which means your $("#DoB").val(newDob); call is executing before before the AJAX request is even made. Changing needs to be done in the AJAX success callback.

// Dropdown ID = PatientID, textbox ID = DoB
var patient = $("#PatientID");
patient.change(function () {
    $.ajax({
        url: '@(Url.Action("PatientDob"))?patientId=' + patient.val(),
        type: "GET",
        success: function (result) {
            $("#DoB").val(result);
        },
        error: function (xhr, status, err) {
            alert(err);
        }
    });

});


问:
psycopg2 change schema does not work
I am writing a simple python prog to connect and display results from Postgres table this is on AWS RDS. I have table mytest in public schema.

```<code>connection = psycopg2.connect(dbname='some_test',
                    user='user1',
                    host='localhost',
                    password='userpwd',
                    port=postgres_port)
cursor = connection.cursor()
cursor.execute("SET SEARCH_PATH TO public;")
cursor.execute("SELECT *  FROM mytest;")
</code>```

But this throws an error

psycopg2.ProgrammingError: relation "mytest" does not exist

LINE 1: SELECT *  FROM mytest;

Connection is successful and I can query other basetables like

```<code>SELECT table_name FROM information_schema.tables
</code>```

It is just that I cannot change to any other schema. I googled and tried all kinds of SET SERACH_PATH and commit it and recreate cursor etc. but no use. I cannot query any other schema.

答:
```<code>ALTER USER username SET search_path = schema1,schema2;
</code>```

After setting this the query works fine!

Title: psycopg2 change schema does not work

Body:
I am writing a simple python prog to connect and display results from Postgres table this is on AWS RDS. I have table mytest in public schema.

connection = psycopg2.connect(dbname='some_test',
                    user='user1',
                    host='localhost',
                    password='userpwd',
                    port=postgres_port)
cursor = connection.cursor()
cursor.execute("SET SEARCH_PATH TO public;")
cursor.execute("SELECT *  FROM mytest;")

But this throws an error

psycopg2.ProgrammingError: relation "mytest" does not exist

LINE 1: SELECT *  FROM mytest;

Connection is successful and I can query other basetables like

SELECT table_name FROM information_schema.tables

It is just that I cannot change to any other schema. I googled and tried all kinds of SET SERACH_PATH and commit it and recreate cursor etc. but no use. I cannot query any other schema.

Body:
ALTER USER username SET search_path = schema1,schema2;

After setting this the query works fine!


问:
how to get all Bootstrap (css, js, fonts) paths using bower?
bower list --paths gives the following:

```<code>>bower list --paths

  bootstrap: [
    'bower_components/bootstrap/less/bootstrap.less',
    'bower_components/bootstrap/dist/js/bootstrap.js'
  ],
  jquery: 'bower_components/jquery/dist/jquery.js'
</code>```

the command does not give paths for bootstrap.css files. Which bower command will give all the required paths (css, js, fonts etc)of a package.

答:
You should install bootstrap-css version.</p>

```<code>bower install bootstrap-css --save
bower list --paths

bootstrap: [
    'bower_components/bootstrap/css/bootstrap.css',
    'bower_components/bootstrap/dist/js/bootstrap.js'
],
jquery: 'bower_components/jquery/dist/jquery.js'
</code>```

Body:
bower list --paths gives the following:

>bower list --paths

  bootstrap: [
    'bower_components/bootstrap/less/bootstrap.less',
    'bower_components/bootstrap/dist/js/bootstrap.js'
  ],
  jquery: 'bower_components/jquery/dist/jquery.js'

the command does not give paths for bootstrap.css files. Which bower command will give all the required paths (css, js, fonts etc)of a package.

Body:
You should install bootstrap-css version.

bower install bootstrap-css --save
bower list --paths

bootstrap: [
    'bower_components/bootstrap/css/bootstrap.css',
    'bower_components/bootstrap/dist/js/bootstrap.js'
],
jquery: 'bower_components/jquery/dist/jquery.js'


问:
When I open Netbeans and start a program, it won't let me input any code into the terminal
This is a little bit puzzling to me, although this could just be a rookie mistake I'm making. I'm experienced with Python, though I was trying to go ahead and start working with Java via NetBeans. Unlike Python, which had a simple IDE to work with, I can't quite get NetBeans to even start allowing me to put code into the terminal. Here's where I'm at so far.

I've tried uninstalling and downloading the NetBeans IDE, but I seem to have this exact same problem. Does anybody have any idea how to work around this? This is a little bit frustrating, and I thought I would be having difficulty with the syntax, not the complier itself.

答:
Try removing the userdir.

From the wiki at netbeans.org:

The NetBeans userdir is a directory where NetBeans stores user configuration data such as window layouts, editor settings, menu and toolbar customizations and various module settings.

By default on Windows and Mac OS X the userdir is inside a directory NetBeans in application settings folder.

On Windows this can be found at C:\Users\<username>\AppData\Roaming\

On OS X this can be found at /Users/<username>/Library/Application Support/

See a related question here.