text:
Q: how to set up hibernate validator 6.0.10.Final correctly I was trying to set up annotation validator to validate the object without using validator class. At first I only include the library validator-api 2.0.1.Final and everything seem to work fine but the object cannot be validated.
After doing some research, I found out that I need to add:
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

to dispatcher servlet but this is when I got very headache. After that it come out an error
then, I added the latest version of hibernate validator to the project and this error come out.
java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.internal.engine.ConfigurationImpl

Trying to solve the error I have tried to add and remove different library and thing and changing the version of the library as well. I end up have these library in my project and I am not using maven to handle the dependency which make me harder to find the error. This is the library I have in my project:

I used few hours to change the library and this is the final result I think might work but it doesn't. Did I miss out something important?
My controller:
@RequestMapping(value = "/add.html", method = RequestMethod.POST)
public ModelAndView addStaff(@Valid @ModelAttribute Staff staff,
        BindingResult result,
        HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    if(result.hasErrors()){
        return new ModelAndView(parentFolder + "addStaff", "staff", staff);
    }

    return new ModelAndView( parentFolder + "addStaff", "staff", new Staff());

}

My Form:

    <form:label path="id">Staff ID</form:label>
    <form:input path="id" type="text" class="form-control" placeholder="0123"/>

    <form:label path="name">Name</form:label>
    <form:input path="name" type="text" class="form-control" placeholder="Adam Teh"/>

    <form:label path="email">Email</form:label>
    <form:input path="email" type="email" class="form-control" placeholder="adam@example.com"/>

    <form:label path="tel">Tel No</form:label>
    <form:input path="tel" type="tel" class="form-control" placeholder="0171234567"/>

    <form:label path="role">Role</form:label>
    <form:select path="role" class="form-control">
        <form:option value="staff" label="staff" />
        <form:option value="admin" label="admin" />
    </form:select>

    Status

        <form:radiobutton path="status" class="form-check-input" id="active" value="1" />
        active

        <form:radiobutton path="status" class="form-check-input" id="inactive" value="0"/>
        inactive

My Modal:
public class Staff {

@NotBlank(message = "Staff id cannot be empty.")
private String id;

@NotBlank(message = "Please type in your name")
private String name;

@Email(message = "There is problem with the email format.")
private String email;

@NotBlank(message = "Please key in your phone number")
@Pattern(message = "Please make sure your phone number only have 10 to 11 number only.", regexp = "^\\d{10,11}$")
private String tel;

private Role role;

private Department department;

private boolean status;

public Staff(String id, String name, String email, String tel, Role role, Department department, boolean status) {
    this.id = id;
    this.name = name;
    this.email = email;
    this.tel = tel;
    this.role = role;
    this.department = department;
    this.status = status;
}

public Staff() {
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getTel() {
    return tel;
}

public void setTel(String tel) {
    this.tel = tel;
}

public Role getRole() {
    return role;
}

public void setRole(Role role) {
    this.role = role;
}

public boolean getStatus() {
    return status;
}

public void setStatus(boolean status) {
    this.status = status;
}

public Department getDepartment() {
    return department;
}

public void setDepartment(Department department) {
    this.department = department;
}}

My Log
29-Jun-2018 09:01:48.460 INFO [http-nio-8084-exec-16] org.apache.catalina.core.ApplicationContext.log Initializing Spring FrameworkServlet 'dispatcher'
29-Jun-2018 09:01:48.996 SEVERE [http-nio-8084-exec-16] org.apache.catalina.core.ApplicationContext.log StandardWrapper.Throwable
 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.internal.engine.ConfigurationImpl
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
    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.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1241)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1154)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:827)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.internal.engine.ConfigurationImpl
    at org.hibernate.validator.HibernateValidator.createGenericConfiguration(HibernateValidator.java:33)
    at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:296)
    at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:223)
    at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
    ... 36 more

29-Jun-2018 09:01:48.996 SEVERE [http-nio-8084-exec-16] org.apache.catalina.core.StandardWrapperValve.invoke Allocate exception for servlet dispatcher
 java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.internal.engine.ConfigurationImpl
    at org.hibernate.validator.HibernateValidator.createGenericConfiguration(HibernateValidator.java:33)
    at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:296)
    at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:223)
    at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
    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.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1241)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1154)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:827)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

Update:
After research for a while I found similar question on nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.internal.engine.ConfigurationImpl
I changed my library to

but another error seem to occur:
29-Jun-2018 13:06:04.616 INFO [http-nio-8084-exec-15] org.apache.catalina.core.ApplicationContext.log Initializing Spring FrameworkServlet 'dispatcher'
29-Jun-2018 13:06:05.068 SEVERE [http-nio-8084-exec-15] org.apache.catalina.core.ApplicationContext.log StandardWrapper.Throwable
 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'validator' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]: Invocation of init method failed; nested exception is javax.validation.NoProviderFoundException: Unable to create a Configuration, because no Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath.
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
    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.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1241)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1154)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:827)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: javax.validation.NoProviderFoundException: Unable to create a Configuration, because no Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath.
    at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:291)
    at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:223)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
    ... 36 more

29-Jun-2018 13:06:05.068 SEVERE [http-nio-8084-exec-15] org.apache.catalina.core.StandardWrapperValve.invoke Allocate exception for servlet dispatcher
 javax.validation.NoProviderFoundException: Unable to create a Configuration, because no Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath.
    at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:291)
    at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:223)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
    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.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1241)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1154)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:827)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

I thought that it might be the problem with class path but adding extra directory to the class path doesn't seem to work at all. I don't know what I miss in there.

A: After searching and trying for few hours, I finally got my problem solved. It turn out that there is some library I am missing that causes the error of NoClassDefFoundError.
This is the list of library I used in the project:

*

*hibernate-validator-6.0.10.Final.jar

*hibernate-validator-annotation-processor-6.0.10.Final.jar

*hibernate-validator-cdi-6.0.10.Final.jar

*validation-api-2.0.1.Final.jar

*javax.el-3.0.1-b09.jar

*classmate-1.4.0.jar

*jboss-logging-3.3.2.Final.jar

by referring to
nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.internal.engine.ConfigurationImpl
After solving this issue, another error pop up, NoProviderFoundException.
This is cause by the line of code
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

I added to my dispatcher servlet. After some troubleshooting, I found a solution on
https://hibernate.atlassian.net/browse/HV-1495 having someone mentioning the old group id problem. I tried to check my library group id and found

org.hibernate

but the new group id is

org.hibernate.validator

Therefore, I change the my library to the correct group id and everything work fine.
and I also removed the line of code I added to my dispatcher-servlet because the problem is still there. Even I remove it, the program still able to run.

A: Could you try to remove javax.el-api-3.0.0.jar? The other jar already contains the API and the implementation and can lead to conflicts.


text:
Q: How to define a structure variable inside another structure? I have 2 structures defined as follows :
typedef struct
{
    char book_name[20] ;
    int book_id ;
    char author[20] ;
    char book_status[20];
}stlib ;

typedef struct
{
    char employee_name[20];
    int employee_id;
    char employee_dept[20];
    char emp_book_status[20];
}stemp ;

How can I define a variable inside a structure pointing to another structure? Is this correct way ?
typedef struct
{
    char book_name[20] ;
    int book_id ;
    char author[20] ;
    char book_status[20];
}stlib ;

typedef struct
{
    char employee_name[20];
    int employee_id;
    char employee_dept[20];
    char emp_book_status[20];
    struct stlib st; // is this correct ?
}stemp ;

A: In your case, as we can see, stlib is a typedef to the unnamed struct and the definition of stlib appears before that of stemp, you need to change
 struct stlib st; // is this correct ?

to
stlib st; // this is correct

in stemp definition and you're good to go.

However, if by saying "inside a structure pointing to another structure", you meant a pointer, then you need to define st as a pointer, that's all.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Customize/modify PrimeVue Bootstrap theme SCSS/SASS I'm new to PrimeVue and I'm trying to customize/modify the Bootstrap theme. I have a separate project where I completely modified the variables of Bootstrap (v4) and I want to use it in PrimeVue. I want to use SCSS so I can manage the styles well (just import the SCSS file needed in the component). How do I do that? Upon looking at the PrimeVue resources directory, it looks like it doesnt have the scss folder of Bootstrap, and it only shows the css file (generated). Any help is greatly appreciated. Thanks!
Edit: I want to completely modify the variables instead of overriding the PrimeVue Bootstrap classes.

A: I don't know if it's still relevant, but you can only make changes in SASS variables if you buy the designer license from Primefaces - otherwise you'll get access only to prebuilt files.
See the designer documentation here.

A: SASS API is open source now, available at github.


text:
Q: Android SQLite Database Update I have a pre-established SQLite Database in my application. It has a table with rows about 20 rows of text. I want to be able to add additional rows to the table without deleting all of the previous information. The only way I have seen which would allow me to do this is to delete all of the previous databases and then recreate it with the new rows. There must be a better way. Thanks for your help!

A: Are you confusing rows with columns?
If you really do mean rows then as antlersoft points out, using the SQL INSERT INTO statement will simply add a new row to a table without affecting any existing table data. This is one of the most basic and commonly used SQL statements.
If you actually mean you need to add columns then use the SQL ALTER TABLE statement.
See..
SQL INSERT INTO statement
SQL ALTER TABLE statement

A: The Android framework, as it relates to SQLite (using a SQLiteOpenHelper) provides two distinct methods for handling database lifecycles - onCreate(), used when the database needs to be created from scratch, and onUpgrade(<database>, int oldVersion, int newVersion) for handling updates.  You can specify the "new" version number in the constructor for the superclass of your SQLiteOpenHelper, and the framework knows to call onUpgrade() based on this parameter and the internal version # in the actual sqlite database.
So, to modify your database during a version change just override onUpgrade() and run whatever SQLite stuff that you need.


text:
Q: Value of Passed-By-Value Struct Does Not Change I am trying to understand how to pass a struct by reference in order to create a linked list. The method I am using is similar to the example code given below. However, when this code is run, the *tester declared in the main function always stays as NULL. Is the passing of a struct to the addNode() function in this way inappropriate (the compiler does not raise any warnings)?
struct test{
  int num;
  struct test *next;
};
void addNode (int num, struct test* tester);

int main (void){
  struct test *tester = null;
  addNode(1, tester);
}

void addNode(int num, struct test* tester){
  struct test *example = malloc(sizeof(struct test));
  example->num = num;
  if (tester == NULL){
    tester = example;
  } else{
    tester->next = example;
  }
}

A: In addNode function the pointer tester no longer points to the location pointed by the tester in main. function and change your function to
void addNode(int num, struct test** tester){
    struct test *example = malloc(sizeof(struct test));
    if (NULL == example )
         exit(0);        // Not enough memory

    example->num = num;
    if (NULL == *tester)
         *tester = example;
    else
        (*tester)->next = example;
}

Call this function from main as addNode(1, &tester);. Now *tester is an alias for tester in main.

A: You are saving the pointer returned by malloc as a struct:
struct test example = malloc(sizeof(struct test));

Perhaps you wanted to store it as a pointer to struct, so that example and tester have matching types:
struct test* example = malloc(sizeof(struct test));

Then, this will make sense:
tester = example;

A: First off, you're assigning NULL to your input.  This:
if (tester = NULL)

should be
if (tester == NULL)

Secondly, in that same branch, you assign a new value to tester.  However, everything in C is passed by value (copy), so your function receives a copy of a pointer.  Therefore, you are only mutating the function's local copy.  You need another level of indirection:
#include <assert.h>

struct test{
  int num;
  struct test *next;
};

void addNode (int num, struct test* tester);

int main (void){
  struct test *tester = NULL;
  addNode(1, &tester);
}

void addNode(int num, struct test** tester){
  / * wrong, check next item */
  assert(tester != NULL);

  struct test example = malloc(sizeof(struct test));
  example->num = num;
  if (*tester == NULL){
    *tester = example;
  } else{
    (*tester)->next = example;
  }
}

Last, malloc returns a void*, which can implicitly be converted to any other type of pointer.  It does not however return an "instance".  So this is wrong:
struct test example = malloc(sizeof(struct test));

and should be:
struct test *example = malloc(sizeof *example);


text:
Q: Why does $\overline{\alpha * \beta}=\bar{\beta} * \bar{\alpha}$ I'm working on this question from Munkres' topology:
Let $\alpha$ be a path in $X$ from $x_0$ to $x_1$; let $\beta$ be a path in $X$ from $x_1$ to $x_2$. Show that if $\gamma = \alpha * \beta$ , then $\bar{\gamma}$= $\bar{\beta} \circ \bar{\alpha}$.
I can answer this questioin I just need help with one step, how would I show that
$$\overline{\alpha * \beta}=\bar{\beta} * \bar{\alpha}$$
Thanks!

A: $$\begin{align}\overline{\alpha * \beta}(t) = (\alpha * \beta)(1-t) &= \begin{cases} \alpha(2(1 - t)) & 0 \leq 1-t \leq 1/2 \\ \beta(2(1-t)-1) & 1/2 \leq 1-t \leq 1 \end{cases}
 \\ &=\begin{cases} \alpha(2 - 2t) & 1/2 \leq t \leq 1 \\ \beta(1 - 2t) & 0 \leq t \leq 1/2 \end{cases}
 \\ &= \begin{cases} \bar{\beta}(2t) & 0 \leq t \leq 1/2  \\ \bar{\alpha}(2t - 1) & 1/2 \leq t \leq 1 \end{cases}
 \\ &= (\overline{\beta}*\overline{\alpha})(t)\end{align}$$
This shows that $\overline{\alpha * \beta} = \overline{\beta} * \overline{\alpha}$ $\blacksquare$

A: This exercise can be done by direct computation of $\overline{\alpha*\beta}$ and $\bar\alpha*\bar\beta$. Compare the result and conclude that they are the same.


text:
Q: Where to find historical release dates? Is there any place on the internet which lists the historical release dates for Winter, Spring and Summer, for every year and every Salesforce instance?

A: Search for "Season YY" site:blogs.salesforce.com
For example, "Winter 14" site:blogs.salesforce.com

Here are the dates for EU1 for the past couple of years.
Winter '15 - 17 Oct 2014
Summer '14 - 18 Jul 2014 – delayed release
Spring '14 - 18 Apr 2014 – delayed release
Winter '14 - 12 Oct 2013
Summer '13 - 15 Jun 2013
Spring '13 - 09 Feb 2013


text:
Q: Terminal applications don't cover the entire terminal I've been researching this for a couple hours so far and I can't seem to find a solution that works and isn't 10 years old so I figured I'd ask again.
I'm using awesome and Alacritty, and when I use, for example, emacs in the terminal, the emacs theme doesn't cover the entirety of the terminal.
I'm fairly sure that the issue has something to do with alacritty resizing based on characters instead of pixels or something like that, but I can't seem to fix it.
I've tried change the gaps in ~/.config/awesome/rc.lua, I've tried changing font sizes in rc.lua, alacritty.yml, and in emacs, all with varying degrees of success.
I've also tried installing i3, and testing on that, because my main pc runs i3 and doesn't have this issue at all, but that doesn't change anything.
All help is appreciated.
Look closely at the bottom of the terminal window, you'll see a dark grey bar. That's the issue I'm talking about.


text:
Q: jdk7 32 bit windows version to download I am just trying to download JDK 7, 32-bit version for windows 7. The system requirement for the JDK on Oracle says it supports a 32-bit version, but it is not listed on the download page. How can I download the 32-bit version?

A: As detailed in the Oracle Java SE Support Roadmap

After April 2015, Oracle will no longer post updates of Java SE 7 to its public download sites. Existing Java SE 7 downloads already posted as of April 2015 will remain accessible in the Java Archive

Check the Java SE 7 Archive Downloads page. The last release was update 80, therefore the 32-bit filename to download is jdk-7u80-windows-i586.exe (64-bit is named jdk-7u80-windows-x64.exe.
Old Java downloads also require a sign on to an Oracle account now :-( however with some crafty cookie creating one can use wget to grab the file without signing in.
wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/7u80-b15/jdk-7u80-windows-i586.exe"

A: Go to the download page and download the Windows x86 version with filename jdk-7-windows-i586.exe.

A: Look for "Windows x86", it's the 32 bit version.


text:
Q: Is it possible to select a whole word in PhpStorm when ctrl-clicking on it? Back in the old days when I was using EditPlus, I could ctrl-click on a word, and the whole word was selected. Is such a functionality possible with PhpStorm as well? If so, how can I achieve this?

A: I've managed to get it done:
I've recorded a macro:

*

*click on a (random) word

*extend selection (ctrl-w)
And saved the macro.
After this, I assigned the shortkey ALT-leftmouse to it, and now I can select a whole word when clicking on it, if you hold down the alt key.
(I decided to keep the ctrl-mouselick to its original function)

A: To select a word just double click the word.
ctrl-click is the Shortcut to go the the declaration of the word(function/variable).
There is a reference sheet and other documentation stuff to dig into:
https://www.jetbrains.com/phpstorm/documentation/


text:
Q: SSH Tunnel to ssl-protected server fails when client connects through tunnel I have a server that has two transport implementations, they are implemented on Qt. Secure and insecure. Secure transport uses QSslSocket, other QTCPSocket. One transport is secure, the other is not.
Both work fine when you connect locally, over VPN or local network. But when you create SSH tunnel to this server on remote machine:
ssh -vvvvv -N -C -p 22 user@10.0.0.35 -L 2506:localhost:2506

... this is where problems start to appear. When I created a tunnel for this server port and tried to connect when servers run insecure implementation of transport - everything is fine. Tunnel is working and the client can connect and work with the server. But when a secure implementation is used (QSslSocket), the ssh tunnel instantly fails right after the client attempts to connect. Errors shown below. Why does this happen?
debug1: Local connections to LOCALHOST:2506 forwarded to remote address localhost:2506
debug3: channel_setup_fwd_listener_tcpip: type 2 wildcard 0 addr NULL
debug3: sock_set_v6only: set socket 4 IPV6_V6ONLY
debug1: Local forwarding listening on ::1 port 2506.
debug2: fd 4 setting O_NONBLOCK
debug3: fd 4 is O_NONBLOCK
debug1: channel 0: new [port listener]
debug1: Local forwarding listening on 127.0.0.1 port 2506.
debug2: fd 5 setting O_NONBLOCK
debug3: fd 5 is O_NONBLOCK
debug1: channel 1: new [port listener]
debug2: fd 3 setting TCP_NODELAY
debug3: ssh_packet_set_tos: set IP_TOS 0x10
debug1: Requesting no-more-sessions@openssh.com
debug3: send packet: type 80
debug1: Entering interactive session.
debug1: pledge: network
debug3: receive packet: type 80
debug1: client_input_global_request: rtype hostkeys-00@openssh.com want_reply 0
debug1: Connection to port 2506 forwarding to localhost port 2506 requested.
debug2: fd 6 setting TCP_NODELAY
debug2: fd 6 setting O_NONBLOCK
debug3: fd 6 is O_NONBLOCK
debug1: channel 2: new [direct-tcpip]
debug3: send packet: type 90
debug3: receive packet: type 92
channel 2: open failed: connect failed: Connection refused
debug2: channel 2: zombie
debug2: channel 2: garbage collecting
debug1: channel 2: free: direct-tcpip: listening port 2506 for localhost port 2506, connect from 127.0.0.1 port 61194 to 127.0.0.1 port 2506, nchannels 3
debug3: channel 2: status: The following connections are open:

A:
channel 2: open failed: connect failed: Connection refused

This means that there is nobody listening on the given address (localhost:2506). So either you program is not started, is crashed, is listening on a different port or has other problems. That's all what can be seen from the logs, for the rest see your program and check with netstat where something is actually listening.


text:
Q: How To Create Business Hours Via Django I am creating a program that allows people to user to sign up their restaurants for a delivery program but, I'm trying implement methods that would allow users to enter their hours of operations when they sign up. So far I got this:
Models.py

WEEKDAYS = [
    (1, _("Monday")),
    (2, _("Tuesday")),
    (3, _("Wednesday")),
    (4, _("Thursday")),
    (5, _("Friday")),
    (6, _("Saturday")),
    (7, _("Sunday")),
    ]

    weekday = models.IntegerField(
        choices=WEEKDAYS,
        unique=True
    )
    from_hour = models.TimeField()
    to_hour = models.TimeField()

Forms.py

class RestaurantForm(forms.ModelForm):

    class Meta:
        model = Restaurant

        fields = ("restaurant_name", "phone", "logo", "tagline", "street_address",
         "state", "city", "zip_Code","weekday", "from_hour", "to_hour")

But, when I run it, the options show ups up in an unusable format that doesn't allow the user to enter more than day and time:

I'm not sure what I should do to be able to setup this form and allow restaurants to add all the days and hours that they are opened or closed.

A: You need to create a new model OpenningTime
with the week_day, from_hour. to_hour
and then have a ManyToManyField in restaurant to OpenningTime.
now you can add multiple days to your restaurant
  WEEKDAYS = [
    (1, _("Monday")),
    (2, _("Tuesday")),
    (3, _("Wednesday")),
    (4, _("Thursday")),
    (5, _("Friday")),
    (6, _("Saturday")),
    (7, _("Sunday")),
 ]
class OpenningTime(models.Model):

    weekday = models.IntegerField(
        choices=WEEKDAYS,
        unique=True)
    from_hour = models.TimeField()
    to_hour = models.TimeField()

class Restaurant(models.Model):
    openning_times = models.ManyToManyField(OpenningTime)


text:
Q: Ruby float with lots of decimals, why? Why is the following operation leading me to this value:
14.99 + 1.5 = 16.490000000000002

I would expect it to be 16.49.  How can I avoid those extra decimals?

A: That's how floating point arithmetic works. If you want a rounded number that's still a Float object, you can do
result.round(2) #=> 16.49

or if you just need a string:
"%0.2f" % result

A: This is not due to Ruby, but because of the way floating point numbers are represented in a computer (according to the IEEE 754 standard).
In short, some floating point numbers just can't be represented exactly in a computer. If you need better precision, you can try the BigDecimal class.


text:
Q: Using a Matlab user function in Python gives an error I  have  user Matlab function. It is written by someone else. There are multiple functions in that file but the first function that has the same name as the .m file itsel is the one that I try to call. It gets 4 arguments (string, string, string, boolean).
Usually in Matlab I call it like this: function('string', 'string, true)
When trying in Python I use following code.
def CodeGenerationAndResim(self, Models=None, Resim=False, Type='TW'):
    """ This function will start Matlab and generates code for each Simulink model
        and creates Resim archives for the release.
        All variables:
            Models                      - All Sim Modelto generate c code for
            Resim                       - Running Resim function
            Type                        - Type of Resim archive
            matlabEngine                - Matlab engine to start Matlab
            MatlabEngineSuccessfull     - Checks if Matlab engine is started without error
            CodeGenSuccessfull          - Checks if Code Generation is successsful
            ResimSuccessfull            - Checks if Resim function is performed successfully.
    """

    # Check variables
    MatlabEngineSuccessfull = True
    CodeGenSuccessfull = True
    ResimSuccessfull = True

    # Call Matlab engine
    try:
        matlabEngine = matlab.engine.start_matlab('-nodesktop', background = False)
        matlabEngine.addpath("C:\\temp")
    except EngineError as e:
        MatlabEngineSuccessfull = False
        Print("Could not start Matlab. Do you have Matlab 64 bits installed?")

    # Generate code for models in a loop
    if Models is not None and MatlabEngineSuccessfull:
        for model in Models:
            try:
                matlabEngine.rtwbuild(model)
            except Exception as e:
                CodeGenSuccessfull = False
                print('Something went wrong')

    # Running Resim
    if Resim and MatlabEngineSuccessfull and CodeGenSuccessfull:
        try:
            matlabEngine.resimPrepareNewVersion('all','DAS2_TwYYWW_2005',1)
        except Exception as e:
            ResimSuccessfull = False
            print(e)

    return MatlabEngineSuccessfull, CodeGenSuccessfull, ResimSuccessfull

The error I get is following:
Error using resimPrepareNewVersion
Too many output arguments.
Too many output arguments.

I don't understand the error. I already give the same arguments as in Matlab.  Even when I give it 3, 2, or no arguments I get the same error.  When Matlab loads this functions are loaded automatically so I don't need to add path but I did it any way. However, I tried without giving any path. Code generation and starting Matlab goes without any problem. In Matlab this function loads some other files and opens a info dialog it it means anything.

A: It was really strange that I all the time red the error as Too many input arguments instead of output arguments
I solved the problem by inserting nargout=0.
Edited:
matlabEngine.resimPrepareNewVersion('all','DAS2_TwYYWW_2005',1)

To :
matlabEngine.resimPrepareNewVersion('all','DAS2_TwYYWW_2005',1, nargout=0)

And it worked very well. Thanks.


text:
Q: go generate stdout piped to gofmt to file What is the syntax so go generate can pipe stdout from go run to gofmt and ultimately to a file?  Below is simple example of what I have tried.  Its in the file main.go.  I can't find any examples of this after searching.  Thank you.
Edit: ultimately I would like to use go generate and have it write a formatted file.
//go:generate go run main.go | go fmt > foo.go
package main

import "fmt"

const content = `
package main
func     foo() string {return "Foo"}
`

func main() {
    fmt.Print(content)
}

A: Use the format package directly instead of running a shell:
//go:generate go run main.go
package main

import (
    "go/format"
    "io/ioutil"
    "log"
)

const content = `
package main
func     foo() string {return "Foo"}
`

func main() {
    formattedContent, err := format.Source([]byte(content))
    if err != nil {
        log.Fatal(err)
    }
    err = ioutil.WriteFile("foo.go", formattedContent, 0666)
    if err != nil {
        log.Fatal(err)
    }
}

Avoid using a shell like bash because the shell may not be available on all systems where the Go tools run.


text:
Q: Ada: Write to File Multiple Times In Ada, can you open, write to, close, then reopen, write to, and close a txt file without it being overwritten? Like continue from where it last left off?
Thanks!

A: Yes.  If you look in section A.10.1 in the reference manual, you can see that the package Ada.Text_IO includes the declaration:
type File_Mode is (In_File, Out_File, Append_File);

Append_File is the mode you are looking for.
A.10.2(3) in the reference manual requires that you get a new line, when you close a file:

For the procedure Close: If the file has the current mode Out_File or Append_File, has the effect of calling New_Page, unless the current page is already terminated; then outputs a file terminator.

... where A.10.5(16) explains what New_Page does:

Operates on a file of mode Out_File or Append_File. Outputs a line terminator if the current line is not terminated, or if the current page is empty (that is, if the current column and line numbers are both equal to one). Then outputs a page terminator, which terminates the current page. Adds one to the current page number and sets the current column and line numbers to one.

If you want more detailed control over what ends up in a file, you should use one of the other I/O packages.


text:
Q: Issue with second flexbox when stacking them I'm currently having an issue where my FlexBox is not positioning my nested element all the way to the right with the justify-content: flex-end; and align-items: flex-start; properties.
In the picture below, the big grey box is in panel class which houses the initial borders. Within the panel class is the panel-price-box which should create a secondary box and send it to the top right position of the initial box.
The code is in SCSS.
CSS:
.product
{
    display: block;
    position: relative;
    background: transparent;
    overflow: hidden;
    height: 100px;
    width: 100%;
    border: $border-small $panel-color;
    border-radius: $border-radius-small;

    &-price
    {
        display: flex;
        justify-content: flex-end;
        align-items: flex-start;

        &-box
        {
            display: flex;
            justify-content: center;
            align-items: center;
            border-left: 1px solid grey;
            border-bottom: 1px solid grey;
            border-radius: 0px 0px 0px 5px;
            height: 25px;
            width: 100px;

        }
    }

}

HTML:

The picture below is the live example of what my end result is.

Any help would be very much appreciated!

A: Did you try this?

.product
{
    position: relative;
    background: transparent;
    overflow: hidden;
    height: 100px;
    width: 100%;
    border: $border-small $panel-color;
    border-radius: $border-radius-small;

    display: flex;
    justify-content: flex-end;
    align-items: flex-start;

    &-price
    {
        &-box
        {
            display: flex;
            justify-content: center;
            align-items: center;
            border-left: 1px solid grey;
            border-bottom: 1px solid grey;
            border-radius: 0px 0px 0px 5px;
            height: 25px;
            width: 100px;

        }
    }

}


text:
Q: Where to write specification file for Flex? I want to perform some pattern matching using flex bison. I want to know how to use flex and where to create specification file for this (tools or software). And when the tokens are generated by flex, where to write specification file for bison. I want to know about Editors IDEs or tools. Can I perform all the tasks using Turbo C or what else is required?

A: This question has not attracted an answer because it's asking for an introductory tutorial and there are plenty available online that any search engine could find.
One nice tutorial is here: http://aquamentus.com/flex_bison.html which answers most of these questions.
As a bison and flex file is a text file, it can be amended by any text editor, such as notepad, notepad++, vi, vim, emacs and so on. You did not specify what platform you would be running on. Visual Studio can even be configured to work with the tools, although it's a bit clunky. Yes: You can build the C output with Turbo C. The tools can also generate C++.
Most people would use GCC and command prompt builds for basic use of flex and bison.
I teach students this method. You can use my online videos if that helps:
YouTube Channel on Flex and Bison


text:
Q: What is needed in my ARM template to add azure function? I have an ARM template for my resource group. In there I have set up a Function App which is correctly deployed with my ARM template using Octopus Deploy (OD).
Now I have with C# developed an Azure Function which I want to be deployed into my Function App.
This can be done with a separate step (using a template) in OD and all seemed well when deploying... Except that it does not show up in my Function App in Azure as I expect it to.
Is there any further configuration in my ARM template I need to do? I haven't found anything on the subject, when deploying a c# azure function.
For a csx azure function it can be configured/deployed in the ARM template but it is not recommended for a c# azure function, what I read.
EDIT:
This is a part of my ARM template. The FunctionApp is created with the following resource.
{
  "type": "Microsoft.Web/sites",
  "apiVersion": "2018-11-01",
  "name": "[parameters('sites_..._name')]",
  "location": "[parameters('location')]",
  "kind": "functionapp",
  "dependsOn": [
    "[resourceId('Microsoft.Web/serverfarms', parameters('serverfarms_..._name'))]",
    "[resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName'))]"
  ],
  "identity": {
    "type": "SystemAssigned"
  },
  "properties": {
    "enabled": true,
    "siteConfig": {
      "appSettings": [
        {
          "name": "FUNCTIONS_WORKER_RUNTIME",
          "value": "[parameters('runtimeStack')]"
        },
        {
          "name": "AzureWebJobsStorage",
          "value": "[concat('DefaultEndpointsProtocol=https;AccountName=',variables('storageAccountName'),';AccountKey=',listKeys(resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName')), '2017-06-01').keys[0].value)]"
        },
        {
          "name": "FUNCTIONS_EXTENSION_VERSION",
          "value": "~2"
        },
        //...
        {
          "name": "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING",
          "value": "[concat('DefaultEndpointsProtocol=https;AccountName=', variables('storageAccountName'), ';AccountKey=', listKeys(resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName')),'2017-06-01').keys[0].value)]"
        },
        {
          "name": "WEBSITE_CONTENTSHARE",
          "value": "[parameters('sites_..._name')]"
        }
      ]
    },
    "hostNameSslStates": [
      {
        "name": "[concat(parameters('sites_..._name'), '.azurewebsites.net')]",
        "sslState": "Disabled",
        "hostType": "Standard"
      },
      {
        "name": "[concat(parameters('sites_..._name'), '.scm.azurewebsites.net')]",
        "sslState": "Disabled",
        "hostType": "Repository"
      }
    ],
    "serverFarmId": "[resourceId('Microsoft.Web/serverfarms', parameters('serverfarms_..._name'))]",
    "reserved": false,
    "isXenon": false,
    "hyperV": false,
    "scmSiteAlsoStopped": false,
    "clientAffinityEnabled": false,
    "clientCertEnabled": false,
    "hostNamesDisabled": false,
    "containerSize": 1536,
    "dailyMemoryTimeQuota": 0,
    "httpsOnly": true,
    "redundancyMode": "None"
  }
}

As you can see I am registering my FunctionApp which after deployment of the ARM template AND separate deploy of my azure function TO that FunctionApp should include the azure function.
Though, the azure function do not show up under my FunctionApp.


text:
Q: What's an HTML code to change the width of an eBay page? This is the what the codes I already have looks like, but I want to set it to an exact width so everything looks neat:

I'm not very good with HTML and was hoping someone could tell me what to put where. Here's the code I have:

  Product Information

    <big>Description
    </big>

    This is a 2016 Peyton Manning #18 Jersey.

    Team: Denver Broncos

    Player: Peyton Manning

    Color: Orange

    Brand: Nike

    This is a used item that has NO defects. No rips, tears, or stains.

      <big>Size
      </big>

      This is a Large/44 Jersey. These are the measurements:

          Measurement Chart

          Country

          Length

          Width

          Sleeves

          U.S.

          Europe

  If you want further details on the sizing, please feel free to message us!

      <big>Shipping
      </big>

    This item is shipped using USPS Priority Mail. It is shipped out of St. Paul, MN 55014.

  We try to ship this package within 24 hour of the time you pay for the item.

We ship Internationally.

  The following is included in this shipment:

    1.      2-4 Day Shipping in the US

      2.      Free Tracking

      3.      Insurance for your package up to $50.00

      Please insure that your address is correct. If you are worried your package could be stolen please contact your Post Office with the tracking number and have them hold it there for you. Unfortunately once the tracking shows the package has been delivered to the address it is your responsibility and refunds cannot be accepted.

      If your package was damaged by USPS, please contact us ASAP with photos showing the extent of the damage. You will be refunded and we will take care of making an insurance claim with USPS since packaging was our responsibility.

          <big>Return Policy
          </big>

        We try to make the description of the item you're buying as detailed as possible to avoid the need for returns. If your item contains a defect that was not listed in the description we will accept a return with photos of the defect. If the item's defect is clearly not in the photos we posted, or seem to be manufactured, your return will not be accepted.

          <big>Payment
          </big>

        We accept PayPal and Credit/Debit cards. After you click "Purchase Item" you are not done checking out! Click on PAY NOW. Your package will not be shipped until you pay for your item, and it will be cancelled if you do not pay within 2 Business Days.

A: I wouldn't recommend a fixed width.  On mobile devices your template wont show very well.  I would recommend you look a simple responsive grid css layout like skeleton - it will resize it all to the width of the browser, works fine in eBay!

A: How about putting your entire page in a container, giving that container a width of how big you want it to be and centering it. In my snippet, I gave the container a width of 50vw (Which equals to 50% of the current viewport width)

#container{
  width:50vw;
  display:block;
  margin:0 auto;
}

Product Information

<big>Description                                                                                </big>

This is a 2016 Peyton Manning #18 Jersey.

Team: Denver Broncos

Player: Peyton Manning

Color: Orange

Brand: Nike

This is a used item that has NO defects. No rips, tears, or stains.

<big>Size                                                                                </big>

This is a Large/44 Jersey. These are the measurements:

Measurement Chart

Country

Length

Width

Sleeves

U.S.

Europe

If you want further details on the sizing, please feel free to message us!

<big>Shipping                                                                                </big>

This item is shipped using USPS Priority Mail. It is shipped out of St. Paul, MN 55014.

We try to ship this package within 24 hour of the time you pay for the item.

We ship Internationally.

The following is included in this shipment:

1.      2-4 Day Shipping in the US

2.      Free Tracking

3.      Insurance for your package up to $50.00

Please insure that your address is correct. If you are worried your package could be stolen please contact your Post Office with the tracking number and have them hold it there for you. Unfortunately once the tracking shows the package has been delivered to the address it is your responsibility and refunds cannot be accepted.

If your package was damaged by USPS, please contact us ASAP with photos showing the extent of the damage. You will be refunded and we will take care of making an insurance claim with USPS since packaging was our responsibility.

<big>Return Policy                                                                                </big>

We try to make the description of the item you're buying as detailed as possible to avoid the need for returns. If your item contains a defect that was not listed in the description we will accept a return with photos of the defect. If the item's defect is clearly not in the photos we posted, or seem to be manufactured, your return will not be accepted.

<big>Payment                                                                                </big>

We accept PayPal and Credit/Debit cards. After you click "Purchase Item" you are not done checking out! Click on PAY NOW. Your package will not be shipped until you pay for your item, and it will be cancelled if you do not pay within 2 Business Days.


text:
Q: Dashed lines with markers in gnuplot 4.6 I am trying to plot my data using gnuplot 4.6 and I'd like to have dashed lines with markers for some data, while using postscript environment for the output. When I define a line style and use it to plot the data, The output has only the markers.
set terminal postscript eps color enhanced dl 3
set out "out.eps"
set style line 1 lt 2 lc rgb "red" pt 7 ps 0.750
plot 'data.dat' u 1:2 ls 1

This gives only the marker pt 7 without the dashed lines. But when I plot the same data without defining any line style, but specifying the options along with plot command, both marker and dashed lines are present in the output.
set terminal postscript eps color enhanced dl 3
set out "out.eps"
plot 'data.dat' u 1:2 w lp lt 2 pt 11 ps 1

I get dashed lines only when I specify linetype along with plot command, but not while defining it as part of the line style. Can anyone explain why is this so?


text:
Q: How to store the images to the app in swift ios?     @IBAction func btnClicked(){

    let alertController = UIAlertController(title: "Choose an option", message: "", preferredStyle: .Alert)

    let cameraRollAction = UIAlertAction(title: "Camera Roll", style: .Default) { (action) in
        self.imagePicker.delegate = self
        self.imagePicker.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum;
        self.imagePicker.allowsEditing = true
        self.presentViewController(self.imagePicker, animated: true, completion: nil)

    }
    alertController.addAction(cameraRollAction)

    let takePictureAction = UIAlertAction(title: "Take a picture", style: .Default) { (action) in
        self.imagePicker.delegate = self
        self.imagePicker.allowsEditing = true
        self.imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
        self.imagePicker.cameraCaptureMode = .Photo
        self.imagePicker.modalPresentationStyle = .FullScreen
        self.presentViewController(self.imagePicker,
            animated: true,
            completion: nil)
    }
    alertController.addAction(takePictureAction)

}

How can I store the images to the app that I am selecting from the device? Whenever I select the images it appears but when I close and reopen the app the image disappears.

A: An alternative could be that you can save the images in the app's document directory. And all the paths to those images can be stored in NSUserDefaults.
Check this link for saving images to document directory :
Click me !
Add your NSUserDefaults logic accordingly.
Thanks.

A: here an example how to store an image
    let image:UIImage = UIImage.init(contentsOfFile: "someImagePath")!//here it will be the image that you get from the pickerController
    let data:NSData = UIImagePNGRepresentation(image)!
    data .writeToFile("file_Path", atomically: true)

EDIT
you have implement this protocol of UIImagePickerViewContoller
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info;

in info dictionary you will find the Image.
so you can put the code example above in the protocol implementation.

A: if you need to store a number of different images, then you should have a look at database options - here's a good tutorial on CoreData http://www.raywenderlich.com/115695/getting-started-with-core-data-tutorial but if you only need to store a single image per app, then you could do that as part of storing the user defaults, and there's a good tutorial available for that as well http://www.raywenderlich.com/1914/nscoding-tutorial-for-ios-how-to-save-your-app-data


text:
Q: MySQL Workbench Error 1005 cant create table So I am very new to MySQL but I would like to think I that grasp a decent bit of it so far. I am struggling with the creation of the table PROJECT. I'm almost positive after my own research that it has something to do with my keys in the table. But I do not understand where the problem is or how to fix it.
The SQL queries below creates all tables for the project. I'm not sure of the problem because I only get the error code for the project for now. Any insight and advice on what causes this and how to rectify this in the code would be greatly appreciated.
CREATE TABLE IF NOT EXISTS `ebrasi1db`.`employee` (
  `ssn` VARCHAR(10) NOT NULL,
  `fname` VARCHAR(45) NULL DEFAULT NULL,
  `minit` VARCHAR(1) NULL DEFAULT NULL,
  `lname` VARCHAR(45) NULL DEFAULT NULL,
  `bdate` DATE NULL DEFAULT NULL,
  `address` VARCHAR(45) NULL DEFAULT NULL,
  `sex` VARCHAR(1) NULL DEFAULT NULL,
  `salary` INT(11) NULL DEFAULT NULL,
  `superssn` VARCHAR(10) NULL DEFAULT NULL,
  `dno` INT(11) NULL DEFAULT NULL,
  PRIMARY KEY (`ssn`),
  INDEX `superssn_idx` (`superssn` ASC),
  INDEX `dno_idx` (`dno` ASC),
  CONSTRAINT `superssn`
    FOREIGN KEY (`superssn`)
    REFERENCES `ebrasi1db`.`employee` (`ssn`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `dno`
    FOREIGN KEY (`dno`)
    REFERENCES `ebrasi1db`.`department` (`dnumber`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)

 ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `ebrasi1db`.`department`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ebrasi1db`.`department` (
  `dnumber` INT(11) NOT NULL,
  `dname` VARCHAR(45) NULL DEFAULT NULL,
  `mgrssn` VARCHAR(10) NULL DEFAULT NULL,
  `mgrstartdate` DATE NULL DEFAULT NULL,
  PRIMARY KEY (`dnumber`),
  INDEX `mgrssn_idx` (`mgrssn` ASC),
  CONSTRAINT `mgrssn`
    FOREIGN KEY (`mgrssn`)
    REFERENCES `ebrasi1db`.`employee` (`ssn`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)

ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `ebrasi1db`.`dept_locations`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ebrasi1db`.`dept_locations` (
  `dnumber` INT(11) NOT NULL,
  `dlocation` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`dnumber`, `dlocation`),
  CONSTRAINT `dnumber`
    FOREIGN KEY (`dnumber`)
    REFERENCES `ebrasi1db`.`department` (`dnumber`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `ebrasi1db`.`project`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ebrasi1db`.`project` (
  `pnumber` INT(11) NOT NULL,
  `pname` VARCHAR(45) NULL,
  `plocation` VARCHAR(45) NULL,
  `dnum` INT(11) NOT NULL,
  PRIMARY KEY (`pnumber`),
  INDEX `dnum_idx` (`dnum` ASC),
  INDEX `plocation_idx` (`plocation` ASC),
  CONSTRAINT `dnum`
    FOREIGN KEY (`dnum`)
    REFERENCES `ebrasi1db`.`department` (`dnumber`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `plocation`
    FOREIGN KEY (`plocation`)
    REFERENCES `ebrasi1db`.`dept_locations` (`dlocation`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `ebrasi1db`.`works_on`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ebrasi1db`.`works_on` (
  `essn` VARCHAR(10) NOT NULL,
  `pno` INT NOT NULL,
  `hours` DECIMAL(5,2) NULL,
  PRIMARY KEY (`essn`, `pno`),
  INDEX `pno_idx` (`pno` ASC),
  CONSTRAINT `works_on_essn`
    FOREIGN KEY (`essn`)
    REFERENCES `ebrasi1db`.`employee` (`ssn`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `pno`
    FOREIGN KEY (`pno`)
    REFERENCES `ebrasi1db`.`project` (`pnumber`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `ebrasi1db`.`dependent`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ebrasi1db`.`dependent` (
  `essn` VARCHAR(10) NOT NULL,
  `dependent_name` VARCHAR(45) NOT NULL,
  `sex` VARCHAR(1) NULL,
  `bdate` DATE NULL,
  `relation` VARCHAR(45) NULL,
  PRIMARY KEY (`essn`, `dependent_name`),
  CONSTRAINT `dependent_essn`
    FOREIGN KEY (`essn`)
    REFERENCES `ebrasi1db`.`employee` (`ssn`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

A: Normally you get the Error 1005 when it unable to create the foreign keys. When you are creating a foreign key constraint the parent table should be available in the database.
In your case 'employee' table has a FK to 'department' table but you are trying to create the 'employee' table before creating the 'department' table. Also the 'department' table has a FK back to 'employee' table. Therefore you are not able to create the 'department' table first. To solve this you may create the 'department' table first without FK to 'employee' table. Then create the 'employee' table and then alter the 'department' table with FK.
Here is the modified code for first two tables and follow the same pattern for rest if you get the same error.
CREATE TABLE IF NOT EXISTS `ebrasi1db`.`department` (
`dnumber` INT(11) NOT NULL,
  `dname` VARCHAR(45) NULL DEFAULT NULL,
  `mgrssn` VARCHAR(10) NULL DEFAULT NULL,
  `mgrstartdate` DATE NULL DEFAULT NULL,
  PRIMARY KEY (`dnumber`),
  INDEX `mgrssn_idx` (`mgrssn` ASC))
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS `ebrasi1db`.`employee` (
  `ssn` VARCHAR(10) NOT NULL,
  `fname` VARCHAR(45) NULL DEFAULT NULL,
  `minit` VARCHAR(1) NULL DEFAULT NULL,
  `lname` VARCHAR(45) NULL DEFAULT NULL,
  `bdate` DATE NULL DEFAULT NULL,
  `address` VARCHAR(45) NULL DEFAULT NULL,
  `sex` VARCHAR(1) NULL DEFAULT NULL,
  `salary` INT(11) NULL DEFAULT NULL,
  `superssn` VARCHAR(10) NULL DEFAULT NULL,
  `dno` INT(11) NULL DEFAULT NULL,
  PRIMARY KEY (`ssn`),
  INDEX `superssn_idx` (`superssn` ASC),
  INDEX `dno_idx` (`dno` ASC),
  CONSTRAINT `superssn`
    FOREIGN KEY (`superssn`)
    REFERENCES `ebrasi1db`.`employee` (`ssn`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `dno`
    FOREIGN KEY (`dno`)
    REFERENCES `ebrasi1db`.`department` (`dnumber`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)

 ENGINE = InnoDB;

alter table department  add
  CONSTRAINT `mgrssn`
    FOREIGN KEY (`mgrssn`)
    REFERENCES `ebrasi1db`.`employee` (`ssn`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION;

A: Your problem lies essentially in the fact that you are trying to create a constraint to a non key column (because the referenced table has a double key).
In your table project you have:
CONSTRAINT `plocation`
FOREIGN KEY (`plocation`)
REFERENCES `dept_locations` (`dlocation`)
ON DELETE NO ACTION
ON UPDATE NO ACTION

dept_locations.dlocation is not a key ALONE (primary key), therefore the reason you are not able to create that constraint.
You need to make the constraint for both keys from the referenced table like this:
CONSTRAINT `plocation`
FOREIGN KEY (`pnumber`, `plocation`)
REFERENCES `dept_locations` (`dnumber`, `dlocation`)
ON DELETE NO ACTION
ON UPDATE NO ACTION

In this case you won't need the first constraint dnum as it is already referenced in dept_locations table.
Also note that you tables department and employee will not be created because one reference the other so you need to create the tables first without the constraints then apply the constraints like:
ALTER TABLE `employee` add
CONSTRAINT `dno`
FOREIGN KEY (`dno`)
REFERENCES `department` (`dnumber`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;

Same for the department table and its constraint to employee


text:
Q: Javascript block on AJAX load I am looking for a way to make an AJAX load request in javascript, but have the javascript code pause execution while waiting for the AJAX load to complete. In other words, I am trying to do a synchronous AJAX load request (I know the 'A' in AJAX stands for asynchronous. I'm just hoping maybe the name isn't exactly right.) . What I have is
$('#my_id').load("my_page.pl?my_param=p1&my_other_param=p2");
//Please wait here
//Now do stuff after load is complete.

The reason I want the request to be synchronous is because it creates an HTML table, and then the javascript which follows parses the table.

A: jQuery's 'load()' method takes a callback. Callbacks are generally how async code handles the "waiting" feature you want.
$("#my_id").load("my_page.pl?my_param=p1&my_other_param=p2", function (response) {
    // do this stuff, which will run after the request is complete
});

A: That looks like jquery... I can't be sure because I don't know jquery at all but if so you might get better answers tagging it as such.
I can tell you that javascript has it's own method for synchronous OR asynchronous calls. This is what I use:
var xmlhttp;
if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
}
else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// Use the activeX object for old IE

xmlhttp.open("GET","http://some.internet.address/woot?foo=bar", false);
// The third argument in the open function determines the asynchronous nature,
//it was set to false, so the code will halt at the send() point while the request is executed.
xmlhttp.send();
// Now, if the call succeeded...
if (xmlhttp.status==200) {
    response = eval('('+xmlhttp.responseText+')');
    // ...save the results to an object named response...
}
else {
    // ...Otherwise do some other stuff
    errorFunction(xmlhttp.status);
}

Lots of good info is also available here -
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp


text:
Q: Is there a way to combine these two if statements? I was working on a personal assignment where the user types their birthday, and then it displays the user's astrological sign and a description of the sign. But since all astrological signs are multiple months, I have split the if statements into multiple if statements, one for each month, for example
if (birthMonth == 5 && (21<=birthDay && birthDay <=31)) {
        JFrame frame = new JFrame();
        String symbol = "Your sign is Gemini. You are cerebral, chatty, love learning and education, charming, and adventurous.   ";
        symbol += bday;
        JLabel label = new JLabel(symbol, new ImageIcon("gemini.jpg"), JLabel.CENTER);
        label.setVerticalTextPosition(SwingConstants.TOP);
        frame.add(label);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    else if (birthMonth == 6 && (1<=birthDay && birthDay <=21)) {
        JFrame frame = new JFrame();
        String symbol = "Your sign is Gemini. You are cerebral, chatty, love learning and education, charming, and adventurous.   ";
        symbol += bday;
        JLabel label = new JLabel(symbol, new ImageIcon("gemini.jpg"), JLabel.CENTER);
        label.setVerticalTextPosition(SwingConstants.TOP);
        frame.add(label);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

I was wondering if there is a way to combine the if statements, while keeping the code working the way it currently is. Many thanks in advance!

A: Both logic and behavior are same so you don't have to use two condition to write your logic you can use below code as a single way.
if (birthMonth == 5 && (21<=birthDay && birthDay <=31) || birthMonth == 6 && (1<=birthDay && birthDay <=21)) {
        JFrame frame = new JFrame();
        String symbol = "Your sign is Gemini. You are cerebral, chatty, love learning and education, charming, and adventurous.   ";
        symbol += bday;
        JLabel label = new JLabel(symbol, new ImageIcon("gemini.jpg"), JLabel.CENTER);
        label.setVerticalTextPosition(SwingConstants.TOP);
        frame.add(label);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

A: Why don't you use the or operator || ? like this:
(birthMonth == 5 && (21<=birthDay && birthDay <=31) || (birthMonth == 6 & (1<=birthDay && birthDay <=21)))


text:
Q: Why is the sign flag set even on addition of 5FH and 33H? I am studying about 8085 microprocessor and I came across an instruction - ADC.
In the example, they gave the accumulator [A] = 57H and a register [D] = 33H and initially carry was set, so [CY] = 01H
Instruction: ADC D
They added 57H, 33H and 01H
0 1 0 1 1 1 1 1
0 0 1 1 0 0 1 1
0 0 0 0 0 0 0 1
Answer: 1 0 0 1 0 0 1 1.
They said that the sign flag is now set as the MSB contains the higher bit. I do not understand why is the answer considered to be negative, even though an addition operation is conducted.

A: It's negative by definition. Under two's complement, any number where the top bit is set is a negative number. 57 + 33 + 1 = 8B, which has the top bit set. Therefore it is a negative number.
In your case it's unfortunate that the register isn't large enough to hold the true result. If it were a 16-bit register you'd have computed 0057 + 0033 + 0001 = 008B, which doesn't have the top bit set. If you intended to keep signed numbers about, you've lost information — you can no longer tell whether this is really meant to be decimal 139 or -117. But if you're working purely in unsigned numbers then you can just ignore the sign flag. You know it doesn't apply.
You can also use the overflow flag to check whether the result has the wrong sign. Overflow is set for addition if two positives seemingly produce a negative or if two negatives seemingly produce a positive.
In your case both sign and overflow should be set.


text:
Q: Can't get rid of a global variable (Need to make it non-global) I'm working on a web app that shows the total duration of a playlist. Here we're dealing with the YouTube API. And I want to know how should I get rid of the global variable newPageToken. Also I still need to use it in the third function on this snippet.
let newPageToken = null;

// Next page for more results (Max 50 per page)
function getNextTokenURL() {
    console.log(newPageToken);
    return newPageToken
        ? `${playlistItemsURL}&playlistId=${extractedPlaylistIDId}&pageToken=${newPageToken}&key=${API_KEY}`
        : `${playlistItemsURL}&playlistId=${extractedPlaylistIDId}&key=${API_KEY}`;
}

async function getVideoIdsForPageToken() {
    try {
        const { data } = await axios.get(getNextTokenURL());
        const nextPageToken = data.nextPageToken;
        const videoIds = data.items.map((video) => {
            return video.contentDetails.videoId;
        });
        return { videoIds, nextPageToken };
    } catch (e) {
        if (e.response) {
            const { code, message } = e.response.data.error;
            throw new Error(`StatusCode ${code}. Reason: ${message}`);
            console.log("Errow while fetching videos list.");
        } else {
            throw new Error(e.message);
        }
    }
}

// Navigates between the videos per page and adds them (Maximum 50)
async function getPlaylistData() {
    try {
        const { videoIds, nextPageToken } = await getVideoIdsForPageToken();
        let pageToken = nextPageToken;
        newPageToken = pageToken;
        const returnedVideoIds = [];
        returnedVideoIds.push(getDetailsForVideoIds(videoIds));
        const videoGroups = await Promise.all(returnedVideoIds);

        for (const group of videoGroups) {
            for (const video of group) {
                finalTotalDuration += returnedToSeconds(video.contentDetails.duration);
            }
        }

        // console.log(videoIds);
        if (nextPageToken) {
            await getPlaylistData();
        }
    } catch (e) {
        throw new Error(e.message);
        console.log("Error while navigating between video pages.");
    }
}```

A: Assumptions

*

*finalTotalDuration is also a global variable declared somewhere (Not a good idea)

*You call getPlaylistData for multiple playlist for multiple users

Solution
You need to ensure the getPlaylistData is standalone and returns the finalTotalDuration as a return value (not set a global one)
To make it standalone it has to be iterative in nature. It should be a recursive function which does the following
async function getPlaylistTotalDuration(newPageToken) {

    // Step 1: Create the required query URL based on the newPageToken parameter
    // Step 2: Start a local duration counter
    // Step 3: Get the video details based on the URL created in Step 1
    // Step 4: Get the durations in seconds and add it to the local duration counter created in Step 2
    // Step 5: Check if the return of Step 3 has a nextPageToken, if so do a recursive call to self with the new token
    // Step 6: Return the final value, which will propogate back in a recursive function

}

You can simply call the function like
let finalTotalDuration = getPlaylistTotalDuration(null); // or getPlaylistTotalDuration();

for example the below getPlaylistTotalDuration is a replacement to your getPlaylistData method

async function getVideoIdsForPageToken(url) {
    try {
        const { data } = await axios.get(url);
        const nextPageToken = data.nextPageToken;
        const videoIds = data.items.map((video) => {
            return video.contentDetails.videoId;
        });
        return { videoIds, nextPageToken };
    } catch (e) {
        if (e.response) {
            const { code, message } = e.response.data.error;
            throw new Error(`StatusCode ${code}. Reason: ${message}`);
            console.log("Errow while fetching videos list.");
        } else {
            throw new Error(e.message);
        }
    }
}

async function getPlaylistTotalDuration(newPageToken) {
    try {
        // Step 1: Create the required query URL based on the newPageToken parameter
        let url = newPageToken
        ? `${playlistItemsURL}&playlistId=${extractedPlaylistIDId}&pageToken=${newPageToken}&key=${API_KEY}`
        : `${playlistItemsURL}&playlistId=${extractedPlaylistIDId}&key=${API_KEY}`;

        // Step 2: Start a local duration counter
        let totalDuration = 0;

        // Step 3: Get the video details based on the URL created in Step 1
        const { videoIds, nextPageToken } = await getVideoIdsForPageToken(url);
        const returnedVideoIds = [];
        returnedVideoIds.push(getDetailsForVideoIds(videoIds));
        const videoGroups = await Promise.all(returnedVideoIds);

        for (const group of videoGroups) {
            for (const video of group) {
                // Step 4: Get the durations in seconds and add it to the local duration counter created in Step 2
                totalDuration += returnedToSeconds(video.contentDetails.duration);
            }
        }

        // Step 5: Check if the return of Step 3 has a nextPageToken, if so do a recursive call to self with the new token
        if (nextPageToken) {
            totalDuration += await getPlaylistTotalDuration(nextPageToken);
        }

        // Step 6: Return the final value, which will propogate back in a recursive function
        return totalDuration;
    } catch (e) {
        throw new Error(e.message);
        console.log("Error while navigating between video pages.");
    }
}

Note: I have not actually ran the above code, but hopefully you get an idea of what needs to be done.


text:
Q: Dynamic property in planar vector in R I have to convert a code from MATLAB to R, but can't find the equivalent command in R. The MATLAB code is
if ~isfield(opt,'TolKKT'), opt.TolKKT = 0.001;

isfield in Matlab is used in order to determine if dynamic property exists in geographic or planar vector.
How can write it in R code? Assume that opt and TolKKT are defined in another of the code. My problem is the convertion of the isfield command


text:
Q: How to make a specific thread to sleep? I have 9 threads that do some calculations . I want to make one of them , or more , to go to sleep .
The code :
public class CalcArray
{
    private static int[] m_array = null;
    private static int sum = 0;
    private final static int MAX_VALUE = 80;

    /**
     *
     */
    public static void putValues()
    {
        for (int i = 0; i < MAX_VALUE ; i++)
        {
            m_array[i] = 1;
        }
    }

    /**
     *
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException
    {
        m_array = new int[80];
        putValues();
        int lowBound = 0;
        int upperBound = 9;

        Thready[] threadsArray = new Thready[10];
        for (int j = 0; j < 8 ; j++)
        {
            threadsArray[j] = new Thready(lowBound , upperBound);
            lowBound += 10;
            upperBound += 10;
        }

        // start the threads

        for (int q = 0; q < 8; q++)
        {
            if (q == 5)
            {
                // make the thread with #5 to take a nap
                // Thread.sleep(3000);
            }
            threadsArray[q].run();
        }

        System.out.println("Main Thread is done!");
        System.out.println(sum);

    }

    /**
     *
     * @author X
     *
     */
    public static class Thready implements Runnable
    {
        int lower = 0;
        int upper = 0;

        public Thready(int paramLower , int paramUpper)
        {
            lower = paramLower;
            upper = paramUpper;
        }

        @Override
        public void run()
        {
            synchronized(m_array)
            {
                for (int i = lower ; i <= upper ; i++)
                {
                    sum += m_array[i];
                }

                System.out.println("The current value is :" + sum);
            }

        }
    }

}

I want to make thread number #5 to take a nap . If I use Thread.sleep(3000); it would cause the Main Thread to go to sleep . So how can I tell thread #5 to go to sleep ?

A: Like this:
public class Test
{
    private static int[] m_array = null;
    private static int sum = 0;
    private final static int MAX_VALUE = 80;

    /**
     *
     */
    public static void putValues()
    {
        for (int i = 0; i < MAX_VALUE ; i++)
        {
            m_array[i] = 1;
        }
    }

    /**
     *
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException
    {
        m_array = new int[80];
        putValues();
        int lowBound = 0;
        int upperBound = 9;

        Thready[] threadsArray = new Thready[10];
        for (int j = 0; j < 8 ; j++)
        {
            threadsArray[j] = new Thready(j, lowBound , upperBound);
            lowBound += 10;
            upperBound += 10;
        }

        // start the threads

        for (int q = 0; q < 8; q++)
        {
            if (q == 5)
            {
                threadsArray[q].snooze(3000);
                // make the thread with #5 to take a nap
                // Thread.sleep(3000);
            }
            (new Thread(threadsArray[q])).start();
        }

        System.out.println("Main Thread is done!");
        System.out.println(sum);

    }

    /**
     *
     * @author X
     *
     */
    public static class Thready implements Runnable
    {
        int lower = 0;
        int upper = 0;
        int threadNum = 0;

        public Thready(int threadNum, int paramLower , int paramUpper)
        {
            this.threadNum = threadNum;
            lower = paramLower;
            upper = paramUpper;
        }

        public void snooze(long howlong) throws InterruptedException
        {
            System.out.println("Thread "+threadNum+": Taking a nap of "+howlong+" millis.");
            Thread.sleep(howlong);
        }

        @Override
        public void run()
        {
            synchronized(m_array)
            {
                for (int i = lower ; i <= upper ; i++)
                {
                    sum += m_array[i];
                }

                System.out.println("Thread "+threadNum+": The current value is :" + sum);
            }

        }
    }

}


text:
Q: mysql_query with $_SESSION or quotes I'm having some grief with this and would appreciate some help. I have tried the following:
$result = mysql_query("SELECT this FROM that WHERE tFirstName = $_SESSION['FirstName'] And tLastName = $_SESSION['LastName']");

but I get error "unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE".
I tried a number of ways with double and single quotes around the session variables but it always seems to find an error.
Eventually I gave up with that and set them before hand to $fn and $ln - then used that in the query:
$result = mysql_query("SELECT this FROM that WHERE tFirstName = '$fn' And tLastName = '$ln'");

This worked fine ... until I came across a user with the last name O'Reilly and now the single quote in their name breaks it!
Help! Any idea how I get around this?

A: You need to escape your variables before using them in an SQL query!  If you don't, bad things can happen (SQL Injection!1).  Since you're using mysql_, you can do this.
$fn = mysql_real_escape_string($_SESSION['FirstName']);
$ln = mysql_real_escape_string($_SESSION['LastName']);

$result = mysql_query("SELECT this FROM that WHERE tFirstName = '$fn' And tLastName = '$ln'");

This is exactly the reason to stop using mysql_ and switch to PDO (or mysqli)!  With those, you can use "prepared queries" and never have to worry about escaping again (it does it for you).  Please see this page: http://us2.php.net/manual/en/mysqlinfo.api.choosing.php
Once you switch, you want either $mysqli->prepare or $dbh->prepare.
1See this for info on SQL Injection: http://bobby-tables.com/

A: to escape the single quotes, use mysql_real_escape_string() before putting the variables into the query.
$result = mysql_query("SELECT this FROM that WHERE tFirstName = '".mysql_real_escape_string($fn)."' And tLastName = '".mysql_real_escape_string($ln)."'");

The correct syntax for the first query (without the escaping now...):
$result = mysql_query("SELECT this FROM that WHERE tFirstName = {$_SESSION['FirstName']} And tLastName = {$_SESSION['LastName']}");

A: You should use something like mysqli_real_escape_string on your inputs:
$fn = mysqli_real_escape_string($link,$_SESSION['FirstName']);
$ln = mysqli_real_escape_string($link,$_SESSION['LastName']);

where $link is the link identifier returned by mysqli_connect() or mysqli_init(). Then:
$result = mysqli_query($link, "SELECT this FROM that WHERE tFirstName = '$fn' And tLastName = '$ln'");

A: First off, I'll repeat myself once again and say this - you shouldn't be using PHP mysql_* functions as they are deprecated. Please consider switching to mysqli or PDO.
Now, the problem with your query is that you're not making sure that the user won't be able to inject malicious code into your database. The query won't work with the last name "O'Reilly" because of the apostrophe '. It's breaking the MySQL query.
Before inserting data into the database please use a functions like htmlspecialchars() and mysql_real_escape_string() (if you still insist on sticking with mysql_*)

A: You can solve this using mysql_real_escape_string or using PDO.
mysql_real_escape_string:
$str = mysql_real_escape_string($str);

PDO:
 // make a connection using mysql on PDO
 $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
 // make a query using params :fn and :ln
 $stmt = $dbh->prepare("SELECT this FROM that WHERE tFirstName = :fn And tLastName = :ln");
 // bind value to these params
 // when binding params, PDO automaticaly escape it and quote it, it's the most safe way to avoid SQL Injection.
 $stmt->bindParam(':fn', $fn);
 $stmt->bindParam(':ln', $ln);
 // execute the created statement
 $stmt->execute();
 // fetch data from statement
 $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
 // dump data
 sprintf("<pre>%s</pre>", printr($data,true));


text:
Q: Can't delete duplicate strings with shell commands I have a file called "1.txt" which contains the following:
111
111
222
777
1111
777

I'm trying to delete duplicate strings from it. Both sort -u 1.txt and sort 1.txt | uniq return this:
111
1111
222
777
777

Question:
Why is the string "777" still contained twice? How to remove the duplicate?

A: Probably, one of the "777" has a hidden character at the end.
Try checking the length of each line of your file with:
$ awk '{ print length($0); }' 1.txt

Compare the length of both "777" lines, they should be different in your file.

A: Try to use sed to delete non-digit char at the end of line, then use sort and uniq to delete duplicate string.
sed  's/[^0-9]\{0,\}$//' 1.txt | sort | uniq

where s : to replace matched string
      [^0-9] : to match non-digit char
      \{0,\} : zero or more pattern match
      $ : matches the end of lines


text:
Q: Local Unit Tests with SparseIntArray and others from android.util.* The Android Studio recommends me to use SparseIntArray instead of Hashmap<Integer, Integer> from standard Java.

SparseIntArray map integers to integers. Unlike a normal array of integers, there can be gaps in the indices. It is intended to be more memory efficient than using a HashMap to map Integers to Integers, both because it avoids auto-boxing keys and values and its data structure doesn't rely on an extra entry object for each mapping.

I think it really fits my code, but I cannot use any methods containing this class in Local Unit Tests. I always end with RuntimeException...
java.lang.RuntimeException: Method put in android.util.SparseIntArray not mocked. See http://g.co/androidstudio/not-mocked for details.
   at android.util.SparseIntArray.put(SparseIntArray.java)
   ...

Is there any way to import this method for local testing? I don't think it uses any Android's features. The unitTests.returnDefaultValues = true only returns default values for all calls. I know I can use Instrumented Unit Tests but it slows down the testing process.

A: You should use Robolectric framework if you want to test class with platform dependencies: http://robolectric.org/


text:
Q: Find a closed form for the following integral: I have to evalute a closed form for the following integral:
$$\int_0^1\left\{\frac{(-1)^{\lfloor\frac{1}{x}\rfloor}}{x}\right\}dx$$
where $\{x\}$ is the fractional part.
I thought of using a substitution $y=1/x$ this will lead me to:
$$\int_\infty^1\frac{\left\{y(-1)^{\lfloor y\rfloor}\right\}}{-y^2}dy$$
And now I have no idea how to proceed.

A:
Assignment:
Find a closed form for the following integral:
$$\mathscr{I}:=\int_0^1\left\{\left(-1\right)^{\left\lfloor\frac{1}{x}\right\rfloor}\cdot\frac{1}{x}\right\}\space\text{d}x\tag1$$
Where $\left\lfloor x\right\rfloor$ is the Floor function and $\left\{x\right\}$ is the Fractional part.

Well, let's first consider the substitution $\text{u}:=\frac{1}{x}$, this let's us rewrite $(1)$ as follows:
$$\mathscr{I}=\int_\infty^1-\frac{1}{\text{u}^2}\cdot\left\{\left(-1\right)^{\left\lfloor\text{u}\right\rfloor}\cdot\text{u}\right\}\space\text{du}=\int_1^\infty\frac{1}{\text{u}^2}\cdot\left\{\left(-1\right)^{\left\lfloor\text{u}\right\rfloor}\cdot\text{u}\right\}\space\text{du}\tag2$$
Now, we can break it into the sum of sub-integrals (because if $\text{p}\le\text{s}<\text{p}+1$ we get $\lfloor\text{s}\rfloor=\text{p}$). So:
$$\mathscr{I}=\sum_{\text{k}\ge1}\int_\text{k}^{\text{k}+1}\frac{1}{\text{u}^2}\cdot\left\{\left(-1\right)^{\left\lfloor\text{u}\right\rfloor}\cdot\text{u}\right\}\space\text{du}=\sum_{\text{k}\ge1}\int_\text{k}^{\text{k}+1}\frac{1}{\text{u}^2}\cdot\left\{\left(-1\right)^\text{k}\cdot\text{u}\right\}\space\text{du}\tag3$$
In order to deal with the term $(-1)^\text{k}$ it is not hard to see that we can split the sum further into the following two sums:
$$\mathscr{I}=\sum_{\text{n}\ge1}\int_{2\text{n}-1}^{2\text{n}}\frac{\left\{-\text{u}\right\}}{\text{u}^2}\space\text{du}+\sum_{\text{n}\ge1}\int_{2\text{n}}^{2\text{n}+1}\frac{\left\{\text{u}\right\}}{\text{u}^2}\space\text{du}\tag4$$
We can use the fact that $\left\{-\text{u}\right\}=1-\left\{\text{u}\right\}=1-\left(\text{u}-\lfloor\text{u}\rfloor\right)$:
$$\mathscr{I}=\sum_{\text{n}\ge1}\int_{2\text{n}-1}^{2\text{n}}\frac{1-\left(\text{u}-\lfloor\text{u}\rfloor\right)}{\text{u}^2}\space\text{du}+\sum_{\text{n}\ge1}\int_{2\text{n}}^{2\text{n}+1}\frac{\text{u}-\lfloor\text{u}\rfloor}{\text{u}^2}\space\text{du}\tag5$$
Now, we can use the fact that we are summing over the positive integers. So we can rewrite the floor function terms in the following way:
$$\mathscr{I}=\sum_{\text{n}\ge1}\int_{2\text{n}-1}^{2\text{n}}\frac{1-\left(\text{u}-\left(2\text{n}-1\right)\right)}{\text{u}^2}\space\text{du}+\sum_{\text{n}\ge1}\int_{2\text{n}}^{2\text{n}+1}\frac{\text{u}-2\text{n}}{\text{u}^2}\space\text{du}\tag6$$
You can evaluate the integrals and combining the sums (because they sum over the same interval), in order to get:
$$\mathscr{I}=\sum_{\text{n}\ge1}\left(\frac{1}{2\text{n}-1}-\frac{1}{2\text{n}+1}+\ln\left(\frac{\left(2\text{n}+1\right)\left(2\text{n}-1\right)}{\left(2\text{n}\right)^2}\right)\right)\tag7$$
Split the sum (because they are both absolutely convergent) and use the fact that a sum of $\ln$ functions can be written as a product of the argument:
$$\mathscr{I}=\underbrace{\sum_{\text{n}\ge1}\left(\frac{1}{2\text{n}-1}-\frac{1}{2\text{n}+1}\right)}_{=\space 1}+\ln\left(\underbrace{\prod_{\text{n}\ge1}\frac{\left(2\text{n}+1\right)\left(2\text{n}-1\right)}{\left(2\text{n}\right)^2}}_{=\space\frac{2}{\pi}}\right)=1+\ln\left(\frac{2}{\pi}\right)\tag8$$
Where $\frac{2}{\pi}$ is found using the Wallis product.


text:
Q: testing a custom data structures big-o complexity As an assignment, I implemented a custom data structure and a few test cases in order to make sure it works properly.
The code itself is not really needed for the question but you can assume it is some sort of a SortedList.
my problem is that I was also asked to test big-O complexity, e.g make sure put() is o(n) etc.
I am having allot of trouble understanding how can I write such a test.
one way that came to mind was to count the amount of iterations inside the put() method with a simple counter and then checking that it is equal to the size of the list, but that would require me to change the code of the list itself to count the exact number, and I would much rather doing it in a proper way, outside the class, holding only an instance of it.
any ideas anyone? I would really appreciate the help!

A: With unit testing you test the interface of a class, but the number of iterations is not part of the interface here. You could use a timer to check the runtime behaviour with different sizes. If it's O(n) there should be a linear dependency between time and n.

A: Get the current time at the start of the test, call the method that you're testing a large number of times, get the current time after, and check the difference to get the execution time. Repeat with a different size input, and check that the execution time follows the expected relationship.
For an o(n) algorithm, a suitable check would be that doubling the input size approximately doubles the execution time.