text:
Q: SpringFramework Java based configuration NoSuchMethodError I am trying to configure a spring framework project from scratch using java class configuration but i can not fix this NoSuchMethodError. May be the problem comes from a wrong mapping but i check everything and it is correct.
III 11, 2016 4:00:17 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:ab' did not find a matching property.
III 11, 2016 4:00:17 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version:        Apache Tomcat/8.0.30
III 11, 2016 4:00:17 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          Dec 1 2015 22:30:46 UTC
III 11, 2016 4:00:17 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number:         8.0.30.0
III 11, 2016 4:00:17 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Windows 10
III 11, 2016 4:00:17 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            10.0
III 11, 2016 4:00:17 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          amd64
III 11, 2016 4:00:17 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             C:\Program Files\Java\jdk1.8.0_66\jre
III 11, 2016 4:00:17 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           1.8.0_66-b18
III 11, 2016 4:00:17 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Oracle Corporation
III 11, 2016 4:00:17 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         D:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
III 11, 2016 4:00:17 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         D:\apache-tomcat-8.0.30
III 11, 2016 4:00:17 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=D:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
III 11, 2016 4:00:17 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=D:\apache-tomcat-8.0.30
III 11, 2016 4:00:17 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=D:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
III 11, 2016 4:00:17 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=D:\apache-tomcat-8.0.30\endorsed
III 11, 2016 4:00:17 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1251
III 11, 2016 4:00:17 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.8.0_66\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_73/bin/server;C:/Program Files/Java/jre1.8.0_73/bin;C:/Program Files/Java/jre1.8.0_73/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files\TortoiseSVN\bin;C:\Program Files\SlikSvn\bin;C:\Program Files\Java\jdk1.8.0_66\bin;C:\Program Files (x86)\Skype\Phone\;C:\Program Files\Git\bin;C:\Users\nikola.nenov\Desktop\eclipse-che-4.0.0-RC12\tools\jre\bin;;C:\Program Files\Docker Toolbox;D:\eclipse;;.
III 11, 2016 4:00:17 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
III 11, 2016 4:00:17 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
III 11, 2016 4:00:17 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
III 11, 2016 4:00:17 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
III 11, 2016 4:00:17 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 410 ms
III 11, 2016 4:00:17 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
III 11, 2016 4:00:17 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.30
III 11, 2016 4:00:19 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
III 11, 2016 4:00:19 PM org.apache.catalina.core.ApplicationContext log
INFO: Spring WebApplicationInitializers detected on classpath: [spitter.config.SpittrWebAppInitializer@2d362710]
III 11, 2016 4:00:19 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
III 11, 2016 4:00:20 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcher'
 WARN | Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation(Ljava/lang/reflect/AnnotatedElement;Ljava/lang/Class;)Ljava/lang/annotation/Annotation;
ERROR | Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation(Ljava/lang/reflect/AnnotatedElement;Ljava/lang/Class;)Ljava/lang/annotation/Annotation;
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1572)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:539)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1231)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1034)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4997)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5289)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoSuchMethodError: org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation(Ljava/lang/reflect/AnnotatedElement;Ljava/lang/Class;)Ljava/lang/annotation/Annotation;
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.createRequestMappingInfo(RequestMappingHandlerMapping.java:203)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.getMappingForMethod(RequestMappingHandlerMapping.java:185)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.getMappingForMethod(RequestMappingHandlerMapping.java:53)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$1.inspect(AbstractHandlerMethodMapping.java:233)
    at org.springframework.core.MethodIntrospector$1.doWith(MethodIntrospector.java:72)
    at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:493)
    at org.springframework.core.MethodIntrospector.selectMethods(MethodIntrospector.java:68)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.detectHandlerMethods(AbstractHandlerMethodMapping.java:229)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.initHandlerMethods(AbstractHandlerMethodMapping.java:213)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.afterPropertiesSet(AbstractHandlerMethodMapping.java:183)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.afterPropertiesSet(RequestMappingHandlerMapping.java:125)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1631)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1568)
    ... 25 more
III 11, 2016 4:00:20 PM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation(Ljava/lang/reflect/AnnotatedElement;Ljava/lang/Class;)Ljava/lang/annotation/Annotation;
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1572)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:539)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1231)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1034)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4997)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5289)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoSuchMethodError: org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation(Ljava/lang/reflect/AnnotatedElement;Ljava/lang/Class;)Ljava/lang/annotation/Annotation;
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.createRequestMappingInfo(RequestMappingHandlerMapping.java:203)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.getMappingForMethod(RequestMappingHandlerMapping.java:185)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.getMappingForMethod(RequestMappingHandlerMapping.java:53)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$1.inspect(AbstractHandlerMethodMapping.java:233)
    at org.springframework.core.MethodIntrospector$1.doWith(MethodIntrospector.java:72)
    at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:493)
    at org.springframework.core.MethodIntrospector.selectMethods(MethodIntrospector.java:68)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.detectHandlerMethods(AbstractHandlerMethodMapping.java:229)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.initHandlerMethods(AbstractHandlerMethodMapping.java:213)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.afterPropertiesSet(AbstractHandlerMethodMapping.java:183)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.afterPropertiesSet(RequestMappingHandlerMapping.java:125)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1631)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1568)
    ... 25 more

III 11, 2016 4:00:20 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet [dispatcher] in web application [/ab] threw load() exception
java.lang.NoSuchMethodError: org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation(Ljava/lang/reflect/AnnotatedElement;Ljava/lang/Class;)Ljava/lang/annotation/Annotation;
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.createRequestMappingInfo(RequestMappingHandlerMapping.java:203)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.getMappingForMethod(RequestMappingHandlerMapping.java:185)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.getMappingForMethod(RequestMappingHandlerMapping.java:53)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$1.inspect(AbstractHandlerMethodMapping.java:233)
    at org.springframework.core.MethodIntrospector$1.doWith(MethodIntrospector.java:72)
    at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:493)
    at org.springframework.core.MethodIntrospector.selectMethods(MethodIntrospector.java:68)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.detectHandlerMethods(AbstractHandlerMethodMapping.java:229)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.initHandlerMethods(AbstractHandlerMethodMapping.java:213)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.afterPropertiesSet(AbstractHandlerMethodMapping.java:183)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.afterPropertiesSet(RequestMappingHandlerMapping.java:125)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1631)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1568)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:539)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1231)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1034)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4997)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5289)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

III 11, 2016 4:00:20 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
III 11, 2016 4:00:20 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
III 11, 2016 4:00:20 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 2991 ms

EDIT:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>ab</groupId>
    <artifactId>ab</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <spring>4.2.5.RELEASE</spring>
        <spring.asm>3.1.4.RELEASE</spring.asm>
        <activemq-all>5.13.2</activemq-all>
        <commons-codec>1.10</commons-codec>
        <commons-collections>3.2.2</commons-collections>
        <commons-dbcp2>2.0.1</commons-dbcp2>
        <commons-logging>1.1.3</commons-logging>
        <commons-pool>1.6</commons-pool>
        <httpclient>4.5.2</httpclient>
        <httpcore>4.4.4</httpcore>
        <httpmime>4.5.2</httpmime>
        <javacsv>2.0</javacsv>
        <jstl-api>1.2</jstl-api>
        <jstl-impl>1.2</jstl-impl>
        <log4j>1.2.17</log4j>
        <javax.mail-api>1.5.5</javax.mail-api>
        <postgresql>9.1-901-1.jdbc4</postgresql>
        <xalan>2.7.2</xalan>
        <xercesImpl>2.11.0</xercesImpl>
        <simplecaptcha>1.1.1</simplecaptcha>
    </properties>

    <dependencies>

        <!-- Spring Framework -->

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${spring}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-instrument</artifactId>
            <version>${spring}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-instrument-tomcat</artifactId>
            <version>${spring}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>${spring}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${spring}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc-portlet</artifactId>
            <version>${spring}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-asm</artifactId>
            <version>${spring.asm}</version>
        </dependency>

        <!-- Other deps -->

        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-all</artifactId>
            <version>${activemq-all}</version>
        </dependency>

        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>${commons-codec}</version>
        </dependency>

        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>${commons-collections}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>${commons-dbcp2}</version>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>${commons-logging}</version>
        </dependency>

        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>${commons-pool}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>${httpclient}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>${httpcore}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>${httpmime}</version>
        </dependency>

        <dependency>
            <groupId>net.sourceforge.javacsv</groupId>
            <artifactId>javacsv</artifactId>
            <version>${javacsv}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl-api</artifactId>
            <version>${jstl-api}</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>jstl-impl</artifactId>
            <version>${jstl-impl}</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j}</version>
        </dependency>

        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>javax.mail-api</artifactId>
            <version>${javax.mail-api}</version>
        </dependency>

        <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>${postgresql}</version>
        </dependency>

        <dependency>
            <groupId>xalan</groupId>
            <artifactId>xalan</artifactId>
            <version>${xalan}</version>
        </dependency>

        <dependency>
            <groupId>xerces</groupId>
            <artifactId>xercesImpl</artifactId>
            <version>${xercesImpl}</version>
        </dependency>

        <dependency>
            <groupId>com.liferay</groupId>
            <artifactId>nl.captcha.simplecaptcha</artifactId>
            <version>${simplecaptcha}</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

A: I think you have two version of Spring-core libraries in your classpath. The below method is not present in this version of class AnnotatedElementUtils that is getting loaded into classpath
    public static <A extends Annotation>
    A findMergedAnnotation(AnnotatedElement element,Class<A> annotationType)

This method is available since 4.2. May be there is a spring core library that is prior to this version. Please check if there is any older version of spring-core library is getting loaded with spring-asm jar as transitive dependency


text:
Q: Buscar palabras con más de 7 letras en una sopa estoy programando un programa que resuelva sopas de letras, indicándole tú la palabra que quieres buscar. El problema que tengo, es que no consigo que busque palabras con siete letras o más. Por el momento solo busca palabras en horizontal.
Se que el fallo está en la función buscarPalabra, o al menos eso creo. Y para facilitar las cosas se pueden meter varias palabras para buscar separándolas con espacios de esta forma "rosa belgica alemania" (esas palabras están pero no muestra la última).
Muchas gracias y un saludo.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define ENTER '\n'

void recogerLetras(int ancho, int alto, char letras[ancho*alto]);
void rellenarMatriz(int i, int j, char matriz[i][j], char elementos[i*j]);
void mostrarMatriz(int i, int j, char matriz[i][j]);
void buscarPalabra(int i, int j, char matriz[i][j], int longitud,  char palabra[longitud]);

typedef char* pChar;

int main() {
    int ancho = 30, alto = 30;

    printf("\nEscribe el ancho y el alto de la sopa de letras: ");
   // scanf("%d %d", &ancho, &alto);
    char letras[ancho*alto];
    pChar palabra = malloc(sizeof(char));
    char sopa[ancho-1][alto-1]; //Crea una matriz con el tamano real que tendra la sopa

    //recogerLetras(ancho, alto, letras); //Recoge las letras de la sopa en un array unidimensional

    rellenarMatriz(ancho, alto, sopa, "lakngmargnehfxwnoduaaaahoiuzuuujkaaznxgelioeacsbelgicaimyngeblkntjoluaniimrjunafxoxdlwawvguoiunzqytaoorqmdvcialrvueajicmhjowdzaruewjbajburnqzpelebgnbsbjnluauflevsbfeyaksmemnpiyumihlufylueikjagucxaubarifheinwnxynjkhcihghenkupcmenucoihzenspuqudrxgcrjrbajnaranlnrreozkookaotfqssdualiatsaiuufnuganhvulovueavrgruamgsigwqzaycaeviaaoyddoeyabuanavabquaarwhwunrucuqjauuaunnocnpouemecrosasunvwynpxrpaquvuoifndbcutsenjqjramutuaeoqtpyeehucfdncobvgnqagjqtahebrmvmipocgkvjeyqayfdazraocikmxmaftawnuufoirnilyyaruprupljnaapizfprtajdkeytbjznnopofuajsrrdxneenctgidatalemaniaaawnpcslratempkguvncangeuevjemsldcoipaooqkienphvohiapgpnivsioizufljgnwofnhqxjdcpfmojorpesaaenqrfuupnmchaojqfmhskfeiihinnaxdnbuntesufuciukuuioziyuiiizoiphxinursifoeixusnrwuurmlqtuinxssiscaognfejsznaeruouwcnnglijisarttepiacpjxujmiruovzkezeuanopjbmdaiizofoqohbyzasuvghqoppuajyiruuozwvuptaxvupucyrqleozgwslbetuixropugomwtiozjasitnvzpicqvienmwdyukinn"); //Las letras recogidas antes, se transforman en una matriz bidimensional
    mostrarMatriz(ancho, alto, sopa); //Muestra la matriz con el formato de una sopa de letras

    printf("\nEscribe todas las palabras que deseas buscar separadas por espacios: ");
    do {
        scanf("%s", palabra);
        buscarPalabra(ancho, alto, sopa, (int) strlen(palabra), palabra);
    } while(getchar() != ENTER);

    return 0;
}

void recogerLetras(int ancho, int alto, char letras[ancho*alto]) {
    int iterador = 0;
    printf("\nEscribe todas las letras seguidas y sin espacios: ");
    do {
        scanf("%s", letras);   //Guarda las letras en un array
        iterador++;
    } while(getchar() != ENTER); // El bucle para cuando entra un ENTER

}

void rellenarMatriz(int i, int j, char matriz[i][j], char elementos[i*j]) {
    int indiceElementos = 0;

    printf("\n");
    for(int fila = 0;  fila < j; fila++) {
        for(int columna = 0; columna < i; columna++) {
            matriz[columna][fila] = elementos[indiceElementos];
            printf("%c ", matriz[columna][fila]);
            indiceElementos++;
        }
    }
    printf("\n");

}

void mostrarMatriz(int i, int j, char matriz[i][j]) {
    printf("\n\n");

    for (int fila = 0; fila < j; fila++) {
        for (int columna = 0; columna < i; columna++) {
            printf("%c  ", matriz[columna][fila]);
        }
        printf("\n");
    }
}

void buscarPalabra(int i, int j, char matriz[i][j], int longitud, char palabra[longitud]) {

    int fila = 0, columna = 0;
    pChar posiblePalabra = malloc(sizeof(char));
     do {
        do {
            //printf("\nEstoy fila %d y columna %d", fila, columna);
            if(palabra[0] == matriz[columna][fila]) {
                //printf("\nEstoy en IF en fila %d y columna %d, palabra[%d] %c matriz[%d][%d] %c\n", fila, columna, 0, palabra[0], columna, fila, matriz[columna][fila]);
                for(int longitudPalabra = 0; longitudPalabra < longitud; longitudPalabra++) {
                    posiblePalabra[longitudPalabra] = matriz[columna+longitudPalabra][fila];
                    //printf("%c", posiblePalabra[longitudPalabra]);
                }
            }
            if(strcmp(posiblePalabra, palabra)==0) {
                break;
            }

            columna++;
        } while(columna < i);
         if(strcmp(posiblePalabra, palabra)==0) {
             break;
         }
        columna = 0;
        fila++;
    } while(fila < j);

     if(strcmp(posiblePalabra, palabra)==0) {
         printf("\nSe encontro la palabra \"%s\" en fila %d y columna %d", palabra, fila+1, columna+1);
     } else {
         printf("\nNo se encontro la palabra \"%s\" en ninguna linea horizontal", palabra);
     }

}

//2 2 abcd
//3 3 abcdefghi
//4 4 abcdefghijklmno
//5 5 abcdefghijklmnopqrstuvwxy
//10 10 abcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxy
//15 15 aholafrojoklmnopqrstuazulabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstadios

A: Tras mucho buscar no encontré cual era el problema, por lo que finalmente decidí una forma distinta para buscar palabras. Así que cambiando el sistema de búsqueda utilizando booleanos cuando las letras coinciden se solucionó todo. El código de la función de búsqueda quedó de esta manera.
bool buscarPalabraHorizontalDerecha(int i, int j, char matriz[i][j], int longitud, char palabra[longitud]) {
    int fila = 0, columna = 0;
    bool letrasCoincidentes = false;

    do {
        do {
            if(palabra[0] == matriz[columna][fila]) {
               for(int longitudPalabra = 0; longitudPalabra < longitud; longitudPalabra++) {
                    if(palabra[longitudPalabra] == matriz[columna+longitudPalabra][fila]) {
                        letrasCoincidentes = true;
                    } else {
                        letrasCoincidentes = false;
                        break;
                    }
               }

            }
            if(letrasCoincidentes == true) break;

            columna++;
        } while(columna < i);
        if(letrasCoincidentes == true) break;

        columna = 0;
        fila++;
    } while(fila < j);

    if(letrasCoincidentes == true) {
        printf("\nSe encontro la palabra \"%s\" en\tFILA:%d COLUMNA:%d\t en posicion HORIZONTAL DERECHA", palabra, fila+1, columna+1);
        return true;
    } else {
        return false;
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Apache Cassandra Backup on linux I have Apache Cassandra on linux OS.
What is the best solution for backup data from enviroment to antother enviroment without losing data

A: Medusa is very good open source tool for backup of Cassandra.


text:
Q: index value cannot updated Here I am using array to store date in local-storage. first add data that is stored after add another one the index value not increased. The newly add data only shows.
function save() {
            var task = [];
            localStorage.getItem('task');
            task.push(document.getElementById("txt1").value);
            console.log(task);
            localStorage.setItem('array', task);
        }


text:
Q: ArrayList print repeated element sectionTreatment.setSurgeryPerformedGrid(Lists.newArrayList());

//testing
if (elementNodeExist(element, "surgery-performed-grid")) {
    NodeList childList = element.getElementsByTagName("surgery-performed-grid");

for(int i = 0; i < childList.getLength(); i++) {
    OromaxSurgeryPerformedGrid surgeryPerformedGrid1 = new OromaxSurgeryPerformedGrid();
    LOG.debug("childList.........." + childList);
    surgeryPerformedGrid1.setSurgeryPerformedDate(getStringValForElementTag(element, "surgery-performed-date"));
    surgeryPerformedGrid1.setSurgeryPerformedProcedureSpecify(getStringValForElementTag(element, "surgery-performed-procedure-specify"));
    surgeryPerformedGrid1.setSurgeryPerformedProcedureCode(new ArrayList<>());
    String surgeryPerformedCode = lookupMapperHelperService.getSurgeryPerformedCodeById(getIntValForElementTag(element, "surgery-performed-procedure"));
    if(surgeryPerformedCode != null && Pris3BMdmMapper.getSurgeryPerformedA(surgeryPerformedCode) != null) {
        surgeryPerformedGrid1.getSurgeryPerformedProcedureCode().add( Pris3BMdmMapper.getSurgeryPerformedA(surgeryPerformedCode));
    }
    String surgeryPerformedlv1 =lookupMapperHelperService.getSurgeryPerformedCodeById(getIntValForElementTag(element, "surgery-performed-procedure-detail-lvl1"));
    if(surgeryPerformedlv1 != null && Pris3BMdmMapper.getSurgeryPerformedA(surgeryPerformedlv1) != null) {
        surgeryPerformedGrid1.getSurgeryPerformedProcedureCode().add(Pris3BMdmMapper.getSurgeryPerformedA(surgeryPerformedlv1));
    }
    String surgeryPerformedlv2 = lookupMapperHelperService.getSurgeryPerformedCodeById(getIntValForElementTag(element, "surgery-performed-procedure-detail-lvl2"));
    if(surgeryPerformedlv2 != null && Pris3BMdmMapper.getSurgeryPerformedA(surgeryPerformedlv2) != null) {
        surgeryPerformedGrid1.getSurgeryPerformedProcedureCode().add(Pris3BMdmMapper.getSurgeryPerformedA(surgeryPerformedlv2));
    }
    surgeryPerformedGrid1.setSurgeryPerformedType(Pris3BMdmMapper.getSurgeryPerformedA(String.valueOf(lookupMapperHelperService.getOromaxLevelCodeById(getIntValForElementTag(element, "surgery-performed-type")))));
    surgeryPerformedGrid1.setSurgeryPerformedSite(lookupMapperHelperService.getOromaxProcedureSiteCodeById(getIntValForElementTag(element, "surgery-performed-site")));
    surgeryPerformedGrid1.setSurgeryPerformedLaterality(lookupMapperHelperService.getLateralityCodeById(getIntValForElementTag(element, "surgery-performed-laterality")));
    surgeryPerformedGrid1.setSurgeryPerformedSiteOthers(getStringValForElementTag(element, "surgery-performed-site-others"));

    sectionTreatment.getSurgeryPerformedGrid().add(surgeryPerformedGrid1);
}

My code supposedly read and print the element inside tag "surgery-performed-grid" in xml. But the my output keep print the first element of the tag. my output :
"surgeryPerformedGrid": [{
            "surgeryPerformedDate": "2018-09-11",
            "surgeryPerformedProcedureCode": ["01"],
            "surgeryPerformedSite": "02",
            "surgeryPerformedSiteOthers": null,
            "surgeryPerformedLaterality": null,
            "surgeryPerformedType": null,
            "surgeryPerformedProcedureSpecify": null
        }, {
            "surgeryPerformedDate": "2018-09-11",
            "surgeryPerformedProcedureCode": ["01"],
            "surgeryPerformedSite": "02",
            "surgeryPerformedSiteOthers": null,
            "surgeryPerformedLaterality": null,
            "surgeryPerformedType": null,
            "surgeryPerformedProcedureSpecify": null

This code keep add same object(surgeryPerformedGrid1) in ArrayList. How to add different object(each element) in ArrayList?
 sectionTreatment.getSurgeryPerformedGrid().add(surgeryPerformedGrid1);

Thank you.

A: You need to use parent element in for, so you code should be something like this:
sectionTreatment.setSurgeryPerformedGrid(Lists.newArrayList());

//testing
if (elementNodeExist(element, "surgery-performed-grid")) {
    NodeList childList = element.getElementsByTagName("surgery-performed-grid");

for(currentElement: childList) {
        OromaxSurgeryPerformedGrid surgeryPerformedGrid1 = new OromaxSurgeryPerformedGrid();
    LOG.debug("childList.........." + childList);
    surgeryPerformedGrid1.setSurgeryPerformedDate(getStringValForcurrentElementTag(currentElement, "surgery-performed-date"));
    surgeryPerformedGrid1.setSurgeryPerformedProcedureSpecify(getStringValForcurrentElementTag(currentElement, "surgery-performed-procedure-specify"));
    surgeryPerformedGrid1.setSurgeryPerformedProcedureCode(new ArrayList<>());
    String surgeryPerformedCode = lookupMapperHelperService.getSurgeryPerformedCodeById(getIntValForcurrentElementTag(currentElement, "surgery-performed-procedure"));
    if(surgeryPerformedCode != null && Pris3BMdmMapper.getSurgeryPerformedA(surgeryPerformedCode) != null) {
        surgeryPerformedGrid1.getSurgeryPerformedProcedureCode().add( Pris3BMdmMapper.getSurgeryPerformedA(surgeryPerformedCode));
    }
    String surgeryPerformedlv1 =lookupMapperHelperService.getSurgeryPerformedCodeById(getIntValForcurrentElementTag(currentElement, "surgery-performed-procedure-detail-lvl1"));
    if(surgeryPerformedlv1 != null && Pris3BMdmMapper.getSurgeryPerformedA(surgeryPerformedlv1) != null) {
        surgeryPerformedGrid1.getSurgeryPerformedProcedureCode().add(Pris3BMdmMapper.getSurgeryPerformedA(surgeryPerformedlv1));
    }
    String surgeryPerformedlv2 = lookupMapperHelperService.getSurgeryPerformedCodeById(getIntValForcurrentElementTag(currentElement, "surgery-performed-procedure-detail-lvl2"));
    if(surgeryPerformedlv2 != null && Pris3BMdmMapper.getSurgeryPerformedA(surgeryPerformedlv2) != null) {
        surgeryPerformedGrid1.getSurgeryPerformedProcedureCode().add(Pris3BMdmMapper.getSurgeryPerformedA(surgeryPerformedlv2));
    }
    surgeryPerformedGrid1.setSurgeryPerformedType(Pris3BMdmMapper.getSurgeryPerformedA(String.valueOf(lookupMapperHelperService.getOromaxLevelCodeById(getIntValForcurrentElementTag(currentElement, "surgery-performed-type")))));
    surgeryPerformedGrid1.setSurgeryPerformedSite(lookupMapperHelperService.getOromaxProcedureSiteCodeById(getIntValForcurrentElementTag(currentElement, "surgery-performed-site")));
    surgeryPerformedGrid1.setSurgeryPerformedLaterality(lookupMapperHelperService.getLateralityCodeById(getIntValForcurrentElementTag(currentElement, "surgery-performed-laterality")));
    surgeryPerformedGrid1.setSurgeryPerformedSiteOthers(getStringValForcurrentElementTag(currentElement, "surgery-performed-site-others"));

    sectionTreatment.getSurgeryPerformedGrid().add(surgeryPerformedGrid1);
}


text:
Q: Result of number with decimal point modulo $10$. This is a very simple question, very trivial to many, but I have to resolve this doubt!
I have done the division $2.2/10$ by hand, and the result is $0.22$, without any remainder:

But why if I do with calculator, I obtain this:
$$2.2 \mod 10 = 2.2$$
why it is not equal to $0$, instead?

A: You can define modulo for real variables like this: $\quad {a \bmod b=a-\lfloor \frac ab\rfloor\times b}$
Here $\frac ab=0.22$ whose integer part is $0$, so basically for $0\le x<10$ then $x\bmod 10=x$.


text:
Q: Rspec test fails to show that model requires an email I'm (mostly) following a tutorial everydayrails.com trying to write a test that shows that my user model requires an email:
 17   it "requires an email" do
 18     user = FactoryGirl.create(:user, email: nil)
 19     expect( user ).to_not be_valid
 20   end

But this fails... because my user model requires an email?
Failures:

  1) User requires an email
     Failure/Error: user = FactoryGirl.create(:user, email: nil)

     ActiveRecord::RecordInvalid:
       Validation failed: Email can't be blank
     # ./spec/models/user_spec.rb:18:in `block (2 levels) in <top (required)>'

What am I doing wrong here?

A: Your call to Factory.create runs the validations and internally factory girl uses save! by default so the failed validation will cause an exception to be raised.
Use Factory.build instead (as in the tutorial you link to) to create an unsaved object that you can test for validity

A: You can try this test like this way
it "requires an email" do
  expect(User.new.errors_on(:email)).to include("can't be blank")
end

or
expect(Factory.build(:user, email: nil)).to_not be_valid

More on this Please consult errors_on

A: The key things I would recommend when writing tests in the future are:

*

*Readable. Tests should be really easy to read (and write).

*Extensive. Tests shouldn't break unnecessarily and should test exactly what you need it to.

The code example that you'd be looking for is:
context "Email address" do
  it 'does not validate if email is nil' do
    user_with_no_email = build(:user, email: nil)

    expect(user_with_no_email).to receive(:validate).with(false)
    expect(user_with_no_email).to have(1).error_on(:email)
  end
end


text:
Q: Doesn't Iconbuttons onTap method or any other onTap work inside a stack widget in flutter? I have a screen which has a image on top of which i have a row with two icons wrapped with gesture detector and all of them are inside a stack. But whenever i tap on any of the buttons they dont work. Please tell me how to solve this.
Below is my code snippet....
import 'package:flutter/material.dart';
import 'package:news/ui/bookmark.dart';
import 'package:share/share.dart';

class DetailScreen extends StatefulWidget {
final String title, description, image, author, content;

DetailScreen(
  {this.title, this.image, this.description, this.author, this.content});

@override
_DetailScreenState createState() => _DetailScreenState();
}

class _DetailScreenState extends State<DetailScreen> {
List<String> list = [];

@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return Scaffold(
  body: ListView(
    children: <Widget>[
      Container(
        height: size.height / 2.6,
        child: Stack(
          fit: StackFit.loose,
          children: <Widget>[
            SizedBox(
                height: size.height / 2.8,
                width: size.width,
                child: Image.network(
                  widget.image,
                  fit: BoxFit.fill,
                )),
            Padding(
              padding: const EdgeInsets.all(15.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  GestureDetector(
                    child: Icon(
                      Icons.arrow_back,
                      color: Colors.white,
                    ),
                    onTap: () {
                      print('Damn You'); //Doesn't work
                    },
                  ),
                  GestureDetector(
                      child: Icon(
                        Icons.share,
                        color: Colors.white,
                      ),
                      onTap: () {
                        Share.share('${widget.image}' +
                            '\n${widget.title}' +
                            '\n${widget.description}');
                      }), //Doesn't work
                ],
              ),
            ),
            InkWell(
              onTap: () {
                list.add(widget.title);
                Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => Bookmark(
                              list: list,
                            )));
              },
              child: Padding(
                padding: const EdgeInsets.only(right: 15.0),
                child: Align(
                  alignment: Alignment.bottomRight,
                  child: Container(
                    height: 60.0,
                    width: 60.0,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(25.0),
                        color: Colors.blue),
                    child: Icon(
                      Icons.bookmark,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ), //works fine
      Padding(
        padding:
            const EdgeInsets.only(left: 15.0, bottom: 15.0, right: 15.0),
        child: Text(
          widget.title,
          style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 20.0,
              color: Colors.black),
          overflow: TextOverflow.clip,
        ),
      ),
      Padding(
        padding: const EdgeInsets.only(bottom: 15.0, left: 15.0),
        child: Row(
          children: <Widget>[
            Icon(
              Icons.edit,
              color: Colors.grey,
              size: 15.0,
            ),
            SizedBox(
              width: 5.0,
            ),
            Text(
              widget.author == null ? 'No Author' : widget.author,
              style: TextStyle(
                color: Colors.grey,
              ),
              overflow: TextOverflow.ellipsis,
            )
          ],
        ),
      ),
      Padding(
        padding: const EdgeInsets.only(
          left: 15.0,
          right: 15.0,
        ),
        child: Divider(
          color: Colors.grey,
        ),
      ),
      Padding(
        padding: const EdgeInsets.only(top: 15.0, left: 15.0, right: 15.0),
        child: Text(
          widget.content == null
              ? 'Sorry this document has no content'
              : widget.content,
          //overflow: TextOverflow.clip,
        ),
      ),
    ],
  ),
 );
  }
}

How to solve the problem please help.
Thanks in advance

A: It's because the InkWell() widget is hidden at the background of your container. And this is because it's referencing the top level Material() widget. All you need to do is instantiate a new Material() widget above the CircularAvatar() widget, therefore making CircularAvatar() its parent.
On your TopArea() widget, make the CircularAvatar() widget the parent of
Material() widget which in turns, makes the InkWell() widget its child.
Example below
 Widget topArea() {
    return Row(
       mainAxisAlignment: MainAxisAlignment.spaceBetween,
    children: <Widget>[
      // Other top widget codes goes here

       CircleAvatar(
          radius: 25.0,
          //backgroundColor: Colors.transparent,
           backgroundImage: NetworkImage( "https://images.pexels.com/photos/1138409/pexels-photo- 1138409.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260", ),
         child: Material(
            type: MaterialType.transparency,
            child: InkWell(
               onTap: () => Navigator.push(context, MaterialPageRoute(builder: (context) => {})),
              highlightColor: Colors.red[200].withOpacity(0.5),
              splashColor: Colors.red[200].withOpacity(0.5),
              borderRadius: BorderRadius.circular(25.0),
              radius: 25.0
          )
        ),

      ),
   ],
 );
}

UPDATED:
Instead of GestureDectector(), try this below
 IconButton(
   icon: Icon( Icons.arrow_back),
   color: Colors.white,
   onPressed: () { print('Hello World')}
 )

When you run your app, check your console if "Hello World" is printed when the button is clicked.


text:
Q: Why do these code blocks produce different results? Below are 2 similar code blocks. They take a string, encrypt in SHA512, then convert to Base64, I had trouble getting the second code block to produce the same results as my manual test using online calculators and encoders. So I broke the process down step by step and discovered that it was capable of producing the same results as my manual test but only if it behaved like the first code block. Why do these two code blocks produce different results? Thanks!
    private void EditText_AfterTextChanged(object sender, AfterTextChangedEventArgs e)
    {
        //This builds a string to encrypt.
        string domain = txtDomain.Text;
        string username = txtUsername.Text;
        string pin = txtPin.Text;
        txtPreview.Text = string.Format("{0}+{1}+{2}", domain, username, pin);

        //This takes the above string, encrypts it.
        StringBuilder Sb = new StringBuilder();
        SHA512Managed HashTool = new SHA512Managed();
        Byte[] PhraseAsByte = System.Text.Encoding.UTF8.GetBytes(string.Concat(txtPreview.Text));
        Byte[] EncryptedBytes = HashTool.ComputeHash(PhraseAsByte);
        HashTool.Clear();

        //This rebuilds the calculated hash for manual comparison.
        foreach (Byte b in EncryptedBytes)
            Sb.Append(b.ToString("x2"));
        txtHash.Text = Sb.ToString();

        //This takes the rebuilt hash and re-converts it to bytes before encoding it in Base64
        EncryptedBytes = System.Text.Encoding.UTF8.GetBytes(string.Concat(txtHash.Text));
        txtResult.Text = Convert.ToBase64String(EncryptedBytes);

    }

and
    private void EditText_AfterTextChanged(object sender, AfterTextChangedEventArgs e)
    {
        //This builds a string to encrypt.
        string domain = txtDomain.Text;
        string username = txtUsername.Text;
        string pin = txtPin.Text;
        txtPreview.Text = string.Format("{0}+{1}+{2}", domain, username, pin);

        //This takes the above string, encrypts it.
        StringBuilder Sb = new StringBuilder();
        SHA512Managed HashTool = new SHA512Managed();
        Byte[] PhraseAsByte = System.Text.Encoding.UTF8.GetBytes(string.Concat(txtPreview.Text));
        Byte[] EncryptedBytes = HashTool.ComputeHash(PhraseAsByte);
        HashTool.Clear();

        //This takes the EncryptedBytes and converts them to base64.
        txtResult.Text = Convert.ToBase64String(EncryptedBytes);

        //This reverses the EncryptedBytes into readable hash for manual comparison
        foreach (Byte b in EncryptedBytes)
        Sb.Append(b.ToString("x2"));
        txtHash.Text = Sb.ToString();
    }

A: Found the answer, no thanks to your less-than-useful downvotes..

Encoding.Unicode is Microsoft's misleading name for UTF-16 (a double-wide encoding, used in the Windows world for historical reasons but not used by anyone else). http://msdn.microsoft.com/en-us/library/system.text.encoding.unicode.aspx
If you inspect your bytes array, you'll see that every second byte is 0x00 (because of the double-wide encoding).
You should be using Encoding.UTF8.GetBytes instead.
But also, you will see different results depending on whether or not you consider the terminating '\0' byte to be part of the data you're hashing. Hashing the two bytes "Hi" will give a different result from hashing the three bytes "Hi". You'll have to decide which you want to do. (Presumably you want to do whichever one your friend's PHP code is doing.)
For ASCII text, Encoding.UTF8 will definitely be suitable. If you're aiming for perfect compatibility with your friend's code, even on non-ASCII inputs, you'd better try a few test cases with non-ASCII characters such as é and 家 and see whether your results still match up. If not, you'll have to figure out what encoding your friend is really using; it might be one of the 8-bit "code pages" that used to be popular before the invention of Unicode. (Again, I think Windows is the main reason that anyone still needs to worry about "code pages".)

Source: Hashing a string with Sha256


text:
Q: WriteFile overlapped and fwrite equivalent On Windows, the WriteFile() function has a parameter called lpOverlapped which lets you specify an offset at which to write to the file.
I was wondering, is there is an fwrite() cross-platform equivalent of that?
I see that if the file is opened with the rb+ flag, I might be able to use fseek() to write to a particular offset. My question is - will this approach be equivalent to the overlapped WriteFile(), and will it produce the same behaviour on all platforms?
Background
The reason I need this is because I am writing blocked compressed data streams to a file, and I want to be able to load a specific block from the file and be able to decompress it. So, basically if I keep track of where the block begins in a file, I can load the block and decompress it in a more efficient manner. I know that there are probably better ways to do this, but I need this solution for some backwards compatibility.

A: Assuming you are okay with using POSIX functions and not just things from the C or C++ standard libraries, the solution is pwrite (aka: positioned write).
ssize_t rc = pwrite(file_handle, data_ptr, data_size, destination_offset);

A: I think you are confusing "overlapped" and "overwrite"/"offset."  I didn't study up on the specifics of why Microsoft explicitly says overlapped writes include a parameter for offset (I think it makes sense as I describe below).  In general, when Microsoft talks about "overlapped" IO, they are talking about how to synchronize events like starting to write the file, receiving notification that the write completed, and starting another write to the file which might or might not overlap with a previous write.  In this last case, by overlap I mean what you would think that overlap means, ie overlaps within the contents of the file.  Whereas Microsoft means that writing the file overlaps in time with your thread running, or not.  Note that this gets very complicated if more than one thread can write the same file.
If possible, and surely if you want portable code, you want to avoid all this nonsense and just do the simplest write possible in each context, which means avoid Microsoft optimizations like "overlapped IO" unless you really need performance.  (And if you need absolutely optimal performance, you might want to cache the file yourself and manage the overlaps, then write it once from start to finish.)

A: While pwrite is probably the best solution, there is an alternative that sticks with stdio functions. Unfortunately, to make it thread-safe, you're using non-standard "stdio" to take direct control of the FILE*'s internal lock, and the names aren't portable. Specifically, POSIX defines one set of "take/release file lock" names and Windows defines another set (_lock_file/_unlock_file).
That said, you could use these semi-portable constructs to use stdio functions to ensure no buffering conflicts (pwrite to fileno(some_FILE_star) could cause problems if the FILE* buffer overlaps the pwrite location, since pwrite won't fix up the buffer):
// Error checking omitted; you should actually check returns in real code
size_t pfwrite(const void *ptr, size_t size, size_t n,
               size_t offset, FILE *stream) {
    // Take FILE*'s lock and hold it for entire transaction
    flockfile(stream);  // _lock_file on Windows

    // Record position
    long origpos = ftell(stream);

    // Seek to desired offset and write
    fseek(stream, offset, SEEK_SET); // Possibly offset * size, not just offset?
    size_t written = fwrite(ptr, size, n, stream);

    // Seek back to original position
    fseek(stream, origpos, SEEK_SET);

    // Release FILE*'s lock now that transaction complete
    funlockfile(stream); // _unlock_file on Windows
    return written;
}


text:
Q: PostgreSQL - export output to CSV I want to export a queried table to CSV file. The query syntax written here is not my codes. I got it from my co-worker. My knowledge with PostgreSQL is very minimal, and I don't know how to modify the code. Please give me a working code that can export the queried table into CSV. Formats aren't important as long as its in CSV format, as I can use Python to reformat the tables.
WITH es_events AS
  (SELECT *
   FROM dblink('foreign_rs_server', $EXT$
           -- Note that since device_id and register_id are known and singular,
        -- they are replaced as constant values rather than retrieved.
        -- As a distributed columnar store, Redshift is most performant when fewer columns are retrieved.
               SELECT DATE("dt")::timestamp as dt, value, 2777 as device_id, 1343 as register_id
               FROM "es_events" AS "events"
                             WHERE "events"."event_type" = 0
                             AND register_id = 1343
                             AND device_id=2777
                             AND dt>='2018-12-01T00:00:00'
                             AND dt<'2018-12-02T00:00:00'
               ORDER BY DATE("dt") ASC; $EXT$) AS es_events (dt TIMESTAMP WITH TIME ZONE, value DOUBLE PRECISION, device_id INTEGER, register_id INTEGER)),
register_versions AS
(
    SELECT
        r.*,
        r.valid_at as valid_start,
        CASE
        WHEN r2.valid_at IS NULL THEN '2020-01-01'
        ELSE r2.valid_at
        END as valid_end
    FROM registers r
    LEFT JOIN registers r2 ON r2.id=r.id AND r2.valid_at>r.valid_at
    ORDER BY id ASC
)

SELECT "dt",
             r.name,
             "events"."value"*r.scaling as scaled_value,
             r.units_of_measure
FROM "es_events" AS "events"
JOIN register_versions r ON r.id = events.register_id AND (r.valid_start <= dt AND r.valid_end > dt)
JOIN device_asset_mapping dam ON dam.device_id=events.device_id AND dam.active
ORDER BY dam.asset_id, dt ASC

A: you can use terminal command like this :
COPY ( your query inside ) TO 'C:\tmp\persons_email_db.csv' DELIMITER ',' CSV;

or you can simply use some Database Tools like navicat or dbeaver to run your query above and export the result to csv


text:
Q: Asterisks in formatted text: questions/answers vs. comments There are several questions that touch upon this bug (?) peripherally, but none of the ones I could find address the question exactly.
I post mostly on ELU, where I am one of the posters that regularly need to write out words and forms that are reconstructed for an earlier stage of a given language. Such forms are traditionally marked by a preceding asterisk, and since they are quoted words in a different language, they should be italicised. In other words, I and others frequently need to write words like *this in italic with a preceding asterisk.
What's odd is that this works in both questions/answers and in comments, but 'backwards'. In questions, the asterisk has to be put outside the underscores, otherwise it doesn't work; in comments, it has to be put inside them:

Questions/answers:
_*test_ = *test
*_test_ = *test [what we want]
Comments:
_*test_ = *test [what we want]
*_test_ = *_test_

This is obviously related to the issue described in this question; but it is somewhat different.
Is there a particular reason comments have to be 'backwards' in this respect? It would be so much easier to remember how to write these forms if it were at least done in the same way everywhere.

A: Thanks to this change, this will behave as expected after the next build. In questions and answers, either of your two versions will work (the only difference of course being whether the asterisk is italicized, which hardly matters).


text:
Q: Credenciales en el gestor de repositorios de Visual Studio alguien ha usado el gestor de repositorios de Visual Studio?
lo comencé a usar, y cuando creo un repositorio permite generar una clave, la genero, luego cuando hago un clone o un primer pull nunca me pide esa credencial, entonces:
-Son públicos estos repositorios
-Son privados pero falta configurar algo?
Gracias


text:
Q: French character 'à' is being read as 'Ã' in Classic ASP server-side and database I have a form that accepts text and is posted to the server.
If a user were to input a French character such as 'à', it will be read as 'Ã' by Classic ASP code and be stored as 'Ã' in a SQL Server 2005 database.
A similar affect happens to other accented characters. What's happening?

A: It's a problem of character encoding. Apparently your server and database are configured with charsets Windows-1252 or ISO-8859-1, and you're receiving UTF-8 data.
You should check that your server sends a Content-Type or a Content-Encoding header with values ending with "charset=iso-8859-1".
I guess your server doesn't send the charset of the documents, and people with default configuration set to UTF-8 send UTF-8 characters which are stored as iso-8859-1 (or Windows-1252) in your database.

A: See my answer here for the detail on what is likely happening.
Utlimately you need to ensure the encoding used in the form post matches the Response.CodePage of the receiving page.  You can configure the actual character set sent by a form by placing the accept-charset attribute on the form element.  The default accept-charset is the documents char-set.
What exactly do you have the ASP files codepages set to (both on the page containing the form and the page receiving the post)?
What are you setting the Response.CharSet value to in the form page?

A: I have just gone around in circles trying to fix this once and for all in my old classic asp app which uses jquery ajax posts to store info in a database. Tried every combination with no luck..
Ended up modifying any sql selects by using the stored proc mentioned here and magic happened. Data is still stored corrupted in the database, but is displayed correctly on the site.


text:
Q: TCPDF: how to install in WAMP without COMPOSER? I'm using WAMP and I would need to create PDF from php/html pages.
I had some trouble with DOMPDF since it seems unable to manage tables longer than a page, and I'm considering to use TCPDF.
I saw that I could install TCPDF with COMPOSER but I would prefer,if possible, to avoid a further installation.
Any chances to install TCPDF without composer?
thanks


text:
Q: How to find and change DataViewListCtrl BackgroundColour of Selected text in WxPython? My problem is I can't find the command to change the background color of DataViewListCtrl for selected text/row/item in DataViewListCtrl object.
I looked into the documentation but there's no apparent reference.
https://docs.wxpython.org/wx.dataview.DataViewCtrl.html#wx-dataview-dataviewctrl
I'm using the sample_one.py script from this reference:
https://wiki.wxpython.org/How%20to%20add%20a%20menu%20bar%20in%20the%20title%20bar%20%28Phoenix%29
The DataViewListCtrl has this example code:
        self.dvlc = dv.DataViewListCtrl(
            self,
            style=dv.DV_MULTIPLE
            | dv.DV_ROW_LINES
            | dv.DV_HORIZ_RULES
            | dv.DV_VERT_RULES,
        )

        self.dvlc.SetBackgroundColour("#ffffff")
        self.dvlc.SetForegroundColour("black")

What I'm looking to do is similar to Tkinter example below (change the selected text background color to blue):
style.configure(
    "Treeview", background="#FFFFDD", foreground="black", fieldbackground="#FFFFDD"
)
style.map("Treeview", background=[("selected", "#F0FFFF")])

I haven't been able to try a workaround yet as I'm not sure how to get the needed command/value, but on my end the selected DataViewListCtrl items have a #242424 color (I checked with an eyedropper from a screenshot).
I found the  2 parameters IsSelected and IsRowSelected in the doc:
https://docs.wxpython.org/wx.dataview.DataViewListCtrl.html#wx.dataview.DataViewListCtrl.IsRowSelected
https://docs.wxpython.org/wx.dataview.DataViewCtrl.html#wx.dataview.DataViewCtrl.IsSelected
and tested as
        self.dvlc = dv.DataViewListCtrl(
            self,
            style=dv.DV_MULTIPLE
            | dv.DV_ROW_LINES
            | dv.DV_HORIZ_RULES
            | dv.DV_VERT_RULES,
        )

        # Give it some columns.
        self.dvlc.AppendTextColumn("Id", width=40)
        self.dvlc.AppendTextColumn("Artist", width=170)
        self.dvlc.AppendTextColumn("Title", width=260)
        self.dvlc.AppendTextColumn("Genre", width=80)

        # Load the data. Each item (row) is added as a sequence
        # of values whose order matches the columns.
        for itemvalues in musicdata:
            self.dvlc.AppendItem(itemvalues)

        # — 1st test with same result as 2nd below
        # if self.dvlc.IsSelected == True:
        #    self.dvlc.SetBackgroundColour("#0066ff")
        # else:
        #    self.dvlc.SetBackgroundColour("#F0FFFF")

        if self.dvlc.IsRowSelected == True:
            self.dvlc.SetBackgroundColour("#0066ff")
        else:
            self.dvlc.SetBackgroundColour("#F0FFFF")

        self.dvlc.SetForegroundColour("black")

I tried also without the == True explicit as
        # — 1st test with same result as 2nd below
        # if self.dvlc.IsSelected:
        #    self.dvlc.SetBackgroundColour("#0066ff")
        # else:
        #    self.dvlc.SetBackgroundColour("#F0FFFF")

        if self.dvlc.IsRowSelected:
            self.dvlc.SetBackgroundColour("#0066ff")
        else:
            self.dvlc.SetBackgroundColour("#F0FFFF")

and the unexpected blue background displays by default (when not selected).
Is there some documented "selected" parameter or otherwise known working method to be able to capture the selected background color and change it in WxPython?

A: You will have to use a custom renderer if you want to change the way the selected items background is rendered -- and you will have to overwrite the entire background entirely, as the default one will still be drawn, you will just be able to paint over it.
Alternatively, you can define a custom wxRendererNative-derived object and override its DrawItemSelectionRect() method and then set it as the renderer to use globally. This should be simpler, but it will change selection drawing in all controls using this function.


text:
Q: Git: how to make a subfolder in a private repo as a public repo without splitting it out from the parent repo? I saw there are a lot of discussions talking about splitting a subfolder of an existing repository into a separate Git repository. My questions is can I just initialize a subfolder of an existing Git repository and push it to a remote place as a new one? I don't care whether the past history of the subfolder preserved in the new repo, but I actually only want to share the subfolder to allow people to contribute into it while let the parent Git project easily track all the changes in the subfolder.
More details: I have read through some methods using Submodule, but that is not what I want from my understanding. When I checkout my parent repo or internal collaborators pull the changes of the parent repo, I expect all changes from the subfolder to be synchronized as well. Maybe subtree neither work for me, but after reading over some posts online, I am actually not sure about my judgement. I prefer to have a simple solution, like just initialize the subfolder as a new folder and push... Does it work.
Thanks for your input!

A:
can I just initialize a subfolder of an existing Git repository and push it to a remote place as a new one?

No. Git-repo is monolithic object, any|all changes of tree inside repo aren't visible to external views as independent object

Submodule, but that is not what I want from my understanding

You have to verify your understanding and fix it. Structuring by submodules assumes supporting link between states of parent repo and submodule, and this link reflect changes on both sides


text:
Q: Diagonal pixels of an image in MATLAB I have an image of size 30 x 100 pixels.

*

*How can I count how many pixels are there on the diagonal? can I
just apply the Pythagorean theorem? but if yes, we may obtain float
number of pixels. So how can I address this issue?

*In addition, how can I extract automatically the x and y coordinate values of
each pixel on the diagonal?
I have written a MATLAB code for a square matrix which is very easy. But how can I generalize my code to include images of any size (not only square images)..
%suppose an image of size 100 x 100
image = rand(100,100);
n = length(image);

%extract how many pixels are there on the diagonal
diagonal_pixels = sqrt(n^2 + n^2);

%Get the x and y coordinates values of each diagonal pixel
for i = 1: n
x_coordinate_diag(i) = i;
y_coordinate_diag(i) = i;
end

A: You could use these steps to get the diagonal pixels

*

*Get min width and height length (suppose it is the width)

*Loop through the min lenght(ex: width)

*get height cordinate by rounding i * height / width

For example 50 x 100

*

*Min is 50

*for i = 0, j = 0 x 100 / 50 = 0

*for i = 1, j = 1 x 100 / 50 = 2

*for i = 2, j = 2 x 100 / 50 = 4

*...

*for i = 50, j = 50 x 100 / 50 = 100


text:
Q: A function that returns a string which resemples a playing board in python I want to write a function that returns a square playing board containing '*' and ' ' based on the input number.
The intended output should be like this:
board_of_5 = (
    ' * * \n'
    '* * *\n'
    ' * * \n'
    '* * *\n'
    ' * * \n'
)

board_of_10 = (
    ' * * * * *\n'
    '* * * * * \n'
    ' * * * * *\n'
    '* * * * * \n'
    ' * * * * *\n'
    '* * * * * \n'
    ' * * * * *\n'
    '* * * * * \n'
    ' * * * * *\n'
    '* * * * * \n'
)

Here is my current code, which produces an output on a single line, and with no offset on alternating lines:
def get_playing_board(num):
    string = ''
    for i in range(num):
        for j in range(num):
            if j % 2 == 0:
                string += ' '
            elif j % 2 != 0:
                string += '*'
        print(string)
    return string

get_playing_board(5)

How do I introduce an offset and newlines?
How do I loop over the rows?
My idea is to add '*' or blank space based on even or odd numbers and loop for each row and col.
However, I cannot get the intended chart board.

A: The thing that goes into a given row, column depends on the relationship of the row and column index. Specifically, if both are even or odd (have the same parity), the element will be ' '. If they are not the same parity, the element will be a '*'.
The simplest way to check parity is with
if (i % 2) == (j % 2):

The parity of a number is encoded in the last bit: 1 for even, 0 for odd. You can therefore check for sameness using the XOR operator:
if (i ^ j) & 1:

In this case & 1 removes the last bit using bitwise AND.
To insert a newline at the end of each row, you just need to add that at the end of the outer loop:
def get_playing_board(num):
    board = ''
    for i in range(num):
        for j in range(num):
            board += ' *'[(i ^ j) & 1] # The index expression is 0 or 1
        board += '\n'
    return board

get_playing_board(5)

There is a clever alternative to manually generating each row. Instead, you can generate a string that is one element longer than num and grab a subset for each row:
def get_playing_board(num):
    row = ' *' * ((num + 2) // 2)
    board = ''
    for i in range(num):
        board += row[i % 2:num + i % 2] + '\n'
    return board

You can write either approach as a one-liner:
'\n'.join(''.join(' *'[(i ^ j) & 1] for j in range(num)) for i in range(num))

'\n'.join((' *' * ((num + 2) // 2))[i % 2:num + i % 2] for i in range(num))

I don't particularly recommend the bottom two approaches.

A: You can use:
def get_playing_board(num):
    import math
    n = math.ceil(num/2)
    s = '* '*n
    return '\n'.join(([" "+s[:num-1], s[:num]]*n)[:num])

print(get_playing_board(5))

print(get_playing_board(10))

Output:
# print(get_playing_board(5))
 * *
* * *
 * *
* * *
 * *

# print(get_playing_board(10))
 * * * * *
* * * * *
 * * * * *
* * * * *
 * * * * *
* * * * *
 * * * * *
* * * * *
 * * * * *
* * * * *


text:
Q: Flutter issue on reusing stateful widget and updating state I have this busy button logic where on api calls, I can replace the widget by loading indicator in event of network requests until it completes.
_BusyButtonState buttonState;

class BusyButton extends StatefulWidget {
  final onTap, text;
  BusyButton({Key key, this.text, this.onTap});
  @override
  _BusyButtonState createState() {
    buttonState = _BusyButtonState();
    return buttonState;
  }
}

class _BusyButtonState extends State<BusyButton> {
  bool isBusy = false;
  void notLoading() {
    setState(() {
      isBusy = false;
    });
  }

  void loading() {
    setState(() {
      isBusy = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    return isBusy
        ? CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation(Colors.blue),
            strokeWidth: 1.5,
          )
        : RaisedButton(
            color: Colors.blue,
            child:
                Text('${widget.text}', style: TextStyle(color: Colors.white)),
            onPressed: widget.onTap);
  }
}

And I have listview builder where I am using this button on each item to change the status of the item from active to inactive and vice versa.
BusyButton(
  key: UniqueKey(),
  text: active?"Inactive":"Active"
  onTap: () {
      sendToServer(active?true:false)
   },
)

sendToServer(bool active) async{
try {
      updateState.loading();
      var response = await CallApi().putData(
          {"active": active.toString()}, "url");
      if (response.data['success']) {
        updateState.notLoading();
        print("done");
      } else {
        updateState.notLoading();
        print("error");
      }
    } catch (e) {
      updateState.notLoading();
      print(e);
    }
}

But when I try and press the button, it works if network request is successful but loading indicator appears on some random button across the listview. Also it throws following error on request fail.
E/flutter (25919): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: setState() called after dispose(): _OutlinedButtonState#971b3(lifecycle state: defunct, not mounted)

How do I resolve this issue?

A: Try to use setState.
BusyButton(
      key: UniqueKey(),
      text: active?"Inactive":"Active"
      onTap: () {
         setState(){
          sendToServer(active?true:false)
         }
       },
    )


text:
Q: get the basename of the project I want to get  the project name 'video' which is in www folder.I have created a file in a folder structure video/profiles/commons/module/modulename/test.php
in my test.php I have the base path $basepath=__DIR__; which returns file:///C:/wamp64/www/video/profiles/commons/modules/modulename/ .I want to get only the project name 'video'

A: I think this will work for you:
$path = dirname(`__FILE__`);
echo basename($path);

A: Try something like this,
$project = basename(__DIR__ . '/../../../../');
echo $project; // video

A: use regex like the following to manipulate the string
(?<=www\/)[^\/]+


text:
Q: Composition Method for negative term I'm a undergraduate student now learning a graduate simulation course, and I met some problems.
The Professor ask us to sample this function by composition method. Its CDF and PDF are like:
$$
F(x)=1-e^{-x}-e^{-2x}+e^{-3x} \\
f(x)=-3e^{-3x}+2e^{-2x} +e^{-x}
$$
I found out the PDF has a negative term $-3x$, and I don't know how to deal with it.
P.S. The Professor taught us the examples but there're all positive terms.
thx btw.

A: Rewrite your density as $(e^{-x} - e^{-3x}) + 2(e^{-2x} - e^{-3x})$. Neither $e^{-x} - e^{-3x}$ nor $e^{-2x} - e^{-3x}$ are proper densities, but you can check that
\begin{align}
f_1(x) &= \tfrac{3}{2}(e^{-x} - e^{-3x}),\\
f_2(x) &= 6(e^{-2x} - e^{-3x})
\end{align}
are. That means you can write your $f$ as
\begin{align*}
f(x) &= \tfrac{2}{3}f_1(x) + (2)(\tfrac{1}{6})f_2(x) \\
&= \tfrac{2}{3}f_1(x) + \tfrac{1}{3}f_2(x).
\end{align*}
So one possible composition method is:

*

*Generate $U$ uniformly from $[0, 1]$.

*If $U \leq \tfrac{2}{3}$ generate a variate from $f_1$; otherwise from $f_2$.

The latter step is easy since you can use sums of two exponentially distributed variates. Generate $E$ and $E'$ as independent exponentially distributed, each with mean 1. If you need an $f_1$ return $E + \tfrac{1}{3}E'$. Otherwise $\tfrac{1}{2}E + \tfrac{1}{3}E'$ gives you an $f_2$.


text:
Q: Linux bash shell copy previous lines (not history) with keyboard Is it possible to use the keyboard in order to select some text in the terminal windows that is not in the currently edited line? (for example, in order to copy part of previous command output).

A: As far as I know, neither of the "big three" terminal emulators can do that, but both screen and tmux offer a scrollback buffer you can access via keyboard.
GNU screen
screen's Prefix key is Ctrl+A per default, but all of that is customizable, so with a default config:

*

*Enter copy mode with Ctrl+A[.

*Move cursor around with vi motions: h, j, k, l, 0, ^, $, H, M, L, w, b, e,  /,  ?, g and G all work (see man screen under copy for more info on key bindings).

*Start selecting with Space, move around, and stop selecting with Space again. This will leave copy mode.

*Paste the selected text with Ctrl+A].
tmux
tmux behaves pretty much the same, except it uses some different keys per default:

*

*Enter copy mode with Ctrl+B[.

*Move cursor around with ←, ↓, ↑, →, PgUp, PgDown etc. (see man tmux | less -p '^WINDOWS AND PANES' for the list of copy-mode bindings).

*Start selecting with Ctrl+Space, move around, and stop selecting with Meta+w. This will leave copy mode.

*Paste the selected text with Ctrl+B].

A: Depends on the terminal you use. It is possible in shell mode in emacs.

A: It's not quite what you're asking, but if you redirect output through xclip, you can pull it from the clipboard and edit it.  I never thought about using it to minimize keyboard use.
$ echo "this is the primary buffer" | xclip -selection "primary"
$ cat << EOF > primary.txt
> this is the primary buffer
> EOF

Under gnome-terminal, I can use shift-insert to paste into the here-file.  From the man page xclip -selection "clipboard" does the real clipboard instead of the x buffer.
I can't seem to get it working with tee though... hmmm....  that's kind of important.


text:
Q: How to get the title or another attribute of an Image in PHP I am building a custom shirt builder for a website http://mytempsite.net/gotie/mixandmatch
What I have setup is step one, they will select a shirt color from 12 different shirts and then move on to the next step where they will be able to choose a tie. I need to be able to pass a variable to that next page telling it to only pull images with ties on it for example the red shirt.
My thought of doing this is by having that attribute at the image alt or title tag and then getting that attribute from the current image that is being displayed.
What i need to know is how?
i tried using this code as a start
<?php
    $url=$this->helper('core/url')->getCurrentUrl();;

    $html = file_get_contents($url);

    $doc = new DOMDocument();
    @$doc->loadHTML($html);

    $divs = $doc->getElementByID('loadarea');

    foreach ($divs as $div) {
           echo "Found the loadarea div
";
    }
?>

but it didn't work, and it also caused my page to load really slowly.
just in case here is code to thumbnails
<?php
    $products = Mage::getModel('catalog/product')->getCollection();

    foreach($products as $prod) {
        $product = Mage::getModel('catalog/product')->load($prod->getId());
        $pro_title = $product->getName();
        $img = $product->getImageUrl();

        echo "";

}?>

I hope that i worded this question correctly as to not be too localized. If so i will reword it.

A: I believe $someVar = get_field('image file') should return an array of all the tagged data in the image.  You can then access the data from the array (ie. $someVar['alt']).
Here is a simpler solution that doesn't require you make the image into an object.
$html=file_get_contents("URL OF YOUR SITE");
$doc = new DOMDocument();
@$doc -> loadHTML($html);
    // Add a class to your big image to identify it (ex. selected)
$tags = getElementsByClassName($doc, 'selected');
foreach ($tags as $tag) {
    echo $tag->getAttribute('alt');
}

    // Not my function but its very useful.  I'll track down where I got it
    // and add source later.
function getElementsByClassName(DOMDocument $DOMDocument, $ClassName) {
    $Elements = $DOMDocument -> getElementsByTagName("*");
    $Matched = array();

    foreach($Elements as $node)
    {
        if( ! $node -> hasAttributes())
            continue;

        $classAttribute = $node -> attributes -> getNamedItem('class');

        if( ! $classAttribute)
                continue;

        $classes = explode(' ', $classAttribute -> nodeValue);

        if(in_array($ClassName, $classes))
            $Matched[] = $node;
    }

    return $Matched;
}

A: What i ended up doing is when the thumbnail image gets clicked a hidden text box gets the product_id of that shirt and then when you go to the next page it automatically pulls the product image of that product. I have inserted the code for my entire form incase anyone ever needs to do this in the future :)
Happy Coding!
         <form id="GoTie_Builder" method="POST" action="/gotie/mixandmatch/tie">

                            <?php
                                $cat_id = 8;
                                $products = Mage::getModel('catalog/category')->load($cat_id)->getProductCollection();
                                echo '<input id="shirt_color" type="text" name="shirt_color" value="0">';
                                foreach($products as $prod) {
                                    $product = Mage::getModel('catalog/product')->load($prod->getId());

                                    $pattern = $this->helper('catalog/image')->init($product, 'thumbnail');

                                    //echo "";

                                    $pro_id = $product->getId();
                                    $pro_title = $product->getName();
                                    $img = $product->getImageUrl();

                                    $input_id = "shirt_color";
                                    echo "helper('catalog/image')->init($product, 'thumbnail')."' alt='".$pro_id."' width='100px' height='100px'/>";

         }?>

         <input type="submit" value="Choose a Tie" />
         </form>


text:
Q: Range-based loop use another operator I have a prime generator based on what I've seen in python by Sieve of Eratosthenes so this generator basically generate prime numbers with good performances.
What I would want is to use the range based loop on a range of prime number so here is what I did :
//Consider prime_generator a class with both operator*, operator!= and operator< overloaded

class primes_range {
private:
    unsigned int max;
public:
    primes_range(unsigned int max) : max(max) {}
    prime_generator begin() const {
        return prime_generator(); //so this generator begin from 2 to
                                  //infinity and beyond but of course
                                  //all primes
    }
    prime_generator end() const {
         prime_generator result;
         for (:*result < max; ++result) {} //so this thing actually create a
                                           //generator and increment it until it
                                           //gives the first prime number
                                           //above max so it basically do
                                           //all the work that I don't
                                           //want it to do now
         return rest;
    }
};

So in my main, I would want to use the range-based loop, that's the point of the primes_range class.
int main() {
    for (auto && i : primes_range(10)) { //So here, this is silly because
                                         //the range-based loop will use end()
                                         //wich will calculate all the prime
                                         //numbers at the very beginning
                                         //and i will increment apart from
                                         //this starting process
        cout << i << endl;
    }
    return 0;
}

Of course instead I could use a simple loop :
int main() {
    for (prime_generator pg; *pg < 10; ++pg) {
        cout << *pg << endl;
    }
    return 0;
}

But because the range-base loop is easier to read and prevent to use the operator*, I would want to use it instead, so my question is : Is there a way to make the range-base loop use another operator than != (in this case <) ? Maybe overloard a particular function for primes_range or specialize a comparator ?

A: Instead of doing the whole work on the end() method your iterator must generate the next prime number at each call to operator++ and then returning them in the calls to operator*. So the scheme for your iterator class may be:
class prime_generator {
   typedef std::forward_iterator_tag iterator_category;
   int cur;
   prime_generator& operator++() {
      cur = GenerateNextPrime();
      return *this;
   }
   int operator*() {
      return curr;
   }
};

NOTES:

*

*For the range-based for to work you need at least operator++ and operator* on your iterator class, with the signatures above.

*The forward_iterator_tag declared in the iterator class tell what kind of iterator you are creating. In this case a forward iterator is one that suport the "get next" operation via operator++ but not random access via indexing for example. It is a good practice to declare this category field in iterator classes in order to hint the standard library methods about the best algorithms to use with your iterators.

A: Here is a complete example on iterators. I forgot to mention above the you need operator!= for the range based for to work because it must compare the current iterator to the result of the end() method. In the code below you just have to place the correct implementation of your algorithm in the generate_next_prime function, or place it inside the casses as you wish.
#include <iostream>
#include <iterator>

int generate_next_prime(int previous) {
    // TODO: a correct one!
    return previous + 1;
}

class prime_generator {
    int limit;

public:

    prime_generator(int limit)
        : limit(limit) {}

    class iterator {
        int cur, limit;

    public:

        typedef std::forward_iterator_tag iterator_category;

        iterator(int cur, int limit)
            : cur(cur), limit(limit) {}

        iterator& operator++() {
            cur = generate_next_prime(cur);
            return *this;
        }

        bool operator==(const iterator &other) {
            // NOTE: for the primes application maybe you should
            // use >= instead of == to ensure cur will not pass limit
            // silently, or do something more elaborate
            return cur == other.cur &&
                   limit == other.limit;
        }

        bool operator!=(const iterator &other) {
            return !(*this == other);
        }

        int operator*() {
            return cur;
        }
    };

    iterator begin() {
        return iterator(2, limit);
    }

    iterator end() {
        return iterator(limit, limit);
    }
};

int main() {
    for (auto p : prime_generator(5))
        std::cout << p << std::endl;

    return 0;
}

A: Based on what you told me, I come here with a solution, this is basically an adapter.
class primes_range {
private:
    unsigned int max;

    class limited_prime_generator {
    private:
        prime_generator pg;
        unsigned int limit;
        bool reachedLimit;

    public:
        limited_prime_generator(unsigned int limit, bool reachedLimit = false) : pg(), limit(limit), reachedLimit(reachedLimit) {}

        limited_prime_generator & operator++() {
            if (not reachedLimit) {
                reachedLimit = *(++pg) >= limit;
            }

            return *this;
        }
        bool operator!=(limited_prime_generator const & lpg) const {
            return operator*() != *lpg;
        }
        unsigned int operator*() const {
            if (reachedLimit)
                return limit;
            else
                return *pg;
        }
    };

public:
    primes_range(unsigned int max) : max(max) {}

    limited_prime_generator begin() const {
        return limited_prime_generator(max);
    }

    limited_prime_generator end() const {
        return limited_prime_generator(max, true);
    }
};