问:
BeanCreationException: Error creating bean with name servletContainer
I work with a Spring Boot project that I could build properly. However, at the time of running the project with the command e.g
mvn spring-boot:run I get the following error stack with BeanCreationException provided below,

```<code>2017-12-04 17:07:03.210 ERROR 2764 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'servletContainer' defined in com.quotecrunchers.email.HubSpotEmailApplication: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.context.embedded.EmbeddedServletContainerFactory]: Factory method 'servletContainer' threw exception; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'BASE' in value "${BASE}"
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:137) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at com.quotecrunchers.email.HubSpotEmailApplication.main(HubSpotEmailApplication.java:58) [classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144]
        at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:527) [spring-boot-maven-plugin-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'servletContainer' defined in com.quotecrunchers.email.HubSpotEmailApplication: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.context.embedded.EmbeddedServletContainerFactory]: Factory method 'servletContainer' threw exception; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'BASE' in value "${BASE}"
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:199) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:162) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:134) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        ... 14 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.context.embedded.EmbeddedServletContainerFactory]: Factory method 'servletContainer' threw exception; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'BASE' in value "${BASE}"
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        ... 25 common frames omitted
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'BASE' in value "${BASE}"
        at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174) ~[spring-core-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126) ~[spring-core-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:236) ~[spring-core-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:210) ~[spring-core-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.core.env.AbstractPropertyResolver.resolveNestedPlaceholders(AbstractPropertyResolver.java:227) ~[spring-core-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:84) ~[spring-core-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:61) ~[spring-core-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.core.env.AbstractEnvironment.getProperty(AbstractEnvironment.java:527) ~[spring-core-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at com.quotecrunchers.email.KeystoreDetailReader.createKeystoreDetails(KeystoreDetailReader.java:17) ~[classes/:na]
        at com.quotecrunchers.email.HubSpotEmailApplication.servletContainer(HubSpotEmailApplication.java:70) [classes/:na]
        at com.quotecrunchers.email.HubSpotEmailApplication$$EnhancerBySpringCGLIB$$da41a424.CGLIB$servletContainer$0(<generated>) ~[classes/:na]
        at com.quotecrunchers.email.HubSpotEmailApplication$$EnhancerBySpringCGLIB$$da41a424$$FastClassBySpringCGLIB$$a6492ef3.invoke(<generated>) ~[classes/:na]
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at com.quotecrunchers.email.HubSpotEmailApplication$$EnhancerBySpringCGLIB$$da41a424.servletContainer(<generated>) ~[classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144]
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        ... 26 common frames omitted

[WARNING]
java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:527)
        at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'servletContainer' defined in com.quotecrunchers.email.HubSpotEmailApplication: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.context.embedded.EmbeddedServletContainerFactory]: Factory method 'servletContainer' threw exception; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'BASE' in value "${BASE}"
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:137)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
        at com.quotecrunchers.email.HubSpotEmailApplication.main(HubSpotEmailApplication.java:58)
        ... 6 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'servletContainer' defined in com.quotecrunchers.email.HubSpotEmailApplication: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.context.embedded.EmbeddedServletContainerFactory]: Factory method 'servletContainer' threw exception; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'BASE' in value "${BASE}"
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
        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:306)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:199)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:162)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:134)
        ... 14 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.context.embedded.EmbeddedServletContainerFactory]: Factory method 'servletContainer' threw exception; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'BASE' in value "${BASE}"
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
        ... 25 more
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'BASE' in value "${BASE}"
        at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
        at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
        at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:236)
        at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:210)
        at org.springframework.core.env.AbstractPropertyResolver.resolveNestedPlaceholders(AbstractPropertyResolver.java:227)
        at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:84)
        at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:61)
        at org.springframework.core.env.AbstractEnvironment.getProperty(AbstractEnvironment.java:527)
        at com.quotecrunchers.email.KeystoreDetailReader.createKeystoreDetails(KeystoreDetailReader.java:17)
        at com.quotecrunchers.email.HubSpotEmailApplication.servletContainer(HubSpotEmailApplication.java:70)
        at com.quotecrunchers.email.HubSpotEmailApplication$$EnhancerBySpringCGLIB$$da41a424.CGLIB$servletContainer$0(<generated>)
        at com.quotecrunchers.email.HubSpotEmailApplication$$EnhancerBySpringCGLIB$$da41a424$$FastClassBySpringCGLIB$$a6492ef3.invoke(<generated>)
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
        at com.quotecrunchers.email.HubSpotEmailApplication$$EnhancerBySpringCGLIB$$da41a424.servletContainer(<generated>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
        ... 26 more
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.367 s
[INFO] Finished at: 2017-12-04T17:07:03+06:00
[INFO] Final Memory: 33M/490M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.5.8.RELEASE:run (default-cli) on project HubSpotEmail: An exception occurred while running. null: InvocationTargetException: Unable to start embedded container; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'servletContainer' defined in com.quotecrunchers.email.HubSpotEmailApplication: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.context.embedded.EmbeddedServletContainerFactory]: Factory method 'servletContainer' threw exception; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'BASE' in value "${BASE}" -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
</code>```

The relevant portion of the code is provided below with the servletContainer method mentioned in the error stack,

```<code>@Slf4j
@Configuration
@SpringBootApplication
public abstract class HubSpotEmailApplication
        implements ApplicationListener<ApplicationReadyEvent>, ApplicationContextAware {

    @Autowired
    private Environment env;

    @Autowired
    private KeystoreDetailReader keystoreDetailReader;

    private boolean hasCertificate = false;

    private ConfigurableApplicationContext applicationContext;

    private KeystoreFacade keystore;

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

    /**
     * This bean configures either an http or an https Tomcat Connector.
     * Whether an http or https connector is configured depends on
     * whether a valid SSL certificate is available.
     *
     * @return
     */
    @Bean
    public EmbeddedServletContainerFactory servletContainer() {
        KeystoreDetails keystoreDetails = keystoreDetailReader.createKeystoreDetails();
        keystore = new KeystoreFacade(keystoreDetails);

        TomcatEmbeddedServletContainerFactory tomcat = null;

        try {

            hasCertificate = isValidCertificateAvailable();

            log.info("SSL Certificate in place: " + hasCertificate);
            log.info("Https protocol requested: " + useHttps());
            if (useHttps() && hasCertificate) {
                tomcat = new TomcatEmbeddedServletContainerFactory() {
                    @Override
                    protected void postProcessContext(Context context) {
                        SecurityConstraint securityConstraint = new SecurityConstraint();
                        securityConstraint.setUserConstraint("CONFIDENTIAL");
                        SecurityCollection collection = new SecurityCollection();
                        collection.addPattern("/*");
                        //collection.removePattern("/.well-known/acme-challenge/*");
                        securityConstraint.addCollection(collection);
                        context.addConstraint(securityConstraint);
                    }
                };
                tomcat.addAdditionalTomcatConnectors(createSslConnector(keystoreDetails));

            } else {
                tomcat = new TomcatEmbeddedServletContainerFactory();
            }
        } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
            log.error(e.getMessage());
        }

        return tomcat;
    }

 // more code goes

}
</code>```

The application.yml file is provided below with the modified keys,

```<code>hubspot:
  url: http://api.hubapi.com/
  fileUpload: filemanager/api/v2/files
  createFolder: filemanager/api/v2/folders
  key: c1488a5b-4c9a-4f80-bb1e-some_key
  emailId: some_id
  singleSendApi: email/public/v1/singleEmail/send
  pdfTemplateUrl:https://ddddrtrt.hubererespot.net/hubfs/3955925/mobile-calc-resources/eclipx-email.pdf

logging:
  level: debug
domain: test.api.thescene.co
keystore-folder: ${BASE}
admin-username: bravo
admin-password: bravo
server.port: 80
server.protocol: http

ssl:
  key-store: lets-encrypt-keystore.jks
  key-store-password: flexigroup
  key-password: flexigroup
  key-alias: test.api.thescene.co
  # below value can be staging or production. Let's encrypt only issue 5 production certs per week so use them carefully
  lets-encrypt: production

spreadsheet:
  user-agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11
  url: https://cdn2.hubspot.net/hubfs/439943/LoanCalculatorTX/{0}.xls?update={1}
  suffix: .xls
</code>```

It seems that the issue started from the keystore-folder: ${BASE} line and the relevant part of the error stack,

```<code>Factory method 'servletContainer' threw exception; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'BASE' in value "${BASE}"
</code>```

Do you know how to fix this?

答: I's obvious that  a key named BASE should be provided.You can refer to this

Body:
I work with a Spring Boot project that I could build properly. However, at the time of running the project with the command e.g
mvn spring-boot:run I get the following error stack with BeanCreationException provided below,

2017-12-04 17:07:03.210 ERROR 2764 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'servletContainer' defined in com.quotecrunchers.email.HubSpotEmailApplication: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.context.embedded.EmbeddedServletContainerFactory]: Factory method 'servletContainer' threw exception; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'BASE' in value "${BASE}"
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:137) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at com.quotecrunchers.email.HubSpotEmailApplication.main(HubSpotEmailApplication.java:58) [classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144]
        at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:527) [spring-boot-maven-plugin-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'servletContainer' defined in com.quotecrunchers.email.HubSpotEmailApplication: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.context.embedded.EmbeddedServletContainerFactory]: Factory method 'servletContainer' threw exception; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'BASE' in value "${BASE}"
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:199) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:162) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:134) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        ... 14 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.context.embedded.EmbeddedServletContainerFactory]: Factory method 'servletContainer' threw exception; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'BASE' in value "${BASE}"
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        ... 25 common frames omitted
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'BASE' in value "${BASE}"
        at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174) ~[spring-core-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126) ~[spring-core-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:236) ~[spring-core-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:210) ~[spring-core-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.core.env.AbstractPropertyResolver.resolveNestedPlaceholders(AbstractPropertyResolver.java:227) ~[spring-core-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:84) ~[spring-core-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:61) ~[spring-core-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.core.env.AbstractEnvironment.getProperty(AbstractEnvironment.java:527) ~[spring-core-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at com.quotecrunchers.email.KeystoreDetailReader.createKeystoreDetails(KeystoreDetailReader.java:17) ~[classes/:na]
        at com.quotecrunchers.email.HubSpotEmailApplication.servletContainer(HubSpotEmailApplication.java:70) [classes/:na]
        at com.quotecrunchers.email.HubSpotEmailApplication$$EnhancerBySpringCGLIB$$da41a424.CGLIB$servletContainer$0(<generated>) ~[classes/:na]
        at com.quotecrunchers.email.HubSpotEmailApplication$$EnhancerBySpringCGLIB$$da41a424$$FastClassBySpringCGLIB$$a6492ef3.invoke(<generated>) ~[classes/:na]
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at com.quotecrunchers.email.HubSpotEmailApplication$$EnhancerBySpringCGLIB$$da41a424.servletContainer(<generated>) ~[classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144]
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        ... 26 common frames omitted

[WARNING]
java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:527)
        at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'servletContainer' defined in com.quotecrunchers.email.HubSpotEmailApplication: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.context.embedded.EmbeddedServletContainerFactory]: Factory method 'servletContainer' threw exception; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'BASE' in value "${BASE}"
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:137)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
        at com.quotecrunchers.email.HubSpotEmailApplication.main(HubSpotEmailApplication.java:58)
        ... 6 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'servletContainer' defined in com.quotecrunchers.email.HubSpotEmailApplication: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.context.embedded.EmbeddedServletContainerFactory]: Factory method 'servletContainer' threw exception; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'BASE' in value "${BASE}"
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
        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:306)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:199)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:162)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:134)
        ... 14 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.context.embedded.EmbeddedServletContainerFactory]: Factory method 'servletContainer' threw exception; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'BASE' in value "${BASE}"
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
        ... 25 more
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'BASE' in value "${BASE}"
        at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
        at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
        at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:236)
        at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:210)
        at org.springframework.core.env.AbstractPropertyResolver.resolveNestedPlaceholders(AbstractPropertyResolver.java:227)
        at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:84)
        at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:61)
        at org.springframework.core.env.AbstractEnvironment.getProperty(AbstractEnvironment.java:527)
        at com.quotecrunchers.email.KeystoreDetailReader.createKeystoreDetails(KeystoreDetailReader.java:17)
        at com.quotecrunchers.email.HubSpotEmailApplication.servletContainer(HubSpotEmailApplication.java:70)
        at com.quotecrunchers.email.HubSpotEmailApplication$$EnhancerBySpringCGLIB$$da41a424.CGLIB$servletContainer$0(<generated>)
        at com.quotecrunchers.email.HubSpotEmailApplication$$EnhancerBySpringCGLIB$$da41a424$$FastClassBySpringCGLIB$$a6492ef3.invoke(<generated>)
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
        at com.quotecrunchers.email.HubSpotEmailApplication$$EnhancerBySpringCGLIB$$da41a424.servletContainer(<generated>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
        ... 26 more
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.367 s
[INFO] Finished at: 2017-12-04T17:07:03+06:00
[INFO] Final Memory: 33M/490M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.5.8.RELEASE:run (default-cli) on project HubSpotEmail: An exception occurred while running. null: InvocationTargetException: Unable to start embedded container; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'servletContainer' defined in com.quotecrunchers.email.HubSpotEmailApplication: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.context.embedded.EmbeddedServletContainerFactory]: Factory method 'servletContainer' threw exception; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'BASE' in value "${BASE}" -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

The relevant portion of the code is provided below with the servletContainer method mentioned in the error stack,

@Slf4j
@Configuration
@SpringBootApplication
public abstract class HubSpotEmailApplication
        implements ApplicationListener<ApplicationReadyEvent>, ApplicationContextAware {

    @Autowired
    private Environment env;

    @Autowired
    private KeystoreDetailReader keystoreDetailReader;

    private boolean hasCertificate = false;

    private ConfigurableApplicationContext applicationContext;

    private KeystoreFacade keystore;

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

    /**
     * This bean configures either an http or an https Tomcat Connector.
     * Whether an http or https connector is configured depends on
     * whether a valid SSL certificate is available.
     *
     * @return
     */
    @Bean
    public EmbeddedServletContainerFactory servletContainer() {
        KeystoreDetails keystoreDetails = keystoreDetailReader.createKeystoreDetails();
        keystore = new KeystoreFacade(keystoreDetails);

        TomcatEmbeddedServletContainerFactory tomcat = null;

        try {

            hasCertificate = isValidCertificateAvailable();

            log.info("SSL Certificate in place: " + hasCertificate);
            log.info("Https protocol requested: " + useHttps());
            if (useHttps() && hasCertificate) {
                tomcat = new TomcatEmbeddedServletContainerFactory() {
                    @Override
                    protected void postProcessContext(Context context) {
                        SecurityConstraint securityConstraint = new SecurityConstraint();
                        securityConstraint.setUserConstraint("CONFIDENTIAL");
                        SecurityCollection collection = new SecurityCollection();
                        collection.addPattern("/*");
                        //collection.removePattern("/.well-known/acme-challenge/*");
                        securityConstraint.addCollection(collection);
                        context.addConstraint(securityConstraint);
                    }
                };
                tomcat.addAdditionalTomcatConnectors(createSslConnector(keystoreDetails));

            } else {
                tomcat = new TomcatEmbeddedServletContainerFactory();
            }
        } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
            log.error(e.getMessage());
        }

        return tomcat;
    }

 // more code goes

}

The application.yml file is provided below with the modified keys,

hubspot:
  url: http://api.hubapi.com/
  fileUpload: filemanager/api/v2/files
  createFolder: filemanager/api/v2/folders
  key: c1488a5b-4c9a-4f80-bb1e-some_key
  emailId: some_id
  singleSendApi: email/public/v1/singleEmail/send
  pdfTemplateUrl:https://ddddrtrt.hubererespot.net/hubfs/3955925/mobile-calc-resources/eclipx-email.pdf

logging:
  level: debug
domain: test.api.thescene.co
keystore-folder: ${BASE}
admin-username: bravo
admin-password: bravo
server.port: 80
server.protocol: http

ssl:
  key-store: lets-encrypt-keystore.jks
  key-store-password: flexigroup
  key-password: flexigroup
  key-alias: test.api.thescene.co
  # below value can be staging or production. Let's encrypt only issue 5 production certs per week so use them carefully
  lets-encrypt: production

spreadsheet:
  user-agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11
  url: https://cdn2.hubspot.net/hubfs/439943/LoanCalculatorTX/{0}.xls?update={1}
  suffix: .xls

It seems that the issue started from the keystore-folder: ${BASE} line and the relevant part of the error stack,

Factory method 'servletContainer' threw exception; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'BASE' in value "${BASE}"

Do you know how to fix this?


来源: stackexchange

问:
Index python dict by object or two floats
I have a number of objects which I need to link to an integer number. These objects are ArcGIS Point objects (exactly what they are isn't relevant), which store an X and a Y value for a point, as floating point numbers.

I need to record that, for example:

```<code>Point(X = 2.765, Y = 3.982) -> 2
Point(X = 33.9, Y = 98.45) -> 7
Point(X = 1.23, Y = 2.43) -> 9
Point(X = 8.342, Y = 6.754) -> 5
</code>```

I then need to be able to look up the resulting value by the X and Y values. I've tried using the Point objects as the dictionary's key, but this doesn't work as when I recreate the point object from the X and Y values it doesn't look it up properly anymore (presumably because the object ID has changed).

How should I go about linking these point values to the integers. Is there another way that I can use a dictionary?

答: You need to override __hash__ in Point.

ContentLicense: CC BY-SA 2.5

Body:
I have a number of objects which I need to link to an integer number. These objects are ArcGIS Point objects (exactly what they are isn't relevant), which store an X and a Y value for a point, as floating point numbers.

I need to record that, for example:

Point(X = 2.765, Y = 3.982) -> 2
Point(X = 33.9, Y = 98.45) -> 7
Point(X = 1.23, Y = 2.43) -> 9
Point(X = 8.342, Y = 6.754) -> 5

I then need to be able to look up the resulting value by the X and Y values. I've tried using the Point objects as the dictionary's key, but this doesn't work as when I recreate the point object from the X and Y values it doesn't look it up properly anymore (presumably because the object ID has changed).

How should I go about linking these point values to the integers. Is there another way that I can use a dictionary?

Body: You need to override __hash__ in Point.


问:
URL Rewriting Add a folder name to URLs
I have an apache2 server.

My directory structure is -  (below is inside - /some-folder/abc)

```<code>- app
  - otherfolder
  - pqr.php
  - xyz.php
- js
- css
</code>```

.htaccess is placed inside /some-folder/abc

Context root for virtual host is set till - /some-folder/

Now, I want my users to enter this URL - http://someserver.com/abc/xyz or http://someserver.com/abc/pqr

I want to open the page at - http://someserver.com/abc/app/xyz.php or http://someserver.com/abc/app/pqr.php

How can I achieve this using URL Rewriting mod_rewrite

This is what I have so far, which is not working -

```<code>Options +FollowSymLinks -MultiViews
#Turn mod_rewrite on
RewriteEngine On
#RewriteBase /abc

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ /app/$1\.php [L] # this doesn't work either
# RewriteRule ^(.*)$ app/$1.php [L] # this doesn't work either
# RewriteRule ^abc/(.*)$ abc/app/$1.php [L] # this doesn't work either
</code>```

Thank you for your help.

If possible, I would also like to take all query params using forward slash
ex - http://someserver.com/abc/app/xyz.php/xId/123/uId/938/sdh/8374 instead of http://someserver.com/abc/app/xyz.php?xId=123?uId=938?sdh=8374

There is no pattern for query params, they can be anything for an page. Is this possible by a generic mod_rewrite, or do I have to rewrite urls for each page, and each time my developers add a new query param?

答:
This rule should work for you from /abc/.htaccess:

```<code>Options +FollowSymLinks -MultiViews
RewriteEngine On

RewriteCond %{DOCUMENT_ROOT}/abc/app/$1.php -f
RewriteRule ^(?!internal)(.+?)/?$ app/$1.php [L,NC]
</code>```

RewriteCond makes sure that we have a corresponding .php file in /abc/app/ sub-directory.

(?!internal) is negative lookahead assertion to skip internal from this rewrite.

Also it appears you're using a relative URL for css/js/images e.g. src="abc.png" and your current URL is: /abc/xyz then browser resolves this relative URL to http://example.com/abc/xyz/abc.png which obviously will cause a 404 since your static files are residing in /abc/app/ sub-directory.

You can add this just below  section of your page's HTML:

```<code><base href="/abc/app/" />
</code>```

so that every relative URL is resolved from that base URL and not from the current page's URL.

Also as a practice to use absolute links instead of relative ones change relative link XYZ, to this one XYZ

ContentLicense: CC BY-SA 3.0

Title: URL Rewriting Add a folder name to URLs

Body:
I have an apache2 server.

My directory structure is -  (below is inside - /some-folder/abc)

- app
  - otherfolder
  - pqr.php
  - xyz.php
- js
- css

.htaccess is placed inside /some-folder/abc

Context root for virtual host is set till - /some-folder/

Now, I want my users to enter this URL - http://someserver.com/abc/xyz or http://someserver.com/abc/pqr

I want to open the page at - http://someserver.com/abc/app/xyz.php or http://someserver.com/abc/app/pqr.php

How can I achieve this using URL Rewriting mod_rewrite

This is what I have so far, which is not working -

Options +FollowSymLinks -MultiViews
#Turn mod_rewrite on
RewriteEngine On
#RewriteBase /abc

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ /app/$1\.php [L] # this doesn't work either
# RewriteRule ^(.*)$ app/$1.php [L] # this doesn't work either
# RewriteRule ^abc/(.*)$ abc/app/$1.php [L] # this doesn't work either

Thank you for your help.

If possible, I would also like to take all query params using forward slash
ex - http://someserver.com/abc/app/xyz.php/xId/123/uId/938/sdh/8374 instead of http://someserver.com/abc/app/xyz.php?xId=123?uId=938?sdh=8374

There is no pattern for query params, they can be anything for an page. Is this possible by a generic mod_rewrite, or do I have to rewrite urls for each page, and each time my developers add a new query param?

Body:
This rule should work for you from /abc/.htaccess:

Options +FollowSymLinks -MultiViews
RewriteEngine On

RewriteCond %{DOCUMENT_ROOT}/abc/app/$1.php -f
RewriteRule ^(?!internal)(.+?)/?$ app/$1.php [L,NC]

RewriteCond makes sure that we have a corresponding .php file in /abc/app/ sub-directory.

(?!internal) is negative lookahead assertion to skip internal from this rewrite.

Also it appears you're using a relative URL for css/js/images e.g. src="abc.png" and your current URL is: /abc/xyz then browser resolves this relative URL to http://example.com/abc/xyz/abc.png which obviously will cause a 404 since your static files are residing in /abc/app/ sub-directory.

You can add this just below <head> section of your page's HTML:

<base href="/abc/app/" />

so that every relative URL is resolved from that base URL and not from the current page's URL.

Also as a practice to use absolute links instead of relative ones change relative link <a href="xyz">XYZ</a>, to this one <a href="/abc/xyz">XYZ</a>


问:
migrate.exceptions.DatabaseAlreadyControlledError while trying to re create DB in heroku using db_create.py file
this is tdb_create.py file under C:\Users\Yasmi\Documents\microblog\flask-psps> which i try to run on heroku using web: gunicorn app:app
init: python db_create.py
upgrade: python db_upgrade.py which is in procfile file under the same folder.
db_create.py doesnt pass , ant figure up why. I did it due to changes in field description in mdels.py file

C:\Users\Yasmi\Documents\microblog\flask-psps>heroku run init
Running init on flask-psps... up, run.8964 (Free)

  postgres://rydbbszhueldrc:9e71d3c3f199b9dea08833d4a4efcf0e3cc9e1519d77ebc48933fca16f39be9c@ec2-23-21-220-48.compute-1.amazonaws.com:5432/dfrmo4cc9toudp
basedir is /app

  postgres://rydbbszhueldrc:9e71d3c3f199b9dea08833d4a4efcf0e3cc9e1519d77ebc48933fca16f39be9c@ec2-23-21-220-48.compute-1.amazonaws.com:5432/dfrmo4cc9toudp
/app/db_repository
SQLALCHEMY_MIGRATE_REPO/app/db_repository
Traceback (most recent call last):
  File "db_create.py", line 15, in <module>
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
  File "<decorator-gen-8>", line 2, in version_control
  File "/app/.heroku/python/lib/python3.6/site-packages/migrate/versioning/util/__init__.py", line 167, in with_engine
    return f(*a, **kw)
  File "/app/.heroku/python/lib/python3.6/site-packages/migrate/versioning/api.py", line 250, in version_control
    ControlledSchema.create(engine, repository, version)
  File "/app/.heroku/python/lib/python3.6/site-packages/migrate/versioning/schema.py", line 141, in create
    table = cls._create_table_version(engine, repository, version)
  File "/app/.heroku/python/lib/python3.6/site-packages/migrate/versioning/schema.py", line 189, in _create_table_version
    raise exceptions.DatabaseAlreadyControlledError
migrate.exceptions.DatabaseAlreadyControlledError
```

```#!flask/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db
import os.path
print(SQLALCHEMY_DATABASE_URI)
print(SQLALCHEMY_MIGRATE_REPO)
db.create_all()

if  not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
    api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
    print ("SQLALCHEMY_MIGRATE_REPO" + SQLALCHEMY_MIGRATE_REPO)
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO,
api.version(SQLALCHEMY_MIGRATE_REPO))
```

答: I have seen this issue. To solve it, just remove the database file app.db and rerun the script db_create.py

ContentLicense: CC BY-SA 4.0

Body:
this is tdb_create.py file under C:\Users\Yasmi\Documents\microblog\flask-psps> which i try to run on heroku using web: gunicorn app:app
init: python db_create.py
upgrade: python db_upgrade.py which is in procfile file under the same folder.
db_create.py doesnt pass , ant figure up why. I did it due to changes in field description in mdels.py file

C:\Users\Yasmi\Documents\microblog\flask-psps>heroku run init
Running init on flask-psps... up, run.8964 (Free)

  postgres://rydbbszhueldrc:9e71d3c3f199b9dea08833d4a4efcf0e3cc9e1519d77ebc48933fca16f39be9c@ec2-23-21-220-48.compute-1.amazonaws.com:5432/dfrmo4cc9toudp
basedir is /app

  postgres://rydbbszhueldrc:9e71d3c3f199b9dea08833d4a4efcf0e3cc9e1519d77ebc48933fca16f39be9c@ec2-23-21-220-48.compute-1.amazonaws.com:5432/dfrmo4cc9toudp
/app/db_repository
SQLALCHEMY_MIGRATE_REPO/app/db_repository
Traceback (most recent call last):
  File "db_create.py", line 15, in <module>
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
  File "<decorator-gen-8>", line 2, in version_control
  File "/app/.heroku/python/lib/python3.6/site-packages/migrate/versioning/util/__init__.py", line 167, in with_engine
    return f(*a, **kw)
  File "/app/.heroku/python/lib/python3.6/site-packages/migrate/versioning/api.py", line 250, in version_control
    ControlledSchema.create(engine, repository, version)
  File "/app/.heroku/python/lib/python3.6/site-packages/migrate/versioning/schema.py", line 141, in create
    table = cls._create_table_version(engine, repository, version)
  File "/app/.heroku/python/lib/python3.6/site-packages/migrate/versioning/schema.py", line 189, in _create_table_version
    raise exceptions.DatabaseAlreadyControlledError
migrate.exceptions.DatabaseAlreadyControlledError

#!flask/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db
import os.path
print(SQLALCHEMY_DATABASE_URI)
print(SQLALCHEMY_MIGRATE_REPO)
db.create_all()

if  not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
    api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
    print ("SQLALCHEMY_MIGRATE_REPO" + SQLALCHEMY_MIGRATE_REPO)
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO,
api.version(SQLALCHEMY_MIGRATE_REPO))


问:
Binding the checked value of a checkbox to boolean attribute of an object in angular
I am trying to bind the value of a checkbox to a boolean variable in an object. The checkbox is used inside
of a table. The functionality that I am trying to achieve is that when I click the checkbox, it should toggle the
boolean variable in the object and the result of which would be shown on the html.

I am using the below code to achieve the same:

HTML:

```<code><tr *ngFor="let item of getListOfItems(); let i = index">
  <td>{{ i+1 }}</td>
  <td>{{ item.action }}</td>
  <td><input name="chk" type="checkbox" [(ngModel)]="item.isComplete" /></td>
  <td [ngSwitch]="item.isComplete">
    <span *ngSwitchCase="true">Yes</span>
    <span *ngSwitchDefault>No</span>
  </td>
</tr>
</code>```

Component:

```<code>getListOfItems() {
  var items = [
    new TodoItem('Buy Flowers', false),
    new TodoItem('Get Shoes', false),
    new TodoItem('Collect Tickets', true),
    new TodoItem('Call Joe', false),
  ];

  return items;
}
</code>```

TodoItem Class

```<code>export class TodoItem {
    action: string;
    isComplete: boolean;

    constructor(action: string, isComplete) {
        this.action = action;
        this.isComplete = isComplete;
    }
}
</code>```

However, when I run the app, the browser keeps on loading the page and freezes after a period of time.
When I comment this checkbox , everything comes back to normal and the code works fine. Could not figure out a solution. Any help would be appreciated.

答:
The problem is caused by getListOfItems() returning a new array instance for every call.

Rather assign the value of the method to a property:

```<code>  items: Array<TodoItem>

  ngOnInit(): void {
    this.getListOfItems();
  }

  getListOfItems() {
    var items = [
      new TodoItem('Buy Flowers', false),
      new TodoItem('Get Shoes', false),
      new TodoItem('Collect Tickets', true),
      new TodoItem('Call Joe', false),
    ];

    this.items = items;
  }
</code>```

StackBlitz

Body:
I am trying to bind the value of a checkbox to a boolean variable in an object. The checkbox is used inside
of a table. The functionality that I am trying to achieve is that when I click the checkbox, it should toggle the
boolean variable in the object and the result of which would be shown on the html.

I am using the below code to achieve the same:

HTML:

  {{ i+1 }}
  {{ item.action }}
  <input name="chk" type="checkbox" [(ngModel)]="item.isComplete" />

    Yes
    No

Component:

getListOfItems() {
  var items = [
    new TodoItem('Buy Flowers', false),
    new TodoItem('Get Shoes', false),
    new TodoItem('Collect Tickets', true),
    new TodoItem('Call Joe', false),
  ];

  return items;
}

TodoItem Class

export class TodoItem {
    action: string;
    isComplete: boolean;

    constructor(action: string, isComplete) {
        this.action = action;
        this.isComplete = isComplete;
    }
}

However, when I run the app, the browser keeps on loading the page and freezes after a period of time.
When I comment this checkbox , everything comes back to normal and the code works fine. Could not figure out a solution. Any help would be appreciated.

Body:
The problem is caused by getListOfItems() returning a new array instance for every call.

Rather assign the value of the method to a property:

  items: Array<TodoItem>

  ngOnInit(): void {
    this.getListOfItems();
  }

  getListOfItems() {
    var items = [
      new TodoItem('Buy Flowers', false),
      new TodoItem('Get Shoes', false),
      new TodoItem('Collect Tickets', true),
      new TodoItem('Call Joe', false),
    ];

    this.items = items;
  }

StackBlitz


问:
SSL for custom client domains
I have an app (hosted in heroku) where customers have an individual subdomain e.g. client1.myapp.com, client2.myapp.com I am using a wildcard SSL cert here.

If however a client wants to use their own custom domain e.g. CNAME app.client1.com

How can i automatically provide an SSL cert (I'm guessing using Lets Encrypt) for the client without them providing me a certificate to upload in a similar way to firebase etc.. provides SSL certs for  domains.

答:
If you are hosting the new application in Heroku/new domain is directed to Heroku app, they will take care of the SSL Certificates for you, as long as you run the application on a paid dyno. Which you should as its a client's application!

https://devcenter.heroku.com/articles/ssl

Heroku provides free Automated Certificate Management (ACM) for all
  applications running on paid dynos. With ACM, Heroku automatically
  provisions and renews SSL certificates for your application. If you
  prefer to upload your own certificate manually, follow the steps in
  this article.

You only have to make an application in Heroku, upgrade the dyno and configure the custom domain name (app.client1.com) for the application, following instructions at https://devcenter.heroku.com/articles/custom-domains

Title: SSL for custom client domains


问:
How to make a proper Javascript regex?
I would like to make regular expression so it matches only value as bellow, but I want to make it so you have to have at least one (i know it works with the "+" symbol) a-z letter, but I don't know where to put the "+" to make it work correctly. Any help on this?

```<code>.match(/^[0-9a-z]{3,10}$/i)
</code>```

Edit:
It should match for string like "12a", but it shouldn't match for "123" cause it has to have at least one a-z in it.

```<code>if( ! ($Username.match(/^[0-9a-z]{3,10}$/i) && $Username.match(/[a-z]/i)) ) {
    return false;
}
</code>```

Edit:
Thanks to Felix now the example code above works perfect.

答:
I believe this will do the filtering, although you'll have to check the character count separately:</p>

```<code>^[0-9a-z]*[a-z]+[0-9a-z]*$
</code>```

Title: How to make a proper Javascript regex?

Body:
I would like to make regular expression so it matches only value as bellow, but I want to make it so you have to have at least one (i know it works with the "+" symbol) a-z letter, but I don't know where to put the "+" to make it work correctly. Any help on this?

.match(/^[0-9a-z]{3,10}$/i)

Edit:
It should match for string like "12a", but it shouldn't match for "123" cause it has to have at least one a-z in it.

if( ! ($Username.match(/^[0-9a-z]{3,10}$/i) && $Username.match(/[a-z]/i)) ) {
    return false;
}

Edit:
Thanks to Felix now the example code above works perfect.

Body:
I believe this will do the filtering, although you'll have to check the character count separately:

^[0-9a-z]*[a-z]+[0-9a-z]*$


问:
Preloading lazy route with canLoad applied
The docs says i cannot use the two features together https://angular.io/docs/ts/latest/guide/router.html#!#canload-blocks-preload

What i want to achieve is to lazy load routes if the user is authorized to visit the route.

答:
you might wanna use CanActivate guard instead of CanLoad.
that way you will still be able to set preloadingStrategy to PreloadAllModules and it effectively preload the content of the 'lazy loaded feature' module even if
canActivate returns false.


问:
How to add the value of a 2nd promise return to an array of values
I am not sure if the title of the question makes sense, but probably with the code it will help me explain it.

I have the following code but in sharepoint content type is not returned by default in the list item values.

```<code>function getListItems(listId, camlQueryString, selectProperties){
    var deferred = $q.defer();
    var context = SP.ClientContext.get_current();
    var web = context.get_web();

    var list = web.get_lists().getById(listId);

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml(camlQueryString);

    var listItems = list.getItems(camlQuery);

    //var includesString = "Include(ID,Title,AssignedTo, WorkflowOutcome, ApproverComments, FileRef, WorkflowItemId, Created, Modified)"; // + selectProperties.join(", ") +  ")";
    if(selectProperties) {
        var includesString = convertSelectPropertiesToIncludesString(selectProperties);
        context.load(listItems, includesString);
    } else {
        context.load(listItems);
    }
    context.executeQueryAsync(
        function() {
            $log.info("Successfully retrieved list item result");

            deferred.resolve(listItems);
        },
        function(error, errorInfo) {
            $log.warn("Retrieving list item result failed");

            deferred.reject(errorInfo);
        }
    );
    return deferred.promise;
}
</code>```

And I am trying to convert this method to get also the content type name in the same array of values

```<code>function getListItemswithContentType(listId, camlQueryString, selectProperties){
    var deferred = $q.defer();
    var context = SP.ClientContext.get_current();
    var web = context.get_web();

    var list = web.get_lists().getById(listId);

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml(camlQueryString);

    var listItems = list.getItems(camlQuery);

    //var includesString = "Include(ID,Title,AssignedTo, WorkflowOutcome, ApproverComments, FileRef, WorkflowItemId, Created, Modified)"; // + selectProperties.join(", ") +  ")";
    if(selectProperties) {
        var includesString = convertSelectPropertiesToIncludesString(selectProperties);
        context.load(listItems, includesString);
    } else {
        context.load(listItems);
    }

    context.executeQueryAsync(Function.createDelegate(this, SuccessHandler),Function.createDelegate(this, ErrorHandler));

    return deferred.promise;
}

function SuccessHandler(result) {
    listItemEnumerator = listItems.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        oListItem = listItemEnumerator.get_current();
        var CT = oListItem.get_contentType();
        context.load(CT);
        context.executeQueryAsync(
            (function (contentobject) {
                return function () {
                    var value = contentobject.get_name();
                    alert("VAL: "+value);
                };
            }(contentobject)),
            function () {
                alert("No Success");
            }
        );
    }
}

function ErrorHandler(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</code>```

However as you can see there is 2 async executions here, in the success handler method I return the content type name, but I have no idea how to add that content type name as a value to the listitems array.

Update 1

Caller method

```<code>function GetRelatedBillingDocumentsFromList(selectProperties, currentBillCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions) {
                $log.info("Retrieving related billing documents for bill cycle with name [" + currentBillCyclePath + "]");
                var deferred = $q.defer();
                var webUrl = _spPageContextInfo.webAbsoluteUrl;
                var viewFields = spService.ConvertSelectPropertiesToViewFields(selectProperties);
                // query must return the documents for the same client but in other bill cycles not the current one
                var camlQuery = '<View>' +   viewFields +
                        '<Query>' +
                            '<Where>' +
                                //'<And>' +
                                    '<Eq>' +
                                        '<FieldRef Name="ClientCode" />' +
                                        '<Value Type="Text">'+ clientCode + '</Value>' +
                                    '</Eq>' +
                                //  '<Neq>' +
                                //      '<FieldRef Name="ContentType" />' +
                                //      '<Value Type="Computed">Bill Cycle</Value>' +
                                //  '</Neq>' +
                                //'</And>' +
                            '</Where>' +
                            //'<QueryOptions>' +
                            //  '<ViewAttributes Scope="RecursiveAll" />' +
                            //'</QueryOptions>' +
                        '</Query>' +
                    '</View>';

                var billCyclesListId = "{c23bbae4-34f7-494c-8f67-acece3ba60da}";
                spService.GetListItemswithContentType(billCyclesListId, camlQuery, selectProperties)
                .then(function(listItems) {
                    var listItemsWithValues = [];
                    if(listItems) {
                        var enumerator = listItems.getEnumerator();
                        while (enumerator.moveNext()) {
                            var listItem = enumerator.get_current();
                            var listItemValues = [];
                            selectProperties
                            .forEach(function(propertyName) {
                                var value = listItem.get_item(propertyName);
                                listItemValues[propertyName] = value;
                            });

                            listItemsWithValues.push(listItemValues);
                        }
                    }

                    // Create the full item url
                    listItemsWithValues.forEach(function(listItem) {
                        var fileDirRef = listItem["FileRef"];
                        var id = listItem["ID"];
                        var serverUrl = _spPageContextInfo.webAbsoluteUrl.replace(_spPageContextInfo.webServerRelativeUrl,"");
                        var dispFormUrl = serverUrl + fileDirRef + "/DispForm.aspx?ID=" + id;
                        listItem["FileRef"] = dispFormUrl;
                    });

                    var enhancedListItemValues = spService.SpSearchQuery.EnhanceSearchResults(listItemsWithValues, enhanceFunctions);
                    deferred.resolve(listItemsWithValues);
                })
                .catch (function (message) {
                    deferred.reject();
                });

                return deferred.promise;
            }
</code>```

答:
Maybe the following will work, if you're using some older javascript engine you may want to look into how to polyfil Promise.all and new Promise. If the arrow functions don't work you can replace e => z with function(e){return z;}

```<code>function SuccessHandler(result) {
  listItemEnumerator = listItems.getEnumerator();
  const promises = [];
  while (listItemEnumerator.moveNext()) {
    oListItem = listItemEnumerator.get_current();
    var CT = oListItem.get_contentType();
    context.load(CT);
    promises.push(
      new Promise(
        (resolve,reject) =>
          context.executeQueryAsync(
            //if contentobject is shared mutable object you're in trouble
            //  that doesn't work with concurrently running code that depends on it
            //  if it's mutable then prividing it in a closure with the IIFE isn't going
            //  to save you either
            (function (contentobject) {
              return function () {
                var value = contentobject.get_name();
                console.log("VAL: " , value);
                //not sure what it is you want to return here
                return [value,result];
              };
            }(contentobject)),
            function () {
              console.log("No Success");
            }
          )
      )
    );
    return Promise.all(promises)
    .then(
      results => {
        results.forEach(
          //just log all the results, you can remove the then
          //  if this was what you need
          ([value,result]) => console.log("value:",value,"result",result)
        );
        return result;
      }
    )
  }
}
</code>```

If the function that calls getListItemswithContentType needs to know when it's done you can return a promise.

```<code>return new Promise(
  (resolve,reject) =>
    context.executeQueryAsync(
      x=>SuccessHandler(x).then(resolve,reject)
      ,error=>reject(error)
    )
);
</code>```

Body:
I am not sure if the title of the question makes sense, but probably with the code it will help me explain it.

I have the following code but in sharepoint content type is not returned by default in the list item values.

function getListItems(listId, camlQueryString, selectProperties){
    var deferred = $q.defer();
    var context = SP.ClientContext.get_current();
    var web = context.get_web();

    var list = web.get_lists().getById(listId);

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml(camlQueryString);

    var listItems = list.getItems(camlQuery);

    //var includesString = "Include(ID,Title,AssignedTo, WorkflowOutcome, ApproverComments, FileRef, WorkflowItemId, Created, Modified)"; // + selectProperties.join(", ") +  ")";
    if(selectProperties) {
        var includesString = convertSelectPropertiesToIncludesString(selectProperties);
        context.load(listItems, includesString);
    } else {
        context.load(listItems);
    }
    context.executeQueryAsync(
        function() {
            $log.info("Successfully retrieved list item result");

            deferred.resolve(listItems);
        },
        function(error, errorInfo) {
            $log.warn("Retrieving list item result failed");

            deferred.reject(errorInfo);
        }
    );
    return deferred.promise;
}

And I am trying to convert this method to get also the content type name in the same array of values

function getListItemswithContentType(listId, camlQueryString, selectProperties){
    var deferred = $q.defer();
    var context = SP.ClientContext.get_current();
    var web = context.get_web();

    var list = web.get_lists().getById(listId);

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml(camlQueryString);

    var listItems = list.getItems(camlQuery);

    //var includesString = "Include(ID,Title,AssignedTo, WorkflowOutcome, ApproverComments, FileRef, WorkflowItemId, Created, Modified)"; // + selectProperties.join(", ") +  ")";
    if(selectProperties) {
        var includesString = convertSelectPropertiesToIncludesString(selectProperties);
        context.load(listItems, includesString);
    } else {
        context.load(listItems);
    }

    context.executeQueryAsync(Function.createDelegate(this, SuccessHandler),Function.createDelegate(this, ErrorHandler));

    return deferred.promise;
}

function SuccessHandler(result) {
    listItemEnumerator = listItems.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        oListItem = listItemEnumerator.get_current();
        var CT = oListItem.get_contentType();
        context.load(CT);
        context.executeQueryAsync(
            (function (contentobject) {
                return function () {
                    var value = contentobject.get_name();
                    alert("VAL: "+value);
                };
            }(contentobject)),
            function () {
                alert("No Success");
            }
        );
    }
}

function ErrorHandler(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

However as you can see there is 2 async executions here, in the success handler method I return the content type name, but I have no idea how to add that content type name as a value to the listitems array.

Update 1

Caller method

function GetRelatedBillingDocumentsFromList(selectProperties, currentBillCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions) {
                $log.info("Retrieving related billing documents for bill cycle with name [" + currentBillCyclePath + "]");
                var deferred = $q.defer();
                var webUrl = _spPageContextInfo.webAbsoluteUrl;
                var viewFields = spService.ConvertSelectPropertiesToViewFields(selectProperties);
                // query must return the documents for the same client but in other bill cycles not the current one
                var camlQuery = '<View>' +   viewFields +
                        '<Query>' +
                            '<Where>' +
                                //'<And>' +
                                    '<Eq>' +
                                        '<FieldRef Name="ClientCode" />' +
                                        '<Value Type="Text">'+ clientCode + '</Value>' +
                                    '</Eq>' +
                                //  '<Neq>' +
                                //      '<FieldRef Name="ContentType" />' +
                                //      '<Value Type="Computed">Bill Cycle</Value>' +
                                //  '</Neq>' +
                                //'</And>' +
                            '</Where>' +
                            //'<QueryOptions>' +
                            //  '<ViewAttributes Scope="RecursiveAll" />' +
                            //'</QueryOptions>' +
                        '</Query>' +
                    '</View>';

                var billCyclesListId = "{c23bbae4-34f7-494c-8f67-acece3ba60da}";
                spService.GetListItemswithContentType(billCyclesListId, camlQuery, selectProperties)
                .then(function(listItems) {
                    var listItemsWithValues = [];
                    if(listItems) {
                        var enumerator = listItems.getEnumerator();
                        while (enumerator.moveNext()) {
                            var listItem = enumerator.get_current();
                            var listItemValues = [];
                            selectProperties
                            .forEach(function(propertyName) {
                                var value = listItem.get_item(propertyName);
                                listItemValues[propertyName] = value;
                            });

                            listItemsWithValues.push(listItemValues);
                        }
                    }

                    // Create the full item url
                    listItemsWithValues.forEach(function(listItem) {
                        var fileDirRef = listItem["FileRef"];
                        var id = listItem["ID"];
                        var serverUrl = _spPageContextInfo.webAbsoluteUrl.replace(_spPageContextInfo.webServerRelativeUrl,"");
                        var dispFormUrl = serverUrl + fileDirRef + "/DispForm.aspx?ID=" + id;
                        listItem["FileRef"] = dispFormUrl;
                    });

                    var enhancedListItemValues = spService.SpSearchQuery.EnhanceSearchResults(listItemsWithValues, enhanceFunctions);
                    deferred.resolve(listItemsWithValues);
                })
                .catch (function (message) {
                    deferred.reject();
                });

                return deferred.promise;
            }

Body:
Maybe the following will work, if you're using some older javascript engine you may want to look into how to polyfil Promise.all and new Promise. If the arrow functions don't work you can replace e => z with function(e){return z;}

function SuccessHandler(result) {
  listItemEnumerator = listItems.getEnumerator();
  const promises = [];
  while (listItemEnumerator.moveNext()) {
    oListItem = listItemEnumerator.get_current();
    var CT = oListItem.get_contentType();
    context.load(CT);
    promises.push(
      new Promise(
        (resolve,reject) =>
          context.executeQueryAsync(
            //if contentobject is shared mutable object you're in trouble
            //  that doesn't work with concurrently running code that depends on it
            //  if it's mutable then prividing it in a closure with the IIFE isn't going
            //  to save you either
            (function (contentobject) {
              return function () {
                var value = contentobject.get_name();
                console.log("VAL: " , value);
                //not sure what it is you want to return here
                return [value,result];
              };
            }(contentobject)),
            function () {
              console.log("No Success");
            }
          )
      )
    );
    return Promise.all(promises)
    .then(
      results => {
        results.forEach(
          //just log all the results, you can remove the then
          //  if this was what you need
          ([value,result]) => console.log("value:",value,"result",result)
        );
        return result;
      }
    )
  }
}

If the function that calls getListItemswithContentType needs to know when it's done you can return a promise.

return new Promise(
  (resolve,reject) =>
    context.executeQueryAsync(
      x=>SuccessHandler(x).then(resolve,reject)
      ,error=>reject(error)
    )
);


问:
Reading values from json files into a node.js file
i was asked by my senior to establish connection into database, but rather than hardcoding the values to creating connection, he asked me to store the values which are required to establish connection in a .JSON file and asked me to get the values into node.js file

This is my json code

```<code>{
    "values" : {
        "host" : "localhost",
        "user" : "root",
        "password" : "root",
        "database" : "node"
    }
}
</code>```

This following code has HARDCODED the vlues to establish connection

```<code>var mysql = require('mysql');

var con  = mysql.createConnection({
    host : "localhost",
    user : "root",
    password : "root",
    database : "node"
});

con.connect(function(err) {
    if (err) throw err;
    console.log("Connected!");
    var sql = "INSERT INTO details (name, prof) VALUES ('grijan1', 'student')";
    con.query(sql, function (err, result) {
      if (err) throw err;
      console.log("1 record inserted");
    });
  });
</code>```

How can i do it?

答:
You put that JSON data into a new file and you load in a new var :</p>

```<code>var cnx = require('./file.json');
var con = mysql.createConnection(cnx.values);
</code>```

Body:
i was asked by my senior to establish connection into database, but rather than hardcoding the values to creating connection, he asked me to store the values which are required to establish connection in a .JSON file and asked me to get the values into node.js file

This is my json code

{
    "values" : {
        "host" : "localhost",
        "user" : "root",
        "password" : "root",
        "database" : "node"
    }
}

This following code has HARDCODED the vlues to establish connection

var mysql = require('mysql');

var con  = mysql.createConnection({
    host : "localhost",
    user : "root",
    password : "root",
    database : "node"
});

con.connect(function(err) {
    if (err) throw err;
    console.log("Connected!");
    var sql = "INSERT INTO details (name, prof) VALUES ('grijan1', 'student')";
    con.query(sql, function (err, result) {
      if (err) throw err;
      console.log("1 record inserted");
    });
  });

How can i do it?

Body:
You put that JSON data into a new file and you load in a new var :

var cnx = require('./file.json');
var con = mysql.createConnection(cnx.values);


问:
spacing between UITableViewCells swift3
I am creating a IOS app in swift and want to add spacing between cells like this

I would like to give space of each table view cell same like my attach image.
How I can do that? and Right now all cells are coming without any space.
swift3

答:
Please try it. It is working fine for me.

You can use section instead of row.
You return array count in numberOfSectionsInTableView method and set 1 in numberOfRowsInSection delegate method

Use [array objectAtIndex:indexPath.section] in cellForRowAtIndexPath method.

Set the heightForHeaderInSection as 40 or according to your requirement.

Thanks,Hope it will helps to you

Title: spacing between UITableViewCells swift3