问:
Spring Boot JPA multiple datasource error
I wanted to connect my spring boot app to 2 databases . So according to a tutorial i created 2 config classes.

Config Class 1

```<code>@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:database-configs.properties" })
@EnableJpaRepositories(
        basePackages = {"com.dialog.pod.ideabiz_admin.data_access_objects"},
        entityManagerFactoryRef = "adminEntityManagerFactory",
        transactionManagerRef = "adminTransactionManager")
public class IdeabizAdminConfig {

    @Autowired
    private Environment env;

    @Bean
    PlatformTransactionManager adminTransactionManager() {
        return new JpaTransactionManager(adminEntityManagerFactory().getObject());
    }

    @Bean
    LocalContainerEntityManagerFactoryBean adminEntityManagerFactory() {

        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
       // jpaVendorAdapter.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();

        factoryBean.setDataSource(adminDataSource());
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        factoryBean.setPackagesToScan("com.dialog.pod.ideabiz_admin.models");
        factoryBean.setJpaPropertyMap(jpaProperties());
        factoryBean.setPersistenceUnitName("adminDataSource");
        return factoryBean;
    }

    @Bean
    DataSource adminDataSource() {

        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("admin.jdbc.driverClassName"));
        dataSource.setUrl(env.getProperty("admin.jdbc.url"));
        dataSource.setUsername(env.getProperty("admin.jdbc.username"));
        dataSource.setPassword(env.getProperty("admin.jdbc.password"));

        return dataSource;
    }

    private Map<String, Object> jpaProperties() {
        Map<String, Object> props = new HashMap<>();
        props.put("hibernate.implicit_naming_strategy","org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl");
        props.put("hibernate.physical_naming_strategy","com.dialog.pod.PhysicalNamingStrategyImpl");
        return props;
    }

}
</code>```

Config Class 2

```<code>@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:database-configs.properties" })
@EnableJpaRepositories(
        basePackages = {"com.dialog.pod.ideabiz_log_summary.data_access_objects"},
        entityManagerFactoryRef = "sumLogEntityManagerFactory",
        transactionManagerRef = "sumLogTransactionManager")
public class IdeabizLogSummaryConfig {

    @Autowired
    private Environment env;

    @Bean
    PlatformTransactionManager sumLogTransactionManager() {
        return new JpaTransactionManager(sumLogEntityManagerFactory().getObject());
    }

    @Bean
    LocalContainerEntityManagerFactoryBean sumLogEntityManagerFactory() {

        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
       // jpaVendorAdapter.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();

        factoryBean.setDataSource(adminDataSource());
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        factoryBean.setPackagesToScan("com.dialog.pod.ideabiz_log_summary.models");
        factoryBean.setJpaPropertyMap(jpaProperties());
        factoryBean.setPersistenceUnitName("sumLogDataSource");
        return factoryBean;
    }

    @Bean
    DataSource adminDataSource() {

        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("sumlog.jdbc.driverClassName"));
        dataSource.setUrl(env.getProperty("sumlog.jdbc.url"));
        dataSource.setUsername(env.getProperty("sumlog.jdbc.username"));
        dataSource.setPassword(env.getProperty("sumlog.jdbc.password"));

        return dataSource;
    }

    private Map<String, Object> jpaProperties() {
        Map<String, Object> props = new HashMap<>();
        props.put("hibernate.implicit_naming_strategy","org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl");
        props.put("hibernate.physical_naming_strategy","com.dialog.pod.PhysicalNamingStrategyImpl");
        return props;
    }

}
</code>```

Application Class

```<code>@SpringBootApplication
@EnableAutoConfiguration (exclude = {  DataSourceAutoConfiguration.class })
@Configuration
@ComponentScan
public class PodApiApplication {

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

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/").allowedOrigins("*");
            }
        };
    }

}
</code>```

When i try to run the app i get following error.

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Method requestMappingHandlerMapping in org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration required a single bean, but 2 were found:
    - adminEntityManagerFactory: defined by method 'adminEntityManagerFactory' in class path resource [com/dialog/pod/ideabiz_admin/IdeabizAdminConfig.class]
    - sumLogEntityManagerFactory: defined by method 'sumLogEntityManagerFactory' in class path resource [com/dialog/pod/ideabiz_log_summary/IdeabizLogSummaryConfig.class]

Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

Process finished with exit code 1
</code>```

I put @Primary to the first config class(according to another tutorial). When i do that datasource in the first config class works. Problem is when i do this first datasource also applied to all the jparepositories.

I'm new to Spring boot. I have been trying to solve this problem for over 5 hours :( . Thanks in advance for any help you are able to provide.

Full Log

```<code>2017-01-27 00:52:39.713  INFO 6704 --- [           main] com.dialog.pod.PodApiApplication         : Starting PodApiApplication on DESKTOP-4B89ITN with PID 6704 (started by y2ksh in H:\Spring MVC Workspace\platform-overview-dashboard\PODApi)
2017-01-27 00:52:39.718  INFO 6704 --- [           main] com.dialog.pod.PodApiApplication         : No active profile set, falling back to default profiles: default
2017-01-27 00:52:39.938  INFO 6704 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6e171cd7: startup date [Fri Jan 27 00:52:39 IST 2017]; root of context hierarchy
2017-01-27 00:52:41.712  INFO 6704 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'adminDataSource' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=ideabizAdminConfig; factoryMethodName=adminDataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/dialog/pod/ideabiz_admin/IdeabizAdminConfig.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=ideabizLogSummaryConfig; factoryMethodName=adminDataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/dialog/pod/ideabiz_log_summary/IdeabizLogSummaryConfig.class]]
2017-01-27 00:52:42.804  INFO 6704 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$3cc0fc3] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-01-27 00:52:43.594  INFO 6704 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8081 (http)
2017-01-27 00:52:43.609  INFO 6704 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2017-01-27 00:52:43.609  INFO 6704 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.6
2017-01-27 00:52:43.810  INFO 6704 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-01-27 00:52:43.810  INFO 6704 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3891 ms
2017-01-27 00:52:44.247  INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-01-27 00:52:44.253  INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'metricFilter' to: [/*]
2017-01-27 00:52:44.254  INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-01-27 00:52:44.254  INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-01-27 00:52:44.254  INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-01-27 00:52:44.254  INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-01-27 00:52:44.255  INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'webRequestLoggingFilter' to: [/*]
2017-01-27 00:52:44.255  INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'applicationContextIdFilter' to: [/*]
2017-01-27 00:52:44.367  INFO 6704 --- [           main] o.s.j.d.DriverManagerDataSource          : Loaded JDBC driver: com.mysql.jdbc.Driver
2017-01-27 00:52:44.403  INFO 6704 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'adminDataSource'
2017-01-27 00:52:44.435  INFO 6704 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: adminDataSource
    ...]
2017-01-27 00:52:44.634  INFO 6704 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.0.11.Final}
2017-01-27 00:52:44.636  INFO 6704 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2017-01-27 00:52:44.641  INFO 6704 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2017-01-27 00:52:44.725  INFO 6704 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-01-27 00:52:45.302  INFO 6704 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-01-27 00:52:46.178  INFO 6704 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'adminDataSource'
2017-01-27 00:52:46.189  INFO 6704 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'sumLogDataSource'
2017-01-27 00:52:46.190  INFO 6704 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: sumLogDataSource
    ...]
2017-01-27 00:52:46.228  INFO 6704 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-01-27 00:52:46.291  INFO 6704 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'sumLogDataSource'
2017-01-27 00:52:46.695  INFO 6704 --- [           main] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
2017-01-27 00:52:46.947  INFO 6704 --- [           main] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
2017-01-27 00:52:47.496  INFO 6704 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6e171cd7: startup date [Fri Jan 27 00:52:39 IST 2017]; root of context hierarchy
2017-01-27 00:52:47.560  WARN 6704 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping]: Factory method 'requestMappingHandlerMapping' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'openEntityManagerInViewInterceptor' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration$JpaWebConfiguration$JpaWebMvcConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManagerFactory' available: expected single matching bean but found 2: adminEntityManagerFactory,sumLogEntityManagerFactory
2017-01-27 00:52:47.562  INFO 6704 --- [           main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'sumLogDataSource'
2017-01-27 00:52:47.563  INFO 6704 --- [           main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'adminDataSource'
2017-01-27 00:52:47.566  INFO 6704 --- [           main] o.apache.catalina.core.StandardService   : Stopping service Tomcat
2017-01-27 00:52:47.586  INFO 6704 --- [           main] utoConfigurationReportLoggingInitializer :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-01-27 00:52:47.592 ERROR 6704 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Method requestMappingHandlerMapping in org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration required a single bean, but 2 were found:
    - adminEntityManagerFactory: defined by method 'adminEntityManagerFactory' in class path resource [com/dialog/pod/ideabiz_admin/IdeabizAdminConfig.class]
    - sumLogEntityManagerFactory: defined by method 'sumLogEntityManagerFactory' in class path resource [com/dialog/pod/ideabiz_log_summary/IdeabizLogSummaryConfig.class]

Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

Process finished with exit code 1
</code>```

答:
Mark one of the beans as primary </p>

```<code>    @Primary
    @Bean
    public EntityManagerFactory entityManagerFactory() {
}
</code>```

Body:
I wanted to connect my spring boot app to 2 databases . So according to a tutorial i created 2 config classes.

Config Class 1

@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:database-configs.properties" })
@EnableJpaRepositories(
        basePackages = {"com.dialog.pod.ideabiz_admin.data_access_objects"},
        entityManagerFactoryRef = "adminEntityManagerFactory",
        transactionManagerRef = "adminTransactionManager")
public class IdeabizAdminConfig {

    @Autowired
    private Environment env;

    @Bean
    PlatformTransactionManager adminTransactionManager() {
        return new JpaTransactionManager(adminEntityManagerFactory().getObject());
    }

    @Bean
    LocalContainerEntityManagerFactoryBean adminEntityManagerFactory() {

        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
       // jpaVendorAdapter.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();

        factoryBean.setDataSource(adminDataSource());
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        factoryBean.setPackagesToScan("com.dialog.pod.ideabiz_admin.models");
        factoryBean.setJpaPropertyMap(jpaProperties());
        factoryBean.setPersistenceUnitName("adminDataSource");
        return factoryBean;
    }

    @Bean
    DataSource adminDataSource() {

        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("admin.jdbc.driverClassName"));
        dataSource.setUrl(env.getProperty("admin.jdbc.url"));
        dataSource.setUsername(env.getProperty("admin.jdbc.username"));
        dataSource.setPassword(env.getProperty("admin.jdbc.password"));

        return dataSource;
    }

    private Map<String, Object> jpaProperties() {
        Map<String, Object> props = new HashMap<>();
        props.put("hibernate.implicit_naming_strategy","org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl");
        props.put("hibernate.physical_naming_strategy","com.dialog.pod.PhysicalNamingStrategyImpl");
        return props;
    }

}

Config Class 2

@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:database-configs.properties" })
@EnableJpaRepositories(
        basePackages = {"com.dialog.pod.ideabiz_log_summary.data_access_objects"},
        entityManagerFactoryRef = "sumLogEntityManagerFactory",
        transactionManagerRef = "sumLogTransactionManager")
public class IdeabizLogSummaryConfig {

    @Autowired
    private Environment env;

    @Bean
    PlatformTransactionManager sumLogTransactionManager() {
        return new JpaTransactionManager(sumLogEntityManagerFactory().getObject());
    }

    @Bean
    LocalContainerEntityManagerFactoryBean sumLogEntityManagerFactory() {

        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
       // jpaVendorAdapter.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();

        factoryBean.setDataSource(adminDataSource());
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        factoryBean.setPackagesToScan("com.dialog.pod.ideabiz_log_summary.models");
        factoryBean.setJpaPropertyMap(jpaProperties());
        factoryBean.setPersistenceUnitName("sumLogDataSource");
        return factoryBean;
    }

    @Bean
    DataSource adminDataSource() {

        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("sumlog.jdbc.driverClassName"));
        dataSource.setUrl(env.getProperty("sumlog.jdbc.url"));
        dataSource.setUsername(env.getProperty("sumlog.jdbc.username"));
        dataSource.setPassword(env.getProperty("sumlog.jdbc.password"));

        return dataSource;
    }

    private Map<String, Object> jpaProperties() {
        Map<String, Object> props = new HashMap<>();
        props.put("hibernate.implicit_naming_strategy","org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl");
        props.put("hibernate.physical_naming_strategy","com.dialog.pod.PhysicalNamingStrategyImpl");
        return props;
    }

}

Application Class

@SpringBootApplication
@EnableAutoConfiguration (exclude = {  DataSourceAutoConfiguration.class })
@Configuration
@ComponentScan
public class PodApiApplication {

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

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/").allowedOrigins("*");
            }
        };
    }

}

When i try to run the app i get following error.

***************************
APPLICATION FAILED TO START
***************************

Description:

Method requestMappingHandlerMapping in org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration required a single bean, but 2 were found:
    - adminEntityManagerFactory: defined by method 'adminEntityManagerFactory' in class path resource [com/dialog/pod/ideabiz_admin/IdeabizAdminConfig.class]
    - sumLogEntityManagerFactory: defined by method 'sumLogEntityManagerFactory' in class path resource [com/dialog/pod/ideabiz_log_summary/IdeabizLogSummaryConfig.class]

Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

Process finished with exit code 1

I put @Primary to the first config class(according to another tutorial). When i do that datasource in the first config class works. Problem is when i do this first datasource also applied to all the jparepositories.

I'm new to Spring boot. I have been trying to solve this problem for over 5 hours :( . Thanks in advance for any help you are able to provide.

Full Log

2017-01-27 00:52:39.713  INFO 6704 --- [           main] com.dialog.pod.PodApiApplication         : Starting PodApiApplication on DESKTOP-4B89ITN with PID 6704 (started by y2ksh in H:\Spring MVC Workspace\platform-overview-dashboard\PODApi)
2017-01-27 00:52:39.718  INFO 6704 --- [           main] com.dialog.pod.PodApiApplication         : No active profile set, falling back to default profiles: default
2017-01-27 00:52:39.938  INFO 6704 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6e171cd7: startup date [Fri Jan 27 00:52:39 IST 2017]; root of context hierarchy
2017-01-27 00:52:41.712  INFO 6704 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'adminDataSource' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=ideabizAdminConfig; factoryMethodName=adminDataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/dialog/pod/ideabiz_admin/IdeabizAdminConfig.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=ideabizLogSummaryConfig; factoryMethodName=adminDataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/dialog/pod/ideabiz_log_summary/IdeabizLogSummaryConfig.class]]
2017-01-27 00:52:42.804  INFO 6704 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$3cc0fc3] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-01-27 00:52:43.594  INFO 6704 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8081 (http)
2017-01-27 00:52:43.609  INFO 6704 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2017-01-27 00:52:43.609  INFO 6704 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.6
2017-01-27 00:52:43.810  INFO 6704 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-01-27 00:52:43.810  INFO 6704 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3891 ms
2017-01-27 00:52:44.247  INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-01-27 00:52:44.253  INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'metricFilter' to: [/*]
2017-01-27 00:52:44.254  INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-01-27 00:52:44.254  INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-01-27 00:52:44.254  INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-01-27 00:52:44.254  INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-01-27 00:52:44.255  INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'webRequestLoggingFilter' to: [/*]
2017-01-27 00:52:44.255  INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'applicationContextIdFilter' to: [/*]
2017-01-27 00:52:44.367  INFO 6704 --- [           main] o.s.j.d.DriverManagerDataSource          : Loaded JDBC driver: com.mysql.jdbc.Driver
2017-01-27 00:52:44.403  INFO 6704 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'adminDataSource'
2017-01-27 00:52:44.435  INFO 6704 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: adminDataSource
    ...]
2017-01-27 00:52:44.634  INFO 6704 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.0.11.Final}
2017-01-27 00:52:44.636  INFO 6704 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2017-01-27 00:52:44.641  INFO 6704 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2017-01-27 00:52:44.725  INFO 6704 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-01-27 00:52:45.302  INFO 6704 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-01-27 00:52:46.178  INFO 6704 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'adminDataSource'
2017-01-27 00:52:46.189  INFO 6704 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'sumLogDataSource'
2017-01-27 00:52:46.190  INFO 6704 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: sumLogDataSource
    ...]
2017-01-27 00:52:46.228  INFO 6704 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-01-27 00:52:46.291  INFO 6704 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'sumLogDataSource'
2017-01-27 00:52:46.695  INFO 6704 --- [           main] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
2017-01-27 00:52:46.947  INFO 6704 --- [           main] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
2017-01-27 00:52:47.496  INFO 6704 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6e171cd7: startup date [Fri Jan 27 00:52:39 IST 2017]; root of context hierarchy
2017-01-27 00:52:47.560  WARN 6704 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping]: Factory method 'requestMappingHandlerMapping' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'openEntityManagerInViewInterceptor' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration$JpaWebConfiguration$JpaWebMvcConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManagerFactory' available: expected single matching bean but found 2: adminEntityManagerFactory,sumLogEntityManagerFactory
2017-01-27 00:52:47.562  INFO 6704 --- [           main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'sumLogDataSource'
2017-01-27 00:52:47.563  INFO 6704 --- [           main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'adminDataSource'
2017-01-27 00:52:47.566  INFO 6704 --- [           main] o.apache.catalina.core.StandardService   : Stopping service Tomcat
2017-01-27 00:52:47.586  INFO 6704 --- [           main] utoConfigurationReportLoggingInitializer :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-01-27 00:52:47.592 ERROR 6704 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Method requestMappingHandlerMapping in org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration required a single bean, but 2 were found:
    - adminEntityManagerFactory: defined by method 'adminEntityManagerFactory' in class path resource [com/dialog/pod/ideabiz_admin/IdeabizAdminConfig.class]
    - sumLogEntityManagerFactory: defined by method 'sumLogEntityManagerFactory' in class path resource [com/dialog/pod/ideabiz_log_summary/IdeabizLogSummaryConfig.class]

Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

Process finished with exit code 1

Body:
Mark one of the beans as primary

    @Primary
    @Bean
    public EntityManagerFactory entityManagerFactory() {
}


来源: stackexchange

问:
What should I use to make scrollable text area (no-editable) with icons (.png) in each line?
Which Flash Component should I use? DataGrid, ScrollPane, TextArea?</p>

答:
it depends on how are icons supposed to be placed in the lines.
anyway imho the best choice is to write a custom class that'd extended Sprite and was a wrapper for a TextField

ContentLicense: CC BY-SA 2.5


问:
maven include main project into test-jar
I have already created a test-jar with the maven-jar-plugin

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.4</version>
    <executions>
        <execution>
            <goals>
                <goal>test-jar</goal>
            </goals>
        </execution>
    </executions>
</plugin>
</code>```

But the test-jar needs the main classes to work, so how can I include them in the test-jar (creating something like a uber-test-jar)?

答:
You can't add other classes to the test-jar trough the maven-jar-plugin but you can do a jar that contains main project classes and test classes in another way: using the maven-assembly-plugin!

```<code><plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>2.5.3</version>
    <configuration>
        <descriptor>src/assembly/dep.xml</descriptor>
    </configuration>
    <executions>
        <execution>
            <id>create-archive</id>
            <phase>package</phase>
            <goals>
                <goal>single</goal>
            </goals>
        </execution>
    </executions>
</plugin>
</code>```

This will create an artifact with the information described in the assembly descriptor, the descriptor default path is src/assembly/.xml
In the descriptor you want to add this:

```<code><assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-  plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
    <id>example</id>
    <formats>
        <format>jar</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory>
    <fileSets>
        <fileSet>
            <directory>${project.build.testOutputDirectory}</directory>
            <outputDirectory>/</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>${project.build.outputDirectory}</directory>
            <outputDirectory>/</outputDirectory>
        </fileSet>
    </fileSets>
</assembly>
</code>```

id -> postfix to the jar

format -> format of the output file (we're creating a jar)

fileSets ->  all the directories to add

fileSet -> single directory to add, with outputDirectory, include exclude ecc.

this example would create a jar with -example as the postfix (ex: plugin-1.0-example.jar) with both main and test files

ContentLicense: CC BY-SA 3.0

Body:
I have already created a test-jar with the maven-jar-plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.4</version>
    <executions>
        <execution>
            <goals>
                <goal>test-jar</goal>
            </goals>
        </execution>
    </executions>
</plugin>

But the test-jar needs the main classes to work, so how can I include them in the test-jar (creating something like a uber-test-jar)?

Body:
You can't add other classes to the test-jar trough the maven-jar-plugin but you can do a jar that contains main project classes and test classes in another way: using the maven-assembly-plugin!

<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>2.5.3</version>
    <configuration>
        <descriptor>src/assembly/dep.xml</descriptor>
    </configuration>
    <executions>
        <execution>
            <id>create-archive</id>
            <phase>package</phase>
            <goals>
                <goal>single</goal>
            </goals>
        </execution>
    </executions>
</plugin>

This will create an artifact with the information described in the assembly descriptor, the descriptor default path is src/assembly/.xml
In the descriptor you want to add this:

<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-  plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
    <id>example</id>
    <formats>
        <format>jar</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory>
    <fileSets>
        <fileSet>
            <directory>${project.build.testOutputDirectory}</directory>
            <outputDirectory>/</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>${project.build.outputDirectory}</directory>
            <outputDirectory>/</outputDirectory>
        </fileSet>
    </fileSets>
</assembly>

id -> postfix to the jar

format -> format of the output file (we're creating a jar)

fileSets ->  all the directories to add

fileSet -> single directory to add, with outputDirectory, include exclude ecc.

this example would create a jar with -example as the postfix (ex: plugin-1.0-example.jar) with both main and test files


问:
Saving an Object that contains a list gives "referential integrity constraint violation"
I'm attempting to understand how to edit a One-to-Many relationship using MVC and Entity Framework and I am running into a few issues, I am attempting to edit the One (Person) and the Many (Color) on the same View (I will move onto Many-to-Many once this is complete).

I've reviewed many other posts and don't see a direct solution to what I think I am experiencing.

BaseObject Class:

```<code>public class BaseObject
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    [Column(Order = 1)]
    public Guid Oid { get; set; }
}
</code>```

Person Class:

```<code>public class Person : BaseObject
{
    public string Name { get; set; }
    public virtual List<Color> Colors { get; set; }
}
</code>```

Color Class:

```<code>public class Color : BaseObject
{
    public string Name { get; set; }

    [DisplayName("Person")]
    public Guid? PersonID { get; set; }

    [ForeignKey("PersonID")]
    public virtual Person Person { get; set; }

}
</code>```

After this I create my Scafolding (and Views), from there I have modified the Person/Edit.cshtml to use a Model Binder method  starting with @for (var i = 0; i < Model.Colors.Count(); i++):

```<code>@model x.Models.One_to_Many.Person
@using x.Models.One_to_Many

@{
    ViewBag.Title = "Edit Person and associated Colors";
}

<h2>Edit</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Person showing associated Colors</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Oid)

        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Colors, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">

                @for(var i = 0; i < Model.Colors.Count(); i++)
                {
                    @Html.HiddenFor(model => Model.Colors[i].Oid)
                    @Html.EditorFor(modelItem => Model.Colors[i].Name, new { htmlAttributes = new { @class = "form-control" } })
                }

                </div>
            </div>

            <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>
</code>```

From there, I have the Person Controller (PeopleController) basically untouched (I've added Colors to the Bind > Include as a test):

```<code>    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "Oid,Name,Colors")] Person person)
    {
        if (ModelState.IsValid)
        {
            db.Entry(person).State = EntityState.Modified; //<-- Error
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(person);
    }
</code>```

When I run the app, open an existing Person I see the Person Name and a list of the colors (Blue and Green).  Modifying or not, when I click "Save", db.Entry(person).State = EntityState.Modified; returns the following error:

System.InvalidOperationException: 'A referential integrity constraint violation occurred: The property value(s) of 'Person.Oid' on one end of a relationship do not match the property value(s) of 'Color.PersonID' on the other end.'

Inspecting at the Person object, it does have 2 Colors (got past that using the Model Binder), going into the Colors collection I see the Name of the color has changed, the Person object is populated, but the PersonID is not.

```<code>person.Colors[0].Name       "Blue updated"                  string
person.Colors[0].PersonID   null                            System.Guid?
+person.Colors[0].Person    {x.Models.One_to_Many.Person}   x.Models.One_to_Many.Person
</code>```

I believe that the PersonID is my issue, it needs to be populated with the current Person.

Do I need to Bind or Include in the Edit GET?

```<code>public ActionResult Edit(Guid? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Person person = db.One.Find(id);
    if (person == null)
    {
        return HttpNotFound();
    }
    return View(person);
}
</code>```

I'm not sure what the best approach is to having this set or setting it on Save.

Edit

This is based on @gert-arnold advice to go to a ViewModel, my plan was to move to that after I figure out the One-to-Many and future Many-to-Many.

Saving the Model wasn't working out too well, if you see below, I would be able to adapt the code to the PeopleController, but putting it into a ViewModel and Controller definitely made sense.

I have now created a PersonViewModel:

```<code>public class PersonView
{
    public string Name { get; set; }
    public virtual List<Color> Colors { get; set; }
}
</code>```

And an associated Controller; PersonViewController:

```<code>public class PersonViewController : Controller
{
    private ApplicationDBContext db = new ApplicationDBContext();
    private Person person;
    private Color color;

    public ActionResult Edit(Guid id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        person = db.People.Find(id);
        if (person == null)
        {
            return HttpNotFound();
        }

        //Setup ViewModel
        PersonView personView = new PersonView();
        personView.Name = person.Name;
        personView.Colors = person.Colors;

        return View(personView);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Guid? id, PersonView personViewModel)
    {
        if (ModelState.IsValid)
        {
            //Person
            person = db.People.Find(id);
            person.Name = personViewModel.Name;
            db.Entry(person).State = EntityState.Modified;
            db.SaveChanges();

            //Colors
            foreach (Color item in personViewModel.Colors)
            {
                color = db.Colors.Find(item.Oid);
                color.Name = item.Name;
                //color.PersonID = id; //Is this neccessary?
                db.Entry(color).State = EntityState.Modified;
                db.SaveChanges();
            }

            return View(personViewModel); //return RedirectToAction("Index");
        }
        return View(personViewModel);
    }
}
</code>```

Finally, the Edit.cshtml is very similar (if not the same) as above.  I believe that I am getting the results that I am looking for and I can expand to allow new Colors to be added inline with Ajax, etc.

I know that I need to check for and catch errors, but I feel this will suffice as a proof of concept.  In short, does anyone have any advice on this code and approach, I am looking to improve it now and apply to my actual project.

答:
Consider removing the PersonId column in your Color entity. Set up your mapping to resolve the "Person" key to a PersonId column, but avoid exposing both a parent reference and it's FK property in your child entity. This leads to all kinds of issues where parent references and FKs could fall out of sync. With both in place depending on how the mapping resolves, you'd need to do something like below with all of your reference properties:

```<code>private Person _person = null;
public virtual Person Person
{
  get {return _person;}
  set
  {
    _person = value;
    if (value != null)
      PersonID = value.OId;
    else
      PersonID = null;
  }
}
</code>```

Disclaimer: I personally do not use code-first mapping. I elect to use DB first with EntityTypeConfiguration declarations as I use bounded contexts and prefer to optimize my schema without the ORM "tinkering" with it. With explicit configuration I can use .Map to resolve my FK's without exposing them as properties in my entities. I don't know if/how this is achievable with code-first.

As a general rule I avoid adding Parent entity references entirely unless I know for a fact I will need reverse resolution. For example: if I always go from Person to list Colors, I wouldn't even have a Person reference (or FK property) in my Color object. However in the case of something like Customers and Orders, I would justify having a Customer reference on my order as I'd expect to be searching through Orders and want to see what customer they were associated to.

Body:
I'm attempting to understand how to edit a One-to-Many relationship using MVC and Entity Framework and I am running into a few issues, I am attempting to edit the One (Person) and the Many (Color) on the same View (I will move onto Many-to-Many once this is complete).

I've reviewed many other posts and don't see a direct solution to what I think I am experiencing.

BaseObject Class:

public class BaseObject
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    [Column(Order = 1)]
    public Guid Oid { get; set; }
}

Person Class:

public class Person : BaseObject
{
    public string Name { get; set; }
    public virtual List<Color> Colors { get; set; }
}

Color Class:

public class Color : BaseObject
{
    public string Name { get; set; }

    [DisplayName("Person")]
    public Guid? PersonID { get; set; }

    [ForeignKey("PersonID")]
    public virtual Person Person { get; set; }

}

After this I create my Scafolding (and Views), from there I have modified the Person/Edit.cshtml to use a Model Binder method  starting with @for (var i = 0; i < Model.Colors.Count(); i++):

@model x.Models.One_to_Many.Person
@using x.Models.One_to_Many

@{
    ViewBag.Title = "Edit Person and associated Colors";
}

Edit

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

Person showing associated Colors

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Oid)

            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Colors, htmlAttributes: new { @class = "control-label col-md-2" })

                @for(var i = 0; i < Model.Colors.Count(); i++)
                {
                    @Html.HiddenFor(model => Model.Colors[i].Oid)
                    @Html.EditorFor(modelItem => Model.Colors[i].Name, new { htmlAttributes = new { @class = "form-control" } })
                }

                <input type="submit" value="Save" class="btn btn-default" />

}

    @Html.ActionLink("Back to List", "Index")

From there, I have the Person Controller (PeopleController) basically untouched (I've added Colors to the Bind > Include as a test):

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "Oid,Name,Colors")] Person person)
    {
        if (ModelState.IsValid)
        {
            db.Entry(person).State = EntityState.Modified; //<-- Error
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(person);
    }

When I run the app, open an existing Person I see the Person Name and a list of the colors (Blue and Green).  Modifying or not, when I click "Save", db.Entry(person).State = EntityState.Modified; returns the following error:

System.InvalidOperationException: 'A referential integrity constraint violation occurred: The property value(s) of 'Person.Oid' on one end of a relationship do not match the property value(s) of 'Color.PersonID' on the other end.'

Inspecting at the Person object, it does have 2 Colors (got past that using the Model Binder), going into the Colors collection I see the Name of the color has changed, the Person object is populated, but the PersonID is not.

person.Colors[0].Name       "Blue updated"                  string
person.Colors[0].PersonID   null                            System.Guid?
+person.Colors[0].Person    {x.Models.One_to_Many.Person}   x.Models.One_to_Many.Person

I believe that the PersonID is my issue, it needs to be populated with the current Person.

Do I need to Bind or Include in the Edit GET?

public ActionResult Edit(Guid? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Person person = db.One.Find(id);
    if (person == null)
    {
        return HttpNotFound();
    }
    return View(person);
}

I'm not sure what the best approach is to having this set or setting it on Save.

Edit

This is based on @gert-arnold advice to go to a ViewModel, my plan was to move to that after I figure out the One-to-Many and future Many-to-Many.

Saving the Model wasn't working out too well, if you see below, I would be able to adapt the code to the PeopleController, but putting it into a ViewModel and Controller definitely made sense.

I have now created a PersonViewModel:

public class PersonView
{
    public string Name { get; set; }
    public virtual List<Color> Colors { get; set; }
}

And an associated Controller; PersonViewController:

public class PersonViewController : Controller
{
    private ApplicationDBContext db = new ApplicationDBContext();
    private Person person;
    private Color color;

    public ActionResult Edit(Guid id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        person = db.People.Find(id);
        if (person == null)
        {
            return HttpNotFound();
        }

        //Setup ViewModel
        PersonView personView = new PersonView();
        personView.Name = person.Name;
        personView.Colors = person.Colors;

        return View(personView);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Guid? id, PersonView personViewModel)
    {
        if (ModelState.IsValid)
        {
            //Person
            person = db.People.Find(id);
            person.Name = personViewModel.Name;
            db.Entry(person).State = EntityState.Modified;
            db.SaveChanges();

            //Colors
            foreach (Color item in personViewModel.Colors)
            {
                color = db.Colors.Find(item.Oid);
                color.Name = item.Name;
                //color.PersonID = id; //Is this neccessary?
                db.Entry(color).State = EntityState.Modified;
                db.SaveChanges();
            }

            return View(personViewModel); //return RedirectToAction("Index");
        }
        return View(personViewModel);
    }
}

Finally, the Edit.cshtml is very similar (if not the same) as above.  I believe that I am getting the results that I am looking for and I can expand to allow new Colors to be added inline with Ajax, etc.

I know that I need to check for and catch errors, but I feel this will suffice as a proof of concept.  In short, does anyone have any advice on this code and approach, I am looking to improve it now and apply to my actual project.

Body:
Consider removing the PersonId column in your Color entity. Set up your mapping to resolve the "Person" key to a PersonId column, but avoid exposing both a parent reference and it's FK property in your child entity. This leads to all kinds of issues where parent references and FKs could fall out of sync. With both in place depending on how the mapping resolves, you'd need to do something like below with all of your reference properties:

private Person _person = null;
public virtual Person Person
{
  get {return _person;}
  set
  {
    _person = value;
    if (value != null)
      PersonID = value.OId;
    else
      PersonID = null;
  }
}

Disclaimer: I personally do not use code-first mapping. I elect to use DB first with EntityTypeConfiguration declarations as I use bounded contexts and prefer to optimize my schema without the ORM "tinkering" with it. With explicit configuration I can use .Map to resolve my FK's without exposing them as properties in my entities. I don't know if/how this is achievable with code-first.

As a general rule I avoid adding Parent entity references entirely unless I know for a fact I will need reverse resolution. For example: if I always go from Person to list Colors, I wouldn't even have a Person reference (or FK property) in my Color object. However in the case of something like Customers and Orders, I would justify having a Customer reference on my order as I'd expect to be searching through Orders and want to see what customer they were associated to.


问:
Collections.max function for iterable<Integer> in java
The Java Collections.max takes only a collection of a sortable object. However since the collection is not necessarily sorted, I don't see any reason not to implement the same max function for iterable types.

Is there a max method for Iterable<T extends Comparable<? super T>> in java's standard library?

答:
By definition the elements of the collection must be "sortable" (specifically, they must implements Comparable) since in order to compute the maximum, it must be possible to work out whether one element is greater than another (which is exactly what Comparable means).

The max() method in the Collections class has essentially the exact type signature you posted there, so it should suit your purpose.

OwnerDisplayName: Elazar Leibovich

LastEditorDisplayName: mmyers

OwnerDisplayName: dtsazza


问:
Creating a new *Dialer with gomail.v2
I'm using gomail.v2 to send emails, and my code works fine. After composing a message msg I can just run

```<code>import ("gopkg.in/gomail.v2")

  ...
  d := gomail.NewDialer("smtp.example.com", 25, "username", "password")
  return d.DialAndSend(msg)
}
</code>```

Of course I'd like to generalize this past a particular username and password and separate it into its own function, so I stubbed it out:

```<code>import ("gopkg.in/gomail.v2")

  ...
  d := MyDialer()
  return d.DialAndSend(msg)
}

func MyDialer() *Dialer {
  return gomail.NewDialer("smtp.example.com", 25, "username", "password")
}
</code>```

But go croaks, complaining that it doesn't know about Dialer.

.\email.go:42: undefined: Dialer

Why is this? I'm using the same return type as NewDialer, which doesn't cause any problems.

```<code>func NewDialer(host string, port int, username, password string) *Dialer
</code>```

What am I missing? I ran

go get -u gopkg.in/gomail.v2

to make sure I wasn't somehow running an out of date version of the package, but no luck there.

答:
*Dialer and *gomail.Dialer are 2 different types. The specific error is because you don't have a Dialer type defined in your package, but you need to match the types in the signature, not just the name. Since gomail.NewDialer returns a *gomail.Dialer, use:

```<code>func MyDialer() *gomail.Dialer {
</code>```

Title: Creating a new *Dialer with gomail.v2

Body:
I'm using gomail.v2 to send emails, and my code works fine. After composing a message msg I can just run

import ("gopkg.in/gomail.v2")

  ...
  d := gomail.NewDialer("smtp.example.com", 25, "username", "password")
  return d.DialAndSend(msg)
}

Of course I'd like to generalize this past a particular username and password and separate it into its own function, so I stubbed it out:

import ("gopkg.in/gomail.v2")

  ...
  d := MyDialer()
  return d.DialAndSend(msg)
}

func MyDialer() *Dialer {
  return gomail.NewDialer("smtp.example.com", 25, "username", "password")
}

But go croaks, complaining that it doesn't know about Dialer.

.\email.go:42: undefined: Dialer

Why is this? I'm using the same return type as NewDialer, which doesn't cause any problems.

func NewDialer(host string, port int, username, password string) *Dialer

What am I missing? I ran

go get -u gopkg.in/gomail.v2

to make sure I wasn't somehow running an out of date version of the package, but no luck there.

Body:
*Dialer and *gomail.Dialer are 2 different types. The specific error is because you don't have a Dialer type defined in your package, but you need to match the types in the signature, not just the name. Since gomail.NewDialer returns a *gomail.Dialer, use:

func MyDialer() *gomail.Dialer {


问:
Little footprint from HTML5 on Primefaces Client Side Validation (CSV)
I'm trying to use the Client Side Validation (CSV) sample from Primefaces a long time to get the footprint effect of HTML5, but after much searching and multiple attempts I could not get the expected result. I followed all the documentation including putting the necessary parameters in the web.xml and the validation itself is working correctly, however the footprint effect could not work.

Added parameter in web.xml:

```<code><context-param>
    <param-name>primefaces.CLIENT_SIDE_VALIDATION</param-name>
    <param-value>true</param-value>
</context-param>
</code>```

At the top of my document I'm using the notation for HTML 5 document:

```<code><!DOCTYPE html>
</code>```

Tried deploy with WildFly 8.2.1 and now WildFly 10.1

Tried with Primefaces 5.3 and now with 6.1, but no success

My question is how to obtain the little footprint from HTML5 with Primefaces CVS?

Example page: https://www.primefaces.org/showcase/ui/csv/basic.xhtml

答:
I think you misunderstood 'little footprint using html5'. What this means is that it uses html5 capabilities of the browser to be a sort of 'light-weight' implementation in that it does not add loads of code to an element to make client-side validation (CSV) a reality.

So if CSV works, you make use of the 'little footprint' and if CSV does not work at all, then you of course do not have it but that is (hopefully) obvious (the 'little footprint' is not some feature that you can turn on and off)

What you describe in your comment is a pure css/theming thing. The default theme in the showcase is 'omega' which has (as far a I know) the property that fields that are in error do not have a full red boundary but just one on the left. Switching a theme in the showcase after making a field invalid (e.g. to Afterdark) will make this clear.

Body:
I'm trying to use the Client Side Validation (CSV) sample from Primefaces a long time to get the footprint effect of HTML5, but after much searching and multiple attempts I could not get the expected result. I followed all the documentation including putting the necessary parameters in the web.xml and the validation itself is working correctly, however the footprint effect could not work.

Added parameter in web.xml:

<context-param>
    <param-name>primefaces.CLIENT_SIDE_VALIDATION</param-name>
    <param-value>true</param-value>
</context-param>

At the top of my document I'm using the notation for HTML 5 document:

<!DOCTYPE html>

Tried deploy with WildFly 8.2.1 and now WildFly 10.1

Tried with Primefaces 5.3 and now with 6.1, but no success

My question is how to obtain the little footprint from HTML5 with Primefaces CVS?

Example page: https://www.primefaces.org/showcase/ui/csv/basic.xhtml


问:
How to understand this C++ palindrome code?
I recently came to the solution of the palindrome problem, but I do not understand how this part of code works (with rbegin and rend). Can someone explain it to me?</p>

```<code>#include <iostream>
#include <string>

using namespace std;
bool checkPalindrome(string);
int main()
{
    string inputString = "palindrom";
    cout << checkPalindrome(inputString);
return 0;
}

bool checkPalindrome(std::string inputString)
{
   return (inputString == string(inputString.rbegin(), inputString.rend()));
}
</code>```

答:
Taking a look at the string constructor:

```<code>    ...
    (7) template <class InputIterator>
    string  (InputIterator first, InputIterator last);
</code>```

You can see it is possible to create a string via iterators. The rbegin/rend iterators are InputIterators that points to the reverse positions that they refer:

```<code>    rend() -->"My string"<-- rbegin()
</code>```

That said, when you pass the rbegin() and rend() to the string constructor, it will iterate from the ending, to the beginning of the string, creating the inverted one:

```<code>    iteration 0: "g"    (currentIterator = rbegin()   : push("g")
    iteration 1: "n"    (currentIterator = rbegin()+1 : push("n")
    iteartion 2: "i"    (currentIterator = rbegin()+2 : push("i")
    ...
    iteration 8: "M"    (currentIterator = rbegin()+8 : push("M")
    iteration 9: rend() (currentIterator = rend()     : stop iteration)
</code>```

Finally, the operator==() will check for equivalence of the strings.

Body:
I recently came to the solution of the palindrome problem, but I do not understand how this part of code works (with rbegin and rend). Can someone explain it to me?

#include <iostream>
#include <string>

using namespace std;
bool checkPalindrome(string);
int main()
{
    string inputString = "palindrom";
    cout << checkPalindrome(inputString);
return 0;
}

bool checkPalindrome(std::string inputString)
{
   return (inputString == string(inputString.rbegin(), inputString.rend()));
}

Body:
Taking a look at the string constructor:

    ...
    (7) template <class InputIterator>
    string  (InputIterator first, InputIterator last);

You can see it is possible to create a string via iterators. The rbegin/rend iterators are InputIterators that points to the reverse positions that they refer:

    rend() -->"My string"<-- rbegin()

That said, when you pass the rbegin() and rend() to the string constructor, it will iterate from the ending, to the beginning of the string, creating the inverted one:

    iteration 0: "g"    (currentIterator = rbegin()   : push("g")
    iteration 1: "n"    (currentIterator = rbegin()+1 : push("n")
    iteartion 2: "i"    (currentIterator = rbegin()+2 : push("i")
    ...
    iteration 8: "M"    (currentIterator = rbegin()+8 : push("M")
    iteration 9: rend() (currentIterator = rend()     : stop iteration)

Finally, the operator==() will check for equivalence of the strings.


问:
Why am I not seeing output in the terminal after executing python script?
Im following a tutorial @: https://blog.scrapinghub.com/category/scrapy-tips-from-the-pros/ ~ The code seems to execute fine, but Im not seeing any output to the terminal.. Im still trying to figure out how to use a "stack trace with python..., to see if there is a issue on the back-end", Problem is that I am not seeing any output in the terminal after executing the script.. Any help would be great..</p>

```<code>import scrapy

class SpidyQuotesViewStateSpider(scrapy.Spider):
    name = 'spidyquotes-viewstate'
    start_urls = ['http://quotes.toscrape.com/search.aspx']
    download_delay = 1.5

    def parse(self, response):
      for author in response.css('select#author > option ::attr(value)').extract():
        yield scrapy.FormRequest(
            'http://quotes.toscrape.com/filter.aspx',
            formdata={
                'author': author,
                '__VIEWSTATE': response.css('input#__VIEWSTATE::attr(value)').extract_first()
            },
            callback=self.parse_tags
        )

     def parse_tags(self, response):
        for tag in response.css('select#tag > option ::attr(value)').extract():
            yield scrapy.FormRequest(
                'http://quotes.toscrape.com/filter.aspx',
                formdata={
                    'author': response.css(
                        'select#author > option[selected] ::attr(value)'
                    ).extract_first(),
                    'tag': tag,
                    '__VIEWSTATE': response.css('input#__VIEWSTATE::attr(value)').extract_first()
                },
                callback=self.parse_results,
            )

     def parse_results(self, response):
       for quote in response.css("div.quote"):
            yield {
                'quote': quote.css('span.content ::text').extract_first(),
                'author': quote.css('span.author ::text').extract_first(),
                'tag': quote.css('span.tag ::text').extract_first(),
            }
</code>```

答:
The given code has no active execution.  This is nothing more than a class definition.  To get output, you need to continue in the tutorial to write a driver (main) program that will instantiate an object of the class and make a call or two to actually scrape the given web sites.

You don't get a "stack trace" unless your program crashes (elicits an fatal exception).  It's not something you implement and "use".

Body:
Im following a tutorial @: https://blog.scrapinghub.com/category/scrapy-tips-from-the-pros/ ~ The code seems to execute fine, but Im not seeing any output to the terminal.. Im still trying to figure out how to use a "stack trace with python..., to see if there is a issue on the back-end", Problem is that I am not seeing any output in the terminal after executing the script.. Any help would be great..

import scrapy

class SpidyQuotesViewStateSpider(scrapy.Spider):
    name = 'spidyquotes-viewstate'
    start_urls = ['http://quotes.toscrape.com/search.aspx']
    download_delay = 1.5

    def parse(self, response):
      for author in response.css('select#author > option ::attr(value)').extract():
        yield scrapy.FormRequest(
            'http://quotes.toscrape.com/filter.aspx',
            formdata={
                'author': author,
                '__VIEWSTATE': response.css('input#__VIEWSTATE::attr(value)').extract_first()
            },
            callback=self.parse_tags
        )

     def parse_tags(self, response):
        for tag in response.css('select#tag > option ::attr(value)').extract():
            yield scrapy.FormRequest(
                'http://quotes.toscrape.com/filter.aspx',
                formdata={
                    'author': response.css(
                        'select#author > option[selected] ::attr(value)'
                    ).extract_first(),
                    'tag': tag,
                    '__VIEWSTATE': response.css('input#__VIEWSTATE::attr(value)').extract_first()
                },
                callback=self.parse_results,
            )

     def parse_results(self, response):
       for quote in response.css("div.quote"):
            yield {
                'quote': quote.css('span.content ::text').extract_first(),
                'author': quote.css('span.author ::text').extract_first(),
                'tag': quote.css('span.tag ::text').extract_first(),
            }


问:
Correcting 3D line drawing in C#
I have (with assistance) created a function that plots and draws a line of blocks within a 3D space. Generally this is performed in a 64x64x64 gridded cube.

This is the code I have:

```<code>    internal static int DrawLine(Player theplayer, Byte drawBlock,
                                 int x0, int y0, int z0, int x1, int y1, int z1)
    {
        int blocks = 0;
        bool cannotUndo = false;
        bool detected = false;

        int dx = x1 - x0;
        int dy = y1 - y0;
        int dz = z1 - z0;

        DrawOneBlock(theplayer, drawBlock, x0, y0, z0, ref blocks, ref cannotUndo);
        if (Math.Abs(dx) > Math.Abs(dy) &&
            Math.Abs(dx) > Math.Abs(dz) &&
            detected == false)
        {
            detected = true;
            float my = (float)dy / (float)dx;
            float mz = (float)dz / (float)dx;
            float by = y0 - my * x0;
            float bz = z0 - mz * x0;
            dx = (dx < 0) ? -1 : 1;
            while (x0 != x1)
            {
                x0 += dx;
                DrawOneBlock(theplayer, drawBlock,
                    Convert.ToInt32(x0),
                    Convert.ToInt32(Math.Round(my * x0 + by)),
                    Convert.ToInt32(Math.Round(mz * x0 + bz)),
                    ref blocks, ref cannotUndo);
            }
        }
        if (Math.Abs(dy) > Math.Abs(dz) &&
            Math.Abs(dy) > Math.Abs(dx) &&
            detected == false)
        {
            detected = true;
            float mz = (float)dz / (float)dy;
            float mx = (float)dx / (float)dy;
            float bz = z0 - mz * y0;
            float bx = x0 - mx * y0;
            dy = (dy < 0) ? -1 : 1;
            while (y0 != y1)
            {
                y0 += dy;
                DrawOneBlock(theplayer, drawBlock,
                             Convert.ToInt32(Math.Round(mx * y0 + bx)),
                             Convert.ToInt32(y0),
                             Convert.ToInt32(Math.Round(mz * y0 + bz)),
                             ref blocks, ref cannotUndo);
            }
        }
        if (detected == false)
        {
            detected = true;
            float mx = (float)dx / (float)dz;
            float my = (float)dy / (float)dz;
            float bx = x0 - mx * z0;
            float by = y0 - my * z0;
            dz = (dz < 0) ? -1 : 1;
            while (z0 != z1)
            {
                z0 += dz;
                DrawOneBlock(theplayer, drawBlock,
                             Convert.ToInt32(Math.Round(mx * z0 + bx)),
                             Convert.ToInt32(Math.Round(my * z0 + by)),
                             Convert.ToInt32(z0),
                             ref blocks, ref cannotUndo);
            }
        }
        return blocks;
    }
</code>```

It should queue up the block drawing and return the number of blocks it has drawn. The problem is that it is not drawing an un-broken line. In certain instances it leaves gaps between the blocks when at the very least all blocks should be connected by their vertices.

The only part of the code I struggled with is that I was calculating the largest difference in axis and creating a slope constant. I ran into an issue when trying to do a perfect diagonal line. All values were equal so I just defaulted to the z axis - this is where I believe the issue exists.

答:
```<code>internal static void LineCallback(Player player, Position[] marks, object tag) //MODIFIED//
    {
        byte drawBlock = (byte)tag;
        if (drawBlock == (byte)Block.Undefined)
        {
            drawBlock = (byte)player.lastUsedBlockType;
        }

        player.undoBuffer.Clear();

        int blocks = 0;
        bool cannotUndo = false;

        // LINE CODE

        int x1 = marks[0].x, y1 = marks[0].y, z1 = marks[0].h, x2 = marks[1].x, y2 = marks[1].y, z2 = marks[1].h;
        int i, dx, dy, dz, l, m, n, x_inc, y_inc, z_inc, err_1, err_2, dx2, dy2, dz2;
        int[] pixel = new int[3];
        pixel[0] = x1;
        pixel[1] = y1;
        pixel[2] = z1;
        dx = x2 - x1;
        dy = y2 - y1;
        dz = z2 - z1;
        x_inc = (dx < 0) ? -1 : 1;
        l = Math.Abs(dx);
        y_inc = (dy < 0) ? -1 : 1;
        m = Math.Abs(dy);
        z_inc = (dz < 0) ? -1 : 1;
        n = Math.Abs(dz);
        dx2 = l << 1;
        dy2 = m << 1;
        dz2 = n << 1;

        DrawOneBlock(player, drawBlock, x2, y2, z2, ref blocks, ref cannotUndo);
        DrawOneBlock(player, drawBlock, x2, y2, z2, ref blocks, ref cannotUndo);

        if ((l >= m) && (l >= n)) {

            err_1 = dy2 - l;
            err_2 = dz2 - l;
            for (i = 0; i < l; i++) {
                DrawOneBlock(player, drawBlock, pixel[0], pixel[1], pixel[2], ref blocks, ref cannotUndo);
                if (err_1 > 0) {
                    pixel[1] += y_inc;
                    err_1 -= dx2;
                }
                if (err_2 > 0) {
                    pixel[2] += z_inc;
                    err_2 -= dx2;
                }
                err_1 += dy2;
                err_2 += dz2;
                pixel[0] += x_inc;
            }
        } else if ((m >= l) && (m >= n)) {
            err_1 = dx2 - m;
            err_2 = dz2 - m;
            for (i = 0; i < m; i++) {
                DrawOneBlock(player, drawBlock, pixel[0], pixel[1], pixel[2], ref blocks, ref cannotUndo);
                if (err_1 > 0) {
                    pixel[0] += x_inc;
                    err_1 -= dy2;
                }
                if (err_2 > 0) {
                    pixel[2] += z_inc;
                    err_2 -= dy2;
                }
                err_1 += dx2;
                err_2 += dz2;
                pixel[1] += y_inc;
            }
        } else {
            err_1 = dy2 - n;
            err_2 = dx2 - n;
            for (i = 0; i < n; i++) {
                DrawOneBlock(player, drawBlock, pixel[0], pixel[1], pixel[2], ref blocks, ref cannotUndo);
                if (err_1 > 0) {
                    pixel[1] += y_inc;
                    err_1 -= dz2;
                }
                if (err_2 > 0) {
                    pixel[0] += x_inc;
                    err_2 -= dz2;
                }
                err_1 += dy2;
                err_2 += dx2;
                pixel[2] += z_inc;
            }
        }

        // END LINE CODE
    }
</code>```

I don't understand the code, but based on the direction Jonas put me in I was able to implement this and test without flaw.

Title: Correcting 3D line drawing in C#

Body:
I have (with assistance) created a function that plots and draws a line of blocks within a 3D space. Generally this is performed in a 64x64x64 gridded cube.

This is the code I have:

    internal static int DrawLine(Player theplayer, Byte drawBlock,
                                 int x0, int y0, int z0, int x1, int y1, int z1)
    {
        int blocks = 0;
        bool cannotUndo = false;
        bool detected = false;

        int dx = x1 - x0;
        int dy = y1 - y0;
        int dz = z1 - z0;

        DrawOneBlock(theplayer, drawBlock, x0, y0, z0, ref blocks, ref cannotUndo);
        if (Math.Abs(dx) > Math.Abs(dy) &&
            Math.Abs(dx) > Math.Abs(dz) &&
            detected == false)
        {
            detected = true;
            float my = (float)dy / (float)dx;
            float mz = (float)dz / (float)dx;
            float by = y0 - my * x0;
            float bz = z0 - mz * x0;
            dx = (dx < 0) ? -1 : 1;
            while (x0 != x1)
            {
                x0 += dx;
                DrawOneBlock(theplayer, drawBlock,
                    Convert.ToInt32(x0),
                    Convert.ToInt32(Math.Round(my * x0 + by)),
                    Convert.ToInt32(Math.Round(mz * x0 + bz)),
                    ref blocks, ref cannotUndo);
            }
        }
        if (Math.Abs(dy) > Math.Abs(dz) &&
            Math.Abs(dy) > Math.Abs(dx) &&
            detected == false)
        {
            detected = true;
            float mz = (float)dz / (float)dy;
            float mx = (float)dx / (float)dy;
            float bz = z0 - mz * y0;
            float bx = x0 - mx * y0;
            dy = (dy < 0) ? -1 : 1;
            while (y0 != y1)
            {
                y0 += dy;
                DrawOneBlock(theplayer, drawBlock,
                             Convert.ToInt32(Math.Round(mx * y0 + bx)),
                             Convert.ToInt32(y0),
                             Convert.ToInt32(Math.Round(mz * y0 + bz)),
                             ref blocks, ref cannotUndo);
            }
        }
        if (detected == false)
        {
            detected = true;
            float mx = (float)dx / (float)dz;
            float my = (float)dy / (float)dz;
            float bx = x0 - mx * z0;
            float by = y0 - my * z0;
            dz = (dz < 0) ? -1 : 1;
            while (z0 != z1)
            {
                z0 += dz;
                DrawOneBlock(theplayer, drawBlock,
                             Convert.ToInt32(Math.Round(mx * z0 + bx)),
                             Convert.ToInt32(Math.Round(my * z0 + by)),
                             Convert.ToInt32(z0),
                             ref blocks, ref cannotUndo);
            }
        }
        return blocks;
    }

It should queue up the block drawing and return the number of blocks it has drawn. The problem is that it is not drawing an un-broken line. In certain instances it leaves gaps between the blocks when at the very least all blocks should be connected by their vertices.

The only part of the code I struggled with is that I was calculating the largest difference in axis and creating a slope constant. I ran into an issue when trying to do a perfect diagonal line. All values were equal so I just defaulted to the z axis - this is where I believe the issue exists.

Body:
internal static void LineCallback(Player player, Position[] marks, object tag) //MODIFIED//
    {
        byte drawBlock = (byte)tag;
        if (drawBlock == (byte)Block.Undefined)
        {
            drawBlock = (byte)player.lastUsedBlockType;
        }

        player.undoBuffer.Clear();

        int blocks = 0;
        bool cannotUndo = false;

        // LINE CODE

        int x1 = marks[0].x, y1 = marks[0].y, z1 = marks[0].h, x2 = marks[1].x, y2 = marks[1].y, z2 = marks[1].h;
        int i, dx, dy, dz, l, m, n, x_inc, y_inc, z_inc, err_1, err_2, dx2, dy2, dz2;
        int[] pixel = new int[3];
        pixel[0] = x1;
        pixel[1] = y1;
        pixel[2] = z1;
        dx = x2 - x1;
        dy = y2 - y1;
        dz = z2 - z1;
        x_inc = (dx < 0) ? -1 : 1;
        l = Math.Abs(dx);
        y_inc = (dy < 0) ? -1 : 1;
        m = Math.Abs(dy);
        z_inc = (dz < 0) ? -1 : 1;
        n = Math.Abs(dz);
        dx2 = l << 1;
        dy2 = m << 1;
        dz2 = n << 1;

        DrawOneBlock(player, drawBlock, x2, y2, z2, ref blocks, ref cannotUndo);
        DrawOneBlock(player, drawBlock, x2, y2, z2, ref blocks, ref cannotUndo);

        if ((l >= m) && (l >= n)) {

            err_1 = dy2 - l;
            err_2 = dz2 - l;
            for (i = 0; i < l; i++) {
                DrawOneBlock(player, drawBlock, pixel[0], pixel[1], pixel[2], ref blocks, ref cannotUndo);
                if (err_1 > 0) {
                    pixel[1] += y_inc;
                    err_1 -= dx2;
                }
                if (err_2 > 0) {
                    pixel[2] += z_inc;
                    err_2 -= dx2;
                }
                err_1 += dy2;
                err_2 += dz2;
                pixel[0] += x_inc;
            }
        } else if ((m >= l) && (m >= n)) {
            err_1 = dx2 - m;
            err_2 = dz2 - m;
            for (i = 0; i < m; i++) {
                DrawOneBlock(player, drawBlock, pixel[0], pixel[1], pixel[2], ref blocks, ref cannotUndo);
                if (err_1 > 0) {
                    pixel[0] += x_inc;
                    err_1 -= dy2;
                }
                if (err_2 > 0) {
                    pixel[2] += z_inc;
                    err_2 -= dy2;
                }
                err_1 += dx2;
                err_2 += dz2;
                pixel[1] += y_inc;
            }
        } else {
            err_1 = dy2 - n;
            err_2 = dx2 - n;
            for (i = 0; i < n; i++) {
                DrawOneBlock(player, drawBlock, pixel[0], pixel[1], pixel[2], ref blocks, ref cannotUndo);
                if (err_1 > 0) {
                    pixel[1] += y_inc;
                    err_1 -= dz2;
                }
                if (err_2 > 0) {
                    pixel[0] += x_inc;
                    err_2 -= dz2;
                }
                err_1 += dy2;
                err_2 += dx2;
                pixel[2] += z_inc;
            }
        }

        // END LINE CODE
    }

I don't understand the code, but based on the direction Jonas put me in I was able to implement this and test without flaw.


问:
Launch ajax on launch modal window (ASP.NET MVC)
I have modal window that opens via button click

Here is code in View:

```<code><button style="margin-bottom: 20px;" class="btn  btn-default" data-toggle="modal" data-target="#myModal">Описание вакансии</button>

<div class="modal fade" id="myModal" role="dialog" data-backdrop="false">
<div class="modal-dialog">
    <!-- Modal content-->
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">×</button>
            <h4 class="modal-title">Описание</h4>
        </div>
        <div class="modal-body">
            @Html.Partial("~/Views/Questions/Info.cshtml")
        </div>
    </div>

</div>
</code>```

Here is code of modal:

```<code>  <div id="detail">

</div>

<script>
    $(document).ready(function() {
        emaillist_update2();
    });

    function emaillist_update2() {
        var url = window.location.pathname;
        var id = url.substring(url.lastIndexOf('/') + 1);
        $.ajax({
            url:'@Url.Action("Displayinfo2","Questions")',
            type: 'Post',
            dataType: 'Json',
            data: {
                ID: id
            },
            success: function(result) {
                var info = result;

                $("#detail").append(info.Greeting);
            },
            error: function(result) {
                alert('Error');
            }
        });
    }
</script>
</code>```

Maodal is Partial View

My problem in that script in modal not work where it opens. Looks like it works when page loads, not modal.

How I can run it when I open modal?

答:
This is how you do it:

Partial view in view shared named _Info.cshtml:

```<code>A Partial View
<div id="detail" />
</code>```

Controller/Model:

```<code>public class MyDataModel
{
    public int ID { get; set; }
}

//Create an edmx to your table
public class HomeController : Controller
{
    [HttpPost]
    public ActionResult Index2005(string ID)
    {
        return Json(new
        {
            Greeting = "This is a Greeting"
        }
        , @"application/json");
    }

    public ActionResult Index2005(int? id) //argument to differ from post
    {
        return View();
    }
</code>```

View:

```<code>@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index2005</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $(".btn").click(function () {
                emaillist_update2()
            })

            function emaillist_update2() {
                alert("ap");
                var url = window.location.pathname;
                //var id = url.substring(url.lastIndexOf('/') + 1);
                var id = "you can compute the id";

                $.ajax({
                    //modified the url for my use
                    url: '/Home/Index2005',
                    type: 'POST',
                    dataType: 'json',
                    data: { ID: id },
                    success: function (result) {
                        $("#detail").append(result.Greeting);
                    },
                    error: function (result) {
                        alert('Error');
                    }
                });
            }

        })
    </script>
</head>
<body>
    <button style="margin-bottom: 20px;" class="btn  btn-default" data-toggle="modal" data-target="#myModal">Описание вакансии</button>
    <div class="modal fade" id="myModal" role="dialog" data-backdrop="false">
        <div class="modal-dialog">
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">×</button>
                    <h4 class="modal-title">Описание</h4>
                </div>
                <div class="modal-body">
                    @*put partial class in views share*@
                    @Html.Partial("_Info")
                </div>
            </div>

        </div>
    </div>
</body>
</html>
</code>```

Body:
I have modal window that opens via button click

Here is code in View:

<button style="margin-bottom: 20px;" class="btn  btn-default" data-toggle="modal" data-target="#myModal">Описание вакансии</button>

            <button type="button" class="close" data-dismiss="modal">×</button>

Описание

            @Html.Partial("~/Views/Questions/Info.cshtml")

Here is code of modal:

Maodal is Partial View

My problem in that script in modal not work where it opens. Looks like it works when page loads, not modal.

How I can run it when I open modal?

Body:
This is how you do it:

Partial view in view shared named _Info.cshtml:

A Partial View
<div id="detail" />

Controller/Model:

public class MyDataModel
{
    public int ID { get; set; }
}

//Create an edmx to your table
public class HomeController : Controller
{
    [HttpPost]
    public ActionResult Index2005(string ID)
    {
        return Json(new
        {
            Greeting = "This is a Greeting"
        }
        , @"application/json");
    }

    public ActionResult Index2005(int? id) //argument to differ from post
    {
        return View();
    }

View:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index2005</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $(".btn").click(function () {
                emaillist_update2()
            })

            function emaillist_update2() {
                alert("ap");
                var url = window.location.pathname;
                //var id = url.substring(url.lastIndexOf('/') + 1);
                var id = "you can compute the id";

                $.ajax({
                    //modified the url for my use
                    url: '/Home/Index2005',
                    type: 'POST',
                    dataType: 'json',
                    data: { ID: id },
                    success: function (result) {
                        $("#detail").append(result.Greeting);
                    },
                    error: function (result) {
                        alert('Error');
                    }
                });
            }

        })
    </script>
</head>
<body>
    <button style="margin-bottom: 20px;" class="btn  btn-default" data-toggle="modal" data-target="#myModal">Описание вакансии</button>
    <div class="modal fade" id="myModal" role="dialog" data-backdrop="false">
        <div class="modal-dialog">
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Описание</h4>
                </div>
                <div class="modal-body">
                    @*put partial class in views share*@
                    @Html.Partial("_Info")
                </div>
            </div>

        </div>
    </div>
</body>
</html>


问:
Convert string to enum in TypeScript
I'm using TypeScript 2.2.1 with target ES5

I have couple of enums like below

```<code>enum PermissionLevel {
    ACCOUNT_OWN,
    ACCOUNT_OTHER,
    USER_OWN
}

enum Permission {
    ACCOUNT_CREATE,
    USER_CREATE
}
</code>```

I have a input JSON as below

```<code>{
    "ACCOUNT_OWN": [
        "USER_CREATE",
        "ACCOUNT_CREATE"
    ],
    "ACCOUNT_OTHER": [
        "USER_CREATE"
    ]
}
</code>```

I want to store this input as Map<Permission, Array<PermissionLevel>>

Following is my code

```<code>        // assume authJson is the input and is a valid JSON.
        this.userPermissions = new Map<Permission, Array<PermissionLevel>>();
        for (let [level, permissions] of Object.entries(authJson)) {
            let newLevel: PermissionLevel = <any>PermissionLevel[level];
            for (let perm of permissions) {
                let newPermission: Permission = <any>Permission[perm];
                if (this.userPermissions.get(newPermission)) {
                    this.userPermissions.set(newPermission, this.userPermissions.get(newPermission).concat(newLevel));
                } else {
                    this.userPermissions.set(newPermission, new Array<PermissionLevel>().concat(newLevel));
                }
            }
        }

        console.log(JSON.stringify(this.userPermissions));
</code>```

The output of the last statement is empty :(. Not sure what I'm doing wrong here.

Update: I just found there are run time errors line below

```<code>EXCEPTION: Uncaught (in promise): ReferenceError: PermissionLevel is not defined
</code>```

Here is a TS fiddle - https://jsfiddle.net/hrwyc6zv/1/

答:
Map object in javascript is not a JSON. Therefore JSON.stringify doesn't show its actual content.

Small test in Firefox:

```<code>var x = new Map()
x.set('a','b')
-> Map { a: "b" }
JSON.stringify(x)
-> "{}"
</code>```

Title: Convert string to enum in TypeScript

Body:
I'm using TypeScript 2.2.1 with target ES5

I have couple of enums like below

enum PermissionLevel {
    ACCOUNT_OWN,
    ACCOUNT_OTHER,
    USER_OWN
}

enum Permission {
    ACCOUNT_CREATE,
    USER_CREATE
}

I have a input JSON as below

{
    "ACCOUNT_OWN": [
        "USER_CREATE",
        "ACCOUNT_CREATE"
    ],
    "ACCOUNT_OTHER": [
        "USER_CREATE"
    ]
}

I want to store this input as Map<Permission, Array<PermissionLevel>>

Following is my code

        // assume authJson is the input and is a valid JSON.
        this.userPermissions = new Map<Permission, Array<PermissionLevel>>();
        for (let [level, permissions] of Object.entries(authJson)) {
            let newLevel: PermissionLevel = <any>PermissionLevel[level];
            for (let perm of permissions) {
                let newPermission: Permission = <any>Permission[perm];
                if (this.userPermissions.get(newPermission)) {
                    this.userPermissions.set(newPermission, this.userPermissions.get(newPermission).concat(newLevel));
                } else {
                    this.userPermissions.set(newPermission, new Array<PermissionLevel>().concat(newLevel));
                }
            }
        }

        console.log(JSON.stringify(this.userPermissions));

The output of the last statement is empty :(. Not sure what I'm doing wrong here.

Update: I just found there are run time errors line below

EXCEPTION: Uncaught (in promise): ReferenceError: PermissionLevel is not defined

Here is a TS fiddle - https://jsfiddle.net/hrwyc6zv/1/

Body:
Map object in javascript is not a JSON. Therefore JSON.stringify doesn't show its actual content.

Small test in Firefox:

var x = new Map()
x.set('a','b')
-> Map { a: "b" }
JSON.stringify(x)
-> "{}"


问:
Error bars for mean of x divided by mean of y
I have some data about fluorescence from different plants treated with different chemicals that make them fluoresce. In each treatment n=2, if that matters.

I am using a column graph to show the mean intensity of each treatment, divided by the control group.

```<code>        Intensity      Mean         SD
Treatment 1 6904890    6877987.5    26902.5
            6851085
Treatment 2 256275     298732.5     42457.5
            341190
Treatment 8 3692910    3671107.5    21802.5
            3649305
Treatment 9 1693710    1599232.5    94477.5
            1504755
</code>```

Now I want to plot four columns:

```<code>(Treatment1/Treatment1)
(Treatment2/Treatment1)
(Treatment3/Treatment1)
(Treatment4/Treatment1)
</code>```

where treatment1 is my control so I am "normalizing" or making my data relative to its value.

My question is what do I properly do with the error bars to show the most applicable measure of variance?

As simple as this question sounds, I can't find a straight forward answer.

答:
Take variance of the sample, divide by root N, then divide again by the value of treatment 1 to get your error.
However with N as low as 2 is doubtful that the error bars actually mean anything.</p>

Body:
I have some data about fluorescence from different plants treated with different chemicals that make them fluoresce. In each treatment n=2, if that matters.

I am using a column graph to show the mean intensity of each treatment, divided by the control group.

        Intensity      Mean         SD
Treatment 1 6904890    6877987.5    26902.5
            6851085
Treatment 2 256275     298732.5     42457.5
            341190
Treatment 8 3692910    3671107.5    21802.5
            3649305
Treatment 9 1693710    1599232.5    94477.5
            1504755

Now I want to plot four columns:

(Treatment1/Treatment1)
(Treatment2/Treatment1)
(Treatment3/Treatment1)
(Treatment4/Treatment1)

where treatment1 is my control so I am "normalizing" or making my data relative to its value.

My question is what do I properly do with the error bars to show the most applicable measure of variance?

As simple as this question sounds, I can't find a straight forward answer.


问:
Making sure the user enters a particular file type
I have a JFileChooser (not shown here) that takes a users file Input. I would like to make sure the user enters only a .txt file. Is there a function available that allows this to be verified with JFileChooser or another possible solution. I considered the following:

```<code>if (selectedFile != null && selectedFile.getName().endsWith(".txt")){
    //action
} else {
    JOptionPane.showMessageDialog(null, "You have not selected a .txt file. Please choose a correct file type to continue.);
}
</code>```

However, if it is possible, I would like for it to be the case that even if the file does not explicitly end with .txt in the name, it will still be accepted but it must still be a text file.

答:
See JavaDoc for using FileFilter with JFileChooser.

You need to implement custom FileFilter that not only will check the file name extension but also check if file content is a text.

Body:
I have a JFileChooser (not shown here) that takes a users file Input. I would like to make sure the user enters only a .txt file. Is there a function available that allows this to be verified with JFileChooser or another possible solution. I considered the following:

if (selectedFile != null && selectedFile.getName().endsWith(".txt")){
    //action
} else {
    JOptionPane.showMessageDialog(null, "You have not selected a .txt file. Please choose a correct file type to continue.);
}

However, if it is possible, I would like for it to be the case that even if the file does not explicitly end with .txt in the name, it will still be accepted but it must still be a text file.