问:
Could not commit Hibernate transaction; nested exception is org.hibernate.Transaction Exception: JDBC commit failed
I am using Windows Azure SQL Server  in my application when i connect to application it shows following error.

```<code>org.springframework.transaction.TransactionSystemException: Could not commit Hibernate transaction; nested exception is org.hibernate.Transaction
Exception: JDBC commit failed
        at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:660)
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754)
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393
)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.interceptor.CustomizableTraceInterceptor.invokeUnderTrace(CustomizableTraceInterceptor.java:256)
        at org.springframework.aop.interceptor.AbstractTraceInterceptor.invoke(AbstractTraceInterceptor.java:110)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:621)
        at com.asman.vote.mypaint.service.UserWorksService$$EnhancerByCGLIB$$803137ef.yesterdayWinner(<generated>)
        at com.asman.vote.mypaint.controller.MainController.yesterdayWinner(MainController.java:102)
        at com.asman.vote.mypaint.controller.MainController$$FastClassByCGLIB$$ff981c3a.invoke(<generated>)
        at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
        at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:688)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
        at org.springframework.aop.interceptor.CustomizableTraceInterceptor.invokeUnderTrace(CustomizableTraceInterceptor.java:256)
        at org.springframework.aop.interceptor.AbstractTraceInterceptor.invoke(AbstractTraceInterceptor.java:110)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:621)
        at com.asman.vote.mypaint.controller.MainController$$EnhancerByCGLIB$$c20ad12a.yesterdayWinner(<generated>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:
426)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:185)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:151)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:269)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
        at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:300)
        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
        at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.TransactionException: JDBC commit failed
        at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:161)
        at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:656)
        ... 53 more
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The connection is closed.
        at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.checkClosed(SQLServerConnection.java:388)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.commit(SQLServerConnection.java:1936)
        at org.hibernate.transaction.JDBCTransaction.commitAndResetAutoCommit(JDBCTransaction.java:170)
        at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:146)
        ... 54 more
</code>```

Hibernate.cfg.xml:

..................

```<code><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
        <property name="hibernate.connection.password">Asman.1234</property>`

        <property name="hibernate.connection.url">jdbc:sqlserver://mzfoe7t5fn.database.windows.net:1433;databaseName=VOTEMYPAINT;encrypt=false;packetSize=10240;loginTimeout=300</property>
        <property name="hibernate.connection.username">SQLAdmin@mzfoe7t5fn</property>
        <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
        <property name="hibernate.search.autoregister_listeners">false</property>
        <property name="hibernate.c3p0.min_size">5</property>

        <mapping class="com.asman.vote.mypaint.to.UserProfile" />
        <mapping class="com.asman.vote.mypaint.to.Purchasedetails" />
        <mapping class="com.asman.vote.mypaint.to.Topics" />
        <mapping class="com.asman.vote.mypaint.to.AgeGroups" />
        <mapping class="com.asman.vote.mypaint.to.Admin" />
        <mapping class="com.asman.vote.mypaint.to.TodaysTopic" />
        <mapping class="com.asman.vote.mypaint.to.UserWorks" />
        <mapping class="com.asman.vote.mypaint.to.Htmlpages" />
    </session-factory>
</hibernate-configuration>
</code>```

Hibernate-context.html:

```<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:p="http://www.springframework.org/schema/p"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">`
<context:property-placeholder location="/WEB-INF/spring.properties" />

    <!-- Enable annotation style of managing transactions -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <!-- Declare the Hibernate SessionFactory for retrieving Hibernate sessions -->
    <!-- See http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/orm/hibernate3/annotation/AnnotationSessionFactoryBean.html -->
    <!-- See http://docs.jboss.org/hibernate/stable/core/api/index.html?org/hibernate/SessionFactory.html -->
    <!-- See http://docs.jboss.org/hibernate/stable/core/api/index.html?org/hibernate/Session.html -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"

                 p:configLocation="${hibernate.config}"
                 p:packagesToScan="com.asman.vote.mypaint"/>
    <!-- p:dataSource-ref="dataSource" -->
    <!-- Declare a datasource that has pooling capabilities--> <!-- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
                destroy-method="close"
                p:driverClass="${app.jdbc.driverClassName}"
                p:jdbcUrl="${app.jdbc.url}"
                p:user="${app.jdbc.username}"
                p:password="${app.jdbc.password}"
                p:acquireIncrement="10"
                p:idleConnectionTestPeriod="60"
                p:maxPoolSize="100000"
                p:maxStatements="100"
                p:minPoolSize="100000" /> --><bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
                p:sessionFactory-ref="sessionFactory" /></beans>
</code>```

applicationContext.xml:

http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.1.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">`

```<code><!-- <context:property-placeholder properties-ref="deployProperties" /> -->

<!-- Activates various annotations to be detected in bean classes -->
<context:annotation-config />

<!-- Scans the classpath for annotated components that will be auto-registered as Spring beans.
 For example @Controller and @Service. Make sure to set the correct base-package -->
<context:component-scan base-package="com.asman.vote.mypaint" />

<!-- Configures the annotation-driven Spring MVC Controller programming model.
Note that, with Spring 3.0, this tag works in Servlet MVC only!  -->
<mvc:annotation-driven />

<!-- Configure the multipart resolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
    p:maxUploadSize="100000000"/>

<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:interceptors>
<bean class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
    <property name="sessionFactory">
        <ref local="sessionFactory" />
    </property>
</bean></mvc:interceptors><!-- Imports logging configuration -->
<import resource="trace-context.xml"/>
<import resource="hibernate-context.xml" />
<bean id="deployProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"
    p:location="/WEB-INF/spring.properties" /></beans>
</code>```

spring-servlet.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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

    <!-- Declare a view resolver -->
    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
            p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="1"/>

</beans>
</code>```

trace-context.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:p="http://www.springframework.org/schema/p"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">`

    <!-- For parsing classes with @Aspect annotation -->
    <aop:aspectj-autoproxy/>

    <bean id="customizableTraceInterceptor" class="com.asman.vote.mypaint.aop.TraceInterceptor"
        p:enterMessage="Entering $[targetClassShortName].$[methodName]($[arguments])"
        p:exitMessage="Leaving $[targetClassShortName].$[methodName](): $[returnValue]"/>

    <aop:config>
      <aop:advisor advice-ref="customizableTraceInterceptor" pointcut="execution(public * com.asman.vote.mypaint.service..*(..))"/>
      <aop:advisor advice-ref="customizableTraceInterceptor" pointcut="execution(public * com.asman.vote.mypaint.controller..*(..))"/>
    </aop:config>

</beans>
</code>```

答:
I have had a similar error, the easiest solution is to add @Transaction with @Transactional(propagation = Propagation.REQUIRES_NEW)

You will not get this error after that and would work perfectly.

Body:
I am using Windows Azure SQL Server  in my application when i connect to application it shows following error.

org.springframework.transaction.TransactionSystemException: Could not commit Hibernate transaction; nested exception is org.hibernate.Transaction
Exception: JDBC commit failed
        at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:660)
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754)
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393
)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.interceptor.CustomizableTraceInterceptor.invokeUnderTrace(CustomizableTraceInterceptor.java:256)
        at org.springframework.aop.interceptor.AbstractTraceInterceptor.invoke(AbstractTraceInterceptor.java:110)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:621)
        at com.asman.vote.mypaint.service.UserWorksService$$EnhancerByCGLIB$$803137ef.yesterdayWinner(<generated>)
        at com.asman.vote.mypaint.controller.MainController.yesterdayWinner(MainController.java:102)
        at com.asman.vote.mypaint.controller.MainController$$FastClassByCGLIB$$ff981c3a.invoke(<generated>)
        at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
        at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:688)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
        at org.springframework.aop.interceptor.CustomizableTraceInterceptor.invokeUnderTrace(CustomizableTraceInterceptor.java:256)
        at org.springframework.aop.interceptor.AbstractTraceInterceptor.invoke(AbstractTraceInterceptor.java:110)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:621)
        at com.asman.vote.mypaint.controller.MainController$$EnhancerByCGLIB$$c20ad12a.yesterdayWinner(<generated>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:
426)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:185)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:151)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:269)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
        at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:300)
        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
        at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.TransactionException: JDBC commit failed
        at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:161)
        at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:656)
        ... 53 more
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The connection is closed.
        at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.checkClosed(SQLServerConnection.java:388)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.commit(SQLServerConnection.java:1936)
        at org.hibernate.transaction.JDBCTransaction.commitAndResetAutoCommit(JDBCTransaction.java:170)
        at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:146)
        ... 54 more

Hibernate.cfg.xml:

..................

<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
        <property name="hibernate.connection.password">Asman.1234</property>`

        <property name="hibernate.connection.url">jdbc:sqlserver://mzfoe7t5fn.database.windows.net:1433;databaseName=VOTEMYPAINT;encrypt=false;packetSize=10240;loginTimeout=300</property>
        <property name="hibernate.connection.username">SQLAdmin@mzfoe7t5fn</property>
        <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
        <property name="hibernate.search.autoregister_listeners">false</property>
        <property name="hibernate.c3p0.min_size">5</property>

        <mapping class="com.asman.vote.mypaint.to.UserProfile" />
        <mapping class="com.asman.vote.mypaint.to.Purchasedetails" />
        <mapping class="com.asman.vote.mypaint.to.Topics" />
        <mapping class="com.asman.vote.mypaint.to.AgeGroups" />
        <mapping class="com.asman.vote.mypaint.to.Admin" />
        <mapping class="com.asman.vote.mypaint.to.TodaysTopic" />
        <mapping class="com.asman.vote.mypaint.to.UserWorks" />
        <mapping class="com.asman.vote.mypaint.to.Htmlpages" />
    </session-factory>
</hibernate-configuration>

Hibernate-context.html:

<?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:p="http://www.springframework.org/schema/p"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">`
<context:property-placeholder location="/WEB-INF/spring.properties" />

    <tx:annotation-driven transaction-manager="transactionManager" />

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"

                 p:configLocation="${hibernate.config}"
                 p:packagesToScan="com.asman.vote.mypaint"/>

     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
                p:sessionFactory-ref="sessionFactory" /></beans>

applicationContext.xml:

http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.1.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">`

<context:annotation-config />

<context:component-scan base-package="com.asman.vote.mypaint" />

<mvc:annotation-driven />

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
    p:maxUploadSize="100000000"/>

<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:interceptors>
<bean class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
    <property name="sessionFactory">
        <ref local="sessionFactory" />
    </property>
</bean></mvc:interceptors>
<import resource="trace-context.xml"/>
<import resource="hibernate-context.xml" />
<bean id="deployProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"
    p:location="/WEB-INF/spring.properties" /></beans>

spring-servlet.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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
            p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="1"/>

</beans>

trace-context.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:p="http://www.springframework.org/schema/p"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">`

    <aop:aspectj-autoproxy/>

    <bean id="customizableTraceInterceptor" class="com.asman.vote.mypaint.aop.TraceInterceptor"
        p:enterMessage="Entering $[targetClassShortName].$[methodName]($[arguments])"
        p:exitMessage="Leaving $[targetClassShortName].$[methodName](): $[returnValue]"/>

    <aop:config>
      <aop:advisor advice-ref="customizableTraceInterceptor" pointcut="execution(public * com.asman.vote.mypaint.service..*(..))"/>
      <aop:advisor advice-ref="customizableTraceInterceptor" pointcut="execution(public * com.asman.vote.mypaint.controller..*(..))"/>
    </aop:config>

</beans>


来源: stackexchange

问:
Should I override hashCode() of Collections?
Given that I some class with various fields in it:

```<code>class MyClass {
    private String s;
    private MySecondClass c;
    private Collection<someInterface> coll;
    // ...

    @Override public int hashCode() {
        // ????
    }
}
</code>```

and of that, I do have various objects which I'd like to store in a HashMap. For that, I need to have the hashCode() of MyClass.

I'll have to go into all fields and respective parent classes recursively to make sure they all implement hashCode() properly, because otherwise hashCode() of MyClass might not take into consideration some values. Is this right?

What do I do with that Collection? Can I always rely on its hashCode() method? Will it take into consideration all child values that might exist in my someInterface object?

I OPENED A SECOND QUESTION regarding the actual problem of uniquely IDing an object here: How do I generate an (almost) unique hash ID for objects?

Clarification:

is there anything more or less unqiue in your class? The String s? Then only use that as hashcode.

MyClass hashCode() of two objects should definitely differ, if any of the values in the coll of one of the objects is changed. HashCode should only return the same value if all fields of two objects store the same values, resursively. Basically, there is some time-consuming calculation going on on a MyClass object. I want to spare this time, if the calculation had already been done with the exact same values some time ago. For this purpose, I'd like to look up in a HashMap, if the result is available already.

Would you be using MyClass in a HashMap as the key or as the value? If the key, you have to override both equals() and hashCode()

Thus, I'm using the hashCode OF MyClass as the key in a HashMap. The value (calculation result) will be something different, like an Integer (simplified).

What do you think equality should mean for multiple collections? Should it depend on element ordering? Should it only depend on the absolute elements that are present?

Wouldn't that depend on the kind of Collection that is stored in coll? Though I guess ordering not really important, no

The response you get from this site is gorgeous. Thank you all

@AlexWien that depends on whether that collection's items are part of the class's definition of equivalence or not.

Yes, yes they are.

答:
For future readers.

Yes, equals and hashCode go hand in hand.

Below shows a typical implementation using a helper library, but it really shows the "hand in hand" nature.  And the helper library from apache keeps things simpler IMHO:

```<code>@Override
public boolean equals(Object o) {
    if (this == o) {
        return true;
    }
    if (o == null || getClass() != o.getClass()) {
        return false;
    }
    MyCustomObject castInput = (MyCustomObject) o;

    boolean returnValue = new org.apache.commons.lang3.builder.EqualsBuilder()
            .append(this.getPropertyOne(), castInput.getPropertyOne())
            .append(this.getPropertyTwo(), castInput.getPropertyTwo())
            .append(this.getPropertyThree(), castInput.getPropertyThree())
            .append(this.getPropertyN(), castInput.getPropertyN())
            .isEquals();

    return returnValue;
}

@Override
public int hashCode() {
    return new org.apache.commons.lang3.builder.HashCodeBuilder(17, 37)
            .append(this.getPropertyOne())
            .append(this.getPropertyTwo())
            .append(this.getPropertyThree())
            .append(this.getPropertyN())
            .toHashCode();
}
</code>```

17, 37 .. those you can pick your own values.

ContentLicense: CC BY-SA 3.0

Body:
Given that I some class with various fields in it:

class MyClass {
    private String s;
    private MySecondClass c;
    private Collection<someInterface> coll;
    // ...

    @Override public int hashCode() {
        // ????
    }
}

and of that, I do have various objects which I'd like to store in a HashMap. For that, I need to have the hashCode() of MyClass.

I'll have to go into all fields and respective parent classes recursively to make sure they all implement hashCode() properly, because otherwise hashCode() of MyClass might not take into consideration some values. Is this right?

What do I do with that Collection? Can I always rely on its hashCode() method? Will it take into consideration all child values that might exist in my someInterface object?

I OPENED A SECOND QUESTION regarding the actual problem of uniquely IDing an object here: How do I generate an (almost) unique hash ID for objects?

Clarification:

is there anything more or less unqiue in your class? The String s? Then only use that as hashcode.

MyClass hashCode() of two objects should definitely differ, if any of the values in the coll of one of the objects is changed. HashCode should only return the same value if all fields of two objects store the same values, resursively. Basically, there is some time-consuming calculation going on on a MyClass object. I want to spare this time, if the calculation had already been done with the exact same values some time ago. For this purpose, I'd like to look up in a HashMap, if the result is available already.

Would you be using MyClass in a HashMap as the key or as the value? If the key, you have to override both equals() and hashCode()

Thus, I'm using the hashCode OF MyClass as the key in a HashMap. The value (calculation result) will be something different, like an Integer (simplified).

What do you think equality should mean for multiple collections? Should it depend on element ordering? Should it only depend on the absolute elements that are present?

Wouldn't that depend on the kind of Collection that is stored in coll? Though I guess ordering not really important, no

The response you get from this site is gorgeous. Thank you all

@AlexWien that depends on whether that collection's items are part of the class's definition of equivalence or not.

Yes, yes they are.

Body:
For future readers.

Yes, equals and hashCode go hand in hand.

Below shows a typical implementation using a helper library, but it really shows the "hand in hand" nature.  And the helper library from apache keeps things simpler IMHO:

@Override
public boolean equals(Object o) {
    if (this == o) {
        return true;
    }
    if (o == null || getClass() != o.getClass()) {
        return false;
    }
    MyCustomObject castInput = (MyCustomObject) o;

    boolean returnValue = new org.apache.commons.lang3.builder.EqualsBuilder()
            .append(this.getPropertyOne(), castInput.getPropertyOne())
            .append(this.getPropertyTwo(), castInput.getPropertyTwo())
            .append(this.getPropertyThree(), castInput.getPropertyThree())
            .append(this.getPropertyN(), castInput.getPropertyN())
            .isEquals();

    return returnValue;
}

@Override
public int hashCode() {
    return new org.apache.commons.lang3.builder.HashCodeBuilder(17, 37)
            .append(this.getPropertyOne())
            .append(this.getPropertyTwo())
            .append(this.getPropertyThree())
            .append(this.getPropertyN())
            .toHashCode();
}

17, 37 .. those you can pick your own values.

ContentLicense: CC BY-SA 4.0


问:
Pass array javascript as param to controller
firstly sorry for my bad english, my problem is, i have  a controller that receive a list of object as param, but when i try sent this list to controller  always receive null.

```<code>    public async Task<ActionResult> MyAction(List<class> object)
    {

        //do stuff
    }
</code>```

my javascript

var array= []

array.push()...
document.location = '/MyAction/Controller?object'JSON.stringify(array)

my controller always receive null```
</div>
</div>
</p>

<p>i alreay tried use ajax, but for some reason ajax call my controler twice, in first call i recieve my list correctly, but in second receive null</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>
       var array =[]
       array.push()//just example

       $.ajax({
            type: 'POST',
            tradicional:true,
            async:true,
            url: '/controller/MyAction',
            data: JSON.stringify({ 'object': array}),
            contentType: 'application/json; charset=utf-8',
            datatype: 'json',
            success: function (result) {
                //if succes then load my View passing array as param
                document.location = '/controller/MyAction?object' + JSON.stringify(array) ;

            },
            error: function (result) {

            }
        });</code>```

答:
i alreay tried use ajax, but for some reason ajax call my controler
  twice

I'm guessing the first call is a POST request done by the lines:

```<code>$.ajax({
    type: 'POST',
</code>```

and the second call is a GET request done by the line:

```<code>  //if succes then load my View passing array as param
  document.location = '/controller/MyAction?object' + JSON.stringify(array) ;
</code>```

Check if this is the case in the "network" tab of your browser's debugger, decide whether you want to use POST or GET, and configure your controller accordingly. This thread may be helpful: asp mvc http get action with object as parameter

Body:
firstly sorry for my bad english, my problem is, i have  a controller that receive a list of object as param, but when i try sent this list to controller  always receive null.

    public async Task<ActionResult> MyAction(List<class> object)
    {

        //do stuff
    }

my javascript

var array= []

array.push()...
document.location = '/MyAction/Controller?object'JSON.stringify(array)

my controller always receive null

i alreay tried use ajax, but for some reason ajax call my controler twice, in first call i recieve my list correctly, but in second receive null

       var array =[]
       array.push()//just example

       $.ajax({
            type: 'POST',
            tradicional:true,
            async:true,
            url: '/controller/MyAction',
            data: JSON.stringify({ 'object': array}),
            contentType: 'application/json; charset=utf-8',
            datatype: 'json',
            success: function (result) {
                //if succes then load my View passing array as param
                document.location = '/controller/MyAction?object' + JSON.stringify(array) ;

            },
            error: function (result) {

            }
        });

Body:
i alreay tried use ajax, but for some reason ajax call my controler
  twice

I'm guessing the first call is a POST request done by the lines:

$.ajax({
    type: 'POST',

and the second call is a GET request done by the line:

  //if succes then load my View passing array as param
  document.location = '/controller/MyAction?object' + JSON.stringify(array) ;

Check if this is the case in the "network" tab of your browser's debugger, decide whether you want to use POST or GET, and configure your controller accordingly. This thread may be helpful: asp mvc http get action with object as parameter


问:
Grouping by date column and applying a function to group by
I tried asking a question earlier, but deleted so I could ask clearer and show what I am trying if it is close.

My sample df is

```<code>    day         a   b
  5/11/19       3   1
  5/11/19       4   6
  5/12/19       1   2
  5/12/19       5   9
  5/13/19      11   14
</code>```

I want to group by the day column and want to have a new df that calculates for both col a and col b the number of values that are < 10 / all values for that day and column ( a or b) as a %. Since there are numerous rows for each day.

I am trying something like

```<code>def calc_(group_df):
result = dict()
result["x"] = group_df[(group_df.x) < 10] / len(group_df.x)
result["y"] = group_df[(group_df.y) < 10] / len(group_df.y)
return pd.Series(result, index=["x", "y"])
</code>```

and then

```<code>df.groupby("day").apply(calc)
</code>```

but I am getting error of

TypeError: Could not operate 163143 with block values unsupported operand type(s) for /: 'str' and 'int'

Am I missing something?

I want my final output

```<code>     day         a   b
  5/11/19       .3  .1
  5/12/19       .5  .9
  5/13/19       .1  .4
</code>```

I want it grouped by the business day and want each business day to show up only once in my final output.

答:
I am not totally sure what you want your final dataframe to look like but it looks like this is something you can do.

Using this dataframe as input:

```<code>       day   a   b
0  5/11/19   3   1
1  5/11/19  11   3
2  5/12/19   5   9
3  5/13/19  11  14

def calc(df):

    len_a_under_10 = (df['a'] < 10).sum() / len(df['a'])
    len_b_under_10 = (df['b'] < 10).sum() / len(df['b'])

    df['a_under_10'] = len_a_under_10
    df['b_under_10'] = len_b_under_10

return df

df.groupby('day').apply(calc)
</code>```

Gives:

```<code>       day   a   b  a_under_10  b_under_10
0  5/11/19   3   1         0.5         1.0
1  5/11/19  11   3         0.5         1.0
2  5/12/19   5   9         1.0         1.0
3  5/13/19  11  14         0.0         0.0
</code>```

Body:
I tried asking a question earlier, but deleted so I could ask clearer and show what I am trying if it is close.

My sample df is

    day         a   b
  5/11/19       3   1
  5/11/19       4   6
  5/12/19       1   2
  5/12/19       5   9
  5/13/19      11   14

I want to group by the day column and want to have a new df that calculates for both col a and col b the number of values that are < 10 / all values for that day and column ( a or b) as a %. Since there are numerous rows for each day.

I am trying something like

def calc_(group_df):
result = dict()
result["x"] = group_df[(group_df.x) < 10] / len(group_df.x)
result["y"] = group_df[(group_df.y) < 10] / len(group_df.y)
return pd.Series(result, index=["x", "y"])

and then

df.groupby("day").apply(calc)

but I am getting error of

TypeError: Could not operate 163143 with block values unsupported operand type(s) for /: 'str' and 'int'

Am I missing something?

I want my final output

     day         a   b
  5/11/19       .3  .1
  5/12/19       .5  .9
  5/13/19       .1  .4

I want it grouped by the business day and want each business day to show up only once in my final output.

Body:
I am not totally sure what you want your final dataframe to look like but it looks like this is something you can do.

Using this dataframe as input:

       day   a   b
0  5/11/19   3   1
1  5/11/19  11   3
2  5/12/19   5   9
3  5/13/19  11  14

def calc(df):

    len_a_under_10 = (df['a'] < 10).sum() / len(df['a'])
    len_b_under_10 = (df['b'] < 10).sum() / len(df['b'])

    df['a_under_10'] = len_a_under_10
    df['b_under_10'] = len_b_under_10

return df

df.groupby('day').apply(calc)

Gives:

       day   a   b  a_under_10  b_under_10
0  5/11/19   3   1         0.5         1.0
1  5/11/19  11   3         0.5         1.0
2  5/12/19   5   9         1.0         1.0
3  5/13/19  11  14         0.0         0.0


问:
Spark - repartition() vs coalesce()
According to Learning Spark

Keep in mind that repartitioning your data is a fairly expensive operation.
  Spark also has an optimized version of repartition() called coalesce() that allows avoiding data movement, but only if you are decreasing the number of RDD partitions.

One difference I get is that with repartition() the number of partitions can be increased/decreased, but with coalesce() the number of partitions can only be decreased.

If the partitions are spread across multiple machines and coalesce() is run, how can it avoid data movement?

答:
For someone who had issues generating a single csv file from PySpark (AWS EMR) as an output and saving it on s3, using repartition helped. The reason being, coalesce cannot do a full shuffle, but repartition can. Essentially, you can increase or decrease the number of partitions using repartition, but can only decrease the number of partitions (but not 1) using coalesce. Here is the code for anyone who is trying to write a csv from AWS EMR to s3:</p>

```<code>df.repartition(1).write.format('csv')\
.option("path", "s3a://my.bucket.name/location")\
.save(header = 'true')
</code>```

Title: Spark - repartition() vs coalesce()

Body:
For someone who had issues generating a single csv file from PySpark (AWS EMR) as an output and saving it on s3, using repartition helped. The reason being, coalesce cannot do a full shuffle, but repartition can. Essentially, you can increase or decrease the number of partitions using repartition, but can only decrease the number of partitions (but not 1) using coalesce. Here is the code for anyone who is trying to write a csv from AWS EMR to s3:

df.repartition(1).write.format('csv')\
.option("path", "s3a://my.bucket.name/location")\
.save(header = 'true')


问:
Getting data back from jinja to Flask?
What I have right now is a list of ingredients displayed which looks like:

```<code>{% block content %}

<form method="POST">
    <h1>DATA</h1>
    {% for c in data %}
    <h1>{{ c.i_id }} {{ c.name }}</h1>
    {% endfor %}
</form>
{% endblock %}
</code>```

What I'm having trouble with is displaying each item as a clickable, to have the user click on one and add it to a DB table "userIngredients" with values u_id and i_id. u_id is already stored on session['u_id'], however, i_id is what I'm trying to retrieve from the clickable items so I can complete the following query on each click: 'INSERT INTO userIngredients VALUES(%s,%s)',(session[u_id],i_id)

```<code>@app.route('/addingredients', methods=['GET','POST'])
def addingredients():
    c = sq.connection.cursor()
    result = c.execute('SELECT * FROM Ingredients')
    data = c.fetchall()
    return render_template('user/addIngredients.html', data=data)
</code>```

答:
Just use regular HTML for this.

```<code><a href="/addingredients/{% session['u_id'] %}/{% c.i_id %}">{{ c.i_id }} {{ c.name }}</a>
</code>```

Clicking this should trigger a response to your endpoint where you can use the following code to add it to the database

@app.route('/addingredients/<user_id>/<ingredient_id>')
def add_ingredients(user_id, ingredient_id):
    # Important to cast the strings here to integers
    # both as protection from SQL injection and to make sure
    # the values are inserted as actual integers
    user_id = int(user_id)
    ingredient_id = int(ingredient_id)
    c = sq.connection.cursor()

    c.execute('INSERT INTO userIngredients VALUES(%s,%s)', (user_id,ingredient_id))

    # Then if you want, you can re-render the template
    result = c.execute('SELECT * FROM Ingredients')
    data = c.fetchall()
    return render_template('user/addIngredients.html', data=data)
```

I would move the rendering to a different endpoint than /addingredients, as the name doesn't really fit with the template. If you can, I'd suggest using either the RESTful /ingredients/add to add a new ingredient and /ingredients to get a list of all ingredients, or /getingredients and /addingredients to do the same thing

Title: Getting data back from jinja to Flask?

Body:
What I have right now is a list of ingredients displayed which looks like:

{% block content %}

<form method="POST">

DATA

    {% for c in data %}

{{ c.i_id }} {{ c.name }}

    {% endfor %}
</form>
{% endblock %}

What I'm having trouble with is displaying each item as a clickable, to have the user click on one and add it to a DB table "userIngredients" with values u_id and i_id. u_id is already stored on session['u_id'], however, i_id is what I'm trying to retrieve from the clickable items so I can complete the following query on each click: 'INSERT INTO userIngredients VALUES(%s,%s)',(session[u_id],i_id)

@app.route('/addingredients', methods=['GET','POST'])
def addingredients():
    c = sq.connection.cursor()
    result = c.execute('SELECT * FROM Ingredients')
    data = c.fetchall()
    return render_template('user/addIngredients.html', data=data)

Body:
Just use regular HTML for this.

<a href="/addingredients/{% session['u_id'] %}/{% c.i_id %}">{{ c.i_id }} {{ c.name }}</a>

Clicking this should trigger a response to your endpoint where you can use the following code to add it to the database

@app.route('/addingredients/<user_id>/<ingredient_id>')
def add_ingredients(user_id, ingredient_id):
    # Important to cast the strings here to integers
    # both as protection from SQL injection and to make sure
    # the values are inserted as actual integers
    user_id = int(user_id)
    ingredient_id = int(ingredient_id)
    c = sq.connection.cursor()

    c.execute('INSERT INTO userIngredients VALUES(%s,%s)', (user_id,ingredient_id))

    # Then if you want, you can re-render the template
    result = c.execute('SELECT * FROM Ingredients')
    data = c.fetchall()
    return render_template('user/addIngredients.html', data=data)

I would move the rendering to a different endpoint than /addingredients, as the name doesn't really fit with the template. If you can, I'd suggest using either the RESTful /ingredients/add to add a new ingredient and /ingredients to get a list of all ingredients, or /getingredients and /addingredients to do the same thing


问:
Using GORM and Postgresql how to set the search_path?
How can I get the current schema from gorm?  Normally it is "SHOW search_path" and is an exec.  Same with setting the current search_path  normally "set search_path to newschema". where new schema can be a single schema name of a series of names.

I attempted db.Exec("show search_path").Find(&result) where result is a []string and I get an empty array.

答:
Setting search_path by executing query like set search_path to newschema is incorrect way of setting, because this will be changed only for the connection that was used to execute the query.

To set it to full set of connection that your application will use you need to provide search_path as an argument to gorm.Open("postgres", "dbname=YourDB search_path=YourSearchPath") with all other connection arguments you gonna to use like dbname or port, user, etc.


问:
Rotation of images
I need to rotate an image by 90, 180, and 270 degrees. I do not need to copy over the image, but rather save the rotated image as its own separate image. So far, my code will rotate the image but will not save it as its own separate file. This is what I have so far.</p>

```<code>import os
import glob
from PIL import Image
os.chdir("./")
for file in glob.glob("*.jpg"):
    image = Image.open(file)
    image_rot_180 = image.rotate(180)
    image_rot_180.save(file.replace(".jpg", "_r180.jpg"))
</code>```

答:
Your code works (I tested it). Here's an improved version, that rotates each image by the 3 mentioned angles and saves it.

code.py:

#!/usr/bin/env python3

import sys
import os
import glob
from PIL import Image

def main():
    img_dir = "./img"
    jpg_ext = ".jpg"
    angles = [90, 180, 270]
    for file_name in glob.iglob(os.path.join(img_dir, "*" + jpg_ext)):
        image = Image.open(file_name)
        for angle in angles:
            rot_suffix = "_r{:03d}{:s}".format(angle, jpg_ext)
            file_name_rot = file_name.replace(jpg_ext, rot_suffix)
            image_rot = image.rotate(angle)
            image_rot.save(file_name_rot)
            print("Rotated: {:s} by {:3d} degrees to {:s}".format(file_name, angle, file_name_rot))

if __name__ == "__main__":
    print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
    main()
    print("\nDone.")
```

<p><strong>Output</strong>:</p>

<blockquote>
<pre class="lang-bat prettyprint-override"><code>[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q056368107]> dir /b .\img
image.jpg
script_file.py

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q056368107]> "e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe" code.py
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32

Rotated: ./img\image.jpg by  90 degrees to ./img\image_r090.jpg
Rotated: ./img\image.jpg by 180 degrees to ./img\image_r180.jpg
Rotated: ./img\image.jpg by 270 degrees to ./img\image_r270.jpg

Done.

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q056368107]> dir /b .\img
image.jpg
image_r090.jpg
image_r180.jpg
image_r270.jpg
script_file.py
</code>```

For more details regarding the operations performed on strings, check [Python 3.Docs]: Format String Syntax.

Title: Rotation of images

Body:
I need to rotate an image by 90, 180, and 270 degrees. I do not need to copy over the image, but rather save the rotated image as its own separate image. So far, my code will rotate the image but will not save it as its own separate file. This is what I have so far.

import os
import glob
from PIL import Image
os.chdir("./")
for file in glob.glob("*.jpg"):
    image = Image.open(file)
    image_rot_180 = image.rotate(180)
    image_rot_180.save(file.replace(".jpg", "_r180.jpg"))

Body:
Your code works (I tested it). Here's an improved version, that rotates each image by the 3 mentioned angles and saves it.

code.py:

#!/usr/bin/env python3

import sys
import os
import glob
from PIL import Image

def main():
    img_dir = "./img"
    jpg_ext = ".jpg"
    angles = [90, 180, 270]
    for file_name in glob.iglob(os.path.join(img_dir, "*" + jpg_ext)):
        image = Image.open(file_name)
        for angle in angles:
            rot_suffix = "_r{:03d}{:s}".format(angle, jpg_ext)
            file_name_rot = file_name.replace(jpg_ext, rot_suffix)
            image_rot = image.rotate(angle)
            image_rot.save(file_name_rot)
            print("Rotated: {:s} by {:3d} degrees to {:s}".format(file_name, angle, file_name_rot))

if __name__ == "__main__":
    print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
    main()
    print("\nDone.")

Output:

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q056368107]> dir /b .\img
image.jpg
script_file.py

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q056368107]> "e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe" code.py
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32

Rotated: ./img\image.jpg by  90 degrees to ./img\image_r090.jpg
Rotated: ./img\image.jpg by 180 degrees to ./img\image_r180.jpg
Rotated: ./img\image.jpg by 270 degrees to ./img\image_r270.jpg

Done.

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q056368107]> dir /b .\img
image.jpg
image_r090.jpg
image_r180.jpg
image_r270.jpg
script_file.py

For more details regarding the operations performed on strings, check [Python 3.Docs]: Format String Syntax.


问:
Stacking column data in excel SQL query
I'm trying to pull data from an access database into an excel table with an SQL query. The problem is that my access database has columns with similar data that I want to combine into one single column. This should give me duplicates of the data in other columns for each entry. I'm not great with SQL but I think I have the basics down.

Database structure that I have:

```<code>Date | Product | Hours 1 | Reason 1 | Hours 2 | Reason 2 |
2019    A          3         "xxx"      5         "yyy"
</code>```

Excel table that I want:

```<code>Date | Product | Hours | Reason |
2019     A         3      "xxx"
2019     A         5      "yyy"
</code>```

Also not sure if it's possible but it would be great to see the source column of each

```<code>Date | Product | Hours | Reason |  Source  |
2019     A         3      "xxx"   "Hours 1"
2019     A         5      "yyy"   "Hours 2"
</code>```

I've tried UNION ALL and got duplicates of the data but not merged into one column. I'm about to try INSERT INTO but sort of lost on how to get each one into the same column

答:
Try this</p>

```<code>SELECT Date, Product, Hours, Reason, Source
  FROM (
SELECT Date, Product, Hours1 Hours, Reason1 Reason, "Hours 1" Source
  FROM Table
UNION
SELECT Date, Product, Hours2, Reason2, "Hours 2"
  FROM Table
)
</code>```

Title: Stacking column data in excel SQL query

Body:
I'm trying to pull data from an access database into an excel table with an SQL query. The problem is that my access database has columns with similar data that I want to combine into one single column. This should give me duplicates of the data in other columns for each entry. I'm not great with SQL but I think I have the basics down.

Database structure that I have:

Date | Product | Hours 1 | Reason 1 | Hours 2 | Reason 2 |
2019    A          3         "xxx"      5         "yyy"

Excel table that I want:

Date | Product | Hours | Reason |
2019     A         3      "xxx"
2019     A         5      "yyy"

Also not sure if it's possible but it would be great to see the source column of each

Date | Product | Hours | Reason |  Source  |
2019     A         3      "xxx"   "Hours 1"
2019     A         5      "yyy"   "Hours 2"

I've tried UNION ALL and got duplicates of the data but not merged into one column. I'm about to try INSERT INTO but sort of lost on how to get each one into the same column

Body:
Try this

SELECT Date, Product, Hours, Reason, Source
  FROM (
SELECT Date, Product, Hours1 Hours, Reason1 Reason, "Hours 1" Source
  FROM Table
UNION
SELECT Date, Product, Hours2, Reason2, "Hours 2"
  FROM Table
)


问:
array of callbacks as Promise?
I am working through some old legacy code dealing with network requests using RPC/YUI library.  It essentially creates  tags to handle network requests.  There are no promises for these.Also, because of IE11 support, we cannot use the native Promise object.  Our build process does not utilize any NPM dependencies, so we cannot use any babel related polyfills.

There is a bug I am working on to fix that the argument ignoreError gets overwritten each time another function calls the same function....obviously!  We have multiple functions calling this network request function library.  Sometimes we want to ignore an error, sometimes we do not.

What is the ideal way to store the multiple requests made and their respective error callbacks so the appropriate item is called?

example:

```<code>var rpcUrl,
rpcRetries,
rpcIgnoreError;

// main function that sets some globals:
rpc: function(url, retries, ignoreError) {
  rpcUrl = url;
  rpcRetries = retries;
  rpcIgnoreError = ignoreError;
  this.doRpc();
},
// calls the YUI library to initialize network script:
doRpc: function() {
  YAHOO.util.Get.script(rpcUrl, {
    onFailure: function() {
      this.callbackError(true);
    },
    timeout: 55000
  });
},
// YUI callback
callbackError: function(retry) {
  if (retry && rpcRetries > 0) {
    rpcRetries = rpcRetries - 1;
    this.doRpc();
  } else {
    // ** how do i know this error handling is for the script which failed?
    if (!rpcIgnoreError) {
      this.populateFormStatus(6);
    }
  }
},
</code>```

now, we have multiple functions calling rpc() such as:

```<code>sendConfig: function() {
  this.rpc(urlForEndpoint, 3, true);
},
sendUser: function() {
  this.rpc(urlForEndpoint, 3, false);
},
sendWidget: function() {
  this.rpc(urlForEndpoint, 3, false);
},
</code>```

I am concerned making an array of callbacks will not guarantee that each item is handled with its respective handler.

I could do something like create a map constant:

```<code>var RPC_ERR_CB = {
    sendConfig: false,
    sendUser: true,
    sendWidget: true
};
</code>```

// and then in the onFailure callback, I can read the src of the script tag:

```<code>...
doRpc: function() {
  YAHOO.util.Get.script(rpcUrl, {
    onFailure: function() {
      var hasCB = Object.keys(RPC_ERR_CB).some(function(item) {
        return arguments[0].src.indexOf(RPC_ERR_CB[item]) <= 0;
     });
      if (hasCB) {
        this.callbackError(true);
      }
    },
    timeout: 55000
  });
},
</code>```

Hope this makes sense...THANKS!

答:
If you're not able to use Promises or ES6 Classes, your options become somewhat limited. If at all possible, I would recommend biting the bullet on getting a Babel transpilation process so you can take advantage of newer features without needing to drop IE11 support.

As it is now though, ideally you don't want to track every request in a global variable somewhere. You can handle each transaction independently by creating each request as a self-contained object:

function RpcRequest (url, retries, ignoreError) {
  this.url = url
  this.retries = retries
  this.ignoreError = ignoreError
}

RpcRequest.prototype.send = function() {
  YAHOO.util.Get.script(this.url, {
    onFailure: function() {
      this.callbackError(true);
    },
    timeout: 55000
  });
}

RpcRequest.prototype.callbackError = function(retry) {
  if (retry && this.retries > 0) {
    this.retries = this.retries - 1;
    this.send();
  } else {
    if (!this.ignoreError) {

      // ...

    }
  }
}

// Somewhere else, initiate a request
var requestOne = new RpcRequest("http://blah", 3, false)
requestOne.send()
```

<p>Something I noted when looking over your code: the code that's creating the request has no idea whether the request succeeded or not. And when you have an error, the calling context doesn't know anything about that error. I took a look at the library you mentioned, and it does appear to have some context that you can pass along.</p>

<p>If I were to rewrite this a little bit, I'd do something like this to bubble the error up to your calling context:</p>

<pre class="lang-js prettyprint-override"><code>RpcRequest.prototype.send = function(callback) {
  YAHOO.util.Get.script(this.url, {
    onFailure: function(context) {
      if( this.ignoreError ) {
        context.ignoredError = true
        callback(null, context);
        return;
      }

      var retError = new Error('Failure doing something!');
      retError.context = context;

      callback(retError);
    },
    onSuccess: function(context) {
      callback(null, context);
    },
    timeout: 55000
  });
}

// Somewhere else in the code...
sendWidget: function() {
  var request = new RpcRequest(urlForEndpoint, 3, false)
  request.send(function(err, result) {
    if( err ) {
      console.error('Failed at doing a widget thing:', err.context);
      // maybe even:
      // throw err;
      return;
    }

    if( result.ignoredError ) {
      console.warn('Ignored an error on the widget thing:', result);
      return;
    }

    console.log('Success on the widget thing!', result);
  })
}
</code>```

Title: array of callbacks as Promise?

Body:
I am working through some old legacy code dealing with network requests using RPC/YUI library.  It essentially creates  tags to handle network requests.  There are no promises for these.Also, because of IE11 support, we cannot use the native Promise object.  Our build process does not utilize any NPM dependencies, so we cannot use any babel related polyfills.

There is a bug I am working on to fix that the argument ignoreError gets overwritten each time another function calls the same function....obviously!  We have multiple functions calling this network request function library.  Sometimes we want to ignore an error, sometimes we do not.

What is the ideal way to store the multiple requests made and their respective error callbacks so the appropriate item is called?

example:

var rpcUrl,
rpcRetries,
rpcIgnoreError;

// main function that sets some globals:
rpc: function(url, retries, ignoreError) {
  rpcUrl = url;
  rpcRetries = retries;
  rpcIgnoreError = ignoreError;
  this.doRpc();
},
// calls the YUI library to initialize network script:
doRpc: function() {
  YAHOO.util.Get.script(rpcUrl, {
    onFailure: function() {
      this.callbackError(true);
    },
    timeout: 55000
  });
},
// YUI callback
callbackError: function(retry) {
  if (retry && rpcRetries > 0) {
    rpcRetries = rpcRetries - 1;
    this.doRpc();
  } else {
    // ** how do i know this error handling is for the script which failed?
    if (!rpcIgnoreError) {
      this.populateFormStatus(6);
    }
  }
},

now, we have multiple functions calling rpc() such as:

sendConfig: function() {
  this.rpc(urlForEndpoint, 3, true);
},
sendUser: function() {
  this.rpc(urlForEndpoint, 3, false);
},
sendWidget: function() {
  this.rpc(urlForEndpoint, 3, false);
},

I am concerned making an array of callbacks will not guarantee that each item is handled with its respective handler.

I could do something like create a map constant:

var RPC_ERR_CB = {
    sendConfig: false,
    sendUser: true,
    sendWidget: true
};

// and then in the onFailure callback, I can read the src of the script tag:

...
doRpc: function() {
  YAHOO.util.Get.script(rpcUrl, {
    onFailure: function() {
      var hasCB = Object.keys(RPC_ERR_CB).some(function(item) {
        return arguments[0].src.indexOf(RPC_ERR_CB[item]) <= 0;
     });
      if (hasCB) {
        this.callbackError(true);
      }
    },
    timeout: 55000
  });
},

Hope this makes sense...THANKS!

Body:
If you're not able to use Promises or ES6 Classes, your options become somewhat limited. If at all possible, I would recommend biting the bullet on getting a Babel transpilation process so you can take advantage of newer features without needing to drop IE11 support.

As it is now though, ideally you don't want to track every request in a global variable somewhere. You can handle each transaction independently by creating each request as a self-contained object:

function RpcRequest (url, retries, ignoreError) {
  this.url = url
  this.retries = retries
  this.ignoreError = ignoreError
}

RpcRequest.prototype.send = function() {
  YAHOO.util.Get.script(this.url, {
    onFailure: function() {
      this.callbackError(true);
    },
    timeout: 55000
  });
}

RpcRequest.prototype.callbackError = function(retry) {
  if (retry && this.retries > 0) {
    this.retries = this.retries - 1;
    this.send();
  } else {
    if (!this.ignoreError) {

      // ...

    }
  }
}

// Somewhere else, initiate a request
var requestOne = new RpcRequest("http://blah", 3, false)
requestOne.send()

Something I noted when looking over your code: the code that's creating the request has no idea whether the request succeeded or not. And when you have an error, the calling context doesn't know anything about that error. I took a look at the library you mentioned, and it does appear to have some context that you can pass along.

If I were to rewrite this a little bit, I'd do something like this to bubble the error up to your calling context:

RpcRequest.prototype.send = function(callback) {
  YAHOO.util.Get.script(this.url, {
    onFailure: function(context) {
      if( this.ignoreError ) {
        context.ignoredError = true
        callback(null, context);
        return;
      }

      var retError = new Error('Failure doing something!');
      retError.context = context;

      callback(retError);
    },
    onSuccess: function(context) {
      callback(null, context);
    },
    timeout: 55000
  });
}

// Somewhere else in the code...
sendWidget: function() {
  var request = new RpcRequest(urlForEndpoint, 3, false)
  request.send(function(err, result) {
    if( err ) {
      console.error('Failed at doing a widget thing:', err.context);
      // maybe even:
      // throw err;
      return;
    }

    if( result.ignoredError ) {
      console.warn('Ignored an error on the widget thing:', result);
      return;
    }

    console.log('Success on the widget thing!', result);
  })
}


问:
How can I properly use < and > operators for 2 vectors of integers when the first element of both are negative?
I'm writing a simple C++17 program that compares two vectors of integers.

e.g., I have two vectors: a represents the number -1, b 25

```<code>std::vector<int> a = {-1};
std::vector<int> b = {2, 5};
if(a < b)       std::cout << "a < b" << std::endl;
else if(a > b)  std::cout << "a > b" << std::endl;
else            std::cout << "a = b" << std::endl;
</code>```

The output produced by the previous piece of code is a < b, and it is correct.
Let us consider now the following example:

```<code>std::vector<int> a = {-1, 9};
std::vector<int> b = {-1, 9, 9};
if(a < b)       std::cout << "a < b" << std::endl;
else if(a > b)  std::cout << "a > b" << std::endl;
else            std::cout << "a = b" << std::endl;
</code>```

Here the output is a < b as well, but since -19 > -199 I would like it to be a > b.

There is a way to solve this? For example, I thought of converting the two vectors into integers and comparing them, but I can't figure out how to do that.

答:
As @MPops commented, using the overloaded operator < with std::vector will do a lexicographical comparison, which is not what you want (a numerical comparison).

Read more in the reference.

You need to do the numerical comparison of two vectors manually, by converting the vector<int> to an int, like this:

```<code>#include <iostream>
#include <vector>

template <typename T> int sgn(T val) {
    return (T(0) < val) - (val < T(0));
}

int vectorToInt(std::vector<int> v) {
  int result = 0;
  if(!v.size()) return result;
  result = result * 10 + v[0];
  for (size_t i = 1; i < v.size(); ++i) {
    result = result * 10 + (v[i] * sgn(v[0]));
  }
  return result;
}

int main(void) {
  std::vector<int> a_vec = {-1, 9};
  int a = vectorToInt(a_vec);
  std::vector<int> b_vec = {-1, 9, 9};
  int b = vectorToInt(b_vec);
  std::cout << "Comparing " << a << " with " << b << std::endl;

  if(a < b)       std::cout << "a < b" << std::endl;
  else if(a > b)  std::cout << "a > b" << std::endl;
  else            std::cout << "a = b" << std::endl;
  return 0;
}
</code>```

Output:

```<code>Comparing -19 with -199
a > b
</code>```

Body:
I'm writing a simple C++17 program that compares two vectors of integers.

e.g., I have two vectors: a represents the number -1, b 25

std::vector<int> a = {-1};
std::vector<int> b = {2, 5};
if(a < b)       std::cout << "a < b" << std::endl;
else if(a > b)  std::cout << "a > b" << std::endl;
else            std::cout << "a = b" << std::endl;

The output produced by the previous piece of code is a < b, and it is correct.
Let us consider now the following example:

std::vector<int> a = {-1, 9};
std::vector<int> b = {-1, 9, 9};
if(a < b)       std::cout << "a < b" << std::endl;
else if(a > b)  std::cout << "a > b" << std::endl;
else            std::cout << "a = b" << std::endl;

Here the output is a < b as well, but since -19 > -199 I would like it to be a > b.

There is a way to solve this? For example, I thought of converting the two vectors into integers and comparing them, but I can't figure out how to do that.

Body:
As @MPops commented, using the overloaded operator < with std::vector will do a lexicographical comparison, which is not what you want (a numerical comparison).

Read more in the reference.

You need to do the numerical comparison of two vectors manually, by converting the vector<int> to an int, like this:

#include <iostream>
#include <vector>

template <typename T> int sgn(T val) {
    return (T(0) < val) - (val < T(0));
}

int vectorToInt(std::vector<int> v) {
  int result = 0;
  if(!v.size()) return result;
  result = result * 10 + v[0];
  for (size_t i = 1; i < v.size(); ++i) {
    result = result * 10 + (v[i] * sgn(v[0]));
  }
  return result;
}

int main(void) {
  std::vector<int> a_vec = {-1, 9};
  int a = vectorToInt(a_vec);
  std::vector<int> b_vec = {-1, 9, 9};
  int b = vectorToInt(b_vec);
  std::cout << "Comparing " << a << " with " << b << std::endl;

  if(a < b)       std::cout << "a < b" << std::endl;
  else if(a > b)  std::cout << "a > b" << std::endl;
  else            std::cout << "a = b" << std::endl;
  return 0;
}

Output:

Comparing -19 with -199
a > b


问:
Changing state even when the react-tabs component is not selected
I'm working with react tabs.

```<code>state = {
    tabIndex: 0
};
</code>```

...

```<code>    <Tabs
                selectedIndex={variable ? variable : tabIndex}
                onSelect={index => this.setState({ tabIndex: index })}
              >
</code>```

If a variable is not pass, the page opens in the tab 0. But some times I want to open in a specific tab, so I pass, for example, the variable = 1.  But I also wants to update the tabIndex, how can I do that?

答: tabIndex in state of the component is updated by you onSelect.

Body:
I'm working with react tabs.

state = {
    tabIndex: 0
};

...

    <Tabs
                selectedIndex={variable ? variable : tabIndex}
                onSelect={index => this.setState({ tabIndex: index })}
              >

If a variable is not pass, the page opens in the tab 0. But some times I want to open in a specific tab, so I pass, for example, the variable = 1.  But I also wants to update the tabIndex, how can I do that?


答:
You can initialize the state with the passed prop (variable in this example) (if passed)

constructor(props) {
  super(props);
  const {
    variable = 0
  } = this.props;

  this.state = {
    tabIndex: variable
  };
}
```

<p>and keep using it as</p>

```<Tabs
    selectedIndex={tabIndex}
    onSelect={index => this.setState({ tabIndex: index })}
>
```

Title: Changing state even when the react-tabs component is not selected

Body:
You can initialize the state with the passed prop (variable in this example) (if passed)

constructor(props) {
  super(props);
  const {
    variable = 0
  } = this.props;

  this.state = {
    tabIndex: variable
  };
}

and keep using it as

<Tabs
    selectedIndex={tabIndex}
    onSelect={index => this.setState({ tabIndex: index })}
>


问:
Version dependency error with setup.py but installs successfully with pip install
I have a project with the following directory structure:

```<code>- module_A
  - a.py
- module_B
  - b.py
requirements.txt
setup.py
</code>```

The project has the dependency on standard python packages, and other git packages. They are listed in requirements.txt.

This projects is successfully installed when I install with pip.

pip install --process-dependency-links -e .
```

<p>But when I try to install with the setup.py with the command</p>

<pre class="lang-sh prettyprint-override"><code>python setup.py install
</code>```

It throws a processing dependencies error.

Installed /private/tmp/py2/.venv/lib/python2.7/site-packages/aspect_based_sentiment_analysis-0.0.4-py2.7.egg
Processing dependencies for aspect-based-sentiment-analysis==0.0.4
error: pandas 0.17.1 is installed but pandas==0.23.4 is required by set(['PyAthena'])
```

<p>Project link</p>

<p>As far as I understand, pip command is equivalent of <code>python setup.py install</code>. It would be great if someone can explain what is going behind the scene.</p>

<p><strong>Update</strong></p>

<p>pip does log the dependency mismatch warning</p>

<pre class="lang-sh prettyprint-override"><code>pyathena 0.2.1 has requirement pandas==0.23.4, but you'll have pandas 0.17.1 which is incompatible.
</code>```

Is there any way package can be installed using setup.py?

答: No, pip install is not the equivalent of python setup.py install; they differ in multiple aspects.  One of the ways they differ is that pip can downgrade packages (uninstall and then reinstall a lower version) in order to meet a version requirement.  Under certain circumstances, pip is even fine with installing conflicting requirements; it'll print out an error message in red, but the command will still exit with status 0.  Inspecting the output from pip install should tell you exactly what is going on.

Body:
I have a project with the following directory structure:

- module_A
  - a.py
- module_B
  - b.py
requirements.txt
setup.py

The project has the dependency on standard python packages, and other git packages. They are listed in requirements.txt.

This projects is successfully installed when I install with pip.

pip install --process-dependency-links -e .

But when I try to install with the setup.py with the command

python setup.py install

It throws a processing dependencies error.

Installed /private/tmp/py2/.venv/lib/python2.7/site-packages/aspect_based_sentiment_analysis-0.0.4-py2.7.egg
Processing dependencies for aspect-based-sentiment-analysis==0.0.4
error: pandas 0.17.1 is installed but pandas==0.23.4 is required by set(['PyAthena'])

Project link

As far as I understand, pip command is equivalent of python setup.py install. It would be great if someone can explain what is going behind the scene.

Update

pip does log the dependency mismatch warning

pyathena 0.2.1 has requirement pandas==0.23.4, but you'll have pandas 0.17.1 which is incompatible.

Is there any way package can be installed using setup.py?


问:
How to avoid useless rerender using useReducer([state,dispatch]) and useContext?
When using multiple useReducers every component using a part of the state rerenders.

```<code>import React, { useContext } from 'react'
import Store from '../store'
import { setName } from "../actions/nameActions"

const Name = () => {
    const { state: { nameReducer: { name } }, dispatch } = useContext(Store)
    const handleInput = ({ target: { value } }) => { dispatch(setName(value)) }
    console.log('useless rerender if other part (not name) of state is changed');
    return <div>
        <p>{name}</p>
        <input value={name} onChange={handleInput} />
    </div>
}

export default Name;
</code>```

How to avoid this useless rerendering?

答:
If useState or useReducer state changes, the component is updated, there is no way to prevent this in the component itself.

Re-render should be prevented in child component that depends on partial state, e.g. by making it pure:

```<code>const NameContainer = () => {
    const { state: { nameReducer: { name } }, dispatch } = useContext(Store)
    return <Name name={name} dispatch={dispatch}/>;
}

const Name = React.memo(({ name, dispatch }) => {
    const handleInput = ({ target: { value } }) => { dispatch(setName(value)) }
    return <div>
        <p>{name}</p>
        <input value={name} onChange={handleInput} />
    </div>
});
</code>```

NameContainer can be rewritten to a HOC and serve the same purpose as Redux connect, to extract needed properties from a store and map them to connected component props.

Body:
When using multiple useReducers every component using a part of the state rerenders.

import React, { useContext } from 'react'
import Store from '../store'
import { setName } from "../actions/nameActions"

const Name = () => {
    const { state: { nameReducer: { name } }, dispatch } = useContext(Store)
    const handleInput = ({ target: { value } }) => { dispatch(setName(value)) }
    console.log('useless rerender if other part (not name) of state is changed');
    return

{name}

        <input value={name} onChange={handleInput} />

}

export default Name;

How to avoid this useless rerendering?

Body:
If useState or useReducer state changes, the component is updated, there is no way to prevent this in the component itself.

Re-render should be prevented in child component that depends on partial state, e.g. by making it pure:

const NameContainer = () => {
    const { state: { nameReducer: { name } }, dispatch } = useContext(Store)
    return <Name name={name} dispatch={dispatch}/>;
}

const Name = React.memo(({ name, dispatch }) => {
    const handleInput = ({ target: { value } }) => { dispatch(setName(value)) }
    return <div>
        <p>{name}</p>
        <input value={name} onChange={handleInput} />
    </div>
});

NameContainer can be rewritten to a HOC and serve the same purpose as Redux connect, to extract needed properties from a store and map them to connected component props.


问:
Validate numbers before and after decimal on key press
I am trying to validate decimal number of 13 digit before and 4 digit after decimal on key press, excluding comma, i.e comma shouldn't be counted as a digit.

Valid Cases

```<code>1,234,567,890,123.1234

1234567890123.1234

123456789012.1234

1234567890123.123

12345.123

1.2

0
</code>```

In Valid Cases

```<code>12345abc.23 // string or special characters  not allowed

1,234,567,890,1231.1234

1,234,567,890,123.12341

12345678901231.1234

1234567890123.12341
</code>```

Current Regex

```<code>^[0-9]{0,13}.?[0-9]{0,4}$
</code>```

Code

```<code> $("#Price").keydown(function (e) {

  var userVal =  $("#Price").val().replace(/,/g, ""); // remove commas

  var validValue = userVal.search(/^[0-9]{0,13}.?[0-9]{0,4}$/) == 0 ? true : false;

  if (userVal !== "" && !validValue && e.keyCode !== 46 && e.keyCode !== 8) {

     e.preventDefault();

  }
  else {

     return true;
  }

});
</code>```

The above regex code works fine in browser console :

```<code>var userVal = "1234567890123.1234";

var validValue = userVal.search(/^[0-9]{0,13}.?[0-9]{0,4}$/) == 0 ? true : false;

console.log(validValue);
</code>```

But using keypress , keydown and keyup  events, user is still able to type 1 extra digit before and after decimal.

How can I prevent user from typing the invalid cases ?

答:
Because keydown is fired before the character is actually typed in the input. See this fiddle where I added outputs: https://jsfiddle.net/n56k0ve3/

```<code><input id='price' type='text' value='0'></input>
<hr>
<span id='userVal'></span>
<br>
<span id='validValue'></span>

$("#price").keydown(function(e) {

  var userVal =  $(this).val().replace(/,/g, ""); // remove commas

  var validValue = userVal.search(/^[0-9]{0,13}\.?[0-9]{0,4}$/) == 0 ? true : false;

  $("#userVal").text(userVal);
  $("#validValue").text(validValue);

  if (userVal !== "" && !validValue && e.keyCode !== 46 && e.keyCode !== 8) {
     e.preventDefault();
  } else {
     return true;
  }
});
</code>```

Instead, use an event which checks the value after the value is changed. keyup works, but doesn't get fired until after the character is displayed in the input, and also fires unnecesilly, e.g., on Shift or Ctrl. Instead, we can use the input event. See this fiddle: https://jsfiddle.net/2b6pc1hu/

```<code>var prevVal = $("#price").val();

$("#price").on('input', function(e) {

  var val = $(this).val();

  var userVal =  val.replace(/,/g, ""); // remove commas

  var validValue = userVal.search(/^[0-9]{0,13}\.?[0-9]{0,4}$/) == 0 ? true : false;

  $("#userVal").text(userVal);
  $("#validValue").text(validValue);

  if (userVal !== "" && !validValue && e.keyCode !== 46 && e.keyCode !== 8) {
     $(this).val(prevVal);
  } else {
    prevVal = val;
  }
});
</code>```

Also, in regular expressions . is a wildcard character. This should be escaped if you want it to only consume a period/decimal.

Body:
I am trying to validate decimal number of 13 digit before and 4 digit after decimal on key press, excluding comma, i.e comma shouldn't be counted as a digit.

Valid Cases

1,234,567,890,123.1234

1234567890123.1234

123456789012.1234

1234567890123.123

12345.123

1.2

0

In Valid Cases

12345abc.23 // string or special characters  not allowed

1,234,567,890,1231.1234

1,234,567,890,123.12341

12345678901231.1234

1234567890123.12341

Current Regex

^[0-9]{0,13}.?[0-9]{0,4}$

Code

 $("#Price").keydown(function (e) {

  var userVal =  $("#Price").val().replace(/,/g, ""); // remove commas

  var validValue = userVal.search(/^[0-9]{0,13}.?[0-9]{0,4}$/) == 0 ? true : false;

  if (userVal !== "" && !validValue && e.keyCode !== 46 && e.keyCode !== 8) {

     e.preventDefault();

  }
  else {

     return true;
  }

});

The above regex code works fine in browser console :

var userVal = "1234567890123.1234";

var validValue = userVal.search(/^[0-9]{0,13}.?[0-9]{0,4}$/) == 0 ? true : false;

console.log(validValue);

But using keypress , keydown and keyup  events, user is still able to type 1 extra digit before and after decimal.

How can I prevent user from typing the invalid cases ?

Body:
Because keydown is fired before the character is actually typed in the input. See this fiddle where I added outputs: https://jsfiddle.net/n56k0ve3/

<input id='price' type='text' value='0'></input>
<hr>
<span id='userVal'></span>
<br>
<span id='validValue'></span>

$("#price").keydown(function(e) {

  var userVal =  $(this).val().replace(/,/g, ""); // remove commas

  var validValue = userVal.search(/^[0-9]{0,13}\.?[0-9]{0,4}$/) == 0 ? true : false;

  $("#userVal").text(userVal);
  $("#validValue").text(validValue);

  if (userVal !== "" && !validValue && e.keyCode !== 46 && e.keyCode !== 8) {
     e.preventDefault();
  } else {
     return true;
  }
});

Instead, use an event which checks the value after the value is changed. keyup works, but doesn't get fired until after the character is displayed in the input, and also fires unnecesilly, e.g., on Shift or Ctrl. Instead, we can use the input event. See this fiddle: https://jsfiddle.net/2b6pc1hu/

var prevVal = $("#price").val();

$("#price").on('input', function(e) {

  var val = $(this).val();

  var userVal =  val.replace(/,/g, ""); // remove commas

  var validValue = userVal.search(/^[0-9]{0,13}\.?[0-9]{0,4}$/) == 0 ? true : false;

  $("#userVal").text(userVal);
  $("#validValue").text(validValue);

  if (userVal !== "" && !validValue && e.keyCode !== 46 && e.keyCode !== 8) {
     $(this).val(prevVal);
  } else {
    prevVal = val;
  }
});

Also, in regular expressions . is a wildcard character. This should be escaped if you want it to only consume a period/decimal.


问:
How to stop Hibernate from eagerly fetching a relationship when it is mapped using a column (referencedColumnName) different than the primary key?
I'm mapping a relationship that does not use the entity's primary key. Using "referencedColumnName" with a column different than the primary key causes hibernate to eagerly fetch the association, by issuing an extra select, even when it's tagged with FetchType.LAZY.

My goal is to make it behave like a regular mapping, meaning it wouldn't issue an extra query every time I need to query the main entity.

I have already tried using @LazyToOne(LazyToOneOption.NO_PROXY), which sorts out the problem, but it does not operate well with Jackson's (JSON parsing library) module "jackson-datatype-hibernate5", which skips hibernate lazy proxies when serializing the results.

Here is a scenario almost like the one I have that causes the problem:
Entities:

@Entity(name = "Book")
@Table(name = "book")
public class Book
    implements Serializable {

    @Id
    @GeneratedValue
    private Long id;

    private String title;

    private String author;

    @NaturalId
    private String isbn;

    //Getters and setters omitted for brevity
}

@Entity(name = "Publication")
@Table(name = "publication")
public class Publication {

    @Id
    @GeneratedValue
    private Long id;

    private String publisher;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(
        name = "isbn",
        referencedColumnName = "isbn"
    )
    private Book book;

    @Column(
        name = "price_in_cents",
        nullable = false
    )
    private Integer priceCents;

    private String currency;

    //Getters and setters omitted for brevity
}
```

<p>Repository (Spring-Data, but you could try directly with the EntityManager):</p>

<pre class="lang-java prettyprint-override"><code>@Repository
public interface PublicationRepository extends JpaReadRepository <Publication, Long>
{
    @Query ("SELECT d FROM Publication d WHERE d.publisher = ?1 ")
    Optional <Publication> findByPublisher (String isbn);
}
</code>```

Thanks

答:
The only way to achieve what you are looking for is by moving the annotatation  @Id to the isbn property.

You can leave the @GeneratedValue on the autoincrement property.

Notes:

1 - Make sure that your equals/hc are following the OID(Object ID) on your domain case the "NaturalId" ISBN.

2 - It will be good to ensure if possible on DB level that your natural ID has unique contraint on it.

Body:
I'm mapping a relationship that does not use the entity's primary key. Using "referencedColumnName" with a column different than the primary key causes hibernate to eagerly fetch the association, by issuing an extra select, even when it's tagged with FetchType.LAZY.

My goal is to make it behave like a regular mapping, meaning it wouldn't issue an extra query every time I need to query the main entity.

I have already tried using @LazyToOne(LazyToOneOption.NO_PROXY), which sorts out the problem, but it does not operate well with Jackson's (JSON parsing library) module "jackson-datatype-hibernate5", which skips hibernate lazy proxies when serializing the results.

Here is a scenario almost like the one I have that causes the problem:
Entities:

@Entity(name = "Book")
@Table(name = "book")
public class Book
    implements Serializable {

    @Id
    @GeneratedValue
    private Long id;

    private String title;

    private String author;

    @NaturalId
    private String isbn;

    //Getters and setters omitted for brevity
}

@Entity(name = "Publication")
@Table(name = "publication")
public class Publication {

    @Id
    @GeneratedValue
    private Long id;

    private String publisher;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(
        name = "isbn",
        referencedColumnName = "isbn"
    )
    private Book book;

    @Column(
        name = "price_in_cents",
        nullable = false
    )
    private Integer priceCents;

    private String currency;

    //Getters and setters omitted for brevity
}

Repository (Spring-Data, but you could try directly with the EntityManager):

@Repository
public interface PublicationRepository extends JpaReadRepository <Publication, Long>
{
    @Query ("SELECT d FROM Publication d WHERE d.publisher = ?1 ")
    Optional <Publication> findByPublisher (String isbn);
}

Thanks


问:
How to move a button background?
I'm having trouble moving a button background. I've identified the class which enables me to move the button text anywhere I like, but I want the  button background to move with it.

Html:

```<code><li class="location"><a class="google_map_link"
href="http://maps.google.com/maps?
q=London&zoom=14&size=512x512&
maptype=roadmap&sensor=false">London</a></li>
</code>```

Tried css:

```<code>.google_map_link {margin-top: 10px;}
</code>```

This works for the text but background and fafa stay in same place??

https://adsler.co.uk/job/holland-and-barratt-london-4-store-colleague

答:
Your background and icon not move because first has fixed height and second has vertical-align

```<code>.location {
...
height: 24px;
}
.single_job_listing .meta .location:before {
...
vertical-align: top;
}
</code>```

disable those styles and they move with text when you add .google_map_link {margin-top: 10px;}

Title: How to move a button background?

Body:
I'm having trouble moving a button background. I've identified the class which enables me to move the button text anywhere I like, but I want the  button background to move with it.

Html:

London

Tried css:

.google_map_link {margin-top: 10px;}

This works for the text but background and fafa stay in same place??

https://adsler.co.uk/job/holland-and-barratt-london-4-store-colleague

Body:
Your background and icon not move because first has fixed height and second has vertical-align

.location {
...
height: 24px;
}
.single_job_listing .meta .location:before {
...
vertical-align: top;
}

disable those styles and they move with text when you add .google_map_link {margin-top: 10px;}


答:
Your exact code works perfectly as-is: given image original.jpg, it flips (rotates 180 degrees) and saves it as original_r180.jpg. The os.chdir is extraneous, since changing to the current directory is a null-op, but it's not wrong.

If you need to do all three, consider this:

import glob
from PIL import Image
os.chdir("./")
for file in glob.glob("*.jpg"):
    for angle in (90, 180, 270):
        image = Image.open(file)
        image_rot = image.rotate(angle)
        image_rot.save(file.replace(".jpg", "_r{0}.jpg".format(angle)))
```

Title: Rotation of images

Body:
I need to rotate an image by 90, 180, and 270 degrees. I do not need to copy over the image, but rather save the rotated image as its own separate image. So far, my code will rotate the image but will not save it as its own separate file. This is what I have so far.

import os
import glob
from PIL import Image
os.chdir("./")
for file in glob.glob("*.jpg"):
    image = Image.open(file)
    image_rot_180 = image.rotate(180)
    image_rot_180.save(file.replace(".jpg", "_r180.jpg"))


问:
calling python3 shows error and calling python starts python2.7
I want to be able to call python3 on my windows 10 machine from cmd.

I've reinstalled Python3.7 to make sure Add to path option was selected, but cannot still call python3 and make the CMD start Python 3.7.

System variables:

Whereas python in CMD stars Python 2.7:

I think I need these because when creating a virtualenv, it is created to use Python 2.7:

```<code># Windows
python -m venv env
</code>```

If I search for Python3.7 I can see the exe file and execute it correctly.

```<code>C:\Users\OGONZALES\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.7
</code>```

答:
Both versions are currently in your path, but Python 2.7 is the first, so Windows will start Python 2.7 if you type python on the command line.

If you have installed the Python launcher (py.exe) you could start Python 3.7 using py -3.7 and Python 2.7 using py -2.

Body:
I want to be able to call python3 on my windows 10 machine from cmd.

I've reinstalled Python3.7 to make sure Add to path option was selected, but cannot still call python3 and make the CMD start Python 3.7.

System variables:

Whereas python in CMD stars Python 2.7:

I think I need these because when creating a virtualenv, it is created to use Python 2.7:

# Windows
python -m venv env

If I search for Python3.7 I can see the exe file and execute it correctly.

C:\Users\OGONZALES\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.7


问:
PHP connect to Google Cloud Sql Instance database with mysqli_connect
I'm new with using Google Cloud SQL and PHP. I'm not able to connect to my Cloud SQL Instance using mysqli_connect. I have been doing lots of research online but I'm still not able to connect. I have stated the variables in the test.php but I don't know how to use them. Please Help

I'm trying to make an android app, where I will have to show data from a database. I'm using method of having php files stored in the cloud storage and my app would send GET or POST request to the php files and the php files would return data from the database. So how can I use php only to connect to the database?

test.php:

```<code><?php
    $public_ip_address = "xx.xxx.xxx.xxx"; // Public IP address of the Instance of Google Cloud SQL
    $user = "root";
    $password = "";
    $instance = "instance_1";
    $database = "db1";

    $conn = mysqli_connect("cloudipad:" + $public_ip_address, $user, $password, $database);
?>
</code>```

Someone help meeeeeeeeeeeeeeeeeeeeeeeeeeeeeee :(

答:
mysqli_connect works fine for me, to connect a PHP app running on Google Cloud App Engine to Cloud SQL...</p>

```<code>// DMBS here means database management system, like Cloud SQL
define('HOSTSPEC', NULL);
define('USERNAME', '[MY_DBMS_USERNAME]');
define('PASSWORD', '[MY_DBMS_PASSWORD]');
define('DATABASE_INSTANCE_NAME', NULL); // Or the name of a database instance within your Cloud SQL instance.
define('PORT', NULL);
define('SOCKET', '/cloudsql/[GOOGLE_CLOUD_PROJECT_NAME]:[GOOGLE_CLOUD_REGION]:[CLOUD_SQL_DBMS_INSTANCE_NAME]');

// Option 1. Object-oriented style...
$mysqli = new mysqli(HOSTSPEC, USERNAME, PASSWORD, DATABASE_INSTANCE_NAME, PORT, SOCKET);

// Option 2. Procedural style...
$DBMSresource = mysqli_connect(HOSTSPEC, USERNAME, PASSWORD, DATABASE_INSTANCE_NAME, PORT, SOCKET);
if (!$DBMSresource)
    // log and handle error, maybe exit...
</code>```

Body:
I'm new with using Google Cloud SQL and PHP. I'm not able to connect to my Cloud SQL Instance using mysqli_connect. I have been doing lots of research online but I'm still not able to connect. I have stated the variables in the test.php but I don't know how to use them. Please Help

I'm trying to make an android app, where I will have to show data from a database. I'm using method of having php files stored in the cloud storage and my app would send GET or POST request to the php files and the php files would return data from the database. So how can I use php only to connect to the database?

test.php:

<?php
    $public_ip_address = "xx.xxx.xxx.xxx"; // Public IP address of the Instance of Google Cloud SQL
    $user = "root";
    $password = "";
    $instance = "instance_1";
    $database = "db1";

    $conn = mysqli_connect("cloudipad:" + $public_ip_address, $user, $password, $database);
?>

Someone help meeeeeeeeeeeeeeeeeeeeeeeeeeeeeee :(

Body:
mysqli_connect works fine for me, to connect a PHP app running on Google Cloud App Engine to Cloud SQL...

// DMBS here means database management system, like Cloud SQL
define('HOSTSPEC', NULL);
define('USERNAME', '[MY_DBMS_USERNAME]');
define('PASSWORD', '[MY_DBMS_PASSWORD]');
define('DATABASE_INSTANCE_NAME', NULL); // Or the name of a database instance within your Cloud SQL instance.
define('PORT', NULL);
define('SOCKET', '/cloudsql/[GOOGLE_CLOUD_PROJECT_NAME]:[GOOGLE_CLOUD_REGION]:[CLOUD_SQL_DBMS_INSTANCE_NAME]');

// Option 1. Object-oriented style...
$mysqli = new mysqli(HOSTSPEC, USERNAME, PASSWORD, DATABASE_INSTANCE_NAME, PORT, SOCKET);

// Option 2. Procedural style...
$DBMSresource = mysqli_connect(HOSTSPEC, USERNAME, PASSWORD, DATABASE_INSTANCE_NAME, PORT, SOCKET);
if (!$DBMSresource)
    // log and handle error, maybe exit...