Q: Spring: Exception when trying to start server When I run the Application.java file I get this exception
java.lang.SecurityException: class "javax.servlet.MultipartConfigElement"'s signer information does not match signer information of other classes in the same package

I'm using eclipse with gradle
Application.Java:
package com.overip.server;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@EnableWebMvc
@ComponentScan
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args){
        SpringApplication.run(Application.class, args);
    }

}

The whole exception thrown:
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.0.2.RELEASE)

2014-10-29 08:41:39.629  INFO 122080 --- [           main] com.overip.server.Application            : Starting Application on Dell-PC with PID 122080 (started by Fady & Emad in C:\Users\Fady & Emad\workspace\OverIP)
2014-10-29 08:41:39.688  INFO 122080 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6d463b81: startup date [Wed Oct 29 08:41:39 EET 2014]; root of context hierarchy
2014-10-29 08:41:40.619  INFO 122080 --- [           main] .b.l.ClasspathLoggingApplicationListener : Application failed to start with classpath: [file:/C:/Users/Fady%20&%20Emad/workspace/OverIP/bin/, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-starter-web/1.0.2.RELEASE/fb26276f8400658e15d571350c5b577dfe40567a/spring-boot-starter-web-1.0.2.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/mysql/mysql-connector-java/5.1.33/8af455a9a3267e6664cafc87ace71a4e4ef02837/mysql-connector-java-5.1.33.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-starter-actuator/1.0.2.RELEASE/699771411accffc41656db59ae51dd6663a653d6/spring-boot-starter-actuator-1.0.2.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-starter-aop/1.0.2.RELEASE/58b239d692c4fab48dc8c430eabd527a2e153816/spring-boot-starter-aop-1.0.2.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-starter-test/1.0.2.RELEASE/ccab7d782c8a8bf95c06573edd2f40d7da332e36/spring-boot-starter-test-1.0.2.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/com.google.guava/guava/17.0/9c6ef172e8de35fd8d4d8783e4821e57cdef7445/guava-17.0.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/com.squareup.retrofit/retrofit/1.6.0/39a9e4b49ded46aa1b67d492fe287c4cebcd815c/retrofit-1.6.0.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/commons-io/commons-io/2.4/b1b6ea3b7e4aa4f492509a4952029cd8e48019ad/commons-io-2.4.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/javax.servlet/servlet-api/2.5/5959582d97d8b61f4d154ca9e495aafd16726e34/servlet-api-2.5.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-starter-jetty/1.0.2.RELEASE/6f8da7ee1e540b2f21f99946ca74eb1726f2fd82/spring-boot-starter-jetty-1.0.2.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/junit/junit/4.11/4e031bb61df09069aeb2bffb4019e7a5034a4ee0/junit-4.11.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/commons-logging/commons-logging/1.1.3/f6f66e966c70a83ffbdb6f17a0919eaf7c8aca7f/commons-logging-1.1.3.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework/spring-core/4.0.3.RELEASE/138d28200d97f4affe9ccaa47fab54718b438319/spring-core-4.0.3.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework/spring-beans/4.0.3.RELEASE/41eabd53fd4ba5ba2b2d8af6c256a3741f65c2f3/spring-beans-4.0.3.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/aopalliance/aopalliance/1.0/235ba8b489512805ac13a8f9ea77a1ca5ebe3e8/aopalliance-1.0.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework/spring-aop/4.0.3.RELEASE/dcedf5329d7092d66cc9d2496687a5f29d883eb6/spring-aop-4.0.3.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework/spring-expression/4.0.3.RELEASE/40b25b3a693cb4cc382ddf2e69ff1b29c75a2e7d/spring-expression-4.0.3.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework/spring-context/4.0.3.RELEASE/782a71a312dc307fa531023aa66247b9b4a109d/spring-context-4.0.3.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot/1.0.2.RELEASE/8d1a06e468b16577075db27123091758b6f880af/spring-boot-1.0.2.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-autoconfigure/1.0.2.RELEASE/3a70e3021aec334ee8b1a454ea791d27997a7191/spring-boot-autoconfigure-1.0.2.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.slf4j/slf4j-api/1.7.7/2b8019b6249bb05d81d3a3094e468753e2b21311/slf4j-api-1.7.7.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.slf4j/jcl-over-slf4j/1.7.7/56003dcd0a31deea6391b9e2ef2f2dc90b205a92/jcl-over-slf4j-1.7.7.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.slf4j/jul-to-slf4j/1.7.7/def21bc1a6e648ee40b41a84f1db443132913105/jul-to-slf4j-1.7.7.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.slf4j/log4j-over-slf4j/1.7.7/d521cb26a9c4407caafcec302e7804b048b07cea/log4j-over-slf4j-1.7.7.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/ch.qos.logback/logback-core/1.1.2/2d23694879c2c12f125dac5076bdfd5d771cc4cb/logback-core-1.1.2.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/ch.qos.logback/logback-classic/1.1.2/b316e9737eea25e9ddd6d88eaeee76878045c6b2/logback-classic-1.1.2.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-starter-logging/1.0.2.RELEASE/47a20c5bad47916ca99d768782de12c54b707a00/spring-boot-starter-logging-1.0.2.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-starter/1.0.2.RELEASE/a6cbc3adc8d95a0e5405d3c1ca30ad8e6bed1cf1/spring-boot-starter-1.0.2.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.yaml/snakeyaml/1.13/73cbb494a912866c4c831a178c3a2a9169f4eaad/snakeyaml-1.13.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/com.fasterxml.jackson.core/jackson-annotations/2.3.0/f5e853a20b60758922453d56f9ae1e64af5cb3da/jackson-annotations-2.3.0.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/com.fasterxml.jackson.core/jackson-core/2.3.3/7d8c5d79cc99995e21e6f955857312d8409f02a1/jackson-core-2.3.3.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/com.fasterxml.jackson.core/jackson-databind/2.3.3/63b77400b5f1cf83a81823562c48d3120ef5518e/jackson-databind-2.3.3.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework/spring-web/4.0.3.RELEASE/4d5066f31ea4b9c58957bf8c0c213b13ed44c1c5/spring-web-4.0.3.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework/spring-webmvc/4.0.3.RELEASE/d6fd9778619ab87a41ae3aa879a53ee60f160c08/spring-webmvc-4.0.3.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-actuator/1.0.2.RELEASE/ec33fd737d646dc4e092176bee856245e2f02f8c/spring-boot-actuator-1.0.2.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.aspectj/aspectjrt/1.7.4/e49a5c0acee8fd66225dc1d031692d132323417f/aspectjrt-1.7.4.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.aspectj/aspectjweaver/1.7.4/d9d511e417710492f78bb0fb291a629d56bf4216/aspectjweaver-1.7.4.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.hamcrest/hamcrest-core/1.3/42a25dc3219429f0e5d060061f71acb49bf010a0/hamcrest-core-1.3.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.objenesis/objenesis/1.0/9b473564e792c2bdf1449da1f0b1b5bff9805704/objenesis-1.0.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.mockito/mockito-core/1.9.5/c3264abeea62c4d2f367e21484fbb40c7e256393/mockito-core-1.9.5.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.hamcrest/hamcrest-library/1.3/4785a3c21320980282f9f33d0d1264a69040538f/hamcrest-library-1.3.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework/spring-test/4.0.3.RELEASE/76b870a5aa132b4c0dd78cd061feb3e1652cddd1/spring-test-4.0.3.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/com.google.code.gson/gson/2.2.4/a60a5e993c98c864010053cb901b7eab25306568/gson-2.2.4.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-util/8.1.14.v20131031/43063284480a41eca024dc8852452eedf6379c16/jetty-util-8.1.14.v20131031.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-xml/8.1.14.v20131031/8732c74817fef6d2e3e667636e6c4f27fb4cada9/jetty-xml-8.1.14.v20131031.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-continuation/8.1.14.v20131031/e3396abd21360191c2277e848eff489b58bba45d/jetty-continuation-8.1.14.v20131031.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-io/8.1.14.v20131031/12f6f92d7e58349501f2cfc0716b8f1c6a2962eb/jetty-io-8.1.14.v20131031.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-http/8.1.14.v20131031/8dd4e01b374e16cf0335b7975a7aa0a57396d5da/jetty-http-8.1.14.v20131031.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-server/8.1.14.v20131031/7f7f9b929b9d9169dd68f36327c819ab9a03a661/jetty-server-8.1.14.v20131031.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-security/8.1.14.v20131031/d6fd7add8e6015a95558b67b43edf7752a925884/jetty-security-8.1.14.v20131031.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-servlet/8.1.14.v20131031/2ea127b7001965201d28ce715f5754573205c4ae/jetty-servlet-8.1.14.v20131031.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-webapp/8.1.14.v20131031/1f29371c74381ac42f961e9b984a7af28cc62093/jetty-webapp-8.1.14.v20131031.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.orbit/javax.servlet/3.0.0.v201112011016/aaaa85845fb5c59da00193f06b8e5278d8bf3f8/javax.servlet-3.0.0.v201112011016.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.orbit/javax.servlet.jsp/2.2.0.v201112011158/80b4ffe7c26ee97313bea2ddda5835fd38812ee4/javax.servlet.jsp-2.2.0.v201112011158.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.orbit/org.apache.jasper.glassfish/2.2.2.v201112011158/3945afe6a042228a92da320aec3fa1bc1308183b/org.apache.jasper.glassfish-2.2.2.v201112011158.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.orbit/javax.servlet.jsp.jstl/1.2.0.v201105211821/db594f1c8fc00d536f6d135bd7f8a9a99a6b8eea/javax.servlet.jsp.jstl-1.2.0.v201105211821.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.orbit/org.apache.taglibs.standard.glassfish/1.2.0.v201112081803/2c4baa72af1d3aae3a1e029d4f8ca07498dabbe0/org.apache.taglibs.standard.glassfish-1.2.0.v201112081803.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.orbit/javax.el/2.2.0.v201108011116/ec8944c11833d84b0283a5afbad0fafb264f86a9/javax.el-2.2.0.v201108011116.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.orbit/com.sun.el/2.2.0.v201108011116/15f7774c3fa514835a371f47c152317704ea411a/com.sun.el-2.2.0.v201108011116.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.orbit/org.eclipse.jdt.core/3.7.1/5b79bfee0852ca685e33cab74496fa3400271b5b/org.eclipse.jdt.core-3.7.1.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-jsp/8.1.14.v20131031/87dc1723a32113d74be2420d940f6825e3b6af42/jetty-jsp-8.1.14.v20131031.jar]
2014-10-29 08:41:40.622  INFO 122080 --- [           main] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6d463b81: startup date [Wed Oct 29 08:41:39 EET 2014]; root of context hierarchy
2014-10-29 08:41:40.629  WARN 122080 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception thrown from ApplicationListener handling ContextClosedEvent

java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6d463b81: startup date [Wed Oct 29 08:41:39 EET 2014]; root of context hierarchy
at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:346)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:333)
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:880)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.doClose(EmbeddedWebApplicationContext.java:152)
at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:841)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:329)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:909)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:898)
at com.overip.server.Application.main(Application.java:16)

2014-10-29 08:41:40.630  WARN 122080 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception thrown from LifecycleProcessor on context close

java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6d463b81: startup date [Wed Oct 29 08:41:39 EET 2014]; root of context hierarchy
at org.springframework.context.support.AbstractApplicationContext.getLifecycleProcessor(AbstractApplicationContext.java:359)
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:888)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.doClose(EmbeddedWebApplicationContext.java:152)
at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:841)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:329)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:909)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:898)
at com.overip.server.Application.main(Application.java:16)

Exception in thread "main" java.lang.SecurityException: class "javax.servlet.MultipartConfigElement"'s signer information does not match signer information of other classes in the same package
at java.lang.ClassLoader.checkCerts(Unknown Source)
at java.lang.ClassLoader.preDefineClass(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at org.springframework.util.ClassUtils.forName(ClassUtils.java:236)
at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getBeanNamesForType(OnBeanCondition.java:144)
at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getMatchingBeans(OnBeanCondition.java:113)
at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getMatchOutcome(OnBeanCondition.java:75)
at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:44)
at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:92)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader$TrackedConditionEvaluator.shouldSkip(ConfigurationClassBeanDefinitionReader.java:400)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:127)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:116)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:324)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:254)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:94)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:609)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:120)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:648)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:311)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:909)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:898)
at com.overip.server.Application.main(Application.java:16)


Q: Open documents(pdf,doc,docx,txt) in browser page using php (without using google docs viewer) My question is that i want to open documents(pdf,doc,docx,txt) in browser page using php (without using google docs viewer) can any one help me?

A: Some of these are doable.  Some, not so much.  Let's tackle the low-hanging fruit first.
Text files
You can just wrap the content in <pre> tags after running it through htmlspecialchars.
PDF
There is no native way for PHP to turn a PDF document into HTML and images.  Your best bet is probably ImageMagick, a common image manipulation program.  You can basically call convert file.pdf file.png and it will convert the PDF file into a PNG image that you can then serve to the user.  ImageMagick is installed on many Linux servers.  If it's not available on your host's machine, please ask them to install it, most quality hosts shouldn't have a problem with this.
DOC & DOCX
We're getting a bit more tricky.  Again, there's no way to do this in pure PHP.  The Docvert extension looks like a possible choice, though it requires OpenOffice be installed as well.  I was actually going to recommend plain vanilla OpenOffice/LibreOffice as well, because it can do the job directly from the command line.  It's very unlikely that a shared host will want to install this.  You'll probably need your own dedicated or virtual private server.
In the end, while these options can be made to work, the output quality is not guaranteeable.  Overall, this is kind of a bad idea that you should not seriously consider implementing.

A: I am sure libraries and such exist that can do this. Google could probably help you there more than I can.
For txt files I would suggest breaking lines after a certain number of characters and putting them inside pre tags.
I know people will not be happy about this response, but if you are on a Linux environment and have pdf2html installed you could use shell_exec and call pdf2html.
Note: If you use shell_exec be wary of what you pass to it since it will be executed on the server outside of PHP.

A: I thought I'd just add that pdfs generally view well in a simple embed tag.
Or use an object so you can have fall backs if it cannot be displayed on the client.


Q: определение максимального возможного размера строки в стеке #include <iostream>

// заголовок
const std::ostream& os = std::cout << "\t\t\tR\tA\tM\n" << std::endl;

int main()
{
    std::string s;
    try {
        s.resize(s.max_size());
        std::cout << s.max_size();
    }
    catch(std::bad_alloc)
    {
        std::cout << "Generated an exception std::bad_alloc\n"
                  <<"RAM_size ==  s.max_size()?..";
    }
    return 0;
}

Не очень то ясно, почему все таки генерируется исключение, если размер строки устанавливаю на максимально возможный?..  И как определить  размер строки, не генерирующий исключение?  Просветите пожалуйста

A: Как указано, например, тут тыц. max_size - это потенциально возможный максимальный размер строки, определяемый либо параметрами системы, либо ограничениями, заданными в реализации. И опять же, как сказано в описании по ссылке, не дается никаких гарантий, что данный размер может быть достигнут.

A: Максимально возможный - это сколько в переменную размера влезет, а не сколько можно реально получить. На 32-разрядном получите, например, 2147483647 - но столько памяти не выделяемо в принципе (в 64-разрядной все еще хуже).
Как узнать? Да вряд ли есть разумный способ... типа методом типа бинарного поиска смотреть, когда памяти не хватает :) Но вопрос - зачем вам это знать заранее?

A: Сначала вам надо было бы распечатать значение max_size() - тогда стало бы понятно, почему не удается выполнить выделение памяти.
Например, в GCC max_size() возвращает 0x7fffffffffffffff, то есть половину диапазона 64-битного целого типа, половину диапазона std::size_t. А это, как известно, максимальный размер объекта/максимальный размер массива/максимальный размер динамически выделяемого блока памяти в GCC (и во многих других реализациях).
Так как блок памяти, который std::string будет пытаться выделять для хранения строки такой длины будет включать дополнительную информацию, неудивительно, что выделение памяти заканчивается безуспешно. Почему авторы станадартной библиотеки GCC не "урезали" величину max_size() соответствующим образом - вопрос к ним. Но формальной ошибки в этом нет, ибо практической возможности создания строки такого размера вам никто не гарантировал.


Q: How to process an array of task asynchronously with swift combine I have a publisher which takes a network call and returns an array of IDs. I now need to call another network call for each ID to get all my data. And I want the final publisher to have the resulting object.
First network result:
"user": {
   "id": 0,
   "items": [1, 2, 3, 4, 5]
}

Final object:
struct User {
    let id: Int
    let items: [Item]
    ... other fields ...
}
struct Item {
    let id: Int
    ... other fields ...
}

Handling multiple network calls:
userPublisher.flatMap { user in
    let itemIDs = user.items
    return Future<[Item], Never>() { fulfill in
        ... OperationQueue of network requests ...
    }
}

I would like to perform the network requests in parallel, since they are not dependent on each other. I'm not sure if Future is right here, but I'd imagine I would then have code to do a
DispatchGroup or OperationQueue and fulfill when they're all done. Is there more of a Combine way of doing this?
Doe Combine have a concept of splitting one stream into many parallel streams and joining the streams together?

A: Combine offers extensions around URLSession to handle network requests unless you really need to integrate with OperationQueue based networking, then Future is a fine candidate. You can run multiple Futures and collect them at some point, but I'd really suggest looking at URLSession extensions for Combine.
struct User: Codable {
   var username: String
}

let requestURL = URL(string: "https://example.com/")!
let publisher = URLSession.shared.dataTaskPublisher(for: requestURL)
    .map { $0.data }
    .decode(type: User.self, decoder: JSONDecoder())

Regarding running a batch of requests, it's possible to use Publishers.MergeMany, i.e:
struct User: Codable {
   var username: String
}

let userIds = [1, 2, 3]

let subscriber = Just(userIds)
    .setFailureType(to: Error.self)
    .flatMap { (values) -> Publishers.MergeMany<AnyPublisher<User, Error>> in
    let tasks = values.map { (userId) -> AnyPublisher<User, Error> in
            let requestURL = URL(string: "https://jsonplaceholder.typicode.com/users/\(userId)")!

            return URLSession.shared.dataTaskPublisher(for: requestURL)
                .map { $0.data }
                .decode(type: User.self, decoder: JSONDecoder())
                .eraseToAnyPublisher()
    }
    return Publishers.MergeMany(tasks)
}.collect().sink(receiveCompletion: { (completion) in
    if case .failure(let error) = completion {
        print("Got error: \(error.localizedDescription)")
    }
}) { (allUsers) in
    print("Got users:")
    allUsers.map { print("\($0)") }
}

In the example above I use collect to collect all results, which postpones emitting the value to the Sink until all of the network requests successfully finished, however you can get rid of the collect and receive each User in the example above one by one as network requests complete.


Q: Negatively Correlated Events I showed the following inequality to a colleague, where $A$ and the $B_i$ are all events:
$$
\Pr\left(A \mid \bigwedge_{i = 1}^n \overline{B_i} \right) \leq \Pr(A)
$$
He summarized, "So $A$ is negatively correlated with the $B_i$."
I have never heard this phrase used to refer to events. Even when it is used with respect to random variables, I'm not sure it is quite the same thing.
Could a more experience probabilist chime in? Does his terminology make sense? Is there a better word?

A:
Does his terminology make sense?

It does: events $A$ and $B$ are negatively correlated if and only if $\mathbb P(A\cap B)\leqslant\mathbb P(A)\mathbb P(B)$, random variables $X$ and $Y$ are negatively correlated if and only if $\mathbb E(XY)\leqslant\mathbb E(X)\mathbb E(Y)$.


Q: Use binding file to set the package on a namespace? I'm working on two large 3rd party schemas, one includes the other and generates a large number of type name collisions. If I could set the package on a namespace this problem would go away.
I hoped something like
<jaxb:bindings namespace="http://www.openapplications.org/oagis/9" >
    <jaxb:schemaBindings>
        <jaxb:package name="org.oagis" />
    </jaxb:schemaBindings>
</jaxb:bindings>

would work, or perhaps
<jaxb:bindings node="/xsd:schema[@targetNamespace='http://www.openapplications.org/oagis/9']">
    <jaxb:schemaBindings>
        <jaxb:package name="org.oagis" />
    </jaxb:schemaBindings>
</jaxb:bindings>

But no joy.
Trying to set on the individual xsd files in that namespace left me with the dread
[ERROR] Multiple <schemaBindings> are defined for the target namespace "http://www.openapplications.org/oagis/9"

Pointers/suggestions are appreciated.

A: This is a bit hard to answer without seeing the whole compilation. However I often got this error when compiling third-party schemas in the case when the same schema was included via different URLs.
I.e. I've implemented a project which compiled an extensive set of OGC Schemas. The problem was that these schemas referenced each other via relative and absolute URLs. So when I customized one of the schemas there were other schemas for the same namespace URI. Since JAXB processes imports and includes, it is not quite transparent what exactly gets compiled. Try to check your XJC logs for cues or - if you compile schemas directly via URLs (which is not recommended) - go through a logging proxy and see what actually gets accessed.


Q: Taylor series for linearization I need to apply Taylor series to linearize following equation
$$f_{dr}= Au'+ Bu + C u^2 +D$$
Here, $A$, $B$, $C$, $D$ are constants and $$u'=\frac{{\rm d}u}{{\rm d}t}, u=\frac{{\rm d}x}{{\rm d}t}$$
While applying Taylor series should I differentiate with respect to $t$ or $u$?


Q: Does Kafka broker server take into account updates to it's configuration file? Does Kafka broker server take into account updates to it's configuration file?
Its cumbersome having to restart all the servers in the cluster simply to update a configuration.

A: No, it's currently not possible to do dynamic configuration updates.
There's a Jira ticket for that exact issue here, and the accompanying KIP (Kafka Improvement Proposal).


Q: Is it acceptable to say "I am off" in meaning that I'm tired or something like that? Is it acceptable in English to say "I am off" in meaning that I'm tired or something like that? I heard it from non native English speaker, that's why I'm not sure about it.

A: Not quite.

Well, I'm off!

Means that you're leaving. See: TheFreeDictionary - I'm off.

This song sounds/feels a little off.

Means that there is something not quite right about this song to you. It feels weird. A thread on ELU about that: What does the idiom “to sound a little off” mean?
If you wanna say you're not feeling well, you could say:

I'm feeling a bit under the weather, I think I'm going to go home.

A: It's possible you may be thinking of

I'm a bit off (BrE)
I am feeling unwell

and therefore the speaker is feeling tired as a result.
To only express tired might be

I'm tired (obviously)
  I'm knackered (BrE)

Usually expressing tiredness and sickness are kept separate.
As pointed out, simply using "I'm off" would usually mean

I'm off (to some destination)
I'm leaving/going

A: Off means many things, including not being normal, being sub-standard, or separated from a place or thing. It does not mean "tired," and if you were to state this, a native speaker would understand it to mean that you're feeling unusual or are ill.

A: Yes, I think so. It may be a little unusual, but I think it would be understood easily by a high percentage of native speakers.
The more "usual" statement would be "I feel [a little] off" or "I'm a little off" or "I'm off my game", etc. but I think "I am off" or "I'm off" are adequate and perfectly understandable.


Q: In what circumstances is uri passed to Android's ContentObserver.onChange() callback? The onChange() method of Android's ContentObserver class says, "Includes the changed content Uri when available." In what circumstances is the URI available? In what circumstances is it not available?
The uri parameter was added in API level 16 (Android 4.1) and so I would expect it to be set in Android 4.1 and newer. However I'm seeing a case on Android 4.3 where uri is not set.
Method 1: Works
MyContentObserver.onChange() is called and is passed a valid uri:
contentResolver.registerContentObserver(myUri, true, new MyContentObserver());

Method 2: Doesn't work--why not?
MyContentObserver.onChange() is called but the uri parameter is null:
contentResolver.query();
cursor.registerContentObserver(new MyContentObserver);

Is this expected? Is one of these preferred over the other? I've tested this using "content://com.google.android.gm/me@example.com/labels" and using my own custom ContentProvider.

A: This is an old question, but still unanswered. So I will add my answer in case people is still curious about it.
When your content provider notifies the registered observer using getContext().getContentResolver().notifyChange(URI, "your_uri");, it asks the ContentResponder for it. The return value from that method is the ContentObserver that you registered with the registerContentObserver() method of the content responder, which is what you did in the first case. However, in the second case, you registered the observer in the Cursor using the registerContentObserver() method of the Cursor, so the ContentResponder doesn't know about it.

A: If you are setting ContentObserver upon common tables(e.g people, mediaprovider etc) then unfortunately you might not receive any Uri as an argument, it might be blank as it depends upon underneath content provider implementation. To receive an valid Uri upon change, respective ContentProvider has to be modified to notify change along with URI.
e.g getContext().getContentResolver().notifyChange(Uri, "your_uri"); // this notifies all the  registered ContentObserver with Uri of modified concerned dataset.
If you are writing your own ContentProvider then use above mentioned line whenever you perform update, delete or insert operation on your database.


Q: How to trigger the marginal note in two column layout I am using marginal note package in two column layout. The below mentioned command does not trigger the two column left and right side.
\ifodd\value{page}
\if@firstcolumn\reversemarginpar\else\normalmarginpar\fi
\else
\if@firstcolumn\reversemarginpar\else\normalmarginpar\fi
\fi

This if then else condition does not working for me.
MWE
    \documentclass[twocolumn]{article}

\usepackage{multicol}
\usepackage{lipsum}
\usepackage{marginnote}

\makeatletter
\let\oldmarginnote\marginnote
\renewcommand*{\marginnote}[1]{%
   \begingroup%
   \ifodd\value{page}
     \if@firstcolumn\reversemarginpar\fi
   \else
     \if@firstcolumn\else\reversemarginpar\fi
   \fi
   \oldmarginnote{#1}%
   \endgroup%
}
\makeatother

\begin{document}

\lipsum[1]\marginnote{Odd page left side note}[-50pt]

\lipsum[2]
\lipsum[3]
\lipsum[4]\marginnote{Odd page right side note}[-50pt]
\lipsum[5]
\lipsum[6]
\lipsum[7]\marginnote{even page left side note}
\lipsum[8]
\lipsum[9]
\lipsum[10]
\lipsum[11]
\lipsum[12]
\lipsum[13]
\lipsum[14]\marginnote{even page right side note}
\lipsum[15]
\lipsum[16]
\lipsum[17]

\clearpage

\onecolumn

\begin{multicols}{2}

\section{Multicol environment begins}

\lipsum[10]\marginnote{Multicol left side note}
\lipsum[11]
\lipsum[12]
\lipsum[13]
\lipsum[14]
\lipsum[15]
\lipsum[16]\marginnote{Multicol right side note}
\lipsum[17]

\end{multicols}

\end{document}

Currently i am using manually given \reversemarginpar and \normalmarginpar. My requirement is auto trigger is working if then else condition. Kindly advice.

A: The multicol package has a colaction option. You can then do column-dependent actions with the \docolaction command. The three arguments are the actions for the first, middle, and last columns.
This is a simple version but it doesn't handle the optional argument to marginnote (which comes after the mandatory argument, not before it).
    \documentclass{article}

    \usepackage[colaction]{multicol}
    \usepackage{lipsum}
    \usepackage{marginnote}

    \let\oldmarginnote\marginnote
    \renewcommand{\marginnote}[1]
         {\begingroup\docolaction{\reversemarginpar}{}{}\oldmarginnote{#1}\endgroup}

    \begin{document}

    \begin{multicols}{2}
    \section{Multicol environment begins}
    \lipsum[10]\marginnote{lipsum 10}
    \lipsum[11]\marginnote{lipsum 11}
    \lipsum[12]\marginnote{lipsum 12}
    \lipsum[13]\marginnote{lipsum 13}
    \lipsum[14]\marginnote{lipsum 14}
    \lipsum[15]\marginnote{lipsum 15}
    \lipsum[16]\marginnote{lipsum 16}
    \lipsum[17]\marginnote{lipsum 17}
    \end{multicols}

\end{document}

To handle the optional argument, we have to dig down inside the package and change the low-level command that actually does the work:
    \documentclass{article}

    \usepackage[colaction]{multicol}
    \usepackage{lipsum}
    \usepackage{marginnote}

    \makeatletter
    \let\old@mn@@@marginnote\@mn@@@marginnote
    \long\def\@mn@@@marginnote[#1]#2[#3]{%
      \begingroup
      \docolaction{\reversemarginpar}{}{}\old@mn@@@marginnote[{#1}]{#2}[{#3}]%
      \endgroup}
    \makeatother

    \begin{document}

    \begin{multicols}{2}
    \section{Multicol environment begins}
    \lipsum[10]\marginnote{lipsum 10}[-30pt]
    \lipsum[11]\marginnote{lipsum 11}
    \lipsum[12]\marginnote{lipsum 12}
    \lipsum[13]\marginnote{lipsum 13}[-30pt]
    \lipsum[14]\marginnote{lipsum 14}
    \lipsum[15]\marginnote{lipsum 15}[-30pt]
    \lipsum[16]\marginnote{lipsum 16}[-30pt]
    \lipsum[17]\marginnote{lipsum 17}
    \end{multicols}

\end{document}

A: alephzero's answer generally works well (after installing the latest version of multicol), but there was a major problem in my case: with a two-sided document it works correctly on odd pages, but on even pages marginnotes tries to automatically reverse the side it uses, resulting in the notes for the right column showing up on the left and vice versa.
This can be corrected with a \checkoddpage, which is built into memoir or can be obtained from the changepage package – you can simply reverse the opposite column's notes on even pages. I am not using the optional argument of marginnote, so I stuck with the first version and used:
\usepackage{marginnote}
\let\oldmarginnote\marginnote
\strictpagecheck
\renewcommand{\marginnote}[1]
  {%
    \checkoddpage%
    \ifoddpage%
      {\begingroup\docolaction{\reversemarginpar}{}{}\oldmarginnote{#1}\endgroup}%
    \else{%
      {\begingroup\docolaction{}{}{\reversemarginpar}\oldmarginnote{#1}\endgroup}}%
    \fi%
  }

Edit: It's important to declare \strictpagecheck, or captions in the first section of a page may end up on the wrong side.


Q: Swift tableView with 3 Prototype Cells and auto-height I have a concept which I want to realize in Xcode. Its a default  TableViewController with 3 Prototype cells.
Cell 1 = name (Prototype Pages)
Cell 2 = seperator (Prototype Seperator)
Cell 3 = only ImageView (Prototype Seperator-with-only-image)

Cell 1 and cell 2 is OK. I need to set the height of all "Prototype Seperator-with-only-image" cells to auto. The height should be calculated based on added image dimensions.
Here my mockup

Addional info: The "Prototype Seperator-with-only-image" can occur multiple times and the dimensions of the images can vary.
Any ideas how I can achieve this?

A: You can set the tableview's rowHeight equal to UITableViewAutomaticDimension in your viewDidLoad method:
    self.yourTableView.rowHeight = UITableViewAutomaticDimension
    self.yourTableView.estimatedRowHeight = 42.0

Here you are telling your tableview to calculate the dimension of the row.
Then you are saying that you estimate that the row will have a height of 42, basically setting a minimum height.
I think this is a great example using a demo app.


Q: Storing Multiple Changes in Entity Framework I'm trying to achieve a form of two phase commit  using Entity Framework 1.0.
What I would like to achieve at a high level is:

*

*get all the data from the database and store this in a cache.

*modify individual entities

*Commit all changes into the database

The problem's i've encountered so far is that caching an IQueryable is a bit pointless as it's going to go back to the database regardless. So the other option is to use IEnumberable for storing the results of a query, but that stops me inheriting one query and refining it into another (I can live with that however). The other problem is that as soon as the EntityContext expires (which i've managed to persist in the current httprequest) that's it, no changes can be tracked.
Has anyone tried to do something similar to this in the past or got any pointers?
Many thanks,
Matt
jumpingmattflash.co.uk

A: The IQueryable is just that a queryable object not the actual data.
You need to run the ToList to get the data out.
You can do what you are trying to do if you can keep the Context open and use transactionscope. In most cases however this is not possible. This would also lock the database leading to other probelms.
A better way to do it would be:

*

*Read the data from the database

*Dispose of the context

*Client makes any changes needed

*Open new context

*Read the data again.

*make changes by copying data from changed data to second set

*commit the changes

*dispose of the context

A: Call .ToList() on your IQueryable results from the database. To then start refining into other queries use .AsQueryable(). This should solve your first problem.
As for your second problem, I'm also searching for a solution. As I understand the underlying implementation of the relationship parts of Entity Framework revolves around the ObjectStateManager in the System.Data.Objects namespace of the System.Data.Entity assembly. This in turn uses the MetadataWorkspace class in the System.Data.Metadata.Edm namespace to lookup the relationship mappings. These might be able to be used without an underlying database connection, and if so, would provide some very groovy tools to update complex object graphs.
It would be nice if the context had a Detach and Attach in a similar way to individual Entities. It looks like the next version of the Entity Framework is going to focus on these specific type of issues; more freedom when dealing with Entities and Contexts.


Q: How to unit test HttpClient GetAsync I have the following in my controller:
public async Task<IActionResult> IndexAsync()
{
    string baseUrl = "https://apilink.com";

    using (HttpClient client = new HttpClient())
    using (HttpResponseMessage response = await client.GetAsync(baseUrl))
    using (HttpContent content = response.Content)
    {
        string data = await content.ReadAsStringAsync();
        if (data != null)
        {
            var recipeList = JsonConvert.DeserializeObject<Recipe[]>(data);
            return View();
        }
    }

    return View();
}

I want to unit test this but cannot work out how to test the HttpClient.
I have tried:
[Test]
public void Index_OnPageLoad_AllRecipesLoaded()
{
    var testController = new HomeController();
    mockHttpClient.Setup(m => m.GetAsync(It.IsAny<string>())).Returns(
        () => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
    mockHttpContent.Setup(m => m.ReadAsStringAsync()).Returns(() => Task.FromResult(LoadJson()));
    var result = testController.IndexAsync();
    Assert.IsNotNull(result);
}

// Loads the Json data as I don't actually want to make the API call in the test.
public string LoadJson()
{
    using (StreamReader r = new StreamReader("testJsonData.json"))
    {
        string json = r.ReadToEnd();
        return json;
    }
}

Is there a way to mock this effectively/simply? Or should I maybe inject my own IHttpClient interface? (I am not sure if that is good practice?)
Thanks

A: There are several ways to unit test HttpClient, but none are straightforward because HttpClient does not implement a straightforward abstraction.
1) Write an abstraction
Here is a straightforward abstraction and you can use this instead of HttpClient. This is my recommended approach. You can inject this into your services and mock the abstraction with Moq as you have done above.
public interface IClient
{
    /// <summary>
    /// Sends a strongly typed request to the server and waits for a strongly typed response
    /// </summary>
    /// <typeparam name="TResponseBody">The expected type of the response body</typeparam>
    /// <param name="request">The request that will be translated to a http request</param>
    /// <returns>The response as the strong type specified by TResponseBody /></returns>
    /// <typeparam name="TRequestBody"></typeparam>
    Task<Response<TResponseBody>> SendAsync<TResponseBody, TRequestBody>(IRequest<TRequestBody> request);

    /// <summary>
    /// Default headers to be sent with http requests
    /// </summary>
    IHeadersCollection DefaultRequestHeaders { get; }

    /// <summary>
    /// Base Uri for the client. Any resources specified on requests will be relative to this.
    /// </summary>
    AbsoluteUrl BaseUri { get; }
}

Full code reference here. The Client class implements the abstraction.
2) Create a Fake Http Server and Verify the Calls on the Server-Side
This code sets up a fake server, and your tests can verify the Http calls.
    using var server = ServerExtensions
        .GetLocalhostAddress()
        .GetSingleRequestServer(async (context) =>
    {
Assert.AreEqual("seg1/", context?.Request?.Url?.Segments?[1]);
Assert.AreEqual("seg2", context?.Request?.Url?.Segments?[2]);
Assert.AreEqual("?Id=1", context?.Request?.Url?.Query);
Assert.AreEqual(headerValue, context?.Request?.Headers[headerKey]);

if (hasRequestBody)
{
    var length = context?.Request?.ContentLength64;
    if (!length.HasValue) throw new InvalidOperationException();
    var buffer = new byte[length.Value];
    _ = (context?.Request?.InputStream.ReadAsync(buffer, 0, (int)length.Value));
    Assert.AreEqual(requestJson, Encoding.UTF8.GetString(buffer));
}

if (context == null) throw new InvalidOperationException();

await context.WriteContentAndCloseAsync(responseJson).ConfigureAwait(false);
});

Full code reference here.
3) Mock the HttpHandler
You can inject a Mock HttpHandler into the HttpClient. Here is an example:
private static void GetHttpClientMoq(out Mock<HttpMessageHandler> handlerMock, out HttpClient httpClient, HttpResponseMessage value)
{
    handlerMock = new Mock<HttpMessageHandler>();

    handlerMock
    .Protected()
    .Setup<Task<HttpResponseMessage>>(
    "SendAsync",
    ItExpr.IsAny<HttpRequestMessage>(),
    ItExpr.IsAny<CancellationToken>())
    .ReturnsAsync(value)
    .Verifiable();

    httpClient = new HttpClient(handlerMock.Object);
}

Full code reference. You can then verify the calls from the mock itself.


Q: Can't Print the RDLC report when I deploy onto another computer? When i run this on VS it works fine but when i run it on another computer it cant find the RDLC path.
  private void button1_Click(object sender, EventArgs e)
    {
        LocalReport localReport = new LocalReport();
        ReportParameterCollection reportParameters = new ReportParameterCollection();
        reportParameters.Add(new ReportParameter("Pallet_label", lb_pallet_name.Text));
        reportParameters.Add(new ReportParameter("Par_PalNum", LB_Number.Text));

        localReport.ReportPath = Application.StartupPath + "\\pallet_label.rdlc";

        localReport.SetParameters(reportParameters);

        localReport.PrintToPrinter();

       }


Q: upload_err_partial error when uploading files of size greater than 3GB I want to upload upto 10GB files using a normal php form. But even after increasing the below values,
upload_max_filesize
post_max_size
php_value upload_max_filesize
php_value post_max_size
request_terminate_timeout
FcgidMaxRequestLen

am able to upload a file upto 3.5gb without any problem. But above that am getting an error as "upload_err_partial". I also reffered a lot of site but the answer I thought releavant was adding "header(connection:close)". I added the line but still I did not get any result. Could anyone guide me in this.

A: This error usually means that the uploading is cancelled by the user , and some times it can be server problem also which can cause this. Try to contact to your hosting provider and see what can he do


Q: hexagonal pyramid The regular hexagonal pyramid trunk shown in the figure has a $ 5 $ cm side edge and base areas $ 54 \sqrt {3} $ $cm ^ 2$ and $ 6 \sqrt {3} $ $cm ^ 2$. Calculate your volume.

My ''solution'':

I think it would be $ a-5 <3 + 4 $

A: The highlighted quadrilateral $OO'A'A$ in the image hints at the solution. Note that $\overline{O'A'}=l'=2$ and $\overline{OA}=l=6$
A line through $A'$ parallel to $OO'$ intersecting $OA$ at $X$ gives $\overline{XA}=4$, and with $\overline{AA'}=5$ we have $\overline{A'X}=k=3$ (Pythagorean theorem).
$OO'$ and $AA'$ meet at $Z$. Triangles $OAZ$ and $XAA'$ are similar, giving us $\overline{OZ}=\frac 92$ the full height of the pyramid.
$$V=\frac 92\times\frac{54\sqrt 3}{3}-\frac 32\times\frac{6\sqrt 3}{3}\\V=81\sqrt 3-3\sqrt 3=78\sqrt 3$$

A: Observe that the truck is the difference between the two pyramids with their base areas given by $S_1= 54\sqrt3$ and $S_2=6\sqrt3$. Let $s$ be the side length of the large pyramid. Then, with $a=5$,
$$\frac{S_1}{S_2}=\frac{s^2}{(s-a)^2}=9\implies s = \frac{15}{2}$$
Also, the area of the large pyramid,
$$S_1 = 6\cdot\frac{\sqrt3}{4}OA^2\implies OA = 6$$
The height of the large pyramid is $h=\sqrt{s^2-OA^2}=\frac92$ and the its volume  $V_1=\frac13 hS_1 = 81\sqrt3$. Then, use the ratio
$$\frac{V_1}{V_2}=\left(\frac{S_1}{S_2}\right)^{3/2}=27$$
to obtain the volume of the truck,
$$V=V_1-V_2 = \left(1-\frac1{27}\right)\cdot 81\sqrt3=78\sqrt3$$


Q: Filezilla not able to connect to sub domain Hosting with AWS, using Apache webserver (using Webmin)
I am using Filezilla to connect to www.domain.com.
I am not able to connect to a subdomain, m.domain.com using filezilla. It always defaults back to the directories of www.domain.com
I am able to view the m.domain.com on the web browser. How do I set it up to connect to m.domain.com
Tried setting the default remote directory to - /var/www/vhosts/m.domain.com/public_html but it default back to domain directory.
I thought it was a dns issue but I am able to view m.domain.com in the browser.
Advice and help appreciated.
Thank you
Richard


Q: /usr/local/bin/bower: No such file or directory after reinstalling Node.js and bower I reinstalled nodejs (node,npm) because of an old corrupted configuration. Than I installed bower
$sudo npm install -g bower
/usr/bin/bower -> /usr/lib/node_modules/bower/bin/bower
/usr/lib
└── bower@1.8.0
$which bower
/usr/bin/bower
$bower -v
bash: /usr/local/bin/bower: No such file or directory

I do not know where\how I should clean the broken link.

A: hash -d bower and you'd be good to go.


Q: How to calculate averages for a 3D matrix for the same day of data over multiple years in Matlab? I am interested in calculating GPH anomalies in Matlab. I have a 3D matrix of lat, lon, and data. Where the data (3rd dimension) is a daily GPH value spaced in one-day increments for 32 years (from Jan. 1st 1979 to Jan. 1st 2011). The matrix is 95x38x11689. How do I compute a daily average across all years for each day of data, when the matrix is 3D?
In other words, how do I compute the average of Jan. 1st dates for all years to compute the climatological mean of all Jan. 1st's from 1979-2010 (where I don't have time information, but a GPH value for each day)? And so forth for each day after. The data also includes leap years. How do I handle that?
Example: Sort, and average all Jan. 1st GPH values for indices 1, 365, 730, etc. And for each day of all years after that in the same manner.

A: First let's take out all the Feb 29th, because these days are in the middle of the data and not appear in every year, and will bother the averaging:
Feb29=60+365*[1:4:32];
mean_Feb29=mean(GPH(:,:,Feb29),3);    % A matrix of 95x38 with the mean of all February 29th

GPH(:,:,Feb29)=[];           % omit Feb 29th from the data
Last_Jan_1=GPH(:,:,end);     % for Jan 1st you have additional data set, of year 2011
GPH(:,:,end)=[];            % omit Jan 1st 2011

re_GPH=reshape(GPH,95,38,365,[]);
av_GPH=mean(re_GPH,4);

Now re_GPH is a matrix of 95x38x365, where each slice in 3rd dimension is an average of a day in the year, starting Jan 1st, etc.
If you want the to include the last Jan 1st (Jen 1st 2011), run this line at after the previous code:
av_GPH(:,:,1)=mean(cat(3,av_GPH(:,:,1),Last_Jan_1),3);

For the ease of knowing which slice nubmer corresponds to each date, you can make an array of all the dates in the year:
t1 = datetime(2011,1,1,'format','MMMMd')
t2 = datetime(2011,12,31,'format','MMMMd')
t3=t1:t2;

Now, for example :
t3(156)=

  datetime

   June5

So av_GPH(:,:,156) is the average of June 5th.

For your comment, if you want to subtract each day from its average:
sub_GPH=GPH-repmat(av_GPH,1,1,32);

And for February 29th, you will need to do that BEFORE you erase them from the data (line 3 up there):
sub_GPH_Feb_29=GPH(:,:,Feb29)-repmat(mean_Feb29,1,1,8);


Q: PHP+Ubuntu Send email using gmail form localhost I have searched several posts on this but no luck. Everyone is using postfix. But when I gone through the text on
https://help.ubuntu.com/community/Postfix

What is a Mail Transfer Agent
  In other words, it's a mail server not a
  mail client like Thunderbird, Evolution, Outlook, Eudora, or a
  web-based email service like Yahoo, GMail, Hotmail, Earthlink,
  Comcast, SBCGlobal.net, ATT.net etc.... If you worked for a company
  named Acme and owned acme.com, you could provide your employees with
  email addresses @acme.com. Employees could send and receive email
  through your computer, but not without your computer running all the
  time. If all your email addresses are at a domain (@gmail.com,
  @yahoo.com) you do not own (you don't own Google) or do not host
  (acme.com) then you do not need this at all.

As the last line says You cannot us it for gmail or yahoo to make it work from localhost..!
Can anyone tell me how can I configure mail server on localhost using gmail SMTP? I am using Ubuntu 14.
Links I have tried before NONE of them worked for me. No error or warnings during testing of below listed links
https://askubuntu.com/questions/314664/sending-php-mail-from-localhost
https://askubuntu.com/questions/228938/how-can-i-configure-postfix-to-send-all-email-through-my-gmail-account
https://easyengine.io/tutorials/linux/ubuntu-postfix-gmail-smtp/
https://easyengine.io/tutorials/mail/postfix-debugging/

A: Please do following steps to send mail from localhost on Ubuntu/Linux through gmail :-
For that you need to install msmtp on Linux/Ubuntu server.
Gmail uses https:// (it's hyper text secure) so you need install ca-certificates
~$ sudo apt-get install msmtp ca-certificates

It will take few seconds to install msmtp package.
Now you have to create configuration file(msmtprc) using , gedit editor.
~$ sudo gedit /etc/msmtprc

Now you have to copy and paste following code in gedit (file you created with above command)
defaults
tls on
tls_starttls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt

account default
host smtp.gmail.com
port 587
auth on
user MY_GMAIL_ID@gmail.com
password MY_GMAIL_PASSSWORD
from MY_GMAIL_ID@gmail.com
logfile /var/log/msmtp.log

Don't forget to replace MY_GMAIL_ID with your "gmail id" and MY_GMAIL_PASSSWORD with your "gmail password" in above lines of code.
Now create msmtp.log as
~$ sudo touch /var/log/msmtp.log

You have to make this file readable by anyone with
~$ sudo chmod 0644 /etc/msmtprc

Now Enable sendmail log file as writable with
~$ sudo chmod 0777 /var/log/msmtp.log

Your configuration for gmail's SMTP is now ready. Now send one test email as
~$ echo -e "Subject: Test Mail\r\n\r\nThis is my first test email." |msmtp --debug --from=default -t MY_GMAIL_ID@gmail.com

Please check your Gmail inbox.

Now if you want to send email with php from localhost please follow below instructions:-
Open and edit php.ini file
~$ sudo gedit /etc/php/7.0/apache2/php.ini

You have to set sendmail_path in your php.ini file.
Check your SMTP path with
~$ which msmtp

and you will get /usr/bin/msmtp like that.
Search sendmail_path in php.ini and edit as below
; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = /usr/bin/msmtp -t

Please check 3rd line carefully there is no semicolon before sendmail_path.
Now save and exit from gedit. Now it's time to restart your apache
~$ sudo /etc/init.d/apache2 restart

Now create one php file with mail function from http://in2.php.net/manual/en/function.mail.php.
Do test and enjoy !!

A: This article explains exactly how to do what you want:
https://www.howtoforge.com/tutorial/configure-postfix-to-use-gmail-as-a-mail-relay/


Q: Is there a way to enable H.264 video in Firefox? I know that Mozilla has taken an ideological stance against H.264 video, but I don't agree with it.  (And I think I paid for a hardware decoder inside my graphics card anyway?)
Is there any way I can force Firefox to play H.264 videos?  Is there a hacked version that includes support for it?  A plug-in?
Chrome's extensions aren't as good as Firefox, so I'm not ready to switch, but videos run so much smoother and more efficiently without the Flash layer in between.

A: If on Windows, there's a "hack" way to include IE in FF:

*

*http://lifehacker.com/5488607/can-i-play-html5-youtube-videos-in-firefox-right-now
Here's a plugin that converts HTML5 to Flash, enabling H264 to be played:

*

*http://userscripts.org/scripts/show/70028
Here's a spin off:

*

*http://wildfox.sourceforge.net/
but no releases yet.
Huge note: http://en.wikipedia.org/wiki/H264#Patent_licensing - this is a patented technology and you, as the user, may need to pay licenses to use the product that contains H264 code in it.

A: You can use the h264ify extension. (also has a Chrome version)

h264ify is a Firefox/Chrome extension that makes YouTube stream H.264
  videos instead of VP8/VP9 videos.
Try h264ify if YouTube videos stutter, take up too much CPU, eat
  battery life, or make your laptop hot.
By default, YouTube streams VP8/VP9 encoded video. However, this can
  cause problems with less powerful machines because VP8/VP9 is not
  typically hardware accelerated.
In contrast, H.264 is commonly hardware accelerated by GPUs, which
  usually means smoother video playback and reduced CPU usage.


Q: Filters with dynamic fields in elasticsearch I am switching a very old version of ElasticSearch to version 6.5.
...
  "text_mined_entities": {
            "nlp": {
                "abbreviations": [],
                "chunks": [],
                "recurring_chunks": [],
                "tagged_entities_grouped": {
                    "NEURO|SCICRUNCH": [
                        {
                            "category": "NEURO",
                            "end": 41,
                            "label": "Infant",
                            "match": "infant",
                            "original_value": "Infant",
                            "reference": "BIRNLEX695",
                            "reference_db": "SCICRUNCH",
                            "sentence": 0,
                            "start": 35
                        },
...

I am wanting to filter on the text_mined_entities.nlp.tagged_entities_grouped.*.reference fields ( which are stored as 'keyword' ), but haven't had much luck. Something like:
GET _search
{
  "query": {
    "bool": {
      "filter": { "term": {
        "text_mined_entities.nlp.tagged_entities_grouped.*.reference": "BIRNLEX695"

      }}

    }
  }
}

Any suggestions? Thanks.

A: Wildcard on fields can't be applied on term query. Instead you can use query_string which supports wildcard on field as well. So following will work:
Assuming text_mined_entities and nlp are of type nested
{
  "query": {
    "nested": {
      "path": "text_mined_entities.nlp",
      "query": {
        "query_string": {
          "query": "BIRNLEX695",
          "fields": [
            "text_mined_entities.nlp.tagged_entities_grouped.*.reference"
          ]
        }
      }
    }
  }
}

Update (if text_mined_entities & nlp are object type and not nested):
{
  "query": {
    "query_string": {
      "query": "BIRNLEX695",
      "fields": [
        "text_mined_entities.nlp.tagged_entities_grouped.*.reference"
      ]
    }
  }
}


Q: Make the animation faster when there are thousands of components I am trying to hide a JSplitPane with animation. By hide, I mean to setDividerLocation(0) so its left component is invisible (technically it is visible, but with zero width):
public class SplitPaneTest {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new BorderLayout());

            JPanel leftPanel = new JPanel(new BorderLayout());

            leftPanel.setBorder(BorderFactory.createLineBorder(Color.green));

            JPanel rightPanel = new JPanel(new GridLayout(60, 60));
            for (int i = 0; i < 60 * 60; i++) {
//              rightPanel.add(new JLabel("s"));
            }
            rightPanel.setBorder(BorderFactory.createLineBorder(Color.red));

            JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
            frame.add(splitPane);

            JButton button = new JButton("Press me to hide");
            button.addActionListener(e -> hideWithAnimation(splitPane));
            leftPanel.add(button, BorderLayout.PAGE_START);

            frame.setMaximumSize(new Dimension(800, 800));
            frame.setSize(800, 800);
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        });
    }

    private static void hideWithAnimation(JSplitPane splitPane) {
        final Timer timer = new Timer(10, null);
        timer.addActionListener(e -> {
            splitPane.setDividerLocation(Math.max(0, splitPane.getDividerLocation() - 3));
            if (splitPane.getDividerLocation() == 0)
                timer.stop();
        });
        timer.start();
    }

}

If you run it, will see that everything seems good, and the animation runs smooth.
However, in the real application the right of the JSplitPane is a JPanel with CardLayout and each card has a lot of components.
If you uncomment this line in order to simulate the number of components:
// rightPanel.add(new JLabel("s"));

and re-run the above example, you will see that the animation no longer runs smoothly. So, the question is, is is possible to make it smooth(-ier)?
I have no idea how to approach a solution - if any exists.
Based on my research, I registered a global ComponentListener:
Toolkit.getDefaultToolkit()
    .addAWTEventListener(System.out::println, AWTEvent.COMPONENT_EVENT_MASK);

and saw the tons of events that are being fired. So, I think the source of the problem is the tons of component events that are being fired for each component. Also, it seems that components with custom renderers (like JList - ListCellRenderer and JTable - TableCellRenderer), component events are firing for all of the renderers. For example, if a JList has 30 elements, 30 events (component) will be fired only for it. It also seems (and that's why I mentioned it) that for CardLayout, events are taking place for the "invisible" components as well.
I know that 60*60 might sound crazy to you, but in a real application (mine has ~1500) as it makes sense, the painting is heavier.

A:
I know that 60*60 might sound crazy to you, but in a real application (mine has ~1500) as it makes sense, the painting is heavier.

The layout manager is invoked every time the divider location is changed which would add a lot of overhead.
One solution might be to stop invoking the layout manager as the divider is animating. This can be done by overriding the doLayout() method of the right panel:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

    public class SplitPaneTest2 {

        public static boolean doLayout = true;

        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());

                JPanel leftPanel = new JPanel(new BorderLayout());

                leftPanel.setBorder(BorderFactory.createLineBorder(Color.green));

                JPanel rightPanel = new JPanel(new GridLayout(60, 60))
                {
                    @Override
                    public void doLayout()
                    {
                        if (SplitPaneTest2.doLayout)
                            super.doLayout();
                    }
                };
                for (int i = 0; i < 60 * 60; i++) {
                  rightPanel.add(new JLabel("s"));
                }
                rightPanel.setBorder(BorderFactory.createLineBorder(Color.red));

                JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
                frame.add(splitPane);

                JButton button = new JButton("Press me to hide");
                button.addActionListener(e -> hideWithAnimation(splitPane));
                leftPanel.add(button, BorderLayout.PAGE_START);

                frame.setMaximumSize(new Dimension(800, 800));
                frame.setSize(800, 800);
                frame.setLocationByPlatform(true);
                frame.setVisible(true);
            });
        }

        private static void hideWithAnimation(JSplitPane splitPane) {
            SplitPaneTest2.doLayout = false;
            final Timer timer = new Timer(10, null);
            timer.addActionListener(e -> {
                splitPane.setDividerLocation(Math.max(0, splitPane.getDividerLocation() - 3));
                if (splitPane.getDividerLocation() == 0)
                {
                    timer.stop();
                    SplitPaneTest2.doLayout = true;
                    splitPane.getRightComponent().revalidate();
                }
            });
            timer.start();
        }

    }

Edit:
I was not going to include my test on swapping out the panel full of components with a panel that uses an image of components since I fell the animation is the same, but since it was suggested by someone else here is my attempt for your evaluation:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.*;

public class SplitPaneTest2 {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new BorderLayout());

            JPanel leftPanel = new JPanel(new BorderLayout());

            leftPanel.setBorder(BorderFactory.createLineBorder(Color.green));

            JPanel rightPanel = new JPanel(new GridLayout(60, 60));
            for (int i = 0; i < 60 * 60; i++) {
              rightPanel.add(new JLabel("s"));
            }
            rightPanel.setBorder(BorderFactory.createLineBorder(Color.red));

            JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
            frame.add(splitPane);

            JButton button = new JButton("Press me to hide");
            button.addActionListener(e -> hideWithAnimation(splitPane));
            leftPanel.add(button, BorderLayout.PAGE_START);

            frame.setMaximumSize(new Dimension(800, 800));
            frame.setSize(800, 800);
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        });
    }

    private static void hideWithAnimation(JSplitPane splitPane) {

        Component right = splitPane.getRightComponent();
        Dimension size = right.getSize();

        BufferedImage bi = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = bi.createGraphics();
        right.paint( g );
        g.dispose();

        JLabel label = new JLabel( new ImageIcon( bi ) );
        label.setHorizontalAlignment(JLabel.LEFT);

        splitPane.setRightComponent( label );
        splitPane.setDividerLocation( splitPane.getDividerLocation() );

        final Timer timer = new Timer(10, null);
        timer.addActionListener(e -> {

            splitPane.setDividerLocation(Math.max(0, splitPane.getDividerLocation() - 3));
            if (splitPane.getDividerLocation() == 0)
            {
                timer.stop();
                splitPane.setRightComponent( right );
            }
        });
        timer.start();
    }

}

A: @GeorgeZ. I think the concept presented by @camickr has to do with when you actually do the layout. As an alternative to overriding doLayout, I would suggest subclassing the GridLayout to only lay out the components at the end of the animation (without overriding doLayout). But this is the same concept as camickr's.
Although if the contents of your components in the right panel (ie the text of the labels) remain unchanged during the animation of the divider, you can also create an Image of the right panel when the user clicks the button and display that instead of the actual panel. This solution, I would imagine, involves:

*

*A CardLayout for the right panel. One card has the actual rightPanel contents (ie the JLabels). The second card has only one JLabel which will be loaded with the Image (as an ImageIcon) of the first card.

*As far as I know, by looking at the CardLayout's implementation, the bounds of all the child components of the Container are set during layoutContainer method. That would probably mean that the labels would be layed out inspite being invisible while the second card would be shown. So you should probably combine this with the subclassed GridLayout to lay out only at the end of the animation.

*To draw the Image of the first card, one should first create a BufferedImage, then createGraphics on it, then call rightPanel.paint on the created Graphics2D object and finally dispose the Graphics2D object after that.

*Create the second card such that the JLabel would be centered in it. To do this, you just have to provide the second card with a GridBagLayout and add only one Component in it (the JLabel) which should be the only. GridBagLayout always centers the contents.

Let me know if such a solution could be useful for you. It might not be useful because you could maybe want to actually see the labels change their lay out profile while the animation is in progress, or you may even want the user to be able to interact with the Components of the rightPanel while the animation is in progress. In both cases, taking a picture of the rightPanel and displaying it instead of the real labels while the animation takes place, should not suffice. So it really depends, in this case, on how dynamic will be the content of the rightPanel. Please let me know in the comments.
If the contents are always the same for every program run, then you could probably pre-create that Image and store it. Or even, a multitude of Images and store them and just display them one after another when the animation turns on.
Similarly, if the contents are not always the same for every program run, then you could also subclass GridLayout and precalculate the bounds of each component at startup. Then that would make GridLayout a bit faster in laying out the components (it would be like encoding a video with the location of each object), but as I am testing it, GridLayout is already fast: it just calculates about 10 variables at the start of laying out, and then imediately passes over to setting the bounds of each Component.
Edit 1:
And here is my attempt of my idea (with the Image):
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.IntBinaryOperator;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class SplitPaneTest {

    //Just a Timer which plays the animation of the split pane's divider going from side to side...
    public static class SplitPaneAnimationTimer extends Timer {
        private final JSplitPane splitPane;
        private int speed, newDivLoc;
        private IntBinaryOperator directionf;
        private Consumer<SplitPaneAnimationTimer> onFinish;

        public SplitPaneAnimationTimer(final int delay, final JSplitPane splitPane) {
            super(delay, null);
            this.splitPane = Objects.requireNonNull(splitPane);
            super.setRepeats(true);
            super.setCoalesce(false);
            super.addActionListener(e -> {
                splitPane.setDividerLocation(directionf.applyAsInt(newDivLoc, splitPane.getDividerLocation() + speed));
                if (newDivLoc == splitPane.getDividerLocation()) {
                    stop();
                    if (onFinish != null)
                        onFinish.accept(this);
                }
            });
            speed = 0;
            newDivLoc = 0;
            directionf = null;
            onFinish = null;
        }

        public int getSpeed() {
            return speed;
        }

        public JSplitPane getSplitPane() {
            return splitPane;
        }

        public void play(final int newDividerLocation, final int speed, final IntBinaryOperator directionf, final Consumer<SplitPaneAnimationTimer> onFinish) {
            if (newDividerLocation != splitPane.getDividerLocation() && Math.signum(speed) != Math.signum(newDividerLocation - splitPane.getDividerLocation()))
                throw new IllegalArgumentException("Speed needs to be in the direction towards the newDividerLocation (from the current position).");
            this.directionf = Objects.requireNonNull(directionf);
            newDivLoc = newDividerLocation;
            this.speed = speed;
            this.onFinish = onFinish;
            restart();
        }
    }

    //Just a GridLayout subclassed to only allow laying out the components only if it is enabled.
    public static class ToggleGridLayout extends GridLayout {
        private boolean enabled;

        public ToggleGridLayout(final int rows, final int cols) {
            super(rows, cols);
            enabled = true;
        }

        @Override
        public void layoutContainer(final Container parent) {
            if (enabled)
                super.layoutContainer(parent);
        }

        public void setEnabled(final boolean enabled) {
            this.enabled = enabled;
        }
    }

    //How to create a BufferedImage (instead of using the constructor):
    private static BufferedImage createBufferedImage(final int width, final int height, final boolean transparent) {
        final GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment();
        final GraphicsDevice gdev = genv.getDefaultScreenDevice();
        final GraphicsConfiguration gcnf = gdev.getDefaultConfiguration();
        return transparent
               ? gcnf.createCompatibleImage(width, height, Transparency.TRANSLUCENT)
               : gcnf.createCompatibleImage(width, height);
    }

    //This is the right panel... It is composed by two cards: one for the labels and one for the image.
    public static class RightPanel extends JPanel {
        private static final String CARD_IMAGE = "IMAGE",
                                    CARD_LABELS = "LABELS";

        private final JPanel labels, imagePanel; //The two cards.
        private final JLabel imageLabel; //The label in the second card.
        private final int speed; //The speed to animate the motion of the divider.
        private final SplitPaneAnimationTimer spat; //The Timer which animates the motion of the divider.
        private String currentCard; //Which card are we currently showing?...

        public RightPanel(final JSplitPane splitPane, final int delay, final int speed, final int rows, final int cols) {
            super(new CardLayout());
            super.setBorder(BorderFactory.createLineBorder(Color.red));

            spat = new SplitPaneAnimationTimer(delay, splitPane);
            this.speed = Math.abs(speed); //We only need a positive (absolute) value.

            //Label and panel of second card:
            imageLabel = new JLabel();
            imageLabel.setHorizontalAlignment(JLabel.CENTER);
            imageLabel.setVerticalAlignment(JLabel.CENTER);
            imagePanel = new JPanel(new GridBagLayout());
            imagePanel.add(imageLabel);

            //First card:
            labels = new JPanel(new ToggleGridLayout(rows, cols));
            for (int i = 0; i < rows * cols; ++i)
                labels.add(new JLabel("|"));

            //Adding cards...
            final CardLayout clay = (CardLayout) super.getLayout();
            super.add(imagePanel, CARD_IMAGE);
            super.add(labels, CARD_LABELS);
            clay.show(this, currentCard = CARD_LABELS);
        }

        //Will flip the cards.
        private void flip() {
            final CardLayout clay = (CardLayout) getLayout();
            final ToggleGridLayout labelsLayout = (ToggleGridLayout) labels.getLayout();
            if (CARD_LABELS.equals(currentCard)) { //If we are showing the labels:

                //Disable the laying out...
                labelsLayout.setEnabled(false);

                //Take a picture of the current panel state:
                final BufferedImage pic = createBufferedImage(labels.getWidth(), labels.getHeight(), true);
                final Graphics2D g2d = pic.createGraphics();
                labels.paint(g2d);
                g2d.dispose();
                imageLabel.setIcon(new ImageIcon(pic));
                imagePanel.revalidate();
                imagePanel.repaint();

                //Flip the cards:
                clay.show(this, currentCard = CARD_IMAGE);
            }
            else { //Else if we are showing the image:

                //Enable the laying out...
                labelsLayout.setEnabled(true);

                //Revalidate and repaint so as to utilize the laying out of the labels...
                labels.revalidate();
                labels.repaint();

                //Flip the cards:
                clay.show(this, currentCard = CARD_LABELS);
            }
        }

        //Called when we need to animate fully left motion (ie until reaching left side):
        public void goLeft() {
            final JSplitPane splitPane = spat.getSplitPane();
            final int currDivLoc = splitPane.getDividerLocation(),
                      minDivLoc = splitPane.getMinimumDividerLocation();
            if (CARD_LABELS.equals(currentCard) && currDivLoc > minDivLoc) { //If the animation is stopped:
                flip(); //Show the image label.
                spat.play(minDivLoc, -speed, Math::max, ignore -> flip()); //Start the animation to the left.
            }
        }

        //Called when we need to animate fully right motion (ie until reaching right side):
        public void goRight() {
            final JSplitPane splitPane = spat.getSplitPane();
            final int currDivLoc = splitPane.getDividerLocation(),
                      maxDivLoc = splitPane.getMaximumDividerLocation();
            if (CARD_LABELS.equals(currentCard) && currDivLoc < maxDivLoc) { //If the animation is stopped:
                flip(); //Show the image label.
                spat.play(maxDivLoc, speed, Math::min, ignore -> flip()); //Start the animation to the right.
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new BorderLayout());

            JPanel leftPanel = new JPanel(new BorderLayout());

            leftPanel.setBorder(BorderFactory.createLineBorder(Color.green));

            int rows, cols;

            rows = cols = 60;

            JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);

            final RightPanel rightPanel = new RightPanel(splitPane, 10, 3, rows, cols);

            splitPane.setLeftComponent(leftPanel);
            splitPane.setRightComponent(rightPanel);

            JButton left = new JButton("Go left"),
                    right = new JButton("Go right");

            left.addActionListener(e -> rightPanel.goLeft());
            right.addActionListener(e -> rightPanel.goRight());

            final JPanel buttons = new JPanel(new GridLayout(1, 0));
            buttons.add(left);
            buttons.add(right);

            frame.add(splitPane, BorderLayout.CENTER);
            frame.add(buttons, BorderLayout.PAGE_START);
            frame.setSize(1000, 800);
            frame.setMaximumSize(frame.getSize());
            frame.setLocationByPlatform(true);
            frame.setVisible(true);

            splitPane.setDividerLocation(0.5);
        });
    }
}


Q: Django REST Framework: nested serializers and deserializing I'm again stuck with Django REST Framework and its serializers.
Basically, what I want to be able to do is stick the following incoming data into a serializers.Serializer instance:
data = {
    "thing_id": 715,
    "sub_things": [
        {
            "id": 1,
            "name": "bob"
        },

        {
             "id": 2,
             "name": "mike"
        }
    ]
}

sub_things are handled by a serializers.ModelSerializer called SubThingSerializer. This is how it looks like.
class SubThingSerializer(serializers.ModelSerializer):
    class Meta:
        model = SubThing
        fields = ('id', 'name')
        read_only_fields = ('id', 'name')

Serialization of Thing is handled by a ThingSerializer, which I've for now handled as below:
class ThingSerializer(serializers.Serializer):
    thing_id = serializers.IntegerField()
    sub_things= SubThingSerializer(many=True)

Now, when I do
serializer = ThingSerializer(data=data)

I get empty OrderedDicts like:
{'sub_things': [OrderedDict(), OrderedDict()], 'thing_id': 715}

I guess it's wise to say that ThingSerializer will not need to get stored into a database, but it does use sub_things from database. These will not be written into db either. This is just to keep track of what sub_things the thing contains, pass this data back and forth between a browser client and a Python object for some calcualtions. And maybe store it in the session.
edit 1:
Most likely there's something I need to add to the create method of my ThingSerializer. So, I guess the ultimate question is: what's the correct syntax to pass sub_thing data to SubThingSerializers?
edit 2:
I dug a bit more. Seems that empty OrderedDicts get passed in validated_data to ThingSerializer.create() for some reason. Serializer validates alright with serializer.is_valid(). I could access the necessary data from initial_data, but that doesn't seem very solid.
edit 3:
Also tested around with serializers.ListField() for sub_things. Still seeing empty OrderedDicts in validated_data inside the create method.

A: Finally figured this out. read_only_fields on my SubThingSerializer prevented the data from getting through the validation resulting in empty dicts being created. I used read_only_fiels to prevent non-existent sub_thing data from being passed to my code, but I guess I'll need to find another way.


Q: Reading values from a text file to a linked list (no array of structs) to use for a stack; advice? I have a question. I am trying to read integer values from a file into a linked list, which will then be used for push and pop functions. I've done my push and pop functions, but I am trying to figure out if I have done the reading correctly. With my code so far, I used fscanf to read the file and printed it and it's printing all values. When I do my push function, it's not printing that correctly. Any advice on what I may be doing wrong.
4
2
1
6
1
5
2
3
3
1
6
1
\\values to be read from file

code below:
//linked list with place to store values and nodes
struct stack_list {
    int list_values;
    struct stack_list *node;
};

struct stack_list *head_node = NULL; //empty list

void stack_print(struct stack_list *);  //prototype to print list
struct stack_list * push(struct stack_list * n, struct stack_list * c); //prototype to push values

int main(int argc, char* argv[]) {

    FILE * fp;  //opening file
    fp = fopen("filename", "r");  //gives name of file to open
    struct stack_list * mock = (struct stack_list *)malloc(sizeof(struct stack_list));
    //int values[12];  //array to be used to collect values to pass to my list
    //int n, t;

    if (fp == NULL){

        printf("File not provided.");
    }
    else if (fp != NULL) {

        printf("Printing values first: \n");

        while (fscanf(fp,"%d", &mock->list_values) == 1) {
            mock->node = head_node;
            printf("%d\n", mock->list_values);
        }
    }
    push(mock, constructor_stack(mock));
    stack_print(mock);
}

struct stack_list * constructor_stack(int j){
    struct stack_list * my_node = (struct stack_list *)malloc(sizeof(struct stack_list));
    my_node->list_values = j;
    my_node->node = NULL;
    return my_node;
}

struct stack_list * push(struct stack_list * num_list, struct stack_list * check_nodes) {

    printf("Added values to stack:\n");
    printf("Push: %d\n", check_nodes->list_values);
    check_nodes->list_values = num_list;
    return check_nodes;
}

This is part of what I have so far. I did attempt to use an array to just store the values and pass to my list, but that didn't work either.
int values[12];  //array to be used to collect values to pass to my list
int n, t;

while (fscanf(fp,"%d", &values[n]) == 1) {
            n++;
        }
    }
    for (t = 0; t < 12; ++t) { //iterating over array where values are stored
        head_node = values[t]; //inputting values into the empty list
        printf("%d\n", head_node); //printing values passed to empty list for reference
    }

This is the output that I receive.
Printing values first:
4
2
1
6
1
5
2
3
3
1
6
1
Added values to stack:
Push: 136352
Printing stack:
1111111111111111111111

This printed the values but did not work in my push function either. I appreciate any advice!


Q: Why ARM Process IPI at the end of ISR I am studying IRQ handling on Linux.
I have a question, why we need to handle IPI at the end of each ISR[for SMP].
Is there something special with IPI? why not we process in do_asm_IRQ with other interrupts.
Any suggestion would be appreciated.
  6         .macro  arch_irq_handler_default
  7         get_irqnr_preamble r6, lr
  8 1:      get_irqnr_and_base r0, r2, r6, lr
  9         movne   r1, sp
 10         @
 11         @ routine called with r0 = irq number, r1 = struct pt_regs *
 12         @
 13         adrne   lr, BSYM(1b)
 14         bne     asm_do_IRQ
 15
 16 #ifdef CONFIG_SMP
 17         /*
 18          * XXX
 19          *
 20          * this macro assumes that irqstat (r2) and base (r6) are
 21          * preserved from get_irqnr_and_base above
 22          */
 23         ALT_SMP(test_for_ipi r0, r2, r6, lr)
 24         ALT_UP_B(9997f)
 25         movne   r1, sp
 26         adrne   lr, BSYM(1b)
 27         bne     do_IPI
 28 #endif

http://lxr.oss.org.cn/source/arch/arm/include/asm/entry-macro-multi.S?v=3.5.2;a=arm


Q: How to generate a random binary matrix where only one bit in each row has value 1? I want to use MATLAB to generate a random binary matrix A (n x m) which satisfies a condition:
Each row contains one position with value 1. Other positions are value 0. The position having 1 value is random position.
I tried this code
   n=5;m=10;
   %% A = randi([0 1], n,m);
   A=zeros(n,m);
   for i=1:n
       rand_pos=randperm(m);
       pos_one=rand_pos(1); % random possition of 1 value
       A(i,pos_one)=1;
   end

Is it correct?

A: The solution works, but it is inefficient.
You are using randperm to create a vector (array), and then use only the first element of the vector.
You can use randi to create a scalar (single element) instead:
n=5;m=10;
A=zeros(n,m);
for i=1:m
    %rand_pos gets a random number in range [1, n].
    rand_pos = randi([1, n]);
    A(rand_pos, i)=1;
end

You can also use the following "vectorized" solution:
rand_pos_vec = randi([1, n], 1, m);
A(sub2ind([n, m], rand_pos_vec, 1:m)) = 1;

The above solution:

*

*Creates a vector of random values in range [1, n].

*Use sub2ind to convert "row index" to "matrix index".

*Place 1 in "matrix index".

A: You can do it in one line using bsxfun and randi:
A = double(bsxfun(@eq, 1:m, randi(n, n, 1)));

This compares the row vector [1 2 ... m] with an n×1 random vector of values from 1 to n. The comparison is done element-wise with singleton expansion. For each row, exactly one of the values of [1 2 ... m] equals that in the random vector.


Q: Change display order of answers in contests We have a second contest going on.
And whenever we have these sort of things I see how unfair the voting system is.
Whoever posts first, or quickly gets more votes, has a huge advantage, since most people wont bother checking all answers posted.
I would like to propose a random display of answers (maybe even hidden votes?), something closer to elections on SO, to make it fairer.

A: I would further suggest that contest entries should be sorted by newest entries first — the reason being that every entrant would have exactly one chance to sit in that "top spot" until sorted down by newer entries.
Further, for anyone following the latest 'activity' (to vote), folks would no longer have to crawl through all the entries again and again looking for those latest entries since my last visit. As the number of posts grows, finding what's new gets more difficult — so folks are less likely to bother. Putting the newest entries at the top helps mitigate that.
You can't (easily) nullify the fact that early entries simply have more time (and short-tail attention) to accumulate more votes, but letting the newest entries trickle down from the top will help offset the advantage of simply being here first (if even just a bit).
Oh, and then change it back to "top winners first" when the contest is over.


Q: Does right continuity imply only countably many discontinuities? Does right continuity imply only countably many discontinuities? That is, if $f:\mathbb{R}\rightarrow \mathbb{R}$ is right continuous then does it only have countable many discontinuities?
Thanks


Q: Decode a string - Quote marks issue I am supposed to decode the string below in a script I have made (it is a task from a webpage). In order to ensure that the decoded word will be correct, I can not change the string in any way. Since the quote marks affects the string, parts like q90:;AI is not a string, which results in a syntax error.
q0Ø:;AI"E47FRBQNBG4WNB8B4LQN8ERKC88U8GEN?T6LaNBG4GØ""N6K086HB"Ø8CRHW"+LS79Ø""N29QCLN5WNEBS8GENBG4FØ47a

Is there a way I can decode the encrypted message without changing it? As of now I am just getting syntax error when I define the string in a variable.

A: You can surround the string with single quotes, since double quotes are used in the string already:
>>> print 'q0Ø:;AI"E47FRBQNBG4WNB8B4LQN8ERKC88U8GEN?T6LaNBG4GØ""N6K086HB"Ø8CRHW"+LS79Ø""N29QCLN5WNEBS8GENBG4FØ47a'
q0Ã:;AI"E47FRBQNBG4WNB8B4LQN8ERKC88U8GEN?T6LaNBG4GÃ""N6K086HB"Ã8CRHW"+LS79Ã""N29QCLN5WNEBS8GENBG4FÃ47a
>>>


Q: Foregin key constraint error but shouldn't be occuring I have a list table with 5 entries in it, the first column in the identity column (PK), within a parent table is a column that is related to this list table by ID (FK). I am using C# in a web app to run an ExecuteScalar with a stored procedure to insert the items into the parent table.
This is within a SQL database
LIST TABLE:
ID INT (PK),
SKILL_SET_NAME VARCHAR

PARENT TABLE:
ID INT,
SKILL_SET_ID INT (FK)

ITEMS WITHIN LIST TABLE:
1, SOMETHING
2, ANOTHER
3, ELSE

INSERT STATEMENT INTO PARENT TABLE
INSERT INTO PARENT TABLE
(ID, SKILL_SET_ID)
VALUES
([NUMBER], 1)

ACTUAL CODE (changed the ExecuteScalar to NonQuery, and the SkillSetID is the foreign key)
public static void SetRIPSSkillSetDetails(int HDR_ID, int SkillSetID, string SkillSetOptional, int SkillSetRating)
{
    ArrayList al = new ArrayList();

    al.Add(new DictionaryEntry("@HDR_ID", HDR_ID));
    al.Add(new DictionaryEntry("@SKILL_SET_ID", SkillSetID));
    al.Add(new DictionaryEntry("@SKILL_SET_OPTIONAL", SkillSetOptional));
    al.Add(new DictionaryEntry("@SKILL_SET_RATING", SkillSetRating));

    Core.RunNonQuery("web", "[IPAM_GLOBAL_INSERT_PARTICIPANT_RATING_DTL]", al);

When the code runs the ExecuteScalar I get the Foreign key constraint error, Please help

A: The stored procedure was bombing out, someone said you can step through sql storec procedures from VS, how do I do that?


Q: Color TdCalendarView rows I am using TdCalendarView code by Tinyfool in my project in which all calendar is designed using core graphics.I want to color rows of this calendar with two alternate colors.How can I do that?

A: You need to change  the stroke fill color here for either even value of i in for loop or odd value
-(void)drawDateWords
  {
CGContextRef ctx=UIGraphicsGetCurrentContext();

int width=self.frame.size.width;

int dayCount=[self getDayCountOfaMonth:currentMonthDate];
int day=0;
int x=0;
int y=0;
int s_width=width/7;
int curr_Weekday=[self getMonthWeekday:currentMonthDate];

// Normaly big Font
[array_Date addObject:@""];
[array_Month addObject:@""];
[array_Year addObject:@""];
[array_Desc addObject:@""];
[array_LastDate addObject:@""];
[self.array_Name addObject:@""];

UIFont *weekfont=[UIFont boldSystemFontOfSize:20];

for(int i=1;i<dayCount+1;i++)
{
    day=i+curr_Weekday-2;
    x=day % 7;
    y=day / 7;
    NSString *date=[[[NSString alloc] initWithFormat:@"%d",i] autorelease];

    for (int j=0; j<[array_Date count]; j++) {

        NSString *date1 = [array_Date objectAtIndex:j];
        int month1 = [[array_Month objectAtIndex:j] intValue];
        int year1 = [[array_Year objectAtIndex:j] intValue];

    if ([date isEqualToString:date1] && currentMonthDate.month == month1 && currentMonthDate.year == year1)
    {
        //[@"*" drawAtPoint:CGPointMake(x*s_width+18,y*itemHeight+headHeight+18) withFont:[UIFont boldSystemFontOfSize:25]];
        //[date drawAtPoint:CGPointMake(x*s_width+18,y*itemHeight+headHeight+18) withFont:[UIFont boldSystemFontOfSize:25]];
        [[UIColor redColor] set];

    }
    else{
        //[[UIColor redColor] set];
        [date drawAtPoint:CGPointMake(x*s_width+15,y*itemHeight+headHeight) withFont:weekfont];
    }

    }

if([self getDayFlag:i]==1)
    {
        CGContextSetRGBFillColor(ctx, 1, 0, 0, 1);
        [@"." drawAtPoint:CGPointMake(x*s_width+19,y*itemHeight+headHeight+6) withFont:[UIFont boldSystemFontOfSize:25]];
    }
    else if([self getDayFlag:i]==-1)
    {
        CGContextSetRGBFillColor(ctx, 0, 8.5, 0.3, 1);
        [@"." drawAtPoint:CGPointMake(x*s_width+19,y*itemHeight+headHeight+6) withFont:[UIFont boldSystemFontOfSize:25]];
    }

    CGContextSetRGBFillColor(ctx, 0, 0, 0, 1);
}
 }


Q: Mixed model for multiple measurements in a crossover study (SAS) I am currently trying to analyse data from a crossover study. In brief, the study is of a crossover design, where each participant takes part in 2 separate sessions, where they play a game. This game repeatedly measures a few different variables, let's call one reaction time. During one session, reaction time is measured 30 times. Before one of the sessions, each participant is given either placebo or treatment, and half the participants receive placebo the first time, and half receive treatment the first time. Consequently, each participant has 60 data points, were 30 are under placebo, and 30 are under treatment.
I am aware that crossover studies have their own considerations, but at the moment I am stuck with how to properly fit a mixed model for this data. The way I understand it, I need to tell the model what a subject is (i.e., that the 60 measurements for every participant are correlated), but it has also been pointed out to me that the 30 measurements of each session are also correlated, and need to be defined as such in the model, before I try to parse out the within-subject effect of the treatment.
Can anyone verify this, and possibly tell me how to best to this? I use SAS, and my code looks like this at the moment:
proc mixed data=test;
  class ID Session Drug MeasurePoint Sequence;
  model ReactionTime=Drug Sequence Session MeasurePoint / ddfm=kenwardroger;
  random int / subject=ID;
  repeated MeasurePoint / subject=ID*Drug type=ar(1);
  lsmeans Drug / diff;
run;

Sequence refers to the sequence of drug / placebo, and MeasurePoint to the order of the measurements during each session. I am not overly interested in the effect of time over each session.
Also, is the ar(1) covariance matrix proper?

A: Firstly, you have multiple observations per subject and per period. As you correctly point out the correlation within subject across session and within the periods needs to be accounted for. There are a number of ways to express this in SAS e.g. "repeated session ID".
Generally, when you know nothing else making very strong assumptions about the correlation structure over time (e.g. type=AR(1) or type=CS or just having a random subject effect on the intercept) is not advisable. In my experience AR(1) tends to treat the furthest apart observations as if they were independent and you end up pretending like you have several times your actual number of (independent) subjects, when you do not. This can lead to a substantial overconfidence in the analysis results with confidence intervals having very poor coverage. If you have sufficient data, it is usually recommended to use an unstructured covariance matrix. One way to specify this here is to write "repeated measurement session / subject=ID type=UN@CS;", when there is only two sessions.
Can you actually identify the effects of drug, session and sequence all at once in a 2 period 2 treatment 2 sequence cross-over? Is drug not a linear combination of session and sequence?