问:
java.lang.NoClassDefFoundError: org/hibernate/Session hibernate jars is set
I inherited several projects Javas in my new job, but I'm having some problems with settings. I'm facing a problem that is researched so common. "java.lang.NoClassDefFoundError: org / hibernate / Session", put all the jars even unnecessary hibernate are mapped in the classpath.

Im using tomcat 7, hirbernat 4, jre7.

every project extends compnet that have all necessary jars in lib folder.

do i need to put those already mapped jars in this project ?

The erro is catch here:

```<code>    @Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    HibernateUtil.currentSession();
}
</code>```

classpath:

```<code><classpathentry kind="src" path="src"/>
<classpathentry exported="true" kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/xstream 1.3/xpp3_min-1.1.4c.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/xstream 1.3/xstream-1.3.1.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="con" path="org.eclipse.jst.server.core.container/org.eclipse.jst.server.tomcat.runtimeTarget/Apache Tomcat v6.0"/>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/commons fileupload 1.2.1/commons-fileupload-1.2.1.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/antlr.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/commons-collections.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/dom4j.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/ejb3-persistence.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/hibernate-annotations.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/hibernate-commons-annotations.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/hibernate-validator.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/hibernate3.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/javassist.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/jta.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/jtds-1.2.4.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/log4j.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/slf4j-api.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/slf4j-log4j12.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/commons logging/commons-logging-1.1.1.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/commons logging/commons-logging-adapters-1.1.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/commons logging/commons-logging-api-1.1.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry combineaccessrules="false" exported="true" kind="src" path="/pkg_ocorrencia"/>
<classpathentry combineaccessrules="false" exported="true" kind="src" path="/pkg_mandado"/>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/commons-beanutils-1.8.2.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/commons-digester-1.7.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/groovy-all-1.5.5.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/iText-2.1.0.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/jasperreports-3.7.4.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/jasperreports-chart-themes-3.7.4.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/jasperreports-extensions-3.5.3.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/jasperreports-fonts-3.7.4.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/spring.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/xalan.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/jfreechart-1.0.12.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/jcommon-1.0.15.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry combineaccessrules="false" kind="src" path="/Compnet"/>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/commons email 1.2/commons-email-1.2.jar"/>
<classpathentry kind="lib" path="D:/Tomcat 7/apache-tomcat-7.0.27/lib/servlet-api.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/antlr-2.7.7.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/c3p0-0.9.1.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/dom4j-1.6.1.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/ehcache-core-2.4.3.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/hibernate-c3p0-4.1.4.Final.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/hibernate-commons-annotations-4.0.1.Final.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/hibernate-core-4.1.4.Final.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/hibernate-ehcache-4.1.4.Final.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/hibernate-entitymanager-4.1.4.Final.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/hibernate-envers-4.1.4.Final.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/hibernate-infinispan-4.1.4.Final.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/hibernate-jpa-2.0-api-1.0.1.Final.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/hibernate-proxool-4.1.4.Final.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/infinispan-core-5.1.4.FINAL.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/javassist-3.15.0-GA.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/jboss-logging-3.1.0.GA.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/jboss-marshalling-1.3.11.GA.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/jboss-marshalling-river-1.3.11.GA.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/jboss-transaction-api_1.1_spec-1.0.0.Final.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/jgroups-3.0.9.Final.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/proxool-0.8.3.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/rhq-pluginAnnotations-3.0.4.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/slf4j-api-1.6.1.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/stax2-api-3.1.1.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/woodstox-core-asl-4.1.1.jar"/>

<classpathentry kind="output" path="build/classes"/>
</code>```

stacktrance:

java.lang.NoClassDefFoundError: org/hibernate/Session
    at br.com.flex4j.servlet.genericActionServlet.init(genericActionServlet.java:29)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1161)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:806)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:129)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.hibernate.Session
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1358)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1204)
    ... 13 more

Jun 21, 2012 3:39:22 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet genericActionServlet
java.lang.ClassNotFoundException: org.hibernate.Session
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1358)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1204)
    at br.com.flex4j.servlet.genericActionServlet.init(genericActionServlet.java:29)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1161)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:806)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:129)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    at java.lang.Thread.run(Unknown Source)

EDIT:

ClassPath of my project: java build path">

答:
To add jars in eclipse you have two options:

Right click on project got to
properties-->click on java build path --> configure build path--> Libraries -->
and select add external jars button. It will open a window where you can add all your jars required.

Second option is to paste jars directly to lib folder. lib folder is in Web Content --> WEB-INF --> lib.

Use any one of them.

Body:
I inherited several projects Javas in my new job, but I'm having some problems with settings. I'm facing a problem that is researched so common. "java.lang.NoClassDefFoundError: org / hibernate / Session", put all the jars even unnecessary hibernate are mapped in the classpath.

Im using tomcat 7, hirbernat 4, jre7.

every project extends compnet that have all necessary jars in lib folder.

do i need to put those already mapped jars in this project ?

The erro is catch here:

    @Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    HibernateUtil.currentSession();
}

classpath:

<classpathentry kind="src" path="src"/>
<classpathentry exported="true" kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/xstream 1.3/xpp3_min-1.1.4c.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/xstream 1.3/xstream-1.3.1.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="con" path="org.eclipse.jst.server.core.container/org.eclipse.jst.server.tomcat.runtimeTarget/Apache Tomcat v6.0"/>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/commons fileupload 1.2.1/commons-fileupload-1.2.1.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/antlr.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/commons-collections.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/dom4j.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/ejb3-persistence.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/hibernate-annotations.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/hibernate-commons-annotations.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/hibernate-validator.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/hibernate3.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/javassist.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/jta.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/jtds-1.2.4.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/log4j.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/slf4j-api.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/hibernate 3/slf4j-log4j12.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/commons logging/commons-logging-1.1.1.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/commons logging/commons-logging-adapters-1.1.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/commons logging/commons-logging-api-1.1.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry combineaccessrules="false" exported="true" kind="src" path="/pkg_ocorrencia"/>
<classpathentry combineaccessrules="false" exported="true" kind="src" path="/pkg_mandado"/>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/commons-beanutils-1.8.2.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/commons-digester-1.7.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/groovy-all-1.5.5.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/iText-2.1.0.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/jasperreports-3.7.4.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/jasperreports-chart-themes-3.7.4.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/jasperreports-extensions-3.5.3.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/jasperreports-fonts-3.7.4.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/spring.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/xalan.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/jfreechart-1.0.12.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/jasper - ireport 3.7.4/jcommon-1.0.15.jar">
    <attributes>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>
<classpathentry combineaccessrules="false" kind="src" path="/Compnet"/>
<classpathentry exported="true" kind="lib" path="/Compnet/lib/commons email 1.2/commons-email-1.2.jar"/>
<classpathentry kind="lib" path="D:/Tomcat 7/apache-tomcat-7.0.27/lib/servlet-api.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/antlr-2.7.7.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/c3p0-0.9.1.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/dom4j-1.6.1.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/ehcache-core-2.4.3.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/hibernate-c3p0-4.1.4.Final.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/hibernate-commons-annotations-4.0.1.Final.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/hibernate-core-4.1.4.Final.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/hibernate-ehcache-4.1.4.Final.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/hibernate-entitymanager-4.1.4.Final.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/hibernate-envers-4.1.4.Final.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/hibernate-infinispan-4.1.4.Final.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/hibernate-jpa-2.0-api-1.0.1.Final.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/hibernate-proxool-4.1.4.Final.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/infinispan-core-5.1.4.FINAL.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/javassist-3.15.0-GA.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/jboss-logging-3.1.0.GA.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/jboss-marshalling-1.3.11.GA.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/jboss-marshalling-river-1.3.11.GA.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/jboss-transaction-api_1.1_spec-1.0.0.Final.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/jgroups-3.0.9.Final.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/proxool-0.8.3.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/rhq-pluginAnnotations-3.0.4.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/slf4j-api-1.6.1.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/stax2-api-3.1.1.jar"/>
<classpathentry kind="lib" path="/Compnet/lib/hibernate4/woodstox-core-asl-4.1.1.jar"/>

<classpathentry kind="output" path="build/classes"/>

stacktrance:

java.lang.NoClassDefFoundError: org/hibernate/Session
    at br.com.flex4j.servlet.genericActionServlet.init(genericActionServlet.java:29)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1161)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:806)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:129)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.hibernate.Session
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1358)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1204)
    ... 13 more

Jun 21, 2012 3:39:22 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet genericActionServlet
java.lang.ClassNotFoundException: org.hibernate.Session
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1358)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1204)
    at br.com.flex4j.servlet.genericActionServlet.init(genericActionServlet.java:29)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1161)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:806)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:129)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    at java.lang.Thread.run(Unknown Source)

EDIT:

ClassPath of my project: java build path">


来源: stackexchange

问:
Bash String Used to Select Range
I have the following data located in a .csv file that changes as new data is downloaded.
The syntax of the data is always YYYY-MM-DDTHHMMSS, examples below:

```<code>2017-12-08T194949
2017-12-08T194952
2017-12-08T195000
2017-12-08T195007
2017-12-08T195007
2017-12-08T195014
2017-12-08T195016
2017-12-08T195016
2017-12-08T195016
2017-12-08T195016
2017-12-08T195021
2017-12-08T195026
2017-12-08T195029
2017-12-08T195030
2017-12-08T195030
2017-12-08T195034
2017-12-08T195051
2017-12-08T195101
2017-12-08T195105
2017-12-08T195135
2017-12-08T195138
2017-12-08T195140
2017-12-08T195144
2017-12-08T195148
2017-12-08T195154
2017-12-08T195204
2017-12-08T195205
2017-12-08T195219
2017-12-08T195223
2017-12-08T195224
2017-12-08T195225
</code>```

Currently, I define my datestrings using:

```<code>lower_bound=`date -d '1 day ago' "+%Y-%m-%dT%H%M%S"`
upper_bound=`date -d '12 hours ago' "+%Y-%m-%dT%H%M%S"`
</code>```

Where the amount of minutes I lookback into the file is dependent on the system time. I can set the amount I lookback to be arbitrary.

I think I have gotten close with sed/awk as follows:

```<code>sed -n "/$lower_bound/,/$upper_bound/p" data.csv
awk -v a="$lower_bound" -v b="$upper_bound" '/a/{flag=1;next}/b/{flag=0}flag' data.csv
</code>```

Given those lookback strings, the commands above should print out the range of dates in between the two variables, $lower_bound and $upper_bound. Obviously, I have experimented with different lookback times in the aforementioned variables.

Any ideas to why the range of dates aren't printing? Any help would be greatly appreciated; thank you in advance.

答:
This: /a/ will match the literal "a". This: $0 ~ a will match the string you have stored in variable a, so your command should be:

```<code>awk -v a="$lower_bound" -v b="$upper_bound"
    '$0 ~ a {flag=1;next} $0 ~ b {flag=0} flag' data.csv
</code>```

But these awk/sed commands will not give you what you want because only accidentally they could match lines, in case the exact datetime bounds exist in your logs. More probably, the exact lower bound will not exist, so flag will never be set.

If you want to print for that date range then you should make an alphabetical
 comparison of these dates, that means $0 > a and $0 < b

```<code>awk -v a="$lower_bound" -v b="$upper_bound" '$0 > a && $0 < b' data.csv
</code>```

ContentLicense: CC BY-SA 3.0

Title: Bash String Used to Select Range

Body:
I have the following data located in a .csv file that changes as new data is downloaded.
The syntax of the data is always YYYY-MM-DDTHHMMSS, examples below:

2017-12-08T194949
2017-12-08T194952
2017-12-08T195000
2017-12-08T195007
2017-12-08T195007
2017-12-08T195014
2017-12-08T195016
2017-12-08T195016
2017-12-08T195016
2017-12-08T195016
2017-12-08T195021
2017-12-08T195026
2017-12-08T195029
2017-12-08T195030
2017-12-08T195030
2017-12-08T195034
2017-12-08T195051
2017-12-08T195101
2017-12-08T195105
2017-12-08T195135
2017-12-08T195138
2017-12-08T195140
2017-12-08T195144
2017-12-08T195148
2017-12-08T195154
2017-12-08T195204
2017-12-08T195205
2017-12-08T195219
2017-12-08T195223
2017-12-08T195224
2017-12-08T195225

Currently, I define my datestrings using:

lower_bound=`date -d '1 day ago' "+%Y-%m-%dT%H%M%S"`
upper_bound=`date -d '12 hours ago' "+%Y-%m-%dT%H%M%S"`

Where the amount of minutes I lookback into the file is dependent on the system time. I can set the amount I lookback to be arbitrary.

I think I have gotten close with sed/awk as follows:

sed -n "/$lower_bound/,/$upper_bound/p" data.csv
awk -v a="$lower_bound" -v b="$upper_bound" '/a/{flag=1;next}/b/{flag=0}flag' data.csv

Given those lookback strings, the commands above should print out the range of dates in between the two variables, $lower_bound and $upper_bound. Obviously, I have experimented with different lookback times in the aforementioned variables.

Any ideas to why the range of dates aren't printing? Any help would be greatly appreciated; thank you in advance.

Body:
This: /a/ will match the literal "a". This: $0 ~ a will match the string you have stored in variable a, so your command should be:

awk -v a="$lower_bound" -v b="$upper_bound"
    '$0 ~ a {flag=1;next} $0 ~ b {flag=0} flag' data.csv

But these awk/sed commands will not give you what you want because only accidentally they could match lines, in case the exact datetime bounds exist in your logs. More probably, the exact lower bound will not exist, so flag will never be set.

If you want to print for that date range then you should make an alphabetical
 comparison of these dates, that means $0 > a and $0 < b

awk -v a="$lower_bound" -v b="$upper_bound" '$0 > a && $0 < b' data.csv


问:
Combine Lens into a Lens of a tuple
Given

```<code>data Person = Person { _name :: String }
makeClassy ''Person
</code>```

which creates a

```<code>name :: Lens' Person String
</code>```

I can define the following lens which uses name inside a tuple.

```<code>sndPerson :: Lens' (a, Person) (a, String)
sndPerson = lens
    (\(a, p) -> (a, p ^. name))
    (\(_, p) (a, n) -> (a, p & name .~ n))
</code>```

Is there a nicer/canonical way to define sndPerson above?

答:
alongside turns a pair of lenses into a lens that works over a pair.

Because in the example you don't focus into the first component, you could simply pass id as the first lens.

```<code>sndPerson :: Lens' (a, Person) (a, String)
sndPerson = alongside id name
</code>```

Title: Combine Lens into a Lens of a tuple

Body:
Given

data Person = Person { _name :: String }
makeClassy ''Person

which creates a

name :: Lens' Person String

I can define the following lens which uses name inside a tuple.

sndPerson :: Lens' (a, Person) (a, String)
sndPerson = lens
    (\(a, p) -> (a, p ^. name))
    (\(_, p) (a, n) -> (a, p & name .~ n))

Is there a nicer/canonical way to define sndPerson above?

Body:
alongside turns a pair of lenses into a lens that works over a pair.

Because in the example you don't focus into the first component, you could simply pass id as the first lens.

sndPerson :: Lens' (a, Person) (a, String)
sndPerson = alongside id name


问:
I was trying to find the magical number in the given range but its giving me error
This is giving me the error like i can't be used in std::is_floating_point because i is not a constant.  </p>

```<code>int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
     int k=18;
    int prime=0, nonprime=0;
    int N=100;
 int i=1, z=0, a=0, b=0;
 int req = 1;
    for(i=2; i<=N; i++){
         if(std::is_floating_point<i/10>){
            for(z=1; z<=i; z++){
                if((i/z) == i){
                    if((i/z) == 0){
                       prime=prime+1;
                    }else{
                        nonprime=nonprime+1;
                    }
</code>```

答:
In

```<code>if(std::is_floating_point<i/10>)
</code>```

The value of i is not known at compile time, so it cannot be used to expand a template.

Next, the is_floating_point template, as @AdnanY points out, is expecting a type not a number. You can turn the expression into a type with decltype,

```<code>if(std::is_floating_point<decltype(i/10)>::value)
</code>```

and this also deals with the problem of i not being a compile-time constant. The value of i isn't constant, but its type is. Note the ::value on the end there. Once the template is expanded, you need ::value to get the resulting bool out of it.

Final point, i/10 is integer division all the way through so the result is guaranteed to be an integer. The if will always test false and skip the body.

Here's bit of example code:

```<code>#include <iostream>
#include <type_traits>

int main() {
    for (int i=1; i < 1000; i++)
        std::cout << std::boolalpha
                  << std::is_floating_point<decltype(i/10)>::value
                  << '\n';
}
</code>```

You can set the upper bound of the loop to whatever you want, and you'll never get anything but false.

Body:
This is giving me the error like i can't be used in std::is_floating_point because i is not a constant.

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
     int k=18;
    int prime=0, nonprime=0;
    int N=100;
 int i=1, z=0, a=0, b=0;
 int req = 1;
    for(i=2; i<=N; i++){
         if(std::is_floating_point){
            for(z=1; z<=i; z++){
                if((i/z) == i){
                    if((i/z) == 0){
                       prime=prime+1;
                    }else{
                        nonprime=nonprime+1;
                    }

Body:
In

if(std::is_floating_point<i/10>)

The value of i is not known at compile time, so it cannot be used to expand a template.

Next, the is_floating_point template, as @AdnanY points out, is expecting a type not a number. You can turn the expression into a type with decltype,

if(std::is_floating_point<decltype(i/10)>::value)

and this also deals with the problem of i not being a compile-time constant. The value of i isn't constant, but its type is. Note the ::value on the end there. Once the template is expanded, you need ::value to get the resulting bool out of it.

Final point, i/10 is integer division all the way through so the result is guaranteed to be an integer. The if will always test false and skip the body.

Here's bit of example code:

#include <iostream>
#include <type_traits>

int main() {
    for (int i=1; i < 1000; i++)
        std::cout << std::boolalpha
                  << std::is_floating_point<decltype(i/10)>::value
                  << '\n';
}

You can set the upper bound of the loop to whatever you want, and you'll never get anything but false.


问:
Jquery: Display img next to line that was clicked
I'm trying to create a bookmarking feature for my site, so when someone clicks on "set bookmark" then they click on a line of text, it will place a bookmark image to the left of that line. (i'll then save the coor to a cookie, but i can do that without help)

One way I thought about doing it was when the person clicked on a line of text in a paragraph, have it grab the Y coordinate of the place the person clicked, then have that number rounded down to the nearest number divisible by 20. The line height of each paragraphs is 20px, so if you rounded the Y coordinates down, then you would get the top position for that single line inside the paragraph they clicked.

So I think it would go like this: when someone clicks on a line of text in a paragraph, it will get the index of that paragraph, so if it's the 4th P down the page, the index will be 3, then it will get the Y coordinates of where the user clicked, then round that number down to the nearest number divisible by 20, then place the image to the left of that paragraph with the TOP position of the image being the rounded Y coordinate.

Can anyone help me out with this? I'm kind of lost as you can see:

```<code>$('p').click(function(e) {
    var myIndex = $(this).index()
    var myIndexTop = myIndex.top()
    var myIndexLeft = myIndex.left()

    var offset = $(this).offset();
    var y = e.pageY - this.offsetTop;

    $('.bookMarkImg')
        .left(myIndexLeft)
        .top('round down to nearest num thats divisible by 20)
OR?
    $('.bookMarkImg')
        .css({'left': myIndexLeft, 'top' 'round down to nearest num thats divisible by 20'})
})
</code>```

答:
To round down to the nearest 20:

```<code>y = Math.floor(y / 20) * 20;
</code>```

Also, .top() and .left() don't exist: you'll want:

$(this).offset().top and $(this).offset().left for getting the positions

.css({left: ..., top: ...}) for setting them

Another thing is that if you only want one of these bookmark images to be floating around, depending on where you click, then you'll probably want to put the  at the  level (at the end), and positioned absolutely, so it is free to move around the entire document. Then, don't bother subtracting the offset of the paragraph from the y coordinate.

Sample code:

```<code>$('p').click(function (e) {
    var offset = $(this).offset();
    var top = Math.floor(e.pageY / 20) * 20;

    $('.bookMarkImg').css({
        left: offset.left,
        top: top
    }).show();
});
</code>```

See a working demo: http://jsfiddle.net/upgBa/

Note: You may have to consider any padding/margin/border you have on the paragraphs and the body though, which could throw off the calculations (just subtract the "top" portions of these).

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to create a bookmarking feature for my site, so when someone clicks on "set bookmark" then they click on a line of text, it will place a bookmark image to the left of that line. (i'll then save the coor to a cookie, but i can do that without help)

One way I thought about doing it was when the person clicked on a line of text in a paragraph, have it grab the Y coordinate of the place the person clicked, then have that number rounded down to the nearest number divisible by 20. The line height of each paragraphs is 20px, so if you rounded the Y coordinates down, then you would get the top position for that single line inside the paragraph they clicked.

So I think it would go like this: when someone clicks on a line of text in a paragraph, it will get the index of that paragraph, so if it's the 4th P down the page, the index will be 3, then it will get the Y coordinates of where the user clicked, then round that number down to the nearest number divisible by 20, then place the image to the left of that paragraph with the TOP position of the image being the rounded Y coordinate.

Can anyone help me out with this? I'm kind of lost as you can see:

$('p').click(function(e) {
    var myIndex = $(this).index()
    var myIndexTop = myIndex.top()
    var myIndexLeft = myIndex.left()

    var offset = $(this).offset();
    var y = e.pageY - this.offsetTop;

    $('.bookMarkImg')
        .left(myIndexLeft)
        .top('round down to nearest num thats divisible by 20)
OR?
    $('.bookMarkImg')
        .css({'left': myIndexLeft, 'top' 'round down to nearest num thats divisible by 20'})
})

Body:
To round down to the nearest 20:

y = Math.floor(y / 20) * 20;

Also, .top() and .left() don't exist: you'll want:

$(this).offset().top and $(this).offset().left for getting the positions

.css({left: ..., top: ...}) for setting them

Another thing is that if you only want one of these bookmark images to be floating around, depending on where you click, then you'll probably want to put the <img> at the <body> level (at the end), and positioned absolutely, so it is free to move around the entire document. Then, don't bother subtracting the offset of the paragraph from the y coordinate.

Sample code:

$('p').click(function (e) {
    var offset = $(this).offset();
    var top = Math.floor(e.pageY / 20) * 20;

    $('.bookMarkImg').css({
        left: offset.left,
        top: top
    }).show();
});

See a working demo: http://jsfiddle.net/upgBa/

Note: You may have to consider any padding/margin/border you have on the paragraphs and the body though, which could throw off the calculations (just subtract the "top" portions of these).


问:
how to select record based on max value and where clause in LINQ to Entities
i have following records in my table tbl_JobMaster

```<code>ID  CIN   JobNumber Version
1   ABC   100           1.0
2   ABC   100           2.0
3   ABC   200           1.0
4   ABC   200           2.0
5   ABC   200           3.0
6   XYZ   300           1.0
</code>```

i want list of records based on CIN column and MAX(Version) and unique JobNumber

for e.g. CIN=ABC
so output should be as follows

```<code>ID  CIN   JobNumber Version
2   ABC   100           2.0
5   ABC   200           3.0
</code>```

I tried following code but it isn't working

```<code>var result=(from job in entity.tbl_JobMaster
            where job.CIN=="ABC" && job.Version==entity.tbl_JobMaster.Where(p=>p.ID==job.ID).Max(p=>p.Version)
            select job).Distinct();
</code>```

答:
Your query should be like below</p>

```<code>var result = (from job in entity.tbl_JobMaster
    where job.CIN == "ABC" && job.Version == entity.tbl_JobMaster.Where(p => p.CIN == job.CIN && p.JobNumber == job.JobNumber).Max(p => p.Version)
    select job).Distinct();
</code>```

Body:
i have following records in my table tbl_JobMaster

ID  CIN   JobNumber Version
1   ABC   100           1.0
2   ABC   100           2.0
3   ABC   200           1.0
4   ABC   200           2.0
5   ABC   200           3.0
6   XYZ   300           1.0

i want list of records based on CIN column and MAX(Version) and unique JobNumber

for e.g. CIN=ABC
so output should be as follows

ID  CIN   JobNumber Version
2   ABC   100           2.0
5   ABC   200           3.0

I tried following code but it isn't working

var result=(from job in entity.tbl_JobMaster
            where job.CIN=="ABC" && job.Version==entity.tbl_JobMaster.Where(p=>p.ID==job.ID).Max(p=>p.Version)
            select job).Distinct();

Body:
Your query should be like below

var result = (from job in entity.tbl_JobMaster
    where job.CIN == "ABC" && job.Version == entity.tbl_JobMaster.Where(p => p.CIN == job.CIN && p.JobNumber == job.JobNumber).Max(p => p.Version)
    select job).Distinct();


问:
Reading TEXT type from SAP HANA into python
I am working on a project that requires me to get data from a SAP HANA database. I utilized SAP Cloud Connector and PyHDB for the job. I execute my select statement and obtain the result data. One of the fields is a TEXT type, containing large articles. While iterating each row I need to somehow get the data from the TEXT field into a string. However I am only able to get the first 1024 characters. The object that stores the TEXT appears to be a StringIO type. How can I read the entire text data instead of the first 1024 characters only?

```<code>import pyhdb

connection_from = pyhdb.connect(
host="localhost",
port=00000,
user="user",
password="password"
)
cursor_from = connection_from.cursor()

cursor_from.execute('SELECT * FROM SCHEMA.TABLE')
results= cursor_from.fetchall()

for row in results:
    text = row[2].data.getvalue()

connection_from.close()
</code>```

This is the what the object looks like: NClob

I need to get the whole text into a string then print it. Thank you.

答: According to the docs, you need to call .read() on the returned object, passing in the number of bytes you want to get. This is not a very friendly interface, but I guess if you pass in a number that is definitely bigger than all your objects, you'll get everything. Or you could do a small loop that iterates with bigger values until you have it all - when the length of string returned by .getvalue() does increase.

Body:
I am working on a project that requires me to get data from a SAP HANA database. I utilized SAP Cloud Connector and PyHDB for the job. I execute my select statement and obtain the result data. One of the fields is a TEXT type, containing large articles. While iterating each row I need to somehow get the data from the TEXT field into a string. However I am only able to get the first 1024 characters. The object that stores the TEXT appears to be a StringIO type. How can I read the entire text data instead of the first 1024 characters only?

import pyhdb

connection_from = pyhdb.connect(
host="localhost",
port=00000,
user="user",
password="password"
)
cursor_from = connection_from.cursor()

cursor_from.execute('SELECT * FROM SCHEMA.TABLE')
results= cursor_from.fetchall()

for row in results:
    text = row[2].data.getvalue()

connection_from.close()

This is the what the object looks like: NClob

I need to get the whole text into a string then print it. Thank you.


问:
Type Labels on Stacked and grouped column - Highcharts
I am trying to get the labels on the stacked bar graphs. The stack type in this is either male/female and I would like show that on the chart. Is there anyway to show it ?

Here is the link

https://jsfiddle.net/jq2e51Lx/

Here is the html:

```<code><script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</code>```

Javascript

```<code>Highcharts.chart('container', {

    chart: {
        type: 'column'
    },

    title: {
        text: 'Total fruit consumtion, grouped by gender'
    },

    xAxis: {
        categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
    },

    yAxis: {
        allowDecimals: false,
        min: 0,
        title: {
            text: 'Number of fruits'
        }
    },

    tooltip: {
        formatter: function () {
            return '<b>' + this.x + '</b><br/>' +
                this.series.name + ': ' + this.y + '<br/>' +
                'Total: ' + this.point.stackTotal;
        }
    },

    plotOptions: {
        column: {
            stacking: 'normal'
        }
    },

    series: [{
        name: 'John',
        data: [5, 3, 4, 7, 2],
        stack: 'male'
    }, {
        name: 'Joe',
        data: [3, 4, 4, 2, 5],
        stack: 'male'
    }, {
        name: 'Jane',
        data: [2, 5, 6, 2, 1],
        stack: 'female'
    }, {
        name: 'Janet',
        data: [3, 0, 4, 4, 3],
        stack: 'female'
    }]
});
</code>```

答:
The OP wrote in a comment:

Thank you so much !, Works like a charm :)

Based on fiddle sample by @Barbara Laird

Highcharts.chart('container', {
  chart: {
    type: 'column'
  },
  title: {
    text: 'Total fruit consumtion, grouped by gender'
  },
  xAxis: {
    categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas'],
    labels: {
      y: 40
    }
  },
  yAxis: {
    allowDecimals: false,
    min: 0,
    title: {
      text: 'Number of fruits'
    },
    stackLabels: {
      enabled: true,
      verticalAlign: 'bottom',
      crop: false,
      overflow: 'none',
      y: 20,
      formatter: function() {
        return this.stack;
      },
      style: {
        fontSize: '9px'
      }
    }
  },
  legend: {
    labelFormatter: function() {
      return this.name + ' (' + this.userOptions.stack + ')';
    }
  },
  tooltip: {
    formatter: function() {
      var stackName = this.series.userOptions.stack;

      return 'Stack name: ' + stackName + '
' + this.x + '
' +
        this.series.name + ': ' + this.y + '
' +
        'Total: ' + this.point.stackTotal;
    }
  },
  plotOptions: {
    column: {
      stacking: 'normal'
    }
  },
  series: [{
    name: 'John',
    data: [5, 3, 4, 7, 2],
    stack: 'male'
  }, {
    name: 'Joe',
    data: [3, 4, 4, 2, 5],
    stack: 'male'
  }, {
    name: 'Jane',
    data: [2, 5, 6, 2, 1],
    stack: 'female'
  }, {
    name: 'Janet',
    data: [3, 0, 4, 4, 3],
    stack: 'female'
  }]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div></code>```

Body:
I am trying to get the labels on the stacked bar graphs. The stack type in this is either male/female and I would like show that on the chart. Is there anyway to show it ?

Here is the link

https://jsfiddle.net/jq2e51Lx/

Here is the html:

Javascript

Highcharts.chart('container', {

    chart: {
        type: 'column'
    },

    title: {
        text: 'Total fruit consumtion, grouped by gender'
    },

    xAxis: {
        categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
    },

    yAxis: {
        allowDecimals: false,
        min: 0,
        title: {
            text: 'Number of fruits'
        }
    },

    tooltip: {
        formatter: function () {
            return '' + this.x + '
' +
                this.series.name + ': ' + this.y + '
' +
                'Total: ' + this.point.stackTotal;
        }
    },

    plotOptions: {
        column: {
            stacking: 'normal'
        }
    },

    series: [{
        name: 'John',
        data: [5, 3, 4, 7, 2],
        stack: 'male'
    }, {
        name: 'Joe',
        data: [3, 4, 4, 2, 5],
        stack: 'male'
    }, {
        name: 'Jane',
        data: [2, 5, 6, 2, 1],
        stack: 'female'
    }, {
        name: 'Janet',
        data: [3, 0, 4, 4, 3],
        stack: 'female'
    }]
});

Body:
The OP wrote in a comment:

Thank you so much !, Works like a charm :)

Based on fiddle sample by @Barbara Laird

Highcharts.chart('container', {
  chart: {
    type: 'column'
  },
  title: {
    text: 'Total fruit consumtion, grouped by gender'
  },
  xAxis: {
    categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas'],
    labels: {
      y: 40
    }
  },
  yAxis: {
    allowDecimals: false,
    min: 0,
    title: {
      text: 'Number of fruits'
    },
    stackLabels: {
      enabled: true,
      verticalAlign: 'bottom',
      crop: false,
      overflow: 'none',
      y: 20,
      formatter: function() {
        return this.stack;
      },
      style: {
        fontSize: '9px'
      }
    }
  },
  legend: {
    labelFormatter: function() {
      return this.name + ' (' + this.userOptions.stack + ')';
    }
  },
  tooltip: {
    formatter: function() {
      var stackName = this.series.userOptions.stack;

      return '<b>Stack name: </b>' + stackName + '<br/><b>' + this.x + '</b><br/>' +
        this.series.name + ': ' + this.y + '<br/>' +
        'Total: ' + this.point.stackTotal;
    }
  },
  plotOptions: {
    column: {
      stacking: 'normal'
    }
  },
  series: [{
    name: 'John',
    data: [5, 3, 4, 7, 2],
    stack: 'male'
  }, {
    name: 'Joe',
    data: [3, 4, 4, 2, 5],
    stack: 'male'
  }, {
    name: 'Jane',
    data: [2, 5, 6, 2, 1],
    stack: 'female'
  }, {
    name: 'Janet',
    data: [3, 0, 4, 4, 3],
    stack: 'female'
  }]
});

<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>


问:
Converting NSObject to NSDictionary
Hello I a class of type NSObject:

```<code>ProductDetails *details = [[ProductDetails alloc] init];
details.name = @"Soap1";
details.color = @"Red";
details.quantity = 4;
</code>```

I want to pass the "details" object to a dictionary.

I did,

```<code>NSDictionary *dict = [NSDictionary dictionaryWithObject:details forKey:@"details"];
</code>```

I am passing this dict to another method which performs a check on JSONSerialization:

```<code>if(![NSJSONSerialization isValidJSONObject:dict])
</code>```

And I am getting a crash on this check. Am I doing anything wrong here? I know that the details I am getting is a JSON object and I am assigning it to the properties in my ProductDetails class.

Please help me. I am a noob in Objective-C.

I now tried:

```<code>NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:(NSData*)details options:kNilOptions error:&error];
</code>```

All I need here is an easy way to convert details to NSData.

I noticed that I have an array inside my object may be thats why all the ways I tried is throwing an exception. However since this question is becoming to big, I have started an another question thread for it where I have displayed the data I am getting inside the object - https://stackoverflow.com/questions/19081104/convert-nsobject-to-nsdictionary

答:
You can convert object (say modelObject) to dictionary at runtime with the help of objc/runtime.h class but that has certain limitations and is not recommended.

Considering MVC, mapping logic should be implemented in Model class.

```<code>@interface ModelObject : NSObject
@property (nonatomic) NSString *p1;
@property (nonatomic) NSString *p2;
-(NSDictionary *)dictionary;
@end

#import "ModelObject.h"

@implementation ModelObject
-(NSDictionary *)dictionary
{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];

    [dict setValue:self.p1 forKey:@"p1"];// you can give different key name here if you want
    [dict setValue:self.p2 forKey:@"p2" ];

    return dict;
}
@end
</code>```

Uses:

```<code>NSDictionary *modelObjDict = [modelObj dictionary];
</code>```

Title: Converting NSObject to NSDictionary

Body:
Hello I a class of type NSObject:

ProductDetails *details = [[ProductDetails alloc] init];
details.name = @"Soap1";
details.color = @"Red";
details.quantity = 4;

I want to pass the "details" object to a dictionary.

I did,

NSDictionary *dict = [NSDictionary dictionaryWithObject:details forKey:@"details"];

I am passing this dict to another method which performs a check on JSONSerialization:

if(![NSJSONSerialization isValidJSONObject:dict])

And I am getting a crash on this check. Am I doing anything wrong here? I know that the details I am getting is a JSON object and I am assigning it to the properties in my ProductDetails class.

Please help me. I am a noob in Objective-C.

I now tried:

NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:(NSData*)details options:kNilOptions error:&error];

All I need here is an easy way to convert details to NSData.

I noticed that I have an array inside my object may be thats why all the ways I tried is throwing an exception. However since this question is becoming to big, I have started an another question thread for it where I have displayed the data I am getting inside the object - https://stackoverflow.com/questions/19081104/convert-nsobject-to-nsdictionary

Body:
You can convert object (say modelObject) to dictionary at runtime with the help of objc/runtime.h class but that has certain limitations and is not recommended.

Considering MVC, mapping logic should be implemented in Model class.

@interface ModelObject : NSObject
@property (nonatomic) NSString *p1;
@property (nonatomic) NSString *p2;
-(NSDictionary *)dictionary;
@end

#import "ModelObject.h"

@implementation ModelObject
-(NSDictionary *)dictionary
{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];

    [dict setValue:self.p1 forKey:@"p1"];// you can give different key name here if you want
    [dict setValue:self.p2 forKey:@"p2" ];

    return dict;
}
@end

Uses:

NSDictionary *modelObjDict = [modelObj dictionary];


问:
how can i make a threadsafe progress bar in C#? what am i doing wrong?
Hey everyone, can someone let me know what they see wrong with this code ?

it throws "Cross-thread operation not valid" exception, on

```<code>_DialogueThread.Start();
</code>```

but if i remove "owner" from

```<code>_progressDialogue = new Progresser{Owner = _owner, StartPosition = FormStartPosition.CenterParent};
</code>```

the exception wont be thrown but the progressDialouge will be shown then hidden right away .

now i understand why this the error is thrown if i set the progressDialouge.Owner to a parent form that was created on a different thread. but why dose the form disappears when i dont ?  what am i doing wrong ?

thanks

```<code>class Sampleer : BackgroundWorker
{
    private Progresser _progressDialogue;
    private Thread _DialogueThread;
    private Form _owner;
    private bool _SampleSuccess;

    public Sampleer(Form owner)
    {
        _owner = owner;
        _progressDialogue = new Progresser{Owner = _owner, StartPosition = FormStartPosition.CenterParent};
        _progressDialogue.Closed += ProgressDialogueClosed;
        WorkerReportsProgress = true;
        WorkerSupportsCancellation = true;
        DoWork += Sampleer_DoWork;
        RunWorkerCompleted += Sampleer_RunWorkerCompleted;
        ProgressChanged += Sampleer_ProgressChanged;
    }

    private void Sampleer_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {

       //UPDATE STATUS CODE IS HERE

    }

    void ProgressDialogueClosed(object sender, EventArgs e)
    {
        CancelAsync();
        Dispose();
    }

    void Sampleer_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        //FINISH PROCESS
    }

    void Sampleer_DoWork(object sender, DoWorkEventArgs e)
    {

        _DialogueThread = new Thread(_progressDialogue.Show);
        _DialogueThread.Start();

        //DO LONG PROCESS HERE
    }
}
</code>```

答:
In your action (button click), i would create the progress dialog, and then fire off the background worker. The background worker then reports back to the dialog in the ProgressChanged event.</p>

```<code>public partial class MainWindow : Window {

    private void btnDoSomething_Click(object sender0, RoutedEventArgs e0) {

        _progressDialogue = new Progresser{Owner = _owner, StartPosition = FormStartPosition.CenterParent};
        _progressDialogue.Closed += ProgressDialogueClosed;
        _progressDialogue.Show();

        BackgroundWorker worker = new BackgroundWorker();
        worker.WorkerReportsProgress = true;
        worker.DoWork += delegate(object sender, DoWorkEventArgs e) {
            DoSomething();

            e.Result = result;
        };
        worker.ProgressChanged += delegate(object sender, ProgressChangedEventArgs e) {
            progressDialogue.Update()
        };
        worker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e) {
            progressDialogue.Close()
        };
        worker.RunWorkerAsync(new CustomArgs() {
            SomeValue = txtValue.Text,
        });
    }
}
</code>```

Body:
Hey everyone, can someone let me know what they see wrong with this code ?

it throws "Cross-thread operation not valid" exception, on

_DialogueThread.Start();

but if i remove "owner" from

_progressDialogue = new Progresser{Owner = _owner, StartPosition = FormStartPosition.CenterParent};

the exception wont be thrown but the progressDialouge will be shown then hidden right away .

now i understand why this the error is thrown if i set the progressDialouge.Owner to a parent form that was created on a different thread. but why dose the form disappears when i dont ?  what am i doing wrong ?

thanks

class Sampleer : BackgroundWorker
{
    private Progresser _progressDialogue;
    private Thread _DialogueThread;
    private Form _owner;
    private bool _SampleSuccess;

    public Sampleer(Form owner)
    {
        _owner = owner;
        _progressDialogue = new Progresser{Owner = _owner, StartPosition = FormStartPosition.CenterParent};
        _progressDialogue.Closed += ProgressDialogueClosed;
        WorkerReportsProgress = true;
        WorkerSupportsCancellation = true;
        DoWork += Sampleer_DoWork;
        RunWorkerCompleted += Sampleer_RunWorkerCompleted;
        ProgressChanged += Sampleer_ProgressChanged;
    }

    private void Sampleer_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {

       //UPDATE STATUS CODE IS HERE

    }

    void ProgressDialogueClosed(object sender, EventArgs e)
    {
        CancelAsync();
        Dispose();
    }

    void Sampleer_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        //FINISH PROCESS
    }

    void Sampleer_DoWork(object sender, DoWorkEventArgs e)
    {

        _DialogueThread = new Thread(_progressDialogue.Show);
        _DialogueThread.Start();

        //DO LONG PROCESS HERE
    }
}

Body:
In your action (button click), i would create the progress dialog, and then fire off the background worker. The background worker then reports back to the dialog in the ProgressChanged event.

public partial class MainWindow : Window {

    private void btnDoSomething_Click(object sender0, RoutedEventArgs e0) {

        _progressDialogue = new Progresser{Owner = _owner, StartPosition = FormStartPosition.CenterParent};
        _progressDialogue.Closed += ProgressDialogueClosed;
        _progressDialogue.Show();

        BackgroundWorker worker = new BackgroundWorker();
        worker.WorkerReportsProgress = true;
        worker.DoWork += delegate(object sender, DoWorkEventArgs e) {
            DoSomething();

            e.Result = result;
        };
        worker.ProgressChanged += delegate(object sender, ProgressChangedEventArgs e) {
            progressDialogue.Update()
        };
        worker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e) {
            progressDialogue.Close()
        };
        worker.RunWorkerAsync(new CustomArgs() {
            SomeValue = txtValue.Text,
        });
    }
}


问:
Ajax To PHP converter get value from ajax
i need help, here my code :

```<code><html>
<head>
<script>
function showHint(str) {
    if (str.length == 0) {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("txtHint").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET", "getstok.php?secretkey=123&sku=" + str, true);
        xmlhttp.send();
    }
}
</script>
</head>
<body>
<p><b>Masukkan kode barang / SKU:</b></p>
<form>
Kode Barang: <input type="text" onkeyup="showHint(this.value)">
</form>
<div id="txtHint"></span>
</body>
</html>
</code>```

What I need is:

I want to hide this "secretkey=123" so visitor cannot see my secret key

when call "xmlhttp.send();" return the value and I want to convert it to php like example

$getxmlhttp = xmlhttp.send();

when I type something it will be call function, but when I press enter that refresh, how to disable the enter or what the best suggestion for me.

this is my site sample:
http://stok.tk

for example type "YI 067"

答:
1 : You can't. The browser (and so the visitor) can always know wich page is called with wich URL and parameters

2 : You can't do it like that. You need to get the value of your request into getstok.php with the super global variables $_GET['your var']

3 : It's reloading the page because it's sending your form. By default it send it to the same page. Just remove your <form>

Body:
i need help, here my code :

Masukkan kode barang / SKU:

<form>
Kode Barang: <input type="text" onkeyup="showHint(this.value)">
</form>

What I need is:

I want to hide this "secretkey=123" so visitor cannot see my secret key

when call "xmlhttp.send();" return the value and I want to convert it to php like example

$getxmlhttp = xmlhttp.send();

when I type something it will be call function, but when I press enter that refresh, how to disable the enter or what the best suggestion for me.

this is my site sample:
http://stok.tk

for example type "YI 067"


问:
Broadcast the message in LAN via android app
Here's my code for sending the string message in LAN on only one device or on one listening server and it is done by defining the IP of the server in client, both client and server programs are android app.But i want to broadcast the message so that all the listening server shall receive my message.

Here's my client code:

```<code>    public class MainActivity extends Activity {
    private Socket socket;
    private static final int SERVERPORT = 6000;
    private static final String SERVER_IP = "10.0.2.2";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Thread(new ClientThread()).start();
    }

    public void onClick(View view) {
        try {
            EditText et = (EditText) findViewById(R.id.EditText01);
            String str = et.getText().toString();
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())),
                    true);
            out.println(str);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class ClientThread implements Runnable {

        @Override
        public void run() {

            try {
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

                DatagramSocket = new Socket(serverAddr, SERVERPORT);

            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }}
</code>```

Here is my server code:

```<code>    public class MainActivity extends Activity {
    private DatagramSocket serverSocket;
    Handler updateConversationHandler;
    Thread serverThread = null;
    private TextView text;
    public static final int SERVERPORT = 6000;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text = (TextView) findViewById(R.id.text2);

        updateConversationHandler = new Handler();

        this.serverThread = new Thread(new ServerThread());
        this.serverThread.start();
    }

    @Override
    protected void onStop() {
        super.onStop();
        try {
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class ServerThread implements Runnable {

        public void run() {
            Socket socket = null;
            try {
                serverSocket = new ServerSocket(SERVERPORT);
            } catch (IOException e) {
                e.printStackTrace();
            }
            while (!Thread.currentThread().isInterrupted()) {

                try {

                    socket = serverSocket.accept();

                    CommunicationThread commThread = new CommunicationThread(socket);
                    new Thread(commThread).start();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class CommunicationThread implements Runnable {

        private Socket clientSocket;
        private BufferedReader input;
        public CommunicationThread(Socket clientSocket) {

            this.clientSocket = clientSocket;

            try {
                this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void run() {
            while (!Thread.currentThread().isInterrupted()) {

                try {
                    String read = input.readLine();

                    updateConversationHandler.post(new updateUIThread(read));

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    class updateUIThread implements Runnable {
        private String msg;
        public updateUIThread(String str) {
            this.msg = str;
        }

        @Override
        public void run() {
            text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
        }
    }}
</code>```

What changing shall I made in client or server so that i can broadcast the string message in LAN and all the listening servers should receive,, Thanks in advance.Please kindly help.

答:
you should use Network Service Discovery, the device broadcast the service (as server in your case) and also listen to the service at the same time:

https://developer.android.com/training/connect-devices-wirelessly/nsd.html

Body:
Here's my code for sending the string message in LAN on only one device or on one listening server and it is done by defining the IP of the server in client, both client and server programs are android app.But i want to broadcast the message so that all the listening server shall receive my message.

Here's my client code:

    public class MainActivity extends Activity {
    private Socket socket;
    private static final int SERVERPORT = 6000;
    private static final String SERVER_IP = "10.0.2.2";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Thread(new ClientThread()).start();
    }

    public void onClick(View view) {
        try {
            EditText et = (EditText) findViewById(R.id.EditText01);
            String str = et.getText().toString();
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())),
                    true);
            out.println(str);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class ClientThread implements Runnable {

        @Override
        public void run() {

            try {
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

                DatagramSocket = new Socket(serverAddr, SERVERPORT);

            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }}

Here is my server code:

    public class MainActivity extends Activity {
    private DatagramSocket serverSocket;
    Handler updateConversationHandler;
    Thread serverThread = null;
    private TextView text;
    public static final int SERVERPORT = 6000;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text = (TextView) findViewById(R.id.text2);

        updateConversationHandler = new Handler();

        this.serverThread = new Thread(new ServerThread());
        this.serverThread.start();
    }

    @Override
    protected void onStop() {
        super.onStop();
        try {
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class ServerThread implements Runnable {

        public void run() {
            Socket socket = null;
            try {
                serverSocket = new ServerSocket(SERVERPORT);
            } catch (IOException e) {
                e.printStackTrace();
            }
            while (!Thread.currentThread().isInterrupted()) {

                try {

                    socket = serverSocket.accept();

                    CommunicationThread commThread = new CommunicationThread(socket);
                    new Thread(commThread).start();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class CommunicationThread implements Runnable {

        private Socket clientSocket;
        private BufferedReader input;
        public CommunicationThread(Socket clientSocket) {

            this.clientSocket = clientSocket;

            try {
                this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void run() {
            while (!Thread.currentThread().isInterrupted()) {

                try {
                    String read = input.readLine();

                    updateConversationHandler.post(new updateUIThread(read));

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    class updateUIThread implements Runnable {
        private String msg;
        public updateUIThread(String str) {
            this.msg = str;
        }

        @Override
        public void run() {
            text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
        }
    }}

What changing shall I made in client or server so that i can broadcast the string message in LAN and all the listening servers should receive,, Thanks in advance.Please kindly help.


问:
Can I pass a variable in Javascript to a child_process.exec command?
I'm relatively new to Node and have been put on a project where the user will input their first and last name in a form, then the server will output a file with their first initial and their last name as the file name (so John Smith would come out as JSmith).

I'm trying to take that user input and put it in my child_process.exec command, but it won't recognize the variable, so I'm getting a file with no name. So instead of JSmith.txt, I'm just getting .txt

```<code>var name = fields['name']
var nameArray = name.split(' ')
var fileName = nameArray[0].charAt(0) + nameArray[1]

process.exec("Start of my command here"+fileName+ ".txt", function(error, stdout, stderr){
    console.log('done')
    console.log('stdout:', stdout);
    console.log('stderr:', stderr);
})
</code>```

Is this the right function to be using or should I use something else? I feel like the problem lies with the variable not being read incorrectly, but I don't know how to pass it in.

答:
I ran into exactly your problem and my workaround included just concatenating the string in advance.

```<code>var name = fields['name']
var nameArray = name.split(' ')
var fileName = nameArray[0].charAt(0) + nameArray[1]
var command = yourCommand + filename + ".txt" #replace yourCommand here

process.exec(command, function(error, stdout, stderr){
    console.log('done')
    console.log('stdout:', stdout);
    console.log('stderr:', stderr);
})
</code>```

In case you want to pass an object (eg. array) into another file via exec, you just need to stringify it first.

```<code>var myArray = ['beans', 'toast']
var stringifiedArray = JSON.stringify(myArray)
var command = 'python myModel.py ' + stringifiedArray

process.exec(command, function(error, stdout, stderr){
    console.log('done')
    console.log('stdout:', stdout);
    console.log('stderr:', stderr);
})
</code>```

In the other file (in this case a python file called myModel.py), you can then parse the input again.

```<code>input = sys.argv[1]   #reading the (first) argument from the shell
data = json.loads(input)
</code>```

Body:
I'm relatively new to Node and have been put on a project where the user will input their first and last name in a form, then the server will output a file with their first initial and their last name as the file name (so John Smith would come out as JSmith).

I'm trying to take that user input and put it in my child_process.exec command, but it won't recognize the variable, so I'm getting a file with no name. So instead of JSmith.txt, I'm just getting .txt

var name = fields['name']
var nameArray = name.split(' ')
var fileName = nameArray[0].charAt(0) + nameArray[1]

process.exec("Start of my command here"+fileName+ ".txt", function(error, stdout, stderr){
    console.log('done')
    console.log('stdout:', stdout);
    console.log('stderr:', stderr);
})

Is this the right function to be using or should I use something else? I feel like the problem lies with the variable not being read incorrectly, but I don't know how to pass it in.

Body:
I ran into exactly your problem and my workaround included just concatenating the string in advance.

var name = fields['name']
var nameArray = name.split(' ')
var fileName = nameArray[0].charAt(0) + nameArray[1]
var command = yourCommand + filename + ".txt" #replace yourCommand here

process.exec(command, function(error, stdout, stderr){
    console.log('done')
    console.log('stdout:', stdout);
    console.log('stderr:', stderr);
})

In case you want to pass an object (eg. array) into another file via exec, you just need to stringify it first.

var myArray = ['beans', 'toast']
var stringifiedArray = JSON.stringify(myArray)
var command = 'python myModel.py ' + stringifiedArray

process.exec(command, function(error, stdout, stderr){
    console.log('done')
    console.log('stdout:', stdout);
    console.log('stderr:', stderr);
})

In the other file (in this case a python file called myModel.py), you can then parse the input again.

input = sys.argv[1]   #reading the (first) argument from the shell
data = json.loads(input)


问:
Swift Query Into Firebase Firestore Nested Array
I have nested data that I'd like to display in a tableView.

My data is structured like so...

```<code>/users
    /userid
         name: "John"
         age: 23
         /likedPosts
            0:post1
            1:post2
</code>```

For the tableview I'd like to display these posts (which have their own collection of data).

In order to do that I need to...

1) Get the count of the array and

2) Query the users likedPost array values to get the content of the post.

I'm currently using the getDocument function and can't figure it out.

for example...

```<code>func getUserLikedPosts() {
    if let user = Auth.auth().currentUser {
        let userFS = Firestore.firestore().collection("users").document(user.uid)
        userFS.getDocument(completion: { (snapshot, error) in
            print(snapshot?)

        })
    }
}
</code>```

This doesn't even print out the nested array?

答:
Something like this should work:

```<code>func getUserLikedPosts() {
if let user = Auth.auth().currentUser {
    let userFS = Firestore.firestore().collection("users").document(user.uid).collection(“likedPosts”)
    userFS.getDocuments(completion: { (snapshot, error) in
        print(snapshot?)

    })
}
}
</code>```

With Firestore you need to drill down to the actual node you want, unlike Firebase where you can access child snapshots.

So after a quick discussion, with the OP, it was that the user in question didn’t have a likedPost object.

To access the array (Please be aware I haven’t tested this code, it is an example):

```<code>If let doc = document, let array = doc[“likedPost] as NSArray {
print(array)
}
</code>```

Body:
I have nested data that I'd like to display in a tableView.

My data is structured like so...

/users
    /userid
         name: "John"
         age: 23
         /likedPosts
            0:post1
            1:post2

For the tableview I'd like to display these posts (which have their own collection of data).

In order to do that I need to...

1) Get the count of the array and

2) Query the users likedPost array values to get the content of the post.

I'm currently using the getDocument function and can't figure it out.

for example...

func getUserLikedPosts() {
    if let user = Auth.auth().currentUser {
        let userFS = Firestore.firestore().collection("users").document(user.uid)
        userFS.getDocument(completion: { (snapshot, error) in
            print(snapshot?)

        })
    }
}

This doesn't even print out the nested array?

Body:
Something like this should work:

func getUserLikedPosts() {
if let user = Auth.auth().currentUser {
    let userFS = Firestore.firestore().collection("users").document(user.uid).collection(“likedPosts”)
    userFS.getDocuments(completion: { (snapshot, error) in
        print(snapshot?)

    })
}
}

With Firestore you need to drill down to the actual node you want, unlike Firebase where you can access child snapshots.

So after a quick discussion, with the OP, it was that the user in question didn’t have a likedPost object.

To access the array (Please be aware I haven’t tested this code, it is an example):

If let doc = document, let array = doc[“likedPost] as NSArray {
print(array)
}


问:
Image upload in a database directory
i am little bit problem in Image upload in a database directory.image upload my avatar folder and can't show my page becouse problem is that in database id, username table show my data but imagelocation table can't show my directory.please any one told me that, what is the problem in my code and correct it specify line

upload.php

```<code><?php

 include("connecton.php");

 $_SESSION['username']="kyle";

 $username = $_SESSION['username'];

  if($_POST['submit'])
  {

      //get file attribute

      $name = $_FILES['myfile']['name'];
      $tmp_name = $_FILES['myfile']['tmp_name'];

      if($name)
      {

          //start upload process

           $location = "avatars/$name";
           move_uploaded_file($tmp_name,$location);

           $query = mysql_query("UPDATE users SET imagelocation='$location' WHERE username='$username'");

           die("Your avatar has been uploaded! <a href='view.php'>HOme</a>");
      }
      else
       die("Please select a file");

  }

 echo "Welcome, ".$username."!<p>";

 echo "Upload Your Image:

<form action='upload.php' method='POST' enctype='multipart/form-data'>

  File: <input type='file' name='myfile'> <input type='submit' name='submit' value='upload!'>

  </form>

 ";

?>
</code>```

view.php

```<code><?php

   include("connecton.php");

   $username = $_SESSION['username'];

   $query = mysql_query("SELECT * FROM users WHERE username='$username'");

   if (mysql_num_rows($query)==0)

   die ("User not found");
   else
   {

       $row = mysql_fetch_assoc($query);
       $location = $row['imagelocation'];

       echo "<img src='$location' width='100' height='100'>";

   }

?>
</code>```

答:
First php statement of both of upload.php and view.php should be this:</p>

```<code>session_start();
</code>```

Title: Image upload in a database directory

Body:
i am little bit problem in Image upload in a database directory.image upload my avatar folder and can't show my page becouse problem is that in database id, username table show my data but imagelocation table can't show my directory.please any one told me that, what is the problem in my code and correct it specify line

upload.php

<?php

 include("connecton.php");

 $_SESSION['username']="kyle";

 $username = $_SESSION['username'];

  if($_POST['submit'])
  {

      //get file attribute

      $name = $_FILES['myfile']['name'];
      $tmp_name = $_FILES['myfile']['tmp_name'];

      if($name)
      {

          //start upload process

           $location = "avatars/$name";
           move_uploaded_file($tmp_name,$location);

           $query = mysql_query("UPDATE users SET imagelocation='$location' WHERE username='$username'");

           die("Your avatar has been uploaded! HOme");
      }
      else
       die("Please select a file");

  }

 echo "Welcome, ".$username."!
";

 echo "Upload Your Image:

<form action='upload.php' method='POST' enctype='multipart/form-data'>

  File: <input type='file' name='myfile'> <input type='submit' name='submit' value='upload!'>

  </form>

 ";

?>

view.php

<?php

   include("connecton.php");

   $username = $_SESSION['username'];

   $query = mysql_query("SELECT * FROM users WHERE username='$username'");

   if (mysql_num_rows($query)==0)

   die ("User not found");
   else
   {

       $row = mysql_fetch_assoc($query);
       $location = $row['imagelocation'];

       echo "";

   }

?>

Body:
First php statement of both of upload.php and view.php should be this:

session_start();


问:
Multiple dex files error when compiling with ant or Eclipse
I am unable to build my application
I am running the latest build tools downloaded today, this started happening after the update.

```<code>-dex:
   [dex] Converting compiled files and external libraries into
         /Users/rob/Repos/my_app/bin/classes.dex...
    [dx]
    [dx] UNEXPECTED TOP-LEVEL EXCEPTION:
    [dx] com.android.dx.util.DexException: Multiple dex files define
         Lcom/robaldred/myapp/About$1;
</code>```

I have tried cleaning and rebuilding, I've also tried in Eclipse but it gives the same error.
Anyone got any ideas? I'm at a brick wall here now.

答:
Change implementation fileTree(include: ['.jar'], dir: 'libs') to
provided fileTree(include: ['.jar'], dir: 'libs') in your app gradle.build> dependencies.

Make sure it has changed in your Module Settings> Dependencies {include=[*jar] dir=libs} too. It must have a scope of Provided next to it and not Implementation.

Body:
I am unable to build my application
I am running the latest build tools downloaded today, this started happening after the update.

-dex:
   [dex] Converting compiled files and external libraries into
         /Users/rob/Repos/my_app/bin/classes.dex...
    [dx]
    [dx] UNEXPECTED TOP-LEVEL EXCEPTION:
    [dx] com.android.dx.util.DexException: Multiple dex files define
         Lcom/robaldred/myapp/About$1;

I have tried cleaning and rebuilding, I've also tried in Eclipse but it gives the same error.
Anyone got any ideas? I'm at a brick wall here now.


问:
how to get only positive results when applying hashCode()?
I am working on a Scala code that convert set of unique strings to unique IDs. I applied HashCode() but I got negative numbers and I need to work only with positive numbers.
I know that I have to use math.abs to get rid of the negative values but I am not sure if this is the correct solution or not.
If I read before that something like this could solve my problem

```<code>math.abs(hashCode()) * constant % size
</code>```

how can I determine the right constant? and does the size means the total number of strings?

previous questions related to that topic solved the question by using math.abs only but if the total number of string is large an overflow could happen and there is a chance to get a negative number as well. by multiplying the result with constant and take the mod of size could help. This is why I need to understand how to determine the constant and the size?

Also is there another way to get unique numbers for unique strings?

答:
We can phrase your problem another way: How to get an unsigned number from a signed number with the same range?

Suppose you are using an Integer. Its value goes from -2147483648 to 2147483647. Now you need to convert this value into the positive range 0 to 2147483647.

Step 1:

ADD a constant to move the range upwards to 0. You can do this by adding 2147483648 to the value. But now the highest possible value is much greater than the MAX.

Step 2:

So use MODULO to move the value back into the required range.

For example, consider the values -2000 and 2000000000.

```<code>| STEP              | MIN VALUE  | EXAMPLE 1  | EXAMPLE 2  | MAX VALUE  |
|-------------------|------------|------------|------------|------------|
| original          |-2147483648 |   -2000    | 2000000000 | 2147483647 |
| add 2147483648    |     0      | 2147481648 | 4147483648 | 4294967295 |
| modulo 2147483648 |     0      | 2147481648 | 2000000001 | 2147483647 |
</code>```

So the final formula is:

```<code>(NUMBER + 2147483648) % 2147481648
</code>```

Warning:

  Hash codes are not designed to give unique values. There are chances of  getting the same hash for two different strings. Also, any scaling operations on the hash (like division, modulo) can further reduce uniqueness.

Body:
I am working on a Scala code that convert set of unique strings to unique IDs. I applied HashCode() but I got negative numbers and I need to work only with positive numbers.
I know that I have to use math.abs to get rid of the negative values but I am not sure if this is the correct solution or not.
If I read before that something like this could solve my problem

math.abs(hashCode()) * constant % size

how can I determine the right constant? and does the size means the total number of strings?

previous questions related to that topic solved the question by using math.abs only but if the total number of string is large an overflow could happen and there is a chance to get a negative number as well. by multiplying the result with constant and take the mod of size could help. This is why I need to understand how to determine the constant and the size?

Also is there another way to get unique numbers for unique strings?

Body:
We can phrase your problem another way: How to get an unsigned number from a signed number with the same range?

Suppose you are using an Integer. Its value goes from -2147483648 to 2147483647. Now you need to convert this value into the positive range 0 to 2147483647.

Step 1:

ADD a constant to move the range upwards to 0. You can do this by adding 2147483648 to the value. But now the highest possible value is much greater than the MAX.

Step 2:

So use MODULO to move the value back into the required range.

For example, consider the values -2000 and 2000000000.

| STEP              | MIN VALUE  | EXAMPLE 1  | EXAMPLE 2  | MAX VALUE  |
|-------------------|------------|------------|------------|------------|
| original          |-2147483648 |   -2000    | 2000000000 | 2147483647 |
| add 2147483648    |     0      | 2147481648 | 4147483648 | 4294967295 |
| modulo 2147483648 |     0      | 2147481648 | 2000000001 | 2147483647 |

So the final formula is:

(NUMBER + 2147483648) % 2147481648

Warning:

  Hash codes are not designed to give unique values. There are chances of  getting the same hash for two different strings. Also, any scaling operations on the hash (like division, modulo) can further reduce uniqueness.


问:
How to make an integer from it's numbers?
I have a number, which I have to write backward. I already separated it's digits in an array, but how can I make the new number from this array?</p>

答:
You don't need to store digits in an array to reverse digits of number. </p>

```<code>#include <iostream>
using namespace std;
int main()
{
    int input;
    cin>>input;
    int reverse = 0;
    while(input)
    {
        reverse *= 10;
        reverse += input % 10;
        input /= 10;
    }
    cout << reverse << endl;
    return 0;
}
</code>```

Body:
You don't need to store digits in an array to reverse digits of number.

#include <iostream>
using namespace std;
int main()
{
    int input;
    cin>>input;
    int reverse = 0;
    while(input)
    {
        reverse *= 10;
        reverse += input % 10;
        input /= 10;
    }
    cout << reverse << endl;
    return 0;
}


问:
Automatically finding server on local network from Android app
I am working on a system consisting of a server and an Android app, which has to contact said server. In the app, it is currently possible to specify the server address, but we now want the client to automatically look for the server on the local network to make it more usable. My current understanding of the problem is that I can send a message to the local broadcast address at 255.255.255.255, and then this message will reach all IP's in the local network. So far, I came up with the following:

```<code>try {
    DatagramSocket discoveryBroadcaster = new DatagramSocket();
    discoveryBroadcaster.send(new DatagramPacket(msg.getBytes(),msg.getBytes().length,
            InetAddress.getByName("255.255.255.255"),8000));
}
catch (IOException e) {
    e.printStackTrace();
}
</code>```

We communicate with the server through a RESTful interface. I would like the message we send to be a GET request so that we can implement the response on the server as an endpoint just like everything else. The problem is that the only way I know of to create a GET request is through the httpurlconnection class, which needs a target URL first. Therefore, my questions are:

Is it possible to compose a GET request as a string and then send it to the broadcast address?

Will sending a GET request to the broadcast address work?

Is the above a correct or viable approach to solving this problem?

答:
more information about Zeroconf, it's called Network Service Discovery in Android

your server broadcast the service and the android devices listen to the service:

https://developer.android.com/training/connect-devices-wirelessly/nsd.html

Body:
I am working on a system consisting of a server and an Android app, which has to contact said server. In the app, it is currently possible to specify the server address, but we now want the client to automatically look for the server on the local network to make it more usable. My current understanding of the problem is that I can send a message to the local broadcast address at 255.255.255.255, and then this message will reach all IP's in the local network. So far, I came up with the following:

try {
    DatagramSocket discoveryBroadcaster = new DatagramSocket();
    discoveryBroadcaster.send(new DatagramPacket(msg.getBytes(),msg.getBytes().length,
            InetAddress.getByName("255.255.255.255"),8000));
}
catch (IOException e) {
    e.printStackTrace();
}

We communicate with the server through a RESTful interface. I would like the message we send to be a GET request so that we can implement the response on the server as an endpoint just like everything else. The problem is that the only way I know of to create a GET request is through the httpurlconnection class, which needs a target URL first. Therefore, my questions are:

Is it possible to compose a GET request as a string and then send it to the broadcast address?

Will sending a GET request to the broadcast address work?

Is the above a correct or viable approach to solving this problem?