问:
problem referencing JPA
I have to use a jpa project on one of my projects, but I'm having this error once I create an entitymanager and call persistencecontect in my sessionbean:

```<code>@Stateless
public class Biblio implements BiblioLocal {
 @PersistenceContext(unitName="BiblioJPA")
 private EntityManager em;
    /**
     * Default constructor.
     */
    public Biblio() {
        // TODO Auto-generated constructor stub
    }

 @Override
 public String succes() {
  // TODO Auto-generated method stub
  return " beta";
 }
 public void toevoegenBoek(){
  Boeken boek = new Boeken();
  boek.setTitel("harry P.");
  boek.setAuteur("rowling");
  em.persist(boek);
 }

}
</code>```

My servlet (which calls a method from this sessionbean) won't load anymore and gives me this very long error of which i don't understand anything. Any ideas? (without the entitymanager and persistencecontext my servlet does load, but then i'm not able to call any functions related to the jpa!)

Thanks!

The error i get when running the servlet:

```<code>javax.servlet.ServletException: Error instantiating servlet class servlets.BiblioServlet
    org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
    org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
    org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
    org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    java.lang.Thread.run(Unknown Source)

root cause

java.lang.RuntimeException: Unable to inject jndi dependency: env/servlets.BiblioServlet/biblio into property servlets.BiblioServlet.biblio: BiblioEAR not bound
    org.jboss.injection.JndiPropertyInjector.lookup(JndiPropertyInjector.java:82)
    org.jboss.injection.JndiPropertyInjector.inject(JndiPropertyInjector.java:99)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.processInjectors(TomcatInjectionContainer.java:366)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.newInstance(TomcatInjectionContainer.java:271)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.newInstance(TomcatInjectionContainer.java:265)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.newInstance(TomcatInjectionContainer.java:256)
    org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
    org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
    org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
    org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    java.lang.Thread.run(Unknown Source)

root cause

javax.naming.NamingException: Could not dereference object [Root exception is javax.naming.NameNotFoundException: BiblioEAR not bound]
    org.jnp.interfaces.NamingContext.resolveLink(NamingContext.java:1352)
    org.jnp.interfaces.NamingContext.lookup(NamingContext.java:817)
    org.jnp.interfaces.NamingContext.lookup(NamingContext.java:686)
    org.jboss.ejb3.JndiUtil.lookup(JndiUtil.java:44)
    org.jboss.injection.JndiPropertyInjector.lookup(JndiPropertyInjector.java:75)
    org.jboss.injection.JndiPropertyInjector.inject(JndiPropertyInjector.java:99)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.processInjectors(TomcatInjectionContainer.java:366)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.newInstance(TomcatInjectionContainer.java:271)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.newInstance(TomcatInjectionContainer.java:265)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.newInstance(TomcatInjectionContainer.java:256)
    org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
    org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
    org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
    org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    java.lang.Thread.run(Unknown Source)

root cause

javax.naming.NameNotFoundException: BiblioEAR not bound
    org.jnp.server.NamingServer.getBinding(NamingServer.java:771)
    org.jnp.server.NamingServer.getBinding(NamingServer.java:779)
    org.jnp.server.NamingServer.getObject(NamingServer.java:785)
    org.jnp.server.NamingServer.lookup(NamingServer.java:396)
    org.jnp.interfaces.NamingContext.lookup(NamingContext.java:726)
    org.jnp.interfaces.NamingContext.lookup(NamingContext.java:686)
    javax.naming.InitialContext.lookup(Unknown Source)
    org.jnp.interfaces.NamingContext.resolveLink(NamingContext.java:1346)
    org.jnp.interfaces.NamingContext.lookup(NamingContext.java:817)
    org.jnp.interfaces.NamingContext.lookup(NamingContext.java:686)
    org.jboss.ejb3.JndiUtil.lookup(JndiUtil.java:44)
    org.jboss.injection.JndiPropertyInjector.lookup(JndiPropertyInjector.java:75)
    org.jboss.injection.JndiPropertyInjector.inject(JndiPropertyInjector.java:99)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.processInjectors(TomcatInjectionContainer.java:366)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.newInstance(TomcatInjectionContainer.java:271)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.newInstance(TomcatInjectionContainer.java:265)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.newInstance(TomcatInjectionContainer.java:256)
    org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
    org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
    org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
    org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    java.lang.Thread.run(Unknown Source)
</code>```

The error in my console (in eclipse)

```<code>DEPLOYMENTS MISSING DEPENDENCIES:
  Deployment "jboss.j2ee:ear=BiblioEAR.ear,jar=BiblioEJB.jar,name=Biblio,service=EJB3" is missing the following dependencies:
    Dependency "<UNKNOWN jboss.j2ee:ear=BiblioEAR.ear,jar=BiblioEJB.jar,name=Biblio,service=EJB3>" (should be in state "Described", but is actually in state "** UNRESOLVED Demands 'persistence.unit:unitName=BiblioEAR.ear/BiblioJPA.jar#BiblioJPA' **")
  Deployment "jboss.j2ee:ear=BiblioEAR.ear,jar=BiblioEJB.jar,name=Biblio,service=EJB3_endpoint" is missing the following dependencies:
    Dependency "jboss.j2ee:ear=BiblioEAR.ear,jar=BiblioEJB.jar,name=Biblio,service=EJB3" (should be in state "Configured", but is actually in state "PreInstall")

DEPLOYMENTS IN ERROR:
  Deployment "persistence.unit:unitName=BiblioEAR.ear/BiblioJPA.jar#BiblioJPA" is in error due to the following reason(s): org.xml.sax.SAXParseException: cvc-complex-type.3.1: Value '2.0' of attribute 'version' of element 'entity-mappings' is not valid with respect to the corresponding attribute use. Attribute 'version' has a fixed value of '1.0'.
  Deployment "<UNKNOWN jboss.j2ee:ear=BiblioEAR.ear,jar=BiblioEJB.jar,name=Biblio,service=EJB3>" is in error due to the following reason(s): ** UNRESOLVED Demands 'persistence.unit:unitName=BiblioEAR.ear/BiblioJPA.jar#BiblioJPA' **
</code>```

Edit:

persistence.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="BiblioJPA" transaction-type="JTA">
        <jta-data-source>java:/MySqlDSAlfa</jta-data-source>
    </persistence-unit>
</persistence>
</code>```

mysql-ds.xml

```<code><datasources>
  <local-tx-datasource>
    <jndi-name>MySqlDSAlfa</jndi-name>
    <connection-url>jdbc:mysql://localhost:8080/database</connection-url>
    <driver-class>com.mysql.jdbc.Driver</driver-class>
    <user-name>root</user-name>
    <password></password>
    <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
    <metadata>
       <type-mapping>mySQL</type-mapping>
    </metadata>
  </local-tx-datasource>
</datasources>
</code>```

Title: problem referencing JPA

Body:
I have to use a jpa project on one of my projects, but I'm having this error once I create an entitymanager and call persistencecontect in my sessionbean:

@Stateless
public class Biblio implements BiblioLocal {
 @PersistenceContext(unitName="BiblioJPA")
 private EntityManager em;
    /**
     * Default constructor.
     */
    public Biblio() {
        // TODO Auto-generated constructor stub
    }

 @Override
 public String succes() {
  // TODO Auto-generated method stub
  return " beta";
 }
 public void toevoegenBoek(){
  Boeken boek = new Boeken();
  boek.setTitel("harry P.");
  boek.setAuteur("rowling");
  em.persist(boek);
 }

}

My servlet (which calls a method from this sessionbean) won't load anymore and gives me this very long error of which i don't understand anything. Any ideas? (without the entitymanager and persistencecontext my servlet does load, but then i'm not able to call any functions related to the jpa!)

Thanks!

The error i get when running the servlet:

javax.servlet.ServletException: Error instantiating servlet class servlets.BiblioServlet
    org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
    org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
    org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
    org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    java.lang.Thread.run(Unknown Source)

root cause

java.lang.RuntimeException: Unable to inject jndi dependency: env/servlets.BiblioServlet/biblio into property servlets.BiblioServlet.biblio: BiblioEAR not bound
    org.jboss.injection.JndiPropertyInjector.lookup(JndiPropertyInjector.java:82)
    org.jboss.injection.JndiPropertyInjector.inject(JndiPropertyInjector.java:99)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.processInjectors(TomcatInjectionContainer.java:366)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.newInstance(TomcatInjectionContainer.java:271)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.newInstance(TomcatInjectionContainer.java:265)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.newInstance(TomcatInjectionContainer.java:256)
    org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
    org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
    org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
    org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    java.lang.Thread.run(Unknown Source)

root cause

javax.naming.NamingException: Could not dereference object [Root exception is javax.naming.NameNotFoundException: BiblioEAR not bound]
    org.jnp.interfaces.NamingContext.resolveLink(NamingContext.java:1352)
    org.jnp.interfaces.NamingContext.lookup(NamingContext.java:817)
    org.jnp.interfaces.NamingContext.lookup(NamingContext.java:686)
    org.jboss.ejb3.JndiUtil.lookup(JndiUtil.java:44)
    org.jboss.injection.JndiPropertyInjector.lookup(JndiPropertyInjector.java:75)
    org.jboss.injection.JndiPropertyInjector.inject(JndiPropertyInjector.java:99)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.processInjectors(TomcatInjectionContainer.java:366)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.newInstance(TomcatInjectionContainer.java:271)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.newInstance(TomcatInjectionContainer.java:265)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.newInstance(TomcatInjectionContainer.java:256)
    org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
    org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
    org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
    org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    java.lang.Thread.run(Unknown Source)

root cause

javax.naming.NameNotFoundException: BiblioEAR not bound
    org.jnp.server.NamingServer.getBinding(NamingServer.java:771)
    org.jnp.server.NamingServer.getBinding(NamingServer.java:779)
    org.jnp.server.NamingServer.getObject(NamingServer.java:785)
    org.jnp.server.NamingServer.lookup(NamingServer.java:396)
    org.jnp.interfaces.NamingContext.lookup(NamingContext.java:726)
    org.jnp.interfaces.NamingContext.lookup(NamingContext.java:686)
    javax.naming.InitialContext.lookup(Unknown Source)
    org.jnp.interfaces.NamingContext.resolveLink(NamingContext.java:1346)
    org.jnp.interfaces.NamingContext.lookup(NamingContext.java:817)
    org.jnp.interfaces.NamingContext.lookup(NamingContext.java:686)
    org.jboss.ejb3.JndiUtil.lookup(JndiUtil.java:44)
    org.jboss.injection.JndiPropertyInjector.lookup(JndiPropertyInjector.java:75)
    org.jboss.injection.JndiPropertyInjector.inject(JndiPropertyInjector.java:99)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.processInjectors(TomcatInjectionContainer.java:366)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.newInstance(TomcatInjectionContainer.java:271)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.newInstance(TomcatInjectionContainer.java:265)
    org.jboss.web.tomcat.service.TomcatInjectionContainer.newInstance(TomcatInjectionContainer.java:256)
    org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
    org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
    org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
    org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    java.lang.Thread.run(Unknown Source)

The error in my console (in eclipse)

DEPLOYMENTS MISSING DEPENDENCIES:
  Deployment "jboss.j2ee:ear=BiblioEAR.ear,jar=BiblioEJB.jar,name=Biblio,service=EJB3" is missing the following dependencies:
    Dependency "<UNKNOWN jboss.j2ee:ear=BiblioEAR.ear,jar=BiblioEJB.jar,name=Biblio,service=EJB3>" (should be in state "Described", but is actually in state "** UNRESOLVED Demands 'persistence.unit:unitName=BiblioEAR.ear/BiblioJPA.jar#BiblioJPA' **")
  Deployment "jboss.j2ee:ear=BiblioEAR.ear,jar=BiblioEJB.jar,name=Biblio,service=EJB3_endpoint" is missing the following dependencies:
    Dependency "jboss.j2ee:ear=BiblioEAR.ear,jar=BiblioEJB.jar,name=Biblio,service=EJB3" (should be in state "Configured", but is actually in state "PreInstall")

DEPLOYMENTS IN ERROR:
  Deployment "persistence.unit:unitName=BiblioEAR.ear/BiblioJPA.jar#BiblioJPA" is in error due to the following reason(s): org.xml.sax.SAXParseException: cvc-complex-type.3.1: Value '2.0' of attribute 'version' of element 'entity-mappings' is not valid with respect to the corresponding attribute use. Attribute 'version' has a fixed value of '1.0'.
  Deployment "<UNKNOWN jboss.j2ee:ear=BiblioEAR.ear,jar=BiblioEJB.jar,name=Biblio,service=EJB3>" is in error due to the following reason(s): ** UNRESOLVED Demands 'persistence.unit:unitName=BiblioEAR.ear/BiblioJPA.jar#BiblioJPA' **

Edit:

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="BiblioJPA" transaction-type="JTA">
        <jta-data-source>java:/MySqlDSAlfa</jta-data-source>
    </persistence-unit>
</persistence>

mysql-ds.xml

<datasources>
  <local-tx-datasource>
    <jndi-name>MySqlDSAlfa</jndi-name>
    <connection-url>jdbc:mysql://localhost:8080/database</connection-url>
    <driver-class>com.mysql.jdbc.Driver</driver-class>
    <user-name>root</user-name>
    <password></password>
    <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
    <metadata>
       <type-mapping>mySQL</type-mapping>
    </metadata>
  </local-tx-datasource>
</datasources>


来源: stackexchange

问:
Set focus on a `CheckboxList` control via javascript
I have a checkboxList named cblNSGONF. It has two list items.

Using vanilla javascript, I want to set focus to the checkboxlist, whether item[0] or item[1].

I tried using document.getElementById('cblNSGONF_0').focus(). However, this is not working. How can I simply set focus to the control?

答:
Hello,

See if it's what you need:

```<code>document.myForm.check1.focus();
</code>```

Sample:

```<code><form name="myForm">
  <input type="checkbox" name="check1">1</br><hr>
  <input type="button" value="Move" onClick="move()">
</form>

<script>
function move() {
  document.myForm.check1.focus();
}
</script>
</code>```

I hope it helped you!

ContentLicense: CC BY-SA 3.0

Body:
Hello,

See if it's what you need:

document.myForm.check1.focus();

Sample:

<form name="myForm">
  <input type="checkbox" name="check1">1</br><hr>
  <input type="button" value="Move" onClick="move()">
</form>

<script>
function move() {
  document.myForm.check1.focus();
}
</script>

I hope it helped you!


问:
Restarting the animation once all divs are clicked?
I am trying to get the script to run again after all the gifs have been clicked and changed to the png's. Once all the gifs are clicked I have to refresh the browser in order for the game to start again. I would preferably like to have the creation of a newDiv happen when one of the divs is clicked. So that way a new one appears when one is clicked, and is constantly adding the newDiv. Any ideas on how to do that would help.

HTML:

```<code><!DOCTYPE html>
<html>

<head>

<title>Shoo Fly</title>

<style>

div.a {
width: 200px;
height:200px;
position:absolute;
background-image: url("fly.gif");
   }

html {
  background: url("fly-background.png");
  background-size: cover;
  background-repeat: no-repeat;
  margin: 0;
  padding:0;
  background-color: #50BBAD;
  zoom: 80%;
  }

 </style>

 <script src="jquery-3.1.1.js"></script>
 <script src="please-work.js"></script>

 </head>

 <body>

 <div class="animatedDivs"></div>

</body>

</html>
</code>```

Javascript:

```<code>$(document).ready(function () {
newDiv();
newDiv();
newDiv();
newDiv();
newDiv(); //5
newDiv();
newDiv();
newDiv();
newDiv();
newDiv(); //10
});

function newDiv() {
var $div = $("<div class='a'>");
$(".animatedDivs").append($div);
animateDiv();

$div.click(function(){
    $div.css('background-image','url(splatter-1.png)');
    $div.css('zIndex' , '-1');
    $div.css({'position': 'absolute'});
    //$(this).data('clicked', true);
    var offset = $div.position();
    $div.stop();
    $div.position({left:(offset.left), right: (offset.right)});
});

function animateDiv() {
    var newq = makeNewPosition();
    var oldq = $div.offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);

    $div.animate({
        top: newq[0],
        left: newq[1]
    }, speed, function () {
        animateDiv();
    });

};

}

function makeNewPosition() {

// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;

var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);

return [nh, nw];

}

function calcSpeed(prev, next) {

var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);

var greatest = x > y ? x : y;

var speedModifier = .1;

var speed = Math.ceil(greatest / speedModifier);

return speed;

}
</code>```

答:
Well, if all what you want it is to create a new div when one is clicked, you just need to call to your newDiv function from inside the click function handler:

```<code>$div.click(function(){
    newDiv();
    // more code
});
</code>```

And if, as the title suggests, you want to restart the animation once all divs are clicked, just check if all are already clicked inside the click function handler:

```<code>$div.click(function(){
    $(this).data('clicked')
    if ( allAreClicked() ) {
        // code to restart the game
    }
    // more code
});

function allAreClicked() {
    return $('.animatedDivs > div').lenght = $('.animatedDivs > div[data-cliked="true"]').lenght;
}
</code>```

Body:
I am trying to get the script to run again after all the gifs have been clicked and changed to the png's. Once all the gifs are clicked I have to refresh the browser in order for the game to start again. I would preferably like to have the creation of a newDiv happen when one of the divs is clicked. So that way a new one appears when one is clicked, and is constantly adding the newDiv. Any ideas on how to do that would help.

HTML:

<!DOCTYPE html>

<title>Shoo Fly</title>

Javascript:

$(document).ready(function () {
newDiv();
newDiv();
newDiv();
newDiv();
newDiv(); //5
newDiv();
newDiv();
newDiv();
newDiv();
newDiv(); //10
});

function newDiv() {
var $div = $("
");
$(".animatedDivs").append($div);
animateDiv();

$div.click(function(){
    $div.css('background-image','url(splatter-1.png)');
    $div.css('zIndex' , '-1');
    $div.css({'position': 'absolute'});
    //$(this).data('clicked', true);
    var offset = $div.position();
    $div.stop();
    $div.position({left:(offset.left), right: (offset.right)});
});

function animateDiv() {
    var newq = makeNewPosition();
    var oldq = $div.offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);

    $div.animate({
        top: newq[0],
        left: newq[1]
    }, speed, function () {
        animateDiv();
    });

};

}

function makeNewPosition() {

// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;

var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);

return [nh, nw];

}

function calcSpeed(prev, next) {

var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);

var greatest = x > y ? x : y;

var speedModifier = .1;

var speed = Math.ceil(greatest / speedModifier);

return speed;

}

Body:
Well, if all what you want it is to create a new div when one is clicked, you just need to call to your newDiv function from inside the click function handler:

$div.click(function(){
    newDiv();
    // more code
});

And if, as the title suggests, you want to restart the animation once all divs are clicked, just check if all are already clicked inside the click function handler:

$div.click(function(){
    $(this).data('clicked')
    if ( allAreClicked() ) {
        // code to restart the game
    }
    // more code
});

function allAreClicked() {
    return $('.animatedDivs > div').lenght = $('.animatedDivs > div[data-cliked="true"]').lenght;
}


问:
Get Duplicates in List and Edit Item
I need to get any items in a list that already exist and edit BOTH items to include a duplicate property.

I've attempted to get duplicates by doing:

```<code>var duplicates = LIST.Select((t, i) => new { Index = i, Text = t }).GroupBy(g => g.Text.PROPERTYTOSEARCGBY).Where(g => g.Count() > 1);
</code>```

However this returns me the property that is duplicated when however I need to get index of both of the records so that I can edit them using:

```<code>LIST[index1].FlaggedData = true;
LIST[index2].FlaggedData = true;
etc...
</code>```

How can I get the index of BOTH duplicate or multiple records?

答:
Use SelectMany</p>

```<code>duplicates = LIST.Select((t, i) => new { Index = i, Text = t })
.GroupBy(g => g.Text.PROPERTYTOSEARCGBY)
.Where(g => g.Count() > 1)
.SelectMany(g => g, (g, x) => x.Index);
</code>```

Title: Get Duplicates in List and Edit Item

Body:
I need to get any items in a list that already exist and edit BOTH items to include a duplicate property.

I've attempted to get duplicates by doing:

var duplicates = LIST.Select((t, i) => new { Index = i, Text = t }).GroupBy(g => g.Text.PROPERTYTOSEARCGBY).Where(g => g.Count() > 1);

However this returns me the property that is duplicated when however I need to get index of both of the records so that I can edit them using:

LIST[index1].FlaggedData = true;
LIST[index2].FlaggedData = true;
etc...

How can I get the index of BOTH duplicate or multiple records?

Body:
Use SelectMany

duplicates = LIST.Select((t, i) => new { Index = i, Text = t })
.GroupBy(g => g.Text.PROPERTYTOSEARCGBY)
.Where(g => g.Count() > 1)
.SelectMany(g => g, (g, x) => x.Index);


问:
Should ngModelChange work with custom form control?
Let's say I'm making a custom form control. Can I do this?

```<code><custom-control [ngModel]="myModelVariable" (ngModelChange)="modelHasChanged($event)"></custom-control>
</code>```

I'm able to get [(ngModel)] working with all the form controls I've made, but I'm not able to check for changes. A lot of people using my components need this, and I'm wondering if there is a clean way to do it without creating @Output EventEmitters. I'm thinking I'm not doing something correctly, but maybe I'm wrong.

This is a sample component implementation following the pattern I understand:

```<code>@Component({
  selector: 'custom-control',
  providers: [
    { provide: NG_VALUE_ACCESSOR, useClass: CustomControlComponent, multi: true }
  ]
})
export class CustomControlComponent implements ControlValueAccessor {

  private onChangeCallback: (_: any) => void = (_: any) => {};
  private onTouchedCallback: () => void = () => {};

  private innerValue: any;

  get value(): any {
    return this.innerValue;
  }

  set value(val: any) {
    if (val !== this.innerValue) {
      this.innerValue = val;
      this.onChangeCallback(this.innerValue);
    }
  }

  writeValue(val: any) {
    if (val !== this.innerValue) {
      this.innerValue = val;
    }
  }

  registerOnChange(fn: any) {
    this.onChangeCallback = fn;
  }

  registerOnTouched(fn: any) {
    this.onTouchedCallback = fn;
  }

}
</code>```

答:
After closer inspection, some of the components in question weren't calling the onChangedCallback in the setter, hence our problems. Others weren't being implemented correctly.

Sorry for bothering you, Angular world.

Body:
Let's say I'm making a custom form control. Can I do this?

<custom-control [ngModel]="myModelVariable" (ngModelChange)="modelHasChanged($event)"></custom-control>

I'm able to get [(ngModel)] working with all the form controls I've made, but I'm not able to check for changes. A lot of people using my components need this, and I'm wondering if there is a clean way to do it without creating @Output EventEmitters. I'm thinking I'm not doing something correctly, but maybe I'm wrong.

This is a sample component implementation following the pattern I understand:

@Component({
  selector: 'custom-control',
  providers: [
    { provide: NG_VALUE_ACCESSOR, useClass: CustomControlComponent, multi: true }
  ]
})
export class CustomControlComponent implements ControlValueAccessor {

  private onChangeCallback: (_: any) => void = (_: any) => {};
  private onTouchedCallback: () => void = () => {};

  private innerValue: any;

  get value(): any {
    return this.innerValue;
  }

  set value(val: any) {
    if (val !== this.innerValue) {
      this.innerValue = val;
      this.onChangeCallback(this.innerValue);
    }
  }

  writeValue(val: any) {
    if (val !== this.innerValue) {
      this.innerValue = val;
    }
  }

  registerOnChange(fn: any) {
    this.onChangeCallback = fn;
  }

  registerOnTouched(fn: any) {
    this.onTouchedCallback = fn;
  }

}


问:
Unexpected result with Floating Point Values inside of Javascript Array
The expected return is shown below:

checkCashRegister(3.26, 100.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]) should return [["TWENTY", 60.00], ["TEN", 20.00], ["FIVE", 15.00], ["ONE", 1.00], ["QUARTER", 0.50], ["DIME", 0.20], ["PENNY", 0.04]].

When I look at the output in the console, it seems the same as expected output, but I don't know the reason it fails. I will appreciate your help. Here is the link to my code: https://jsfiddle.net/do91m6qy/

function checkCashRegister(price, cash, cid) {
  var change;
  // Here is your change, ma'am.
  change="Insufficient Funds";
  change="Closed";
  var typeObj={"PENNY":0.01,"NICKEL":0.05,"DIME":0.10,"QUARTER":0.25,"ONE":1,"FIVE":5,"TEN":10,"TWENTY":20,"ONE HUNDRED":100};
  var changeArr=[["PENNY", 0],["NICKEL", 0],["DIME", 0],["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY",0], ["ONE HUNDRED", 0]];

  var diff=cash-price;
  var total=cid.reduce(function(acc,val){
    //console.log("acc",acc,"val",val);
    return Math.round((acc+val[1])*100)/100;
  },0);
  //console.log("total",total);
  if(diff>total)
   return "Insufficient Funds";
  else if(diff==total)
   return "Closed";

  cid.reverse().forEach(function(arr,i){
   var key=arr[1];
    var curr=typeObj[arr[0]];
    var sum=0;
    diff=Math.round(diff*100)/100;
    console.log("curr",curr,"key",key,"diff",diff,"diff/curr",diff/curr);
    //console.log("changeArr[changeArr.length-1-i][1]",changeArr[changeArr.length-1-i][1]);
   while(key>=curr && (diff/curr>=1)){
        diff=Math.round(diff*100)/100;
 console.log("inside","curr",curr,"key",key,"diff",diff,"diff/curr",diff/curr);       sum+=curr;
       changeArr[changeArr.length-1-i][1]=sum/100*100;
       key-=curr;
       if(diff>=curr)
         diff-=curr;
    }
  });
    console.log("changeArr",changeArr);

  changeArr=changeArr.filter(function(arr){
    return arr[1]!==0;
  });

  console.log(changeArr);
  if(diff===0)
   return changeArr;

  console.log("------");
  return "Insufficient Funds";
}

// Example cash-in-drawer array:
// [["PENNY", 1.01],
// ["NICKEL", 2.05],
// ["DIME", 3.10],
// ["QUARTER", 4.25],
// ["ONE", 90.00],
// ["FIVE", 55.00],
// ["TEN", 20.00],
// ["TWENTY", 60.00],
// ["ONE HUNDRED", 100.00]]

checkCashRegister(3.26, 100.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]);```

答: The test was failing just because of the array order which was in reverse. So all I had to do was to use array.reverse() and the issue was resolved.</p>


问:
Glade treeview liststore data not visible, can't imagine why
I've got 99% 44/100 of everything working. I have a glade file, I use gtkbuilder to render it and voila it comes up. Everything except the data in my treeview liststore.
I notice by default the tree view is not visible, and setting that to true makes a box appear in the tree view area, but I can't get any of my liststore items to display in the treeview.
I have some default data in the list store defined in glade, and I programmatically add some too, but nothing ever displays. Is there some visible on/off option I'm missing?</p>

答:
Just to add to what ptomato said, thought I'd throw in the xml for what I have :</p>

```<code><object class="GtkTreeView" id="portfolio_treeview">
    <property name="visible">True</property>
    <property name="can_focus">True</property>
    <property name="model">portfolio_liststore</property>
    <property name="search_column">0</property>
    <child>
      <object class="GtkTreeViewColumn" id="treeviewcolumn4">
        <property name="title">ID</property>
        <property name="clickable">True</property>
        <property name="sort_indicator">True</property>
        <property name="sort_column_id">0</property>
        <child>
          <object class="GtkCellRendererText" id="cellrenderertext4"/>
          <attributes>
            <attribute name="text">0</attribute>
          </attributes>
        </child>
      </object>
    </child>
</object>
</code>```

Body:
Just to add to what ptomato said, thought I'd throw in the xml for what I have :

<object class="GtkTreeView" id="portfolio_treeview">
    <property name="visible">True</property>
    <property name="can_focus">True</property>
    <property name="model">portfolio_liststore</property>
    <property name="search_column">0</property>
    <child>
      <object class="GtkTreeViewColumn" id="treeviewcolumn4">
        <property name="title">ID</property>
        <property name="clickable">True</property>
        <property name="sort_indicator">True</property>
        <property name="sort_column_id">0</property>
        <child>
          <object class="GtkCellRendererText" id="cellrenderertext4"/>
          <attributes>
            <attribute name="text">0</attribute>
          </attributes>
        </child>
      </object>
    </child>
</object>

ContentLicense: CC BY-SA 2.5


问:
Unexpected status line when making post request from android device
Hi I have an Android app that needs to connect to an API (currently running locally) to authenticate the user, so I'm trying to send a POST request with a JSON object as the request body but whenever I try to login I get the following error:

```<code>Unexpected status line: ��
           java.net.ProtocolException: Unexpected status line: ��
</code>```

Here's my code:

```<code>    String API_URL = "http://10.0.2.2:8443/api/";
        try {
            URL url = new URL(API_URL);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try {
                urlConnection.setDoOutput(true);
                urlConnection.setRequestMethod("POST");
                urlConnection.setRequestProperty("Content-Type", "application/json");
                urlConnection.connect();

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("customerId", 1);
                jsonObject.put("password" , mPassword);
                jsonObject.put("username" , mEmail);

                DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
                wr.writeBytes(jsonObject.toString());
                Log.d("REQUEST BODY", jsonObject.toString());
                wr.flush();
                wr.close();

                int response = urlConnection.getResponseCode();
                Log.d("RESPONSE", String.valueOf(response));
                if(response == HttpURLConnection.HTTP_OK) {
                    InputStream bis = new BufferedInputStream(urlConnection.getInputStream());
                    return getStringFromInputStream(bis);
                }
            }
            finally{
                urlConnection.disconnect();
            }
        }
        catch(Exception e) {
            Log.e("ERROR", e.getMessage(), e);
            return null;
        }
</code>```

Can anyone please tell me what I might be doing wrong? Thanks!

EDIT

Not sure if this helps but the problem seems to occur when I call urlConnection.getResponseCode();.

答:
Possibly you are recycling the connection

try adding urlConnection.setRequestProperty("Connection", "close");  before connecting

Body:
Hi I have an Android app that needs to connect to an API (currently running locally) to authenticate the user, so I'm trying to send a POST request with a JSON object as the request body but whenever I try to login I get the following error:

Unexpected status line: ��
           java.net.ProtocolException: Unexpected status line: ��

Here's my code:

    String API_URL = "http://10.0.2.2:8443/api/";
        try {
            URL url = new URL(API_URL);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try {
                urlConnection.setDoOutput(true);
                urlConnection.setRequestMethod("POST");
                urlConnection.setRequestProperty("Content-Type", "application/json");
                urlConnection.connect();

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("customerId", 1);
                jsonObject.put("password" , mPassword);
                jsonObject.put("username" , mEmail);

                DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
                wr.writeBytes(jsonObject.toString());
                Log.d("REQUEST BODY", jsonObject.toString());
                wr.flush();
                wr.close();

                int response = urlConnection.getResponseCode();
                Log.d("RESPONSE", String.valueOf(response));
                if(response == HttpURLConnection.HTTP_OK) {
                    InputStream bis = new BufferedInputStream(urlConnection.getInputStream());
                    return getStringFromInputStream(bis);
                }
            }
            finally{
                urlConnection.disconnect();
            }
        }
        catch(Exception e) {
            Log.e("ERROR", e.getMessage(), e);
            return null;
        }

Can anyone please tell me what I might be doing wrong? Thanks!

EDIT

Not sure if this helps but the problem seems to occur when I call urlConnection.getResponseCode();.


问:
OleDb - Incorrect syntax near the keyword 'DEFAULT'
Alright so, Im trying to do a simple update query to a table but I keep getting this error Incorrect syntax near the keyword 'DEFAULT'. The thing is. it only goes wrong when ome values are NULL, but I've checked and IT DOES allow null values. Here is my code for the query

```<code>public void UpdateQuery(String[] valores)
{
    conexion = this.Connections.OLEDBCONNECTION.ConnectionString;
    String query = " UPDATE [UTB_CUENTAS] SET CODTYP=ISNULL(?,CODTYP), CODORG=ISNULL(?,CODORG), CODGRP=ISNULL(?,CODGRP), TXTDEN=ISNULL(?,TXTDEN),"
                 + " IDEACC=ISNULL(?,IDEACC), CODAPP=ISNULL(?,CODAPP), NUMPLZ=ISNULL(?,NUMPLZ), CODCUR=ISNULL(?,CODCUR), DATING=ISNULL(?,DATING),"
                 + " NUMACCCTE=ISNULL(?,NUMACCCTE), DATCAN=ISNULL(?,DATCAN), FLGESTADO=ISNULL(?,FLGESTADO), DATELI=ISNULL(?,DATELI),"
                 + " DATUPD=ISNULL(?,DATUPD), TXTADR=ISNULL(?,TXTADR), CODUSR=ISNULL(?,CODUSR)"
                 + " WHERE NUMACC = ?";

    using (OleDbConnection con = new OleDbConnection(conexion))
    {
        con.Open();
        using (OleDbCommand cmd = con.CreateCommand())
        {
            cmd.Parameters.Add("@CODTYP", OleDbType.VarChar, 3).Value = valores[1];
            cmd.Parameters.Add("@CODORG", OleDbType.VarChar, 18).Value = valores[2];
            cmd.Parameters.Add("@CODGRP", OleDbType.VarChar, 4).Value = valores[3];
            cmd.Parameters.Add("@TXTDEN", OleDbType.VarChar, 150).Value = valores[4];
            cmd.Parameters.Add("@IDEACC", OleDbType.Char, 1).Value = valores[5];
            cmd.Parameters.Add("@CODAPP", OleDbType.VarChar, 2).Value = valores[6];
            cmd.Parameters.Add("@NUMPLZ", OleDbType.VarChar, 3).Value = valores[7];
            cmd.Parameters.Add("@CODCUR", OleDbType.Char, 3).Value = valores[8];

            if (valores[9] == null)
                cmd.Parameters.Add("@DATING", OleDbType.DBTimeStamp).Value = DBNull.Value;
            else
                cmd.Parameters.Add("@DATING", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[9]);

            cmd.Parameters.Add("@NUMACCCTE", OleDbType.VarChar, 18).Value = valores[10];

            if (valores[11] == null)
                cmd.Parameters.Add("@DATCAN", OleDbType.DBTimeStamp).Value = DBNull.Value;
            else
                cmd.Parameters.Add("@DATCAN", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[11]);

            cmd.Parameters.Add("@FLGESTADO", OleDbType.Char, 1).Value = valores[12];

            if (valores[13] == null)
                cmd.Parameters.Add("@DATELI", OleDbType.DBTimeStamp).Value = DBNull.Value;
            else
                cmd.Parameters.Add("@DATELI", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[13]);

            cmd.Parameters.Add("@DATUPD", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[14]);
            cmd.Parameters.Add("@TXTADR", OleDbType.VarChar, 100).Value = valores[15];
            cmd.Parameters.Add("@CODUSR", OleDbType.VarChar, 7).Value = valores[16];
            cmd.Parameters.Add("@NUMACC", OleDbType.VarChar, 18).Value = valores[0];

            cmd.CommandText = query;
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (OleDbException ex)
            {
                byte[] emptybytes = new byte[0];

                this.Log("CustomMessage: Error en NUMACC: " + valores[0] + " | " + ex.Message, 0, emptybytes);
            }
            cmd.Parameters.Clear();
        }
        con.Close();
    }
}
</code>```

I have given the "yyyy-MM-dd HH:mm:ss" format for the datetime column. It works when I do it from SQl Server Management Studio, but thats it. Now, I know OLEDB doesnt really care about parameter name, it works on the same order is called in the query. Thats why I did it this way.

I've testing with just using

```<code>String query = " UPDATE [UTB_CUENTAS] SET CODTYP=ISNULL(?,CODTYP) WHERE NUMACC = ?"
</code>```

and only using the first parameter and it works! but using the second value CODORG it throws the error.

In this case, valores[2] and valores[3] are null values, but since Im using ISNULL() in the query, I believe it shouldnt be a problem. Even if it is, the column allow null values, but its not updating

答:
I meant creates sql string dinamically in that way...

```<code>String SQLquery = " UPDATE [UTB_CUENTAS] SET ";

if (valores[1] != null)
{
    SQLquery = SQLquery + " CODTYP=?, " +
    cmd.Parameters.Add("@CODTYP", OleDbType.VarChar, 3).Value = valores[1];
}
</code>```

.... so for all the value,
and finally

```<code>//REMOVE THE LAST COMMA
SQLquery = SQLquery.Substring(0,SQLquery.lenght -2) + " WHERE NUMACC = ? "
cmd.Parameters.Add("@NUMACC", OleDbType.VarChar, 18).Value = valores[0];

cmd.CommandText = query;
cmd.ExecuteNonQuery();
</code>```

and also the processing is optimized

Body:
Alright so, Im trying to do a simple update query to a table but I keep getting this error Incorrect syntax near the keyword 'DEFAULT'. The thing is. it only goes wrong when ome values are NULL, but I've checked and IT DOES allow null values. Here is my code for the query

public void UpdateQuery(String[] valores)
{
    conexion = this.Connections.OLEDBCONNECTION.ConnectionString;
    String query = " UPDATE [UTB_CUENTAS] SET CODTYP=ISNULL(?,CODTYP), CODORG=ISNULL(?,CODORG), CODGRP=ISNULL(?,CODGRP), TXTDEN=ISNULL(?,TXTDEN),"
                 + " IDEACC=ISNULL(?,IDEACC), CODAPP=ISNULL(?,CODAPP), NUMPLZ=ISNULL(?,NUMPLZ), CODCUR=ISNULL(?,CODCUR), DATING=ISNULL(?,DATING),"
                 + " NUMACCCTE=ISNULL(?,NUMACCCTE), DATCAN=ISNULL(?,DATCAN), FLGESTADO=ISNULL(?,FLGESTADO), DATELI=ISNULL(?,DATELI),"
                 + " DATUPD=ISNULL(?,DATUPD), TXTADR=ISNULL(?,TXTADR), CODUSR=ISNULL(?,CODUSR)"
                 + " WHERE NUMACC = ?";

    using (OleDbConnection con = new OleDbConnection(conexion))
    {
        con.Open();
        using (OleDbCommand cmd = con.CreateCommand())
        {
            cmd.Parameters.Add("@CODTYP", OleDbType.VarChar, 3).Value = valores[1];
            cmd.Parameters.Add("@CODORG", OleDbType.VarChar, 18).Value = valores[2];
            cmd.Parameters.Add("@CODGRP", OleDbType.VarChar, 4).Value = valores[3];
            cmd.Parameters.Add("@TXTDEN", OleDbType.VarChar, 150).Value = valores[4];
            cmd.Parameters.Add("@IDEACC", OleDbType.Char, 1).Value = valores[5];
            cmd.Parameters.Add("@CODAPP", OleDbType.VarChar, 2).Value = valores[6];
            cmd.Parameters.Add("@NUMPLZ", OleDbType.VarChar, 3).Value = valores[7];
            cmd.Parameters.Add("@CODCUR", OleDbType.Char, 3).Value = valores[8];

            if (valores[9] == null)
                cmd.Parameters.Add("@DATING", OleDbType.DBTimeStamp).Value = DBNull.Value;
            else
                cmd.Parameters.Add("@DATING", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[9]);

            cmd.Parameters.Add("@NUMACCCTE", OleDbType.VarChar, 18).Value = valores[10];

            if (valores[11] == null)
                cmd.Parameters.Add("@DATCAN", OleDbType.DBTimeStamp).Value = DBNull.Value;
            else
                cmd.Parameters.Add("@DATCAN", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[11]);

            cmd.Parameters.Add("@FLGESTADO", OleDbType.Char, 1).Value = valores[12];

            if (valores[13] == null)
                cmd.Parameters.Add("@DATELI", OleDbType.DBTimeStamp).Value = DBNull.Value;
            else
                cmd.Parameters.Add("@DATELI", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[13]);

            cmd.Parameters.Add("@DATUPD", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[14]);
            cmd.Parameters.Add("@TXTADR", OleDbType.VarChar, 100).Value = valores[15];
            cmd.Parameters.Add("@CODUSR", OleDbType.VarChar, 7).Value = valores[16];
            cmd.Parameters.Add("@NUMACC", OleDbType.VarChar, 18).Value = valores[0];

            cmd.CommandText = query;
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (OleDbException ex)
            {
                byte[] emptybytes = new byte[0];

                this.Log("CustomMessage: Error en NUMACC: " + valores[0] + " | " + ex.Message, 0, emptybytes);
            }
            cmd.Parameters.Clear();
        }
        con.Close();
    }
}

I have given the "yyyy-MM-dd HH:mm:ss" format for the datetime column. It works when I do it from SQl Server Management Studio, but thats it. Now, I know OLEDB doesnt really care about parameter name, it works on the same order is called in the query. Thats why I did it this way.

I've testing with just using

String query = " UPDATE [UTB_CUENTAS] SET CODTYP=ISNULL(?,CODTYP) WHERE NUMACC = ?"

and only using the first parameter and it works! but using the second value CODORG it throws the error.

In this case, valores[2] and valores[3] are null values, but since Im using ISNULL() in the query, I believe it shouldnt be a problem. Even if it is, the column allow null values, but its not updating

Body:
I meant creates sql string dinamically in that way...

String SQLquery = " UPDATE [UTB_CUENTAS] SET ";

if (valores[1] != null)
{
    SQLquery = SQLquery + " CODTYP=?, " +
    cmd.Parameters.Add("@CODTYP", OleDbType.VarChar, 3).Value = valores[1];
}

.... so for all the value,
and finally

//REMOVE THE LAST COMMA
SQLquery = SQLquery.Substring(0,SQLquery.lenght -2) + " WHERE NUMACC = ? "
cmd.Parameters.Add("@NUMACC", OleDbType.VarChar, 18).Value = valores[0];

cmd.CommandText = query;
cmd.ExecuteNonQuery();

and also the processing is optimized


问:
Parsing XML using the xpath.js in Node JS
My XML looks like this:

```<code><ns2:OrderList>
  <order order_id="123" item_name="123"/>
  <order order_id="234" item_name="1233"/>
  <order order_id="2357" item_name="1234"/>
  ......
</ns2:OrderList>
</code>```

I am wanting to use the XPath.js from npjms.

How can I get array with "order_id" values ????

答:
Something like this should do the trick if you want to use xpath.js (you also need xmldom for parsing though).</p>

```<code>const Dom = require('xmldom').DOMParser;
const select = require('xpath.js');
const xml = '<ns2:OrderList> <order order_id="123" item_name="123"/> <order order_id="234" item_name="1233"/> <order order_id="2357" item_name="1234"/> </ns2:OrderList>¬';
const doc = new Dom().parseFromString(xml);
const nodes = select(doc, '//order');

const orderIds = nodes.map((node) => node.getAttribute('order_id'));
console.log(orderIds);
</code>```

Body:
My XML looks like this:

<ns2:OrderList>
  <order order_id="123" item_name="123"/>
  <order order_id="234" item_name="1233"/>
  <order order_id="2357" item_name="1234"/>
  ......
</ns2:OrderList>

I am wanting to use the XPath.js from npjms.

How can I get array with "order_id" values ????

Body:
Something like this should do the trick if you want to use xpath.js (you also need xmldom for parsing though).

const Dom = require('xmldom').DOMParser;
const select = require('xpath.js');
const xml = '<ns2:OrderList> <order order_id="123" item_name="123"/> <order order_id="234" item_name="1233"/> <order order_id="2357" item_name="1234"/> </ns2:OrderList>¬';
const doc = new Dom().parseFromString(xml);
const nodes = select(doc, '//order');

const orderIds = nodes.map((node) => node.getAttribute('order_id'));
console.log(orderIds);


问:
Getting duplicate rows when querying Cloud SQL in AppMaker
I migrated from Drive tables to a 2nd gen MySQL Google Cloud SQL data model.  I was able to insert 19 rows into the following Question table in AppMaker:

```<code>+-------------------+--------------+------+-----+---------+-------+
| Field             | Type         | Null | Key | Default | Extra |
+-------------------+--------------+------+-----+---------+-------+
| SurveyType        | varchar(64)  | NO   | PRI | NULL    |       |
| QuestionNumber    | int(11)      | NO   | PRI | NULL    |       |
| QuestionType      | varchar(64)  | NO   |     | NULL    |       |
| Question          | varchar(512) | NO   |     | NULL    |       |
| SecondaryQuestion | varchar(512) | YES  |     | NULL    |       |
+-------------------+--------------+------+-----+---------+-------+
</code>```

I queried the data from the command line and know it is good.  However, when I query the data in AppMaker like this:

```<code>var newQuery = app.models.Question.newQuery();
newQuery.filters.SurveyType._equals = surveyType;
newQuery.sorting.QuestionNumber._ascending();
var allRecs = newQuery.run();
</code>```

I get 19 rows with the same data (the first row) instead of the 19 different rows.  Any idea what is wrong?  Additionally (and possibly related) my list rows in AppMaker are not showing any data.  I did notice that _key is not being set correctly in the records.

(Edit: I thought maybe having two columns as the primary key was the problem, but I tried having the PK be a single identity column, same result.)

Thanks for any tips or pointers.

答: I was able to get this to work by creating the table inside AppMaker rather than using a table created directly in the Cloud Shell.  Not sure if existing tables are not supported or if there is a bug in AppMaker, but since it is working I am closing this.</p>

Body:
I migrated from Drive tables to a 2nd gen MySQL Google Cloud SQL data model.  I was able to insert 19 rows into the following Question table in AppMaker:

+-------------------+--------------+------+-----+---------+-------+
| Field             | Type         | Null | Key | Default | Extra |
+-------------------+--------------+------+-----+---------+-------+
| SurveyType        | varchar(64)  | NO   | PRI | NULL    |       |
| QuestionNumber    | int(11)      | NO   | PRI | NULL    |       |
| QuestionType      | varchar(64)  | NO   |     | NULL    |       |
| Question          | varchar(512) | NO   |     | NULL    |       |
| SecondaryQuestion | varchar(512) | YES  |     | NULL    |       |
+-------------------+--------------+------+-----+---------+-------+

I queried the data from the command line and know it is good.  However, when I query the data in AppMaker like this:

var newQuery = app.models.Question.newQuery();
newQuery.filters.SurveyType._equals = surveyType;
newQuery.sorting.QuestionNumber._ascending();
var allRecs = newQuery.run();

I get 19 rows with the same data (the first row) instead of the 19 different rows.  Any idea what is wrong?  Additionally (and possibly related) my list rows in AppMaker are not showing any data.  I did notice that _key is not being set correctly in the records.

(Edit: I thought maybe having two columns as the primary key was the problem, but I tried having the PK be a single identity column, same result.)

Thanks for any tips or pointers.


问:
Should I await a 'async Task' function if I don't care its return value?
Do I need to await a async Task function if it doesn't return anything? Will that cause the following code be wrapped in a delegate and executed after the async Task function returns?

```<code>Task DoSomethingAsync()
{
    return Task.Run(() =>
    {
        // Do something, but doesn't return values.
    });
}

void Test()
{
    DoSomethingAsync();  // should I await?

    // Do other things, totally not related to the async function
    Console.WriteLine("aaa");
}
</code>```

In above example, if I await DoSomethingAsync() in Test(), will that cause the following code Console.WriteLine be wrapped in delegate and defer executed only when the async task is done?

答:
If you don't and your program exits before the task completes, you're screwed. You at least would want to await all/any of those tasks before allowing to exit. You should also consider any implications of multiple instances of those tasks running at the same time if you don't know when the unawaited one will finish. Exceptions also can't be relied on to bubble up to the caller.

A better way might be to always await at the top level caller only await at the latest possible moment when you really need to (like if the app is about to exit)

To your question about Console.WriteLine - yes it will only print after completion IF you await the previous line. If you don't await, it will race with the code executing in the task.

Body:
Do I need to await a async Task function if it doesn't return anything? Will that cause the following code be wrapped in a delegate and executed after the async Task function returns?

Task DoSomethingAsync()
{
    return Task.Run(() =>
    {
        // Do something, but doesn't return values.
    });
}

void Test()
{
    DoSomethingAsync();  // should I await?

    // Do other things, totally not related to the async function
    Console.WriteLine("aaa");
}

In above example, if I await DoSomethingAsync() in Test(), will that cause the following code Console.WriteLine be wrapped in delegate and defer executed only when the async task is done?


问:
Getting "object references an unsaved transient instance" on already saved object
I have a Report object that has a 'reporter' property.  This 'reporter' is a reference to a Person's ssn that already exists.  When I try and save the Report object I am getting "object references an unsaved transient instance" on the reporter property, however this person is already in the Persons table.

```<code>@Entity
@Table(name="REPORTS")
public class Report {
    @Id
    private long id;

    @OneToOne
    @JoinColumn(name="reporter",
         referenceColumnName="ssn") // <-- Joining to a non-primary key property
    private Person reporter;
    // mutators
}

@Entity
@Table(name="PERSONS")
public class Person {
    @Id
    private long id;
    @Column(name="ssn")
    private long ssn;
    // other properties

    // mutators
}
</code>```

Here's where I am seeing the Exception being thrown:

```<code>public ReportTask implements Runnable {
   @Autowire
   private String reportName;
   @Autowire
   private ReportRepository reportRepo;
   @Autowire
   private PersonRepository personRepo;

   public void run(){
      Person p = personRepo.getByName(reportName);  // gets Person Entity by Name
      Report r = new Report();
      r.setName("Report for "+reportName);
      r.setReporter(p);

      reportRepo.save(r);  // <-- Exception is thrown here
   }
}
</code>```

The Exception states that the Person Object is transient and needs to be saved before saving the Report Object.

Also, to make matters more interesting, it seems the first 89 records insert perfectly fine;  It only fails on the 90th.  I've checked all the values and there is no difference between record 89 and 90...

答:
If anyone runs into the same issue, I wanted to post what my issue was.  It might help you out as well.

My issue was a null field value. It was omitted in my original question because it was for auditing purposes and doesn't play a role in the Objects functionality, however it seems as though if Hibernate sees a null value, it treats the Object as a new instance and tries to persist it (or at least it was in my case)

Body:
I have a Report object that has a 'reporter' property.  This 'reporter' is a reference to a Person's ssn that already exists.  When I try and save the Report object I am getting "object references an unsaved transient instance" on the reporter property, however this person is already in the Persons table.

@Entity
@Table(name="REPORTS")
public class Report {
    @Id
    private long id;

    @OneToOne
    @JoinColumn(name="reporter",
         referenceColumnName="ssn") // <-- Joining to a non-primary key property
    private Person reporter;
    // mutators
}

@Entity
@Table(name="PERSONS")
public class Person {
    @Id
    private long id;
    @Column(name="ssn")
    private long ssn;
    // other properties

    // mutators
}

Here's where I am seeing the Exception being thrown:

public ReportTask implements Runnable {
   @Autowire
   private String reportName;
   @Autowire
   private ReportRepository reportRepo;
   @Autowire
   private PersonRepository personRepo;

   public void run(){
      Person p = personRepo.getByName(reportName);  // gets Person Entity by Name
      Report r = new Report();
      r.setName("Report for "+reportName);
      r.setReporter(p);

      reportRepo.save(r);  // <-- Exception is thrown here
   }
}

The Exception states that the Person Object is transient and needs to be saved before saving the Report Object.

Also, to make matters more interesting, it seems the first 89 records insert perfectly fine;  It only fails on the 90th.  I've checked all the values and there is no difference between record 89 and 90...


问:
serilog.sinks.mssqlservercore causes a FileNotFoundException
I'm trying to use Serilog.Sinks.MSSqlServerCore (1.1.0) with Serilog.Settings.Configuration (2.2.0).

Serilog.Settings.Configuration works fine with sinks like File and Seq.

As soon as I add Serilog.Sinks.MSSqlServerCore to the project.json and tries to run the program again, I get an "Could not load file or assembly 'Serilog.Sinks.MSSqlServerCore, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified."

If I remove the "Configuration" nuget and add the mssqlcore sink in the code, then it works just fine.

Anybody know how to combine these two nuget??

答:
You need to upgrade Serilog.Settings.Configuration to 2.3 which is still in development. This is a known issue and bug which loads the wrong file name for Serilog.Sinks.MSSqlServerCore.

You can see details in GitHub.
https://github.com/serilog/serilog-settings-configuration/issues/39


问:
How to unquote header without unquote other data?
I have data that looks like the following:

```<code>Scenario,ScenName,Step,Date,GBP_fx,EUR_fx
0,"assets",0,"30/09/2016",1,0.865126741
</code>```

It's a huge file with 100k observations. I read it in R and trim it down to 10k and then write it to csv. However, I couldn't find how to unquote only the header without losing the quotes within the data. If I keep quote = TRUE, this is what the final data looks like but I want to get rid of the quotes in the header.

```<code>"Scenario","ScenName","Step","Date","GBP_fx","EUR_fx"
0,"assets",0,"30/09/2016",1,0.865126741
</code>```

Any suggestions?

答:
It looks the parameter quote itself will do it. use quote="" as in:

```<code>testDF <- read.csv(text=
'Scenario,ScenName,Step,Date,GBP_fx,EUR_fx
0,"assets",0,"30/09/2016",1,0.865126741', quote="")
</code>```

one gets:

```<code>> testDF
  Scenario ScenName Step         Date GBP_fx    EUR_fx
1        0 "assets"    0 "30/09/2016"      1 0.8651267
</code>```

Body:
I have data that looks like the following:

Scenario,ScenName,Step,Date,GBP_fx,EUR_fx
0,"assets",0,"30/09/2016",1,0.865126741

It's a huge file with 100k observations. I read it in R and trim it down to 10k and then write it to csv. However, I couldn't find how to unquote only the header without losing the quotes within the data. If I keep quote = TRUE, this is what the final data looks like but I want to get rid of the quotes in the header.

"Scenario","ScenName","Step","Date","GBP_fx","EUR_fx"
0,"assets",0,"30/09/2016",1,0.865126741

Any suggestions?

Body:
It looks the parameter quote itself will do it. use quote="" as in:

testDF <- read.csv(text=
'Scenario,ScenName,Step,Date,GBP_fx,EUR_fx
0,"assets",0,"30/09/2016",1,0.865126741', quote="")

one gets:

> testDF
  Scenario ScenName Step         Date GBP_fx    EUR_fx
1        0 "assets"    0 "30/09/2016"      1 0.8651267


问:
Java repeat part of a program with if and boolean operators
Hello I'm fairly new to java and I had troubles in a little test game.
So this is just a part of the code, I want that the user can repeat the part as often as he like with an while operater.

The code is here:

```<code>else if (a == 6){
        boolean InGame = true;
        while ( InGame );

        System.out.println("Glückspiel: Wer näher an der zufälligen Zahl ist gewinnt! 1-100");
        System.out.println("Spieler Eins");
        double playerOne = scan.nextDouble();
        System.out.println("Spieler Zwei");
        double playerTwo = scan.nextDouble();

        double randomValue = Math.random() * 100.0;

        // Math.abs
        double spacingOne = Math.abs(playerOne - randomValue);
        double spacingTwo = Math.abs(playerTwo - randomValue);
        System.out.println("Die Random Zahl war " + randomValue);

        if (spacingOne < spacingTwo) {
            System.out.println("Spieler Eins hat gewonnen!");
        }

        if (spacingOne > spacingTwo) {
            System.out.println("Spieler Zwei hat gewonnen!");
        }

        if (spacingOne == spacingTwo) {
            System.out.println("Unentschieden!");
        }
        System.out.println("Wenn du nochmal spielen willst schreibe 'ja' wenn nicht 'nein'");
        String PlayAgain = scan.nextLine();
        if  (PlayAgain == "nein");
        boolean inGame = false;
</code>```

Well I have never worked alot with booleans due to me being new in java.
Would nice if you could help me out.

答:
i have just modified your code and it's working perfectly  </p>

```<code>boolean InGame = true;
        while ( InGame ) { // begin of while loop

            System.out.println("Glückspiel: Wer näher an der zufälligen Zahl ist gewinnt! 1-100");
            System.out.println("Spieler Eins");
            double playerOne = scan.nextDouble();
            System.out.println("Spieler Zwei");
            double playerTwo = scan.nextDouble();

            double randomValue = Math.random() * 100.0;

            // Math.abs
            double spacingOne = Math.abs(playerOne - randomValue);
            double spacingTwo = Math.abs(playerTwo - randomValue);
            System.out.println("Die Random Zahl war " + randomValue);

            if(spacingOne < spacingTwo) {
                System.out.println("Spieler Eins hat gewonnen!");
            }

            else if(spacingOne > spacingTwo) { // use else if condition
                System.out.println("Spieler Zwei hat gewonnen!");
            }

            else {
                System.out.println("Unentschieden!");
            }

            System.out.println("Wenn du nochmal spielen willst schreibe 'ja' wenn nicht 'nein'");
            String PlayAgain = scan.next();
            if (PlayAgain.equals("nein")) { // use equal() method
                InGame = false;
            }

        } // end of while loop
</code>```

Body:
Hello I'm fairly new to java and I had troubles in a little test game.
So this is just a part of the code, I want that the user can repeat the part as often as he like with an while operater.

The code is here:

else if (a == 6){
        boolean InGame = true;
        while ( InGame );

        System.out.println("Glückspiel: Wer näher an der zufälligen Zahl ist gewinnt! 1-100");
        System.out.println("Spieler Eins");
        double playerOne = scan.nextDouble();
        System.out.println("Spieler Zwei");
        double playerTwo = scan.nextDouble();

        double randomValue = Math.random() * 100.0;

        // Math.abs
        double spacingOne = Math.abs(playerOne - randomValue);
        double spacingTwo = Math.abs(playerTwo - randomValue);
        System.out.println("Die Random Zahl war " + randomValue);

        if (spacingOne < spacingTwo) {
            System.out.println("Spieler Eins hat gewonnen!");
        }

        if (spacingOne > spacingTwo) {
            System.out.println("Spieler Zwei hat gewonnen!");
        }

        if (spacingOne == spacingTwo) {
            System.out.println("Unentschieden!");
        }
        System.out.println("Wenn du nochmal spielen willst schreibe 'ja' wenn nicht 'nein'");
        String PlayAgain = scan.nextLine();
        if  (PlayAgain == "nein");
        boolean inGame = false;

Well I have never worked alot with booleans due to me being new in java.
Would nice if you could help me out.

Body:
i have just modified your code and it's working perfectly

boolean InGame = true;
        while ( InGame ) { // begin of while loop

            System.out.println("Glückspiel: Wer näher an der zufälligen Zahl ist gewinnt! 1-100");
            System.out.println("Spieler Eins");
            double playerOne = scan.nextDouble();
            System.out.println("Spieler Zwei");
            double playerTwo = scan.nextDouble();

            double randomValue = Math.random() * 100.0;

            // Math.abs
            double spacingOne = Math.abs(playerOne - randomValue);
            double spacingTwo = Math.abs(playerTwo - randomValue);
            System.out.println("Die Random Zahl war " + randomValue);

            if(spacingOne < spacingTwo) {
                System.out.println("Spieler Eins hat gewonnen!");
            }

            else if(spacingOne > spacingTwo) { // use else if condition
                System.out.println("Spieler Zwei hat gewonnen!");
            }

            else {
                System.out.println("Unentschieden!");
            }

            System.out.println("Wenn du nochmal spielen willst schreibe 'ja' wenn nicht 'nein'");
            String PlayAgain = scan.next();
            if (PlayAgain.equals("nein")) { // use equal() method
                InGame = false;
            }

        } // end of while loop


问:
Reading integers from txt file in C
I`m making a file reader that reads integers numbers line by line from a file. The problem is that is not working. I think I am using fscanf in a wrong way. Can someone help me?

I had already look for answers in others questions but I can`t find anything that explain why I my code is not working.

```<code>int read_from_txt(){
    FILE *file;
    file = fopen("random_numbers.txt", "r");
    //Counting line numbers to allocate exact memory
    int i;
    unsigned int lines = 0;
    unsigned int *num;
    char ch;
    while(!feof(file)){
        ch = fgetc(file);
        if (ch == '\n'){
            lines++;
        }
    }
    //array size will be lines+1
    num = malloc(sizeof(int)*(lines+1));
    //storing random_numbers in num vector
    for(i=0;i<=lines;i++){
        fscanf(file, "%d", &num[i]);
        printf("%d", num[i]);
    }
    fclose(file);
}
</code>```

The txt file is like:

```<code>12
15
32
68
46
...
</code>```

But the output of this code keeps giving "0000000000000000000..."

答:
You forgot to "rewind" the file:

```<code>fseek(file, 0, SEEK_SET);
</code>```

Your process of reading goes through the file twice - once to count lines, and once more to read the data. You need to go back to the beginning of the file before the second pass.

Note that you can do this in a single pass by using realloc as you go: read numbers in a loop into a temporary int, and for each successful read expand the num array by one by calling realloc. This will expand the buffer as needed, and you would not need to rewind.

Be careful to check the results of realloc before re-assigning to num to avoid memory leaks.

Title: Reading integers from txt file in C

Body:
I`m making a file reader that reads integers numbers line by line from a file. The problem is that is not working. I think I am using fscanf in a wrong way. Can someone help me?

I had already look for answers in others questions but I can`t find anything that explain why I my code is not working.

int read_from_txt(){
    FILE *file;
    file = fopen("random_numbers.txt", "r");
    //Counting line numbers to allocate exact memory
    int i;
    unsigned int lines = 0;
    unsigned int *num;
    char ch;
    while(!feof(file)){
        ch = fgetc(file);
        if (ch == '\n'){
            lines++;
        }
    }
    //array size will be lines+1
    num = malloc(sizeof(int)*(lines+1));
    //storing random_numbers in num vector
    for(i=0;i<=lines;i++){
        fscanf(file, "%d", &num[i]);
        printf("%d", num[i]);
    }
    fclose(file);
}

The txt file is like:

12
15
32
68
46
...

But the output of this code keeps giving "0000000000000000000..."

Body:
You forgot to "rewind" the file:

fseek(file, 0, SEEK_SET);

Your process of reading goes through the file twice - once to count lines, and once more to read the data. You need to go back to the beginning of the file before the second pass.

Note that you can do this in a single pass by using realloc as you go: read numbers in a loop into a temporary int, and for each successful read expand the num array by one by calling realloc. This will expand the buffer as needed, and you would not need to rewind.

Be careful to check the results of realloc before re-assigning to num to avoid memory leaks.


问:
GMap.NET explicit load cache?
How do I explicitly load the Data.gmdb cache file in GMap.NET? I tried copying over the file created on my machine to another machine and run the application in offline mode but the cache file (generated in PC1-Online) does not work for PC2-Offline. Is there a way to explicitly load the file?</p>

答:
I think you could try to load your your-cache-file.gmdb into your application in this way:

In you MainForm_Load listener do the following:

```<code> string pathToExecutable = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
 GMaps.Instance.ImportFromGMDB(pathToExecutable + "\your-cache-file.gmdb"); //or just whatever path to your cache
</code>```

Or in this way:

```<code>YourGMapControl.CacheLocation = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
</code>```

The last one creates TileDBv5/en/Data.gmdb in your executable directory folder, where cache to be replaced is located.

But! Don't forget about main things:

Gmap will make cache data in MainMap.Manager.Mode = AccessMode.ServerAndCache; mode only. In CacheOnly it will use allready created cache, in ServerOnly it will load all the data from server without caching it locally.

In order to force caching process use TilePrefetcher. Example here.

Title: GMap.NET explicit load cache?

Body:
I think you could try to load your your-cache-file.gmdb into your application in this way:

In you MainForm_Load listener do the following:

 string pathToExecutable = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
 GMaps.Instance.ImportFromGMDB(pathToExecutable + "\your-cache-file.gmdb"); //or just whatever path to your cache

Or in this way:

YourGMapControl.CacheLocation = System.IO.Path.GetDirectoryName(Application.ExecutablePath);

The last one creates TileDBv5/en/Data.gmdb in your executable directory folder, where cache to be replaced is located.

But! Don't forget about main things:

Gmap will make cache data in MainMap.Manager.Mode = AccessMode.ServerAndCache; mode only. In CacheOnly it will use allready created cache, in ServerOnly it will load all the data from server without caching it locally.

In order to force caching process use TilePrefetcher. Example here.


问:
Running Super when frame is shown - Python Tkinter
I have this frame that is displayed however, I want the last line to run only when this frame is actually shown (and not when the program runs). Things are happening in the function start which I only want happening when this frame is shown

```<code>class FrameTwo(reviseTen):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        self.instructions = tk.Label(self, text="Click on the option you think is correct, then click 'Proceed to next question'")
        self.startButton = tk.Button(self, text="Click here to start revision session")
        self.optionOne = tk.Button(self, text="Option One", command=super(FrameTwo, self).clickOptionOne)
        self.optionTwo = tk.Button(self, text="Option Two", command=super(FrameTwo, self).clickOptionTwo)
        self.optionThree = tk.Button(self, text="Option Three", command=super(FrameTwo, self).clickOptionThree)
        self.optionFour = tk.Button(self, text="Option Four", command=super(FrameTwo, self).clickOptionFour)
        self.question = tk.Label(self, text="What is the definition of: ")
        self.proceedButton = tk.Button(self, text="Proceed to next question", command=lambda: controller.show_frame(FrameThree))
############# EDIT ####################
        self.bind("<<Show>>", self.do_something)

def do_something(self, event):
    self.start()
</code>```

EDIT Here is my show_frame method:

```<code>def show_frame(self, cont): # Method to show the current frame being used
    for frame in self.frames.values():
        frame.grid_remove()
    frame = self.frames[cont]
    frame.tkraise()
    frame.update()
    frame.grid()
    frame.event_generate("<<Show>>")
</code>```

答:
The main problem is that you are using code you don't understand. You should probably start with a simpler architecture until you are able to understand how it works.

That being said, there are several simple solutions. For example, you can modify the show_frame method to either directly call a method in each page, or it can send an event which you can bind a function to.

For example:

```<code>class SampleApp(tk.Tk):
    ...
    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()
        frame.event_generate("<<Show>>")

class FrameTwo(reviseTen):
    def __init__(self, parent, controller):
        ...
        self.bind("<<Show>>", self.do_something)

    def do_something(self, event):
        self.start()
</code>```

Note: since FrameTwo inherits from reviseTen, you shouldn't call Super(FrameTwo, self).start(), you can just call self.start().

Body:
I have this frame that is displayed however, I want the last line to run only when this frame is actually shown (and not when the program runs). Things are happening in the function start which I only want happening when this frame is shown

class FrameTwo(reviseTen):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        self.instructions = tk.Label(self, text="Click on the option you think is correct, then click 'Proceed to next question'")
        self.startButton = tk.Button(self, text="Click here to start revision session")
        self.optionOne = tk.Button(self, text="Option One", command=super(FrameTwo, self).clickOptionOne)
        self.optionTwo = tk.Button(self, text="Option Two", command=super(FrameTwo, self).clickOptionTwo)
        self.optionThree = tk.Button(self, text="Option Three", command=super(FrameTwo, self).clickOptionThree)
        self.optionFour = tk.Button(self, text="Option Four", command=super(FrameTwo, self).clickOptionFour)
        self.question = tk.Label(self, text="What is the definition of: ")
        self.proceedButton = tk.Button(self, text="Proceed to next question", command=lambda: controller.show_frame(FrameThree))
############# EDIT ####################
        self.bind("<<Show>>", self.do_something)

def do_something(self, event):
    self.start()

EDIT Here is my show_frame method:

def show_frame(self, cont): # Method to show the current frame being used
    for frame in self.frames.values():
        frame.grid_remove()
    frame = self.frames[cont]
    frame.tkraise()
    frame.update()
    frame.grid()
    frame.event_generate("<<Show>>")

Body:
The main problem is that you are using code you don't understand. You should probably start with a simpler architecture until you are able to understand how it works.

That being said, there are several simple solutions. For example, you can modify the show_frame method to either directly call a method in each page, or it can send an event which you can bind a function to.

For example:

class SampleApp(tk.Tk):
    ...
    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()
        frame.event_generate("<<Show>>")

class FrameTwo(reviseTen):
    def __init__(self, parent, controller):
        ...
        self.bind("<<Show>>", self.do_something)

    def do_something(self, event):
        self.start()

Note: since FrameTwo inherits from reviseTen, you shouldn't call Super(FrameTwo, self).start(), you can just call self.start().


问:
Powerpoint VBA dont close Excel
My VBA code in Powerpoint wont "kill" my excel application.
it still runs if i have a look in task manager.

I would like to close it the right way rather than kill.

Anyone that could help me? I already searched and tried to get it working but with no luck.

```<code>Public Sub OnSlideShowPageChange(ByVal Wn As SlideShowWindow)
If Wn.View.CurrentShowPosition = 2 Then

    Dim xlApp As Object
    Dim xlWorkBook As Object

    Set xlApp = CreateObject("Excel.Application")
    xlApp.Visible = False
    Set xlWorkBook = xlApp.Workbooks.Open("D:\ELE_powerpoint\book1.xlsx", True, False)

    With xlWorkBook.ActiveSheet
    txt1 = xlWorkBook.sheets(1).Range("A2")
    txt2 = xlWorkBook.sheets(1).Range("A3")
    txt3 = xlWorkBook.sheets(1).Range("A4")
    End With

    ActivePresentation.Slides(2).Shapes("a2").TextFrame.TextRange = txt1
    ActivePresentation.Slides(2).Shapes("a3").TextFrame.TextRange = txt2
    ActivePresentation.Slides(2).Shapes("a4").TextFrame.TextRange = txt3

    Set xlApp = Nothing
    Set xlWorkBook = Nothing

End If
End Sub
</code>```

答:
```<code>Set xlApp = Nothing
</code>```

That instruction sets the xlApp object reference to Nothing. It doesn't destroy the object it's referring to, but it prevents further code from using that reference.

Excel is a rather complex application; creating an instance of an Excel.Application object has many implications, and in order to properly shut itself down, it needs to run through a certain sequence of instructions (unload Excel and COM add-ins, close any opened file, tear down the VBE if it was initialized - which in turn may need to tear down its own add-ins, etc.) - by setting your reference to Nothing, you say "I don't need it anymore" - but what of the COM add-ins that still use it? That workbook that's still open is a Workbook object with an Application property that also references the very same object you were referring to - and these references aren't gone yet!

As Tim and Tom said, you need to call the Quit method of the Excel.Application instance, so that it can clean itself up.

And if that's the last thing your code does, then you probably don't even need to Set xlApp = Nothing, since the VBA runtime will know that it doesn't need to hold on to the xlApp reference after it's out of scope; Set xlWorkbook = Nothing is superfluous as well.

Quitting Excel will close the unmodified workbook you've opened, but since you opened it, I'd argue that it's good form to close it yourself - just call xlWorkbook.Close before you call xlApp.Quit.

Title: Powerpoint VBA dont close Excel

Body:
My VBA code in Powerpoint wont "kill" my excel application.
it still runs if i have a look in task manager.

I would like to close it the right way rather than kill.

Anyone that could help me? I already searched and tried to get it working but with no luck.

Public Sub OnSlideShowPageChange(ByVal Wn As SlideShowWindow)
If Wn.View.CurrentShowPosition = 2 Then

    Dim xlApp As Object
    Dim xlWorkBook As Object

    Set xlApp = CreateObject("Excel.Application")
    xlApp.Visible = False
    Set xlWorkBook = xlApp.Workbooks.Open("D:\ELE_powerpoint\book1.xlsx", True, False)

    With xlWorkBook.ActiveSheet
    txt1 = xlWorkBook.sheets(1).Range("A2")
    txt2 = xlWorkBook.sheets(1).Range("A3")
    txt3 = xlWorkBook.sheets(1).Range("A4")
    End With

    ActivePresentation.Slides(2).Shapes("a2").TextFrame.TextRange = txt1
    ActivePresentation.Slides(2).Shapes("a3").TextFrame.TextRange = txt2
    ActivePresentation.Slides(2).Shapes("a4").TextFrame.TextRange = txt3

    Set xlApp = Nothing
    Set xlWorkBook = Nothing

End If
End Sub

Body:
Set xlApp = Nothing

That instruction sets the xlApp object reference to Nothing. It doesn't destroy the object it's referring to, but it prevents further code from using that reference.

Excel is a rather complex application; creating an instance of an Excel.Application object has many implications, and in order to properly shut itself down, it needs to run through a certain sequence of instructions (unload Excel and COM add-ins, close any opened file, tear down the VBE if it was initialized - which in turn may need to tear down its own add-ins, etc.) - by setting your reference to Nothing, you say "I don't need it anymore" - but what of the COM add-ins that still use it? That workbook that's still open is a Workbook object with an Application property that also references the very same object you were referring to - and these references aren't gone yet!

As Tim and Tom said, you need to call the Quit method of the Excel.Application instance, so that it can clean itself up.

And if that's the last thing your code does, then you probably don't even need to Set xlApp = Nothing, since the VBA runtime will know that it doesn't need to hold on to the xlApp reference after it's out of scope; Set xlWorkbook = Nothing is superfluous as well.

Quitting Excel will close the unmodified workbook you've opened, but since you opened it, I'd argue that it's good form to close it yourself - just call xlWorkbook.Close before you call xlApp.Quit.


问:
How to use viewWillAppear?
Hi I am currently teaching myself swift and I am reading The Big Nerd Ranch 6th edition. In chapter 5 it says for a challenge try and update the background color based on the time of day. It says I need to override viewWillAppear. However I am unable to find any documentation that shows how to play with this. I can only find documentation explaining the differences between this and viewDidLoad. Any links that can help me understand the concept here and maybe show me an example would be greatly appreciated!</p>

答:
```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    //Your Code Here...
}
</code>```

Title: How to use viewWillAppear?


问:
SQLBulkCopy does not work
This is my first attempt to use sqlbulkcopy class. When I run it, nothing happens, no errors whatsoever. Please help me.

Here is my code:-

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration.ConfigurationManager

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim connectionString As String = GetConnectionString()
    ' Open a connection
    Using sourceConnection As SqlConnection = New SqlConnection(connectionString)
        sourceConnection.Open()

        ' Perform an initial count on the destination table.
        Dim commandRowCount As New SqlCommand("SELECT COUNT(*) FROM dbo.BRANCH;", sourceConnection)
        Dim countStart As Long = System.Convert.ToInt32(commandRowCount.ExecuteScalar())
        Console.WriteLine("Starting row count = {0}", countStart)

        ' Get data from the source table as a SqlDataReader.
        Dim commandSourceData As SqlCommand = New SqlCommand("select * from BRANCH", sourceConnection)
        Dim reader As SqlDataReader = commandSourceData.ExecuteReader
        UpdateHQDB(reader)

    End Using
End Sub

Private Function GetConnectionString() As String
    Return "Data Source=127.0.0.1;Initial Catalog=SOURCEDB;User ID=sa;Password="
End Function

Private Function GetDestString() As String
    Return "Data Source=192.168.123.194;Initial Catalog=DESTINATIONDB;User ID=sa;Password="
End Function

Public Sub UpdateHQDB(ByVal reader)
    Dim DestConString As String = GetDestString()
    ' Open a connection
    Using DestinationConnection As SqlConnection = New SqlConnection(DestConString)
        DestinationConnection.Open()

        ' Perform an initial count on the destination table.
        Dim DestcommandRowCount As New SqlCommand("SELECT COUNT(*) FROM dbo.BRANCH;", DestinationConnection)
        Dim DestcountStart As Long = System.Convert.ToInt32(DestcommandRowCount.ExecuteScalar())
        Console.WriteLine("Starting row count at destination = {0}", DestcountStart)

        Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(DestinationConnection)
            bulkCopy.DestinationTableName = "dbo.BRANCH"

            Try
                ' Write from the source to the destination.
                bulkCopy.WriteToServer(reader)

            Catch ex As Exception
                Console.WriteLine(ex.Message)

            Finally
                ' Close the SqlDataReader. The SqlBulkCopy
                ' object is automatically closed at the end
                ' of the Using block.
                reader.Close()
            End Try
        End Using

        ' Perform a final count on the destination table
        ' to see how many rows were added.
        Dim countEnd As Long = _
            System.Convert.ToInt32(DestcommandRowCount.ExecuteScalar())
        Console.WriteLine("Ending row count = {0}", countEnd)
        Console.WriteLine("{0} rows were added.", countEnd - DestcountStart)

        Console.WriteLine("Press Enter to finish.")
        Console.ReadLine()
    End Using
End Sub
End Class
```

答:
i would say that use NotifyAfter and SqlRowsCopied event of SqlBulkCopy to troubleshoot

following code in c#

```<code>        sb.NotifyAfter = 1;
        sb.SqlRowsCopied += new SqlRowsCopiedEventHandler(sb_SqlRowsCopied);

    void sb_SqlRowsCopied(object sender, SqlRowsCopiedEventArgs e)
    {
       // See if this event fired
    }
</code>```

Title: SQLBulkCopy does not work

Body:
i would say that use NotifyAfter and SqlRowsCopied event of SqlBulkCopy to troubleshoot

following code in c#

        sb.NotifyAfter = 1;
        sb.SqlRowsCopied += new SqlRowsCopiedEventHandler(sb_SqlRowsCopied);

    void sb_SqlRowsCopied(object sender, SqlRowsCopiedEventArgs e)
    {
       // See if this event fired
    }


问:
How can I clear a specific filter without clearing all filters?
Background:

I am creating an app that stores record of trainings that employees in a company took in table. I want to filter the rows of the table based on training name and/or employee name. I was able to figure out this first part, and I was able to create a button that clears all the filters and reloads the entire table using the clearFilters() function.

Problem:

I want to create two buttons that clear the filter selections one ("All Trainings") for the training name and one ("All Employees") for the employee name. To be more clear, when I click on the "All Trainings" button, I want to clear the filters on the training name, but not on the Employee name. This will become useful once I have a table with multiple fields that I want to filter, and I want to navigate the table without having to reset all fields every time.

I tried searching the functions available on Google App Maker, but there was nothing that seemed to be able to solve my problem. Any suggestions?

答:
From the Reference about datasources:

https://developers.google.com/appmaker/models/datasources#query_datasources

Like field filters, assigning null to a relation filter property clears that restriction.

So, something like:

```<code>datasource.query.filters.Employee._contains = null;
datasource.load();
</code>```

should work for you.

Body:
From the Reference about datasources:

https://developers.google.com/appmaker/models/datasources#query_datasources

Like field filters, assigning null to a relation filter property clears that restriction.

So, something like:

datasource.query.filters.Employee._contains = null;
datasource.load();

should work for you.


问:
Get Duplicates in List and Edit Item
I need to get any items in a list that already exist and edit BOTH items to include a duplicate property.

I've attempted to get duplicates by doing:

```<code>var duplicates = LIST.Select((t, i) => new { Index = i, Text = t }).GroupBy(g => g.Text.PROPERTYTOSEARCGBY).Where(g => g.Count() > 1);
</code>```

However this returns me the property that is duplicated when however I need to get index of both of the records so that I can edit them using:

```<code>LIST[index1].FlaggedData = true;
LIST[index2].FlaggedData = true;
etc...
</code>```

How can I get the index of BOTH duplicate or multiple records?

答:
You already have the correct LINQ query to do what you want. Seems like your code to update the Duplicate flag is incorrect. You should use some code like below to update the Dupe flag

```<code>foreach (var group in duplicates) {
    foreach (var item in group) {
        LIST[item.Index].FlaggedData = true;
    }
}
</code>```

or some more concise code like

```<code>foreach (var item in duplicates.SelectMany(item => item))
    item.Text.FlaggedData = true;
</code>```

Title: Get Duplicates in List and Edit Item

Body:
I need to get any items in a list that already exist and edit BOTH items to include a duplicate property.

I've attempted to get duplicates by doing:

var duplicates = LIST.Select((t, i) => new { Index = i, Text = t }).GroupBy(g => g.Text.PROPERTYTOSEARCGBY).Where(g => g.Count() > 1);

However this returns me the property that is duplicated when however I need to get index of both of the records so that I can edit them using:

LIST[index1].FlaggedData = true;
LIST[index2].FlaggedData = true;
etc...

How can I get the index of BOTH duplicate or multiple records?

Body:
You already have the correct LINQ query to do what you want. Seems like your code to update the Duplicate flag is incorrect. You should use some code like below to update the Dupe flag

foreach (var group in duplicates) {
    foreach (var item in group) {
        LIST[item.Index].FlaggedData = true;
    }
}

or some more concise code like

foreach (var item in duplicates.SelectMany(item => item))
    item.Text.FlaggedData = true;


问:
dynamically change method name inside array in ruby
I have a user object which i access like this.. user.email, user.first_name

Now I want to loop through each and return a message based on the current key in loop somewhat like this.

```<code>[user.first_name, user.email, user.last_name].each do |key|
      puts "#{key} is required"
 end
</code>```

The above works but loops through values instead of fields. so will do this below but how to prepend user to keys and get values inside array?

```<code>[first_name, email, last_name].each do |key|
 #inside here I want to prepend the user to the keys so that I can access like user.key

 puts "#{user.key} is required"
end
</code>```

If this was a string we can concatenate but how to deal with this here as its a method call?

答:
With ActiveRecord you can access properties via the [] method:

```<code>[ :first_name, :email, :last_name ].each do |key|
  unless (user[key])
    puts "#{key} is required"
  end
end
</code>```

This generally a lot safer than the send approach because it's not calling arbitrary methods.

Body:
I have a user object which i access like this.. user.email, user.first_name

Now I want to loop through each and return a message based on the current key in loop somewhat like this.

[user.first_name, user.email, user.last_name].each do |key|
      puts "#{key} is required"
 end

The above works but loops through values instead of fields. so will do this below but how to prepend user to keys and get values inside array?

[first_name, email, last_name].each do |key|
 #inside here I want to prepend the user to the keys so that I can access like user.key

 puts "#{user.key} is required"
end

If this was a string we can concatenate but how to deal with this here as its a method call?

Body:
With ActiveRecord you can access properties via the [] method:

[ :first_name, :email, :last_name ].each do |key|
  unless (user[key])
    puts "#{key} is required"
  end
end

This generally a lot safer than the send approach because it's not calling arbitrary methods.