问:
repository:auditing-attributes cannot be resolved to a(n) attribute group component
Getting the Spring Data library, specifically Spring Repositories, into a Java legacy application(Java 1.6). The legacy application is using an Ant build as well and I am getting the following error when the Spring ApplicationContext is being loaded.

```<code>org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 43 in XML document from ServletContext resource [/WEB-INF/spring/beans/cycpersistence-beans.xml] is invalid; nested exception is org.xml.sax.SAXParseException: src-resolve: Cannot resolve the name 'repository:auditing-attributes' to a(n) 'attribute group' component.
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:399)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:399)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:612)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:513)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3910)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4389)
at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeployInternal(TomcatDeployment.java:313)
at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeploy(TomcatDeployment.java:145)
at org.jboss.web.deployers.AbstractWarDeployment.start(AbstractWarDeployment.java:461)
at org.jboss.web.deployers.WebModule.startModule(WebModule.java:122)
at org.jboss.web.deployers.WebModule.start(WebModule.java:97)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:157)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:96)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:668)
at org.jboss.system.microcontainer.ServiceProxy.invoke(ServiceProxy.java:206)
at com.sun.proxy.$Proxy38.start(Unknown Source)
at org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:42)
at org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:37)
at org.jboss.dependency.plugins.action.SimpleControllerContextAction.simpleInstallAction(SimpleControllerContextAction.java:62)
at org.jboss.dependency.plugins.action.AccessControllerContextAction.install(AccessControllerContextAction.java:71)
at org.jboss.dependency.plugins.AbstractControllerContextActions.install(AbstractControllerContextActions.java:51)
at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
at org.jboss.system.microcontainer.ServiceControllerContext.install(ServiceControllerContext.java:297)
at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1652)
at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:938)
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:988)
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:826)
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:556)
at org.jboss.system.ServiceController.doChange(ServiceController.java:688)
at org.jboss.system.ServiceController.start(ServiceController.java:460)
at org.jboss.system.deployers.ServiceDeployer.start(ServiceDeployer.java:163)
at org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:99)
at org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:46)
at org.jboss.deployers.spi.deployer.helpers.AbstractSimpleRealDeployer.internalDeploy(AbstractSimpleRealDeployer.java:62)
at org.jboss.deployers.spi.deployer.helpers.AbstractRealDeployer.deploy(AbstractRealDeployer.java:55)
at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:179)
at org.jboss.deployers.plugins.deployers.DeployersImpl.doDeploy(DeployersImpl.java:1454)
at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1172)
at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1193)
at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1225)
at org.jboss.deployers.plugins.deployers.DeployersImpl.install(DeployersImpl.java:1113)
at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1652)
at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:938)
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:988)
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:826)
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:556)
at org.jboss.deployers.plugins.deployers.DeployersImpl.process(DeployersImpl.java:789)
at org.jboss.deployers.plugins.main.MainDeployerImpl.process(MainDeployerImpl.java:699)
at org.jboss.system.server.profileservice.repository.MainDeployerAdapter.process(MainDeployerAdapter.java:117)
at org.jboss.system.server.profileservice.repository.ProfileDeployAction.install(ProfileDeployAction.java:70)
at org.jboss.system.server.profileservice.repository.AbstractProfileAction.install(AbstractProfileAction.java:53)
at org.jboss.system.server.profileservice.repository.AbstractProfileService.install(AbstractProfileService.java:403)
at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1652)
at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:938)
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:988)
at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:778)
at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:543)
at org.jboss.system.server.profileservice.repository.AbstractProfileService.registerProfile(AbstractProfileService.java:308)
at org.jboss.system.server.profileservice.ProfileServiceBootstrap.start(ProfileServiceBootstrap.java:256)
at org.jboss.bootstrap.AbstractServerImpl.start(AbstractServerImpl.java:461)
at org.jboss.Main.boot(Main.java:229)
</code>```

Here are the Spring libraries I'm using, all versions outside of spring-data-commons-core.jar corresponding to the Hopper-SR10 release train from the Spring.io site. All are verified to be on the classpath

```<code>        <!-- New Spring, Spring Data, Spring JPA, Spring ORM Libs-->
    <pathelement location="${compile.lib}/spring-core-4.2.9.RELEASE.jar"/>
    <pathelement location="${compile.lib}/spring-data-jpa-1.10.10.RELEASE.jar"/>
    <pathelement location="${compile.lib}/spring-data-commons-1.12.10.RELEASE.jar"/>
    <pathelement location="${compile.lib}/spring-orm-4.2.9.RELEASE.jar"/>
    <pathelement location="${compile.lib}/spring-aop-4.2.9.RELEASE.jar"/>
    <pathelement location="${compile.lib}/spring-aspects-4.2.9.RELEASE.jar"/>
    <pathelement location="${compile.lib}/spring-jdbc-4.2.9.RELEASE.jar"/>
    <pathelement location="${compile.lib}/spring-beans-4.2.9.RELEASE.jar"/>
    <pathelement location="${compile.lib}/spring-web-4.2.9.RELEASE.jar"/>
    <pathelement location="${compile.lib}/spring-context-4.2.9.RELEASE.jar"/>
    <pathelement location="${compile.lib}/spring-expression-4.2.9.RELEASE.jar"/>
    <pathelement location="${compile.lib}/spring-data-commons-core-1.4.1.RELEASE.jar"/>
</code>```

Here is the Spring configuration xml:

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.2.xsd
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
    http://www.springframework.org/schema/data/repository
    http://www.springframework.org/schema/data/repository/spring-repository.xsd
    http://www.springframework.org/schema/data/jpa
    http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
 ">

    <context:component-scan base-package="com.cc.spring.beans.persistence, com.cc.spring.beans.persistence.repository"/>
    <jpa:repositories base-package="com.cc.spring.beans.persistence.repository"/>

</beans>
</code>```

Previous Stack Overflow posts have mentioned that it can be due to incompatible spring Data jar files, but again I used the Spring release train to avoid that very situation. I have used different versions of the spring-data xsd schema in the xml file with no success. I have removed and added the spring repository xsd schema. Any and all ideas will be very appreciated in moving forward.

答:
The issue is solved, it boiled down to digging into the error rather than just randomly trying answers to similar questions. It couldn't find the XML attribute group "repository:auditing-attributes". I then dug into the jar file for Spring Data Commons 1.12.10 and found that it contained spring-repository-1.8.xsd. I specified that version in the xml, cycpersistenance.xml, and it worked.

Look at the xsd to see where it is being referenced and where the error was coming from: http://www.springframework.org/schema/data/jpa/spring-jpa.xsd

```<code><xsd:complexType>
<xsd:attributeGroup ref="repository:auditing-attributes"/>
</xsd:complexType>
</code>```

And then the definition found here in http://www.springframework.org/schema/data/repository/spring-repository-1.8.xsd. It is under the complex group "repository

Body:
Getting the Spring Data library, specifically Spring Repositories, into a Java legacy application(Java 1.6). The legacy application is using an Ant build as well and I am getting the following error when the Spring ApplicationContext is being loaded.

org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 43 in XML document from ServletContext resource [/WEB-INF/spring/beans/cycpersistence-beans.xml] is invalid; nested exception is org.xml.sax.SAXParseException: src-resolve: Cannot resolve the name 'repository:auditing-attributes' to a(n) 'attribute group' component.
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:399)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:399)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:612)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:513)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3910)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4389)
at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeployInternal(TomcatDeployment.java:313)
at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeploy(TomcatDeployment.java:145)
at org.jboss.web.deployers.AbstractWarDeployment.start(AbstractWarDeployment.java:461)
at org.jboss.web.deployers.WebModule.startModule(WebModule.java:122)
at org.jboss.web.deployers.WebModule.start(WebModule.java:97)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:157)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:96)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:668)
at org.jboss.system.microcontainer.ServiceProxy.invoke(ServiceProxy.java:206)
at com.sun.proxy.$Proxy38.start(Unknown Source)
at org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:42)
at org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:37)
at org.jboss.dependency.plugins.action.SimpleControllerContextAction.simpleInstallAction(SimpleControllerContextAction.java:62)
at org.jboss.dependency.plugins.action.AccessControllerContextAction.install(AccessControllerContextAction.java:71)
at org.jboss.dependency.plugins.AbstractControllerContextActions.install(AbstractControllerContextActions.java:51)
at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
at org.jboss.system.microcontainer.ServiceControllerContext.install(ServiceControllerContext.java:297)
at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1652)
at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:938)
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:988)
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:826)
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:556)
at org.jboss.system.ServiceController.doChange(ServiceController.java:688)
at org.jboss.system.ServiceController.start(ServiceController.java:460)
at org.jboss.system.deployers.ServiceDeployer.start(ServiceDeployer.java:163)
at org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:99)
at org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:46)
at org.jboss.deployers.spi.deployer.helpers.AbstractSimpleRealDeployer.internalDeploy(AbstractSimpleRealDeployer.java:62)
at org.jboss.deployers.spi.deployer.helpers.AbstractRealDeployer.deploy(AbstractRealDeployer.java:55)
at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:179)
at org.jboss.deployers.plugins.deployers.DeployersImpl.doDeploy(DeployersImpl.java:1454)
at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1172)
at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1193)
at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1225)
at org.jboss.deployers.plugins.deployers.DeployersImpl.install(DeployersImpl.java:1113)
at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1652)
at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:938)
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:988)
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:826)
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:556)
at org.jboss.deployers.plugins.deployers.DeployersImpl.process(DeployersImpl.java:789)
at org.jboss.deployers.plugins.main.MainDeployerImpl.process(MainDeployerImpl.java:699)
at org.jboss.system.server.profileservice.repository.MainDeployerAdapter.process(MainDeployerAdapter.java:117)
at org.jboss.system.server.profileservice.repository.ProfileDeployAction.install(ProfileDeployAction.java:70)
at org.jboss.system.server.profileservice.repository.AbstractProfileAction.install(AbstractProfileAction.java:53)
at org.jboss.system.server.profileservice.repository.AbstractProfileService.install(AbstractProfileService.java:403)
at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1652)
at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:938)
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:988)
at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:778)
at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:543)
at org.jboss.system.server.profileservice.repository.AbstractProfileService.registerProfile(AbstractProfileService.java:308)
at org.jboss.system.server.profileservice.ProfileServiceBootstrap.start(ProfileServiceBootstrap.java:256)
at org.jboss.bootstrap.AbstractServerImpl.start(AbstractServerImpl.java:461)
at org.jboss.Main.boot(Main.java:229)

Here are the Spring libraries I'm using, all versions outside of spring-data-commons-core.jar corresponding to the Hopper-SR10 release train from the Spring.io site. All are verified to be on the classpath

    <pathelement location="${compile.lib}/spring-core-4.2.9.RELEASE.jar"/>
    <pathelement location="${compile.lib}/spring-data-jpa-1.10.10.RELEASE.jar"/>
    <pathelement location="${compile.lib}/spring-data-commons-1.12.10.RELEASE.jar"/>
    <pathelement location="${compile.lib}/spring-orm-4.2.9.RELEASE.jar"/>
    <pathelement location="${compile.lib}/spring-aop-4.2.9.RELEASE.jar"/>
    <pathelement location="${compile.lib}/spring-aspects-4.2.9.RELEASE.jar"/>
    <pathelement location="${compile.lib}/spring-jdbc-4.2.9.RELEASE.jar"/>
    <pathelement location="${compile.lib}/spring-beans-4.2.9.RELEASE.jar"/>
    <pathelement location="${compile.lib}/spring-web-4.2.9.RELEASE.jar"/>
    <pathelement location="${compile.lib}/spring-context-4.2.9.RELEASE.jar"/>
    <pathelement location="${compile.lib}/spring-expression-4.2.9.RELEASE.jar"/>
    <pathelement location="${compile.lib}/spring-data-commons-core-1.4.1.RELEASE.jar"/>

Here is the Spring configuration xml:

    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.2.xsd
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
    http://www.springframework.org/schema/data/repository
    http://www.springframework.org/schema/data/repository/spring-repository.xsd
    http://www.springframework.org/schema/data/jpa
    http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
 ">

    <context:component-scan base-package="com.cc.spring.beans.persistence, com.cc.spring.beans.persistence.repository"/>
    <jpa:repositories base-package="com.cc.spring.beans.persistence.repository"/>

</beans>

Previous Stack Overflow posts have mentioned that it can be due to incompatible spring Data jar files, but again I used the Spring release train to avoid that very situation. I have used different versions of the spring-data xsd schema in the xml file with no success. I have removed and added the spring repository xsd schema. Any and all ideas will be very appreciated in moving forward.

Body:
The issue is solved, it boiled down to digging into the error rather than just randomly trying answers to similar questions. It couldn't find the XML attribute group "repository:auditing-attributes". I then dug into the jar file for Spring Data Commons 1.12.10 and found that it contained spring-repository-1.8.xsd. I specified that version in the xml, cycpersistenance.xml, and it worked.

Look at the xsd to see where it is being referenced and where the error was coming from: http://www.springframework.org/schema/data/jpa/spring-jpa.xsd

<xsd:complexType>
<xsd:attributeGroup ref="repository:auditing-attributes"/>
</xsd:complexType>

And then the definition found here in http://www.springframework.org/schema/data/repository/spring-repository-1.8.xsd. It is under the complex group "repository


来源: stackexchange

问:
How to handle aggregates relationship in Event Sourcing properly?
When having a somehow "complex" domain model, it's unavoidable to have related entities (that's the sense of aggregate root). But how should I reconstitute relationships from events? Searching by other aggregate id in serialized events is obviously not an option.

I have an idea to use such DB structure (for example). It has aggregates tables with just id and foreign keys, to simplify retrieving all necessary events from different entities. Doesn't this break the ES principles?

答:
DDD says that "rich domain model" consists from entities which handles business logic, and we work with them as they model the domain objects

Yes, and that's still true when you use event sourcing.

So I can imagine i.e. order.addItem(product) method, where OrderItem creating and making relationship with Order and Product.

Aha, no -- not in either approach.  If Order and Product are different aggregates, then order.addItem(product) is not a spelling that you would use.  The order and the product don't share responsibility for the product's state.  Or, put another way, we never nest aggregates roots inside each other.

The usual spelling, per the rules of DDD, would be order.addItem(product.id).  Note this important difference: changing an Order cannot change any of the details of a Product.

It's part of the point: each bit of state in your domain has a single authority responsible for maintaining its consistency.

Note: the spelling order.addItem(product) makes sense for a model where Product is an entity that is not an aggregate root, but instead is subordinate to Order (and more precisely, each Product is associated with exactly one order).

But if Item has many-to-one relationship to Order, shouldn't it contain orderId instead? (Not Order containing list of ItemId). But that would mean it should be Item.AddToOrder(order.Id), which makes not so much sense.

The short answer is that you get different spellings for the methods depending on how you decide to model the data, and which items are responsible for maintaining the integrity of aggregates.

Working backwards - part of the motivation for aggregates at all (rather than just having one large consistency boundary around you entire model) is the idea of concurrent modification of different parts of the model.  Whether or not OrderItem is a separate aggregate from Order is going to depend -- in part -- on how important it is that two different OrderItems can be modified concurrently.

For cases like online shopping carts, that's probably not super important.

For a setting where many parties are trying to modify the same order at the same time, something like

```<code>OrderItem.create(order.id, product.id)
</code>```

Wouldn't be unreasonable.

And still, aggregate root contains other aggregates, and OrderItem in that case is aggregate, not aggregate root or value object.

An aggregate root has responsibility for one aggregate.  That aggregate (which fundamentally is just "state") can conceptually be the current state of multiple entities subordinate to the root, each managing a specific part of the whole.

And if I'm right, aggregate root contains business logic to control inner aggregates, so we still need to build aggregate root which contains other entities in it.

"Inner aggregate" doesn't make sense -- aggregates don't nest.  Entities nest, with the outermost entity playing the role of the aggregate root.

So, how do we build nested entities?

Let's step back, and look at how we typically create a single entity.  We run some query (like getById) to get the State that we had previously saved.

```<code>Factory {
    Entity fromState(currentState) {
        return new (entity);
    }

    State fromEntity(theEntity) {
        return theEntity.getState();
    }
}
</code>```

Nested entities work the same way, with the subordinate entities taking over part of the work.  For an Order, it might look like...

```<code>Factory {
    Order fromState(currentState) {
        List<OrderItem> items = ...

        for (State.Item itemState : currentState.items()) {
            OrderItem orderItem = OrderItem.from(itemState)
            items.add(orderItem)
        }

        return new Order(items);
    }
}

Order {
    State getState() {
        State currentState = State.EMPTY;

        for(OrderItem orderItem : this.items) {
            currentState = currentState.addItemState(orderItem.getState())

        return currentState
    }
}
</code>```

When we use event sourcing, the bit that changes is that we use collections of events instead of state.

```<code>Factory {
    Order fromEvents(history) {

        // The one tricky bit -- the history we will be looking
        // at is a mix of histories from all of the entities that
        // coordinate the changes to the aggregate, so we may need
        // to untangle that.

        Map<OrderItemId, Events> = itemHistories
        for (Event e : history )
            items.put(e.orderItemId, e)

        List<OrderItem> items = ...

        for (Events events: itemHistories.values) {
            OrderItem orderItem = OrderItem.from(events)
            items.add(orderItem)
        }
        return new Order(items);
    }
}

Order {
    List<Event> getEvents () {
        List<Event> events = new List();

        for(OrderItem orderItem : this.items) {
            events.addAll(orderItem.getEvents())
        }
        return events
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
DDD says that "rich domain model" consists from entities which handles business logic, and we work with them as they model the domain objects

Yes, and that's still true when you use event sourcing.

So I can imagine i.e. order.addItem(product) method, where OrderItem creating and making relationship with Order and Product.

Aha, no -- not in either approach.  If Order and Product are different aggregates, then order.addItem(product) is not a spelling that you would use.  The order and the product don't share responsibility for the product's state.  Or, put another way, we never nest aggregates roots inside each other.

The usual spelling, per the rules of DDD, would be order.addItem(product.id).  Note this important difference: changing an Order cannot change any of the details of a Product.

It's part of the point: each bit of state in your domain has a single authority responsible for maintaining its consistency.

Note: the spelling order.addItem(product) makes sense for a model where Product is an entity that is not an aggregate root, but instead is subordinate to Order (and more precisely, each Product is associated with exactly one order).

But if Item has many-to-one relationship to Order, shouldn't it contain orderId instead? (Not Order containing list of ItemId). But that would mean it should be Item.AddToOrder(order.Id), which makes not so much sense.

The short answer is that you get different spellings for the methods depending on how you decide to model the data, and which items are responsible for maintaining the integrity of aggregates.

Working backwards - part of the motivation for aggregates at all (rather than just having one large consistency boundary around you entire model) is the idea of concurrent modification of different parts of the model.  Whether or not OrderItem is a separate aggregate from Order is going to depend -- in part -- on how important it is that two different OrderItems can be modified concurrently.

For cases like online shopping carts, that's probably not super important.

For a setting where many parties are trying to modify the same order at the same time, something like

OrderItem.create(order.id, product.id)

Wouldn't be unreasonable.

And still, aggregate root contains other aggregates, and OrderItem in that case is aggregate, not aggregate root or value object.

An aggregate root has responsibility for one aggregate.  That aggregate (which fundamentally is just "state") can conceptually be the current state of multiple entities subordinate to the root, each managing a specific part of the whole.

And if I'm right, aggregate root contains business logic to control inner aggregates, so we still need to build aggregate root which contains other entities in it.

"Inner aggregate" doesn't make sense -- aggregates don't nest.  Entities nest, with the outermost entity playing the role of the aggregate root.

So, how do we build nested entities?

Let's step back, and look at how we typically create a single entity.  We run some query (like getById) to get the State that we had previously saved.

Factory {
    Entity fromState(currentState) {
        return new (entity);
    }

    State fromEntity(theEntity) {
        return theEntity.getState();
    }
}

Nested entities work the same way, with the subordinate entities taking over part of the work.  For an Order, it might look like...

Factory {
    Order fromState(currentState) {
        List<OrderItem> items = ...

        for (State.Item itemState : currentState.items()) {
            OrderItem orderItem = OrderItem.from(itemState)
            items.add(orderItem)
        }

        return new Order(items);
    }
}

Order {
    State getState() {
        State currentState = State.EMPTY;

        for(OrderItem orderItem : this.items) {
            currentState = currentState.addItemState(orderItem.getState())

        return currentState
    }
}

When we use event sourcing, the bit that changes is that we use collections of events instead of state.

Factory {
    Order fromEvents(history) {

        // The one tricky bit -- the history we will be looking
        // at is a mix of histories from all of the entities that
        // coordinate the changes to the aggregate, so we may need
        // to untangle that.

        Map<OrderItemId, Events> = itemHistories
        for (Event e : history )
            items.put(e.orderItemId, e)

        List<OrderItem> items = ...

        for (Events events: itemHistories.values) {
            OrderItem orderItem = OrderItem.from(events)
            items.add(orderItem)
        }
        return new Order(items);
    }
}

Order {
    List<Event> getEvents () {
        List<Event> events = new List();

        for(OrderItem orderItem : this.items) {
            events.addAll(orderItem.getEvents())
        }
        return events
    }
}

ContentLicense: CC BY-SA 4.0


问:
how to get json data in jquery for dinamic combobox
I have json data in here
Which is obtained from the Propinsi id but I do not understand how to use json data into my combobox, my script in here... please tell me how to correct this</p>

```<code>$(document).ready(function(){
    $('#propinsi').on('change',function(){
        var prop_kode = $('#propinsi').val();
        console.log(prop_kode);
        if (prop_kode == "") {
            $('#kabupaten').prop('disabled', true);
        }
        else {
            $('#kabupaten').prop('disabled', false);
            $.ajax({
                url:"<?=$url; ?>/show_kabupaten",
                type:"POST",
                data: {'prop_kode' : prop_kode},
                dataType: 'html',
                success: function(data){
                    $('#kabupaten').html(data);
                       // $.each(json, function(i, value) {
                            $('#kabupaten').append($('<option>').text('Pilih Kabupaten').attr('value', 'value'));
                            $.each( kabupaten, function( kab_nama, kab_kode ) {
                            alert( kabupaten.kab_nama);
                        });
                    console.log(data);
                },
                error: function(){
                    alert('error .......');
                }
            })
        }
    });
});
</code>```

答:
Something like this?

$('#propinsi').on('change', function() {
  var prop_kode = $('#propinsi').val();

  if (prop_kode == "") {
    $('#kabupaten').prop('disabled', true);
    return;
  }

  $('#kabupaten').prop('disabled', false);

  // This is just because I don't know where to find your json data
  var data = JSON.parse('{"kabupaten":[{"kab_id":"8","prop_kode":"12","kab_kode":"1201","kab_nama":"KABUPATEN NIAS","kab_status":"1","kab_created_by":"1","kab_created_date":"1496631492"},{"kab_id":"9","prop_kode":"12","kab_kode":"1202","kab_nama":"KABUPATEN MANDAILING NATAL","kab_status":"1","kab_created_by":"1","kab_created_date":"1496631518"}]}');

  $("#kabupaten").html("");

  $.each(data.kabupaten, function(i, kab) {
    var id = kab.kab_id;
    var name = kab.kab_nama;
    $("#kabupaten").append('<option value="' + id + '">' + name + '</option>');
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="propinsi">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
</select>

<br>

<select id="kabupaten"></select></code>```

To implement it into your JS, the code below may help.

```<code>// Add this code just below the line $('#kabupaten').prop('disabled', false);
$.ajax({
    url: "<?=$url; ?>/show_kabupaten",
    type: "POST",
    data: {'prop_kode': prop_kode},
    dataType: 'json',
    success: function(data) {
        $("#kabupaten").html("");

        $.each(data.kabupaten, function(i, kab) {
            var id = kab.kab_id;
            var name = kab.kab_nama;
            $("#kabupaten").append('<option value="'+id+'">'+name+'</option>');
        });
    },
    error: function() {
        alert('error .......');
    }
});
</code>```

Body:
I have json data in here
Which is obtained from the Propinsi id but I do not understand how to use json data into my combobox, my script in here... please tell me how to correct this

$(document).ready(function(){
    $('#propinsi').on('change',function(){
        var prop_kode = $('#propinsi').val();
        console.log(prop_kode);
        if (prop_kode == "") {
            $('#kabupaten').prop('disabled', true);
        }
        else {
            $('#kabupaten').prop('disabled', false);
            $.ajax({
                url:"<?=$url; ?>/show_kabupaten",
                type:"POST",
                data: {'prop_kode' : prop_kode},
                dataType: 'html',
                success: function(data){
                    $('#kabupaten').html(data);
                       // $.each(json, function(i, value) {
                            $('#kabupaten').append($('<option>').text('Pilih Kabupaten').attr('value', 'value'));
                            $.each( kabupaten, function( kab_nama, kab_kode ) {
                            alert( kabupaten.kab_nama);
                        });
                    console.log(data);
                },
                error: function(){
                    alert('error .......');
                }
            })
        }
    });
});

Body:
Something like this?

$('#propinsi').on('change', function() {
  var prop_kode = $('#propinsi').val();

  if (prop_kode == "") {
    $('#kabupaten').prop('disabled', true);
    return;
  }

  $('#kabupaten').prop('disabled', false);

  // This is just because I don't know where to find your json data
  var data = JSON.parse('{"kabupaten":[{"kab_id":"8","prop_kode":"12","kab_kode":"1201","kab_nama":"KABUPATEN NIAS","kab_status":"1","kab_created_by":"1","kab_created_date":"1496631492"},{"kab_id":"9","prop_kode":"12","kab_kode":"1202","kab_nama":"KABUPATEN MANDAILING NATAL","kab_status":"1","kab_created_by":"1","kab_created_date":"1496631518"}]}');

  $("#kabupaten").html("");

  $.each(data.kabupaten, function(i, kab) {
    var id = kab.kab_id;
    var name = kab.kab_nama;
    $("#kabupaten").append('<option value="' + id + '">' + name + '</option>');
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="propinsi">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
</select>

<br>

<select id="kabupaten"></select>

To implement it into your JS, the code below may help.

// Add this code just below the line $('#kabupaten').prop('disabled', false);
$.ajax({
    url: "<?=$url; ?>/show_kabupaten",
    type: "POST",
    data: {'prop_kode': prop_kode},
    dataType: 'json',
    success: function(data) {
        $("#kabupaten").html("");

        $.each(data.kabupaten, function(i, kab) {
            var id = kab.kab_id;
            var name = kab.kab_nama;
            $("#kabupaten").append('<option value="'+id+'">'+name+'</option>');
        });
    },
    error: function() {
        alert('error .......');
    }
});


问:
PHP unable to load ZIP module
PHP 7.0.14 (Arch Linux) complains with the following error

```<code> PHP Warning:  PHP Startup: Unable to load dynamic library
 '/usr/lib/php/modules/zip.so' - libzip.so.4: cannot open shared object file: No such file or directory in Unknown on line 0
</code>```

locate libzip.so.4 finds nothing

Looks like I have a newer version of libzip (libzip.so.5)

```<code>$ locate zip.so
/usr/lib/libminizip.so
/usr/lib/libminizip.so.1
/usr/lib/libminizip.so.1.0.0
/usr/lib/libzip.so
/usr/lib/libzip.so.5
/usr/lib/libzip.so.5.0.0
/usr/lib/gnome-vfs-2.0/modules/libgzip.so
/usr/lib/jvm/java-7-openjdk/jre/lib/amd64/libzip.so
/usr/lib/jvm/java-8-openjdk/jre/lib/amd64/libzip.so
/usr/lib/php/modules/zip.so
</code>```

How can I rebuild it in Arch Linux for php-7.0.14 with the new zip lib?

I already have /var/cache/pacman/pkg/php-7.0.14-1-x86_64.pkg.tar.xz

答:
Try this:

```<code>sudo apt-get install php7.0-zip
</code>```

and also install

```<code>sudo apt-get install php7.0-gd
</code>```

Then after restart apache

```<code>sudo /etc/init.d/apache2 restart
</code>```

Title: PHP unable to load ZIP module

Body:
PHP 7.0.14 (Arch Linux) complains with the following error

 PHP Warning:  PHP Startup: Unable to load dynamic library
 '/usr/lib/php/modules/zip.so' - libzip.so.4: cannot open shared object file: No such file or directory in Unknown on line 0

locate libzip.so.4 finds nothing

Looks like I have a newer version of libzip (libzip.so.5)

$ locate zip.so
/usr/lib/libminizip.so
/usr/lib/libminizip.so.1
/usr/lib/libminizip.so.1.0.0
/usr/lib/libzip.so
/usr/lib/libzip.so.5
/usr/lib/libzip.so.5.0.0
/usr/lib/gnome-vfs-2.0/modules/libgzip.so
/usr/lib/jvm/java-7-openjdk/jre/lib/amd64/libzip.so
/usr/lib/jvm/java-8-openjdk/jre/lib/amd64/libzip.so
/usr/lib/php/modules/zip.so

How can I rebuild it in Arch Linux for php-7.0.14 with the new zip lib?

I already have /var/cache/pacman/pkg/php-7.0.14-1-x86_64.pkg.tar.xz

Body:
Try this:

sudo apt-get install php7.0-zip

and also install

sudo apt-get install php7.0-gd

Then after restart apache

sudo /etc/init.d/apache2 restart


问:
C# Cannot implicity convert int[] to int
```<code>public int[] kdPegawai;
if (Convert.ToInt16(comboBoxJumlahPegawai.Text) == 4)
{
    kdPegawai[1] = new int[] { Convert.ToInt16(comboBoxKdPegawai.Text) };
}
</code>```

I need to put value from combobox to kdPegawai array, but keep getting error like this:

cannot implicitly convert int[] to int

答:
You can not assign a whole array to a single value in another array (unless it's a 2D array).

So this line should be changed to:

```<code>kdPegawai[1] = Convert.ToInt16(comboBoxKdPegawai.Text);
</code>```

And you have to initialize array before assigning any value to it.

If you just want to insert one value like you've shown in the code, then you can also do something like this:

```<code>kdPegawai = new int[] { Convert.ToInt16(comboBoxKdPegawai.Text) };
</code>```

Body:
public int[] kdPegawai;
if (Convert.ToInt16(comboBoxJumlahPegawai.Text) == 4)
{
    kdPegawai[1] = new int[] { Convert.ToInt16(comboBoxKdPegawai.Text) };
}

I need to put value from combobox to kdPegawai array, but keep getting error like this:

cannot implicitly convert int[] to int

Body:
You can not assign a whole array to a single value in another array (unless it's a 2D array).

So this line should be changed to:

kdPegawai[1] = Convert.ToInt16(comboBoxKdPegawai.Text);

And you have to initialize array before assigning any value to it.

If you just want to insert one value like you've shown in the code, then you can also do something like this:

kdPegawai = new int[] { Convert.ToInt16(comboBoxKdPegawai.Text) };


问:
Concatenate two values or variables in AngularJS?
I am new with angularJS. and trying to concatenate two variables?

```<code>ng-init = "imgid={{$parent.$index+$index}}"
</code>```

also tried=>

```<code>setImgCounter(post.postImages.length,$parent.$index+$index)
</code>```

here $index=3 and $oarent.$index=3. I want something like 33 but it is showing me 6 . setImgCounter is a function and I want to send $parent.$index+$index as a variable.is there any way to achieve 33 instate of 6.

答:
Try this

```<code>ng-init = "imgid={{$parent.$index+' '+$index}}"
</code>```

Body:
I am new with angularJS. and trying to concatenate two variables?

ng-init = "imgid={{$parent.$index+$index}}"

also tried=>

setImgCounter(post.postImages.length,$parent.$index+$index)

here $index=3 and $oarent.$index=3. I want something like 33 but it is showing me 6 . setImgCounter is a function and I want to send $parent.$index+$index as a variable.is there any way to achieve 33 instate of 6.

Body:
Try this

ng-init = "imgid={{$parent.$index+' '+$index}}"


问:
Conditional group membership with Ansible
I'm trying to assign the group "webadmins" to a directory if the group already exists or set it to group "root" if it doesn't exist.

```<code>- getent:
    database=group
    key=webadmins
    fail_key=no

- debug:
    var=getent_group.webadmins

- file:
    path=/var/www
    state=directory
    owner=root
    group="{{ (getent_group.webadmins == '') | ternary('root', 'webadmins') }}"
    mode=0775
</code>```

The debug task returns this when the group doesn't exist:

```<code>ok: [host] => {
    "getent_group.webadmins": ""
}
</code>```

But the value assigned to the group propriety is always "webadmins", even if the group doesn't exist, so it make my playbook to fail.

The group may exists in AD domain, so I cannot parse /etc/group.

答:
Try this without using the ternary filter:</p>

```<code>{{ 'webadmins' if getent_group.webadmins != '' else 'root' }}
</code>```

Body:
I'm trying to assign the group "webadmins" to a directory if the group already exists or set it to group "root" if it doesn't exist.

- getent:
    database=group
    key=webadmins
    fail_key=no

- debug:
    var=getent_group.webadmins

- file:
    path=/var/www
    state=directory
    owner=root
    group="{{ (getent_group.webadmins == '') | ternary('root', 'webadmins') }}"
    mode=0775

The debug task returns this when the group doesn't exist:

ok: [host] => {
    "getent_group.webadmins": ""
}

But the value assigned to the group propriety is always "webadmins", even if the group doesn't exist, so it make my playbook to fail.

The group may exists in AD domain, so I cannot parse /etc/group.

Body:
Try this without using the ternary filter:

{{ 'webadmins' if getent_group.webadmins != '' else 'root' }}


问:
How to trigger another controller on AngularJS?
I don't want to share data between controller. I just want to trigger controller C when i click either tab A or tab B.

```<code><body ng-controller="MainController">
   <div class="div1" ng-controller="ControllerA" ng-click="changeTab('tab1')">
    ...
   </div>
   <div class="div2" ng-controller="ControllerB" ng-click="changeTab('tab2')">
    ...
   </div>
   <div class="div3" ng-controller="ControllerC">
    ...
   </div>
</body>
</code>```

How this can be done ? Any idea ?

答:
Inject $rootScope on your controller and on changeTab() you can call

$rootScope.$broadcast('key', true);

and on the second controller ControllerC  listen to that like

```<code>$scope.$on('key', function(response) {
   //code you want to run here
});
</code>```

Body:
I don't want to share data between controller. I just want to trigger controller C when i click either tab A or tab B.

    ...

    ...

    ...

How this can be done ? Any idea ?

Body:
Inject $rootScope on your controller and on changeTab() you can call

$rootScope.$broadcast('key', true);

and on the second controller ControllerC  listen to that like

$scope.$on('key', function(response) {
   //code you want to run here
});


问:
How to convert List to Map?
Recently I have conversation with a colleague about what would be the optimal way to convert List to Map in Java and if there any specific benefits of doing so.

I want to know optimal conversion approach and would really appreciate if any one can guide me.

Is this good approach:

```<code>List<Object[]> results;
Map<Integer, String> resultsMap = new HashMap<Integer, String>();
for (Object[] o : results) {
    resultsMap.put((Integer) o[0], (String) o[1]);
}
</code>```

答:
You can leverage the streams API of Java 8.

```<code>public class ListToMap {

  public static void main(String[] args) {
    List<User> items = Arrays.asList(new User("One"), new User("Two"), new User("Three"));

    Map<String, User> map = createHashMap(items);
    for(String key : map.keySet()) {
      System.out.println(key +" : "+map.get(key));
    }
  }

  public static Map<String, User> createHashMap(List<User> items) {
    Map<String, User> map = items.stream().collect(Collectors.toMap(User::getId, Function.identity()));
    return map;
  }
}
</code>```

For more details visit: http://codecramp.com/java-8-streams-api-convert-list-map/

Title: How to convert List to Map?

Body:
Recently I have conversation with a colleague about what would be the optimal way to convert List to Map in Java and if there any specific benefits of doing so.

I want to know optimal conversion approach and would really appreciate if any one can guide me.

Is this good approach:

List<Object[]> results;
Map<Integer, String> resultsMap = new HashMap<Integer, String>();
for (Object[] o : results) {
    resultsMap.put((Integer) o[0], (String) o[1]);
}

Body:
You can leverage the streams API of Java 8.

public class ListToMap {

  public static void main(String[] args) {
    List<User> items = Arrays.asList(new User("One"), new User("Two"), new User("Three"));

    Map<String, User> map = createHashMap(items);
    for(String key : map.keySet()) {
      System.out.println(key +" : "+map.get(key));
    }
  }

  public static Map<String, User> createHashMap(List<User> items) {
    Map<String, User> map = items.stream().collect(Collectors.toMap(User::getId, Function.identity()));
    return map;
  }
}

For more details visit: http://codecramp.com/java-8-streams-api-convert-list-map/


问:
Elasticsearch: No handler for type [text] declared on field
I'm using elasticsearch-5.4.1 and am unable to create a mapping for a custom type on my index.  Basically I'm trying to create a document of a login to a system.

I created an index via curl curl -X PUT http://localhost:9200/userlogin

I can see it with curl -XGET 'localhost:9200/_cat/indices?v&pretty'

To create the mapping (which fails):

```<code>curl -XPUT 'http://localhost:9200/userlogin/_mapping/login' -H 'Content-Type: application/json' -d '
{"properties": {
    "username": {"type": "text"},
    "firstname": {"type": "text"},
    "lastname": {"type": "text"},
    "queue": {"type": "text"},
    "timestamp": {"type": "date"}
}}'
</code>```

Error:

{"error":"MapperParsingException[No handler for type [text] declared
  on field [username]]","status":400}[root@gv-karaf-dev-1
  elasticsearch-5.4.1]

According to https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-put-mapping.html this is exactly how one is supposed to do this from what I understand.
How is test not a thing I can use?  Is there an alternative?

possible duplicate of No handler for type [text] declared on field [title] (python elasticsearch but there was no answer there

答:
Are you sure you are connecting to an Elastic search 5.4 instance? From the error it looks like you are connecting to an older version (2.4 ?).

Try doing the following on your terminal and see if you are really connecting to 5.4 instance.

```<code>curl -XGET 'localhost:9200'
</code>```

Body:
I'm using elasticsearch-5.4.1 and am unable to create a mapping for a custom type on my index.  Basically I'm trying to create a document of a login to a system.

I created an index via curl curl -X PUT http://localhost:9200/userlogin

I can see it with curl -XGET 'localhost:9200/_cat/indices?v&pretty'

To create the mapping (which fails):

curl -XPUT 'http://localhost:9200/userlogin/_mapping/login' -H 'Content-Type: application/json' -d '
{"properties": {
    "username": {"type": "text"},
    "firstname": {"type": "text"},
    "lastname": {"type": "text"},
    "queue": {"type": "text"},
    "timestamp": {"type": "date"}
}}'

Error:

{"error":"MapperParsingException[No handler for type [text] declared
  on field [username]]","status":400}[root@gv-karaf-dev-1
  elasticsearch-5.4.1]

According to https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-put-mapping.html this is exactly how one is supposed to do this from what I understand.
How is test not a thing I can use?  Is there an alternative?

possible duplicate of No handler for type [text] declared on field [title] (python elasticsearch but there was no answer there

Body:
Are you sure you are connecting to an Elastic search 5.4 instance? From the error it looks like you are connecting to an older version (2.4 ?).

Try doing the following on your terminal and see if you are really connecting to 5.4 instance.

curl -XGET 'localhost:9200'


问:
MYSQL Query Error
I'm trying to use this query

```<code>$page_set = mysql_query("SELECT * FROM pages WHERE subject_id =
            {$subject["id"]}", $connection);
</code>```

but i keep getting this error when loading my page .

Database query failed: You have an
  error in your SQL syntax; check the
  manual that corresponds to your MySQL
  server version for the right syntax to
  use near '' at line 1

答:
you're experiencing a quote mismatch. try replacing the double quotes around your array key with single quotes. </p>

```<code>$page_set = mysql_query("SELECT * FROM pages WHERE subject_id =
            {$subject['id']}", $connection);
</code>```

ContentLicense: CC BY-SA 2.5

Title: MYSQL Query Error

Body:
I'm trying to use this query

$page_set = mysql_query("SELECT * FROM pages WHERE subject_id =
            {$subject["id"]}", $connection);

but i keep getting this error when loading my page .

Database query failed: You have an
  error in your SQL syntax; check the
  manual that corresponds to your MySQL
  server version for the right syntax to
  use near '' at line 1

Body:
you're experiencing a quote mismatch. try replacing the double quotes around your array key with single quotes.

$page_set = mysql_query("SELECT * FROM pages WHERE subject_id =
            {$subject['id']}", $connection);


问:
ASP.NET WEB API 2 Works Locally But Not On Production Web Server
I've developed a new WEB API 2 that works great locally, however when I upload the same code to my production server (Arvixe in this case) all I get is a 404 when I call it. I've spent HOURS searching the web, reading forums, etc.. and have been able to find no resolution, so I'm asking here as my last effort.

I'm currently only testing with the default project that gets created when you do New Project > ASP.NET Web API 2 Empty Project in Visual Studio. This creates an empty project with a single ValuesController. You should be able the JSON response by called /api/values, but this doesn't even work.

I'm using Fiddler to test the API locally and on the web server.

```<code>http://localhost:1993/api/values    <--- works great
</code>```

but

```<code>http://api.mydomain.com/api/values   <--- returns 404
</code>```

Note: I created a subdomain "api" in this case, but everything for the code for the API is unchanged from when it was created.

Why in the world does this work locally but not on the production web server?

答:
in your case, since you create a subdomain of 'api', you should try

```<code>http://api.mydomain.com/api/api/values
</code>```

note that if you're using database for the function, you should change the connectionString in your web config

Body:
I've developed a new WEB API 2 that works great locally, however when I upload the same code to my production server (Arvixe in this case) all I get is a 404 when I call it. I've spent HOURS searching the web, reading forums, etc.. and have been able to find no resolution, so I'm asking here as my last effort.

I'm currently only testing with the default project that gets created when you do New Project > ASP.NET Web API 2 Empty Project in Visual Studio. This creates an empty project with a single ValuesController. You should be able the JSON response by called /api/values, but this doesn't even work.

I'm using Fiddler to test the API locally and on the web server.

http://localhost:1993/api/values    <--- works great

but

http://api.mydomain.com/api/values   <--- returns 404

Note: I created a subdomain "api" in this case, but everything for the code for the API is unchanged from when it was created.

Why in the world does this work locally but not on the production web server?

Body:
in your case, since you create a subdomain of 'api', you should try

http://api.mydomain.com/api/api/values

note that if you're using database for the function, you should change the connectionString in your web config


答:
The error message is clear enough, it reminds you that you are trying to assign a integer array to an integer variable. Here we can see that kdPegawai is an integer array and hence any value at a valid index will be an integer(kdPegawai[0]) and you are trying to assign integer array to that causing the error. And Why there is too many conversions? why not do it like the following?

```<code>public int[] kdPegawai;

int intPegawai = 0;
if (int.TryParse(comboBoxJumlahPegawai.Text, out intPegawai) &&  intPegawai == 4)
{
    kdPegawai = new int[] { intPegawai };
}
</code>```

Still I'm confused what is the need for array here, as you are dealing with a single value? why dont you proceed with intPegawai

Title: C# Cannot implicity convert int[] to int

Body:
The error message is clear enough, it reminds you that you are trying to assign a integer array to an integer variable. Here we can see that kdPegawai is an integer array and hence any value at a valid index will be an integer(kdPegawai[0]) and you are trying to assign integer array to that causing the error. And Why there is too many conversions? why not do it like the following?

public int[] kdPegawai;

int intPegawai = 0;
if (int.TryParse(comboBoxJumlahPegawai.Text, out intPegawai) &&  intPegawai == 4)
{
    kdPegawai = new int[] { intPegawai };
}

Still I'm confused what is the need for array here, as you are dealing with a single value? why dont you proceed with intPegawai


问:
Another annoying JavaScript click event issue
```<code>var Home = document.getElementById("home");
var Page = document.getElementById("page");

Home.onclick = function(){Page.innerHTML = "I TYPED A BUNCH OF HTML HERE";};
</code>```

Why is this not working? Nothing happens to the div id="page" when I click the div id="home" element.

Note: This is plain Javascript linked between script tags in a .js document

Edit: I tried using the Event Listener method.

```<code>Home.addEventListener("click", function(){Page.innerHTML = "

ALL THE HTML HERE

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

Still, nothing happens to the div id "page" when the div id "home" is clicked.
Tried running in IE and Chrome.

答:
See the below example it runs perfectly.

But remember the element should be loaded before the event listener is attached.

I would recommend you put the below code at the bottom of the page like after closing the body tag.

Or calling the code on the document onload like so:

```<code>document.addEventListener("load", function(){
    //ATTACH THE CLICK LISTENER HERE
});
</code>```

var Home = document.getElementById("home");
Home.onclick = function(){
  alert("click happened");
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="home">This is the div with id home</div></code>```

Body:
var Home = document.getElementById("home");
var Page = document.getElementById("page");

Home.onclick = function(){Page.innerHTML = "I TYPED A BUNCH OF HTML HERE";};

Why is this not working? Nothing happens to the div id="page" when I click the div id="home" element.

Note: This is plain Javascript linked between script tags in a .js document

Edit: I tried using the Event Listener method.

Home.addEventListener("click", function(){Page.innerHTML = "

ALL THE HTML HERE

";
});

Still, nothing happens to the div id "page" when the div id "home" is clicked.
Tried running in IE and Chrome.

Body:
See the below example it runs perfectly.

But remember the element should be loaded before the event listener is attached.

I would recommend you put the below code at the bottom of the page like after closing the body tag.

Or calling the code on the document onload like so:

document.addEventListener("load", function(){
    //ATTACH THE CLICK LISTENER HERE
});

var Home = document.getElementById("home");
Home.onclick = function(){
  alert("click happened");
};

<div id="home">This is the div with id home</div>


问:
Set form to redirect to current page on submit (SilverStripe/PHP)
I have a signup form for a SilverStripe site that handles everything on the server side. Originally, it was only going to be on the home page, so the setup I have worked fine. But then requirements changed and the form needed to appear on subpages as well. Everything still works except the form always submits to the home page regardless of what I have set for the action parameter.

Originally, the action parameter was "/home/submit." I changed it to accept a variable that returns the current page url and appends "/submit" to it by making a function called Link (see code below). That seems to work and puts the correct url into the action parameter.

But the form still sends the user back to the home page when you hit the submit button, which is not what I want. I want them to stay on the current page that the form is on (be it the home page or any subpage).

I tried getting the current URL and using it for the final line of the submit function like so:

```<code>$current = $this->get_current_page()->Link();
return $this->redirect("$current/?redirected=1#signupform");;
</code>```

But that sends the user to an incorrect url: http://my-site.org/sub-page-title /submit (this is not valid)

Here is the form code which is stored in Page.php:

```<code>  public function Link($action='') {
    $req = Controller::curr()->getRequest();
    $req->setURL(parent::Link($action));
    $url = $req->getURL(TRUE); // get the url back but with querystr intact.
    return $url ;
 }

public function getFirstName() {
    return Session::get('first_name');
}

public function getLastName() {
    return Session::get('last_name');
}

public function getCompanyName() {
    return Session::get('company_name');
}

public function getEmail() {
    return Session::get('email');
}

public function submit(SS_HTTPRequest $request) {
    $firstName = $request->postVar('first_name');
    $lastName  = $request->postVar('last_name');
    $c  = $request->postVar('company_name');
    $email     = $request->postVar('email');

    Session::clear('FORM_ERRORS');
    $errors = [];

    if (empty($email)) {
        array_push($errors, "Email is required");
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        array_push($errors, "Email must be in a valid format. Example: example@domain.com");
    }
    if(empty($firstName)){
        array_push($errors, "Please enter a first name");
    }
    if(empty($lastName)){
        array_push($errors, "Please enter a last name");
    }

    if (empty($errors)) {
        Session::clear('first_name');
        Session::clear('last_name');
        Session::clear('email');
        Session::clear('company_name');

        $comment = new EmailSignUpSubmission();
        $comment->FirstName = $firstName;
        $comment->LastName  = $lastName;
        $comment->CompanyName   = $c;
        $comment->Email     = $email;

        $comment->write();
    } else {
        Session::set($this->formErrorsKey, $errors);
        Session::set('first_name', $firstName);
        Session::set('last_name', $lastName);
        Session::set('company_name', $c);
        Session::set('email', $email);
    }

    return $this->redirect("/?redirected=1#signupform");

}

public function getFormErrors() {
    $errors = Session::get($this->formErrorsKey);
    if ($errors == null || $errors == "") {
        return null;
    } else {
        $errorList = new ArrayList();
        foreach ($errors as $error) {
            $e = new ArrayData(['Text' => $error]);
            $errorList->add($e);
        }
        return $errorList;
    }
}

public function isRedirect() {
    $request = $this->getRequest();
    return $request->getVar('redirected') == "1";
}
</code>```

And here is the HTML form itself:

```<code> <div class="sign-up" id="signupform">
    <div class="form-container">
        <% if $isRedirect && not $getFormErrors %>
            <div class="row">
                <p class="success">
                    Thank you for your submission. You will hear back from us shortly.
                </p>

            </div>
        <% else %>
        <form method="post" action="/$Link/submit">
            <h2 class="text-center white subscribe-hdr">Sign up</h2>
            <% if $getFormErrors %>
                <% loop $getFormErrors %>
                    <p class="error">$Text</p>
                <% end_loop %>
            <% end_if %>
            <p class="white subscribe-body" style="text-align:center;">Sign up for the latest newsletter.</p>

            <div class="form-group">
                <input class="form-control" type="text" name="first_name" value="$getFirstName" placeholder="First Name">
            </div>
            <div class="form-group">
                <input class="form-control" type="text" name="last_name" value="$getLastName" placeholder="Last Name">
            </div>
            <div class="form-group">
                <input class="form-control" type="text" name="company_name" value="$getCompanyName" placeholder="Company">
            </div>
            <div class="form-group">
                <input class="form-control" type="email" name="email" value="$getEmail" placeholder="Email">
            </div>
            <div class="form-group">
                <button class="btn btn-primary btn-block" type="submit"
                        style="width:140px;margin-left:auto;margin-right:auto; float: none; text-align: center">Submit
                </button>
            </div>
        </form>
    <% end_if %>
    </div>
</div>
</code>```

答:
You could always use a hidden field:

```<code><input type="hidden" value="{$AbsoluteLink}" name="redirectURL" />
</code>```

Then use that in your submit method to redirect.

This would be alot easier by extending the Form class because you pass the current Controller object to the form. https://docs.silverstripe.org/en/3/developer_guides/forms/introduction/

Body:
I have a signup form for a SilverStripe site that handles everything on the server side. Originally, it was only going to be on the home page, so the setup I have worked fine. But then requirements changed and the form needed to appear on subpages as well. Everything still works except the form always submits to the home page regardless of what I have set for the action parameter.

Originally, the action parameter was "/home/submit." I changed it to accept a variable that returns the current page url and appends "/submit" to it by making a function called Link (see code below). That seems to work and puts the correct url into the action parameter.

But the form still sends the user back to the home page when you hit the submit button, which is not what I want. I want them to stay on the current page that the form is on (be it the home page or any subpage).

I tried getting the current URL and using it for the final line of the submit function like so:

$current = $this->get_current_page()->Link();
return $this->redirect("$current/?redirected=1#signupform");;

But that sends the user to an incorrect url: http://my-site.org/sub-page-title /submit (this is not valid)

Here is the form code which is stored in Page.php:

  public function Link($action='') {
    $req = Controller::curr()->getRequest();
    $req->setURL(parent::Link($action));
    $url = $req->getURL(TRUE); // get the url back but with querystr intact.
    return $url ;
 }

public function getFirstName() {
    return Session::get('first_name');
}

public function getLastName() {
    return Session::get('last_name');
}

public function getCompanyName() {
    return Session::get('company_name');
}

public function getEmail() {
    return Session::get('email');
}

public function submit(SS_HTTPRequest $request) {
    $firstName = $request->postVar('first_name');
    $lastName  = $request->postVar('last_name');
    $c  = $request->postVar('company_name');
    $email     = $request->postVar('email');

    Session::clear('FORM_ERRORS');
    $errors = [];

    if (empty($email)) {
        array_push($errors, "Email is required");
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        array_push($errors, "Email must be in a valid format. Example: example@domain.com");
    }
    if(empty($firstName)){
        array_push($errors, "Please enter a first name");
    }
    if(empty($lastName)){
        array_push($errors, "Please enter a last name");
    }

    if (empty($errors)) {
        Session::clear('first_name');
        Session::clear('last_name');
        Session::clear('email');
        Session::clear('company_name');

        $comment = new EmailSignUpSubmission();
        $comment->FirstName = $firstName;
        $comment->LastName  = $lastName;
        $comment->CompanyName   = $c;
        $comment->Email     = $email;

        $comment->write();
    } else {
        Session::set($this->formErrorsKey, $errors);
        Session::set('first_name', $firstName);
        Session::set('last_name', $lastName);
        Session::set('company_name', $c);
        Session::set('email', $email);
    }

    return $this->redirect("/?redirected=1#signupform");

}

public function getFormErrors() {
    $errors = Session::get($this->formErrorsKey);
    if ($errors == null || $errors == "") {
        return null;
    } else {
        $errorList = new ArrayList();
        foreach ($errors as $error) {
            $e = new ArrayData(['Text' => $error]);
            $errorList->add($e);
        }
        return $errorList;
    }
}

public function isRedirect() {
    $request = $this->getRequest();
    return $request->getVar('redirected') == "1";
}

And here is the HTML form itself:

        <% if $isRedirect && not $getFormErrors %>

                    Thank you for your submission. You will hear back from us shortly.

        <% else %>
        <form method="post" action="/$Link/submit">

Sign up

            <% if $getFormErrors %>
                <% loop $getFormErrors %>

$Text

                <% end_loop %>
            <% end_if %>

Sign up for the latest newsletter.

                <input class="form-control" type="text" name="first_name" value="$getFirstName" placeholder="First Name">

                <input class="form-control" type="text" name="last_name" value="$getLastName" placeholder="Last Name">

                <input class="form-control" type="text" name="company_name" value="$getCompanyName" placeholder="Company">

                <input class="form-control" type="email" name="email" value="$getEmail" placeholder="Email">

                <button class="btn btn-primary btn-block" type="submit"
                        style="width:140px;margin-left:auto;margin-right:auto; float: none; text-align: center">Submit
                </button>

        </form>
    <% end_if %>

Body:
You could always use a hidden field:

<input type="hidden" value="{$AbsoluteLink}" name="redirectURL" />

Then use that in your submit method to redirect.

This would be alot easier by extending the Form class because you pass the current Controller object to the form. https://docs.silverstripe.org/en/3/developer_guides/forms/introduction/


问:
Is Rails Collection_Select onchange still supported?
I'm trying to create a text field that is visible only when the user selects "Other" from a dropdown menu.

I've done this before with some jQuery and rails "select" but I haven't been able to get it working for "collection_select".

People say that onChange should work but so far I have had no luck.

Collection Select:

```<code>  <%= f.collection_select(:professor, Professor.order(:fullname), :id, :fullname,
     include_blank: false, :prompt => "Other", :onchange => "review_professor();")%>
     <%= f.text_field :professor, class: "class-reveal", style: "display: none;"%>
</code>```

Javascript:

```<code>    review_professor = function() {
     if(this.value == "Other") {
       $('.class-reveal').show();
       $('.class-reveal').val('');
     }else{
       $('.class-reaveal').hide();
       $('.class-reveal').val(this.value);
     }
   });
</code>```

Any ideas of why this is not working or another way I can do this?   Is collection_select still supported?

答:
It still works for collection_select, it just needs to go in the html_options hash, like so:</p>

```<code>{include_blank: false, prompt: "Other"}, {onchange: "review_professor();"}
</code>```

Body:
I'm trying to create a text field that is visible only when the user selects "Other" from a dropdown menu.

I've done this before with some jQuery and rails "select" but I haven't been able to get it working for "collection_select".

People say that onChange should work but so far I have had no luck.

Collection Select:

  <%= f.collection_select(:professor, Professor.order(:fullname), :id, :fullname,
     include_blank: false, :prompt => "Other", :onchange => "review_professor();")%>
     <%= f.text_field :professor, class: "class-reveal", style: "display: none;"%>

Javascript:

    review_professor = function() {
     if(this.value == "Other") {
       $('.class-reveal').show();
       $('.class-reveal').val('');
     }else{
       $('.class-reaveal').hide();
       $('.class-reveal').val(this.value);
     }
   });

Any ideas of why this is not working or another way I can do this?   Is collection_select still supported?

Body:
It still works for collection_select, it just needs to go in the html_options hash, like so:

{include_blank: false, prompt: "Other"}, {onchange: "review_professor();"}


问:
Error remove form with button click in React-Native
i'm new in React-Native. and i want to remove form with button click. but, if i add more than one form and i click remove form with last button remove, then all form remove. whereas, i want if i click button remove in last form, then just last form will remove.

this is my code

```<code>class.....{
 constructor(props) {
    super(props);
    this.state = {
      showMaterial: [],
    };
    this.onAddBtnClick = this.onAddBtnClick.bind(this);
  }
 render(){
  return(
   <Icon name='add' onPress={() => this.onAddBtnClick()}/>

    {this.state.showMaterial.map((input, index)=>{
      return input;
      })
    }
  );
 }

 onAddBtnClick(event) {
    const showMaterial = this.state.showMaterial;
        this.setState({
            showMaterial: showMaterial.concat(
                <List key={showMaterial.length}>
                  <ListItem>
                      <Text >Description</Text>
                      <Icon name='remove' onPress={() => this.onRemove()}/>
                      <Input style={{height: 30}} placeholderTextColor='lightgray' placeholder="Description" multiline={true} onChangeText={(description) => this.setState({description})}/>

                  </ListItem>
              </List>
              )
        });
  }

  onRemove(){
    this.setState({
      showMaterial:this.state.showMaterial.filter((e, i) => !this.state.showMaterial)
    })
  }

}
</code>```

答:
You can try passing the id of the list to remove method</p>

```<code>onAddBtnClick(event) {
    const showMaterial = this.state.showMaterial;
        this.setState({
            showMaterial: showMaterial.concat(
                <List key={showMaterial.length}>
                  <ListItem>
                      <Text >Description</Text>
                      <Icon name='remove' onPress={() => this.onRemove(showMaterial.length-1)}/>
                      <Input style={{height: 30}} placeholderTextColor='lightgray' placeholder="Description" multiline={true} onChangeText={(description) => this.setState({description})}/>

                  </ListItem>
              </List>
              )
        });
  }

  onRemove(idx){
    this.setState({
      showMaterial:this.state.showMaterial.splice(idx,1)
    })
  }
</code>```

Body:
i'm new in React-Native. and i want to remove form with button click. but, if i add more than one form and i click remove form with last button remove, then all form remove. whereas, i want if i click button remove in last form, then just last form will remove.

this is my code

class.....{
 constructor(props) {
    super(props);
    this.state = {
      showMaterial: [],
    };
    this.onAddBtnClick = this.onAddBtnClick.bind(this);
  }
 render(){
  return(
   <Icon name='add' onPress={() => this.onAddBtnClick()}/>

    {this.state.showMaterial.map((input, index)=>{
      return input;
      })
    }
  );
 }

 onAddBtnClick(event) {
    const showMaterial = this.state.showMaterial;
        this.setState({
            showMaterial: showMaterial.concat(
                <List key={showMaterial.length}>
                  <ListItem>
                      <Text >Description</Text>
                      <Icon name='remove' onPress={() => this.onRemove()}/>
                      <Input style={{height: 30}} placeholderTextColor='lightgray' placeholder="Description" multiline={true} onChangeText={(description) => this.setState({description})}/>

                  </ListItem>
              </List>
              )
        });
  }

  onRemove(){
    this.setState({
      showMaterial:this.state.showMaterial.filter((e, i) => !this.state.showMaterial)
    })
  }

}

Body:
You can try passing the id of the list to remove method

onAddBtnClick(event) {
    const showMaterial = this.state.showMaterial;
        this.setState({
            showMaterial: showMaterial.concat(
                <List key={showMaterial.length}>
                  <ListItem>
                      <Text >Description</Text>
                      <Icon name='remove' onPress={() => this.onRemove(showMaterial.length-1)}/>
                      <Input style={{height: 30}} placeholderTextColor='lightgray' placeholder="Description" multiline={true} onChangeText={(description) => this.setState({description})}/>

                  </ListItem>
              </List>
              )
        });
  }

  onRemove(idx){
    this.setState({
      showMaterial:this.state.showMaterial.splice(idx,1)
    })
  }


问:
How to Debug a deadlock in Java using Eclipse
What techniques can one use to debug what appears to be a deadlock in a Java program.
My IDE is Eclipse and I think I've identifid the two deadlocked threads. In the debugger, right-clicking any of the threads in question and selecting suspend suspends the thread and displays the code currently being executed. Attempting step-into or step-over the line question appears to have no effect - the thread state changes to "Stepping" with control never returning to the debugger unless suspend is clicked again.

Thanks

答:
A few minutes ago I stumbled upon this:

http://runnerwhocodes.blogspot.com/2007/10/deadlock-detection-with-eclipse.html

For me it looks like the best approach detect deadlocks (even it would not help in each case, e.g. detecting deadlocks in combination with EMT-Locks).


问:
Localization without the (old or new) Gui Builder?
About localization, I studied the developer guide, section "Localization & Internationalization (L10N & I18N)", at:
https://www.codenameone.com/manual/misc-features.html

and this video:
http://www.codenameone.com/how-do-i---localizetranslate-my-application-apply-i18nl10n-internationalizationlocalization-to-my-app.html

Both of them seems referring to the old gui builder.
I'm writing a new app without using the (old or new) gui builder, so my question is if I can localize my app using the Localization tool inside Codename One Designer.

For example, see this screenshot:

I have two Buttons with the labels "LOGIN-Button" and "SIGNUP-Button", but they are not translated automatically. I wasn't able to use the following line of code, as suggested in the developer guide, because I haven't any reference to "res":

```<code>UIManager.getInstance().setBundle(res.getL10N("l10n", local));
</code>```

I was able to translate my app with the following manual code. Is there any way to use the Localization tool inside Codename One Designer without manual coding?

```<code>// LOCALIZATION
    // Retrive the device language (as an ISO 639 two letter code)
    String local = L10NManager.getInstance().getLanguage();
    Log.p("The device language is: " + local);

    //Creates the bundle that maps strings in the local language
    HashMap EnglishBundle = new HashMap<String, String>();
    EnglishBundle.put("LOGIN-Button", "LOG IN");
    EnglishBundle.put("SIGNUP-Button", "SIGN UP");
    EnglishBundle.put("@rtl", "false");

    HashMap ItalianBudle = new HashMap<String, String>();
    ItalianBudle.put("LOGIN-Button", "ENTRA");
    ItalianBudle.put("SIGNUP-Button", "REGISTRATI");
    ItalianBudle.put("@rtl", "false");

    switch (local) {
        case "it":
            UIManager.getInstance().setBundle(ItalianBudle);
            break;
        default:
            UIManager.getInstance().setBundle(EnglishBundle);
    }
</code>```

答:
The localization tool has nothing to do with the GUI builder. It's a part of the designer tool which also handles theming, multi-image and other features all of which are useful for handcoded apps just as much as visual apps.

The only GUI builder specific capability in that video is auto-generating the keys from the GUI form.

Since localization is just a lookup map you can use properties files and don't have to keep the data within your app source.

Body:
About localization, I studied the developer guide, section "Localization & Internationalization (L10N & I18N)", at:
https://www.codenameone.com/manual/misc-features.html

and this video:
http://www.codenameone.com/how-do-i---localizetranslate-my-application-apply-i18nl10n-internationalizationlocalization-to-my-app.html

Both of them seems referring to the old gui builder.
I'm writing a new app without using the (old or new) gui builder, so my question is if I can localize my app using the Localization tool inside Codename One Designer.

For example, see this screenshot:

I have two Buttons with the labels "LOGIN-Button" and "SIGNUP-Button", but they are not translated automatically. I wasn't able to use the following line of code, as suggested in the developer guide, because I haven't any reference to "res":

UIManager.getInstance().setBundle(res.getL10N("l10n", local));

I was able to translate my app with the following manual code. Is there any way to use the Localization tool inside Codename One Designer without manual coding?

// LOCALIZATION
    // Retrive the device language (as an ISO 639 two letter code)
    String local = L10NManager.getInstance().getLanguage();
    Log.p("The device language is: " + local);

    //Creates the bundle that maps strings in the local language
    HashMap EnglishBundle = new HashMap<String, String>();
    EnglishBundle.put("LOGIN-Button", "LOG IN");
    EnglishBundle.put("SIGNUP-Button", "SIGN UP");
    EnglishBundle.put("@rtl", "false");

    HashMap ItalianBudle = new HashMap<String, String>();
    ItalianBudle.put("LOGIN-Button", "ENTRA");
    ItalianBudle.put("SIGNUP-Button", "REGISTRATI");
    ItalianBudle.put("@rtl", "false");

    switch (local) {
        case "it":
            UIManager.getInstance().setBundle(ItalianBudle);
            break;
        default:
            UIManager.getInstance().setBundle(EnglishBundle);
    }


问:
Pick up lines from a file based on line numbers in another file
I have two files - one contains the addresses (line numbers) and the other one data, like this:

address file:

```<code>2
4
6
7
1
3
5
</code>```

data file

```<code>1.000451451
2.000589214
3.117892278
4.479511994
5.484514874
6.784499874
7.021239396
</code>```

I want to randomize the data file based on the numbers of address files
so I get:

```<code>2.000589214
4.479511994
6.784499874
7.021239396
1.000451451
3.117892278
5.484514874
</code>```

I want to do it either in python or in bash, but didn't yet find any solution.

答:
You can do it, also, within Python, like this example:

```<code>with open("address_file", 'r') as f1, open("data_file", "r") as f2:
    data1 = f1.read().splitlines()
    data2 = f2.read().splitlines()

for k in data1:
    # Handle exceptions if there is any
    try:
        print(data2[int(k)-1])
    except Exception:
        pass
</code>```

Edit: As suggested @heemayl, here is another solution using only one list:

```<code>with open("file1", 'r') as f1, open("file2", 'r') as f2:
    data = f2.read().splitlines()

    for k in f1.read().splitlines():
        print(data[int(k)-1])
</code>```

Both will output:

```<code>2.000589214
4.479511994
6.784499874
7.021239396
1.000451451
3.117892278
5.484514874
</code>```

Body:
I have two files - one contains the addresses (line numbers) and the other one data, like this:

address file:

2
4
6
7
1
3
5

data file

1.000451451
2.000589214
3.117892278
4.479511994
5.484514874
6.784499874
7.021239396

I want to randomize the data file based on the numbers of address files
so I get:

2.000589214
4.479511994
6.784499874
7.021239396
1.000451451
3.117892278
5.484514874

I want to do it either in python or in bash, but didn't yet find any solution.

Body:
You can do it, also, within Python, like this example:

with open("address_file", 'r') as f1, open("data_file", "r") as f2:
    data1 = f1.read().splitlines()
    data2 = f2.read().splitlines()

for k in data1:
    # Handle exceptions if there is any
    try:
        print(data2[int(k)-1])
    except Exception:
        pass

Edit: As suggested @heemayl, here is another solution using only one list:

with open("file1", 'r') as f1, open("file2", 'r') as f2:
    data = f2.read().splitlines()

    for k in f1.read().splitlines():
        print(data[int(k)-1])

Both will output:

2.000589214
4.479511994
6.784499874
7.021239396
1.000451451
3.117892278
5.484514874


问:
detecting native objects with reflection
I am working with a reflection based object translator.

it basically loops through properties of an object, and assigns the values to properties with the same name/type on the translated object.

ObjectA.Name = "Joe"

translates to:

ObjectB.Name = "Joe"

I need to put a special case, for when a property is a custom class such as:

ObjectA.Address

i was hoping i could detect such properties with IsClass flag of PropertyType

```<code>propInfo.PropertyType.IsClass
</code>```

but this flag also appears to return true for string properties.

is there another way i could verify that the property is of a non native type?

答: string is an exception, the only primitive type in .NET which is a reference type. You have to consider this exception in your code so that you check if IsClass is true and type is not the same as System.String.

Body:
I am working with a reflection based object translator.

it basically loops through properties of an object, and assigns the values to properties with the same name/type on the translated object.

ObjectA.Name = "Joe"

translates to:

ObjectB.Name = "Joe"

I need to put a special case, for when a property is a custom class such as:

ObjectA.Address

i was hoping i could detect such properties with IsClass flag of PropertyType

propInfo.PropertyType.IsClass

but this flag also appears to return true for string properties.

is there another way i could verify that the property is of a non native type?


问:
When are the Clojure core.async go-blocks useful?
Since the thread pool running go-blocks is fairly small, it seems that some operations inside go-blocks aren't recommended. For example doing blocking I/O is bad, and doing compute-heavy operations is bad. A few such operations running in go-blocks will hog the entire thread pool, and no other go-blocks would be able to run at all.

What most common scenarios do Clojure programmers use go-blocks for? Is it mainly useful for working with already asynchronous libraries? Transform callback-using libraries/code into a more palatable channel variant? I'll be very interested to see practical examples where go-blocks with parking channel ops are preferable to threads.

答:
Each thread requires a minimum amount of memory (default 1MB on 64-bit linux) for its stack, etc. While several hundred threads may not be a problem on an average computer, several thousand or more may consume a lot of memory (i.e. 1000 threads => 1GB memory). And, these resources are consumed even when the thread is blocked (not running).

Suppose you have a task that is only running 1-10% of the time. Then using regular threads consumes 10x-100x more resources than required. Since go blocks share threads via "parking", you can reduce the thread resources required by 10x-100x.  This is the benefit.

A second benefit is that core.async can be used in ClojureScript and run in the browser.  Since JavaScript (which CLJS compiles into) has only a single thread, core.async allows one to have the illusion of multithreading in the browser even though regular Java threads are not available.


问:
Override bootstrap !important
I just want to get rid of outline in my dropdown list when focus state. See this image

I tried to override bootstrap using !important but not working at all. Just check the dev tools and suddenly see this.

Bootstrap is also using !important tag. So I couldn't override it. I can use id to button and set focus outline to 0 but I have so many dropdowns in my website. Any fix for this kind of situation?

```<code>.bootstrap-select .dropdown-toggle:focus{
   outline: none!important;
}
</code>```

答:
In your HTML, load style.css after you have loaded bootstrap-select.min.css.

In other words, load bootstrap-select.min.css first, then load style.css.

Within the same rule, the property that got defined later on will override the formerly defined property.

Title: Override bootstrap !important

Body:
I just want to get rid of outline in my dropdown list when focus state. See this image

I tried to override bootstrap using !important but not working at all. Just check the dev tools and suddenly see this.

Bootstrap is also using !important tag. So I couldn't override it. I can use id to button and set focus outline to 0 but I have so many dropdowns in my website. Any fix for this kind of situation?

.bootstrap-select .dropdown-toggle:focus{
   outline: none!important;
}


问:
Why doesn't this SQL statement work?
```
SELECT * FROM table1, table2
WHERE table1.user_id = table2.id
AND table1.content = news
AND table1.content_id = 1
```

that wont work. cant u have two "AND" in a sql statement??

//Tomek

答: I liked cmartin's response. Also, you can use more than one AND, if needed.</p>

OwnerDisplayName: Tomek

LastEditorDisplayName: Graeme Perrow

Title: Why doesn't this SQL statement work?

Body:
SELECT * FROM table1, table2
WHERE table1.user_id = table2.id
AND table1.content = news
AND table1.content_id = 1

that wont work. cant u have two "AND" in a sql statement??

//Tomek

OwnerDisplayName: Pat


问:
Difference between 'Stored as InputFormat, OutputFormat' and 'Stored as' in Hive
Issue when executing a show create table and then executing the resulting create table statement if the table is ORC.

Using show create table, you get this:

```<code>STORED AS INPUTFORMAT
  ‘org.apache.hadoop.hive.ql.io.orc.OrcInputFormat’
OUTPUTFORMAT
  ‘org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat’
</code>```

But if you create the table with those clauses, you will then get the casting error when selecting. Error likes:

Failed with exception
  java.io.IOException:java.lang.ClassCastException:
  org.apache.hadoop.hive.ql.io.orc.OrcStruct cannot be cast to
  org.apache.hadoop.io.BinaryComparable

To fix this, just change create table statement to STORED AS ORC

But, as the answer said in the similar question:
What is the difference between 'InputFormat, OutputFormat' & 'Stored as' in Hive? .

I can't figure out the reason.

答:
STORED AS implies 3 things:

SERDE

INPUTFORMAT

OUTPUTFORMAT

You have defined only the last 2, leaving the SERDE to be defined by hive.default.serde

hive.default.serde

Default Value: org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe

Added in: Hive 0.14 with HIVE-5976

The default SerDe Hive will use for storage formats that do not specify a SerDe.

Storage formats that currently do not specify a SerDe include 'TextFile, RcFile'.

Demo

hive.default.serde

```<code>set hive.default.serde;
</code>```

```<code>hive.default.serde=org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe
</code>```

STORED AS ORC

```<code>create table mytable (i int)
stored as orc;

show create table mytable;
</code>```

Note that the SERDE is 'org.apache.hadoop.hive.ql.io.orc.OrcSerde'

```<code>CREATE TABLE `mytable`(
  `i` int)
ROW FORMAT SERDE
  'org.apache.hadoop.hive.ql.io.orc.OrcSerde'
STORED AS INPUTFORMAT
  'org.apache.hadoop.hive.ql.io.orc.OrcInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat'
LOCATION
  'file:/home/cloudera/local_db/mytable'
TBLPROPERTIES (
  'COLUMN_STATS_ACCURATE'='{\"BASIC_STATS\":\"true\"}',
  'numFiles'='0',
  'numRows'='0',
  'rawDataSize'='0',
  'totalSize'='0',
  'transient_lastDdlTime'='1496982059')
</code>```

STORED AS INPUTFORMAT  ... OUTPUTFORMAT ...

```<code>create table mytable2 (i int)
STORED AS
INPUTFORMAT
  'org.apache.hadoop.hive.ql.io.orc.OrcInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat'
;

show create table mytable2
;
</code>```

Note that the SERDE is 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'

```<code>CREATE TABLE `mytable2`(
  `i` int)
ROW FORMAT SERDE
  'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'
STORED AS INPUTFORMAT
  'org.apache.hadoop.hive.ql.io.orc.OrcInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat'
LOCATION
  'file:/home/cloudera/local_db/mytable2'
TBLPROPERTIES (
  'COLUMN_STATS_ACCURATE'='{\"BASIC_STATS\":\"true\"}',
  'numFiles'='0',
  'numRows'='0',
  'rawDataSize'='0',
  'totalSize'='0',
  'transient_lastDdlTime'='1496982426')
</code>```

Body:
Issue when executing a show create table and then executing the resulting create table statement if the table is ORC.

Using show create table, you get this:

STORED AS INPUTFORMAT
  ‘org.apache.hadoop.hive.ql.io.orc.OrcInputFormat’
OUTPUTFORMAT
  ‘org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat’

But if you create the table with those clauses, you will then get the casting error when selecting. Error likes:

Failed with exception
  java.io.IOException:java.lang.ClassCastException:
  org.apache.hadoop.hive.ql.io.orc.OrcStruct cannot be cast to
  org.apache.hadoop.io.BinaryComparable

To fix this, just change create table statement to STORED AS ORC

But, as the answer said in the similar question:
What is the difference between 'InputFormat, OutputFormat' & 'Stored as' in Hive? .

I can't figure out the reason.

Body:
STORED AS implies 3 things:

SERDE

INPUTFORMAT

OUTPUTFORMAT

You have defined only the last 2, leaving the SERDE to be defined by hive.default.serde

hive.default.serde

Default Value: org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe

Added in: Hive 0.14 with HIVE-5976

The default SerDe Hive will use for storage formats that do not specify a SerDe.

Storage formats that currently do not specify a SerDe include 'TextFile, RcFile'.

Demo

hive.default.serde

set hive.default.serde;

hive.default.serde=org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe

STORED AS ORC

create table mytable (i int)
stored as orc;

show create table mytable;

Note that the SERDE is 'org.apache.hadoop.hive.ql.io.orc.OrcSerde'

CREATE TABLE `mytable`(
  `i` int)
ROW FORMAT SERDE
  'org.apache.hadoop.hive.ql.io.orc.OrcSerde'
STORED AS INPUTFORMAT
  'org.apache.hadoop.hive.ql.io.orc.OrcInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat'
LOCATION
  'file:/home/cloudera/local_db/mytable'
TBLPROPERTIES (
  'COLUMN_STATS_ACCURATE'='{\"BASIC_STATS\":\"true\"}',
  'numFiles'='0',
  'numRows'='0',
  'rawDataSize'='0',
  'totalSize'='0',
  'transient_lastDdlTime'='1496982059')

STORED AS INPUTFORMAT  ... OUTPUTFORMAT ...

create table mytable2 (i int)
STORED AS
INPUTFORMAT
  'org.apache.hadoop.hive.ql.io.orc.OrcInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat'
;

show create table mytable2
;

Note that the SERDE is 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'

CREATE TABLE `mytable2`(
  `i` int)
ROW FORMAT SERDE
  'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'
STORED AS INPUTFORMAT
  'org.apache.hadoop.hive.ql.io.orc.OrcInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat'
LOCATION
  'file:/home/cloudera/local_db/mytable2'
TBLPROPERTIES (
  'COLUMN_STATS_ACCURATE'='{\"BASIC_STATS\":\"true\"}',
  'numFiles'='0',
  'numRows'='0',
  'rawDataSize'='0',
  'totalSize'='0',
  'transient_lastDdlTime'='1496982426')