问:
How do resolve this exception in my Spring Application?
Here is my configuration file

```<code>import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
//activates spring MVC
@EnableWebMvc
//scans for our classes in the package
@ComponentScan("in.nit")
//loads properties file into Spring Container
@PropertySource("classpath:app.properties")

public class AppConfig {
@Autowired
Environment env;

//1.DataSource
@Bean
public DataSource ds() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(env.getProperty("db.driver"));
    ds.setUrl("db.url");
    ds.setUsername("db.user");
    ds.setPassword("db.password");
    return ds;
}
//session factory
@Bean
public LocalSessionFactoryBean sf() {
    LocalSessionFactoryBean sf = new LocalSessionFactoryBean();
    sf.setDataSource(ds());
    sf.setHibernateProperties(props());
//  sf.setAnnotatedClasses(annotatedClasses);
    sf.setPackagesToScan("in.nit.model");
    return  sf;
}
//Hibernate properties

public Properties props() {
    Properties props = new Properties();
    props.put("hibernate.dialect", env.getProperty("orm.dialect"));
    props.put("hibernate.format_sql",env.getProperty("orm.format_sql"));
    props.put("hibernate.show_sql",env.getProperty("orm.show_sql"));
    props.put("hibernate.hbm2ddl.auto", env.getProperty("orm.hb2ddl.auto"));
    return props;

}
//Tx Manager

@Bean
public HibernateTransactionManager tm() {
    HibernateTransactionManager tm = new HibernateTransactionManager();
    tm.setSessionFactory(sf().getObject());
    return tm;
}
//HibernateTemplate
@Bean
public HibernateTemplate ht() {
    HibernateTemplate ht = new HibernateTemplate();
    ht.setSessionFactory(sf().getObject());
    return ht;
}

//view resolver
@Bean
public InternalResourceViewResolver vr() {
    InternalResourceViewResolver vr = new InternalResourceViewResolver();
    vr.setSuffix(env.getProperty("mvc.suffix"));
    vr.setPrefix(env.getProperty("mvc.prefix"));
    return vr;
}
}
</code>```

And this is my Prperties file from which The config would read values

```<code>##Connection Properties##
db.driver = oracle.jdbc.driver.OracleDriver
db.url = jdbc:oracle:thin:@localhost:1521:ORCL.168.0.29
db.user = prem
db.password = rempe

##ORM PROPERTIES ##
orm.dialect = org.hibernate.dialect.OracleDialect
orm.show_sql = true
orm.format_sql = true
orm.hbm2ddl.auto = create

##MVC properties##
mvc.prefix = /WEB-INF/views/
mvc.suffix = .jsp
</code>```

and below is my WebApplicationInitializer file

```<code>import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AppInit extends AbstractAnnotationConfigDispatcherServletInitializer {

    //provivde root configuration classes to FrontController something like providing web.xml to ServletContainer
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] {AppConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        // TODO Auto-generated method stub
        return null;
    }

    //URL pattern
    @Override
    protected String[] getServletMappings() {
        return new String[] {"/"};
    }

}

</code>```

and on running the application in tomcat 9.0 webserver ,I get the following exception

```<code>WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sf' defined in AppConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method 'sf' threw exception; nested exception is java.lang.NullPointerException
Feb 15, 2020 7:09:54 PM org.springframework.web.context.ContextLoader initWebApplicationContext
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sf' defined in AppConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method 'sf' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:484)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:860)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:401)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:292)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4680)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5150)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:841)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:421)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:932)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:633)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:344)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:475)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method 'sf' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
    ... 45 more
Caused by: java.lang.NullPointerException
    at java.base/java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1011)
    at java.base/java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:1006)
    at java.base/java.util.Properties.put(Properties.java:1331)
    at AppConfig.props(AppConfig.java:57)
    at AppConfig.sf(AppConfig.java:45)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2.CGLIB$sf$4(<generated>)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2$$FastClassBySpringCGLIB$$69575c9b.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2.sf(<generated>)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 46 more

Feb 15, 2020 7:09:54 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class [org.springframework.web.context.ContextLoaderListener]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sf' defined in AppConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method 'sf' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:484)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:860)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:401)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:292)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4680)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5150)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:841)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:421)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:932)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:633)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:344)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:475)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method 'sf' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
    ... 45 more
Caused by: java.lang.NullPointerException
    at java.base/java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1011)
    at java.base/java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:1006)
    at java.base/java.util.Properties.put(Properties.java:1331)
    at AppConfig.props(AppConfig.java:57)
    at AppConfig.sf(AppConfig.java:45)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2.CGLIB$sf$4(<generated>)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2$$FastClassBySpringCGLIB$$69575c9b.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2.sf(<generated>)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 46 more
</code>```

Please Guide me how to resolve this issue and explain why is it occuring?

答:
you are getting null pointer exception because you tried to put null value in property. check props() method and find out whether you are getting not null values from the environment.

hint: issue is with property at line number 57

Body:
Here is my configuration file

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
//activates spring MVC
@EnableWebMvc
//scans for our classes in the package
@ComponentScan("in.nit")
//loads properties file into Spring Container
@PropertySource("classpath:app.properties")

public class AppConfig {
@Autowired
Environment env;

//1.DataSource
@Bean
public DataSource ds() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(env.getProperty("db.driver"));
    ds.setUrl("db.url");
    ds.setUsername("db.user");
    ds.setPassword("db.password");
    return ds;
}
//session factory
@Bean
public LocalSessionFactoryBean sf() {
    LocalSessionFactoryBean sf = new LocalSessionFactoryBean();
    sf.setDataSource(ds());
    sf.setHibernateProperties(props());
//  sf.setAnnotatedClasses(annotatedClasses);
    sf.setPackagesToScan("in.nit.model");
    return  sf;
}
//Hibernate properties

public Properties props() {
    Properties props = new Properties();
    props.put("hibernate.dialect", env.getProperty("orm.dialect"));
    props.put("hibernate.format_sql",env.getProperty("orm.format_sql"));
    props.put("hibernate.show_sql",env.getProperty("orm.show_sql"));
    props.put("hibernate.hbm2ddl.auto", env.getProperty("orm.hb2ddl.auto"));
    return props;

}
//Tx Manager

@Bean
public HibernateTransactionManager tm() {
    HibernateTransactionManager tm = new HibernateTransactionManager();
    tm.setSessionFactory(sf().getObject());
    return tm;
}
//HibernateTemplate
@Bean
public HibernateTemplate ht() {
    HibernateTemplate ht = new HibernateTemplate();
    ht.setSessionFactory(sf().getObject());
    return ht;
}

//view resolver
@Bean
public InternalResourceViewResolver vr() {
    InternalResourceViewResolver vr = new InternalResourceViewResolver();
    vr.setSuffix(env.getProperty("mvc.suffix"));
    vr.setPrefix(env.getProperty("mvc.prefix"));
    return vr;
}
}

And this is my Prperties file from which The config would read values

##Connection Properties##
db.driver = oracle.jdbc.driver.OracleDriver
db.url = jdbc:oracle:thin:@localhost:1521:ORCL.168.0.29
db.user = prem
db.password = rempe

##ORM PROPERTIES ##
orm.dialect = org.hibernate.dialect.OracleDialect
orm.show_sql = true
orm.format_sql = true
orm.hbm2ddl.auto = create

##MVC properties##
mvc.prefix = /WEB-INF/views/
mvc.suffix = .jsp

and below is my WebApplicationInitializer file

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AppInit extends AbstractAnnotationConfigDispatcherServletInitializer {

    //provivde root configuration classes to FrontController something like providing web.xml to ServletContainer
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] {AppConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        // TODO Auto-generated method stub
        return null;
    }

    //URL pattern
    @Override
    protected String[] getServletMappings() {
        return new String[] {"/"};
    }

}

and on running the application in tomcat 9.0 webserver ,I get the following exception

WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sf' defined in AppConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method 'sf' threw exception; nested exception is java.lang.NullPointerException
Feb 15, 2020 7:09:54 PM org.springframework.web.context.ContextLoader initWebApplicationContext
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sf' defined in AppConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method 'sf' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:484)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:860)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:401)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:292)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4680)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5150)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:841)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:421)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:932)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:633)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:344)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:475)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method 'sf' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
    ... 45 more
Caused by: java.lang.NullPointerException
    at java.base/java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1011)
    at java.base/java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:1006)
    at java.base/java.util.Properties.put(Properties.java:1331)
    at AppConfig.props(AppConfig.java:57)
    at AppConfig.sf(AppConfig.java:45)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2.CGLIB$sf$4(<generated>)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2$$FastClassBySpringCGLIB$$69575c9b.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2.sf(<generated>)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 46 more

Feb 15, 2020 7:09:54 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class [org.springframework.web.context.ContextLoaderListener]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sf' defined in AppConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method 'sf' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:484)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:860)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:401)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:292)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4680)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5150)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:841)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:421)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:932)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:633)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:344)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:475)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method 'sf' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
    ... 45 more
Caused by: java.lang.NullPointerException
    at java.base/java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1011)
    at java.base/java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:1006)
    at java.base/java.util.Properties.put(Properties.java:1331)
    at AppConfig.props(AppConfig.java:57)
    at AppConfig.sf(AppConfig.java:45)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2.CGLIB$sf$4(<generated>)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2$$FastClassBySpringCGLIB$$69575c9b.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2.sf(<generated>)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 46 more

Please Guide me how to resolve this issue and explain why is it occuring?


来源: stackexchange

问:
FLUTTER : any Solution to this Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'
Launching lib\main.dart on Android SDK built for x86 in debug mode...

FAILURE: Build failed with an exception.

What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.

Could not resolve all task dependencies for configuration ':app:debugCompileClasspath'.
  Could not resolve io.flutter:flutter_embedding_debug:1.0.0-a67792536ca236a971d0efbcfd7af4efb8f6c119.
   Required by:
       project :app
  Skipped due to earlier error
  Skipped due to earlier error
  Skipped due to earlier error
  Could not resolve io.flutter:x86_debug:1.0.0-a67792536ca236a971d0efbcfd7af4efb8f6c119.
   Required by:
       project :app
  Skipped due to earlier error
  Skipped due to earlier error
  Skipped due to earlier error
  Could not resolve io.flutter:x86_64_debug:1.0.0-a67792536ca236a971d0efbcfd7af4efb8f6c119.
   Required by:
       project :app
  Skipped due to earlier error
  Skipped due to earlier error
  Skipped due to earlier error

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 2m 35s
Gradle task assembleDebug failed with exit code 1
Exited (sigterm)

I recently install back my flutter after I reset my PC and this message keep poping up eventhough I just created new project, any solution to this would be helpful.thx

答:
from this github issue
seems like you need to make sure your dependencies are not conflicting /same versions.

You can update or lower your dependencies version if you changed any before this error occured, run flutter clean and finally flutter run

ContentLicense: CC BY-SA 4.0


问:
How to write a recursive function to search for a key in a binary tree using in-order traversal in C?
I am trying to write a recursive function that, given the root of a binary tree and a key, searches for the key using in-order traversal.  The function returns NULL if the node with the key isn't found; otherwise it returns the node containing the key.

What I'm having trouble with is returning the node that contains the key.  Every time I call the function and the key is in the binary tree, the function returns NULL.  It feels like the result keeps getting overwritten by the initialization in the first line in the function.

Here's the in-order search function:

```<code>typedef struct treeNode
{
    int data;
    struct treeNode *left, *right;
} TreeNode, *TreeNodePtr;

typedef struct
{
    TreeNodePtr root;
} BinaryTree;

TreeNodePtr inOrderKey(TreeNodePtr root, int key)
{
    TreeNodePtr node = NULL;

    if (root != NULL)
    {
        node = inOrderKey(root->left, key);
        if(key == root->data)
        {
           node = root;
           return node;
        }
        node = inOrderKey(root->right, key);
    }

    return node;
}
</code>```

Here's the main function:

```<code>int main()
{
    FILE * in = fopen("numbst.txt", "r");

    BinaryTree bst;
    bst.root = NULL;

    int num;

    fscanf(in, "%d", &num);
    while (num != 0)
    {
        if (bst.root == NULL)
            bst.root = newTreeNode(num);
        else
        {
            TreeNodePtr node = findOrInsert(bst, num);
        }
        fscanf(in, "%d", &num);
    }

    printf("\nThe in-order traversal is: ");
    inOrder(bst.root);
    printf("\nThe pre-order traversal is: ");
    preOrder(bst.root);

    TreeNodePtr keyNode;
    int count = 0;
    keyNode = inOrderKey(bst.root, 9);
    if (keyNode != NULL)
        count = 1;
    else
        count = 0;

    if (count == 1)
        printf("\n\n%d exists in the binary tree. In order traversal was used.\n", 9);
    else
        printf("\n\n%d doesn't exist in the binary tree. In order traversal was used.\n", 9);
        return 0;
}
</code>```

The in-order traversal of the binary tree I'm working with is: 1 2 3 4 5 7 9 21

The pre-order traversal of the binary tree is: 4 1 2 3 7 5 21 9

I'm testing the function using 9 and 31.

答:
The problem you have is that you insist in navigating the whole tree without checking if you found the key already.  In

```<code>TreeNodePtr inOrderKey(TreeNodePtr root, int key)
{
    /* don't declare a local you don't know
     * yet if you are going to use */

    /* better to check the opposite */
    if (root == NULL)
        return NULL;  /* no tree, nothing can be found */

    TreeNodePtr node = inOrderKey(root->left, key);

    if (node) return node; /* we found it in the left child */
    if(key == root->data) { /* check here */
        /* you found it in this node */
        return root;
    }

    /* last chance, right child :) */
    return inOrderKey(root->right, key);
}
</code>```

the verifications are made, so this should work (I've not tested it, as you didn't post a complete and verifiable example, my apologies for that)

Body:
I am trying to write a recursive function that, given the root of a binary tree and a key, searches for the key using in-order traversal.  The function returns NULL if the node with the key isn't found; otherwise it returns the node containing the key.

What I'm having trouble with is returning the node that contains the key.  Every time I call the function and the key is in the binary tree, the function returns NULL.  It feels like the result keeps getting overwritten by the initialization in the first line in the function.

Here's the in-order search function:

typedef struct treeNode
{
    int data;
    struct treeNode *left, *right;
} TreeNode, *TreeNodePtr;

typedef struct
{
    TreeNodePtr root;
} BinaryTree;

TreeNodePtr inOrderKey(TreeNodePtr root, int key)
{
    TreeNodePtr node = NULL;

    if (root != NULL)
    {
        node = inOrderKey(root->left, key);
        if(key == root->data)
        {
           node = root;
           return node;
        }
        node = inOrderKey(root->right, key);
    }

    return node;
}

Here's the main function:

int main()
{
    FILE * in = fopen("numbst.txt", "r");

    BinaryTree bst;
    bst.root = NULL;

    int num;

    fscanf(in, "%d", &num);
    while (num != 0)
    {
        if (bst.root == NULL)
            bst.root = newTreeNode(num);
        else
        {
            TreeNodePtr node = findOrInsert(bst, num);
        }
        fscanf(in, "%d", &num);
    }

    printf("\nThe in-order traversal is: ");
    inOrder(bst.root);
    printf("\nThe pre-order traversal is: ");
    preOrder(bst.root);

    TreeNodePtr keyNode;
    int count = 0;
    keyNode = inOrderKey(bst.root, 9);
    if (keyNode != NULL)
        count = 1;
    else
        count = 0;

    if (count == 1)
        printf("\n\n%d exists in the binary tree. In order traversal was used.\n", 9);
    else
        printf("\n\n%d doesn't exist in the binary tree. In order traversal was used.\n", 9);
        return 0;
}

The in-order traversal of the binary tree I'm working with is: 1 2 3 4 5 7 9 21

The pre-order traversal of the binary tree is: 4 1 2 3 7 5 21 9

I'm testing the function using 9 and 31.

Body:
The problem you have is that you insist in navigating the whole tree without checking if you found the key already.  In

TreeNodePtr inOrderKey(TreeNodePtr root, int key)
{
    /* don't declare a local you don't know
     * yet if you are going to use */

    /* better to check the opposite */
    if (root == NULL)
        return NULL;  /* no tree, nothing can be found */

    TreeNodePtr node = inOrderKey(root->left, key);

    if (node) return node; /* we found it in the left child */
    if(key == root->data) { /* check here */
        /* you found it in this node */
        return root;
    }

    /* last chance, right child :) */
    return inOrderKey(root->right, key);
}

the verifications are made, so this should work (I've not tested it, as you didn't post a complete and verifiable example, my apologies for that)


问:
Get property with lowest value from ArrayList of objects
I have ArrayList containing objects inside of it, every object in the ArrayList has a property and I wan't to see which of these objects has the lowest value on that property. Here's my code + Object structure</p>

```<code>class ServerInfo{

   public int playerCount = 0; //This is different per every object in the array list
}

List<ServerInfo> onlineServers = new ArrayList<ServerInfo> //From this array i want object with lowest 'playerCount' property value.
</code>```

答:
Do it as follows:

```<code>ServerInfo elemWithMin = onlineServers.get(0);
int min = onlineServers.get(0).playerCount;
for(int i = 1; i < onlineServers.size(); i++) {
    if(onlineServers.get(i).playerCount < min) {
        min = onlineServers.get(i).playerCount;
        elemWithMin=onlineServers.get(i);
    }
}
</code>```

At the end of this loop, elemWithMin will have the element with the minimum value of playerCount.

A quick test:

```<code>class Main {
    public static void main(String[] args) {
        List<ServerInfo> onlineServers = new ArrayList<ServerInfo>();
        ServerInfo si1 = new ServerInfo();
        ServerInfo si2 = new ServerInfo();
        ServerInfo si3 = new ServerInfo();
        si1.playerCount = 20;
        si2.playerCount = 10;
        si3.playerCount = 30;
        onlineServers.add(si1);
        onlineServers.add(si2);
        onlineServers.add(si3);
        ServerInfo elemWithMin = onlineServers.get(0);
        int min = onlineServers.get(0).playerCount;
        for (int i = 1; i < onlineServers.size(); i++) {
            if (onlineServers.get(i).playerCount < min) {
                min = onlineServers.get(i).playerCount;
                elemWithMin = onlineServers.get(i);
            }
        }
        System.out.println("The minimum value of payerCount: " + elemWithMin.playerCount);
    }
}
</code>```

Output:

```<code>The minimum value of payerCount: 10
</code>```

Body:
I have ArrayList containing objects inside of it, every object in the ArrayList has a property and I wan't to see which of these objects has the lowest value on that property. Here's my code + Object structure

class ServerInfo{

   public int playerCount = 0; //This is different per every object in the array list
}

List<ServerInfo> onlineServers = new ArrayList<ServerInfo> //From this array i want object with lowest 'playerCount' property value.

Body:
Do it as follows:

ServerInfo elemWithMin = onlineServers.get(0);
int min = onlineServers.get(0).playerCount;
for(int i = 1; i < onlineServers.size(); i++) {
    if(onlineServers.get(i).playerCount < min) {
        min = onlineServers.get(i).playerCount;
        elemWithMin=onlineServers.get(i);
    }
}

At the end of this loop, elemWithMin will have the element with the minimum value of playerCount.

A quick test:

class Main {
    public static void main(String[] args) {
        List<ServerInfo> onlineServers = new ArrayList<ServerInfo>();
        ServerInfo si1 = new ServerInfo();
        ServerInfo si2 = new ServerInfo();
        ServerInfo si3 = new ServerInfo();
        si1.playerCount = 20;
        si2.playerCount = 10;
        si3.playerCount = 30;
        onlineServers.add(si1);
        onlineServers.add(si2);
        onlineServers.add(si3);
        ServerInfo elemWithMin = onlineServers.get(0);
        int min = onlineServers.get(0).playerCount;
        for (int i = 1; i < onlineServers.size(); i++) {
            if (onlineServers.get(i).playerCount < min) {
                min = onlineServers.get(i).playerCount;
                elemWithMin = onlineServers.get(i);
            }
        }
        System.out.println("The minimum value of payerCount: " + elemWithMin.playerCount);
    }
}

Output:

The minimum value of payerCount: 10


问:
Can't see my EC2 instances on the management console?
I'm a beginner to AWS and servers in general

I logged into AWS on laptop 1 and set up an EC2 instance. Next day I logged into AWS console on laptop 2, then the instance was gone. So I set up another EC2 instance to play with. Then logging into the console using a third laptop 3 the day after that, I found my first instance but not the second...

The second instance is still running as I can access the IP..

Any idea why this is happening? It's really confusing and annoying

Thanks!

答:
The instance is running, but the console is set to a different region,

Just change the region, it will work

ContentLicense: CC BY-SA 3.0


问:
I'm having trouble with some fairly basic math functions in Xcode
Basically, the program has 5 textfields for numbers. I want a math function that totals all 5 textboxes, then multiplies by 1.39, then again by 1.12, but I can't get the textfields to add properly. It works so far if you only put a number in one of the textfields, but it gets a little confused when it comes to adding more than one textfield. Here's my code:

```<code>- (IBAction)calculate {
    float b = ([BCB.text floatValue]);
    float d = b+([MCD.text floatValue]);
    float f = b+d+([SF.text floatValue]);
    float w = b+d+f+([SW.text floatValue]);
    float a = b+d+f+w+([AP.text floatValue]);
    float p = 1.39f;
    float h = 1.12f;
    float t = a*p*h;

    Total.text = [ [NSString alloc] initWithFormat:@"%.2f", t];
}
</code>```

Bear in mind I'm 100% beginner when it comes to Xcode, and I've kind of Frankensteined this code together from various tutorials, and this might be completely wrong.

答:
You should add the value of each text field only once, e.g.:</p>

```<code>- (IBAction)calculate {
    float b = [BCB.text floatValue];
    float d = [MCD.text floatValue];
    float f = [SF.text floatValue];
    float w = [SW.text floatValue];
    float a = [AP.text floatValue];
    float p = 1.39f;
    float h = 1.12f;
    float t = (b+d+f+w+a)*p*h;

    Total.text = [ [NSString alloc] initWithFormat:@"%.2f", t];
}
</code>```

Body:
Basically, the program has 5 textfields for numbers. I want a math function that totals all 5 textboxes, then multiplies by 1.39, then again by 1.12, but I can't get the textfields to add properly. It works so far if you only put a number in one of the textfields, but it gets a little confused when it comes to adding more than one textfield. Here's my code:

- (IBAction)calculate {
    float b = ([BCB.text floatValue]);
    float d = b+([MCD.text floatValue]);
    float f = b+d+([SF.text floatValue]);
    float w = b+d+f+([SW.text floatValue]);
    float a = b+d+f+w+([AP.text floatValue]);
    float p = 1.39f;
    float h = 1.12f;
    float t = a*p*h;

    Total.text = [ [NSString alloc] initWithFormat:@"%.2f", t];
}

Bear in mind I'm 100% beginner when it comes to Xcode, and I've kind of Frankensteined this code together from various tutorials, and this might be completely wrong.

Body:
You should add the value of each text field only once, e.g.:

- (IBAction)calculate {
    float b = [BCB.text floatValue];
    float d = [MCD.text floatValue];
    float f = [SF.text floatValue];
    float w = [SW.text floatValue];
    float a = [AP.text floatValue];
    float p = 1.39f;
    float h = 1.12f;
    float t = (b+d+f+w+a)*p*h;

    Total.text = [ [NSString alloc] initWithFormat:@"%.2f", t];
}


问:
Route [blog.all_article] not defined
I want to go from home.blade.php to all_article.blade.php, but they tell me that such a route was not found. What am I doing wrong. Thanks in advance for your help.

blog/home.blade

```<code> <a href="{{route('blog.all_article')}}" class="btn btn-primary pull-right"><i class="fa fa-plus-square-o"></i> Add</a>
</code>```

BlogController

```<code>public function articlesAll_blade(){
   return view('blog.all_article',[
     'articles' => Article::orderBy('created_at', 'desc')->paginate(10),
      'footers' => System::all(),
   ]);
}
</code>```

web.php

```<code> Route::get('/', 'BlogController@articlesAll', function () {
     return view('blog.home');
 });

 Route::get('/all_article', 'BlogController@articlesAll_blade', function () {
     return view('blog.all_article');
 });
</code>```

答:
what you are missing is a route name, add a name to your route

```<code>Route::get('/all_article', 'BlogController@articlesAll_blade', function () {
     return view('blog.all_article');
 })->name('blog.all_article');// see the name part
</code>```

doc link https://laravel.com/docs/routing#named-routes

Title: Route [blog.all_article] not defined

Body:
I want to go from home.blade.php to all_article.blade.php, but they tell me that such a route was not found. What am I doing wrong. Thanks in advance for your help.

blog/home.blade

  Add

BlogController

public function articlesAll_blade(){
   return view('blog.all_article',[
     'articles' => Article::orderBy('created_at', 'desc')->paginate(10),
      'footers' => System::all(),
   ]);
}

web.php

 Route::get('/', 'BlogController@articlesAll', function () {
     return view('blog.home');
 });

 Route::get('/all_article', 'BlogController@articlesAll_blade', function () {
     return view('blog.all_article');
 });

Body:
what you are missing is a route name, add a name to your route

Route::get('/all_article', 'BlogController@articlesAll_blade', function () {
     return view('blog.all_article');
 })->name('blog.all_article');// see the name part

doc link https://laravel.com/docs/routing#named-routes


问:
In Keras, what exactly am I configuring when I create a stateful `LSTM` layer with N `units`?
The first arguments in a normal Dense layer is also units, and is the number of neurons/nodes in that layer. A standard LSTM unit however looks like the following:

(This is a reworked version of "Understanding LSTM Networks")

In Keras, when I create an LSTM object like this LSTM(units=N, ...), am I actually creating N of these LSTM units? Or is it the size of the "Neural Network" layers inside the LSTM unit, i.e., the W's in the formulas? Or is it something else?

For context, I'm working based on this example code.

The following is the documentation: https://keras.io/layers/recurrent/

It says:

units: Positive integer, dimensionality of the output space.

It makes me think it is the number of outputs from the Keras LSTM "layer" object. Meaning the next layer will have N inputs. Does that mean there actually exists N of these LSTM units in the LSTM layer, or maybe that that exactly one LSTM unit is run for N iterations outputting N of these h[t] values, from, say, h[t-N] up to h[t]?

If it only defines the number of outputs, does that mean the input still can be, say, just one, or do we have to manually create lagging input variables x[t-N] to x[t], one for each LSTM unit defined by the units=N argument?

As I'm writing this it occurs to me what the argument return_sequences does. If set to True all the N outputs are passed forward to the next layer, while if it is set to False it only passes the last h[t] output to the next layer. Am I right?

答: "Intuitively" just like a dense layer with 100 dim (Dense(100)) will have 100 neurons. Same way LSTM(100) will be a layer of 100 'smart neurons' where each neuron is the figure you mentioned and the output will be a vector of 100 dimensions</p>


问:
How do I export data that contains tabs and other arbitrary characters from Hive to disk?
For example:

```<code>hive -e "select '\t' as a, ',' as b, 1 as c" > output.txt
</code>```

The tabs are not escaped in the output file, even though they are used as a delimiter.

How can I ensure I can use a full ASCII map of characters when outputting data from Hive?

答:
Try this answer if that helps:</p>

```<code>select "\\t" as a, "\," as b
</code>```

Body:
For example:

hive -e "select '\t' as a, ',' as b, 1 as c" > output.txt

The tabs are not escaped in the output file, even though they are used as a delimiter.

How can I ensure I can use a full ASCII map of characters when outputting data from Hive?

Body:
Try this answer if that helps:

select "\\t" as a, "\," as b


问:
Javascript console.log() on HTC Android devices and adb logcat
I am developing the application in HTML which is calling the console.log() from Javascript to provide me logs during the development about what happens in the web page code.

Unfortunately when I use the adb logcat command to check logs I can see output from all other applications, but not the output from my JavaScript code. I can see even the log from web browser that the page is loaded, but not console.log() output from my JavaScript code executed in the web browser.

According to information on this page (http://developer.android.com/guide/webapps/debugging.html) it should work.

I am testing on HTC WildFire and HTC Desire HD.

Edited after more then 6 months

After some time and experience with different devices (phones, TVs, set top boxes, WebViews, UIWebViews...) my advice is to do the remote logging from JavaScript and not relying on the console.log() or other methods - see the nice trick with the image loading here.

Do not miss the presentation here
Hope this helps!
STeN

答:
I have been using three different HTC phones, almost exclusively, and have never had this issue.  Here are a few things to check:

Make sure USB debugging is enabled.

Make sure your Webview has a WebChromeClient set.  The browser used in Webview does not implement console.log().

It should be easy to see the output of adb logcat, but to make it easier, filter the output.

Turn on USB debugging:

Disconnect your device from your computer.

Go to Settings -> Applications -> Development -> Select "Enable USB Debugging"

Plugin to computer. (Make sure you have the correct drivers installed to use ADB - more info here: http://developer.android.com/guide/developing/device.html)

Set a WebChromeClient that overrides onConsoleMessage():

```<code>//Set the output prefix so you can filter adb logcat results later
public static final String TAG = "Your-Application-Name";

myWebView = (WebView) findViewById(R.id.webview);

//Not going to have much luck running JS without this:
myWebView.getSettings().setJavaScriptEnabled(true);

//Override onConsoleMessage() to output to the Log.
myWebView.setWebChromeClient(new WebChromeClient() {
    @Override
    public boolean onConsoleMessage(ConsoleMessage cm) {
        Log.d(TAG, cm.message() + " -- From line "
        + cm.lineNumber() + " of "
        + cm.sourceId() );
        return true;
    }
});
</code>```

More info on onConsoleMessage() here: http://developer.android.com/reference/android/webkit/WebChromeClient.html#onConsoleMessage(java.lang.String, int, java.lang.String)

More info on debugging in general here: http://developer.android.com/guide/webapps/debugging.html

Filter the output of adb logcat:

```<code>adb logcat tag-name:log-level *:S
</code>```

tag-name matches the string specified in Log.x
log-level matches the log level you indicated when calling Log.x <---

Example relating to code above:

```<code>adb logcat Your-Application-Name:D *:S
</code>```

This will show all d level logs for the matching tag, Your-Application-Name, and silence everything else.

More info on adb filtering here:
http://developer.android.com/guide/developing/tools/adb.html#logcat

Hope it helps!  I know it was a bit of summarizing of the other answers, but, the fact is, it takes all of the steps to make it work. :)

Body:
I have been using three different HTC phones, almost exclusively, and have never had this issue.  Here are a few things to check:

Make sure USB debugging is enabled.

Make sure your Webview has a WebChromeClient set.  The browser used in Webview does not implement console.log().

It should be easy to see the output of adb logcat, but to make it easier, filter the output.

Turn on USB debugging:

Disconnect your device from your computer.

Go to Settings -> Applications -> Development -> Select "Enable USB Debugging"

Plugin to computer. (Make sure you have the correct drivers installed to use ADB - more info here: http://developer.android.com/guide/developing/device.html)

Set a WebChromeClient that overrides onConsoleMessage():

//Set the output prefix so you can filter adb logcat results later
public static final String TAG = "Your-Application-Name";

myWebView = (WebView) findViewById(R.id.webview);

//Not going to have much luck running JS without this:
myWebView.getSettings().setJavaScriptEnabled(true);

//Override onConsoleMessage() to output to the Log.
myWebView.setWebChromeClient(new WebChromeClient() {
    @Override
    public boolean onConsoleMessage(ConsoleMessage cm) {
        Log.d(TAG, cm.message() + " -- From line "
        + cm.lineNumber() + " of "
        + cm.sourceId() );
        return true;
    }
});

More info on onConsoleMessage() here: http://developer.android.com/reference/android/webkit/WebChromeClient.html#onConsoleMessage(java.lang.String, int, java.lang.String)

More info on debugging in general here: http://developer.android.com/guide/webapps/debugging.html

Filter the output of adb logcat:

adb logcat tag-name:log-level *:S

tag-name matches the string specified in Log.x
log-level matches the log level you indicated when calling Log.x <---

Example relating to code above:

adb logcat Your-Application-Name:D *:S

This will show all d level logs for the matching tag, Your-Application-Name, and silence everything else.

More info on adb filtering here:
http://developer.android.com/guide/developing/tools/adb.html#logcat

Hope it helps!  I know it was a bit of summarizing of the other answers, but, the fact is, it takes all of the steps to make it work. :)


问:
RISC-V: S-format instructions table

I have this table of S-format instructions. Can you explain to me what imm[11:5] and funct3 are? I know funct indicates its size in bits and sometimes it is 000 or 010. I don't know exactly why it's there. Also, imm[11:5] is also 7-bits of all 0s.

Please help!

答:
imm[4:0] and imm[11:5] denote closed-intervals into the bit-representation of the immediate operand.

The S-format is used to encode store instructions, i.e.:

```<code>sX rs2, offset(r1)
</code>```

There are different types of store instructions, e.g. store-byte (sb), store-half-word (sh), store-word (sw), etc. The funct3 part is used to encode the type (i.e. 0b00 -> sb, 0b010 -> sw, 0b011 -> sd, etc.). This allows to just use one (major) opcode while still having multiple types of store instructions - instead of having to waste several (major) opcodes. IOW, funct3 encodes the minor opcode of the instruction.

The immediate operand encodes the offset. If you ask yourself why it's split like this - it allows to increase similarity of the remaining parts in the encoding with other instruction formats. For example, the opcode, rs1, and funct3 parts are located at the exact same place in the R-type, I-type and B-type instruction formats. The rs2 part placement is shared with the R-type and B-type instruction formats. Those similarities help to simplify the instruction decoder.

That means the offset is 12 bit wide and in pseudo-code:

```<code>offset = sign_ext(imm[11:5] << 5 | imm[4:0])
</code>```

See also the first figure in Section 2.6 (Load and Store Instruction) of the RISC-V Base specification (2019-06-08 ratified):

Title: RISC-V: S-format instructions table

Body:
imm[4:0] and imm[11:5] denote closed-intervals into the bit-representation of the immediate operand.

The S-format is used to encode store instructions, i.e.:

sX rs2, offset(r1)

There are different types of store instructions, e.g. store-byte (sb), store-half-word (sh), store-word (sw), etc. The funct3 part is used to encode the type (i.e. 0b00 -> sb, 0b010 -> sw, 0b011 -> sd, etc.). This allows to just use one (major) opcode while still having multiple types of store instructions - instead of having to waste several (major) opcodes. IOW, funct3 encodes the minor opcode of the instruction.

The immediate operand encodes the offset. If you ask yourself why it's split like this - it allows to increase similarity of the remaining parts in the encoding with other instruction formats. For example, the opcode, rs1, and funct3 parts are located at the exact same place in the R-type, I-type and B-type instruction formats. The rs2 part placement is shared with the R-type and B-type instruction formats. Those similarities help to simplify the instruction decoder.

That means the offset is 12 bit wide and in pseudo-code:

offset = sign_ext(imm[11:5] << 5 | imm[4:0])

See also the first figure in Section 2.6 (Load and Store Instruction) of the RISC-V Base specification (2019-06-08 ratified):


问:
Spring 3 MVC resources and tag <mvc:resources />
I'm having some problems with the  tag (Spring 3.0.5).
I want to add images to my web application, but it doesnt work.

Here is part of my beans config:

```<code><mvc:annotation-driven/>
<mvc:default-servlet-handler default-servlet-name="ideafactory"/>
<mvc:resources mapping="/resources/**" location="/, classpath:/WEB-INF/public-resources/" cache-period="10000" />
</code>```

Trying to add an image in a jsp file:

```<code><img src="<c:url value="/resources/logo.png" />" alt="Idea Factory" />
</code>```

First of all, I don't know really where to store the resources (src/main/resources/public-resources? src/main/webapp/WEB-INF/public-resources?).
Secondly, this config does not work, I can't see the image. What's wrong?

Thanks!

EDIT: the solution given here: Spring Tomcat and static resources and mvc:resources doesn't work either...
Added  without success.

EDIT 2: I tried to remove the mvc:resource tag and let only the mvc:default-servlet-handler> one, gave me infinite loop and stackoverflow... o_O (Serving static content with Spring 3)

答:
This worked for me

In JSP, to view the image

```<code><img src="${pageContext.request.contextPath}/resources/images/slide-are.jpg">
</code>```

In dispatcher-servlet.xml

```<code><mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />
</code>```

Body:
I'm having some problems with the  tag (Spring 3.0.5).
I want to add images to my web application, but it doesnt work.

Here is part of my beans config:

<mvc:annotation-driven/>
<mvc:default-servlet-handler default-servlet-name="ideafactory"/>
<mvc:resources mapping="/resources/**" location="/, classpath:/WEB-INF/public-resources/" cache-period="10000" />

Trying to add an image in a jsp file:

<img src="<c:url value="/resources/logo.png" />" alt="Idea Factory" />

First of all, I don't know really where to store the resources (src/main/resources/public-resources? src/main/webapp/WEB-INF/public-resources?).
Secondly, this config does not work, I can't see the image. What's wrong?

Thanks!

EDIT: the solution given here: Spring Tomcat and static resources and mvc:resources doesn't work either...
Added  without success.

EDIT 2: I tried to remove the mvc:resource tag and let only the mvc:default-servlet-handler> one, gave me infinite loop and stackoverflow... o_O (Serving static content with Spring 3)

Body:
This worked for me

In JSP, to view the image

<img src="${pageContext.request.contextPath}/resources/images/slide-are.jpg">

In dispatcher-servlet.xml

<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />


问:
Access VBA - Problems looping through fields in Access last record and exporting to Word bookmarks?
Thanks for looking at this.

I have a recordset with 60 fields and I want to export the last record for each field into a Microsoft Word file with 60 bookmarks called g1 to g60.

Of course I would like to loop through these but can't make it work.

Essentially what I want is this:

```<code>Dim wApp As Word.Application
Dim wDoc As Word.Document
Dim wDoct As Word.Document
Dim rs As DAO.Recordset
Dim rng As Word.Range
Dim intI As Integer
Dim fld As DAO.field

Set wApp = New Word.Application
Set wDoc = wApp.Documents.Open("C:\Users\Peter\Documents\testdoc.docm", ReadOnly:=False)
Set wDoct = wApp.Documents.Open("C:\Users\Peter\Documents\Trends.docx")
Set rs = CurrentDb.OpenRecordset("Overall")

Set rs = CurrentDb.OpenRecordset("Grades")

If Not rs.EOF Then rs.MoveLast

wDoc.Bookmarks("g1").Range.Text = Nz(rs!PlanQ, "")
wDoc.Bookmarks("g2").Range.Text = Nz(rs!PlanQMin, "")
wDoc.Bookmarks("g3").Range.Text = Nz(rs!PlanUnsat, "")
wDoc.Bookmarks("g4").Range.Text = Nz(rs!BriefQ, "")
wDoc.Bookmarks("g5").Range.Text = Nz(rs!BriefQmin, "")
wDoc.Bookmarks("g6").Range.Text = Nz(rs!BriefUnsat, "")
' and so on up to 60
wDoct.Save
wApp.Quit
</code>```

This works but needs to be looped of course - I tried this, but it errors out:

```<code>Dim wApp As Word.Application
Dim wDoc As Word.Document
Dim wDoct As Word.Document
Dim rs As DAO.Recordset
Dim rng As Word.Range
Dim intI As Integer
Dim fld As DAO.field

Set wApp = New Word.Application
Set wDoc = wApp.Documents.Open("C:\Users\Peter\Documents\testdoc.docm", ReadOnly:=False)
Set wDoct = wApp.Documents.Open("C:\Users\Peter\Documents\Trends.docx")
Set rs = CurrentDb.OpenRecordset("Overall")

Set rs = CurrentDb.OpenRecordset("Grades")

If Not rs.EOF Then rs.MoveLast

intI = 1

With rs
Do Until .EOF
For Each fld in rs.Fields
wDoc.Bookmarks("g" & "intI").Range.Text = Nz(rs!fld.Name, "")

Next fld
intI = intI + 1
loop
End With

wDoct.save
Wapp.quit
</code>```

Any ideas will be very much welcome, otherwise I have a lot of typing ahead of me. :-)

Thank you for your time!

Peter

This is the current code that fail like mentioned below:
UPDATE This is the exact copy paste.

```<code>Public Sub Looptest()

Dim wApp As Word.Application
Dim wDoc As Word.Document
Dim rs As DAO.Recordset
Dim index As Integer
Dim item As Variant

Set wApp = New Word.Application
Set wDoc = wApp.Documents.Open("C:\Users\Peter\Documents\testdoc.docm", ReadOnly:=False)

Set rs = CurrentDb.OpenRecordset("Grades")

If Not rs.EOF Then rs.MoveLast

For Each item In rs.Fields
    index = index + 1

    Dim bookmarkName As String
    bookmarkName = "g" & index

    Dim bookmarkValue As Variant
    bookmarkValue = Nz(rs(item.Name).Value, "")

    Debug.Print "Try set bookmark '" & bookmarkName & "' to '" & bookmarkValue & "' now."

    Dim bookmarkRange As Word.Range
    Set bookmarkRange = wDoc.Bookmarks(bookmarkName).Range

    bookmarkRange.Text = bookmarkValue

    Set bookmarkRange = Nothing
    Next item

wApp.DisplayAlerts = False
wDoc.SaveAs2 "C:\Users\Peter\Documents\" & rs!ID & "_gradesheet.docm"
wDoc.Close
wApp.Quit
</code>```

答:
This seems to be what you want:

Dim index As Integer
Dim item As Variant

For Each item In rs.Fields
    index = index + 1
    wDoc.Bookmarks("g" & index).Range.Text = Nz(rs(item.Name).Value, "")
Next item
```

<p>It iterates the fields of the recordset and fills the bookmarks like you seem to want it.</p>

<p>What exactly error did you receive?</p>

<p>You should also check your code again, there are some superfluous fragments in it.</p>

<h1>Update:</h1>

<p>You get this error as I understand:</p>

<blockquote>
  <p>5941: The requested member of the collection does not exist.</p>
</blockquote>

<p>Try this instead. It separates the functionality to single steps, enabling you to determine what the cause is:</p>

<ul>
<li>It builds the new bookmark name</li>
<li>It retrieves the value to set to the bookmark</li>
<li>It prints out which bookmark now will be set to which value</li>
<li>It gets a reference to the bookmark to be set</li>
<li>It sets the bookmarks value</li>
</ul>

<p>You should be able now to find out the reason for the error, by seeing which line of code breaks and what the values of the variables are.</p>

<pre class="lang-vb prettyprint-override"><code>    Dim index As Integer
    Dim item As Variant

    For Each item In rs.Fields
        If item.Name <> "ID" Then
            index = index + 1

            If index = 127 Then Exit For

            Dim bookmarkName As String
            bookmarkName = "g" & index

            Dim bookmarkValue As Variant
            bookmarkValue = Nz(rs(item.Name).Value, "")

            Debug.Print "Try set bookmark '" & bookmarkName & "' to '" & bookmarkValue & "' now."

            Dim bookmarkRange As Word.Range
            Set bookmarkRange = wDoc.Bookmarks(bookmarkName).Range

            bookmarkRange.Text = bookmarkValue

            Set bookmarkRange = Nothing
        End If
    Next item
</code>```

Body:
Thanks for looking at this.

I have a recordset with 60 fields and I want to export the last record for each field into a Microsoft Word file with 60 bookmarks called g1 to g60.

Of course I would like to loop through these but can't make it work.

Essentially what I want is this:

Dim wApp As Word.Application
Dim wDoc As Word.Document
Dim wDoct As Word.Document
Dim rs As DAO.Recordset
Dim rng As Word.Range
Dim intI As Integer
Dim fld As DAO.field

Set wApp = New Word.Application
Set wDoc = wApp.Documents.Open("C:\Users\Peter\Documents\testdoc.docm", ReadOnly:=False)
Set wDoct = wApp.Documents.Open("C:\Users\Peter\Documents\Trends.docx")
Set rs = CurrentDb.OpenRecordset("Overall")

Set rs = CurrentDb.OpenRecordset("Grades")

If Not rs.EOF Then rs.MoveLast

wDoc.Bookmarks("g1").Range.Text = Nz(rs!PlanQ, "")
wDoc.Bookmarks("g2").Range.Text = Nz(rs!PlanQMin, "")
wDoc.Bookmarks("g3").Range.Text = Nz(rs!PlanUnsat, "")
wDoc.Bookmarks("g4").Range.Text = Nz(rs!BriefQ, "")
wDoc.Bookmarks("g5").Range.Text = Nz(rs!BriefQmin, "")
wDoc.Bookmarks("g6").Range.Text = Nz(rs!BriefUnsat, "")
' and so on up to 60
wDoct.Save
wApp.Quit

This works but needs to be looped of course - I tried this, but it errors out:

Dim wApp As Word.Application
Dim wDoc As Word.Document
Dim wDoct As Word.Document
Dim rs As DAO.Recordset
Dim rng As Word.Range
Dim intI As Integer
Dim fld As DAO.field

Set wApp = New Word.Application
Set wDoc = wApp.Documents.Open("C:\Users\Peter\Documents\testdoc.docm", ReadOnly:=False)
Set wDoct = wApp.Documents.Open("C:\Users\Peter\Documents\Trends.docx")
Set rs = CurrentDb.OpenRecordset("Overall")

Set rs = CurrentDb.OpenRecordset("Grades")

If Not rs.EOF Then rs.MoveLast

intI = 1

With rs
Do Until .EOF
For Each fld in rs.Fields
wDoc.Bookmarks("g" & "intI").Range.Text = Nz(rs!fld.Name, "")

Next fld
intI = intI + 1
loop
End With

wDoct.save
Wapp.quit

Any ideas will be very much welcome, otherwise I have a lot of typing ahead of me. :-)

Thank you for your time!

Peter

This is the current code that fail like mentioned below:
UPDATE This is the exact copy paste.

Public Sub Looptest()

Dim wApp As Word.Application
Dim wDoc As Word.Document
Dim rs As DAO.Recordset
Dim index As Integer
Dim item As Variant

Set wApp = New Word.Application
Set wDoc = wApp.Documents.Open("C:\Users\Peter\Documents\testdoc.docm", ReadOnly:=False)

Set rs = CurrentDb.OpenRecordset("Grades")

If Not rs.EOF Then rs.MoveLast

For Each item In rs.Fields
    index = index + 1

    Dim bookmarkName As String
    bookmarkName = "g" & index

    Dim bookmarkValue As Variant
    bookmarkValue = Nz(rs(item.Name).Value, "")

    Debug.Print "Try set bookmark '" & bookmarkName & "' to '" & bookmarkValue & "' now."

    Dim bookmarkRange As Word.Range
    Set bookmarkRange = wDoc.Bookmarks(bookmarkName).Range

    bookmarkRange.Text = bookmarkValue

    Set bookmarkRange = Nothing
    Next item

wApp.DisplayAlerts = False
wDoc.SaveAs2 "C:\Users\Peter\Documents\" & rs!ID & "_gradesheet.docm"
wDoc.Close
wApp.Quit

Body:
This seems to be what you want:

Dim index As Integer
Dim item As Variant

For Each item In rs.Fields
    index = index + 1
    wDoc.Bookmarks("g" & index).Range.Text = Nz(rs(item.Name).Value, "")
Next item

It iterates the fields of the recordset and fills the bookmarks like you seem to want it.

What exactly error did you receive?

You should also check your code again, there are some superfluous fragments in it.

Update:

You get this error as I understand:

5941: The requested member of the collection does not exist.

Try this instead. It separates the functionality to single steps, enabling you to determine what the cause is:

It builds the new bookmark name

It retrieves the value to set to the bookmark

It prints out which bookmark now will be set to which value

It gets a reference to the bookmark to be set

It sets the bookmarks value

You should be able now to find out the reason for the error, by seeing which line of code breaks and what the values of the variables are.

    Dim index As Integer
    Dim item As Variant

    For Each item In rs.Fields
        If item.Name <> "ID" Then
            index = index + 1

            If index = 127 Then Exit For

            Dim bookmarkName As String
            bookmarkName = "g" & index

            Dim bookmarkValue As Variant
            bookmarkValue = Nz(rs(item.Name).Value, "")

            Debug.Print "Try set bookmark '" & bookmarkName & "' to '" & bookmarkValue & "' now."

            Dim bookmarkRange As Word.Range
            Set bookmarkRange = wDoc.Bookmarks(bookmarkName).Range

            bookmarkRange.Text = bookmarkValue

            Set bookmarkRange = Nothing
        End If
    Next item


问:
ER_ACCESS_DENIED_ERROR: When i try to connect to the database on remote server - Node.js
I have issue when i try to connect to the database on remote server.

My code:

```<code>const mysql = require('mysql');
const database = mysql.createPool({
    host: 'localhost',
    user: 'user',
    password: 'pass',
    database: 'db'
});

database.getConnection(function (err, connection) {
    if (!err) {
        console.log('Database is connected ...');
    } else {
        console.log('Error connecting database ...');
    }
});
</code>```

The credentials for connection in code is faked. With the right credentials  I have, I login successfully on phpMyAdmin on remote server, on datebase that I want to connect. Credentials is good.

When I run script, return this error:
view error

Also, when I input credentials for connection with my local database, everything work perfect.

答:
As pointed out by Luuk, you need to replace the localhost with the actual IP address of the remote database server and the port on which the database server is running.

For example -

```<code>const database = mysql.createPool({
    host: '123.234.121.234',
    port : '3306',
    user: 'user',
    password: 'pass',
    database: 'db'
});
</code>```

Also, make sure the port is whitelisted and can be accessed over the network. Heres a tiny little diagram for explanation.

Body:
I have issue when i try to connect to the database on remote server.

My code:

const mysql = require('mysql');
const database = mysql.createPool({
    host: 'localhost',
    user: 'user',
    password: 'pass',
    database: 'db'
});

database.getConnection(function (err, connection) {
    if (!err) {
        console.log('Database is connected ...');
    } else {
        console.log('Error connecting database ...');
    }
});

The credentials for connection in code is faked. With the right credentials  I have, I login successfully on phpMyAdmin on remote server, on datebase that I want to connect. Credentials is good.

When I run script, return this error:
view error

Also, when I input credentials for connection with my local database, everything work perfect.

Body:
As pointed out by Luuk, you need to replace the localhost with the actual IP address of the remote database server and the port on which the database server is running.

For example -

const database = mysql.createPool({
    host: '123.234.121.234',
    port : '3306',
    user: 'user',
    password: 'pass',
    database: 'db'
});

Also, make sure the port is whitelisted and can be accessed over the network. Heres a tiny little diagram for explanation.


问:
Laravel - Eloquent Relationship not working One to Many relationship
I have two models with One-to-Many relationship. I want to display data with relationship in blade.

Products Table

```<code>Table name = Products
PrimaryKey = pro_id
ForeignKey = cat_id
</code>```

Categories Table

```<code>Table name = categories
PrimaryKey = cat_id
</code>```

Products Model Code

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class productsModel extends Model
{
    //code...
    protected $table      = 'products';
    protected $primaryKey = 'pro_id';

    // Every Products Belongs To One Category

    public function category()
    {
        # code...
        return $this->belongsTo('APP\abcModel','cat_id');
    }
}
</code>```

Categories Model Code

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class categoryModel extends Model
{
    //code...
    protected $table      = 'categories';
    protected $primaryKey = 'cat_id';

    // One Category Has Many Products

    public function products()
    {
        # code...
        return $this->hasMany('App\productsModel','cat_id','pro_id');
    }
}
</code>```

Controller Code

namespace App\Http\Controllers;

```<code>use Illuminate\Http\Request;
use App\productsModel;
class productsController extends Controller
{
    //code...
    public function products($category_id='')
    {
        # code...
        $data["products"] = productsModel::where
                            ('cat_id',$category_id)
                            ->get();
        $data["categories"] = productsModel::where
                            ('cat_id',$category_id)->first()->category;
        echo "```";
        print_r($data);
        echo "```";
    }
}
</code>```

ERROR:
Symfony\Component\Debug\Exception\FatalThrowableError
Class 'APP\categoryModel' not found

答:
```<code>public function category()
{
    return $this->belongsTo(abcModel::class,'cat_id');
}
</code>```

<hr>

```<code>public function products()
    {
        return $this->hasMany(productsModel::class,'cat_id');
    }
</code>```

Body:
I have two models with One-to-Many relationship. I want to display data with relationship in blade.

Products Table

Table name = Products
PrimaryKey = pro_id
ForeignKey = cat_id

Categories Table

Table name = categories
PrimaryKey = cat_id

Products Model Code

namespace App;

use Illuminate\Database\Eloquent\Model;

class productsModel extends Model
{
    //code...
    protected $table      = 'products';
    protected $primaryKey = 'pro_id';

    // Every Products Belongs To One Category

    public function category()
    {
        # code...
        return $this->belongsTo('APP\abcModel','cat_id');
    }
}

Categories Model Code

namespace App;

use Illuminate\Database\Eloquent\Model;

class categoryModel extends Model
{
    //code...
    protected $table      = 'categories';
    protected $primaryKey = 'cat_id';

    // One Category Has Many Products

    public function products()
    {
        # code...
        return $this->hasMany('App\productsModel','cat_id','pro_id');
    }
}

Controller Code

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\productsModel;
class productsController extends Controller
{
    //code...
    public function products($category_id='')
    {
        # code...
        $data["products"] = productsModel::where
                            ('cat_id',$category_id)
                            ->get();
        $data["categories"] = productsModel::where
                            ('cat_id',$category_id)->first()->category;
        echo "
";
        print_r($data);
        echo "
";
    }
}

ERROR:
Symfony\Component\Debug\Exception\FatalThrowableError
Class 'APP\categoryModel' not found

Body:
public function category()
{
    return $this->belongsTo(abcModel::class,'cat_id');
}

public function products()
    {
        return $this->hasMany(productsModel::class,'cat_id');
    }


问:
round to higher multiple of 5
i am trying to round values to it's higher multiple of 5
For example:</p>

```<code>df
values    rounded_values (expected column)
    10                10
    11                15
    13                15
    22                25
    21                25
    34                35
    35                35
</code>```

Title: round to higher multiple of 5

Body:
i am trying to round values to it's higher multiple of 5
For example:

df
values    rounded_values (expected column)
    10                10
    11                15
    13                15
    22                25
    21                25
    34                35
    35                35

Body:
Try:

df["rounded_values"] = ((df.values+4)//5)*5
print(df)
   values  rounded_values
0      10              10
1      11              15
2      13              15
3      22              25
4      21              25
5      34              35
6      35              35


问:
js-tree. The input field after choosing a context menu not appear
After selecting create/rename/etc, the input field should've appeared on any node.

You can right click on any node. The context menu should appear

Root node 1

Child node 1

Child node 2

Root node 2

  <button>demo button</button>
```

this is the reproduction:
https://codepen.io/dhika345/pen/PoqPrgo

答: Didn't know there is check_callback property. Added to the core property solves it</p>

Body:
After selecting create/rename/etc, the input field should've appeared on any node.

You can right click on any node. The context menu should appear

Root node 1

Child node 1

Child node 2

Root node 2

  <button>demo button</button>

this is the reproduction:
https://codepen.io/dhika345/pen/PoqPrgo


答:
Use mod:

```<code>def round_to5(x):
    if x%5 == 0:
        return x
    else:
        return x + (5 - x%5)

df['round_values'] = df['values'].apply(lambda x: round_to5(x))
</code>```

Output is:

```<code>  values    round_values
0   10          10
1   12          15
2   24          25
3   27          30
</code>```

Title: round to higher multiple of 5

Body:
Use mod:

def round_to5(x):
    if x%5 == 0:
        return x
    else:
        return x + (5 - x%5)

df['round_values'] = df['values'].apply(lambda x: round_to5(x))

Output is:

  values    round_values
0   10          10
1   12          15
2   24          25
3   27          30


问:
adding more Values in tow Textinput Dynamic Arrays and getting the Sum in Label in the same screen,
I am still a beginner in Kivy and have this Issue !
the User has to write different values in the first text input "First Textinput Values Box" and dot "." between each value, e.g. 12.32.3
if He press "Enter", he get the possibility to create a new box, "Second Textinput values box"
and then he can continue to write the values in the 2nd box,and dot"." between each value e.g. two values 1.2
then He can press Button "Result", He get the sum in the same Screen in 3 different labels.
The Label are : first value from the first box "12" plus first value from the second box "1"
second value from the first box "32" plus second value from the second box "2"
third value from the first box "3" plus third value from the second box "0"
can you please help me how can i make this Dynamic Array in the Box ?
Thanks

答:
I'm not totally sure what you'r asking for exactly. Do you want something like this?</p>

```<code>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.properties import ObjectProperty, StringProperty
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout

Builder.load_string('''
<BestWindow>:
    inpt_one: inpt_one
    inpt_two: inpt_two
    result_layout: result_layout
    BoxLayout:
        orientation:"vertical"
        TextInput:
            id: inpt_one
        TextInput:
            id: inpt_two
        Button:
            text: "Add them up!"
            on_press: root.calculate()
        BoxLayout:
            id: result_layout
            orientation: "horizontal"

''')

class BestWindow(BoxLayout):
    my_result = StringProperty("")
    inpt_one = ObjectProperty(None)
    result_layout = ObjectProperty(None)
    def __init__(self, **kwargs):
        super(BestWindow, self).__init__(**kwargs)

    def calculate(self):
        self.result_layout.clear_widgets()
        nums_one = self.inpt_one.text.strip().split(".")
        nums_two = self.inpt_two.text.strip().split(".")
        if(len(nums_one) < len(nums_two)):
            for _ in range(len(nums_two)-len(nums_one)):
                nums_one.append(0)
        elif(len(nums_two) < len(nums_one)):
            for _ in range(len(nums_one)-len(nums_two)):
                nums_two.append(0)
        result = [int(x) + int(y) for x,y in zip(nums_one, nums_two)]

        for res in result:
            self.result_layout.add_widget(Label(text=str(res)))
        self.inpt_one.text = ''
        self.inpt_two.text = ''

class TestApp(App):
    def build(self):
        return BestWindow()

if __name__ == "__main__":
    TestApp().run()
</code>```

Body:
I'm not totally sure what you'r asking for exactly. Do you want something like this?

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.properties import ObjectProperty, StringProperty
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout

Builder.load_string('''
<BestWindow>:
    inpt_one: inpt_one
    inpt_two: inpt_two
    result_layout: result_layout
    BoxLayout:
        orientation:"vertical"
        TextInput:
            id: inpt_one
        TextInput:
            id: inpt_two
        Button:
            text: "Add them up!"
            on_press: root.calculate()
        BoxLayout:
            id: result_layout
            orientation: "horizontal"

''')

class BestWindow(BoxLayout):
    my_result = StringProperty("")
    inpt_one = ObjectProperty(None)
    result_layout = ObjectProperty(None)
    def __init__(self, **kwargs):
        super(BestWindow, self).__init__(**kwargs)

    def calculate(self):
        self.result_layout.clear_widgets()
        nums_one = self.inpt_one.text.strip().split(".")
        nums_two = self.inpt_two.text.strip().split(".")
        if(len(nums_one) < len(nums_two)):
            for _ in range(len(nums_two)-len(nums_one)):
                nums_one.append(0)
        elif(len(nums_two) < len(nums_one)):
            for _ in range(len(nums_one)-len(nums_two)):
                nums_two.append(0)
        result = [int(x) + int(y) for x,y in zip(nums_one, nums_two)]

        for res in result:
            self.result_layout.add_widget(Label(text=str(res)))
        self.inpt_one.text = ''
        self.inpt_two.text = ''

class TestApp(App):
    def build(self):
        return BestWindow()

if __name__ == "__main__":
    TestApp().run()


问:
Make label snap to the right edge of another label
I have a variable length title label in my view, and i would like a second label representing a count to be immediately to it's right.

The reason I'd like to do 2 labels is that I'd like the title to be truncated past a certain length, and the count to be visible after the ellipsis.

Is this approach the right way to do this? Or should i just build a single string based on title length?

Thanks

答: I would just use one label and truncate the string in my code. Its just one less IBOutlet you have to deal with and it will also make it easier if you ever want to change the length of the string in the future.</p>


答:
The underlying container of a Pandas column is a numpy array, so you could just use numpy here:</p>

```<code>import numpy as np

df['rounded_values'] = np.round_((np.ceil(df['values']/5)*5)).astype(int)
</code>```

Title: round to higher multiple of 5

Body:
The underlying container of a Pandas column is a numpy array, so you could just use numpy here:

import numpy as np

df['rounded_values'] = np.round_((np.ceil(df['values']/5)*5)).astype(int)


问:
Hudson : Builds Taking Longer time than What it takes by running it Locally
I found a unusual behavior on Hudson.
The Hudson jobs take around 25 minutes , where as when I run the same job locally, it takes 9 minutes.
What I'm missing here?

I increased the JAVA_OPTS, MAVEN_OPTS and even gave the server more memory to start with.
The machine has 12 Gigs of memory.

-Xrs -Xms1024m -Xmx1024m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle
  -jar "%BASE%\hudson.war" --httpPort=9090 --ajp13Port=9099

MAVEN_OPTS:

C:>echo %MAVEN_OPTS%
  -Xmx1024M -XX:MaxPermSize=1024m

JAVA_OPTS:

C:>echo %JAVA_OPTS%
  -server -Xms1024m -Xmx1024m

Still the build takes 25 minutes.

答:
Comparing a local build on one system to the time it takes hudson to complete a build on a completely different system doesn't necessarily indicate any problems (maybe your local machine is a better machine than your build server?)

On your hudson server (maybe via SSH) run the mvn build and see how long it takes to run.

Then run the same build via hudson on that same system and see how long it takes to run.

Then you'd not be comparing two different machines.

Also, your hudson build could be doing a lot more than your normal build - for instance if you are asking it to start with a clean repository before the build it will be doing a whole lot of downloading for each build that your local machine wont have to do - especially if you don't have a cached maven repository server running on your local network.


问:
How to load initial data in H2 when using flyway on spring boot application?
I'm creating a spring boot application using Flyway to migration and want to use a memory database for development profile, but the problem is that data is lost every time I restart application. So I need to insert some data when my application start in development profile. I tried to put a file called data.sql on src/main/resource to spring load it when application starts but it doesnt work (It didnt run the script). I tried to put INIT=runscript from 'classpath:data.sql' in the h2 url but it tries to run it before Flyway migration execution so the tables doesnt exist yet. Can anyone give me an other way to do it?

My application.yml:

```<code>spring:
  datasource:
    url: jdbc:h2:mem:testdb;IFEXISTS=FALSE
    username: sa
    password:
    driver-class-name: org.h2.Driver
  jpa:
    show-sql: true
    hibernate:
      ddl-auto: none
    properties:
      hibernate:
        dialect: org.hibernate.dialect.H2Dialect
  flyway:
    enabled: true
</code>```

答:
Per documentation ,  a profile-specific customised flyway spring.flyway.locations can be configured. The profile-specific scripts runs when that profile is active . So a dev profile configured will work on this requirement.

The initialisation script can be placed as part of migration folder which will run and populate the db.

An example can be found here

Body:
I'm creating a spring boot application using Flyway to migration and want to use a memory database for development profile, but the problem is that data is lost every time I restart application. So I need to insert some data when my application start in development profile. I tried to put a file called data.sql on src/main/resource to spring load it when application starts but it doesnt work (It didnt run the script). I tried to put INIT=runscript from 'classpath:data.sql' in the h2 url but it tries to run it before Flyway migration execution so the tables doesnt exist yet. Can anyone give me an other way to do it?

My application.yml:

spring:
  datasource:
    url: jdbc:h2:mem:testdb;IFEXISTS=FALSE
    username: sa
    password:
    driver-class-name: org.h2.Driver
  jpa:
    show-sql: true
    hibernate:
      ddl-auto: none
    properties:
      hibernate:
        dialect: org.hibernate.dialect.H2Dialect
  flyway:
    enabled: true