text:
Q: Cannot acquire data source. Can't Use JPA EntityManager (EclipseLink) with JBoss 5.1 I'm facing a lot of difficulties to put the JPA (EclipseLink) working in the JBoss Server. I normally use Tomcat and it's quite simple...

*

*I copied the mysql-ds.xml from /jboss-5.1.0.GA/docs/examples/jca to /jboss-5.1.0.GA/servers/default/deploy/ and then I configured it.

mysql-ds.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<datasources>
  <local-tx-datasource>
    <jndi-name>EDeliveryUnit</jndi-name>
    <connection-url>jdbc:mysql://localhost:3306/edelivery_db</connection-url>
    <driver-class>com.mysql.jdbc.Driver</driver-class>
    <user-name>root</user-name>
    <password>root</password>
    <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
    <check-valid-connection-sql>SELECT * FROM systemuser</check-valid-connection-sql>
    <metadata>
       <type-mapping>mySQL</type-mapping>
    </metadata>
  </local-tx-datasource>
</datasources>

*

*Then I configured the persistence.xml in my WebApplication.

persistence.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<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"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="edeliveryPU"
    transaction-type="RESOURCE_LOCAL">
    <jta-data-source>jdbc/EDeliveryUnit</jta-data-source>
    <non-jta-data-source>jdbc/EDeliveryUnit</non-jta-data-source>
    <class>pt.inov.spocs.board.server.model.entity.SystemUser</class>
    <class>pt.inov.spocs.board.server.model.entity.UserSession</class>
    <properties>
        <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/edelivery_db" />
        <property name="javax.persistence.jdbc.user" value="root" />
        <property name="javax.persistence.jdbc.password" value="root" />
        <property name="eclipselink.jdbc.batch-writing" value="JDBC" />
        <property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
    </properties>
</persistence-unit>

Finale I instantiate the EntityManager:
private EntityManagerFactory emf;
private EntityManager em;

public Controller() {
    System.out.println("Begin..");

    emf = Persistence.createEntityManagerFactory("edeliveryPU");
    em = emf.createEntityManager();

    user = em.find(SystemUser.class, new Long(1));
    System.out.println("Username: " + user.getUsername() + " | pass: "
            + user.getPassword());
}

When I deploy it I got these error in my jboss:
2012-07-20 13:22:15,762 INFO  [STDOUT] (http-127.0.0.1-8080-1) Begin..
2012-07-20 13:22:16,346 INFO  [STDOUT] (http-127.0.0.1-8080-1) [EL Config]: The access type for the persistent class [class pt.inov.spocs.board.server.model.entity.UserSession] is set to [FIELD].
2012-07-20 13:22:16,414 INFO  [STDOUT] (http-127.0.0.1-8080-1) [EL Config]: The target entity (reference) class for the many to one mapping element [field user] is being defaulted to: class pt.inov.spocs.board.server.model.entity.SystemUser.
2012-07-20 13:22:16,417 INFO  [STDOUT] (http-127.0.0.1-8080-1) [EL Config]: The access type for the persistent class [class pt.inov.spocs.board.server.model.entity.SystemUser] is set to [FIELD].
2012-07-20 13:22:16,419 INFO  [STDOUT] (http-127.0.0.1-8080-1) [EL Config]: The alias name for the entity class [class pt.inov.spocs.board.server.model.entity.UserSession] is being defaulted to: UserSession.
2012-07-20 13:22:16,424 INFO  [STDOUT] (http-127.0.0.1-8080-1) [EL Config]: The table name for entity [class pt.inov.spocs.board.server.model.entity.UserSession] is being defaulted to: USERSESSION.
2012-07-20 13:22:16,468 INFO  [STDOUT] (http-127.0.0.1-8080-1) [EL Config]: The column name for element [sessionKey] is being defaulted to: SESSIONKEY.
2012-07-20 13:22:16,470 INFO  [STDOUT] (http-127.0.0.1-8080-1) [EL Config]: The column name for element [endDate] is being defaulted to: ENDDATE.
2012-07-20 13:22:16,472 INFO  [STDOUT] (http-127.0.0.1-8080-1) [EL Config]: The column name for element [beginDate] is being defaulted to: BEGINDATE.
2012-07-20 13:22:16,472 INFO  [STDOUT] (http-127.0.0.1-8080-1) [EL Config]: The column name for element [ip] is being defaulted to: IP.
2012-07-20 13:22:16,474 INFO  [STDOUT] (http-127.0.0.1-8080-1) [EL Config]: The alias name for the entity class [class pt.inov.spocs.board.server.model.entity.SystemUser] is being defaulted to: SystemUser.
2012-07-20 13:22:16,475 INFO  [STDOUT] (http-127.0.0.1-8080-1) [EL Config]: The table name for entity [class pt.inov.spocs.board.server.model.entity.SystemUser] is being defaulted to: SYSTEMUSER.
2012-07-20 13:22:16,476 INFO  [STDOUT] (http-127.0.0.1-8080-1) [EL Config]: The column name for element [id] is being defaulted to: ID.
2012-07-20 13:22:16,477 INFO  [STDOUT] (http-127.0.0.1-8080-1) [EL Config]: The column name for element [username] is being defaulted to: USERNAME.
2012-07-20 13:22:16,477 INFO  [STDOUT] (http-127.0.0.1-8080-1) [EL Config]: The column name for element [password] is being defaulted to: PASSWORD.
2012-07-20 13:22:16,479 INFO  [STDOUT] (http-127.0.0.1-8080-1) [EL Config]: The pk column value for the table generator named [SystemUserGenerator] defined on [class pt.inov.spocs.board.server.model.entity.SystemUser] from [class pt.inov.spocs.board.server.model.entity.SystemUser] is being defaulted to: SystemUserGenerator.
2012-07-20 13:22:16,526 INFO  [STDOUT] (http-127.0.0.1-8080-1) [EL Config]: The primary key column name for the mapping element [field user] is being defaulted to: ID.
2012-07-20 13:22:16,526 INFO  [STDOUT] (http-127.0.0.1-8080-1) [EL Config]: The foreign key column name for the mapping element [user] is being defaulted to: USER_ID.
2012-07-20 13:22:16,696 INFO  [STDOUT] (http-127.0.0.1-8080-1) [EL Warning]: PersistenceUnitInfo edeliveryPU has transactionType RESOURCE_LOCAL and therefore jtaDataSource will be ignored
2012-07-20 13:22:16,700 INFO  [STDOUT] (http-127.0.0.1-8080-1) [EL Info]: EclipseLink, version: Eclipse Persistence Services - 2.3.2.v20111125-r10461
2012-07-20 13:22:16,716 INFO  [STDOUT] (http-127.0.0.1-8080-1) [EL Severe]: Exception [EclipseLink-7060] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Cannot acquire data source [java:/EDeliveryUnit].
Internal Exception: javax.naming.InvalidNameException: Not a compound name: EDeliveryUnit
2012-07-20 13:22:16,717 SEVERE [org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage] (http-127.0.0.1-8080-1) Error Rendering View[/index.xhtml]
javax.el.ELException: /index.xhtml: Exception [EclipseLink-7060] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Cannot acquire data source [java:/EDeliveryUnit].
Internal Exception: javax.naming.InvalidNameException: Not a compound name: EDeliveryUnit
at org.apache.myfaces.view.facelets.compiler.TextInstruction.write(TextInstruction.java:57)
at org.apache.myfaces.view.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:46)
at org.apache.myfaces.view.facelets.compiler.UILeaf.encodeAll(UILeaf.java:214)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:614)
at org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage.renderView(FaceletViewDeclarationLanguage.java:1159)
at org.apache.myfaces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:263)
at org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:85)
at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:239)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:191)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:662)
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-7060] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Cannot acquire data source [java:/EDeliveryUnit].
Internal Exception: javax.naming.InvalidNameException: Not a compound name: EDeliveryUnit
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:517)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getDatabaseSession(EntityManagerFactoryDelegate.java:188)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.createEntityManagerImpl(EntityManagerFactoryDelegate.java:277)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:294)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:272)
at pt.inov.spocs.board.server.model.entity.Controller.<init>(Controller.java:19)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at java.lang.Class.newInstance0(Class.java:355)
at java.lang.Class.newInstance(Class.java:308)
at org.apache.myfaces.config.annotation.TomcatAnnotationLifecycleProvider.newInstance(TomcatAnnotationLifecycleProvider.java:49)
at org.apache.myfaces.config.ManagedBeanBuilder.buildManagedBean(ManagedBeanBuilder.java:162)
at org.apache.myfaces.el.unified.resolver.ManagedBeanResolver.createManagedBean(ManagedBeanResolver.java:303)
at org.apache.myfaces.el.unified.resolver.ManagedBeanResolver.getValue(ManagedBeanResolver.java:266)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:54)
at org.apache.myfaces.el.unified.resolver.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:142)
at org.apache.myfaces.el.VariableResolverImpl.resolveVariable(VariableResolverImpl.java:65)
at org.apache.myfaces.el.convert.VariableResolverToELResolver.getValue(VariableResolverToELResolver.java:96)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:54)
at org.apache.myfaces.el.unified.resolver.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:142)
at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:61)
at org.apache.el.parser.AstValue.getValue(AstValue.java:107)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:186)
at org.apache.myfaces.view.facelets.el.ELText$ELTextVariable.writeText(ELText.java:213)
at org.apache.myfaces.view.facelets.el.ELText$ELTextComposite.writeText(ELText.java:125)
at org.apache.myfaces.view.facelets.compiler.TextInstruction.write(TextInstruction.java:48)
... 28 more
Caused by: Exception [EclipseLink-7060] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Cannot acquire data source [java:/EDeliveryUnit].
Internal Exception: javax.naming.InvalidNameException: Not a compound name: EDeliveryUnit
at org.eclipse.persistence.exceptions.ValidationException.cannotAcquireDataSource(ValidationException.java:497)
at org.eclipse.persistence.sessions.JNDIConnector.connect(JNDIConnector.java:109)
at org.eclipse.persistence.sessions.DatasourceLogin.connectToDatasource(DatasourceLogin.java:162)
at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.loginAndDetectDatasource(DatabaseSessionImpl.java:584)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.login(EntityManagerFactoryProvider.java:206)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:488)
... 55 more
Caused by: javax.naming.InvalidNameException: Not a compound name: EDeliveryUnit
at javax.naming.CompoundName.addAll(CompoundName.java:445)
at org.jnp.interfaces.NamingContext.composeName(NamingContext.java:1077)
at org.jnp.interfaces.NamingContext.getAbsoluteName(NamingContext.java:1855)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:717)
at javax.naming.InitialContext.lookup(InitialContext.java:396)
at org.eclipse.persistence.sessions.JNDIConnector.connect(JNDIConnector.java:103)
... 59 more
2012-07-20 13:22:16,764 SEVERE [org.apache.myfaces.renderkit.ErrorPageWriter] (http-127.0.0.1-8080-1) An exception occurred
javax.faces.FacesException: javax.persistence.PersistenceException: Exception [EclipseLink-7060] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Cannot acquire data source [java:/EDeliveryUnit].
Internal Exception: javax.naming.InvalidNameException: Not a compound name: EDeliveryUnit
at org.apache.myfaces.shared_impl.context.ExceptionHandlerImpl.wrap(ExceptionHandlerImpl.java:241)
at org.apache.myfaces.shared_impl.context.ExceptionHandlerImpl.handle(ExceptionHandlerImpl.java:156)
at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:258)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:191)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:662)
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-7060] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Cannot acquire data source [java:/EDeliveryUnit].
Internal Exception: javax.naming.InvalidNameException: Not a compound name: EDeliveryUnit
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:517)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getDatabaseSession(EntityManagerFactoryDelegate.java:188)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.createEntityManagerImpl(EntityManagerFactoryDelegate.java:277)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:294)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:272)
at pt.inov.spocs.board.server.model.entity.Controller.<init>(Controller.java:19)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at java.lang.Class.newInstance0(Class.java:355)
at java.lang.Class.newInstance(Class.java:308)
at org.apache.myfaces.config.annotation.TomcatAnnotationLifecycleProvider.newInstance(TomcatAnnotationLifecycleProvider.java:49)
at org.apache.myfaces.config.ManagedBeanBuilder.buildManagedBean(ManagedBeanBuilder.java:162)
at org.apache.myfaces.el.unified.resolver.ManagedBeanResolver.createManagedBean(ManagedBeanResolver.java:303)
at org.apache.myfaces.el.unified.resolver.ManagedBeanResolver.getValue(ManagedBeanResolver.java:266)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:54)
at org.apache.myfaces.el.unified.resolver.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:142)
at org.apache.myfaces.el.VariableResolverImpl.resolveVariable(VariableResolverImpl.java:65)
at org.apache.myfaces.el.convert.VariableResolverToELResolver.getValue(VariableResolverToELResolver.java:96)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:54)
at org.apache.myfaces.el.unified.resolver.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:142)
at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:61)
at org.apache.el.parser.AstValue.getValue(AstValue.java:107)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:186)
at org.apache.myfaces.view.facelets.el.ELText$ELTextVariable.writeText(ELText.java:213)
at org.apache.myfaces.view.facelets.el.ELText$ELTextComposite.writeText(ELText.java:125)
at org.apache.myfaces.view.facelets.compiler.TextInstruction.write(TextInstruction.java:48)
at org.apache.myfaces.view.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:46)
at org.apache.myfaces.view.facelets.compiler.UILeaf.encodeAll(UILeaf.java:214)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:614)
at org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage.renderView(FaceletViewDeclarationLanguage.java:1159)
at org.apache.myfaces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:263)
at org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:85)
at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:239)
... 21 more
Caused by: Exception [EclipseLink-7060] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Cannot acquire data source [java:/EDeliveryUnit].
Internal Exception: javax.naming.InvalidNameException: Not a compound name: EDeliveryUnit
at org.eclipse.persistence.exceptions.ValidationException.cannotAcquireDataSource(ValidationException.java:497)
at org.eclipse.persistence.sessions.JNDIConnector.connect(JNDIConnector.java:109)
at org.eclipse.persistence.sessions.DatasourceLogin.connectToDatasource(DatasourceLogin.java:162)
at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.loginAndDetectDatasource(DatabaseSessionImpl.java:584)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.login(EntityManagerFactoryProvider.java:206)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:488)
... 55 more
   Caused by: javax.naming.InvalidNameException: Not a compound name: EDeliveryUnit
at javax.naming.CompoundName.addAll(CompoundName.java:445)
at org.jnp.interfaces.NamingContext.composeName(NamingContext.java:1077)
at org.jnp.interfaces.NamingContext.getAbsoluteName(NamingContext.java:1855)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:717)
at javax.naming.InitialContext.lookup(InitialContext.java:396)
at org.eclipse.persistence.sessions.JNDIConnector.connect(JNDIConnector.java:103)
... 59 more

I tried in many different ways but I can't put these working.
Anyone can help me please?

A: I found the solution.
JBoss force us to define a non-jta-data-source if we don't want to use transactions or a jta-data-source if you want to use it..
Either way no matter if we want to use transactions, the problem is that most of the information provided advise us to specify these with a jdbc/JNDI-NAME when what we want to use is a java:/JNDI-NAME.
In conclusion, if you want to use a EclipseLink JPA with JBoss instead of Data-Source you need to ensure that you are specifying the:

*

*transaction-type="RESOURCE_LOCAL"

*<non-jta-data-source>java:/JNDI-NAME</non-jta-data-source> or <jta-data-source>java:/JNDI-NAME</jta-data-source>
Here is the correction of my persistence.xml:
<persistence-unit name="persistenceSamplePU" transaction-type="RESOURCE_LOCAL">
     <non-jta-data-source>java:/EDeliveryUnit</non-jta-data-source>

     <!-- Entities must be specified for EclipseLink weaving -->
    <class>pt.inov.spocs.board.server.model.entity.SystemUser</class>
    <class>pt.inov.spocs.board.server.model.entity.UserSession</class>

    <properties>
        <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/edelivery_db" />
        <property name="javax.persistence.jdbc.user" value="root" />
        <property name="javax.persistence.jdbc.password" value="root" />
    </properties>
</persistence-unit>

Thank you for your precious help @Chris.

A: You are specifying "javax.persistence.jdbc.x" properties which do not mix with datasources.  You should specify the datasource to use, or the JDBC connection url etc but not both.  Are you trying to use JTA?  There is also a warning stating you are using transaction-type="resource-local" with a JTA datasource defined - you need to specify the "JTA" transaction type for the JTA datasource to be used, and the  will be needed so it can hook into the JBoss transaction manager.  Setting the target server might also be needed for the datasource lookup.

A: I know this might be old. I faced same issue with jdeveloper 12c and weblogic 12.x
I fixed this by omitting java: from datasource name at persistence.xml file as follows:
 from:
java:/app/jdbc/data_source
to:
/app/jdbc/data_source


text:
Q: "Dictionary update sequence element #0 has lenght" ошибка dictionary update sequence element #0 has length 12; 2 is required
Надо было получить текст из запроса requests.get("https://www.google.com/"), и из ссылок полученных при помощи regex отделить ссылки, и посчитать сколько раз встречается определенное слово в result. Возможно, я совершенно неправильно сделал задачу, и ошибка исходит отсюда, в любом случае прошу помощи в решении этого вопроса. Код:
import requests, re

response = requests.get("https://www.google.com/")

result = re.findall(r'/[A-Za-z\.]+/', response.text)
print(result)

def count_words(List):
    counter = 0
    for word in range(len(List)):
        if List.has_key(word):
            counter += 1
        else:
            counter = 0
    print(f"word {word} matches {counter}")

count_words(dict(result))

A: Подсчет можно сделать проще через Counter.
Попробуйте:
import re
from collections import Counter

import requests

def count_words(words):
    for word, counter in Counter(words).items():
        print(f"word {word} matches {counter}")

response = requests.get("https://www.google.com/")
result = re.findall(r'/[A-Za-z.]+/', response.text)
count_words(result)

PS.
В квадратных скобках регулярки не нужно экранировать метасимволы. Поэтому у меня точка без \

A: import requests, re

response = requests.get("https://www.google.com/")

result = re.findall(r'/[A-Za-z\.]+/', response.text)

def count_words(List):
    Dict = {}
    for word in List:
        if word in Dict:
            Dict[word] += 1
        else:
            Dict[word] = 1

    for word, counter in Dict.items():
        print(f"word {word} matches {counter}")

count_words(result)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Access Violation in ArcObject Multi-threaded Application I think I have figured it out. The most probable cause of exception in Multithreaded application may be:
When both threads trying to open same featureclass it breaks: coz one of the thread is already in the process of opening it and other tries to do the same, So it gives error like:
"Memory could not be read or write from protected memory"
This is my guess, but what wonders me is that why there is no separation of concern, even if I am opening a different workspace in each thread. May be Arcobjects internally, looks for same address space for any object in database.
I have written few lines of code and tried to run it with different threads opening different object classes and this also breaks
but
whenver, I deligate few thread to open same featureclass it breaks with the above errors.
Also, not releasing memory is the other cause for such errors as well.
Any suggestions?
Adding some code for more clarification:
private void ReadFeatureClass(string featureclassname)
{
    IWorkspaceFactory workspaceFactory = new SdeWorkspaceFactory();

    IPropertySet connectionProperties = new PropertySet();
    connectionProperties.SetProperty("SERVER",settings.Server);
    connectionProperties.SetProperty("INSTANCE", Settings.Instance);
    connectionProperties.SetProperty("USER", settings.User);
    connectionProperties.SetProperty("PASSWORD", settings.Password);
    connectionProperties.SetProperty("VERSION", settings.Version);

    FeatureWorkspace featureWorkspace = workspaceFactory.Open(connectionProperties, 0) as IFeatureWorkspace;

    ITable featureClass = featureWorkspace.OpenTable(featureClassName);
}

Above code breaks with the said exception most of the time.
@AndOne, I am using oracle spatial direct connect. Also, I created a new feature class and ran the same code against it, this also fails when threads are increased. There are few differences which I could figure out between these two featureclasses:
Any suggestions?

A: It could potentially be the WorkspaceFactory object. That is a singleton object that may be causing problems for you.

A: When you create ArcObjects objects, they must be created on the main Thread of the Process that loaded the AO binary resource.
You can safely pass reference to the IApplication instance between threads, and cast that to IObjectFactory in order to safely create instances of AO objects.

A: ...For ArcObjects applications to run efficiently in a multithreaded environment, the apartment threading model used by ArcObjects, Threads in Isolation, must be considered. This model works by eliminating cross-thread communication. All ArcObjects references within a thread should only communicate with objects in the same thread...
...For this model to work, the singleton objects at ArcGIS 9.x were designed to be singletons per thread and not singletons per process. The resource overhead of hosting multiple singletons in a process is outweighed by the performance gain of stopping the cross-thread communication that would occur if the singleton were created in one thread, then accessed from the other threads...
Activator class to create singletons avoids problem: ... sometimes when you use the new keyword to instantiate a COM object, you are getting a reference to an object that exists. This happens when attempting to instantiate a singleton class that has previously been instantiated.
The .NET Framework is unable to wrap in a strongly typed RCW an instance of an object that has previously been wrapped in the generic System.__ComObject RCW ...

A: I have been in the same issue, but my environment came from versions 9.2, 9.3, and the application was migrated to version 10.
The solution that was to register the assembly using the REGASM.exe tool.
Registering the assembly, does not produce the error.

A: I had this error occasionally when accessing IFeature or IRow objects which had been created with a recycling cursor. Holding a reference to those objects is discouraged and leads to serious problems, even though it works in most cases.
What are your threads doing on that feature class? Are they just reading data or are they modifying it? In the latter case you will run into problems because of race conditions. Deleting a row within one thread while cycling over it in another thread will probably not work.
Have you checked if the reference to your FeatureWorkspace is valid? Perhaps the reference has been released accidentally? How do you create the reference to your workspace?
The correct (isolation mode) way to obtain a workspace object is to create a new WorkspaceFactory within each thread and then open a workspace with said factory. Although it also works if you pass the workspace reference to all threads but you buy that with some heavy marshalling/unmarshalling because of the inter-thread communication. Makes the code about 10-20% slower in my experience.
edit:
This code runs perfectly with ArcGIS 9.3.1. It creates 10 threads which access in parallel the same Workspace and open a feature class to read from it. Maybe you have some connection limits to your Sde-Workspace?
    private void Click()
    {
        List<Thread> list = new List<Thread>();
        for(int i=0; i<10; i++)
        {
            Thread t = new Thread(new ThreadStart(Run));
            t.SetApartmentState(ApartmentState.STA);
            t.Name = "worker" + i;
            t.Start();
            list.Add(t);
        }

        Thread.Sleep(5000); // Make sure all threads are set up
        foreach(Thread t in list) {
            t.Interrupt();
        }
    }

    private void Run()
    {
        IWorkspaceFactory fac = new AccessWorkspaceFactoryClass();
        IWorkspace ws = fac.OpenFromFile(@"g:\path\to\my.mdb", 0);
        IFeatureWorkspace fws = ws as IFeatureWorkspace;

        try {
            Thread.Sleep(Timeout.Infinite);
        } catch(ThreadInterruptedException) {}

        Trace.WriteLine("starting work: "+Thread.CurrentThread.Name);
        ITable table = fws.OpenTable("featureClassName");
        ICursor cursor = table.Search(null, true);
        IRow row = cursor.NextRow();
        while(row != null) {
            // do something time consuming
            row.Fields.FindField("AttrName");
            row = cursor.NextRow();
        }
        Trace.WriteLine("finished "+Thread.CurrentThread.Name);
        Marshal.ReleaseComObject(cursor);
    }

A: You probably have not marked the new threads as STA (Single Threaded Apartments).
I am sure you have read this document, so this isonly a reminder :)
If you are curious, the ArcObjects singletons have thread affinity (not process) and in their internal implementation will check for the threadid and keep a {threadid/singletoninstance} tuple in a global hash.


text:
Q: Get data from table with id from another table i have two Tables users_data and users_statistics
users_data:
id    money     position   uid
1     1000      20921      3
2     3000      8742       0
3     2000      23214      3

users_statistics:
id    lastname   lastlogin
1     Hans       13.05.2200
2     Uwe        10.03.1900
3     Herbert    13.42.2421

Now, i want to SELECT all lastname WHERE uid = 3
My try was
 SELECT `lastname` FROM users_statistics
 JOIN users_data USING (id)
 WHERE `uid` = 3

With this Query he returns me all 3 Rows, but why?
In the second row the uid is 0...
I hop someone can help, thanks in advance.

A: Sounds weird but now it works...
I only changed the uid to users_data.uid
SELECT `lastname` FROM users_statistics
JOIN users_data USING (id)
WHERE users_data.uid = 3

Now he only gives me the two rows with uid = 3
When someone can explain this, let me know it :D

A: your query works for me:
http://sqlfiddle.com/#!9/c5025/1
Also tested under local MySQL 5.5.38


text:
Q: Running a chainlink node on GCP, when connecting to the DB I get [ERROR] unable to lock ORM: dial tcp? I`m running a chainlink node on GCP ,I followed the chainlink docs https://docs.chain.link/docs/running-a-chainlink-node/, I created my VM and a DB , SSH tunneled through Google cloud SDK, but when trying to connect to my DB with cd ~/.chainlink-kovan && docker run -p 6688:6688 -v ~/.chainlink-kovan:/chainlink -it --env-file=.env smartcontract/chainlink:0.9.8 local n I get:

So I tried to use psql client to connect to the instance with psql -h [address IP]  -U [db_user], but got
Is the server running on host "35.100....16" and accepting
        TCP/IP connections on port 5432?

So after that, I tried to manually open the port 5432 in GCP but still nothing... If I run netstat -na I get this:

I also double-checked my .env if the DATABASE_URL is correct.
Managed to find some similar errors on Stack, but nothing has helped so far.

A: Fixed the issue with setting up a private IP connection instead of public one for my SQL database and changed my .env file.

A: I tried replicating the scenario using the Running a Chainlink Node
 and How to build a simple Chainlink node on the GCP  and I was able to start the Chainlink Node.
The issue is with the network path for connecting to the PostgreSQL DB instance; it is "Public IP" and without any "Authorized networks" by default when creating the DB. On using the Public IP address to connect the Chainlink node with the DB, I faced the same error.
This can be resolved by following either of the two methods:

*

*If the network path for connecting to the PostgreSQL DB instance is "Public IP", then add the VM's(Node) External IP to "Authorized networks" in PostgreSQL DB instance details. Configure access to your Cloud SQL instance for more information.

*Change the network path for connecting to the PostgreSQL DB instance to "Private IP" with "default" network and use the Private IP Address of the PostgreSQL DB instance when connecting the Node.


text:
Q: Can you have multiple HTML images from one php file? I recently learned that you can use a php file as a source for an img in HTML.
Example:
I'm trying to use this method to get multiple images from another folder on the server, and showing them to the user. However, I can't get this to work.
The JS code:
var container = document.getElementById("container");
container.innerHTML = "";
for (var i = 0; i < imgAmount; i++) {
  container.innerHTML += '';
}

image.php code:
session_start();
$path = '../images/*';
$images = glob($path);
if ($_SESSION["imgCurrent"] < $_SESSION["imgAmount"]) {
  header('Content-Type: image/jpeg');
  readfile($images[$_SESSION["imgCurrent"]]);
  $_SESSION["imgCurrent"] = $_SESSION["imgCurrent"]+1;
}

imgAmount from the JS code, and $_SESSION["imgCurrent"] $_SESSION["imgAmount"]from the image.php code are declared in another file, and they are working properly. For some reason all the images end up being the same picture. It's always the image that's in the position of the $images array equal to the value of $_SESSION["imgCurrent"] when it's first declared, so 0 by default. When changing the starting value to another number, the image changes too. At first glance it looks like the variable isn't changing, however returning the value of $_SESSION["imgCurrent"] back to the JS code and using console.log shows that the variable is increasing properly.
I also tested with window.open("URL/image.php"); instead of the img tag, and that worked properly aswell. All the pictures showed up correctly in seperate tabs.
This is probably a very bad way to do what I'm trying to do, so if anyone has a simpler method, I'm all ears. However, I have to use php, as the folder containing the images is not reachable by HTML.

A: Removing the session variables and using url parameters instead, made the code work correctly. All images are showing up.
Example:


text:
Q: MoveNext instead of actual method/task name Using log4net declared as:
private readonly ILog log =
       LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType());

In an async method or task, like this one:
public async void CheckSomething()
{
    log.Info(null);
    //....
}

logs MoveNext instead of CheckSomething.
Any idea how to make it log an actual method name?

A: With thanks to the answer from Jacek Gorgoń, here is the utility I came up. It has a couple of improvements but still has a long way to go to work nicely with anonymous or lambda methods.
static string GetMethodContextName() {
    var name = new StackTrace().GetFrame(1).GetMethod().GetMethodContextName();
}

static string GetMethodContextName(this MethodBase method) {
    if (method.DeclaringType.GetInterfaces().Any(i => i == typeof(IAsyncStateMachine))) {
        var generatedType = method.DeclaringType;
        var originalType = generatedType.DeclaringType;
        var foundMethod = originalType.GetMethods(Instance | Static | Public | NonPublic | DeclaredOnly)
            .Single(m => m.GetCustomAttribute<AsyncStateMachineAttribute>()?.StateMachineType == generatedType);
        return foundMethod.DeclaringType.Name + "." + foundMethod.Name;
    } else {
        return method.DeclaringType.Name + "." + method.Name;
    }
}

Here's an example usage:
class Program {
    static void Main(string[] args) {
        // outputs Program.Main
        Console.WriteLine(GetMethodContextName());
        Test().Wait();
    }
    static async Task Test() {
        // outputs Program.Test
        Console.WriteLine(GetMethodContextName());
        await Task.CompletedTask;
    }
}

A: I wrote a simple wrapper around log4net.
public class Logger
{
    private ILog _Log { get; set; }

    public Logger(Type declaringType)
    {
        _Log = LogManager.GetLogger(declaringType);
    }

    public void Error(Exception exception, [CallerMemberName] string callerMemberName = "")
    {
        _Log.Error(callerMemberName, exception);
    }
}

In the code that is doing the logging, just do:
private Logger Log = new Logger(MethodBase.GetCurrentMethod().DeclaringType);

Of course if you want to do things like Info, Debug, etc, you can just add it to the wrapper class.
NOTE
this utilizes the c# 5.0 [CallerMemberName]

A: Use this, works great...
public void Log(Microsoft.Extensions.Logging.LogLevel level, string message,
        [System.Runtime.CompilerServices.CallerMemberName] string memberName = "",
        [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
        [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
    {
//do your logging here....
    }

A: All async methods are rewritten into a state machine to satisfy potential await values within the method.  The final method in which the code lives is the MoveNext method which is what log4net is reporting.
There is really no good way at runtime to transition from MoveNext to the actual method in which the code was originally written.  They are somewhat disconnected at a metadata level.  You may just have to resort to logging the name directly

A: With an extension method that just returns the caller member name for a MethodBase.
public static class MemberBaseExtension
{
    public static string GetDeclaringName(this MethodBase methodBase, [CallerMemberName] string memberName = "")
    {
        return memberName;
    }
}

A: Short: given the MoveNext() method, try this:
private static MethodBase GetRealMethodFromAsyncMethod(MethodBase asyncMethod)
{
    var generatedType = asyncMethod.DeclaringType;
    var originalType = generatedType.DeclaringType;
    var matchingMethods =
        from methodInfo in originalType.GetMethods()
        let attr = methodInfo.GetCustomAttribute<AsyncStateMachineAttribute>()
        where attr != null && attr.StateMachineType == generatedType
        select methodInfo;

    // If this throws, the async method scanning failed.
    var foundMethod = matchingMethods.Single();
    return foundMethod;
}

Long (Disclaimer)
Don't use this in production. It relies on compiler behavior, which may likely change in a future version without notice. The following assumptions about compiler are made:

*

*The actual running async method is generated inside a generated type.

*The generated type is a nested type of the original type containing the original, hand-written method.

*The original method gets a compiler-generated attribute AsyncStateMachine with the generated type supplied in it.

It works in my code, where I use it for runtime code analysis during debug/tests only. Again, please, don't use it in production code.

A: You could do something like this from just using configuration, but it's not exactly what you mention. If you're able to read it and don't mind the weird syntax you could use the %type pattern to print out the qualified name of the method and then the %method pattern to print the method. You can even only print some of the qualified name to combat long namespaces.
From the docs:

Used to output the fully qualified type name of the caller issuing the logging request. This conversion specifier can be optionally followed by precision specifier, that is a decimal constant in brackets.

If a precision specifier is given, then only the corresponding number of right most components of the class name will be printed. By default the class name is output in fully qualified form.

For example, for the class name "log4net.Layout.PatternLayout", the pattern %type{1} will output "PatternLayout".

eg.
<layout type="log4net.Layout.PatternLayout">
  <conversionPattern value="%date %5level %logger %type{2}.%method [%line] - %message%newline %exception" />
</layout>

In terms of the MoveNext printing, it'll look like:
2021-03-10 11:45:29,203  INFO StackOverflowLogger SubNamespace.ClassName+<MethodNameAsync>d__15.MoveNext [123] - Logging is starting...

We didn't care about the d__15.MoveNext as long as the async method was there SubNamespace.ClassName+<MethodNameAsync>.


text:
Q: From dataframe to a nested dictionary I am experiencing some hard time trying in creating a nested dictionary from a dataframe in python and would really appreciate your help.This is what the data looks like.

tag
id
cat

0
PA14_00030
GO:0005524
F

1
PA14_00030
GO:0006281
P

2
PA14_00050
GO:0003677
F

3
PA14_00050
GO:0003918
F

4
PA14_00050
GO:0005524
F

5
PA14_00050
GO:0006265
P

6
PA14_00060
GO:0016746
F

7
PA14_00070
GO:0005975
C

8
PA14_00080
GO:0009055
C

I want to create a nested dictionary that will look something like this:
{'C':{'PA14_00080':{'GO:0009055'},'PA14_00070':{'GO:0005975'}},
'F':{'PA14_0003': {'GO:0005524'}, 'PA14_00050': {'GO:0003677', 'GO:0003918','GO:0005524'}},
'P':{PA14_00050:{GO:0006265}, PA14_00030:{GO:0006281}}}

Thank you for your help.

A: If I understand you correctly, you can do:
out = {
    k: {
        row["tag"]: set(g.loc[g["tag"] == row["tag"], "id"].to_list())
        for _, row in g.iterrows()
    }
    for k, g in df.groupby("cat")
}

print(out)

Prints:
{
    "C": {"PA14_00070": {"GO:0005975"}, "PA14_00080": {"GO:0009055"}},
    "F": {
        "PA14_00030": {"GO:0005524"},
        "PA14_00050": {"GO:0003918", "GO:0005524", "GO:0003677"},
        "PA14_00060": {"GO:0016746"},
    },
    "P": {"PA14_00030": {"GO:0006281"}, "PA14_00050": {"GO:0006265"}},
}


text:
Q: Delete asset from cache after single read I'm trying to ensure that cached assets are only read once, then deleted from cache. However, what I have below seems to leave the assets in the cache.
// At top of ServiceWorker...
const singleUse = ['https://www.example.com/api/some-data'];

// Inside fetch event...
event.respondWith(
  caches.match(event.request).then((cachedResponse) => {
    if (cachedResponse) {
      if (singleUse.includes(cachedResponse.url)) {
        event.waitUntil(
          caches.open(SINGLE_USE_ASSETS_KEY).then((cache) => {
            return cache.delete(cachedResponse.url);
          }),
        );
      }

      return cachedResponse;
    }

    return fetch(event.request);
  }),
);


text:
Q: TYPO3-extension webkitpdf (wkhtml2pdf) can't use login-secured pages (fe_users) I'm using webkitpdf to generate PDFs out of TYPO3-pages. This works like a charm - except with pages which are behind an fe_users-Login.
The webkitpdf implements wkhtml2pdf which works not under the scope of the TYPO3-rights-and-login-system but directly on the server as a binary. It calls the pages (which should be converted to PDFs) from the outside like a not-logged-in-browser.
Does anyone have an idea how this issue could be solved? (No solution needed, only an idea to approach the issue.)

A: Use the --cookie option in wkhtmltopdf to pass the cookie of a logged in user.


text:
Q: no such table: goods: I have a strange problem on an android application, I have no such table exception, but I'm sure that the database exists. For some that will redirect me to the other posts here I would like to add that I'm trying the app on my own cell phone not a an emulator, this because I read a lot of questions here that talk about the same problem on emulator.
Any ideas or hint will be greatly appreciated.
the code of activity with the error:
...

public class chartView extends Activity{
    Button editbtm;
    Button cleanbtm;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chart_layout);
        editbtm = (Button) findViewById(R.id.editBasketbtm);
        cleanbtm = (Button) findViewById(R.id.cleanBasketbtm);
        //fletch all goods that should be presented on the text View
        dbAdapter goodsfletcher = new dbAdapter(chartView.this);
    //  goodsfletcher.createGoodsTable();
        goodsfletcher.open();
        ...

the code of teh dbADapter class:
public class dbAdapter {

    public static final String KEY_ARTI = "ARTI";
    public static final String KEY_PROV = "PROV";
    public static final String KEY_CODART = "CODART";
    public static final String KEY_PRECBOL ="PRECBOL";
    public static final String KEY_QUANT ="QUANT";

    private static final String TAG = "DbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    private static final String DATABASE_CREATE = "create table goods ( CODART VARCHAR(10) primary key, ARTI varchar(50) not null, PROV varchar(15) not null, PRECBOL FLOAT(6,2) not null, QUANT int not null);";

    private static final String DATABASE_NAME = "ketanoBase";
    private static final String DATABASE_TABLE = "goods";
    private static final int DATABASE_VERSION = 1;

    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS goods");
            onCreate(db);
        }
    }

    public dbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    public dbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }

    public void addĜood(String code, String title, String source, String quantity, String price  ) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_ARTI, title);
        initialValues.put(KEY_CODART, code);
        initialValues.put(KEY_PROV, source);
        initialValues.put(KEY_PRECBOL, price);
        initialValues.put(KEY_QUANT, quantity);
        mDb.insert(DATABASE_TABLE, code, initialValues);

    }

    public boolean deleteGood(long rowId) {

        return mDb.delete(DATABASE_TABLE, KEY_CODART + "=" + rowId, null) > 0;
    }

    public void eraseGoods(){
        String sql = "drop table if exists goods";
        mDb.execSQL(sql);
    }

    public Cursor fetchAllGoods() {

        return mDb.query(DATABASE_TABLE, new String[] {KEY_CODART, KEY_ARTI,
                KEY_PROV, KEY_PRECBOL, KEY_QUANT}, null, null, null, null, null);
    }

    public Cursor fetchGood(long rowId) throws SQLException {

        Cursor mCursor =

                mDb.query(true, DATABASE_TABLE, new String[] {KEY_CODART,
                        KEY_ARTI, KEY_PROV,KEY_PRECBOL, KEY_QUANT}, KEY_CODART + "=" + rowId, null,
                        null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }

    public boolean updateGood(long rowId, String quantity) {
        ContentValues args = new ContentValues();

        args.put(KEY_QUANT,quantity);

        return mDb.update(DATABASE_TABLE, args, KEY_CODART + "=" + rowId, null) > 0;
    }
}

The LogCat og the error:
03-14 09:52:05.668: W/KeyCharacterMap(30808): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
03-14 09:52:06.384: D/AndroidRuntime(30808): Shutting down VM
03-14 09:52:06.384: W/dalvikvm(30808): threadid=1: thread exiting with uncaught exception (group=0x40018560)
03-14 09:52:06.394: E/AndroidRuntime(30808): FATAL EXCEPTION: main
03-14 09:52:06.394: E/AndroidRuntime(30808): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.remotedata.firstapp/com.remotedata.firstapp.chartView}: android.database.sqlite.SQLiteException: no such table: goods: , while compiling: SELECT CODART, ARTI, PROV, PRECBOL, QUANT FROM goods
03-14 09:52:06.394: E/AndroidRuntime(30808):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1768)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1784)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at android.app.ActivityThread.access$1500(ActivityThread.java:123)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:939)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at android.os.Looper.loop(Looper.java:130)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at android.app.ActivityThread.main(ActivityThread.java:3835)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at java.lang.reflect.Method.invokeNative(Native Method)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at java.lang.reflect.Method.invoke(Method.java:507)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at dalvik.system.NativeStart.main(Native Method)
03-14 09:52:06.394: E/AndroidRuntime(30808): Caused by: android.database.sqlite.SQLiteException: no such table: goods: , while compiling: SELECT CODART, ARTI, PROV, PRECBOL, QUANT FROM goods
03-14 09:52:06.394: E/AndroidRuntime(30808):    at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:92)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:65)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:83)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:49)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:42)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1356)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1235)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1189)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1271)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at com.remotedata.firstapp.dbAdapter.fetchAllGoods(dbAdapter.java:138)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at com.remotedata.firstapp.chartView.onCreate(chartView.java:31)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-14 09:52:06.394: E/AndroidRuntime(30808):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1722)
03-14 09:52:06.394: E/AndroidRuntime(30808):    ... 11 more

A: I believe that the database file exists, but the table doesn't exist as the error says. Have you tried deleting the database file and running again? Since the file exists, DatabaseHelper.onCreate() won't be called. It will only be called if the file doesn't exist and a new database is created.


text:
Q: Having trouble grasping the class equation as an explanation as to why a conjugate class's order divides the order of a group. Suppose $|G|$ is a prime power $p^n$ and that $N$ is a normal subgroup of $G$.
Show that $|y^G|$ is a power of $p$ whenever $y \in G$
Attempt:
Firstly, I assume that $y^G = \{ gyg^{-1} | g \in G \}$' i.e. we're talking about a  conjugacy class here. And I know I'm supposed to use the class equation and the fact that $N$ is a normal subgroup in $G$ but I just don't know how. I mean, I saw the Wiki explanation for it but I just don't think I was able to follow the logic in a way I can absorb and repeat.
Could you show me how to answer this question and maybe explain how I can conceptualize conjugation classes in the future?

A: $|y^G|=[G:C_G(y)]$ by orbit stabilizer theorem and $C_G(y)$ denotes the stabilizer of $y$ in $G$.
Since $C_G(y)$ is a subgroup of $G$ its index is equal to a power of $p$.
http://en.wikipedia.org/wiki/Conjugacy_class


text:
Q: Can't align horizontal scrollbar properly Python beginner here. Horizontal scrollbar not working properly: it won't stretch out the whole window width. However vertical scrollbar and everything else works perfectly fine. What could be the problem?
import tkinter
from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk

def listwindow():
    list_window = Toplevel()

    list_window.geometry("1000x300")
    list_window.title("List Presentation")
    list_window.config(background="#232323")

    main_frame = Frame(list_window)
    main_frame.pack(fill=BOTH, expand=1)

    mcanvas = Canvas(main_frame)
    mcanvas.pack(side=LEFT, fill=BOTH, expand=1)

    mscrollbar = ttk.Scrollbar(main_frame, orient=HORIZONTAL, command=mcanvas.xview)
    mscrollbar.pack(side=BOTTOM, fill=X)

    mscrollbar2 = ttk.Scrollbar(main_frame, orient=VERTICAL, command=mcanvas.yview)
    mscrollbar2.pack(side=RIGHT, fill=Y)

    mcanvas.configure(xscrollcommand=mscrollbar.set)
    mcanvas.bind('<Configure>', lambda e: mcanvas.configure(scrollregion=mcanvas.bbox("all")))

    mcanvas.configure(yscrollcommand=mscrollbar2.set)
    mcanvas.bind('<Configure>', lambda e: mcanvas.configure(scrollregion=mcanvas.bbox("all")))

    second_frame = Frame(mcanvas)

    mcanvas.create_window((0, 0), window=second_frame, anchor="nw")

    for i in range(len(googleimg.searchlist)):
        globals()["itemImage"+str(i + 1)] = PhotoImage(file="D:\\Photos\\listcreator\\" + str(googleimg.targetpath) + "\\resized\\"+str(i+1)+".png")
        globals()["labelImage" + str(i + 1)] = Label(second_frame,image=globals()["itemImage"+str(i+1)]).grid(row=0,column=i)

    list_window.mainloop()

A: The order of calling .pack() matters:
mscrollbar.pack(side=BOTTOM, fill=X)
mscrollbar2.pack(side=RIGHT, fill=Y)
mcanvas.pack(side=LEFT, fill=BOTH, expand=1)


text:
Q: Spring boot, usando o banco h2 para testes Eu uso o postgresql, porém para os testes quero usar o banco H2, como faço o spring reconhecer o banco H2 para os testes?
Criar outro application.properties passando os dados do h2?
***estou usando o mybatis ao invés do JPA
spring.h2.console.path=/h2-console

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver ```

A: Você pode criar um arquivo .properties com a sigla -dev, assim você pode indicar o profile no momento de executar seu projeto.
Exemplo:
Maven
mvn spring-boot:run -Dspring-boot.run.profiles=dev

Veja também: how-to-use-spring-boot-profiles


text:
Q: How do I convert a variable containing a percentage to a number in LESS, but leave plain numbers alone? In a LESS mixin, I have an alpha value that I'd like to convert to a plain number (0.xx) even if it is given as a percentage (xx%). I've found the percentage() function to convert a number to a percentage, but percentage(xx%) returns "xx00%" and dividing by 100 makes 0.xx into 0.00xx, which is no good either. All the "if-then" statements that I could find in LESS invlove making a new scope, so while I could detect the "%", I couldn't pass that information back into a variable to use it.
How do I go about converting a percentage to a number if and only if it is a percentage?

A: While you can use JS within Less to achieve the desired effect, a better approach would be to use the built-in ispercentage() and isnumber() type functions to check whether a variable value is a number or a percentage or neither and then output the value accordingly.
.percentlike(@var) {
  & when (ispercentage(@var)){ /* is input value a percentage */
    alpha: unit(@var / 100); /* unit() strips the % symbol */
    /* you could also use the replace function like below
      @percentage: @var / 100;
      alpha: replace(~"@{percentage}", "%", "");
    */
  }
  & when not (ispercentage(@var)) and (isnumber(@var)){ /* not percentage but is a number */
    alpha: @var;
  }
  & when not (ispercentage(@var)) and not (isnumber(@var)){ /* neither */
    alpha: ~"NaN";
  }
}

div#div1 {
  .percentlike(20%);
}
div#div2{
  .percentlike(0.2);
}
div#div3{
  .percentlike(a);
}

Compiled CSS:
div#div1 {
  alpha: 0.2;
}
div#div2 {
  alpha: 0.2;
}
div#div3 {
  alpha: NaN;
}

A: Try this: replace(~"@{value}", '%', '');

A: Well, it's an end-run, but I found a solution. You can use backticks to run arbitrary JS in LESS, so I just did...
.percentlike(@var1, @var2) {
  -percent-property: ~`"@{var1}".match(/%$/) ? parseFloat("@{var1}") / 100 : parseFloat("@{var1}")`;
  -decimal-property: ~`"@{var2}".match(/%$/) ? parseFloat("@{var2}") / 100 : parseFloat("@{var2}")`;
}

div {
  .percentlike(20%, 0.2);
}

Which, as desired, yields...
div {
  -percent-property: 0.2;
  -decimal-property: 0.2;
}


text:
Q: user authentication on heroku with play framework What is the best way to create user authentication with play framework on heroku? Because both are stateless.

A: You can simply use the secure module.
If you want to build yourself, then on authentication, store something in the session cookie to show the user is logged in (I usually store userId). The session cookie is secure, so can't be hacked, and keeps everything stateless. Remember that the contents of the cookie can be read, it just can't be modified without corrupting the cookie.

A:
if you need to store any state server side, then you would normally do this by putting the data in a database, and then deleting the data at the end of the process.

Don't forget about caching. For multiple threads/dynos, you can use memcached to access shared cached data. Heroku even mentions it in their great talk: http://www.infoq.com/presentations/Horizontal-Scalability


text:
Q: Firebase functions nodemailer: gmail and oauth2 fails on the free plan I am using Firebase functions with nodemailer to send email from a contact form on my website.
I am on the free plan, and as I understood Gmail API is considered to be a Google service and not general internet request, so it should work fine.
Here is my Typescript code
import * as functions from 'firebase-functions';
import * as nodemailer from 'nodemailer';
import { DocumentSnapshot } from 'firebase-functions/lib/providers/firestore';

export const sendMessage = functions.firestore.document('/emails/{pushKey}').onCreate((snap: DocumentSnapshot) => {

  const form = snap.data();

  const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      type: 'OAuth2',
      user: 'myemail@gmail.com',
      clientId: 'xxxxxxxxxxxxx',
      clientSecret: 'xxxxxxxxx',
      refreshToken: 'xxxxxxxxx'
    },
    debug: true
  });

  const mailOptions = {
    from: 'sender@gmail.com',
    to: 'receiver@gmail.com',
    subject: `Message from ${form.name} <${form.email}>`,
    html: form.message
  };

  return transporter.sendMail(mailOptions)
    .then(() => {
      console.log('Email sent.');
    }).catch((err) => {
      console.log(err);
    });
});

However, I get in the console log

*

*sendMessage  Function execution took 2908 ms, finished with status: 'ok'

*sendMessage  Function returned undefined, expected Promise or value

*sendMessage  Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions

*sendMessage  Function execution started
Am I using any external network here!
The following code works
import * as functions from 'firebase-functions';
import * as nodemailer from 'nodemailer';
import { DocumentSnapshot } from 'firebase-functions/lib/providers/firestore';

const gmailEmail = encodeURIComponent(functions.config().gmail.email);
const gmailPassword = encodeURIComponent(functions.config().gmail.password);
const mailTransport = nodemailer.createTransport(`smtps://${gmailEmail}:${gmailPassword}@smtp.gmail.com`);

export const sendMessage = functions.firestore.document('/emails/{pushKey}').onCreate((snap: DocumentSnapshot) => {

  const form = snap.data();

  const mailOptions = {
    to: 'receiver@gmail.com',
    subject: `Message from ${form.name} <${form.email}>`,
    html: form.message
  };
  return mailTransport.sendMail(mailOptions)
    .then(() => console.log('worked!'))
    .catch(e => console.log(e));
});

But this way is unsecured, and It requires me to allow less secure apps on my Gmail account.
How can I use Gmail and OAuth2 with the free Firebase plan?

A: So you cannot make outbound requests on the Firebase free plan. You need to upgrade your plan to make outbound requests, and I believe since you are using 'nodemailer' that is the part trying to make an outbound request. Here is another question with comments about upgrading to use a mail service: How can I use nodemailer with Cloud Functions for Firebase?
I believe Firebase also made the Blaze plan free until you go past the quota of the free plan, so it really won't cost anything until you step past the free quota specified in the pricing (https://firebase.google.com/pricing/).


text:
Q: Which is correct? "Get an answer by him" or "get an answer from him" I am confused with below expression.

*

*You might get a correct answer by him.

*You might get a correct answer from him.

Which is the correct expression?

A: "From" is correct.   I don't know if there's a particular English grammar rule that defines this -- it's just the proper idiom in common use.

A: The differences between the two are extremely difficult to explain because it is not based on some sort of logic, but rather on habit of how speakers use English. Altogether this gets very complicated and you're probably perfectly fine just thinking that the "by him" version is incorrect. It can be used in certain contexts, although rarely. So rare in fact, that I don't think I've ever used English like that in 29 years of speaking English as a native.
Basically, you almost never need to use the "by him" version and it generally sounds incorrect, however, there are a few instances where I could imagine saying it. I would say that the "by him" is not the normal way of speaking, so it sounds like the fact that an answer is by the person is being emphasized. In the normal use of the word "answer", using the "by" collocation here is incorrect. An answer, as in a reply to a question, is not something that we say is "by" someone. However, I can imagine that if you were talking about answers that are written on websites such as this website, then you would say that an answer is "by" someone. For example, this very answer that I am writing right now is an answer that is by me. This is the same usage of the word "by" as if I were talking about a letter by me or a book that was written by me, etc. It means that a person is the author of the answer. It has to be something written or typed for one to say that an answer was written "by" someone and for it to be correct English. You could not refer to a verbal answer and use the expression "by him".
Imagine if you were searching through a list of correct answers to a question on this website. You then ask, "Do you think I might find a correct answer by George?" (notice that here "by" is correct and not "from", because "from" makes it sound like George specifically sent his answer to you) and then I tell you that "you might find a correct answer by him." "By him" is correct because George would be the author of the answer.
Whew, what a pain in the English. This is one of those things where not being a native speaker makes it a lot harder to know this stuff. Maybe a proper linguist could help explain this stuff more technically than I could?


text:
Q: How to create Azure function with C# using HTTP POST and store incoming data into text file in BLOB storage? I am new to Azure function. I am trying to create Azure function in portal with Http trigger which gets the data as JSON and POST it as a text file in BLOB storage. I know I am missing something here in the code:

function.json

{
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "blob",
      "name": "outputBlob",
      "path": "outcontainer/{rand-guid}",
      "connection": "AzureWebJobsStorage",
      "direction": "out"
    }
  ]
}

run.csx

#r "Newtonsoft.Json"
#r "Microsoft.WindowsAzure.Storage"
#r "Microsoft.Azure.WebJobs.Extensions.Storage"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.Azure.WebJobs.Extensions.Storage;

public static async Task<IActionResult> Run(HttpRequest req,
[Blob("blobcontainer", Connection = "AzureWebJobsStorage")] CloudBlobContainer outputContainer,
ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    await outputContainer.CreateIfNotExistsAsync();

    var requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    var blobName = Guid.NewGuid().ToString();

    var cloudBlockBlob = outputContainer.GetBlockBlobReference(blobName);
    await cloudBlockBlob.UploadTextAsync(data);

    return new OkObjectResult(blobName);
}

It compiles successfully but getting run time error as below:

No value was provided for parameter 'outputContainer'

A: Ok, now with a valid and tested sample :) (although somebody else posed a similar sample now as well)
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage.Blob;

namespace SampleFunctions
{
    public static class Http2BlobFunction
    {
        [FunctionName("Http2BlobFunction")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req,
            [Blob("myblobcontainer/{rand-guid}.txt", FileAccess.Write)] CloudBlockBlob blob,
            ILogger log)
        {
            log.LogInformation("Received file upload request");
            var requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            await blob.UploadTextAsync(requestBody);
            return new OkObjectResult(blob.Name);
        }
    }
}

A: Maybe you could try with my code, just bind the blob and write the request.
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
[Blob("myblobcontainer/{rand-guid}.txt", FileAccess.Write)]CloudBlockBlob outputblob)
{
    var requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    await outputblob.UploadTextAsync(requestBody);
    return new OkObjectResult(outputblob);
}

I test local, it could write the request body to a txt blob.

Hope this could help you.


text:
Q: Trouble with map() I'm trying to convert the values of a list using the map function but i am getting a strange result.
s = input("input some numbers: ")
i = map(int, s.split())
print(i)

gives:
input some numbers: 4 58 6
<map object at 0x00000000031AE7B8>

why does it not return ['4','58','6']?

A: You are using python 3 which returns generators instead of lists.
Call list(x) on the variable after you assign it the map generator.

A: You need to do list(i) to get ['4','58','6'] as map in python 3 returns a generator instead of a list.
Also, as Lattyware pointed in the comment of the first answer you better do this:
i = [int(x) for x in s.split()]


text:
Q: Rotate a vector until it is perpendicular to another Let $x, y\in\mathbb{R}^n$. I would like to rotate $y$ so that it is perpendicular to $x$. Is it possible to find a matrix $R\in\mathbb{R}^{n\times n}$ that does that?
$$
x^\top Ry = 0
$$
Attempt
The matrix must be orthogonal $RR^\top =I$. This means we must have
$$
\sum_{k=1}^n r_{ik} r_{jk} = \delta_{ij} \qquad \forall i,j\in\{1, \ldots, n\}
$$
Since $RR^\top$ is symmetric, we must have that the above and below diagonal entries are the same, thus they would lead to the same constraints. Overall we have $n$ diagonal and $\frac{1}{2}n(n-1)$ off-diagonal constraints for a total of $\frac{1}{2}n(n+1)$ constraints. In addition, we also have the constraints given by the condition that $y'=Ry$ is perpendicular to $x$
$$
\sum_{i=1}^n\sum_{j=1}^n x_i R_{ij} y_j = 0
$$
Thus we have $\frac{1}{2}n^2 + \frac{1}{2}n + 1$ constraints. One final constrain, in order for $R$ to be a proper rotation, is given by the determinant $\det(R) = 1$, which gives one more constraint. Overall we have
$$
\frac{1}{2}n^2 + \frac{1}{2}n + 2
$$
constraints. However, $R$ has $n^2$ entries.

A: First, find the orthogonal projection of $y$ onto the line spanned by $x$ - call it $\hat y$. This amounts to saying $\hat y=u(y\cdot u)$, where $u=x/\|x\|$, the unit vector for that line. The matrix for this is
$$P=\begin{bmatrix}u_1^2&u_1u_2&u_1u_3&\cdots\\u_2u_1&u_2^2&u_2u_3&\cdots\\u_3u_1&u_3u_2&u_3^2&\cdots\\\vdots&\vdots&\vdots&\cdots\end{bmatrix}$$
Such that $\hat y=Py$. Now, the projection onto the orthogonal complement of this is $I-P$. $I$ denotes the identity matrix. From now on, $\hat y$ refers to the orthogonal projection of $y$ onto the orthogonal complement of the line spanned by $x$. This will orthogonally project $y$ onto a line orthogonal to $x$, but we need a rotation of $y$ - we must make it the same length. So we need to rescale by $\|y\|/\|\hat y\|$. The length of this new orthogonal projection, $\hat y=(I-P)y$, is calculated as follows:
$$\|(I-P)y\|=\|y-Py\|=\|y-u(y\cdot u)\|$$
I don't know how to make a single matrix to accomplish this, but very simply we can say $x^T(I-P)y=0$, and to make this a proper rotation we scale $(I-P)y$ by $\|y\|/\|(I-P)y\|$.
Concrete example:
$$x=\begin{pmatrix}2\\4\\5\end{pmatrix},\,y=\begin{pmatrix}2\\1\\2\end{pmatrix},\|x\|=3\sqrt{5},\,\|y\|=3\\u=\begin{pmatrix}\frac{2}{3\sqrt{5}}\\\frac{4}{3\sqrt{5}}\\\frac{\sqrt{5}}{3}\end{pmatrix}\\P=\frac{1}{45}\begin{pmatrix}4&8&10\\8&16&20\\10&20&25\end{pmatrix}\\I-P=\frac{1}{45}\begin{pmatrix}41&-8&-10\\-8&29&-20\\-10&-20&20\end{pmatrix}\\\hat y=(I-P)y=\frac{1}{45}\begin{pmatrix}54\\-27\\0\end{pmatrix}=\begin{pmatrix}\frac{6}{5}\\-\frac{3}{5}\\0\end{pmatrix}$$
And $\hat y$ is orthogonal to $x$, but is not the same length as $y$, so the rescale is necessary.

A: We are given $x$ and $y$, and we want to find $R$ such that $x^T R y = 0$.  Thus we must have the vector $y_1 = R y$ in the orthogonal space of vector $x$.
So the first step is to generate the orthogonal space to $x$ by solving the homogenous linear system $ x^T v = 0 $ for all possible $v$'s.  Let the matrix $V$ contain a basis of this orthogonal space, then we can select
$y_1 = V u $
for some $u \in \mathbb{R}^{n-1} $
Since rotation preserves length, then we have to scale $y_1$ to have the same length as $y$.
Next, the rotation matrix $R$ alters $y$ into $y_1 = R y$ but does not alter the vectors orthogonal to $y$ and $y_1$, so the next step is to find an orthogonal basis for the orthogonal complement to the two vectors {$y$, $y_1$}, and this can be done in two steps, first find a basis (not necessarily orthogonal) of the orthogonal complement to {$y$, $y_1$}, which will have dimension $n-2$.  In step two, you'll take these $n-2$ vectors and ammend them with the vectors $y$ and $y_1$, so that now you have a complete set of $n$ vectors.  Run the Gram-Schmidt process to orthogonalize them, and let the matrix containing the orthonormal vectors be $G$. Now express $y$ and $y_1$ in terms of these basis vectors.
$y = G w_1 $ and $y_1 = G w_2 $
Since the first $(n-2)$ vectors of $G$ are orthogonal to $y$ and $y_1$, then the first $(n-2)$ entries of $w_1$ and $w_2$ will be zero.
Let $p_1$ be the $2 \times 1$ vector of the last two entries of $w_1$ and $p_2$ be the $2 \times 1$ vector of the last two entries of $w_2$, then we can relate $p_2$ to $p_1$ by a rotation (remember they have the same length),
$p_2 = R_{22} p_1$
where $R_{22}$ is a $2 \times 2$ rotation matrix.  Finally define the matrix $E $ by
$ E = \begin{bmatrix} I_{(n-2) \times (n-2)} && 0_{(n-2) \times 2} \\ 0_{2 \times (n-2)} && R_{22} \end{bmatrix} $
Then we have $w_2 = E w_1 $
Recalling the $y= G w_1 $ and $y_1 = G w_2$ then we can write
$y_1 = G E w_1 = G E G^T y $
Hence the rotation matrix relating $y$ and $y_1$ is $R = G E G^T$
Thus, there are infinite rotation matrices $R$ that can rotate a given vector $y$ to become orthogonal to another given vector $x$.

A: Not too familiar with matrix algebra but your first problem I can certainly solve. The answer is:
$$ \frac{y \times x}{|x| \sin \theta}$$
You may check that this is the result expression above can be geometrically visualized as 'twisting' $y$ ninty degrees about the line define by $x$ after killing of the component of $y$ along $x$. To restore the length to the original case we bring in the scaling factor in the denominator.
For the case of matrix, we can consider this rotation aspect of cross product to be realized as a matrix by the method described here


text:
Q: Opening a named pipe in bash, without reading or writing to it I want to use a named pipe in bash without reading or writing to it, until an event occurs. i need to keep this pipe open for the entire duration the shell script runs. I will read from it whenever I need to. Meaning, can something be done like this:
open(<$NAMED_PIPE>, "r+")
--do something--
--call child ruby script, which will write to named pipe--
--do something more---
read line < $NAMED_PIPE

Is this possible in bash?
I am using the following code:
../Ruby
|-- try1.rb
`-- try2.sh
try1.rb is as follows:
#!/usr/bin/ruby

require 'optparse'

puts 'Hello World!, This is my first ruby program'

options = {}

optparse = OptionParser.new do|opts|

  opts.banner = "Featbuild minimal trial script for command line parsing"

  options[:cpl] = nil
  opts.on('--cpl SWITCH_STATE', 'compile on or off') do|cplopt|
      options[:cpl] = cplopt
      OPT_CPL=cplopt
      puts cplopt
  end

  opts.on('-h', '--help', 'Display this screen') do
    puts opts
    exit
  end
end

optparse.parse!

output = open("mypipe", "w+")

output.puts OPT_CPL
output.flush

And the try2.sh script(which calls the ruby script):
#!/bin/sh

mkfifo mypipe
exec 4< /home/yusufh/Ruby/mypipe

OPT=$*
./try1.rb ${OPT}

#read -ru 4 line
read line <&4

echo $line

exec 4<&- #close FIFO my_pipe

rm mypipe

@konsolebox, your solution worked when I used a normal text file where I copy the data from the ruby script, and from there itself the bash script picks it up.
However, On trying with named pipes, the bash script blocks after executing the following statement:exec 4< /home/yusufh/Ruby/mypipe. Control doesnt reach to spawning the ruby script process, where the data will be genrated, and after that the actual waiting/blocking by the bash script has to be done at this line: read line <&4.
Due to this, what I want to achieve isn't happening. Additional, when bash waits in when it acquires the fd of the FIFO, if I echo something into the named pipe on a duplicate terminal, it then does come out of wait and proceeds further. But then in this case, the data returned from the Ruby script is also not written to the FIFO, as I have observed. This is the output of the scritps in debug mode:
[yusufh@verigybuild6 Ruby]$ bash -xv try2.sh --cpl on &
[1] 2777
[yusufh@verigybuild6 Ruby]$ #!/bin/sh

mkfifo mypipe
+ mkfifo mypipe
exec 4< /home/yusufh/Ruby/mypipe
+ exec

[yusufh@verigybuild6 Ruby]$ echo "Hello World" > mypipe
[yusufh@verigybuild6 Ruby]$
OPT=$*
+ OPT='--cpl on'
./try1.rb ${OPT}
+ ./try1.rb --cpl on
Hello World!, This is my first ruby program
on

#read -ru 4 line
read line <&4
+ read line

echo $line
+ echo Hello World
Hello World

exec 4<&- #close FIFO my_pipe
+ exec

rm mypipe
+ rm mypipe

[1]+  Done                    bash -xv try2.sh --cpl on
[yusufh@verigybuild6 Ruby]$

Any ideas as why this is failing?. I appreciate the efforts! :-)

A: It's pretty simple with Bash:
# Open the named pipe with a custom fd for input
exec 4< /path/to/named_pipe

# Do other things
:

# Read a line from pipe
read -ru 4 line

# Or
read -r line <&4

# Just make this consistent and close it when you're done. May not be necessary at exit but still a good practice.
exec 4<&-

*

*When reading input with read, it may be a good idea to use -r to prevent backslashes from escaping any character

*Running read with IFS unset (IFS= read ...) may also be helpful to prevent trimming of leading and trailing spaces.

Similar concept would apply for writing:
exec 4> /path/to/named_pipe
echo something >&4
exec 4>&-

Bonus: You may also open a named pipe in the scope of a block like {}, while, for, if, until, etc.. With it won't be necessary to close the file descriptor:
{
    # Do reads and other things
    ...
} 4< /path/to/named_pipe

A: In absence of information about how your script rights to pipe, here is one possible option that i can think of.
1) open pipe mkfifo /path/to/pipe
2) do something echo test1
3) call child ruby script,which will write to named pipe (assuming script to be executable)  /path/to/script >> /path/to/pipe &
4) do something more echo test2
5) read line from pipe read pipeddata < /path/to/pipe


text:
Q: Card overlapping raised button in flutter friends, I am thinking to make this type of view but I can't able to set the button overlapping like the given image I am using stack widget which is containing the text fields and the buttons as given image please check and help me out I also tried to use the center widgets as well but the view is coming as required in it also i had used the positioned widget but its getting button bottom of the screen   like this  but i need as the above image
MyLayoutDesign
 class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    MyAppState myAppState() => new MyAppState();
    return myAppState();
  }
}

class MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(home: new Scaffold(body: new Builder(
      builder: (BuildContext context) {
        return new Stack(
          children: <Widget>[
            new Image.asset(
              'assets/images/bg.png',
              fit: BoxFit.cover,
            ),
            new Center(
              child: new Container(
                child: new Card(
                  color: Colors.white,
                  elevation: 6.0,
                  margin: EdgeInsets.only(right: 15.0, left: 15.0),
                  child: new Wrap(
                    children: <Widget>[
                      Center(
                        child: new Container(
                          margin: EdgeInsets.only(top: 20.0),
                          child: new Text(
                            'Login',
                            style: TextStyle(
                                fontSize: 25.0, color: secondarycolor),
                          ),
                        ),
                      ),
                      new ListTile(
                        leading: const Icon(Icons.person),
                        title: new TextFormField(
                          decoration: new InputDecoration(
                            hintText: 'Please enter email',
                            labelText: 'Enter Your Email address',
                          ),
                          keyboardType: TextInputType.emailAddress,
                        ),
                      ),
                      new ListTile(
                        leading: const Icon(Icons.lock),
                        title: new TextFormField(
                          decoration: new InputDecoration(
                            hintText: 'Please enter password',
                            labelText: 'Enter Your Password',
                          ),
                          keyboardType: TextInputType.emailAddress,
                          obscureText: true,
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(top: 10.0, bottom: 15.0),
                        child: Center(
                          child: Text(
                            "FORGOT PASSWORD",
                            style: TextStyle(
                                decoration: TextDecoration.underline,
                                color: Colors.black,
                                fontSize: 16.0),
                          ),
                        ),
                      ),
                      Center(
                        child: Container(
                          margin: EdgeInsets.only(bottom: 40.0, top: 10.0),
                          child: Text.rich(
                            TextSpan(
                              children: const <TextSpan>[
                                TextSpan(
                                    text: 'NEW USER ? ',
                                    style: TextStyle(
                                        fontSize: 16.0, color: Colors.black)),
                                TextSpan(
                                    text: 'REGISTER',
                                    style: TextStyle(
                                        fontSize: 16.0,
                                        decoration: TextDecoration.underline,
                                        color: Colors.black)),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            new RaisedButton(
              onPressed: () {
                print('Login Pressed');
              },
              color: primarycolor,
              shape: new RoundedRectangleBorder(
                  borderRadius: new BorderRadius.circular(30.0)),
              child: new Text('Login',
                  style: new TextStyle(
                      color: Colors.white,
                      fontSize: 16.0,
                      fontWeight: FontWeight.bold)),
            ),
          ],
        );
      },
    )));
  }
}

A: this is just one the many ways you can achieve the expected result.
In this case, i assume you know the height of the background.
Again, there are many ways to achieve what you want. There is nothing wrong with your code, you just have to get an understanding of how 'things' work in Flutter
Widget demo = Stack(
  children: <Widget>[
    //First thing in the stack is the background
    //For the backgroud i create a column
    Column(
      children: <Widget>[
        //first element in the column is the white background (the Image.asset in your case)
        DecoratedBox(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20.0),
            color: Colors.white
          ),
          child: Container(
            width: 300.0,
            height: 400.0,
          )
        ),
        //second item in the column is a transparent space of 20
        Container(
          height: 20.0
        )
      ],
    ),
    //for the button i create another column
    Column(
      children:<Widget>[
        //first element in column is the transparent offset
        Container(
          height: 380.0
        ),
        Center(
          child: FlatButton(
            color: Colors.red,
            child: Text("Press Me"),
            onPressed: () {},
          ),
        )
      ]
    )
  ],
);

A: Here you can find your solution code below.
    import 'package:flutter/material.dart';

    void main() => runApp(MyApp());

    class MyApp extends StatefulWidget {
    @override
    State<StatefulWidget> createState() {
    MyAppState myAppState() => new MyAppState();
    return myAppState();
    }
   }

   class MyAppState extends State<MyApp> {
   @override
   Widget build(BuildContext context) {
     return new MaterialApp(home: new Scaffold(body: new Builder(
       builder: (BuildContext context) {
         return new Stack(
          children: <Widget>[
             new Image.asset(
            'assets/images/bg.jpeg',
             fit: BoxFit.fitWidth,
           ),
           new Center(

          child: new Container(
            height: 370.0,

            child: Container(

              height:250.0,
              child: new Card(
              color: Colors.white,
              elevation: 6.0,
              margin: EdgeInsets.only(right: 15.0, left: 15.0),
              child: new Wrap(

                children: <Widget>[
                  Center(
                    child: new Container(
                      margin: EdgeInsets.only(top: 20.0),
                      child: new Text(
                        'Login',
                        style: TextStyle(
                            fontSize: 25.0, color: Colors.red),
                      ),
                    ),
                  ),
                  new ListTile(
                    leading: const Icon(Icons.person),
                    title: new TextFormField(
                      decoration: new InputDecoration(
                        hintText: 'Please enter email',
                        labelText: 'Enter Your Email address',
                      ),
                      keyboardType: TextInputType.emailAddress,
                    ),
                  ),
                  new ListTile(
                    leading: const Icon(Icons.lock),
                    title: new TextFormField(
                      decoration: new InputDecoration(
                        hintText: 'Please enter password',
                        labelText: 'Enter Your Password',
                      ),
                      keyboardType: TextInputType.emailAddress,
                      obscureText: true,
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 10.0, bottom: 15.0),
                    child: Center(
                      child: Text(
                        "FORGOT PASSWORD",
                        style: TextStyle(
                            decoration: TextDecoration.underline,
                            color: Colors.black,
                            fontSize: 16.0),
                      ),
                    ),
                  ),
                  Center(
                    child: Container(
                      margin: EdgeInsets.only(bottom: 40.0, top: 10.0),
                      child: Text.rich(
                        TextSpan(
                          children: const <TextSpan>[
                            TextSpan(
                                text: 'NEW USER ? ',
                                style: TextStyle(
                                    fontSize: 16.0, color: Colors.black)),
                            TextSpan(
                                text: 'REGISTER',
                                style: TextStyle(
                                    fontSize: 16.0,
                                    decoration: TextDecoration.underline,
                                    color: Colors.black)),
                          ],
                        ),
                      ),
                    ),
                  ),
                  Padding(padding: EdgeInsets.only(left: 120.0)),

                ],

              ),

              ),

            ),
            padding: EdgeInsets.only(bottom: 30),

          ),

        ),
        new Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(padding: EdgeInsets.only(top: 310.0)),
            RaisedButton(
              onPressed: () {
                print('Login Pressed');
              },
              color: Colors.green,
              shape: new RoundedRectangleBorder(
                  borderRadius: new BorderRadius.circular(30.0)),
              child: new Text('Login',
                  style: new TextStyle(
                      color: Colors.white,
                      fontSize: 16.0,
                      fontWeight: FontWeight.bold)),
            ),
          ],
        )
         )
        ],
       );
     },
    )));
   }
  }

A: @ibhavikmakwana propsed a better solution to your question. The other answers all depend on the size of the background and are not screen independent. They both create an invisible object above the button (either by adding a Container or a Padding).
I was having that question too and did not find your question first.
His simple solution is to wrap the button in a Positioned widget and give it a bottom of 0 or < 0.
Positioned(
  child: FlatButton(
        color: Colors.red,
        child: Text("Press Me"),
        onPressed: () {},
      ),
  right: 0,
  left: 0,
  bottom: 0,
)

I found out that the "bottom" attribute set to 0 will offset the widget by exactly 0.5*height of the widget.


text:
Q: Why doesn't setValue:forKeyPath invoked on mutable dictionary throw exception for unknown keypaths? I have following code:
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[defs setObject:[NSNumber numberWithInt:100] forKey:@"test1.test2.test3"];
[defs setValue:[NSNumber numberWithInt:10] forKeyPath:@"test2.test3.test4"];

I understand that setObject:forKey: creates association between "test1.test2.test3" key and given number object. On the other hand, setValue:forKeyPath: is Key-Value-Coding method that tries to locate object for path "test2.test3.test4", but in the end, it just silently does nothing. It doesn't even modify the dictionary!
What confuses me greatly is that setValue:forKeyPath: doesn't raise any exception nor does it report any error. Why is this? Is this behavior documented anywhere?

A: I can't find any documentation for this specific case, sorry, but my guess is that this:
[defs setValue:x forKeyPath:@"a.b.c"];

Is being implemented something like this:
[[defs objectForKey:@"a"] setValue:x forKeyPath:@"b.c"];

So objectForKey: returns nil, and methods called on nil just do nothing. That would explain the behaviour you have described.

A: NSMutableDictionary *dict = [@{@"test1" : [@{@"test2":[@{} mutableCopy]} mutableCopy]} mutableCopy];

[dict setValue:@(100) forKeyPath:@"test1.test2.test3"]; // ok
[dict setValue:@(200) forKeyPath:@"test1.test2.test4"]; // ok
[dict setValue:@(300) forKeyPath:@"test1.test21"];      // ok
[dict setValue:@(400) forKeyPath:@"test1.test22.test3"]; // fail, test22 not mutable

[dict setValue:[@{} mutableCopy] forKeyPath:@"test1.test23"]; // ok
[dict setValue:@(500) forKeyPath:@"test1.test23.test34"]; // ok