text:
Q: Deploying War on Tomcat 7 error It's been a time that I want to deploy my .WAR file on my Tomcat 7 server, in localhost, and every time I want to make it, I have this probleme :
SEVERE: ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/my-app-0.1.0]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:632)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1073)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1857)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)

I dont know how to bypass this.
In fact, I try to create a REST Webservice with Spring. It works fine when I use the tutorial where we have to start the service manually.
But when I want to deploy my app witch a war file (with the Spring tutorial build.gradle) it doesnt work...
Any idea ?
Edit : This is the fully stack->
SEVERE: ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/my-app-0.1.0]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:632)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1073)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1857)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'viewResolver' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafViewResolverConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.thymeleaf.spring4.SpringTemplateEngine org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafViewResolverConfiguration.templateEngine; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafDefaultConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private final java.util.Collection org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafDefaultConfiguration.templateResolvers; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$DefaultTemplateResolverConfiguration': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Cannot find template location: class path resource [templates/] (please add some templates or check your Thymeleaf configuration)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    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.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:130)
    at org.springframework.boot.context.web.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:89)
    at org.springframework.boot.context.web.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:51)
    at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:175)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5456)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 11 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafViewResolverConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.thymeleaf.spring4.SpringTemplateEngine org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafViewResolverConfiguration.templateEngine; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafDefaultConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private final java.util.Collection org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafDefaultConfiguration.templateResolvers; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$DefaultTemplateResolverConfiguration': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Cannot find template location: class path resource [templates/] (please add some templates or check your Thymeleaf configuration)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:370)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:470)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:459)
    at org.springframework.context.support.AbstractApplicationContext.getBeansOfType(AbstractApplicationContext.java:1063)
    at org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors(BeanFactoryUtils.java:228)
    at org.springframework.web.servlet.view.ContentNegotiatingViewResolver.initServletContext(ContentNegotiatingViewResolver.java:243)
    at org.springframework.web.context.support.WebApplicationObjectSupport.initApplicationContext(WebApplicationObjectSupport.java:77)
    at org.springframework.context.support.ApplicationObjectSupport.setApplicationContext(ApplicationObjectSupport.java:74)
    at org.springframework.context.support.ApplicationContextAwareProcessor.invokeAwareInterfaces(ApplicationContextAwareProcessor.java:119)
    at org.springframework.context.support.ApplicationContextAwareProcessor.postProcessBeforeInitialization(ApplicationContextAwareProcessor.java:94)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:407)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1545)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    ... 28 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.thymeleaf.spring4.SpringTemplateEngine org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafViewResolverConfiguration.templateEngine; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafDefaultConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private final java.util.Collection org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafDefaultConfiguration.templateResolvers; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$DefaultTemplateResolverConfiguration': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Cannot find template location: class path resource [templates/] (please add some templates or check your Thymeleaf configuration)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    ... 56 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafDefaultConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private final java.util.Collection org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafDefaultConfiguration.templateResolvers; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$DefaultTemplateResolverConfiguration': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Cannot find template location: class path resource [templates/] (please add some templates or check your Thymeleaf configuration)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:370)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1017)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
    ... 58 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private final java.util.Collection org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafDefaultConfiguration.templateResolvers; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$DefaultTemplateResolverConfiguration': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Cannot find template location: class path resource [templates/] (please add some templates or check your Thymeleaf configuration)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    ... 78 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$DefaultTemplateResolverConfiguration': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Cannot find template location: class path resource [templates/] (please add some templates or check your Thymeleaf configuration)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:136)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:407)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1545)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:370)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1017)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:912)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
    ... 80 more
Caused by: java.lang.IllegalStateException: Cannot find template location: class path resource [templates/] (please add some templates or check your Thymeleaf configuration)
    at org.springframework.util.Assert.state(Assert.java:385)
    at org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$DefaultTemplateResolverConfiguration.checkTemplateLocationExists(ThymeleafAutoConfiguration.java:87)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:349)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:300)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:133)
    ... 101 more

mai 05, 2014 11:26:16 AM org.apache.catalina.startup.HostConfig deployWAR
SEVERE: Erreur lors du déploiement de l'archive F:\Java\j2ee\apache-tomcat-7.0.52-windows-x64\apache-tomcat-7.0.52\webapps\my-app-0.1.0.war de l'application web
java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/my-app-0.1.0]]
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:904)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:632)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1073)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1857)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)

A: Okay, so I created a template in src /resources/templates , with nothing inside and the War can be deployed.
Now, my problem is that I always have a 404 error. Even of I use @ReponseBody with a string :
@Controller
public class HomeController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public @ResponseBody String index() {
        return "index";
    }
}


text:
Q: Wrap fetch function for token when using reactn I am using reactn to store the access and refresh tokens from logging in.  Normally, to do an API call, I would do something like the following...
fetch('/api/options/1/', {
    method: 'PUT',
    credentials: 'same-origin',
    body: JSON.stringify(state),
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${auth.access.token}`,
    },
})

But since the access token expires quickly, this can easily fail.  What I wanted to do is wrap the fetch function in a function like 'callAPI(url, options)' that would do the following:

*

*Check if access token is expired (global.auth.access.exp variable).  If expired, first call /api/auth/token/refresh passing the refresh token to get a new access token

*Send fetch with the Authorization header added automatically

*Return response promise

What would be the best way to go about this when the auth information is stored in the reactn global state, so that in any component I could just import a function callAPI and do the API call?

A: Considering you are using async/await syntax you can do it using below:
const fetchWrapper = async (URI, options) => {
    const auth = await fetch('/api/auth/token/refresh');
    const newOptions = {
        ...options,
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${auth.access.token}`,
        },
    }
    const res = await fetch(URI, newOptions);
    return res;
}

if you are not using async/await you can use below:
const fetchWrapper = (URI, options) => {
    const promise = new Promise((resolve, reject) => {
        fetch('/api/auth/token/refresh').then((auth) => {
            const newOptions = {
                ...options,
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${auth.access.token}`,
                },
            }
            fetch(URI, newOptions).then(res => {
                resolve(res);
            }).catch((err) => {
                reject(err);
            });
        }).catch((err) => {
            reject(err);
        });
    })

    return promise;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Digit swap wrong examples swap digit problem
This problem is screwing with my mind because of the examples.
If I have:
38276

Then the next biggest is
87632

But the problem points it out as the next biggest being 38627
I don't understand what the output should be?

A: 38276 < 38627 < 87632
So your suggestion of 87632 cannot be next biggest. As the comment section of the linked problem suggests, look at C++ next_permute.
If it helps, think of this as the next alphabetical ordered solution. I.e. if you have abc, (next biggest) the next alphabetic order will be acb.

A: The problem is to find the next highest number not the highest number as you are currently thinking.
If the initial number n is 38276 the next highest number m would be 38627 since there is no number k that can be formed from the initial digits such that n < k < m.

A: The Next highest number is surely 38627 not 87632. Using a brute force method, you can find all permutations of the number then sort it.  equivalent of the logic in c++ is next_permutation function


text:
Q: How to read the value of a specific cell from MS Excel with ADO query? I am trying to extract data from specific cell from MS Excel worksheet.
Select [A1] from [Sheet1$]

does not work.

*

*How to read the value of a specific cell from MS Excel with ADO query ?

this is my connection string if it is from any help.
Provider=Microsoft.ACE.OLEDB.12.0;
User ID=Admin;Data Source=c:\clients.xlsx;
Mode=Share Deny None;
Extended Properties="Excel 12.0 Xml;
HDR=yes";
Jet OLEDB:System database="";
Jet OLEDB:Registry Path="";
Jet OLEDB:Database Password="";
Jet OLEDB:Engine Type=37;
Jet OLEDB:Database Locking Mode=0;
Jet OLEDB:Global Partial Bulk Ops=2;
Jet OLEDB:Global Bulk Transactions=1;
Jet OLEDB:New Database Password="";
Jet OLEDB:Create System Database=False;
Jet OLEDB:Encrypt Database=False;
Jet OLEDB:Don''t Copy Locale on Compact=False;
Jet OLEDB:Compact Without Replica Repair=False;
Jet OLEDB:SFP=False;
Jet OLEDB:Support Complex Data=False';

A: You've said that the data has headers (using HDR=YES; in your connection string), so you need to use the column name from that header row. For instance, if you have a sheet such as this:
    A    B
1 CODE  DESCRIPTION
2 100   This is an item description
3 200   This is another item

Your SELECT statement would be
SELECT Code, Description FROM [Sheet1$] WHERE [Code] = 100

The query above would return
Code  Description
100   This is an item description

If you need a specific cell from the resulting column, you can move to it after the query:
ADOQuery1.MoveBy(25);         // Move to row 25 of the results
DescriptStr :=  ADOQuery1.FieldByName('Description').Value;

Note that using ADO may not be the best way to access a single cell. Automation, for instance, would be much easier:
// You'll need to add ComObj to your uses clause for CreateOleObject
procedure TForm2.Button2Click(Sender: TObject);
var
  XLS: Variant;
  Range: Variant;
  Description: String;
begin
  XLS := CreateOleObject('Excel.Application');
  try
    XLS.WorkBooks.Open('C:\ExcelDocs\MyFile.xls');

    // Retrieve the cell
    Range := XLS.ActiveWorkBook.WorkSheets[1].Range['B2'];

    // Read its content
    Description := Range.Value;
    ShowMessage(Description);  // Displays 'This is an item description'
  finally
    Range := null;             // Release reference

    XLS.Quit;                  // Close Excel application
    XLS := null;               // Release reference
  end;
end;

A: Are you sure ADO is the best way to get the value of specific cell? ADO treats excel spreadsheets like sql tables and your question is similar to 'how to get record #5 from sql server table'.
Better try OLE automation. There you can easily address single cell or a range of cells. Here is an example from Microsoft.

A: If you have headers, you select the name of the header, if you do not, the first column is F1, followed by F2 and so on. You can experiment by using SELECT * ... and then looking up the field names.


text:
Q: Make custom Error validation rule I'm trying to store student info in database id, name with course_1, course_2 from a form.
Same student can't register for same course again.
Students Table
id name
 1  X
 2  Y
Courses Table
 id course_name
 1   A
 2   B

Student_courses Table
 student_id courses_id
  1          1
  2          1
  2          2

Student controller like this :
public function studentRegistration(Request $request)
{
  $student = new Student();
  $student->name = $request->Input(['student_name']);
  $student->save();

   $courses = array(
            $request->Input(['course_1']),
            $request->Input(['course_2']),
            $request->Input(['course_3'])
        );

   foreach ($courses as $course)
        {
           $studentCourse = new StudentCourse();
           $studentCourse->student_id = $student->id;
           $studentCourse->course_id = $course;
           $studentCourse->save();
        }
}

How to make this custom validation with Laravel so same student can't take same course again?

A: Could you use an existing rule?
Validation rules:
'course_1' => 'different:course_2,course_3|...',
'course_2' => 'different:course_3|...',

I am not sure how exact the actual problem is to the example. If these fields are more dynamic than that, then a custom rule would make sense.
That is just for validating the input to be unique values for those fields. To check against the database is where the unique rule can come in:
'course_1' => [..., $uniqueRule = Rule::unique('student_courses', 'course_id')->where('student_id', $whoEverTheStudentToCheckAgainstIs)],
'course_2' => [..., $uniqueRule],
'course_3' => [$uniqueRule],

Could hide that behind a custom rule if you really needed to.


text:
Q: Adding attribute to object in jbuilder doesn't work While building a JSON response with jbuilder, I want to add an attribute "image_full_url" to each of my Employee objects.
In my jbuilder file this looks like follows:
json.branch_companies @companies.select{ |branch| branch.head_company_id == head_company.id}.map{|branch| {
    :branch => branch,
    :employees => branch.employees.select(employee_attributes).each{ |emp| emp.image_full_url = "#{root_url[0..-2]}#{emp.photo_image.url}" },
    :machine_categories => branch.machine_categories.pluck(:id, :name, :description)
    }
}

In my Emplyoee Model I have a corresponding attr_accessor:
attr_accessor :image_full_url

Adding an attribute to an Employee object works perfectly on the console.
The part I having problems is here:
:employees => branch.employees.select(employee_attributes).each{ |emp| emp.image_full_url = "#{root_url[0..-2]}#{emp.photo_image.url}" }

I would expect that the "image_full_url" attribute was added to the emp object, but it isnn't. The JSON response doesn't contain the "image_full_path" field. What am I doing wrong? Can anyone help here?

A: Of course you will not get :image_full_url attribute in your json output, because serializer does know nothing about it. You can simply check this by doing next:
Emplyoee.limit(2).each{|e| e.image_full_url = "asdw"}.as_json

As a result, output won't contain :image_full_url attribute. If you want that attribute to be in your final result, add to that next line:
.as_json(:methods => [:image_full_url])


text:
Q: Optimize a python code for transforming variables I'm doing the following operation on a sorted dataset 'df_post_decay' containing time-series dataset for multiple IDs and I want to transform my 'demean_variables' variables for each ID.
The created variable for transformed tactic variable ''dm_'+var' for an id (i) and time (t1)  will be:
{(tactic) -  (mean(tactic) for all the rows of ID (i)) - (mean(tactic) for all the rows of time (t1)) + (grand mean(tactic) across whole tactic column)}
time_col = 'mnth'
demean_variables =['overall_details','speaker_total','overall_samples_eu','copay_redemption_count','voucher_redemption_count','dtc']
df_post_demean['key'] = 1

for var in demean_variables:

    df_post_demean['dm_'+var] = df_post_demean[var] - df_post_demean.groupby(id_col)[var].transform(np.mean) - df_post_demean.groupby(time_col)[var].transform(np.mean) + df_post_demean.groupby('key')[var].transform(np.mean)

del df_post_demean[var]
print(sum(df_post_demean['dm_'+var]))

del df_post_demean['key']

I want to optimize this section of code as it is taking more than 10 mins for 5 million+ rows in my dataset.
Please find the sample of dataset 'df_post_decay'
ID  mnth    overall_details speaker_total   overall_samples_eu  copay_redemption_count  voucher_redemption_count    dtc
1   201701  3   1   10  9   3   6
1   201702  6   1   0   7   7   10
1   201703  10  8   7   8   9   10
1   201704  3   9   3   0   1   1
1   201705  9   0   8   9   6   4
1   201706  8   3   2   10  8   9
1   201707  3   10  3   0   5   6
1   201708  2   10  3   9   6   2
1   201709  1   3   7   10  8   0
1   201710  3   8   2   8   0   10
1   201711  6   7   4   8   5   6
1   201712  3   8   2   9   4   10
2   201701  7   4   7   4   10  2
2   201702  10  0   2   2   10  5
2   201703  10  6   4   10  5   3
2   201704  4   3   6   4   0   8
2   201705  7   8   9   10  6   10
2   201706  8   0   2   7   1   8
2   201707  10  2   8   1   9   4
2   201708  10  6   7   0   3   5
2   201709  10  10  3   8   9   0
2   201710  2   0   3   5   5   8
2   201711  1   8   0   7   3   4
2   201712  8   5   1   0   7   9
3   201701  2   2   7   7   1   2
3   201702  2   8   10  9   6   9
3   201703  10  5   8   5   9   4
3   201704  6   1   2   4   6   2
3   201705  6   9   4   4   3   0
3   201706  5   1   6   4   1   7
3   201707  0   7   6   9   5   6
3   201708  10  3   2   0   4   5
3   201709  5   8   6   4   10  4
3   201710  8   3   10  6   7   0
3   201711  7   5   6   3   1   10
3   201712  3   9   8   4   10  0

A: Have you ever looked at BLAS/LAPACK sort of things. This libraries are built for linear algebraic operations in compilers. Try these operations through BLAS/LAPACK. To set it for Python have a look at the following:
You can check here Why BLAS matters ?

*

*Netlib - BLAS page

*Netlib - LAPACAK page

*OpenBLAS


text:
Q: passing variables between methods in ROR controller In my controller I pass date from method create to method index. How can I pass it back from index to create (for new create)?
 def index
   @date = params[:date].
 end

 def create
    <<<NEED to get @date from index here>>>
    @entry = Entry.new(:input => input, :user => current_user, :time => @date)
   respond_to do |format|
     if @entry.save
       format.html { redirect_to(:action => "index", :edit => true) }
     end
   end

A: Why do you need to get it from index?
Keep it in a hidden form variable and submit it, etc. You can't get it from index.


text:
Q: Localization for user profile information Asp.net I'm trying to implement page localization to my webpage made in asp.net-mvc. I understand how to implement titles and other modular data.
The problem comes when i want to give user/admin of this page rights to change his personal information/bio on her webpage if needed. Do i save the bio in the database? With another column in the table which indicates for which language it is meant?
Or is there any better solution?


text:
Q: how to parallelize a function in python I have an embarrassingly parallel problem but have been wondering how to "design" function so that it achieves the end result
So, here is the sequential version
def train_weights(Xtr, ztr, Xte, zte):
    regr = some_model()
    regr.fit(Xtr, ztr)
    error = np.mean((regr.predict(Xte) - zte) ** 2)
    return regr.coef_, error

rnge = range(z_train.shape[0])
weights = []
errors = []
for i in rnge:
    z_dim_tr = z_train[:,i]
    z_dim_te = z_test[:, i]
    weight, error = train_weights(X_train, z_dim_tr, X_test, z_dim_te)
    weights.append(wgts)
    errors.append(error)

So, I am just slicing a column from a matrix (train and test matrices)
and then passing it to the function..
Note that, order of output matters.. which is the index of weight in weights list corresponds to a particular "i" and same for error.
How do i parallelize this?

A: Since this is just a general parallel processing problem, you can use Pool from multiprocessing.dummy.
Since I don't have your data set, let's instead consider this following example.
import multiprocessing
from multiprocessing.dummy import Pool

def test(args):
    a, b = args
    return a

data = [
    (1, 2),
    (2, 3),
    (3, 4),
]

pool = Pool(multiprocessing.cpu_count())

results = pool.map(test, data)

pool.close()
pool.join()

for result in results:
    print(result)

Pool creates an amount of worker processes (in this case multiprocessing.cpu_count()). Each worker then continuously execute a job until all jobs have been executed. In other words map() first returns when all jobs have been executed.
All in all, the above example, when calling map() it returns a list of results which are in the same order as they're given. So in the end the above code prints 1, 2 then 3.

A: check out joblib
https://pythonhosted.org/joblib/parallel.html

Joblib provides a simple helper class to write parallel for loops
  using multiprocessing. The core idea is to write the code to be
  executed as a generator expression, and convert it to parallel
  computing:

>>> from math import sqrt
>>> [sqrt(i ** 2) for i in range(10)]
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]

can be spread over 2 CPUs using the following:

>>> from math import sqrt
>>> from joblib import Parallel, delayed
>>> Parallel(n_jobs=2)(delayed(sqrt)(i ** 2) for i in range(10))
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]

A: it can easily achieved using concurrents.futures library
here's the example code:
from concurrent.futures.thread import ThreadPoolExecutor

MAX_WORKERS = 20

def train_weights(Xtr, ztr, Xte, zte):
    regr = some_model()
    regr.fit(Xtr, ztr)
    error = np.mean((regr.predict(Xte) - zte) ** 2)
    return regr.coef_, error

def work_done(future):
    weights.append(future.result())

rnge = range(z_train.shape[0])
weights = []
errors = []
for i in rnge:
    z_dim_tr = z_train[:, i]
    z_dim_te = z_test[:, i]
    with ThreadPoolExecutor(MAX_WORKERS) as executor:
        executor.submit(train_weights, X_train, X_test, Xte, z_dim_te).add_done_callback(work_done)

here executor returns future for every task it submits. keep in mind that if you use add_done_callback() finished task from thread returns to the main thread (which would block your main thread) if you really want true parallelism then you should wait for future objects separately. here's the code snippet for that.
futures = []
for i in rnge:
    z_dim_tr = z_train[:, i]
    z_dim_te = z_test[:, i]
    with ThreadPoolExecutor(MAX_WORKERS) as executor:
        futures.append(executor.submit(train_weights, X_train, X_test, Xte, z_dim_te))

wait(futures)

for succeded, failed in futures:
    # work with your result here
    if succeded:
        weights.append(succeded.result())
    if failed:
        errors.append(failed.result())

A: Here's one way to parallelize the code using Ray. Some advantages of using Ray

*

*Large data will be stored in shared memory and can be accessed by multiple workers (in a read only fashion) so that workers don't need to create their own copy of the data.

*The same code will run on one machine or on multiple machines.

Ray is a library for writing parallel and distributed Python.
import numpy as np
import ray

ray.init()

z_train = np.random.normal(size=(100, 30))
z_test = np.random.normal(size=(50, 30))

@ray.remote(num_return_vals=2)
def train_weights(ztr, zte):
    # Fit model.
    predictions = np.random.normal(size=zte.shape[0])
    error = np.mean((predictions - zte) ** 2)
    coef = np.random.normal()
    return coef, error

weight_ids = []
error_ids = []
for i in range(z_train.shape[1]):
    z_dim_tr = z_train[:, i]
    z_dim_te = z_test[:, i]
    weight_id, error_id = train_weights.remote(z_dim_tr, z_dim_te)
    weight_ids.append(weight_id)
    error_ids.append(error_id)

weights = ray.get(weight_ids)
errors = ray.get(error_ids)

You can read more in the Ray documentation. Note I'm one of the Ray developers.


text:
Q: ORA-00933: SQL command not properly ended when deleting two tables at the same time I am trying to delete data from two related tables - primary key in the table users and foreign key in the table login - but I'm getting error PL/SQL: ORA-00933: SQL command not properly ended.
Create table users and primary key:
/* table user*/
create table users (id_user number(10) not null,
                    name_user varchar(30) not null);
/* primary key */
alter table users add constraint user_pk primary key (id_user);

Create table login and primary key and foreign key:
/* table login*/
create table login (id_login number(10) not null,
                    id_user_login number(10) not null,
                    email_login varchar(20) not null,
                    password_login varchar(20) not null);
/* primary key */
alter table login add constraint login_pk primary key (id_login);

/* foreign key reference to user*/
alter table login add constraint login_fk_user foreign key (id_user_login)
references users(id_user) on delete cascade;

Procedure to create session with table users/login, which works:
PROCEDURE create_user_session( p_name   IN VARCHAR2,
                               p_email  IN VARCHAR2,
                               p_pass   IN VARCHAR2,
                               p_error  OUT NUMBER,
                               p_msg_error OUT VARCHAR2)
  IS
  BEGIN
    p_error := 0;
    INSERT ALL

    INTO users (id_user, name_user) VALUES(seq_user.NEXTVAL,p_name)

    INTO login(id_login, id_user_login, email_login, pass_login)
    VALUES(seq_login.NEXTVAL, seq_user.CURRVAL, p_email, p_pass)

    SELECT * FROM DUAL COMMIT;
  EXCEPTION
  WHEN OTHERS THEN
    p_error     := 1;
    p_msg_error := 'Error!'||SQLERRM;
  END create_user_session;

Now I want to delete this session, but I have error PL/SQL: ORA-00933: SQL command not properly ended from this procedure:
PROCEDURE delete_user_session(
    p_id_user IN NUMBER,
    p_error OUT NUMBER,
    p_msg_error OUT VARCHAR2)
IS
BEGIN
  p_error := 0;
  DELETE FROM users, login USING users
  INNER JOIN login WHERE users.id_user = p_id_user
  AND login.id_user_login  = p_id_user;
  COMMIT;
EXCEPTION
WHEN OTHERS THEN
  p_error     := 1;
  p_msg_error := 'Error!'||SQLERRM;
END delete_user_session;

I have this image from SQL developer to show the error (red squiggle underline on the s, in DELETE FROM users, login ... if you can't see the image):

What am I doing wrong?

A: You can't delete from two tables in one statement - there is no delete equivalent of insert all. (Unless you have constraints that cascade the delete, or a trigger that does that manually). The documentation shows that your syntax is not valid, as there is no path to specify more than one table.
You will need to have two delete statements, removing the records from the child table first:
  DELETE FROM login
  WHERE login.id_user_login = p_id_user;
  DELETE FROM users
  WHERE users.id_user = p_id_user;

You could change your foreign key constraint to delete cascade:
alter table login add constraint login_fk_user foreign key (id_user_login)
references users(id_user) on delete cascade;

... which would mean you would only have to explicitly delete from the users table; but that may not actually be what you want, as it removes one level of validation - you may want to prevent a parent key being accidentally removed if it has children. Issuing two deletes doesn't really hurt here.
Incidentally, your first procedure is not committing, which you might be expecting. In this line:
    ...
    SELECT * FROM DUAL COMMIT;

... the COMMIT is interpreted as an alias for the DUAL table, not a separate command. You would need a semicolon after DUAL, and preferably a new line for the COMMIT;. But it's generally considered better not to commit in a procedure, and let the top-level caller decide whether to commit or roll back to preserve data integrity.


text:
Q: How can I define 2 classes in one var? I have a problem with define a second class in one Var
Here is the Code: http://jsfiddle.net/2DuQc/
How can I make work this fine?
It's written in JQuery!
var animateEye = $('.rightEye, .leftEye');

doesnt work!

A: Actually your code won't work because you are overwriting your variabile with only one selector .leftEye so the .rightEye will not have nothing attached to it.
You can use a multiple selector than loop through the result using jQuery each and apply yuor current code.
Use the same class as inner element and find it as a children of the current element.
Code:
$('.rightEye, .leftEye').each(function () {
    var animateEye = $(this);
    var eyes = animateEye.find(".Eye");

Demo: http://jsfiddle.net/IrvinDominin/rU9E2/

A: var animateEye = $('.rightEye, .leftEye');

This will give you an array of items, so when you call, say, animateEye.offset(), which one is it supposed to choose? It'll bomb out.
Your current code:
var animateEye = $('.rightEye');
var  eyes = $(".Eye");
var animateEye = $('.leftEye');

This will obviously always use .leftEye.
My suggestion? Loop through rightEye and leftEye like so:
var eyes = $('.rightEye, .leftEye');
for(var i = 0; i < eyes.length; i++) {
    var animateEye = eyes[i];
}


text:
Q: Setting data in viewModel knockoutjs from html5 websocket I am trying to create knockout.js component that is getting data from HTML5 Websocket. Websocket code is in separate script e.g. util.js. I am able to connect and get data from socket, but dont know how correctly to set corresponding property in component`s ViewModel.
Websocket  - util.js:
     var options = {
    server: '127.0.0.1',
    port: '12345'
};

var socket, loadedFlag;
var timeout = 2000;
var clearTimer = -1;
var data = {};

function handleErrors(sError, sURL, iLine)
{
    return true;
};
function getSocketState()
{
    return (socket != null) ? socket.readyState : 0;
}

function onMessage(e)
{
    data=$.parseJSON(e.data);

 // ???? Is it possible to have here something like
 // ???? viewModel.getDataWS1(data);
}

function onError()
{
    clearInterval(clearTimer);
    socket.onclose = function () {
        loadedFlag = false;
    };
    clearTimer = setInterval("connectWebSocket()", timeout);
}

function onClose()
{
    loadedFlag = false;
    clearInterval(clearTimer);
    clearTimer = setInterval("connectWebSocket()", timeout);
}

function onOpen()
{
    clearInterval(clearTimer);
    console.log("open" + getSocketState());
}

function connectWebSocket()
{

    if ("WebSocket" in window)
    {
        if (getSocketState() === 1)
        {
            socket.onopen = onOpen;
            clearInterval(clearTimer);
            console.log(getSocketState());
        }
        else
        {
            try
            {
                host = "ws://" + options.server + ":" + options.port;
                socket = new WebSocket(host);
                socket.onopen = onOpen;
                socket.onmessage = function (e) {
                    onMessage(e);
                };
                socket.onerror = onError;
                socket.onclose = onClose;
            }
            catch (exeption)
            {
                console.log(exeption);
            }
        }
    }
}

Component (productDisplay.js) - creating so that is can be used on multiple pages:
define([
    'jquery',
    'app/models/productDisplayModel',
    'knockout',
    'mapping',
    'socket'
],
        function ($, model, ko, mapping) {
            ko.components.register('product', {
                viewModel: {require: 'app/models/productModel'},
                template: {require: 'text!app/views/product.html'}
            });

        });

Product ViewModel (productModel.js) - where I struggle to set viewModel property to data from websocket:
var viewModel = {};

define(['knockout', 'mapping', 'jquery'], function (ko, mapping, $) {

    function Product(name, rating) {
        this.name = name;
        this.userRating = ko.observable(rating || null);
    }

    function MyViewModel() {
        this.products = ko.observableArray(); // Start empty
    }

    MyViewModel.prototype.getDataWS1 = function () {

     //Websocket has not connected and returned data yet, so data object is empty
     // ???? Is there anyway I can add something like promise so that the value is set once socket is connected?
        this.products(data);
    };

// apply binding on page load
    $(document).ready(function () {
        connectToServer1();
        viewModel = new MyViewModel();

        ko.applyBindings(viewModel);
        viewModel.getDataWS1();
    });

});

Thank you for any ideas.

A: You can update an observable when you get a message in the following manner:
util.js
function onMessage(e) {
    var productData = $.parseJSON(e.data);
    viewModel.addNewProduct(productData);
}

productModel.js
function Product(name, rating) {
    this.name = name;
    this.userRating = ko.observable(rating || null);
}

function MyViewModel() {
    this.products = ko.observableArray(); // Start empty
}

MyViewModel.prototype.addNewProduct(product) {
  var newProduct = new Product(product.name, product.rating);
  this.products.push(newProduct);
}

Basically the idea is that when you get a message (in onMessage function), you will parse the data and call a function in your viewmodel to add the message data to the viewmodel properties (observables, observableArrays, etc.)


text:
Q: Learning Ember.js- How Would I do this? To learn Ember.js I started writing a small bookmark application.
Bookmarks with the selected label should be displayed in the bottom box.
Template:
...
{{#each itemController="label"}}

    {{name}}

{{/each}}
...
{{#each links}}

{{name}}

{{/each}}
...

App.LabelController:
...
App.LabelController = Ember.ObjectController.extend({
    needs: ["list"],
    active: false,

    actions: {
        findLinks: function() {
            var listController = this.get('controllers.list');

            this.toggleProperty('active');
            listController.set('model', this.get('store').find('link'));
        }
    }
});
...

Label Data:
App.Label = DS.Model.extend({
    links: DS.hasMany('link'),
    name: DS.attr('string'),
    color: DS.attr('string')
});

App.Label.FIXTURES = [
    {
        id: 1,
        name: 'Develop',
        color: 'blue'
    },
    ...
];

Link Data:
App.Link = DS.Model.extend({
    labels: DS.hasMany('label'),
    name: DS.attr(),
    url: DS.attr()
});

App.Link.FIXTURES = [
    {
        id: 1,
        name: 'Google',
        url: 'http://google.com',
        labels: [1]
    },
    ...
];

The issue I have now is that setting the model in LabelController doesn't update the list of links. I also doubt that this is the right approuch.
How would you do such a thing in Ember?
Edit:
http://jsbin.com/Ovuw/81/edit

A: Is this what you want? http://jsbin.com/Ovuw/83/edit I commented the code, if you have questions be free to comment
Good luck


text:
Q: Print every two from a string with x I will from a string with numbers and words ,than print it , separate every two Len with an x as start.
I have this code:
d = "e345a46be5"
for i in d:
    print "x", i[::2],

and i come,  x 43c48eaff x 43c48eaff x ..... . I will xe3,x45,xa4,x6b,xe5

A: The third parameter of the slice is the step size. This means you are taking the first, third, fifth... item.
I think the easiest way to do what you want is to use range:
d = "e345a46be5"
for i in range(0, len(d), 2):
    print "x", d[i:i+2]

range(start, stop, step) => range(0,5,2) => [0, 2, 4]

A: This code that should work on python 2.7 and python 3:
for i in range(0,len(d),2):
    print ("x", d[i:i+2])

Here we use i as an index instead as a specific letter as you did. and range (a,b,2) enables to go through a list starting with a, going to b excluded with step 2.


text:
Q: How to use ScrollView properly? I'm trying to use ScrollView widget to show multiple lines scroll in the screen. But the lines don't scroll. The text that should scroll is "myList" label in the screen_second.
The idea is to click on button 1, which directs the user to the second screen, and at that moment a list will be generated that should appear in the center of the second screen.
However, the list will be too many lines and therefore must scroll on the screen.
But the list is static. It's not rolling.
This is the kv file: myform.kv:
<ScreenManagement>:
    ScreenFirst:
    ScreenSecond:
<ScreenFirst>:
    id: screen_first
    name: 'screen_first'
    space_x: self.size[0]/14
    BoxLayout:
        orientation: "vertical"
        size_hint_y: 1
        canvas.before:
            Color:
                rgba: (0.5, 0.8, 0.4, 1.0)
            Rectangle:
                size: self.size
                pos: self.pos
        BoxLayout:
            size_hint_y: .1
            canvas.before:
                Color:
                    rgba: (0.0, 0.0, 0.0, 0.8)
                Rectangle:
                    size: self.size
                    pos: self.pos
            Label:
                text: 'Screen Number 01'
                size_hint_x: 1
        BoxLayout:
            orientation: 'vertical'
            size_hint_y: .8
            padding: screen_first.space_x, 10
            Label:
                size_hint_y: 0.6
            Button:
                id: button1
                text: 'Go To Second Screen'
                size_hint_y: 0.1
                background_color: (0.7, 0.0, 0.2, 0.5)
                background_normal: ''
                on_release: app.root.gotoSecondScreen()
            Label:
                size_hint_y: 0.1
            Button:
                id: button2
                text: 'None'
                size_hint_y: 0.1
                background_color: (0.7, 0.0, 0.2, 0.5)
                background_normal: ''
                on_release: app.root.donothing()
            Label:
                size_hint_y: 0.1
        BoxLayout:
            orientation: 'vertical'
            size_hint_y: .1
            canvas.before:
                Color:
                    rgba: (0.0, 0.0, 0.0, 0.8)
                Rectangle:
                    size: self.size
                    pos: self.pos
            Label:
                text: 'Footnote'
                size_hint_x: 1
<ScreenSecond>:
    id: screen_second
    name: 'screen_second'
    space_x: self.size[0]/14
    BoxLayout:
        orientation: "vertical"
        size_hint_y: 1
        canvas.before:
            Color:
                rgba: (0.5, 0.8, 0.4, 1.0)
            Rectangle:
                size: self.size
                pos: self.pos
        BoxLayout:
            size_hint_y: .1
            canvas.before:
                Color:
                    rgba: (0.0, 0.0, 0.0, 0.8)
                Rectangle:
                    size: self.size
                    pos: self.pos
            Label:
                text: 'Screen Number 02'
                size_hint_x: 1
        BoxLayout:
            orientation: 'vertical'
            size_hint_y: .8
            padding: screen_second.space_x, 10
            BoxLayout:
                orientation: 'vertical'
                ScrollView:
                    do_scroll_y: True
                    Label:
                        id: myList
                        text: ''
                        size_hint_y: 1
                        color: (0.0, 0.0, 0.0, 0.8)
            Button:
                id: button3
                text: 'Return'
                size_hint_y: 0.1
                background_color: (0.7, 0.0, 0.2, 0.5)
                background_normal: ''
                on_release: app.root.gotoFirstScreen()
            Label:
                size_hint_y: 0.1
        BoxLayout:
            orientation: 'vertical'
            size_hint_y: .1
            canvas.before:
                Color:
                    rgba: (0.0, 0.0, 0.0, 0.8)
                Rectangle:
                    size: self.size
                    pos: self.pos
            Label:
                text: ''
                size_hint_x: 1

And this is the py file: main.py:
from kivy.app import App
from kivy.lang import Builder
from kivy.app import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from kivy.uix.image import Image
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.properties import ObjectProperty

class ScreenFirst(Screen):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

class ScreenSecond(Screen):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

class ScreenManagement(ScreenManager):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def gotoFirstScreen(self):
        self.get_screen('screen_first').ids.button1.focus = True
        self.current = 'screen_first'

    def gotoSecondScreen(self):
        mytext = ''
        for i in range(50):
            mytext = mytext + 'Line nr. ' + str(i) + '\n'
        self.get_screen('screen_second').ids.myList.text = mytext
        self.get_screen('screen_second').ids.button3.focus = True
        self.current = 'screen_second'

    def donothing(self):
        pass

class MyForm(App):
    def build(self):
        self.root = ScreenManagement()
        return self.root

if __name__=="__main__":
    pol = MyForm()
    pol.run()

What am I doing wrong?

A: The class that is the child of ScrollView must not have:
size_hint_y: 1

because that is setting the Label height to the same as the ScrollView, and that means there is nothing to scroll. You want the height of the Label to grow as the text requires. Try changing that Label rule in your kv to:
                Label:
                    id: myList
                    text: ''
                    size_hint_y: None
                    text_size: self.width, None
                    height: self.texture_size[1]
                    color: (0.0, 0.0, 0.0, 0.8)


text:
Q: Create replica of a folder structure I have few folders like below structure:
c:\temp\project\folder1\folder2 (this directory is dynamic, I mean there can be more or less folder)
I want to create a shadow of this structure with additional 2 folders in each directory like
C:\temp\projectNew\folder1(under folder1 I want to create 2 more folders, Archive folder, and notprocessed)\folder2(under folder2 I want to create 2 more folders, Archive folder and not processed)
here is my try
var sourcePath = @"C:\\temp\\project";
var parentDirectorty = Directory.GetParent(folderPath);

var sourceDirectoryName = folderPath.Replace(Path.GetDirectoryName(folderPath) + Path.DirectorySeparatorChar, "");
var firstDestiDirectoryName = Directory.CreateDirectory($@"{parentDirectorty}\{sourceDirectoryName}new");

But don't know how to get other folders name and create Archive and NotProcessed folders in each directory.
Sorry for my terrible English.

A: Use GetDirectories to get all directory and sub-directory path of a given path.
Next, for each path, add your folder into it.
public void XXXX(string path)
{
    string[] directories = Directory.GetDirectories(path, "*", SearchOption.AllDirectories);

    directories.ForEach(x=> AddNewFolders(x));
}

public void AddNewFolders(string path)
{
      var archivedFoldeer = Path.Combine(path,"Archive");
      if (!Directory.Exists(archivedFoldeer )
           Directory.CreateDirectory(archivedFoldeer );
      //var notProcesssedFoldeer = Path.Combine(path,"NotProcessed");
}

A: Dump all available directories to string array:
string[] directories = Directory.GetDirectories("C:\\temp\\project", "*", SearchOption.AllDirectories);

Then loop it:
for(int i = 0; i<directories.Length; i++)
{
    string newPath = directories[i].Replace("C:\\temp\\project\\", "C:\\temp\\projectNEW\\");
    Directory.CreateDirectory(newPath);
}

fortunately Directory.CreateDirectory automatically takes care of everything for you


text:
Q: Handling multiple colour declarations for colour printing I want to simplify the task of colour printing a multiline variable using awk.
var="
Blu:
  Some text in blue here
  Some more blue text

Grn:
  Some green text here
  More green text"

awk \
  'BEGIN {
     "tput sgr0" |& getline sgr
     "tput bold; tput setaf 15"  |& getline wht
     "tput bold; tput setaf 34"  |& getline grn
     "tput bold; tput setaf 39"  |& getline blu
     "tput bold; tput setaf 11"  |& getline ylw
     "tput bold; tput setaf 196" |& getline red
     "tput bold; tput setaf 214" |& getline amb

     "tput bold; tput setaf 51"  |& getline cyn
     "tput bold; tput setaf 201" |& getline mgn
   }

   /Wht:$/ { kw=1 ; next }
   /Grn:$/ { kg=1 ; next }
   /Blu:$/ { kb=1 ; next }
   /Ylw:$/ { ky=1 ; next }
   /Red:$/ { kr=1 ; next }
   /Amb:$/ { ka=1 ; next }
   /Cyn:$/ { kc=1 ; next }
   /Mgn:$/ { km=1 ; next }

   !NF { kw=0 ; kg=0 ; kb=0 ; ky=0 ; kr=0 ; ka=0 ; kc=0 ; km=0
         next }
   kw { printf("%s%s%s\n", wht, $0, sgr) }
   kb { printf("%s%s%s\n", blu, $0, sgr) }
   ky { printf("%s%s%s\n", ylw, $0, sgr) }
   kr { printf("%s%s%s\n", red, $0, sgr) }
   ka { printf("%s%s%s\n", amb, $0, sgr) }
   kc { printf("%s%s%s\n", cyn, $0, sgr) }
   km { printf("%s%s%s\n", mgn, $0, sgr) }
  ' <<< "$var"

A: Building on my answer to your previous question and factoring in the requirements from your previous question plus what your current code is trying to do:
$ cat tst.sh
#!/usr/bin/env bash

var="
Blu:
  Some text in blue here
  Some more blue text

Grn:
  Some green text here
  More green text"

awk '
    BEGIN {
        n = split("Wht 15 Grn 34 Blu 39 Ylw 11 Red 196 Amb 214 Cyn 51 Mgn 201",tputColors)
        for ( i=1; i<n; i+=2 ) {
            colorName = tputColors[i] ":"
            colorNr = tputColors[i+1]

            cmd = "tput setaf " colorNr
            fgEscSeq[colorName] = ( (cmd | getline escSeq) > 0 ? escSeq : "<" colorName ">" )
            close(cmd)
        }

        cmd = "tput sgr0"
        colorOff = ( (cmd | getline escSeq) > 0 ? escSeq : "<sgr0>" )
        close(cmd)

        fgColor = dfltFgColor = "Grn:"
    }

    /^[[:alpha:]]+:/ && ($1 in fgEscSeq) { fgColor = $1; next }
    !NF { fgColor = dfltFgColor; next }
    { print fgEscSeq[fgColor] $0 colorOff }
' <<< "$var"

The result of calling tput with the numbers you're using doesn't generate any colors on my terminal so I can't show it working but presumably it'll work on your terminal. Here's the output showing the escape sequences that are produced:
$ ./tst.sh | cat -v
^[[339m  Some text in blue here^[(B^[[m
^[[339m  Some more blue text^[(B^[[m
^[[334m  Some green text here^[(B^[[m
^[[334m  More green text^[(B^[[m

By the way, if you're ever considering using getline make sure to read and fully understand http://awk.freeshell.org/AllAboutGetline to know when and how to use it correctly. In your code you're calling it using a co-process which is unnecessarily GNU-specific and you're calling it in a way that'd just silently populate the wrong colors if it failed and you aren't closing the pipes or killing the processes you're spinning off until the script ends, see my code for the correct and portable way to call it.


text:
Q: Ubuntu 15.04 join domain problem (pbis) I just installed a clean Ubuntu 15.04, and I want to join to a domain for active directory.
Downloaded and installed PBIS Open 8.2.2 - Stable Release but when i run it:
Error: /usr/sbin/service lwsmd start returned 6
Failed to start lwsmd.service: Unit lwsmd.service failed to load: No  such file or directory.

regshell (error = 40700 - LWREG_ERROR_NO_SUCH_KEY_OR_VALUE)
No such key or value

 Error code: ERROR_FILE_NOT_FOUND (0x00000002)

and
Backtrace:
/builder/src-buildserver/Platform-8.2/src/linux/domainjoin/domainjoin-gui/gtk/main.c:614
/builder/src-buildserver/Platform-8.2/src/linux/domainjoin/libdomainjoin/src/djapi.c:257
/builder/src-buildserver/Platform-8.2/src/linux/domainjoin/libdomainjoin/src/djroutines.c:54
/builder/src-buildserver/Platform-8.2/src/linux/domainjoin/libdomainjoin/src/djauthinfo.c:1027

And when I execute the domainjoin-cli it returns me:
Error: Received error while querying lwsmd. [code 0x00000002]

when I try to execute /etc/init.d/lwsmd start, Ubuntu doesn't find it.
How should I proceed?

A: You need to create a systemd unit file for this service, and then enable it. The following worked for me on Ubuntu 15.04 (upgraded from 14.04) with PBIS 8.2.2.
Create the file lwsmd.service in /lib/systemd/system like this:
nano /lib/systemd/system/lwsmd.service

Here are the contents (paste this in to the file you created above)  (taken from a redhat one) so thanks to them:
[Unit]
Description=BeyondTrust PBIS Service Manager
After=network.target

[Service]
Type=forking
EnvironmentFile=/opt/pbis/libexec/init-base.sh
ExecStart=/opt/pbis/sbin/lwsmd --start-as-daemon
ExecReload=/opt/pbis/bin/lwsm refresh
ExecStop=/opt/pbis/bin/lwsm shutdown
# We want systemd to give lwsmd some time to finish gracefully, but still want
# it to kill lwsmd after TimeoutStopSec if something went wrong during the
# graceful stop. Normally, Systemd sends SIGTERM signal right after the
# ExecStop, which would kill lwsmd. We are sending useless SIGCONT here to give
# lwsmd time to finish.
KillSignal=SIGCONT
PrivateTmp=true

[Install]
WantedBy=multi-user.target nss-lookup.target

Once this is done, make a symlink to this file in /etc/systemd/system:
cd /etc/systemd/system
ln -s /lib/systemd/system/lwsmd.service

At this point you should be able to type:
service lwsmd status

and see that the service exists and is enabled.
Then typing:
service lwsmd start

should start it up and have pbis working as expected.
Now to make it work at boot time. Enable the service with this command:
systemctl enable lwsmd.service

It should give some feedback about creating some symlinks.
Then reboot your comp and all should be working.
I hope it was clear enough, and please forgive any typos... Good luck!

A: PBIS is not yet installing a service script (startup script) compatible to systemd in ubuntu. You will have to wait fpr pbis guys to fix that or copy the one used for Fedora/Redhat and startup lwsmd before trying to join your domain.

A: I found this to kind of work so that domainjoin-cli query would work.
sudo /etc/init.d/lwsmd restart
sudo domainjoin-cli query

A: Some addition, in /lib/systemd/system/lwsmd.service you should use
PrivateTmp=false

Because lwsmd service writes krb5cc_uid file for user and computer in /tmp/systemd-private-/some hash/-lwsmd.service/tmp and other applications (browsers, samba clients) can't find it in /tmp/
Therefore SSO doesn't work


text:
Q: Carousel-caption stays below overlay even with higher z-index I want my Bootstrap carousel to have a dotted overlay above the images. The Carousel Caption should be above the dotted overlay.
I can't get it to work with z-indexes.
Am I doing something wrong? (quiet possibly :-))
Here is a JS Fiddle of what i have so far.
http://jsfiddle.net/r4x99ecf/50/
HTML:

This is a caption of image 1.

This is a caption of image 2.

CSS:
.carousel, .carousel-inner {
height: 350px;
}

.overlay {
background: transparent url("http://i.imgur.com/8B7UFiv.png") repeat;
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 1;
}
.carousel-caption {
  position: absolute;
  right: 15%;
  bottom: 100px;
  left: 15%;
  z-index: 10;
  padding-top: 20px;
  padding-bottom: 20px;
  color: #fff;
  text-align: center;
  text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
  font-size:22px;
 }

A: Add

 in each section of the .item
HTML

This is a caption of image 1.

This is a caption of image 2.

This is a caption of image 3.

Fiddle:http://jsfiddle.net/r4x99ecf/51/

A: You can do like Srinivas said, or you can do it like this
http://jsfiddle.net/766omu70/1/

This is a caption of image 1.

This is a caption of image 2.

This is a caption of image 3.

CSS:
.carousel, .carousel-inner {
    height: 350px;
}

.item:before{
    content:"";
    background: transparent url("http://i.imgur.com/8B7UFiv.png") repeat;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    z-index: 1;
}
.carousel-caption {
  position: absolute;
  right: 15%;
  bottom: 100px;
  left: 15%;
  z-index: 10;
  padding-top: 20px;
  padding-bottom: 20px;
  color: #fff;
  text-align: center;
  text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
  font-size:22px;
}

I put the overlay as a pseudoelement, no additional divs necessary.


text:
Q: about electron-vue jQuery.verto is not a constructor I'm using a Verto library in my Vue-electron based project.
In my component's methods I have something like this:
function newVerto () {
  vertoHandle = new jQuery.verto({
    ...
  }, vertoCallbacks)
}

But once I execute it, I receive an error:

"TypeError: jQuery.verto is not a constructor"


text:
Q: Struts2 - How to escape values while filling the options of a select box I have the following code :
<s:select name="user.primaryGroup.id" list="#groupListAction.groups" listKey="id" listValue="name"
  headerKey="" headerValue="Please select" id="addUser-primaryGroup" />

The problem is that the option text will have unescaped HTML like <b>Name</b>. This will cause the options to be displayed in bold. How can I prevent this ? Only the <s:property/> tag seems to escape html.

A: That's true.. According to documentation, only property tag has parameter escape which is by default set to true. Select tag has no such parameter, so I am afraid you have to escape HTML server side... You can use JSoup or similar library for HTML manipulation...

A: You could use this approach instead: html select with struts iterator <s:iterator>
<select id="xxx" size="1" name="xxx">
   <option value=""> <s:text name="page.search.emptyOption" /></option>
   <s:iterator value="xxx">
      <s:if test="%{key.indexOf('|') == -1}">
         <option value="">XXXXXXXXXXXXXXXXX</option>
      </s:if>
   </s:iterator>
</select>

This will allow you to control the situation with <s:property> tag and escape it.


text:
Q: Can You Do MYSQL Transactions in C? I have to regularly put 40k records into my database which is done in a big loop.  This creates a single transaction for every SQL statement and can be quite slow.
In other languages like PHP, I can do transactions and commit all the data to the database in one shot.  It speeds things up tremendously.
But I recently had to write a processing engine for my data in C, and I have not found a way to do transactions in this language.  I tried turning off autocommit, then executing each query in the loop, and finally committing the data when the loop is complete.  But the write is still taking almost 4 minutes.  WAAAAYYYYY too long!
I don't find any information in the MySQL Connector/C documentation for transactions, but since they exist for other MySQL interfaces, surely there is something for C.  Any ideas???


text:
Q: To SSD or not to SSD? (Virtualization - Xenserver) I have several Xenserver boxes running (very well). Most of ours are setup with a RAID1 with two mechanical 7200rpm enterprise sata drives, or RAID10 with 4 7200 enterprise sata drives. The sata drives were selected due to high capacity for the dollar and are WD RE4's, so they are of good quality and decent mechanical drive performance.
I have extra budget to get some nice things for my department, and we were considering getting some SSD's for our virtualization infrastructure. The question is:
Will Xenserver benefit from the SSD's? This isn't such a simple question as it gets complicated when you think out the various possibilities for storage.
We don't have the budget to setup a proper SAN(s) so network storage is out of the question for the time being (guest os's will be stored on the host).
There is no question that the VM's themselves would benefit in performance if they resided on the SSD's, but due to low capacity of SSD's, we were looking at the possibility of having Xenserver itself run off a SSD, however we are questioning if this would have any benefit (does dom0 need high i/o performance? does it matter? or will VM's only really benefit from SSD performance?).
Xenserver configs are fairly basic so having it run from a single disk is not a worry for us (we would just throw together a fresh install then import the VM's from the storage array).
Please advise. (but please don't just say, "yes of course SSD's are better", because it depends how they are used).

A: Getting SSDs just for the hypervisor is a waste of money.  It should be running from memory most of the time, so you would just see faster boot time.  Unless faster boot time for a host is of critical importance to you.  In most cases I would expect you would get better bang for your buck elsewhere.

A: If you really really want to get SSDs you should think about the workloads you are running on XenServer and which ones would benefit from the much higher IOPS and lower latencies - typical candidates are database servers and high traffic mail servers.
As dunxd already said, don't waste money putting the hypervisor on an SSD... I'd rather put it on some 3.5" floppy disks in raid :)
Seriously speaking, where does the SSD thing comes out from? They're just a nice toy you want or you did some analysis and found that your current storage performance is limiting your systems?
Also, SANs will give you many many benefits, you should consider diverting there your budget or keeping it in your pockets until you have enough for a SAN. They are also less expensive than some people might think - keep in mind you could buy some "good enough" SAN (like these) without fully populating it with disks, and add new disks as you need them, choosing from time to time if you need more space (7200rpm nearline disks) or performance (10k, 15k disks) or absolute l33t performance (SSDs), and mix and match them as you need.
(we are actually looking at buying an MD3220i with dual controllers, some 15k disks for our VMs, some 7k2 disks for storing backups, logs, and other slowly moving data, and we'll have plenty of unused slots to fill in the future with whatever we'll need).
If you're into that sort of stuff, you can also buy a new server with lots of disks slots and build up a SAN with FreeNAS or similar stuff.


text:
Q: ASP.net set the Top and Left position of a Panel (Div) using server side code I am using Visual Studio Express 2010, C#
I have a div and need to set it's absolute position (Top, Left) in the server side code.  The position of the div is read in from a file on the server.  I can set the width and height (also read in from a file) but so far I have not been able to find away of setting the position.
Is it possible?
Thanks

A: You can modify attributes in code using:
MyPanel.Attributes.Add("style", "position: [your_position]");

Kris

A: You can also set it like this
YourDivID.Style["position"] = "absolute";
YourDivID.Style["top"] = "20px"; //--- replace with your value
YourDivID.Style["left"] = "20px"; //--- replace with your value

Good Luck!


text:
Q: How to create a entry count for each user in Rails I'm developing an app in which users can create entries. Each entry needs a unique identifier. That identifier consists of 2 values:

*

*A user unique identifier code (ex: ZZ)

*The amount of entries the user has entered

So, if there's a user whose identifier is "ZZ", his entries will be identified by the following ids: "ZZ1", "ZZ2", "ZZ3" and so on.
Other users would have different identifier codes. And their entry count should be independent, even when they are all stored in the same table.
My first attempt was adding a "user_code" field in the users table, and the entry count was a scope in the model that counted the user entries. It does the job. But the problem arises when users delete their entries. The count gets messed up. Let's say that a user has 5 entries, but deletes the 4th entry. Then when a new he creates a new entry, it should be counted as the 6th entry. But since one entry was deleted, then the counter just counts 4 entries, instead of 5.
I'm looking for a better way to do this. Any ideas?
Thanks!

A: Why not just use the standard rails id column? It will meet all of your requirements, increment itself, it won't go back when you delete an entry, and you don't have to write any code.
If you want the identifiers to be something other than a self incrementing integer, have a read of this thread.
Edit I misunderstood the question.
I would suggest adding the next_entry_id to the user model, then retrieving it in a before_create callback to set the value in the entry object and finally incrementing it in an after_create callback (in case db constraints fail the creation).


text:
Q: countif value equals value in another column I want to count the number of values of a column that are equal to a value on the same line in another column. In the following exmaple, I want for each « ans » column the number of values matching the ones on the « ID » column:
ID    | ans A | ans B | ans C
------|-------|-------|------
1     |    34 |     1 |     1
23    |    23 |    23 |    32
4     |     4 |    16 |    25
54    |    54 |    54 |    16
32    |    32 |    17 |    12
.../...
TOTAL |     4 |     3 |     1

I tried with COUNTIF but I can only enter a single value as criteria, if I enter a range I always get a 0 as result. Which function should I use?

A: In B8 enter:
=SUMPRODUCT(--($A2:$A6=B2:B6))

and copy across.

The formula in B8 just compares column B to column A (row-by-row) and counts the matches.For more info see:
xlDynamic
EDIT#1:
The formula:
=SUM({1,2,3})

does correctly calculate in:

*

*GoogleSheets

*Excel 365

*the Excel web-app

*Excel 2007 / Win 7

I don't know about other environments.


text:
Q: How to turn array to int in pyspark? Let's say I have the following dataframe:
my_x = [([1,100]), ([2]), ([3,2])]
my_df = spark.createDataFrame(my_x, ArrayType(IntegerType()))
Now, I want to extract the first element (int) from each array-row. So the final dataframe would have 1,2,3 (one per row). Is there a way of doing this without using a UDF? I tried doing something like
my_df.withColumn("casted", my_df.value.getItem(IntegerType()))
to no avail.
Thanks!

A: Select the 0th position :
my_df.show()
+--------+
|   value|
+--------+
|[1, 100]|
|     [2]|
|  [3, 2]|
+--------+

my_df.withColumn('casted', my_df['value'][0]).show()
+--------+------+
|   value|casted|
+--------+------+
|[1, 100]|     1|
|     [2]|     2|
|  [3, 2]|     3|
+--------+------+

A: A different approach from the above:
    from pyspark.sql.types import ArrayType, IntegerType
    my_x = [([1,100]), ([2]), ([3,2])]
    my_df = spark.createDataFrame(my_x, ArrayType(IntegerType()))

    my_df = my_df.withColumn("firstVal", col("value").getItem([0]))

This should return a dataframe consisting of two columns:
    +--------+--------+
    |   value|FirstVal|
    +--------+--------+
    |[1, 100]|       1|
    |     [2]|       2|
    |  [3, 2]|       3|
    +--------+--------+

A: You can also use element_at function:
from pyspark.sql.types import ArrayType, IntegerType
from pyspark.sql import functions as F
x = [([1,100]), ([2]), ([3,2])]
df = spark.createDataFrame(x, ArrayType(IntegerType()))
df = df.withColumn('extract', F.element_at(F.col('value'), 1))
df.show()

+--------+-------+
|   value|extract|
+--------+-------+
|[1, 100]|      1|
|     [2]|      2|
|  [3, 2]|      3|
+--------+-------+


text:
Q: Why isn't my spline chart showing when using combo charts? So I'm using Highcharts-ng with Angular to create a combination chart of a spline chart and a column chart formatted as a histogram to show trends.
The way it works is that the on the load of the page, I only see the histogram, and not the spline. Changing the order does nothing.
It looks as though if I have the spline chart data hard-coded it shows, but using the program to add in the data after a service is called in does not work.
(function() {
  'use strict';

angular
    .module('app.widgets')
    .directive('trends', trends);

trends.$inject = ['ResultsService'];

/* @ngInject */

function trends() {
    var ddo = {
        restrict: 'EA',
        templateUrl: 'app/widgets/trends/trends.directive.html',
        link: link,
        scope: {
            data: '=',
            config: '='
        },
        controller: controller,
        controllerAs: 'vm',
        bindToController: true
    };

    return ddo;

    function link(scope, element, attrs) {

    }

    function controller($scope, ResultsService) {

        var vm = this;
        var parent = $scope.widgetController;
        var size = {

            height: angular.element('li.widget-border.ng-scope.gridster-item')[1].style.height - 20 ,
            width: angular.element('li.widget-border.ng-scope.gridster-item')[1].style.width - 20
        };

        vm.histogram = {
            chart: {
                zoomType: 'xy'
            },
            title: {
                text: 'Average Monthly Weather Data for Tokyo'
            },
            subtitle: {
                text: 'Source: WorldClimate.com'
            },
            xAxis: {
                categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
                crosshair: true
            },
            yAxis: { // Primary yAxis
                labels: {
                    style: {
                        color: Highcharts.getOptions().colors[2]
                    }
                },
                title: {
                    text: 'Events',
                    style: {
                        color: Highcharts.getOptions().colors[2]
                    }
                }

            },
            tooltip: {
                shared: true
            },
            legend: {
                layout: 'vertical',
                align: 'left',
                x: 80,
                verticalAlign: 'top',
                y: 55,
                floating: true,
                backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
            },

                series: [{
                    name: 'Average',
                    type: 'spline',
                    data: [],
                    marker: {
                        enabled: true
                    }
                }],

            loading: false,
            useHighStocks: false,
            size: {
                height: size.height,
                width: size.width
            }
        };

        vm.processChartData = processChartData;

        vm.data = {
            charts: {
            }
        };

        ResultsService.getData().then(function(res) {
            vm.data = {
                charts: {}
            };

            vm.data.charts = processChartData(res);

            vm.histogram.xAxis.categories = [];
            vm.histogram.series.push ({
                name: 'Events per month',
                type: 'column',
                data: [],
                marker: {
                    enabled: true
                }
            });
            console.log(vm.histogram.series);
            angular.forEach(vm.data.charts.months, function(v,k){

                vm.histogram.xAxis.categories.push(k);
                vm.histogram.series[1].data.push(v);

                });
            vm.histogram.options = {
                plotOptions: {

                }
            };
            vm.histogram.options.plotOptions = {

                column: {

                    borderWidth: 0.5,
                    groupPadding: 0,
                    shadow: true

                },

            };
            console.log(vm.data.charts.months);
            vm.histogram.xAxis.categories.sort();

           var average = calculateAverage();
            vm.histogram.series[0].data=average;

            console.log(vm.histogram.series);

        });

        function swap(pos1, pos2){
            var temp = vm.histogram.series[pos1];
            vm.histogram.series[pos1] = vm.histogram.series[pos2];
            vm.histogram.series[pos2] = temp;

        }

        function calculateAverage() {

            var averageArray = [];
            var total = 0;
            angular.forEach(vm.data.charts.months, function(v,k){
                console.log(v);
                total += v;
            });
            console.log((total/12.0).toFixed(2));
            var average = (total/12.0).toFixed(2);

            angular.forEach(vm.histogram.xAxis.categories, function(v,k){
                averageArray.push(average);

            });
            return averageArray;

        }

        function processChartData(data) {
            var output = {};
            var months = {};
            var dayOfWeek = {};
            var epoch = {};

            angular.forEach(data, function (value, index) {
                // by month
                if (!months[value.eventDate.month]) {
                    months[value.eventDate.month] = 1;
                }
                months[value.eventDate.month] += 1;

                // by day of week
                if (!dayOfWeek[value.eventDate.dayOfWeek]) {
                    dayOfWeek[value.eventDate.dayOfWeek] = 1;
                }
                dayOfWeek[value.eventDate.dayOfWeek] += 1;

                // by day
                if (!epoch[value.eventDate.epoch]) {
                    epoch[value.eventDate.epoch] = 1;
                }
                epoch[value.eventDate.epoch] += 1;

            });
            output.months = months;
            output.dayOfWeek = dayOfWeek;
            return output;
        }
        $scope.$on('gridster-item-resized', function(item){

            var element = angular.element(item.targetScope.gridsterItem.$element[0]);

            vm.histogram.size = {
                height: element.height()-35,
                width: element.width()
            };
            $scope.$broadcast('highchartsng.reflow');

        });

    }

}

})();

The chart on the webpage looks like this with the given code!
As you can see, it shows the legend with the spline, but the spline doesn't show up. I can't figure out why.

A: Your calculateAverage() function returns an array of strings since .toFixed(2) returns a string. Make sure it's an array of numbers. Convert average to a number with average = parseFloat(average) for example.


text:
Q: magento 2.3 customer tax class not showing on product page this is my general setup for taxes:

it works perfectly for customer in the retail customer class. However, I have a few customers who needs to have no tax applied to them. So I've created a new customer tax class, applied this tax class to the wholesale customer group and placed these few customers into the wholesale group. This is my tax rules setup:

these are my customer groups:

this is my test customer with the wholesale group assignment:

I created a test product with price = 50. If I open the product page from frontend, I can see the price as 50. When I add it to the cart, I can see the total correctly: subtotal 40.98 plus taxes. So far, everything works as intended: the price in catalog page shows the price including taxes and the totals shows the net price + the tax separately.
The problem is when I login as the wholesale customer:

*

*in the cart I see everything correctly: price 40.98, subtotal 40.98 + 0 taxes:

*

*but in the product page, I still see 50 as the product price: shouldn't it be 40.98 since the wholesale customer has no tax applied?

I also tried to change the basic tax setup from "including tax" to "excluding tax" for catalog prices but that doesn't seem to change anything: even with excluding tax from catalog prices, the price displayed in the product page is still 50.
Cleaning cache and reindexing doesnt help: the price in catalog page is still 50.
How can I have the price in product page show it correctly for the wholesale customer?

A: I got the same issue, this is fixed for Magento 2.4 but still exist for version 2.3.
You can fix by updating this file: Magento/Tax/Model/Config.php
public function needPriceConversion($store = null)
    {
        $res = false;
        $priceIncludesTax = $this->priceIncludesTax($store) || $this->getNeedUseShippingExcludeTax();
        if ($priceIncludesTax) {
            switch ($this->getPriceDisplayType($store)) {
                case self::DISPLAY_TYPE_EXCLUDING_TAX:
                case self::DISPLAY_TYPE_BOTH:
                    return self::PRICE_CONVERSION_MINUS;
                case self::DISPLAY_TYPE_INCLUDING_TAX:
                    $res = $this->displayCartPricesInclTax($store);
                    break;
                default:
                    break;
            }
        } else {
            switch ($this->getPriceDisplayType($store)) {
                case self::DISPLAY_TYPE_INCLUDING_TAX:
                case self::DISPLAY_TYPE_BOTH:
                    return self::PRICE_CONVERSION_PLUS;
                case self::DISPLAY_TYPE_EXCLUDING_TAX:
                    $res = false;
                    break;
                default:
                    break;
            }
        }

        if ($res === false) {
            $res = $this->displayCartPricesBoth();
        }
        return $res;
    }

https://github.com/magento/magento2/issues/26014


text:
Q: Can signals be used directly in conditional statements in lieu of comparison to 0/1? Can a signal (of type std_logic) be used directly as the condition in an 'if' statement? For example, can I write
if (A and not B) then
instead of
if (A = '1' and B = '0') then ?
I realize something wonky may happen if the signals take other values like 'Z', but aside from that sort of thing, is this syntactically valid? The first one seems much briefer, especially for more complicated logical expressions.
Addendum: What worries me is whether the argument of the "if" is of the right type, if that matters. I'm from a programming (C++) background, so I routinely use things like if( my_int ) instead of if( my_int != 0 ) where my_int is implicitly cast to a bool. Just wasn't sure if the same thing is really going on here. I presume the result of the VHDL comparison A = '1' is an abstract logical value ("true" or "false") and not some concrete std_logic value.

A: Signals of type Boolean : yes of course.
And you can happily use boolean types for synthesis, making life simpler, especially in internal signals, cases where 'Z' and 'X' etc cannot happen.
Signals of type std_logic : yes in VHDL-2008 mode.
It's one of the additions I least like in VHDL-2008 because it implicitly equates '1' and TRUE, and '0' and FALSE. If this is combined with negative logic or active-low signals (as are often used  for resets, RESET_N, imposed by external requirements) the result is an atrocious mess like
if RESET_N then
  -- non-reset case
else
  -- reset case
end if;

Even worse, sometimes the signal is active low but named RESET.
In such cases, please PLEASE please write out if RESET_N = '0' then longhand...
In other cases, use judgment whether the shorter implicit version, or the longer explicit version, will make more sense to the next guy. Both have their uses.


text:
Q: How can I write below programming in jquery function abc(a,b,c)
{
    alert('a :'+a+' b:'+ b);
    xyz(c);
}

function xyz(c)
{
   alert('c :' + c);
}

click here to check value of abc

A: This is a wild guess but I think you might want to rename link to something like
click here ...

And do the following in jquery
$(document).ready(function(){$('#myId').click(function(){
  abc(1,2,3)})});

Jquery is a javascript framework, not a programming language.

A: You could fire the event using this:
$(document).ready(function(){$('some-id').click(abc(1, 2, 3))});

function abc(a,b,c) {
   alert('a :'+a+' b:'+ b);
   xyz(c);
}

function xyz(c) {
   alert('c :' + c);
}

...

click here to check value of abc

A: jQuery is a JavaScript library whose purpose is to make some browser scripting tasks easier. It is not a replacement for JavaScript. Don't try to use it for everything.
Also, using onclick is preferable to using the javascript: pseudo-protocol in a link, and you should provide a real URL for the link to take the user when they have JavaScript turned off:
click here to check value of abc