问:
Spring Runtime Error - Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument
I've inherited a legacy Java app require JDK 7.

The app will compile, but I'm getting runtime errors which look like Hibernate entityManagerFactory issues.

The strange part is this app works on another developers machine. He even sent me his Tomcat directory, I have tried it on a Mac and on an Ubuntu machine. No matter where I run it, the runtime errors persist.

I think the problems is an init method in entityManagerFactory class,

```<code>Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Invocation of init method failed; nested exception is java.lang.NullPointerException
</code>```

pom.xml

PersistenceConfiguration Class:

```<code> * Copyright (c) 2014, German Federal Agency for Cartography and Geodesy
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.

 *     * Redistributions in binary form must reproduce the above
 *       copyright notice, this list of conditions and the following
 *       disclaimer in the documentation and/or other materials
 *       provided with the distribution.

 *     * The names "German Federal Agency for Cartography and Geodesy",
 *       "Bundesamt für Kartographie und Geodäsie", "BKG", "GDI-DE",
 *       "GDI-DE Registry" and the names of other contributors must not
 *       be used to endorse or promote products derived from this
 *       software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GERMAN
 * FEDERAL AGENCY FOR CARTOGRAPHY AND GEODESY BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */
package de.geoinfoffm.registry.persistence;

import java.sql.Connection;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.sql.DataSource;

import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.MigrationInfo;
import org.flywaydb.core.api.MigrationInfoService;
import org.flywaydb.core.api.callback.FlywayCallback;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import de.bespire.LoggerFactory;
import de.geoinfoffm.registry.core.Repository;
import de.geoinfoffm.registry.core.configuration.RegistryConfiguration;
import de.geoinfoffm.registry.persistence.jpa.HibernateConfiguration;

/**
 * Spring configuration class for the persistence layer.
 *
 * @author Florian Esser
 *
 */
@ComponentScan(basePackages = { "de.bespire.registry", "de.geoinfoffm.registry" })
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = { "de.bespire.registry", "de.geoinfoffm.registry" },
                       repositoryFactoryBeanClass = EntityBackendFactoryBean.class)
public class PersistenceConfiguration
{
    private static final Logger logger = LoggerFactory.make();

    @Autowired
    private Environment env;

    /**
     * Creates a {@link LocalContainerEntityManagerFactoryBean} that will handle the creation
     * of {@link EntityManager}s used by the {@link Repository}s of domain object {@link Repository}s.
     */
    @Autowired
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(HibernateConfiguration hibernateConfiguration, RegistryConfiguration registryConfiguration, DatabaseSchemaMangementService schemaManagementService) {
        // Handle schema migration before creating the EntityManagerFactoryBean
        final String flywayMigration = hibernateConfiguration.additionalParameters().getProperty("flyway.migration", "false").toString().toLowerCase();
        if ("true".equalsIgnoreCase(flywayMigration)) {
            schemaManagementService.analyze();
            schemaManagementService.migrate();
        }
        else if ("repair".equalsIgnoreCase(flywayMigration)) {
            schemaManagementService.repair();
        }
        else if ("repairAndMigrate".equalsIgnoreCase(flywayMigration)) {
            schemaManagementService.repairAndMigrate();
        }

        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource(hibernateConfiguration));
        em.setPackagesToScan(registryConfiguration.getBasePackages());
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(hibernateConfiguration.additionalParameters());

        return em;
    }

    @Autowired
    @Bean
    public LocalSessionFactoryBean sessionFactory(HibernateConfiguration hibernateConfiguration, RegistryConfiguration registryConfiguration) {
        LocalSessionFactoryBean result = new LocalSessionFactoryBean();
        result.setDataSource(dataSource(hibernateConfiguration));
        result.setPackagesToScan(registryConfiguration.getBasePackages());

        return result;
    }

    /**
     * @return the {@link DataSource} for the application, based on the connection properties
     */
    @Autowired
    @Bean
    public DataSource dataSource(HibernateConfiguration hibernateConfiguration) {
        return hibernateConfiguration.dataSource();
    }

    /**
     * @return the {@link PlatformTransactionManager} for the application
     */
    @Autowired
    @Bean
    public PlatformTransactionManager transactionManager(HibernateConfiguration hibernateConfiguration, RegistryConfiguration registryConfiguration, DatabaseSchemaMangementService schemaService) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory(hibernateConfiguration, registryConfiguration, schemaService).getObject());

        return transactionManager;
    }

    /**
     * @return the {@link PersistenceExceptionTranslationPostProcessor} for the application
     */
    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    @Autowired
    @Bean
    public DatabaseSchemaMangementService databaseSchemaMangementService(HibernateConfiguration hibernateConfiguration) {
        return new FlywayDatabaseSchemaManagementService(dataSource(hibernateConfiguration));
    }

}
</code>```

Log file

```<code>INFO: 2 Spring WebApplicationInitializers detected on classpath
Feb 14, 2020 12:28:42 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Feb 14, 2020 12:29:00 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class [org.springframework.web.context.ContextLoaderListener]
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'isoClientConfiguration': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Unsatisfied dependency expressed through method 'sessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateConfiguration' defined in class path resource [org/iso/registry/client/configuration/web/IsoClientHibernateConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metaDataSourceAdvisor': Cannot resolve reference to bean 'methodSecurityMetadataSource' while setting constructor argument; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration': Unsatisfied dependency expressed through method 'setPermissionEvaluator' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registryUserRepository': Cannot create inner bean '(inner bean)#7a511d1d' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#7a511d1d': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Invocation of init method failed; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1272)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:372)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1181)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1075)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.context.support.AbstractApplicationContext.initMessageSource(AbstractApplicationContext.java:713)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:531)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5195)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5720)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:1016)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:992)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:639)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1127)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:2020)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Unsatisfied dependency expressed through method 'sessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateConfiguration' defined in class path resource [org/iso/registry/client/configuration/web/IsoClientHibernateConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metaDataSourceAdvisor': Cannot resolve reference to bean 'methodSecurityMetadataSource' while setting constructor argument; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration': Unsatisfied dependency expressed through method 'setPermissionEvaluator' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registryUserRepository': Cannot create inner bean '(inner bean)#7a511d1d' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#7a511d1d': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Invocation of init method failed; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1181)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1075)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
    ... 36 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateConfiguration' defined in class path resource [org/iso/registry/client/configuration/web/IsoClientHibernateConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metaDataSourceAdvisor': Cannot resolve reference to bean 'methodSecurityMetadataSource' while setting constructor argument; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration': Unsatisfied dependency expressed through method 'setPermissionEvaluator' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registryUserRepository': Cannot create inner bean '(inner bean)#7a511d1d' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#7a511d1d': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Invocation of init method failed; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564)
    at
</code>```

Update - Looks like the problem is base packages are not found for this project.

The class that handles getting base packages - getBasePackages()
Of course, I don't know why this project is not finding base packages on my dev instance.

答:
There is a problem with existing code and handling string arrays.

Nothing wrong with Spring or Hibernate or pom file configurations.

Body:
I've inherited a legacy Java app require JDK 7.

The app will compile, but I'm getting runtime errors which look like Hibernate entityManagerFactory issues.

The strange part is this app works on another developers machine. He even sent me his Tomcat directory, I have tried it on a Mac and on an Ubuntu machine. No matter where I run it, the runtime errors persist.

I think the problems is an init method in entityManagerFactory class,

Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Invocation of init method failed; nested exception is java.lang.NullPointerException

pom.xml

PersistenceConfiguration Class:

 * Copyright (c) 2014, German Federal Agency for Cartography and Geodesy
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.

 *     * Redistributions in binary form must reproduce the above
 *       copyright notice, this list of conditions and the following
 *       disclaimer in the documentation and/or other materials
 *       provided with the distribution.

 *     * The names "German Federal Agency for Cartography and Geodesy",
 *       "Bundesamt für Kartographie und Geodäsie", "BKG", "GDI-DE",
 *       "GDI-DE Registry" and the names of other contributors must not
 *       be used to endorse or promote products derived from this
 *       software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GERMAN
 * FEDERAL AGENCY FOR CARTOGRAPHY AND GEODESY BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */
package de.geoinfoffm.registry.persistence;

import java.sql.Connection;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.sql.DataSource;

import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.MigrationInfo;
import org.flywaydb.core.api.MigrationInfoService;
import org.flywaydb.core.api.callback.FlywayCallback;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import de.bespire.LoggerFactory;
import de.geoinfoffm.registry.core.Repository;
import de.geoinfoffm.registry.core.configuration.RegistryConfiguration;
import de.geoinfoffm.registry.persistence.jpa.HibernateConfiguration;

/**
 * Spring configuration class for the persistence layer.
 *
 * @author Florian Esser
 *
 */
@ComponentScan(basePackages = { "de.bespire.registry", "de.geoinfoffm.registry" })
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = { "de.bespire.registry", "de.geoinfoffm.registry" },
                       repositoryFactoryBeanClass = EntityBackendFactoryBean.class)
public class PersistenceConfiguration
{
    private static final Logger logger = LoggerFactory.make();

    @Autowired
    private Environment env;

    /**
     * Creates a {@link LocalContainerEntityManagerFactoryBean} that will handle the creation
     * of {@link EntityManager}s used by the {@link Repository}s of domain object {@link Repository}s.
     */
    @Autowired
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(HibernateConfiguration hibernateConfiguration, RegistryConfiguration registryConfiguration, DatabaseSchemaMangementService schemaManagementService) {
        // Handle schema migration before creating the EntityManagerFactoryBean
        final String flywayMigration = hibernateConfiguration.additionalParameters().getProperty("flyway.migration", "false").toString().toLowerCase();
        if ("true".equalsIgnoreCase(flywayMigration)) {
            schemaManagementService.analyze();
            schemaManagementService.migrate();
        }
        else if ("repair".equalsIgnoreCase(flywayMigration)) {
            schemaManagementService.repair();
        }
        else if ("repairAndMigrate".equalsIgnoreCase(flywayMigration)) {
            schemaManagementService.repairAndMigrate();
        }

        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource(hibernateConfiguration));
        em.setPackagesToScan(registryConfiguration.getBasePackages());
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(hibernateConfiguration.additionalParameters());

        return em;
    }

    @Autowired
    @Bean
    public LocalSessionFactoryBean sessionFactory(HibernateConfiguration hibernateConfiguration, RegistryConfiguration registryConfiguration) {
        LocalSessionFactoryBean result = new LocalSessionFactoryBean();
        result.setDataSource(dataSource(hibernateConfiguration));
        result.setPackagesToScan(registryConfiguration.getBasePackages());

        return result;
    }

    /**
     * @return the {@link DataSource} for the application, based on the connection properties
     */
    @Autowired
    @Bean
    public DataSource dataSource(HibernateConfiguration hibernateConfiguration) {
        return hibernateConfiguration.dataSource();
    }

    /**
     * @return the {@link PlatformTransactionManager} for the application
     */
    @Autowired
    @Bean
    public PlatformTransactionManager transactionManager(HibernateConfiguration hibernateConfiguration, RegistryConfiguration registryConfiguration, DatabaseSchemaMangementService schemaService) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory(hibernateConfiguration, registryConfiguration, schemaService).getObject());

        return transactionManager;
    }

    /**
     * @return the {@link PersistenceExceptionTranslationPostProcessor} for the application
     */
    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    @Autowired
    @Bean
    public DatabaseSchemaMangementService databaseSchemaMangementService(HibernateConfiguration hibernateConfiguration) {
        return new FlywayDatabaseSchemaManagementService(dataSource(hibernateConfiguration));
    }

}

Log file

INFO: 2 Spring WebApplicationInitializers detected on classpath
Feb 14, 2020 12:28:42 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Feb 14, 2020 12:29:00 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class [org.springframework.web.context.ContextLoaderListener]
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'isoClientConfiguration': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Unsatisfied dependency expressed through method 'sessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateConfiguration' defined in class path resource [org/iso/registry/client/configuration/web/IsoClientHibernateConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metaDataSourceAdvisor': Cannot resolve reference to bean 'methodSecurityMetadataSource' while setting constructor argument; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration': Unsatisfied dependency expressed through method 'setPermissionEvaluator' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registryUserRepository': Cannot create inner bean '(inner bean)#7a511d1d' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#7a511d1d': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Invocation of init method failed; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1272)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:372)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1181)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1075)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.context.support.AbstractApplicationContext.initMessageSource(AbstractApplicationContext.java:713)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:531)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5195)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5720)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:1016)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:992)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:639)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1127)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:2020)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Unsatisfied dependency expressed through method 'sessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateConfiguration' defined in class path resource [org/iso/registry/client/configuration/web/IsoClientHibernateConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metaDataSourceAdvisor': Cannot resolve reference to bean 'methodSecurityMetadataSource' while setting constructor argument; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration': Unsatisfied dependency expressed through method 'setPermissionEvaluator' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registryUserRepository': Cannot create inner bean '(inner bean)#7a511d1d' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#7a511d1d': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Invocation of init method failed; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1181)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1075)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
    ... 36 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateConfiguration' defined in class path resource [org/iso/registry/client/configuration/web/IsoClientHibernateConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metaDataSourceAdvisor': Cannot resolve reference to bean 'methodSecurityMetadataSource' while setting constructor argument; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration': Unsatisfied dependency expressed through method 'setPermissionEvaluator' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registryUserRepository': Cannot create inner bean '(inner bean)#7a511d1d' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#7a511d1d': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Invocation of init method failed; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564)
    at

Update - Looks like the problem is base packages are not found for this project.

The class that handles getting base packages - getBasePackages()
Of course, I don't know why this project is not finding base packages on my dev instance.


来源: stackexchange

问:
Salesforce Table Relationships for Business Analyst
I am a business analyst. I use Tableau a lot but have limited knowledge about the back-end of Salesforce. The majority of our company's data is stored in Salesforce and our data team does not support business users for understanding such topics.

In many of my projects, I use the Salesforce connector inside Tableau to extract Salesforce tables, but it requires knowledge about joins relationships among tables. Most of the time, I can guess correctly about the primary key among tables, but I still want to learn systematically about the data structure and have my data independence.

So, how do I learn the data structure by myself? Or how do I ask specific structure questions to data team so I don't trouble them as much?

答:
If your job is to build advanced reports off these data sources, I would imagine you need to understand the data structure to some extent. This would mean you need to have authorization to view and access the database table list to get familiar with it and possibly run raw queries to verify data integrity.

If they are not comfortable with you touching the production system, ask for access to a development system which is a copy of production or even just realistic test data.

ContentLicense: CC BY-SA 4.0


问:
React-Native: Warning: React state update on an unmounted component
I have probleme with React-Native (I use Expo).

I pass a function in componentDidMount() which makes a call to action (redux) to retrieve data from the API.

When I close the application and I open it's again, I have this error:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in %s.%s, the componentWillUnmount method

I tried several methods like this :

https://github.com/material-components/material-components-web-react/issues/434

React-Native: Warning: Can't perform a React state update on an unmounted component

And other similair methods that I found on Stack overflow, but nothing works and the error is still present.

Anybody had this problem before ?

Could you please help me to resolve  this problem ?

答:
I am not sure the react-native would be the same issue as I had with reactjs, but when on my react app it was complaining the memory leak error I just had to add AbortController().

You can try something like this

```<code>abortController = new AbortController();

componentDidMount() {
    fetch('url', {
      signal: this.abortController.signal,
    }).then((res) => {
      // do something
    }).catch((err) => {
        if (err.name === 'AbortError') {
          // throw error;
        }
    })

    componentWillUnmount() {
      this.abortController.abort();
    }
}
</code>```

Hope this helps.

Body:
I am not sure the react-native would be the same issue as I had with reactjs, but when on my react app it was complaining the memory leak error I just had to add AbortController().

You can try something like this

abortController = new AbortController();

componentDidMount() {
    fetch('url', {
      signal: this.abortController.signal,
    }).then((res) => {
      // do something
    }).catch((err) => {
        if (err.name === 'AbortError') {
          // throw error;
        }
    })

    componentWillUnmount() {
      this.abortController.abort();
    }
}

Hope this helps.


问:
Socket Hang Up when using https.request in node.js
When using https.request with node.js v04.7, I get the following error:

```<code>Error: socket hang up
    at CleartextStream.<anonymous> (http.js:1272:45)
    at CleartextStream.emit (events.js:61:17)
    at Array.<anonymous> (tls.js:617:22)
    at EventEmitter._tickCallback (node.js:126:26)
</code>```

Simplified code that will generate the error:

```<code>var https = require('https')
  , fs    = require('fs')

var options = {
  host: 'localhost'
, port: 8000
, key: fs.readFileSync('../../test-key.pem')
, cert: fs.readFileSync('../../test-cert.pem')
}

// Set up server and start listening
https.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'})
  res.end('success')
}).listen(options.port, options.host)

// Wait a second to let the server start up
setTimeout(function() {
  var clientRequest = https.request(options, function(res) {
    res.on('data', function (chunk) {
      console.log('Called')
    })
  })

  clientRequest.write('')
  clientRequest.end()
}, 1000)
</code>```

I get the error even with the server and client running on different node instances and have tested with port 8000, 3000, and 443 and with and without the SSL certificates. I do have libssl and libssl-dev on my Ubuntu machine.

Any ideas on what could be the cause?

答:
Short answer: Use the the latest source code instead of the one you have. Store it where you will and then require it, you are good to go.

In the request 1.2.0 source code, main.js line 76, I see

```<code>http.createClient(options.uri.port, options.uri.hostname, options.uri.protocol === 'https:');
</code>```

Looking at the http.js source code, I see

```<code>exports.createClient = function(port, host) {
  var c = new Client();
  c.port = port;
  c.host = host;
  return c;
};
</code>```

It is requesting with 3 params but the actual function only has 2. The functionality is replaced with a separate module for https.

Looking at the latest main.js source code, I see dramatic changes. The most important is the addition of require('https').

It appears that request has been fixed but never re-released. Fortunately, the fix seems to work if you just copy manually from the raw view of the latest main.js source code and use it instead.

ContentLicense: CC BY-SA 3.0

Body:
When using https.request with node.js v04.7, I get the following error:

Error: socket hang up
    at CleartextStream.<anonymous> (http.js:1272:45)
    at CleartextStream.emit (events.js:61:17)
    at Array.<anonymous> (tls.js:617:22)
    at EventEmitter._tickCallback (node.js:126:26)

Simplified code that will generate the error:

var https = require('https')
  , fs    = require('fs')

var options = {
  host: 'localhost'
, port: 8000
, key: fs.readFileSync('../../test-key.pem')
, cert: fs.readFileSync('../../test-cert.pem')
}

// Set up server and start listening
https.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'})
  res.end('success')
}).listen(options.port, options.host)

// Wait a second to let the server start up
setTimeout(function() {
  var clientRequest = https.request(options, function(res) {
    res.on('data', function (chunk) {
      console.log('Called')
    })
  })

  clientRequest.write('')
  clientRequest.end()
}, 1000)

I get the error even with the server and client running on different node instances and have tested with port 8000, 3000, and 443 and with and without the SSL certificates. I do have libssl and libssl-dev on my Ubuntu machine.

Any ideas on what could be the cause?

Body:
Short answer: Use the the latest source code instead of the one you have. Store it where you will and then require it, you are good to go.

In the request 1.2.0 source code, main.js line 76, I see

http.createClient(options.uri.port, options.uri.hostname, options.uri.protocol === 'https:');

Looking at the http.js source code, I see

exports.createClient = function(port, host) {
  var c = new Client();
  c.port = port;
  c.host = host;
  return c;
};

It is requesting with 3 params but the actual function only has 2. The functionality is replaced with a separate module for https.

Looking at the latest main.js source code, I see dramatic changes. The most important is the addition of require('https').

It appears that request has been fixed but never re-released. Fortunately, the fix seems to work if you just copy manually from the raw view of the latest main.js source code and use it instead.


问:
When creating a new element my foreignKey is always null. Sequelize, Node, Postgresql
I currently have a User model and a Team model that I want to associate.

User.js Model

```<code>"use strict";
module.exports = sequelize => {
  const User = sequelize.define(
    "User",
    {
      id: {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV1,
        primaryKey: true,
        allowNull: false
      },
        ...more fields
    }
    { tableName: "Users", timestamps: true }
  );

User.associate = function(models) {
    // 1 to many with skill
    User.hasMany(models.Skill, {
      foreignKey: "userId"
    });
    // 1 to many with team
    User.hasMany(models.Team, {
      foreignKey: "userId"
    });
  };

  return User;
};
</code>```

Team.js Model

```<code>"use strict";
module.exports = (sequelize, DataTypes) => {
  const Team = sequelize.define(
    "Team",
    {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: DataTypes.INTEGER
      },
      ...more fields
    },
    { tableName: "Teams", timestamps: true }
  );

  Team.associate = function(models) {

    Team.belongsTo(models.User, {
      foreignKey: "userId"
    });
  };
  return Team;
};
</code>```

The column userId is automatically added to the team's table with the correct type (uuid) but no matter what I try it's always null.

I have tried just defining without options, and again the column was added, but set to null when a team was created.

1). Define the associations with no options.

```<code>User.associate = function(models) {
    User.hasMany(models.Team);
}
</code>```

Also, I have another table "Skills" that uses the same code but it works.

```<code>"use strict";
module.exports = (sequelize, DataTypes) => {
  const Skill = sequelize.define(
    "Skill",
    {
      id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        autoIncrement: true,
        primaryKey: true
      },
    },
    { tableName: "Skills", timestamps: true }
  );

  Skill.associate = models => {
    Skill.belongsTo(models.User, {
      foreignKey: "userId"
    });
  };

  return Skill;
};
</code>```

This is the method i'm using to create the team.

```<code>// Create a new team
exports.createTeam = async (req, res) => {
  // Get the user id from the session
  const userId = req.session.passport.user.id;

  const { title } = req.body;

  // Make sure the user hasn't already created a team with that title.
  const existingTeam = await models.Team.findOne({
    where: { title: title, userId: userId }
  });

  if (existingTeam !== null) {
    // Response and let the user know.
    ...
    return;
  }

  const defaultTeamValues = {
    title: title,
    ...
  };

  // No existing team was found with that title and created by that user.

  // Create it.
  const team = await models.Team.create(defaultTeamValues);

  // Done
  res.status(200).json(team);
};
</code>```

New record in Team's table showing null value in foreign key (userId) column.

I'm using pgAdmin 4 to view the tables and each table has the correct constraints fkeys too.

I feel like I'm missing something simple here, but I've read the docs and searched for similar issues but haven't found what I needed. What am I missing?

答:
Ok, so I sort of figured out the problem. Instead of using

```<code>// Look for existing team
const existingTeam = await models.Team.findOne({
  where: { title: title, userId: userId }
});

if (existingTeam !== null) {
  ...
  return;
}

// No existing team was found with that title and created by that user.

// Create it.
const team = await models.Team.create(defaultTeamValues);
</code>```

I switch to this method.

```<code>const team = await models.Team.findOrCreate({
    where: {
      title: title,
      userId: userId
    },
    // title and userId will be appended to defaults on create.
    defaults: defaultTeamValues
  });
</code>```

The difference being that findOrCreate will append, the values in the where query, to the default values you provide.

This is what I did previously when adding new skills and that's why my Skills records had the userId and Teams did not.

So at this point, I don't know if my associations are even working because I'm actually just adding the userId value into the new record.

Back to reading the docs and testing.

Body:
I currently have a User model and a Team model that I want to associate.

User.js Model

"use strict";
module.exports = sequelize => {
  const User = sequelize.define(
    "User",
    {
      id: {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV1,
        primaryKey: true,
        allowNull: false
      },
        ...more fields
    }
    { tableName: "Users", timestamps: true }
  );

User.associate = function(models) {
    // 1 to many with skill
    User.hasMany(models.Skill, {
      foreignKey: "userId"
    });
    // 1 to many with team
    User.hasMany(models.Team, {
      foreignKey: "userId"
    });
  };

  return User;
};

Team.js Model

"use strict";
module.exports = (sequelize, DataTypes) => {
  const Team = sequelize.define(
    "Team",
    {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: DataTypes.INTEGER
      },
      ...more fields
    },
    { tableName: "Teams", timestamps: true }
  );

  Team.associate = function(models) {

    Team.belongsTo(models.User, {
      foreignKey: "userId"
    });
  };
  return Team;
};

The column userId is automatically added to the team's table with the correct type (uuid) but no matter what I try it's always null.

I have tried just defining without options, and again the column was added, but set to null when a team was created.

1). Define the associations with no options.

User.associate = function(models) {
    User.hasMany(models.Team);
}

Also, I have another table "Skills" that uses the same code but it works.

"use strict";
module.exports = (sequelize, DataTypes) => {
  const Skill = sequelize.define(
    "Skill",
    {
      id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        autoIncrement: true,
        primaryKey: true
      },
    },
    { tableName: "Skills", timestamps: true }
  );

  Skill.associate = models => {
    Skill.belongsTo(models.User, {
      foreignKey: "userId"
    });
  };

  return Skill;
};

This is the method i'm using to create the team.

// Create a new team
exports.createTeam = async (req, res) => {
  // Get the user id from the session
  const userId = req.session.passport.user.id;

  const { title } = req.body;

  // Make sure the user hasn't already created a team with that title.
  const existingTeam = await models.Team.findOne({
    where: { title: title, userId: userId }
  });

  if (existingTeam !== null) {
    // Response and let the user know.
    ...
    return;
  }

  const defaultTeamValues = {
    title: title,
    ...
  };

  // No existing team was found with that title and created by that user.

  // Create it.
  const team = await models.Team.create(defaultTeamValues);

  // Done
  res.status(200).json(team);
};

New record in Team's table showing null value in foreign key (userId) column.

I'm using pgAdmin 4 to view the tables and each table has the correct constraints fkeys too.

I feel like I'm missing something simple here, but I've read the docs and searched for similar issues but haven't found what I needed. What am I missing?

Body:
Ok, so I sort of figured out the problem. Instead of using

// Look for existing team
const existingTeam = await models.Team.findOne({
  where: { title: title, userId: userId }
});

if (existingTeam !== null) {
  ...
  return;
}

// No existing team was found with that title and created by that user.

// Create it.
const team = await models.Team.create(defaultTeamValues);

I switch to this method.

const team = await models.Team.findOrCreate({
    where: {
      title: title,
      userId: userId
    },
    // title and userId will be appended to defaults on create.
    defaults: defaultTeamValues
  });

The difference being that findOrCreate will append, the values in the where query, to the default values you provide.

This is what I did previously when adding new skills and that's why my Skills records had the userId and Teams did not.

So at this point, I don't know if my associations are even working because I'm actually just adding the userId value into the new record.

Back to reading the docs and testing.


问:
Why would Airflow Scheduler only work as a non-daemon process but fail as a daemon process?
I have set up airflow on an Ubuntu server. I started the webserver just fine as a daemon process. I can start the scheduler using

```<code>airflow scheduler
</code>```

and it works fine and the dags run. I then stop it and remove all the airflow-scheduler files in $AIRFLOW_HOME (airflow-scheduler.err, airflow-scheduler.log, airflow-scheduler.out)

I then try to start it as a daemon process using

```<code>airflow scheduler -D
</code>```

It appears to start okay without error. However when I got to the webserver it says:

"The scheduler does not appear to be running. Last heartbeat was received 2 minutes ago.

The DAGs list may not update, and new tasks will not be scheduled."

When I look in airflow-scheduler.err I see:

```<code>Traceback (most recent call last):
  File "/home/emauser/.local/lib/python3.6/site-packages/sqlalchemy/pool/base.py", line 503, in <lambda>
  File "/home/emauser/.local/lib/python3.6/site-packages/sqlalchemy/pool/base.py", line 702, in _finalize_fairy
  File "/usr/lib/python3.6/logging/__init__.py", line 1337, in error
  File "/usr/lib/python3.6/logging/__init__.py", line 1444, in _log
  File "/usr/lib/python3.6/logging/__init__.py", line 1454, in handle
  File "/usr/lib/python3.6/logging/__init__.py", line 1516, in callHandlers
  File "/usr/lib/python3.6/logging/__init__.py", line 865, in handle
  File "/usr/lib/python3.6/logging/__init__.py", line 1071, in emit
  File "/usr/lib/python3.6/logging/__init__.py", line 1061, in _open
NameError: name 'open' is not defined
</code>```

Any idea why I'm getting an error on the built-in open function from the logging module?

答:
Before restarting your scheduler in daemon mode, make sure no other scheduler process are running.
ps aux | grep airflow-scheduler

If there are any , kill them and then start your scheduler as a daemon .

Body:
I have set up airflow on an Ubuntu server. I started the webserver just fine as a daemon process. I can start the scheduler using

airflow scheduler

and it works fine and the dags run. I then stop it and remove all the airflow-scheduler files in $AIRFLOW_HOME (airflow-scheduler.err, airflow-scheduler.log, airflow-scheduler.out)

I then try to start it as a daemon process using

airflow scheduler -D

It appears to start okay without error. However when I got to the webserver it says:

"The scheduler does not appear to be running. Last heartbeat was received 2 minutes ago.

The DAGs list may not update, and new tasks will not be scheduled."

When I look in airflow-scheduler.err I see:

Traceback (most recent call last):
  File "/home/emauser/.local/lib/python3.6/site-packages/sqlalchemy/pool/base.py", line 503, in <lambda>
  File "/home/emauser/.local/lib/python3.6/site-packages/sqlalchemy/pool/base.py", line 702, in _finalize_fairy
  File "/usr/lib/python3.6/logging/__init__.py", line 1337, in error
  File "/usr/lib/python3.6/logging/__init__.py", line 1444, in _log
  File "/usr/lib/python3.6/logging/__init__.py", line 1454, in handle
  File "/usr/lib/python3.6/logging/__init__.py", line 1516, in callHandlers
  File "/usr/lib/python3.6/logging/__init__.py", line 865, in handle
  File "/usr/lib/python3.6/logging/__init__.py", line 1071, in emit
  File "/usr/lib/python3.6/logging/__init__.py", line 1061, in _open
NameError: name 'open' is not defined

Any idea why I'm getting an error on the built-in open function from the logging module?


问:
deoplete completion from other file types
I'm trying to use deoplete for completion and found a problem: deoplete by default doesn't complete using data from all opened files. For example, when I edit JavaScript, HTML and CSS files I can't complete word in JS file from HTML file.

I tried to put in init.vim:

```<code>call deoplete#custom#source('require_same_filetype', 0)
let g:deoplete#buffer#require#same_filetype = 0
</code>```

Also, I tried to use Shougo/context_filetype.vim, but it didn't solve the problem.

答:
Shugo wrote something like that here:

```<code>call deoplete#custom#var('buffer', 'require_same_filetype', v:false)
</code>```

Hopefully it'll help.

Body:
I'm trying to use deoplete for completion and found a problem: deoplete by default doesn't complete using data from all opened files. For example, when I edit JavaScript, HTML and CSS files I can't complete word in JS file from HTML file.

I tried to put in init.vim:

call deoplete#custom#source('require_same_filetype', 0)
let g:deoplete#buffer#require#same_filetype = 0

Also, I tried to use Shougo/context_filetype.vim, but it didn't solve the problem.

Body:
Shugo wrote something like that here:

call deoplete#custom#var('buffer', 'require_same_filetype', v:false)

Hopefully it'll help.


问:
How to make a RectTransform follow another RectTransform that is located under a different parent?
I am trying to make a RectTransform with default anchor settings follow a RectTransform that is right-bottom aligned non-stretch. However, there is always an offset between them.

I have tried GetWorldRect().center and transform it into a WorldPoint with no luck. Using transform. position only works when both UIElements are anchored with default values.

Can anyone help fill the following method body?

```<code>public static void FollowRectTransform(this RectTransform source, RectTransform target)
{
}
</code>```

答: You can use the Parent Constraint component to make one Gameobject act as though it is the child of another GameObject for purposes of positioning and scale, including RectTransform.</p>

Body:
I am trying to make a RectTransform with default anchor settings follow a RectTransform that is right-bottom aligned non-stretch. However, there is always an offset between them.

I have tried GetWorldRect().center and transform it into a WorldPoint with no luck. Using transform. position only works when both UIElements are anchored with default values.

Can anyone help fill the following method body?

public static void FollowRectTransform(this RectTransform source, RectTransform target)
{
}


问:
Excelsheet in xlsxwriter
I want to create a workbook and worksheet once using xlsxwriter outside my function, as I am calling my function from a robot framework to insert the items in excel.

However, my code gives me an error.

class writetoexcel:

    workbook = xlsxwriter.Workbook('Example2.xlsx')
    worksheet = workbook.add_worksheet()

    def my_func(self, value, count):
        print(value)

        row = 0
        column = 1
        # worksheet.write_string(row, column, value)

        for item in value:
            worksheet.write_string(row, column, item)
            worksheet.write_string(row, column, item)

            row += 1

        workbook.close()
```

答:
You are getting an error because you are trying to initiate the xlsxwriter outside of the function or of the init method. This is your corrected code:

```<code>import xlsxwriter

class writetoexcel:

    def my_func(self, value):
        workbook = xlsxwriter.Workbook('Example2.xlsx')
        worksheet = workbook.add_worksheet()

        print(value)
        row = 0
        column = 1

        for item in value:
            worksheet.write_string(row, column, item)
            row += 1

        workbook.close()
</code>```

Then you need to create an object:

```<code>myworkbook = writetoexcel()
</code>```

And finally call its method we created:

```<code>myworkbook.my_func('abcd')
</code>```

Output:

Finally i think this code is a better approach if you want to handle the workbooks as objects:

```<code>class writetoexcel:

    def __init__(self):
        self.workbook = xlsxwriter.Workbook('Example2.xlsx')
        self.worksheet = self.workbook.add_worksheet()

    def my_func(self, value):
        row = 0
        column = 1

        for item in value:
            self.worksheet.write_string(row, column, item)
            row += 1

        self.workbook.close()
</code>```

Title: Excelsheet in xlsxwriter

Body:
You are getting an error because you are trying to initiate the xlsxwriter outside of the function or of the init method. This is your corrected code:

import xlsxwriter

class writetoexcel:

    def my_func(self, value):
        workbook = xlsxwriter.Workbook('Example2.xlsx')
        worksheet = workbook.add_worksheet()

        print(value)
        row = 0
        column = 1

        for item in value:
            worksheet.write_string(row, column, item)
            row += 1

        workbook.close()

Then you need to create an object:

myworkbook = writetoexcel()

And finally call its method we created:

myworkbook.my_func('abcd')

Output:

Finally i think this code is a better approach if you want to handle the workbooks as objects:

class writetoexcel:

    def __init__(self):
        self.workbook = xlsxwriter.Workbook('Example2.xlsx')
        self.worksheet = self.workbook.add_worksheet()

    def my_func(self, value):
        row = 0
        column = 1

        for item in value:
            self.worksheet.write_string(row, column, item)
            row += 1

        self.workbook.close()


问:
Searching through Array in javascript based on user input
Hey guys im trying to search through an array and display the search results base on the user input

A runthrough of my program is to read in an array of student name and their marks and determine their grades. Afterwhich, I want to search for a student and display his name, mark and grades.

Currently what I have so far is always printing student not found.

```<code>"use strict"
const readline = require('readline-sync');

var name, marks;
var studentList = [];

input();
search();

function printList(list) {
    for (const entry of list) {
        // Get a local for `marks` via destructuring
        const {marks} = entry;
        if (marks > 100 || marks < 0) {
            throw new Error(`Invalid 'marks' value: ${marks}`);
        } else if (marks >= 80) {
            entry.grade = 'HD'
        } else if (marks >= 70) {
            entry.grade = 'D'
        } else if (marks >= 60) {
            entry.grade = 'C'
        } else if (marks >= 51) {
            entry.grade = 'P'
        } else { // No `if (marks >= 0)` because we know it is, otherwise we would have thrown an error above
            entry.grade = 'N'
        }
        console.log(entry);
    }

function searchStudent(searchName){
    for (let i = 0; i<= studentList.length; i++){
        if(studentList[i] == searchName){
            console.log(studentList[i]);
        }
        else {
            console.log("student not found");
        }
    }
}

function input() {

    while (true)
    {
        console.log('Please enter the student name (or "end" to end): ');
        const name = readline.question('Student Name: ');
        if (name === 'end')
        {
            printList(studentList);
            break;
        }
        console.log('Student Name is' , name);
        const marks = readline.question('Enter marks for ' + name + ': ');
        if (marks === 'end')
        {
            printList(studentList);
            break;
        }
        console.log('Marks for ' + name + ' are ' + marks );
        studentList.push({name:name, marks: parseFloat(marks)});
    }
}

function search() {
    while (true)
    {
        console.log('Please enter the name of student to search for: (or "stop" to end search): ');
        const searchName= readline.question("Student Name: ");

        if(searchName === 'stop'){
            break;
        }
    searchStudent(searchName);
    }
}
</code>```

答:
You need to fix these:

Replace for (let i = 0; i <= studentList.length; i++) { with for (let i = 0; i < studentList.length; i++) { so it does not try to access a non-existent index. e.g. if studentList is an array of length 4, the indexes only go from 0 to 3

Change if (studentList[i] == searchName) { to if (studentList[i].name == searchName) {. Otherwise you are comparing an object with a string.

What your code does is it loops through all elements in the studentList and for every entry that is not the searchName, it prints 'student not found'. You only want to print 'student not found' after you have looped through all the list items.

If do you find the student you were finding for, exit the function early with a return keyword.

So your code should look like this:

```<code>function searchStudent(searchName) {
  for (let i = 0; i < studentList.length; i++) {
    if (studentList[i].name == searchName) {
      console.log(studentList[i]);
      return;
    }
  }
  console.log('student not found');
}
</code>```

Here is another way of doing the same thing:

```<code>function searchStudent(searchName) {
  const student = studentList.find(student => student.name === searchName);
  if (!student) {
    console.log('student not found');
    return;
  }
  console.log(student);
}
</code>```

Body:
Hey guys im trying to search through an array and display the search results base on the user input

A runthrough of my program is to read in an array of student name and their marks and determine their grades. Afterwhich, I want to search for a student and display his name, mark and grades.

Currently what I have so far is always printing student not found.

"use strict"
const readline = require('readline-sync');

var name, marks;
var studentList = [];

input();
search();

function printList(list) {
    for (const entry of list) {
        // Get a local for `marks` via destructuring
        const {marks} = entry;
        if (marks > 100 || marks < 0) {
            throw new Error(`Invalid 'marks' value: ${marks}`);
        } else if (marks >= 80) {
            entry.grade = 'HD'
        } else if (marks >= 70) {
            entry.grade = 'D'
        } else if (marks >= 60) {
            entry.grade = 'C'
        } else if (marks >= 51) {
            entry.grade = 'P'
        } else { // No `if (marks >= 0)` because we know it is, otherwise we would have thrown an error above
            entry.grade = 'N'
        }
        console.log(entry);
    }

function searchStudent(searchName){
    for (let i = 0; i<= studentList.length; i++){
        if(studentList[i] == searchName){
            console.log(studentList[i]);
        }
        else {
            console.log("student not found");
        }
    }
}

function input() {

    while (true)
    {
        console.log('Please enter the student name (or "end" to end): ');
        const name = readline.question('Student Name: ');
        if (name === 'end')
        {
            printList(studentList);
            break;
        }
        console.log('Student Name is' , name);
        const marks = readline.question('Enter marks for ' + name + ': ');
        if (marks === 'end')
        {
            printList(studentList);
            break;
        }
        console.log('Marks for ' + name + ' are ' + marks );
        studentList.push({name:name, marks: parseFloat(marks)});
    }
}

function search() {
    while (true)
    {
        console.log('Please enter the name of student to search for: (or "stop" to end search): ');
        const searchName= readline.question("Student Name: ");

        if(searchName === 'stop'){
            break;
        }
    searchStudent(searchName);
    }
}

Body:
You need to fix these:

Replace for (let i = 0; i <= studentList.length; i++) { with for (let i = 0; i < studentList.length; i++) { so it does not try to access a non-existent index. e.g. if studentList is an array of length 4, the indexes only go from 0 to 3

Change if (studentList[i] == searchName) { to if (studentList[i].name == searchName) {. Otherwise you are comparing an object with a string.

What your code does is it loops through all elements in the studentList and for every entry that is not the searchName, it prints 'student not found'. You only want to print 'student not found' after you have looped through all the list items.

If do you find the student you were finding for, exit the function early with a return keyword.

So your code should look like this:

function searchStudent(searchName) {
  for (let i = 0; i < studentList.length; i++) {
    if (studentList[i].name == searchName) {
      console.log(studentList[i]);
      return;
    }
  }
  console.log('student not found');
}

Here is another way of doing the same thing:

function searchStudent(searchName) {
  const student = studentList.find(student => student.name === searchName);
  if (!student) {
    console.log('student not found');
    return;
  }
  console.log(student);
}


问:
Google Sheets Time tracking formula
I'm trying to build a formula that looks across input data from one sheet (range C5:I52) and categorize it in another. It is a time tracking sheet.
What I am trying to achieve is one sheet with input data, per 30 minutes, where I can put in for example Netflix from 22:00 to 23:00 in cell C49 & C50, and have in sheet2 Netflix added as a category under a value ranging from a dollar amount.

For example, Netflix would be a category under maybe $10 (not making traction to my goals - therefore a low value).

What I have tried is to create a LookUp formula with premade categories (e.g. for $10 maybe Netflix, and for $0 maybe Instagram, Snapchat, and other 'useless' activities) but I can't seem to get it to work. It would search how many times it can maybe find Snapchat in cells C5:I52 and then have that amount (let's say Netflix found 2 times - meaning 2 times 30 minutes - is 1 hour total) times $5, so if I would spend 1 hour a day on Netflix it would value my total activity for that week at $70.

The main things are to 1. search the amount of times a premade activities is found and 2. have that amount be a number (say if found 4 times it would be 30 minutes * 4 = 2 hours) and maybe have it 4 * $5 resulting in a $20 value for that category.

Hopefully, someone can help. The total value in dollar amount is a different column, on the right to the category. So let's say under column $10 it would say Snapchat in column D under $0, and column E is the amount of Hours in a dollar amount being Value. Then column F would be $10, column G value, etc.

The goal is to manually log time through an Input sheet, and have it valued automatically in an Output sheet.

答:
this is how you get the duration of spent time for each category:

```<code>=ARRAYFORMULA(IFNA(VLOOKUP(B5:B28, TEXT(SORTN(SORT({'Time Input'!C5:C52,
 MMULT(N(TRANSPOSE(IF((TRANSPOSE(ROW('Time Input'!C5:C52))>=
 ROW('Time Input'!C5:C52))*('Time Input'!C5:C52=TRANSPOSE('Time Input'!C5:C52)),
 TIMEVALUE("00:30"), 0))), ROW('Time Input'!C5:C52)^0),
 ROW('Time Input'!C5:C52)}, 3, 0), 49, 2, 1, 0), "[h]:mm"), 2, 0)))
</code>```

where time input sheet is:

Title: Google Sheets Time tracking formula

Body:
this is how you get the duration of spent time for each category:

=ARRAYFORMULA(IFNA(VLOOKUP(B5:B28, TEXT(SORTN(SORT({'Time Input'!C5:C52,
 MMULT(N(TRANSPOSE(IF((TRANSPOSE(ROW('Time Input'!C5:C52))>=
 ROW('Time Input'!C5:C52))*('Time Input'!C5:C52=TRANSPOSE('Time Input'!C5:C52)),
 TIMEVALUE("00:30"), 0))), ROW('Time Input'!C5:C52)^0),
 ROW('Time Input'!C5:C52)}, 3, 0), 49, 2, 1, 0), "[h]:mm"), 2, 0)))

where time input sheet is:


问:
Migrate a SharePoint 2013 WSP (web part) to SharePoint 2019 (On-Prem)
I'm fairly new to SP 2019 (On-prem), but haven't had much luck finding information regarding moving a SP13 web part to SP 2019. It looks like I may have to recreate it using the SharePoint Framework. Does anyone have experience with migrating an existing SP 2013 webpart successfully to SP 2019 (on-prem) or is the Framework the only way to do that now?</p>

答:
As long as you stick with classic-mode sites, you don't have to change a thing.  SharePoint already has .NET Assembly redirects in place so that anything .NET assembly trying to reference the SP2013 or SP2016 .dll's will be directed to the SP2019 .dll's.

We just finished upgrading an Enterprise customer who has 30+ complex .wsp solution packages utilized across 2,000+ sites from SP2013 to SP2019.  The only solution packages we had to make modifications to were ones that dependencies on Third-party purchased products.  But we kept every migrated site in classic mode to achieve this.

Now, if you want to use the Modern UI on any of your SharePoint 2019 sites, depending on what your customization are, there is a high probability that they will not work.  If they are purely back-end Event Receiver and Timer Job type customizations, they may still work, but if they have any type of UI customizations, they will definitely break in the new Modern interface.  For front-end user-interface customizations, you would have to re-build your solution using the SharePoint Framework.


问:
Access ListViewItem information from MenuItem in ContextMenu
I have a ListView with several items. I would like to copy in the system clipboard, information associated to a given row (e.g. id of the item in that row).

I have created a ContextMenu that opens when right clicking a row, and it displays a MenuItem to copy the id:

```<code><ListView x:Name="MyListView" MouseDoubleClick="MyListView_MouseDoubleClick">
    <ListView.Columns>
        <GridViewColumn Header="Id" DisplayMemberBinding="{Binding MyItem.Id}"/>
    </ListView.Columns>
    <ListView.ItemTemplate>
        <HierarchicalDataTemplate DataType="{x:Type mynamespace:MyItemDefinition}" ItemsSource="{Binding MyGroupOfItems, Mode=OneWay}" />
    </ListView.ItemTemplate>
    <ListView.ContextMenu>
        <ContextMenu>
            <MenuItem x:Name="MenuItemCopyId" Header="Copy ID" Click="MenuItemCopyId_Click"/>
        </ContextMenu>
    </ListView.ContextMenu>
</ListView>
</code>```

and

```<code>private void MenuItemCopyId_Click(object sender, RoutedEventArgs e)
{
     var menu_item = ((System.Windows.Controls.MenuItem)sender);
}
</code>```

For what I read (ListViewItem Context Menu Get Data from ListViewItem) it needs to access the DataContext of the item. Which can be achieved through the PlacementTarget of the ContextMenu, but I cannot manage to do it. Any suggestions?

Thanks in advance

答:
You can often use the PlacementTargetto perform some relative binding and give ContextMenuinformation it wouldn't normally have because it's outside the visual tree. Given the way you have things setup here, I'm not sure that would work out too well for you. It looks like you want a context menu that belongs to the ListView but works on the row that is right clicked on. You can do that by manually attaching the DataContext in the ContextOpening event. For example, I loosely followed what you had to set up a ListView

```<code><ListView ItemsSource="{Binding MyGroupOfItems}">
    <ListView.Resources>
        <Style TargetType="ListViewItem">
            <EventSetter Event="ContextMenuOpening" Handler="ListViewItem_ContextMenuOpening" />
        </Style>
    </ListView.Resources>
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}" />
        </GridView>
    </ListView.View>
    <ListView.ContextMenu>
        <ContextMenu Name="menu">
            <MenuItem Header="Copy ID" Click="MenuItem_Click" />
        </ContextMenu>
    </ListView.ContextMenu>
</ListView>
</code>```

I added a style for the ListViewItem that handles ContextMenuOpening events.This will allow you to know which row you're over when the context menu is opening. In the code behind, you can attach the DataContext for that row.

```<code>private void ListViewItem_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
    ListViewItem listItem = sender as ListViewItem;
    menu.DataContext = listItem.DataContext;
}
</code>```

In this case, menu is the name of the ContextMenu. I simply grab the DataContext from the ListItemView and attach it to the ContextMenu.

Now when you handle the menu click event, you can fetch that data and use it to do whatever you need to do.

```<code>private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    MyItem item = (MyItem)(sender as MenuItem).DataContext;
    //Now you can do stuff with MyItem
}
</code>```

Just a note: I omitted the stuff you were doing with the HierarchicalDataTemplate because I didn't understand the intent, and for me it was causing nothing to render. Regardless, this strategy for attaching the DataContext when opening the ContextMenu should transfer to other use cases.

Body:
I have a ListView with several items. I would like to copy in the system clipboard, information associated to a given row (e.g. id of the item in that row).

I have created a ContextMenu that opens when right clicking a row, and it displays a MenuItem to copy the id:

<ListView x:Name="MyListView" MouseDoubleClick="MyListView_MouseDoubleClick">
    <ListView.Columns>
        <GridViewColumn Header="Id" DisplayMemberBinding="{Binding MyItem.Id}"/>
    </ListView.Columns>
    <ListView.ItemTemplate>
        <HierarchicalDataTemplate DataType="{x:Type mynamespace:MyItemDefinition}" ItemsSource="{Binding MyGroupOfItems, Mode=OneWay}" />
    </ListView.ItemTemplate>
    <ListView.ContextMenu>
        <ContextMenu>
            <MenuItem x:Name="MenuItemCopyId" Header="Copy ID" Click="MenuItemCopyId_Click"/>
        </ContextMenu>
    </ListView.ContextMenu>
</ListView>

and

private void MenuItemCopyId_Click(object sender, RoutedEventArgs e)
{
     var menu_item = ((System.Windows.Controls.MenuItem)sender);
}

For what I read (ListViewItem Context Menu Get Data from ListViewItem) it needs to access the DataContext of the item. Which can be achieved through the PlacementTarget of the ContextMenu, but I cannot manage to do it. Any suggestions?

Thanks in advance

Body:
You can often use the PlacementTargetto perform some relative binding and give ContextMenuinformation it wouldn't normally have because it's outside the visual tree. Given the way you have things setup here, I'm not sure that would work out too well for you. It looks like you want a context menu that belongs to the ListView but works on the row that is right clicked on. You can do that by manually attaching the DataContext in the ContextOpening event. For example, I loosely followed what you had to set up a ListView

<ListView ItemsSource="{Binding MyGroupOfItems}">
    <ListView.Resources>
        <Style TargetType="ListViewItem">
            <EventSetter Event="ContextMenuOpening" Handler="ListViewItem_ContextMenuOpening" />
        </Style>
    </ListView.Resources>
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}" />
        </GridView>
    </ListView.View>
    <ListView.ContextMenu>
        <ContextMenu Name="menu">
            <MenuItem Header="Copy ID" Click="MenuItem_Click" />
        </ContextMenu>
    </ListView.ContextMenu>
</ListView>

I added a style for the ListViewItem that handles ContextMenuOpening events.This will allow you to know which row you're over when the context menu is opening. In the code behind, you can attach the DataContext for that row.

private void ListViewItem_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
    ListViewItem listItem = sender as ListViewItem;
    menu.DataContext = listItem.DataContext;
}

In this case, menu is the name of the ContextMenu. I simply grab the DataContext from the ListItemView and attach it to the ContextMenu.

Now when you handle the menu click event, you can fetch that data and use it to do whatever you need to do.

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    MyItem item = (MyItem)(sender as MenuItem).DataContext;
    //Now you can do stuff with MyItem
}

Just a note: I omitted the stuff you were doing with the HierarchicalDataTemplate because I didn't understand the intent, and for me it was causing nothing to render. Regardless, this strategy for attaching the DataContext when opening the ContextMenu should transfer to other use cases.


问:
ASP.NET Core - producing "000000..." sha256 hash under heavy load
I have a bit of a strange problem. I'm running a web API on ASP.NET Core 3.1. One thing the API does is to generate a SHA256 from an input string

```<code>private static HashAlgorithm algorithm = SHA256.Create();
public static byte[] GetSha256Hash(string inputString)
{
    return algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));
}

public static string GetSha256HashString(string inputString)
{
    var result = GetSha256Hash(inputString);
    // Return as hexadecimal string
    return string.Join(
        string.Empty,
        result.Select(x => x.ToString("x2")));
}

player.Id = GetSha256HashString($"{player.Name}-{player.Region}-{player.Country}");

</code>```

I check that the fields player.Name, region and country and not null before I do the hashing. But sometimes, mostly seems to happen when the server is under heavy load (~100 requests/second), for a few requests (about ~0.5%) it generates

0000000000000000000000000000000000000000000000000000000000000000 for the player.id. Usually they look something like this a7da37b8a57ea714ec11f92c0025d6e654a483144eb68b829d388ea91eb81c79

Even if all the fields would be empty, the three dashes alone would ensure that this should not happen.

I do not see any exceptions and I am a bit out of ideas how to debug this. Any help is welcome! Let me know if I need to add any more information.

Env: Running in Docker on Linux.

答:
The object you are setting as:

private static HashAlgorithm algorithm = SHA256.Create();

is not thread safe.

In your case it really depends on the accessor, instance or static and also the runtime (OS, netcore, etc.)

To be sure that it is really working without having troubles and not creating different / wrong hashes for the same source you have to create a new SHA256.Create() all the time you want to create a hash.

```<code>public static string GenerateSHA256(string input)
{
    var bytes = Encoding.Unicode.GetBytes(input);
    using (var hashEngine = SHA256.Create())
    {
        var hashedBytes = hashEngine.ComputeHash(bytes, 0, bytes.Length);
        var sb = new StringBuilder();
        foreach (var b in hashedBytes)
        {
            var hex = b.ToString("x2");
            sb.Append(hex);
        }
        return sb.ToString();
    }
}
</code>```

You can also find this in some documentations of Microsoft.

Any public static (Shared in Visual Basic) members of this type are
  thread safe. Any instance members are not guaranteed to be thread
  safe.

.NET Fiddle

SO: instance-members-thread-unsafe-vs-public-static

Git: Discussion about this topic

Body:
I have a bit of a strange problem. I'm running a web API on ASP.NET Core 3.1. One thing the API does is to generate a SHA256 from an input string

private static HashAlgorithm algorithm = SHA256.Create();
public static byte[] GetSha256Hash(string inputString)
{
    return algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));
}

public static string GetSha256HashString(string inputString)
{
    var result = GetSha256Hash(inputString);
    // Return as hexadecimal string
    return string.Join(
        string.Empty,
        result.Select(x => x.ToString("x2")));
}

player.Id = GetSha256HashString($"{player.Name}-{player.Region}-{player.Country}");

I check that the fields player.Name, region and country and not null before I do the hashing. But sometimes, mostly seems to happen when the server is under heavy load (~100 requests/second), for a few requests (about ~0.5%) it generates

0000000000000000000000000000000000000000000000000000000000000000 for the player.id. Usually they look something like this a7da37b8a57ea714ec11f92c0025d6e654a483144eb68b829d388ea91eb81c79

Even if all the fields would be empty, the three dashes alone would ensure that this should not happen.

I do not see any exceptions and I am a bit out of ideas how to debug this. Any help is welcome! Let me know if I need to add any more information.

Env: Running in Docker on Linux.

Body:
The object you are setting as:

private static HashAlgorithm algorithm = SHA256.Create();

is not thread safe.

In your case it really depends on the accessor, instance or static and also the runtime (OS, netcore, etc.)

To be sure that it is really working without having troubles and not creating different / wrong hashes for the same source you have to create a new SHA256.Create() all the time you want to create a hash.

public static string GenerateSHA256(string input)
{
    var bytes = Encoding.Unicode.GetBytes(input);
    using (var hashEngine = SHA256.Create())
    {
        var hashedBytes = hashEngine.ComputeHash(bytes, 0, bytes.Length);
        var sb = new StringBuilder();
        foreach (var b in hashedBytes)
        {
            var hex = b.ToString("x2");
            sb.Append(hex);
        }
        return sb.ToString();
    }
}

You can also find this in some documentations of Microsoft.

Any public static (Shared in Visual Basic) members of this type are
  thread safe. Any instance members are not guaranteed to be thread
  safe.

.NET Fiddle

SO: instance-members-thread-unsafe-vs-public-static

Git: Discussion about this topic


问:
JSON deserialize if the Field is missing in the JSON object , Set the Field in a wrapper class to NULL
```<code>JSON Object
 {
    x = 'String1'

}
</code>```

Consider this scenario if the JSON object is passing only one value I want to set the other value to NULL Which in this case is Y

```<code> public with sharing class SerializeObject{
        public String x {get;set;}
        public String y {get;set;}
 }
</code>```

Function that Serialize

```<code> public SerializeObject SerializeObjectJSON(String json){
    return (SerializeObject ) System.JSON.deserialize(json.replace('""','null'), SerializeObject.class);
  }
</code>```

答:
Your "object" is not valid JSON. I don't know what you're trying to do but you have some serious issues with data source, not with Apex. If you fix your syntax errors - other variable will be null out of the box.</p>

```<code>public with sharing class SerializeObject{
        public String x {get;set;}
        public String y {get;set;}
}

String s = '{"x" : "String 1"}';

SerializeObject so = (SerializeObject) JSON.deserialize(s, SerializeObject.class);
System.debug(so.x); // String 1
System.debug(so.y); // null
</code>```

Body:
JSON Object
 {
    x = 'String1'

}

Consider this scenario if the JSON object is passing only one value I want to set the other value to NULL Which in this case is Y

 public with sharing class SerializeObject{
        public String x {get;set;}
        public String y {get;set;}
 }

Function that Serialize

 public SerializeObject SerializeObjectJSON(String json){
    return (SerializeObject ) System.JSON.deserialize(json.replace('""','null'), SerializeObject.class);
  }

Body:
Your "object" is not valid JSON. I don't know what you're trying to do but you have some serious issues with data source, not with Apex. If you fix your syntax errors - other variable will be null out of the box.

public with sharing class SerializeObject{
        public String x {get;set;}
        public String y {get;set;}
}

String s = '{"x" : "String 1"}';

SerializeObject so = (SerializeObject) JSON.deserialize(s, SerializeObject.class);
System.debug(so.x); // String 1
System.debug(so.y); // null


问:
How to animate the command line?
I have always wondered how people update a previous line in a command line. a great example of this is when using the wget command in linux. It creates an ASCII loading bar of sorts that looks like this:

[======>                    ] 37%

and of course the loading bar moves and the percent changes, But it doesn't make a new line. I cannot figure out how to do this. Can someone point me in the right direction?

答: PowerShell has a Write-Progress cmdlet that creates an in-console progress bar that you can update and modify as your script runs.</p>

ContentLicense: CC BY-SA 2.5

Title: How to animate the command line?

OwnerDisplayName: Steven Murawski


问:
Do you believe the Firefox project should be forked into a developer targeted version?
I've just got this idea that there is a need for a forked version of Firefox that would provide right out of the box tools for web development. Like FireBug, YSlow, FireCookie, LiveHTTPHeaders, etc.

Maybe the fork should only include those extensions or take a further step and implement them in existing chrome.

The reason I'm thinking about this is that right now I have two Firefox profiles. A "browsing" one which has only one extension and a "development" one which has lots and lots of extensions. The advantage is obviously that the former is faster than the latter. Maybe if aimed from the beginning at developers, a forked version would bring some speed improvements and other niceties.

What do you think? Any volunteers?

答: Adding functionality to FireFox via extensions is IMO the reason why it is such a  popular browser. If you take that freedom 'away' from people by providing them 'pre-baked' solutions, that will not be for the best.

OwnerDisplayName: Ionut G. Stan

OwnerDisplayName: Zaagmans


问:
Anti-aliasing in R graphics under Windows (as per Mac)
is there a way to plot anti-aliased graphics from the Windows version of R? As you can see from the two versions below the Mac version of R prints graphics anti aliased....

....whereas while the Windows version anti-aliases text, it does not anti-alias the actual graphic, as can be seen from the riser points, and the grid:

Here is the code by the way:

```<code>library(scatterplot3d)
attach(mtcars)
s3d <-scatterplot3d(wt,disp,mpg, pch=16, highlight.3d=TRUE,
  type="h", main="3D Scatterplot")
fit <- lm(mpg ~ wt+disp)
s3d$plane3d(fit)
</code>```

I need the highest quality possible, for web page publication. I am running Windows 7 and pulling data from RBloomberg, which only works under Windows.

答:
Use a vector device such as pdf. First make sure you have that capability and so not surprisingly the capabilities function is what to check. If you do have pdf then just do this:

```<code>pdf(file="out_graph.pdf")
s3d <-scatterplot3d(wt,disp,mpg, pch=16, highlight.3d=TRUE,
  type="h", main="3D Scatterplot")
fit <- lm(mpg ~ wt+disp)
s3d$plane3d(fit)
dev.off()
</code>```

An alternative for web output might be the png() graphics device. It gets high marks for compactness and web browser compatibility although it is a raster format.

Body:
is there a way to plot anti-aliased graphics from the Windows version of R? As you can see from the two versions below the Mac version of R prints graphics anti aliased....

....whereas while the Windows version anti-aliases text, it does not anti-alias the actual graphic, as can be seen from the riser points, and the grid:

Here is the code by the way:

library(scatterplot3d)
attach(mtcars)
s3d <-scatterplot3d(wt,disp,mpg, pch=16, highlight.3d=TRUE,
  type="h", main="3D Scatterplot")
fit <- lm(mpg ~ wt+disp)
s3d$plane3d(fit)

I need the highest quality possible, for web page publication. I am running Windows 7 and pulling data from RBloomberg, which only works under Windows.

Body:
Use a vector device such as pdf. First make sure you have that capability and so not surprisingly the capabilities function is what to check. If you do have pdf then just do this:

pdf(file="out_graph.pdf")
s3d <-scatterplot3d(wt,disp,mpg, pch=16, highlight.3d=TRUE,
  type="h", main="3D Scatterplot")
fit <- lm(mpg ~ wt+disp)
s3d$plane3d(fit)
dev.off()

An alternative for web output might be the png() graphics device. It gets high marks for compactness and web browser compatibility although it is a raster format.