问:
How to properly connect to MongoDB with Spring?
I'm total beginner in Spring. I want to create simple Spring app connecting to MongoDB. I generated Spring Boot with Spring Initializer and I created necessery files following a guide.

MongoDB is working. When I run the app I got the following error:

SpringFramework 2.2.0 M3
MongoDB 4.0
Dependencies (chosen in Spring Initializer): Web, MongoDB

DatabaseConfiguration.java

```<code>package com.talkingflashcards.server.TalkingFlashcards.config;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@EnableMongoRepositories(basePackages = "com.talkingflashcards.server.TalkingFlashcards.repository")

@Configuration
public class DatabaseConfiguration extends AbstractMongoClientConfiguration {

    @Value("${spring.data.mongodb.host}")
    private String host;

    @Value("${spring.data.mongodb.port}")
    private String port;

    @Value("${spring.data.mongodb.username}")
    private String username;

    @Value("${spring.data.mongodb.password}")
    private String password;

    @Value("${spring.data.mongodb.database}")
    private String database;

    @Override
    public MongoClient mongoClient() {
        return MongoClients.create(host + ":" + port);
    }

    @Override
    protected String getDatabaseName() {
        return database;
    }
}

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
    2019-05-29 23:52:19.955 ERROR 10144 --- [           main] o.s.boot.SpringApplication               : Application run failed

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in class path resource [com/talkingflashcards/server/TalkingFlashcards/config/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/talkingflashcards/server/TalkingFlashcards/config/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:638) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:468) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1325) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1164) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:868) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:782) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:404) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:319) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1275) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1263) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at com.talkingflashcards.server.TalkingFlashcards.TalkingFlashcardsApplication.main(TalkingFlashcardsApplication.java:14) [classes/:na]
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/talkingflashcards/server/TalkingFlashcards/config/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:633) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        ... 19 common frames omitted
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/talkingflashcards/server/TalkingFlashcards/config/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:638) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:468) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1325) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1164) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.resolveBeanReference(ConfigurationClassEnhancer.java:394) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:366) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.mongoDbFactory(<generated>) ~[classes/:na]
        at org.springframework.data.mongodb.config.AbstractMongoClientConfiguration.mongoTemplate(AbstractMongoClientConfiguration.java:58) ~[spring-data-mongodb-2.2.0.M4.jar:2.2.0.M4]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.CGLIB$mongoTemplate$3(<generated>) ~[classes/:na]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38$$FastClassBySpringCGLIB$$5311e25d.invoke(<generated>) ~[classes/:na]
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.mongoTemplate(<generated>) ~[classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        ... 20 common frames omitted
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:633) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        ... 43 common frames omitted
    Caused by: java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at com.mongodb.ConnectionString.<init>(ConnectionString.java:288) ~[mongodb-driver-core-3.11.0-beta3.jar:na]
        at com.mongodb.client.MongoClients.create(MongoClients.java:61) ~[mongodb-driver-3.11.0-beta3.jar:na]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration.mongoClient(DatabaseConfiguration.java:32) ~[classes/:na]
        at org.springframework.data.mongodb.config.AbstractMongoClientConfiguration.mongoDbFactory(AbstractMongoClientConfiguration.java:71) ~[spring-data-mongodb-2.2.0.M4.jar:2.2.0.M4]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.CGLIB$mongoDbFactory$2(<generated>) ~[classes/:na]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38$$FastClassBySpringCGLIB$$5311e25d.invoke(<generated>) ~[classes/:na]
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.mongoDbFactory(<generated>) ~[classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        ... 44 common frames omitted

    Disconnected from the target VM, address: '127.0.0.1:60940', transport: 'socket'

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

答:
With Spring Boot, you need not config MongoDB connection explicitly.
In application.properties, you only need set below config (with MongoDB at local)

spring.data.mongodb.uri=mongodb://localhost:27017/yourDB
```

Body:
I'm total beginner in Spring. I want to create simple Spring app connecting to MongoDB. I generated Spring Boot with Spring Initializer and I created necessery files following a guide.

MongoDB is working. When I run the app I got the following error:

SpringFramework 2.2.0 M3
MongoDB 4.0
Dependencies (chosen in Spring Initializer): Web, MongoDB

DatabaseConfiguration.java

package com.talkingflashcards.server.TalkingFlashcards.config;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@EnableMongoRepositories(basePackages = "com.talkingflashcards.server.TalkingFlashcards.repository")

@Configuration
public class DatabaseConfiguration extends AbstractMongoClientConfiguration {

    @Value("${spring.data.mongodb.host}")
    private String host;

    @Value("${spring.data.mongodb.port}")
    private String port;

    @Value("${spring.data.mongodb.username}")
    private String username;

    @Value("${spring.data.mongodb.password}")
    private String password;

    @Value("${spring.data.mongodb.database}")
    private String database;

    @Override
    public MongoClient mongoClient() {
        return MongoClients.create(host + ":" + port);
    }

    @Override
    protected String getDatabaseName() {
        return database;
    }
}

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
    2019-05-29 23:52:19.955 ERROR 10144 --- [           main] o.s.boot.SpringApplication               : Application run failed

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in class path resource [com/talkingflashcards/server/TalkingFlashcards/config/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/talkingflashcards/server/TalkingFlashcards/config/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:638) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:468) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1325) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1164) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:868) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:782) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:404) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:319) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1275) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1263) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at com.talkingflashcards.server.TalkingFlashcards.TalkingFlashcardsApplication.main(TalkingFlashcardsApplication.java:14) [classes/:na]
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/talkingflashcards/server/TalkingFlashcards/config/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:633) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        ... 19 common frames omitted
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/talkingflashcards/server/TalkingFlashcards/config/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:638) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:468) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1325) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1164) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.resolveBeanReference(ConfigurationClassEnhancer.java:394) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:366) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.mongoDbFactory(<generated>) ~[classes/:na]
        at org.springframework.data.mongodb.config.AbstractMongoClientConfiguration.mongoTemplate(AbstractMongoClientConfiguration.java:58) ~[spring-data-mongodb-2.2.0.M4.jar:2.2.0.M4]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.CGLIB$mongoTemplate$3(<generated>) ~[classes/:na]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38$$FastClassBySpringCGLIB$$5311e25d.invoke(<generated>) ~[classes/:na]
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.mongoTemplate(<generated>) ~[classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        ... 20 common frames omitted
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:633) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        ... 43 common frames omitted
    Caused by: java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at com.mongodb.ConnectionString.<init>(ConnectionString.java:288) ~[mongodb-driver-core-3.11.0-beta3.jar:na]
        at com.mongodb.client.MongoClients.create(MongoClients.java:61) ~[mongodb-driver-3.11.0-beta3.jar:na]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration.mongoClient(DatabaseConfiguration.java:32) ~[classes/:na]
        at org.springframework.data.mongodb.config.AbstractMongoClientConfiguration.mongoDbFactory(AbstractMongoClientConfiguration.java:71) ~[spring-data-mongodb-2.2.0.M4.jar:2.2.0.M4]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.CGLIB$mongoDbFactory$2(<generated>) ~[classes/:na]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38$$FastClassBySpringCGLIB$$5311e25d.invoke(<generated>) ~[classes/:na]
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.mongoDbFactory(<generated>) ~[classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        ... 44 common frames omitted

    Disconnected from the target VM, address: '127.0.0.1:60940', transport: 'socket'

    Process finished with exit code 1


来源: stackexchange

问:
Creating schema via declarative mapping: Base.metadata.create_all(engine) does not work
Here is an absurd problem with sqlalchemy that seems easy! First, this is my config file for connecting to mysql database:

```<code>from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
engine = create_engine('mysql://root:@localhost:3306/digi')
</code>```

and then, I am trying to create a table called 'sale-history' :

```<code>from config import *
from sqlalchemy import *

class Sale(Base):
    __tablename__ = 'sale-history'
    order_id = column(Integer, primary_key= True)
    customer_id = column(Integer)
    item_id = column(Integer)       #froeign key with product list
    cartFinalize_dateTime = column(DATETIME)
    amount_ordrered = column(Integer)
    city_name = column(String(191))
    quantity_ordered = column(Integer)

    def __repr__(self):
        return "<Sale(city_name='%s')>" % (self.city_name)

Sale.__table__
Base.metadata.create_all(engine)
</code>```

Now, what I wonder is that

```<code>Sale.__table__
</code>```

and

```<code>Base.metadata.create_all(engine)
</code>```

are not known to my code. More accurate, these are not in suggestion options showed by pycharm editor. Debugging the code does not throw any error(returns 0). What should I do to create tables?
I appreciate your consideration so much!

答:
The code is using column to define columns in the table but it should be using Column (note the upper-case "C").

A few tips/comments

Pycharm may provide better support if you avoid the from module import * idiom. You can alias module names if they are to long to type, for example import sqlalchemy as sa

You can see the SQL generated by the engine by passing echo=True to create_engine

Tablenames with hyphens need to be quoted with backticks to be valid.  Sqlalchemy does this automatically, but other applications may not. Using underscores instead may be more convenient.

The final code might look like this:

config

```<code>from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
engine = create_engine('mysql://root:@localhost:3306/test', echo=True)
</code>```

Model

```<code>import sqlachemy as sa
import config

class Sale(Base):
    __tablename__ = 'sale-history'
    order_id = sa.Column(sa.Integer, primary_key=True)
    customer_id = sa.Column(sa.Integer)
    item_id = sa.Column(sa.Integer)       # foreign key with product list
    cartFinalize_dateTime = sa.Column(sa.DATETIME)
    amount_ordrered = sa.Column(sa.Integer)
    city_name = sa.Column(sa.String(191))
    quantity_ordered = sa.Column(sa.Integer)

    def __repr__(self):
        return "<Sale(city_name='%s')>" % (self.city_name)

Base.metadata.create_all(config.engine)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is an absurd problem with sqlalchemy that seems easy! First, this is my config file for connecting to mysql database:

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
engine = create_engine('mysql://root:@localhost:3306/digi')

and then, I am trying to create a table called 'sale-history' :

from config import *
from sqlalchemy import *

class Sale(Base):
    __tablename__ = 'sale-history'
    order_id = column(Integer, primary_key= True)
    customer_id = column(Integer)
    item_id = column(Integer)       #froeign key with product list
    cartFinalize_dateTime = column(DATETIME)
    amount_ordrered = column(Integer)
    city_name = column(String(191))
    quantity_ordered = column(Integer)

    def __repr__(self):
        return "<Sale(city_name='%s')>" % (self.city_name)

Sale.__table__
Base.metadata.create_all(engine)

Now, what I wonder is that

Sale.__table__

and

Base.metadata.create_all(engine)

are not known to my code. More accurate, these are not in suggestion options showed by pycharm editor. Debugging the code does not throw any error(returns 0). What should I do to create tables?
I appreciate your consideration so much!

Body:
The code is using column to define columns in the table but it should be using Column (note the upper-case "C").

A few tips/comments

Pycharm may provide better support if you avoid the from module import * idiom. You can alias module names if they are to long to type, for example import sqlalchemy as sa

You can see the SQL generated by the engine by passing echo=True to create_engine

Tablenames with hyphens need to be quoted with backticks to be valid.  Sqlalchemy does this automatically, but other applications may not. Using underscores instead may be more convenient.

The final code might look like this:

config

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
engine = create_engine('mysql://root:@localhost:3306/test', echo=True)

Model

import sqlachemy as sa
import config

class Sale(Base):
    __tablename__ = 'sale-history'
    order_id = sa.Column(sa.Integer, primary_key=True)
    customer_id = sa.Column(sa.Integer)
    item_id = sa.Column(sa.Integer)       # foreign key with product list
    cartFinalize_dateTime = sa.Column(sa.DATETIME)
    amount_ordrered = sa.Column(sa.Integer)
    city_name = sa.Column(sa.String(191))
    quantity_ordered = sa.Column(sa.Integer)

    def __repr__(self):
        return "<Sale(city_name='%s')>" % (self.city_name)

Base.metadata.create_all(config.engine)


问:
What is the best way to pass the **sensitive data** from one action method controller to another controller action method controller
Here am using TempData["Amount"] to pass the total cart amount from one controller action to another action method. so I had a doubt its good practice to use TempData["Amount"] pass sensitive information from one action method to another action method . what's the life time of time data (like sessions 20 mins) and how handle the exception of TempData["Amount"].

```<code>if (adoptionDetails != null)
      {
        foreach (var m in adoptionDetails.animalAdaptionDetails.ToList())
          {
            amount += Convert.ToInt32(m.amount);
            animalNames += m.name;
             animalNames += ",";
           }
        ViewBag.Amount = amount;
        ViewBag.animalsName = animalNames;
        TempData["Amount"] = amount;
        return View(adoptionDetails);
       }
else
     {
        return View("~/Views/Users/Errorpage.cshtml");
      }
</code>```

答:
TempData is tied to a user by the same logic that ties a Session to a user.

TempData is only available for the next request sent by the same session after which it is automatically deleted.

TempData is held in-memory in the server, only when you insert it into the response is it transmitted to the client.

Body:
Here am using TempData["Amount"] to pass the total cart amount from one controller action to another action method. so I had a doubt its good practice to use TempData["Amount"] pass sensitive information from one action method to another action method . what's the life time of time data (like sessions 20 mins) and how handle the exception of TempData["Amount"].

if (adoptionDetails != null)
      {
        foreach (var m in adoptionDetails.animalAdaptionDetails.ToList())
          {
            amount += Convert.ToInt32(m.amount);
            animalNames += m.name;
             animalNames += ",";
           }
        ViewBag.Amount = amount;
        ViewBag.animalsName = animalNames;
        TempData["Amount"] = amount;
        return View(adoptionDetails);
       }
else
     {
        return View("~/Views/Users/Errorpage.cshtml");
      }


问:
why doesn't ODBC support french accented words when inserting to sql server?
I am working with php to insert a line in sql server with odbc but I have this problem with french accents ( é , â , ô , î , è ,...), when I insert inside sql server it works and also php reads it well, but when inserting using odbc it is read as a special character

Example:

```<code>$sujet = 'BEM relevé bancaire';

$sql ="INSERT into matrice values('$groupe','$sujet','$nom','$ref','$ref','$next')";

odbc_exec($connection, $sql);
</code>```

Output:

ID:           542

    groupe:         Groupe_name

    CI:             BEM relevÃ© bancaire //THE PROBLEM

    Nom:            Name

    affectationRef: 1

    restAffect:     1

    nextAffect:     0

How can I make it reads the french accents ?

The possible duplicate doesn't answer my question unfortunately

答:
I would need to see the schema of the table to provide a definite answer.   SQL Server data types of char and varchar do not support double-byte characters sets.  Ensure that your table column, that you wish to insert to, has nchar or nvarchar as the data type.

You can test this with a simple table, with multiple columns.  Inserting the same value into column A and column B, will return different results.

```<code>Create table test (A varchar(20), B nvarchar(20))
Insert into test (A,B) values ('â',N'â')</code>```

If this does not solve the issue, then I think the client code page differs from that of the sql server code page.   You can read more about this here: You cannot correctly translate character data from a client to a server by using the SQL Server ODBC driver if the client code page differs from the server code page

Body:
I am working with php to insert a line in sql server with odbc but I have this problem with french accents ( é , â , ô , î , è ,...), when I insert inside sql server it works and also php reads it well, but when inserting using odbc it is read as a special character

Example:

$sujet = 'BEM relevé bancaire';

$sql ="INSERT into matrice values('$groupe','$sujet','$nom','$ref','$ref','$next')";

odbc_exec($connection, $sql);

Output:

ID:           542

    groupe:         Groupe_name

    CI:             BEM relevÃ© bancaire //THE PROBLEM

    Nom:            Name

    affectationRef: 1

    restAffect:     1

    nextAffect:     0

How can I make it reads the french accents ?

The possible duplicate doesn't answer my question unfortunately

Body:
I would need to see the schema of the table to provide a definite answer.   SQL Server data types of char and varchar do not support double-byte characters sets.  Ensure that your table column, that you wish to insert to, has nchar or nvarchar as the data type.

You can test this with a simple table, with multiple columns.  Inserting the same value into column A and column B, will return different results.

Create table test (A varchar(20), B nvarchar(20))
Insert into test (A,B) values ('â',N'â')

If this does not solve the issue, then I think the client code page differs from that of the sql server code page.   You can read more about this here: You cannot correctly translate character data from a client to a server by using the SQL Server ODBC driver if the client code page differs from the server code page


问:
Django template iterating over list
I have a list created in Django view:

```<code>list = [ elem1, elem2, ..., elemN ]
</code>```

The list is variable length: it can contain 0-6 elements. I want to iterate over the list in the template, but I would like the loop to run always 6 times, yielding None or empty string for non-existing elements.

I tried something like this:

```<code>{% for i in "0123456" %}
    {{ list.i }}
{% endfor %}
</code>```

but this obviously doesn't work. I know I could do this in the view, but I would like to have this in the template. Is is possible?

答: Check this snippet: Template range filter </p>

ContentLicense: CC BY-SA 3.0

Title: Django template iterating over list

Body:
I have a list created in Django view:

list = [ elem1, elem2, ..., elemN ]

The list is variable length: it can contain 0-6 elements. I want to iterate over the list in the template, but I would like the loop to run always 6 times, yielding None or empty string for non-existing elements.

I tried something like this:

{% for i in "0123456" %}
    {{ list.i }}
{% endfor %}

but this obviously doesn't work. I know I could do this in the view, but I would like to have this in the template. Is is possible?


问:
DI: constructor of class how injectable calls serveral times
There are several classes, how injected TermsExchangeService:

```<code>import {TermsExchangeService} from './terms-exchange.service';

@injectable()
export class TermsExchangeComponent {
  constructor(
        private termsExchangeService: TermsExchangeService
    ) {}
}
</code>```

and

```<code>import {TermsExchangeService} from './terms-exchange.service';

@injectable()
export class PurchaseMainComponent {
    constructor(
       private termsExchangeService: TermsExchangeService
    ) {}
</code>```

and service how has been used in PurchaseMainComponent and TermsExchangeComponent

```<code>@injectable()
export class TermsExchangeService {

    constructor() {
        debugger; // call 2 times!!!
    }
}
</code>```

I use autoBindInjectable:

```<code>var simpleContainer = new Container({ autoBindInjectable: true })
</code>```

When getting components from loop constructor of TermsExchangeService call several times:

```<code>for (let item = 0; item < components.length; item++) {
   const container = simpleContainer.get(components[item]);
}
</code>```

Why object created in every components? And how do normal injections?

答:
By default injectable is not Singleton.

Solve this problem can adding defaultScope: 'Singleton':

```<code>var simpleContainer = new Container(
            {
               autoBindInjectable: true,
               defaultScope: 'Singleton'
            }
)
</code>```

Body:
There are several classes, how injected TermsExchangeService:

import {TermsExchangeService} from './terms-exchange.service';

@injectable()
export class TermsExchangeComponent {
  constructor(
        private termsExchangeService: TermsExchangeService
    ) {}
}

and

import {TermsExchangeService} from './terms-exchange.service';

@injectable()
export class PurchaseMainComponent {
    constructor(
       private termsExchangeService: TermsExchangeService
    ) {}

and service how has been used in PurchaseMainComponent and TermsExchangeComponent

@injectable()
export class TermsExchangeService {

    constructor() {
        debugger; // call 2 times!!!
    }
}

I use autoBindInjectable:

var simpleContainer = new Container({ autoBindInjectable: true })

When getting components from loop constructor of TermsExchangeService call several times:

for (let item = 0; item < components.length; item++) {
   const container = simpleContainer.get(components[item]);
}

Why object created in every components? And how do normal injections?

Body:
By default injectable is not Singleton.

Solve this problem can adding defaultScope: 'Singleton':

var simpleContainer = new Container(
            {
               autoBindInjectable: true,
               defaultScope: 'Singleton'
            }
)


问:
Foreground does not apply for labels
I have some labels like this:

```<code> <Label x:Name="ledCalculate" Width="Auto" Content="Calculate" Height="25" FontFamily="Cambria" FontSize="18.667" VerticalContentAlignment="Bottom" Padding="10,0,0,0"  BorderThickness="0,0,0,1" Style="{StaticResource RightPanelLabels}" Grid.Row="11"/>
</code>```

I defined a style for it:

```<code> <Style TargetType="Label" x:Key="RightPanelLabels" BasedOn="{StaticResource
    {x:Type Label } }">

        <Setter Property="Foreground" Value="#FFEABEBE"></Setter>
        <Setter Property="BorderBrush" Value="#FF818080"></Setter>
        <Setter Property="BorderThickness" Value="0,0,0,1"></Setter>
    </Style>
</code>```

Border thickness setter in style applies for control and it has upper precedence in style, and visual studio ignores its values in local, but  foreground setter in style does not applies, when i set it locally it applies,

Why border thickness in style have upper precedence but foreground in local have upper precedence????????

I know there is a default template for labels like bellow that have a trigger for IsEnabled , that template is something like this:

```<code><ControlTemplate TargetType="{x:Type Label}">
    <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True">
        <ContentPresenter ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
    </Border>
    <ControlTemplate.Triggers>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
        </Trigger>
    </ControlTemplate.Triggers>
 </ControlTemplate>
</code>```

Can anyone help me?
Sorry for my English.

答:
you have to change property name in style setter</p>

```<code><Setter Property="TextBlock.Foreground" Value="#FFEABEBE">

</code>```

Title: Foreground does not apply for labels

Body:
I have some labels like this:

I defined a style for it:

Border thickness setter in style applies for control and it has upper precedence in style, and visual studio ignores its values in local, but  foreground setter in style does not applies, when i set it locally it applies,

Why border thickness in style have upper precedence but foreground in local have upper precedence????????

I know there is a default template for labels like bellow that have a trigger for IsEnabled , that template is something like this:

<ControlTemplate TargetType="{x:Type Label}">
    <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True">
        <ContentPresenter ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
    </Border>
    <ControlTemplate.Triggers>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
        </Trigger>
    </ControlTemplate.Triggers>
 </ControlTemplate>

Can anyone help me?
Sorry for my English.

Body:
you have to change property name in style setter

<Setter Property="TextBlock.Foreground" Value="#FFEABEBE">


问:
Email notifications after 'git archive'?
Custom requirement: How to notify specific people, using email as soon as a git archive command is run to download a single file?

Couldn't find a hook which can do so.

答:
Couldn't find a hook which can do so.

That is because there isn't one associated to the git archive command.

One possible workaround would be to make a global git alias to archive, in order to call a wrapper script which would:

check who is running that command

execute the actual git archive command

send an email appropriately

But all that is on the client side, which means this is valid for an environment shared among several clients.


问:
React Native: Phone number not updating and continuing to give error message
I have a bug in my application where I am trying to update a phone number and when I click on save, I get the error message and the original phone number stays populated:

Obviously, something has gone wrong with validation. I was hoping it was perhaps the regex although it has a solid one, but I changed it like so:

```<code>const regex = {
  userName: /^[-.\sa-zA-Z]+$/,
  cardName: /^[-\sa-zA-Z]+$/,
  password: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&*()\-+!\\.]?).{8,}$/,
  zip: /(^\d{5}$)|(^\d{5}-\d{4}$)/,
  memberId: /^\d+$/,
  // phoneNumber: /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
  phoneNumber: /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im,
  email: /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
};
</code>```

That did not help.

I am thinking it has to be the validation function, but I am staring at this thing and I can't see anything that sticks out:

```<code>_validate = props => {

    const validationErrors = {
      businessName: props.businessName ? '' : 'Is Required',
      businessPhoneNumber:
        props.businessPhoneNumber.length === 0 ||
        regex.phoneNumber.test(props.businessPhoneNumber)
          ? ''
          : 'Phone number must be valid and contain 10 digits',
    };
    const isValid = Object.keys(validationErrors).reduce((acc, curr) => {
      if (validationErrors[curr] !== '') {
        return false;
      }

      return acc;
    }, true);

    this.setState({validationErrors, displayErrors: !isValid});
    return isValid;
  };
</code>```

UPDATE

I tried the solution in the below answer, but unfortunately that did not work.

Here is whats going on:

When I add the phone number and save it, it is in props here:

_validate = props => { and you can see that here:

```<code>{screenProps: undefined, navigation: {…}, businessName: "Ceramic Tile Distributors", businessWebsite: "", businessPhoneNumber: "8667073945", …}
</code>```

but then it ceases to exist in the validationErrors object here:

```<code>const validationErrors = {
      businessName: props.businessName ? "" : "Is Required",
      businessPhoneNumber:
        props.businessPhoneNumber.length === 0 ||
        regex.phoneNumber.test(props.businessPhoneNumber)
          ? ""
          : "Phone number must be valid and contain 10 digits"
    };
</code>```

and you can see that here:

```<code>{businessName: "", businessPhoneNumber: ""}
</code>```

Why its re-rendering with the above as empty strings I do not know.

I can tell you that this here:

```<code>const isValid = Object.keys(validationErrors).reduce((acc, curr) => {
      console.log("On line 84 of BusinessDetails: ", isValid);
      if (validationErrors[acc] !== "") {
        return false;
      }

      return acc;
    }, true);
</code>```

returns undefined, but why I do not know.

_validate is being used inside the _saveChanges function like so:

```<code>_saveChanges = () => {
    const isValid = this._validate(this.props);

if (isValid) {
  this.setState({ displaySpinner: true });
  this.props
    .updateInformation()
    .then(() => {
      this.setState({ displaySpinner: false }, () => {
        this.props.navigation.goBack();
      });
    })
    .catch(() => {
      Alert.alert(
        "Error",
        this.props.businessPhoneNumber.length === 0
          ? "Please provide a business phone number. If your business phone number no longer exists, please call 1-800-NFIB-NOW to have this information deleted."
          : "We couldn't save your changes. Please try again.",
        [
          {
            text: "OK",
            onPress: () => this.setState({ displaySpinner: false })
          }
        ],
        { cancelable: false }
      );
    });
}
</code>```

};

I can tell you that const isValid = this._validate(this.props); returns false.

答:
When I test your code, it looks like there is no problem with your regex.  But the below line is not  correct

```<code>  if (validationErrors[curr] !== '') {
    return false;
  }
</code>```

You should use acc to get the values. consider the below code

```<code>  if (validationErrors[acc] !== '') {
    return false;
  }
</code>```

However, I can't run your code in my system. .reduce not working here. As  a workaround, you can use below code

```<code>  _validate = props => {

    const validationErrors = {
      businessName: props.businessName ? '' : 'Is Required',
      businessPhoneNumber:
        props.businessPhoneNumber.length === 0 ||
        regex.phoneNumber.test(props.businessPhoneNumber)
          ? ''
          : 'Phone number must be valid and contain 10 digits',
    };
    let isValid = true
    Object.keys(validationErrors).map((acc, curr) => {
      if (validationErrors[acc] !== '') {
       isValid= false
      }

    });

    this.setState({validationErrors, displayErrors: !isValid});
    return isValid;
  };
</code>```

Body:
I have a bug in my application where I am trying to update a phone number and when I click on save, I get the error message and the original phone number stays populated:

Obviously, something has gone wrong with validation. I was hoping it was perhaps the regex although it has a solid one, but I changed it like so:

const regex = {
  userName: /^[-.\sa-zA-Z]+$/,
  cardName: /^[-\sa-zA-Z]+$/,
  password: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&*()\-+!\\.]?).{8,}$/,
  zip: /(^\d{5}$)|(^\d{5}-\d{4}$)/,
  memberId: /^\d+$/,
  // phoneNumber: /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
  phoneNumber: /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im,
  email: /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
};

That did not help.

I am thinking it has to be the validation function, but I am staring at this thing and I can't see anything that sticks out:

_validate = props => {

    const validationErrors = {
      businessName: props.businessName ? '' : 'Is Required',
      businessPhoneNumber:
        props.businessPhoneNumber.length === 0 ||
        regex.phoneNumber.test(props.businessPhoneNumber)
          ? ''
          : 'Phone number must be valid and contain 10 digits',
    };
    const isValid = Object.keys(validationErrors).reduce((acc, curr) => {
      if (validationErrors[curr] !== '') {
        return false;
      }

      return acc;
    }, true);

    this.setState({validationErrors, displayErrors: !isValid});
    return isValid;
  };

UPDATE

I tried the solution in the below answer, but unfortunately that did not work.

Here is whats going on:

When I add the phone number and save it, it is in props here:

_validate = props => { and you can see that here:

{screenProps: undefined, navigation: {…}, businessName: "Ceramic Tile Distributors", businessWebsite: "", businessPhoneNumber: "8667073945", …}

but then it ceases to exist in the validationErrors object here:

const validationErrors = {
      businessName: props.businessName ? "" : "Is Required",
      businessPhoneNumber:
        props.businessPhoneNumber.length === 0 ||
        regex.phoneNumber.test(props.businessPhoneNumber)
          ? ""
          : "Phone number must be valid and contain 10 digits"
    };

and you can see that here:

{businessName: "", businessPhoneNumber: ""}

Why its re-rendering with the above as empty strings I do not know.

I can tell you that this here:

const isValid = Object.keys(validationErrors).reduce((acc, curr) => {
      console.log("On line 84 of BusinessDetails: ", isValid);
      if (validationErrors[acc] !== "") {
        return false;
      }

      return acc;
    }, true);

returns undefined, but why I do not know.

_validate is being used inside the _saveChanges function like so:

_saveChanges = () => {
    const isValid = this._validate(this.props);

if (isValid) {
  this.setState({ displaySpinner: true });
  this.props
    .updateInformation()
    .then(() => {
      this.setState({ displaySpinner: false }, () => {
        this.props.navigation.goBack();
      });
    })
    .catch(() => {
      Alert.alert(
        "Error",
        this.props.businessPhoneNumber.length === 0
          ? "Please provide a business phone number. If your business phone number no longer exists, please call 1-800-NFIB-NOW to have this information deleted."
          : "We couldn't save your changes. Please try again.",
        [
          {
            text: "OK",
            onPress: () => this.setState({ displaySpinner: false })
          }
        ],
        { cancelable: false }
      );
    });
}

};

I can tell you that const isValid = this._validate(this.props); returns false.

Body:
When I test your code, it looks like there is no problem with your regex.  But the below line is not  correct

  if (validationErrors[curr] !== '') {
    return false;
  }

You should use acc to get the values. consider the below code

  if (validationErrors[acc] !== '') {
    return false;
  }

However, I can't run your code in my system. .reduce not working here. As  a workaround, you can use below code

  _validate = props => {

    const validationErrors = {
      businessName: props.businessName ? '' : 'Is Required',
      businessPhoneNumber:
        props.businessPhoneNumber.length === 0 ||
        regex.phoneNumber.test(props.businessPhoneNumber)
          ? ''
          : 'Phone number must be valid and contain 10 digits',
    };
    let isValid = true
    Object.keys(validationErrors).map((acc, curr) => {
      if (validationErrors[acc] !== '') {
       isValid= false
      }

    });

    this.setState({validationErrors, displayErrors: !isValid});
    return isValid;
  };


问:
Line number in android log util
Is there any way to print file line number with android Log ?

答:
Better Logging In Android Using Timber with Log Line Number

In /app/build.gradle file

```<code>implementation 'com.jakewharton.timber:timber:4.7.1'
</code>```

In Application class

```<code>Timber.plant(new Timber.DebugTree() {
                @Override
                protected @Nullable String createStackElementTag(@NotNull StackTraceElement element) {
                    return super.createStackElementTag(element) + ":"+element.getLineNumber();
                }
            });
</code>```

Title: Line number in android log util

Body:
Better Logging In Android Using Timber with Log Line Number

In /app/build.gradle file

implementation 'com.jakewharton.timber:timber:4.7.1'

In Application class

Timber.plant(new Timber.DebugTree() {
                @Override
                protected @Nullable String createStackElementTag(@NotNull StackTraceElement element) {
                    return super.createStackElementTag(element) + ":"+element.getLineNumber();
                }
            });


问:
Execute two functions for a button in flutter
So i want to be able to save the text from the textcontroller that user have keyed in into shared preferences However, i want to go to the next page too at the same time.

So:

Save the text in a shared preference

Go to next page

```<code>final _text = TextEditingController();

_nameSaver() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('my_string_key', _text.text);
  }

FooterRaisedButton(
                  "Next",
                  () => (_text.text.isEmpty)
                      ? null
                      : Navigator.pushNamed(context, '/onboardMarket'),
                  "#0087a8")
</code>```

I dont know how to call out the function that saves the name at the same time the button pressed will go to the next page

答:
Try this code it should work :

Code:

```<code>final _text = TextEditingController();

  _nameSaver() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('my_string_key', _text.text);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: RaisedButton(
        child: Text("Next"),
        onPressed: (){
          if(_text.text.isEmpty){
            print("Cannot use empty text");
          }
          else {
            _nameSaver();
            Navigator.pushNamed(context, '/onboardMarket');
          }

        },
      ),
    );
  }
</code>```

Body:
So i want to be able to save the text from the textcontroller that user have keyed in into shared preferences However, i want to go to the next page too at the same time.

So:

Save the text in a shared preference

Go to next page

final _text = TextEditingController();

_nameSaver() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('my_string_key', _text.text);
  }

FooterRaisedButton(
                  "Next",
                  () => (_text.text.isEmpty)
                      ? null
                      : Navigator.pushNamed(context, '/onboardMarket'),
                  "#0087a8")

I dont know how to call out the function that saves the name at the same time the button pressed will go to the next page

Body:
Try this code it should work :

Code:

final _text = TextEditingController();

  _nameSaver() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('my_string_key', _text.text);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: RaisedButton(
        child: Text("Next"),
        onPressed: (){
          if(_text.text.isEmpty){
            print("Cannot use empty text");
          }
          else {
            _nameSaver();
            Navigator.pushNamed(context, '/onboardMarket');
          }

        },
      ),
    );
  }


问:
Tomcat 8 on CentOS 7 does not start as service (but it starts manually ....)
I've installed Tomcat (apache-tomcat-8.5.37), on a CentOS VM (using bento/centos-7).

Tomcat is installed in

```<code>/opt/tomcat/apache-tomcat-8.5.37
</code>```

and Java 8 is installed in

```<code>/usr/java/jre1.8.0_192-amd64
</code>```

Before to install Tomcat I've created a tomcat user in this way

```<code>sudo useradd tomcat
sudo passwd tomcat
sudo mkdir /opt/tomcat
sudo chown -R tomcat:tomcat /opt/tomcat
su – tomcat
</code>```

If I try to start Tomcat manually using

```<code>/opt/tomcat/apache-tomcat-8.5.37/bin/startup.sh
</code>```

all works fine and I can test Tomcat ad its examples from the url

```<code>http://192.168.33.10:8080
</code>```

(note: 192.168.33.10 is the IP of my virtual machine ...)

I can also shutdown Tomcat using

```<code>/opt/tomcat/apache-tomcat-8.5.37/bin/shutdown.sh
</code>```

I'd like to start Tomcat like e service so I've stopped Tomcat and then  I've edited a file

```<code>/etc/systemd/system/tomcat.service
</code>```

with this content

```<code>[Unit]
Description=Apache Tomcat Web Application Container
After=syslog.target network.target

[Service]
Type=forking

Environment=JAVA_HOME=/usr/java/jre1.8.0_192-amd64
Environment=CATALINA_PID=/opt/tomcat/apache-tomcat-8.5.37/temp/tomcat.pid
Environment=CATALINA_HOME=/opt/tomcat/apache-tomcat-8.5.37/
Environment=CATALINA_BASE=/opt/tomcat/apache-tomcat-8.5.37/
Environment='CATALINA_OPTS=-Xms512M -Xmx1024M -server -XX:+UseParallelGC'
Environment='JAVA_OPTS=-Djava.awt.headless=true -Djava.security.egd=file:/dev/./urandom'

ExecStart=/opt/tomcat/apache-tomcat-8.5.37/bin/startup.sh
ExecStop=/bin/kill -15 $MAINPID

User=tomcat
Group=tomcat
UMask=0007

[Install]
WantedBy=multi-user.target
</code>```

Then

```<code>sudo systemctl daemon-reload
</code>```

and

```<code>sudo systemctl start tomcat
</code>```

Tomcat does not responding now invoking the url

```<code>http://192.168.33.10:8080
</code>```

and the output of

```<code>sudo systemctl status tomcat
</code>```

is the follow

```<code>● tomcat.service - Apache Tomcat Web Application Container
   Loaded: loaded (/etc/systemd/system/tomcat.service; disabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Tue 2019-01-01 09:34:46 UTC; 13min ago
  Process: 14438 ExecStop=/bin/kill -15 $MAINPID (code=exited, status=1/FAILURE)
  Process: 14425 ExecStart=/opt/tomcat/apache-tomcat-8.5.37/bin/startup.sh (code=exited, status=0/SUCCESS)
 Main PID: 14436 (code=exited, status=0/SUCCESS)

Jan 01 09:34:46 localhost.localdomain systemd[1]: Starting Apache Tomcat Web Application Container...
Jan 01 09:34:46 localhost.localdomain startup.sh[14425]: Existing PID file found during start.
Jan 01 09:34:46 localhost.localdomain startup.sh[14425]: Removing/clearing stale PID file.
Jan 01 09:34:46 localhost.localdomain systemd[1]: Started Apache Tomcat Web Application Container.
Jan 01 09:34:46 localhost.localdomain systemd[1]: tomcat.service: control process exited, code=exited status=1
Jan 01 09:34:46 localhost.localdomain systemd[1]: Unit tomcat.service entered failed state.
Jan 01 09:34:46 localhost.localdomain systemd[1]: tomcat.service failed.
</code>```

The output of

```<code>journalctl -xe
</code>```

is the follow

```<code>Jan 01 09:34:46 localhost.localdomain sudo[14418]:   tomcat : TTY=pts/0 ; PWD=/opt/tomcat/apache-tomcat-8.5.37/temp ; USER=root ; COMMAND=/bin/systemctl start tomcat
Jan 01 09:34:46 localhost.localdomain polkitd[635]: Registered Authentication Agent for unix-process:14419:1135902 (system bus name :1.85 [/usr/bin/pkttyagent --notify-fd 5 --fallb
Jan 01 09:34:46 localhost.localdomain systemd[1]: Starting Apache Tomcat Web Application Container...
-- Subject: Unit tomcat.service has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit tomcat.service has begun starting up.
Jan 01 09:34:46 localhost.localdomain startup.sh[14425]: Existing PID file found during start.
Jan 01 09:34:46 localhost.localdomain startup.sh[14425]: Removing/clearing stale PID file.
Jan 01 09:34:46 localhost.localdomain startup.sh[14425]: Tomcat started.
Jan 01 09:34:46 localhost.localdomain polkitd[635]: Unregistered Authentication Agent for unix-process:14419:1135902 (system bus name :1.85, object path /org/freedesktop/PolicyKit1
Jan 01 09:34:46 localhost.localdomain systemd[1]: Started Apache Tomcat Web Application Container.
-- Subject: Unit tomcat.service has finished start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit tomcat.service has finished starting up.
--
-- The start-up result is done.
Jan 01 09:34:46 localhost.localdomain kill[14438]: Usage:
Jan 01 09:34:46 localhost.localdomain kill[14438]: kill [options] <pid|name> [...]
Jan 01 09:34:46 localhost.localdomain kill[14438]: Options:
Jan 01 09:34:46 localhost.localdomain kill[14438]: -a, --all              do not restrict the name-to-pid conversion to processes
Jan 01 09:34:46 localhost.localdomain kill[14438]: with the same uid as the present process
Jan 01 09:34:46 localhost.localdomain kill[14438]: -s, --signal <sig>     send specified signal
Jan 01 09:34:46 localhost.localdomain kill[14438]: -q, --queue <sig>      use sigqueue(2) rather than kill(2)
Jan 01 09:34:46 localhost.localdomain kill[14438]: -p, --pid              print pids without signaling them
Jan 01 09:34:46 localhost.localdomain kill[14438]: -l, --list [=<signal>] list signal names, or convert one to a name
Jan 01 09:34:46 localhost.localdomain kill[14438]: -L, --table            list signal names and numbers
Jan 01 09:34:46 localhost.localdomain kill[14438]: -h, --help     display this help and exit
Jan 01 09:34:46 localhost.localdomain kill[14438]: -V, --version  output version information and exit
Jan 01 09:34:46 localhost.localdomain kill[14438]: For more details see kill(1).
Jan 01 09:34:46 localhost.localdomain systemd[1]: tomcat.service: control process exited, code=exited status=1
Jan 01 09:34:46 localhost.localdomain systemd[1]: Unit tomcat.service entered failed state.
Jan 01 09:34:46 localhost.localdomain systemd[1]: tomcat.service failed.
Jan 01 09:34:59 localhost.localdomain sudo[14451]:   tomcat : TTY=pts/0 ; PWD=/opt/tomcat/apache-tomcat-8.5.37/temp ; USER=root ; COMMAND=/bin/systemctl status tomcat
Jan 01 09:48:45 localhost.localdomain sudo[15115]:   tomcat : TTY=pts/0 ; PWD=/opt/tomcat/apache-tomcat-8.5.37/bin ; USER=root ; COMMAND=/bin/systemctl status tomcat
</code>```

The output of catalina.out is the follow

```<code>01-Jan-2019 09:09:21.585 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["ajp-nio-8009"]
01-Jan-2019 09:09:21.602 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
01-Jan-2019 09:09:21.614 INFO [main] org.apache.catalina.startup.Catalina.load Initialization processed in 2829 ms
01-Jan-2019 09:09:21.697 INFO [main] org.apache.catalina.core.StandardService.startInternal Starting service [Catalina]
01-Jan-2019 09:09:21.697 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.5.37
01-Jan-2019 09:09:21.738 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/opt/tomcat/apache-tomcat-8.5.37/webapps/ROOT]
01-Jan-2019 09:09:22.777 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/opt/tomcat/apache-tomcat-8.5.37/webapps/ROOT] has finished in [1,038] ms
01-Jan-2019 09:09:22.795 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/opt/tomcat/apache-tomcat-8.5.37/webapps/docs]
01-Jan-2019 09:09:22.847 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/opt/tomcat/apache-tomcat-8.5.37/webapps/docs] has finished in [70] ms
01-Jan-2019 09:09:22.847 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/opt/tomcat/apache-tomcat-8.5.37/webapps/examples]
01-Jan-2019 09:09:23.468 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/opt/tomcat/apache-tomcat-8.5.37/webapps/examples] has finished in [621] ms
01-Jan-2019 09:09:23.469 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/opt/tomcat/apache-tomcat-8.5.37/webapps/host-manager]
01-Jan-2019 09:09:23.522 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/opt/tomcat/apache-tomcat-8.5.37/webapps/host-manager] has finished in [54] ms
01-Jan-2019 09:09:23.522 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/opt/tomcat/apache-tomcat-8.5.37/webapps/manager]
01-Jan-2019 09:09:23.569 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/opt/tomcat/apache-tomcat-8.5.37/webapps/manager] has finished in [47] ms
01-Jan-2019 09:09:23.592 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-8080"]
01-Jan-2019 09:09:23.601 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-nio-8009"]
01-Jan-2019 09:09:23.604 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 1990 ms
01-Jan-2019 09:12:38.830 INFO [main] org.apache.catalina.core.StandardServer.await A valid shutdown command was received via the shutdown port. Stopping the Server instance.
01-Jan-2019 09:12:38.831 INFO [main] org.apache.coyote.AbstractProtocol.pause Pausing ProtocolHandler ["http-nio-8080"]
01-Jan-2019 09:12:38.870 INFO [main] org.apache.coyote.AbstractProtocol.pause Pausing ProtocolHandler ["ajp-nio-8009"]
01-Jan-2019 09:12:38.878 INFO [main] org.apache.catalina.core.StandardService.stopInternal Stopping service [Catalina]
01-Jan-2019 09:12:39.117 INFO [main] org.apache.coyote.AbstractProtocol.stop Stopping ProtocolHandler ["http-nio-8080"]
01-Jan-2019 09:12:39.123 INFO [main] org.apache.coyote.AbstractProtocol.stop Stopping ProtocolHandler ["ajp-nio-8009"]
01-Jan-2019 09:12:39.131 INFO [main] org.apache.coyote.AbstractProtocol.destroy Destroying ProtocolHandler ["http-nio-8080"]
01-Jan-2019 09:12:39.137 INFO [main] org.apache.coyote.AbstractProtocol.destroy Destroying ProtocolHandler ["ajp-nio-8009"]
</code>```

????

Suggestions are appreciated!!

答:
Some time it would be your java heap memory exceed as your current server memory. You can set it in your setenv.sh file in tomcat8 and then restart the server.

I have face same kind of issue when I have downgrade the system configuration after that tomcat could't be restart so I have just adjust the heap memory in tomcat/bin/setenv.sh file and /etc/systemd/system/tomcat.service file according to system configuration then I have restart the tomcat. Now it's working fine.

Body:
I've installed Tomcat (apache-tomcat-8.5.37), on a CentOS VM (using bento/centos-7).

Tomcat is installed in

/opt/tomcat/apache-tomcat-8.5.37

and Java 8 is installed in

/usr/java/jre1.8.0_192-amd64

Before to install Tomcat I've created a tomcat user in this way

sudo useradd tomcat
sudo passwd tomcat
sudo mkdir /opt/tomcat
sudo chown -R tomcat:tomcat /opt/tomcat
su – tomcat

If I try to start Tomcat manually using

/opt/tomcat/apache-tomcat-8.5.37/bin/startup.sh

all works fine and I can test Tomcat ad its examples from the url

http://192.168.33.10:8080

(note: 192.168.33.10 is the IP of my virtual machine ...)

I can also shutdown Tomcat using

/opt/tomcat/apache-tomcat-8.5.37/bin/shutdown.sh

I'd like to start Tomcat like e service so I've stopped Tomcat and then  I've edited a file

/etc/systemd/system/tomcat.service

with this content

[Unit]
Description=Apache Tomcat Web Application Container
After=syslog.target network.target

[Service]
Type=forking

Environment=JAVA_HOME=/usr/java/jre1.8.0_192-amd64
Environment=CATALINA_PID=/opt/tomcat/apache-tomcat-8.5.37/temp/tomcat.pid
Environment=CATALINA_HOME=/opt/tomcat/apache-tomcat-8.5.37/
Environment=CATALINA_BASE=/opt/tomcat/apache-tomcat-8.5.37/
Environment='CATALINA_OPTS=-Xms512M -Xmx1024M -server -XX:+UseParallelGC'
Environment='JAVA_OPTS=-Djava.awt.headless=true -Djava.security.egd=file:/dev/./urandom'

ExecStart=/opt/tomcat/apache-tomcat-8.5.37/bin/startup.sh
ExecStop=/bin/kill -15 $MAINPID

User=tomcat
Group=tomcat
UMask=0007

[Install]
WantedBy=multi-user.target

Then

sudo systemctl daemon-reload

and

sudo systemctl start tomcat

Tomcat does not responding now invoking the url

http://192.168.33.10:8080

and the output of

sudo systemctl status tomcat

is the follow

● tomcat.service - Apache Tomcat Web Application Container
   Loaded: loaded (/etc/systemd/system/tomcat.service; disabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Tue 2019-01-01 09:34:46 UTC; 13min ago
  Process: 14438 ExecStop=/bin/kill -15 $MAINPID (code=exited, status=1/FAILURE)
  Process: 14425 ExecStart=/opt/tomcat/apache-tomcat-8.5.37/bin/startup.sh (code=exited, status=0/SUCCESS)
 Main PID: 14436 (code=exited, status=0/SUCCESS)

Jan 01 09:34:46 localhost.localdomain systemd[1]: Starting Apache Tomcat Web Application Container...
Jan 01 09:34:46 localhost.localdomain startup.sh[14425]: Existing PID file found during start.
Jan 01 09:34:46 localhost.localdomain startup.sh[14425]: Removing/clearing stale PID file.
Jan 01 09:34:46 localhost.localdomain systemd[1]: Started Apache Tomcat Web Application Container.
Jan 01 09:34:46 localhost.localdomain systemd[1]: tomcat.service: control process exited, code=exited status=1
Jan 01 09:34:46 localhost.localdomain systemd[1]: Unit tomcat.service entered failed state.
Jan 01 09:34:46 localhost.localdomain systemd[1]: tomcat.service failed.

The output of

journalctl -xe

is the follow

Jan 01 09:34:46 localhost.localdomain sudo[14418]:   tomcat : TTY=pts/0 ; PWD=/opt/tomcat/apache-tomcat-8.5.37/temp ; USER=root ; COMMAND=/bin/systemctl start tomcat
Jan 01 09:34:46 localhost.localdomain polkitd[635]: Registered Authentication Agent for unix-process:14419:1135902 (system bus name :1.85 [/usr/bin/pkttyagent --notify-fd 5 --fallb
Jan 01 09:34:46 localhost.localdomain systemd[1]: Starting Apache Tomcat Web Application Container...
-- Subject: Unit tomcat.service has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit tomcat.service has begun starting up.
Jan 01 09:34:46 localhost.localdomain startup.sh[14425]: Existing PID file found during start.
Jan 01 09:34:46 localhost.localdomain startup.sh[14425]: Removing/clearing stale PID file.
Jan 01 09:34:46 localhost.localdomain startup.sh[14425]: Tomcat started.
Jan 01 09:34:46 localhost.localdomain polkitd[635]: Unregistered Authentication Agent for unix-process:14419:1135902 (system bus name :1.85, object path /org/freedesktop/PolicyKit1
Jan 01 09:34:46 localhost.localdomain systemd[1]: Started Apache Tomcat Web Application Container.
-- Subject: Unit tomcat.service has finished start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit tomcat.service has finished starting up.
--
-- The start-up result is done.
Jan 01 09:34:46 localhost.localdomain kill[14438]: Usage:
Jan 01 09:34:46 localhost.localdomain kill[14438]: kill [options] <pid|name> [...]
Jan 01 09:34:46 localhost.localdomain kill[14438]: Options:
Jan 01 09:34:46 localhost.localdomain kill[14438]: -a, --all              do not restrict the name-to-pid conversion to processes
Jan 01 09:34:46 localhost.localdomain kill[14438]: with the same uid as the present process
Jan 01 09:34:46 localhost.localdomain kill[14438]: -s, --signal <sig>     send specified signal
Jan 01 09:34:46 localhost.localdomain kill[14438]: -q, --queue <sig>      use sigqueue(2) rather than kill(2)
Jan 01 09:34:46 localhost.localdomain kill[14438]: -p, --pid              print pids without signaling them
Jan 01 09:34:46 localhost.localdomain kill[14438]: -l, --list [=<signal>] list signal names, or convert one to a name
Jan 01 09:34:46 localhost.localdomain kill[14438]: -L, --table            list signal names and numbers
Jan 01 09:34:46 localhost.localdomain kill[14438]: -h, --help     display this help and exit
Jan 01 09:34:46 localhost.localdomain kill[14438]: -V, --version  output version information and exit
Jan 01 09:34:46 localhost.localdomain kill[14438]: For more details see kill(1).
Jan 01 09:34:46 localhost.localdomain systemd[1]: tomcat.service: control process exited, code=exited status=1
Jan 01 09:34:46 localhost.localdomain systemd[1]: Unit tomcat.service entered failed state.
Jan 01 09:34:46 localhost.localdomain systemd[1]: tomcat.service failed.
Jan 01 09:34:59 localhost.localdomain sudo[14451]:   tomcat : TTY=pts/0 ; PWD=/opt/tomcat/apache-tomcat-8.5.37/temp ; USER=root ; COMMAND=/bin/systemctl status tomcat
Jan 01 09:48:45 localhost.localdomain sudo[15115]:   tomcat : TTY=pts/0 ; PWD=/opt/tomcat/apache-tomcat-8.5.37/bin ; USER=root ; COMMAND=/bin/systemctl status tomcat

The output of catalina.out is the follow

01-Jan-2019 09:09:21.585 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["ajp-nio-8009"]
01-Jan-2019 09:09:21.602 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
01-Jan-2019 09:09:21.614 INFO [main] org.apache.catalina.startup.Catalina.load Initialization processed in 2829 ms
01-Jan-2019 09:09:21.697 INFO [main] org.apache.catalina.core.StandardService.startInternal Starting service [Catalina]
01-Jan-2019 09:09:21.697 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.5.37
01-Jan-2019 09:09:21.738 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/opt/tomcat/apache-tomcat-8.5.37/webapps/ROOT]
01-Jan-2019 09:09:22.777 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/opt/tomcat/apache-tomcat-8.5.37/webapps/ROOT] has finished in [1,038] ms
01-Jan-2019 09:09:22.795 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/opt/tomcat/apache-tomcat-8.5.37/webapps/docs]
01-Jan-2019 09:09:22.847 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/opt/tomcat/apache-tomcat-8.5.37/webapps/docs] has finished in [70] ms
01-Jan-2019 09:09:22.847 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/opt/tomcat/apache-tomcat-8.5.37/webapps/examples]
01-Jan-2019 09:09:23.468 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/opt/tomcat/apache-tomcat-8.5.37/webapps/examples] has finished in [621] ms
01-Jan-2019 09:09:23.469 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/opt/tomcat/apache-tomcat-8.5.37/webapps/host-manager]
01-Jan-2019 09:09:23.522 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/opt/tomcat/apache-tomcat-8.5.37/webapps/host-manager] has finished in [54] ms
01-Jan-2019 09:09:23.522 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/opt/tomcat/apache-tomcat-8.5.37/webapps/manager]
01-Jan-2019 09:09:23.569 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/opt/tomcat/apache-tomcat-8.5.37/webapps/manager] has finished in [47] ms
01-Jan-2019 09:09:23.592 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-8080"]
01-Jan-2019 09:09:23.601 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-nio-8009"]
01-Jan-2019 09:09:23.604 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 1990 ms
01-Jan-2019 09:12:38.830 INFO [main] org.apache.catalina.core.StandardServer.await A valid shutdown command was received via the shutdown port. Stopping the Server instance.
01-Jan-2019 09:12:38.831 INFO [main] org.apache.coyote.AbstractProtocol.pause Pausing ProtocolHandler ["http-nio-8080"]
01-Jan-2019 09:12:38.870 INFO [main] org.apache.coyote.AbstractProtocol.pause Pausing ProtocolHandler ["ajp-nio-8009"]
01-Jan-2019 09:12:38.878 INFO [main] org.apache.catalina.core.StandardService.stopInternal Stopping service [Catalina]
01-Jan-2019 09:12:39.117 INFO [main] org.apache.coyote.AbstractProtocol.stop Stopping ProtocolHandler ["http-nio-8080"]
01-Jan-2019 09:12:39.123 INFO [main] org.apache.coyote.AbstractProtocol.stop Stopping ProtocolHandler ["ajp-nio-8009"]
01-Jan-2019 09:12:39.131 INFO [main] org.apache.coyote.AbstractProtocol.destroy Destroying ProtocolHandler ["http-nio-8080"]
01-Jan-2019 09:12:39.137 INFO [main] org.apache.coyote.AbstractProtocol.destroy Destroying ProtocolHandler ["ajp-nio-8009"]

????

Suggestions are appreciated!!


问:
How to align the bottom of two left- and right aligned texts with bottom of parent container?
Imagine you have this:

```<code><div class="parent_with_height200px">
  <div class="left">This is the left floated text, size 12px</div>
  <div class="right">This is the right floated text, size 40px</div>
</div>
</code>```

How can I make the two texts "stand" on the bottom of the parent div having their baseline aligned with each other?

It's perfectly ok to change the css/html, it's the result I want.

答:
Is this what you're looking for?</p>

```<code>.left {
    float:left;
    width:50%;
}
.right {
    float:left;
    width:50%;
}
</code>```

Body:
Imagine you have this:

This is the left floated text, size 12px

This is the right floated text, size 40px

How can I make the two texts "stand" on the bottom of the parent div having their baseline aligned with each other?

It's perfectly ok to change the css/html, it's the result I want.

Body:
Is this what you're looking for?

.left {
    float:left;
    width:50%;
}
.right {
    float:left;
    width:50%;
}


问:
How to lock the result of the output cell, once it meets a criteria, from subsequent value change in the input cell in Google Sheets?
I'm looking to solve this situation:

Depending on the value —variable in time— in B1 (input cell), print a specific "status" in the output cell (D1).

With 3 possible status:

1st: "VALID"

2nd: "PENDING"

3rd: "APPROVED"

with the 3 main properties:

A1 = value fixed (doesn't change in time)

B1 = value changing in time

C1 = string "APPROVED" (to be inputted manually)

D1 = output cell

Following this formula:

```<code>=IFS(len(C1),"APPROVED",B1>A1,"VALID",B1<=A1,"PENDING",TRUE,"ERROR")
</code>```

What I'm trying to do is:

As soon as B1>A1 ("VALID" status) changes to B1<=A1 ("PENDING" status), have the D1 cell status "PENDING" locked to "PENDING".
I.e. not reverting to "VALID" if/when B1<=A1 changes back to B1>A1.

Additionally, only unlocking the "PENDING" status to the "APPROVED" status if the condition for the Status "APPROVED" (len(C1)-manually inputting the string "APPROVED" into C1) is met subsequently.

Here a simple example of expected result:

At T1 (say, May 27 2019, 12:15pm):

B1>A1 -> Status= VALID

A1 = 1.2 (in A1, fixed number)

B1 = 1.5 (in B1, number variable in time)

C1 = (empty cell)

D1 = VALID

At T2 (say, May 27 2019, 1:15pm):

B1<=A1 -> Status= PENDING

A1 = 1.2 (say May 27 2019, 12:15pm)

B1 = 1.2 (or 1.1) (in B1, number variable in time)

C1 =  (empty cell)

D1 = PENDING

At T3 (say, May 27 2019, 2:15pm):

B1>A1 -> Status= PENDING (no revert back to VALID despite B1 reverting to B1>A1)

A1 = 1.2 (in A1, fixed number)

B1 = 1.4 (in B1, number variable in time)

C1 = (empty cell)

D1 = PENDING

At T4 (say, May 27 2019, 3:15pm):

A1 = 1.2 (in A1, fixed number)

B1 = 1.4 or 1.1 (in B1, number variable in time)

D1 = APPROVED (because of manual input of any character into C1)

C1 = (any lenght of character into C1)

(User manually input any character/string into C1 -> Status= APPROVED (because of len(C1), the PENDING Status gets unlocked to APPROVED status)

At T3 is the issue I'm currently facing.

With this formula:

```<code>=IFS(len(C1),"APPROVED",B1>A1,"VALID",B1<=A1,"PENDING",TRUE,"ERROR")
</code>```

The "PENDING" status (gained from T2) reverts back to "VALID"

How can one lock the "PENDING" status as soon as B1>A1 ("VALID" status) changes to B1<=A1 ("PENDING" status)?

Then unlock the "PENDING" status when the "APPROVED" string is manually typed into D1?

New question:
Can we color and bold code the status as well?

For example:

Cells A22 to A25 in the sheet below.

Sheet here:

https://docs.google.com/spreadsheets/d/1UjjMnLmNbEDUfXjeCIOgBZwYqTeXdm_t_4N45OL0k6I/edit#gid=0

Thanks a lot for your help!

答:
Regarding the 2nd argument to enable change of status from "PENDING" to "APPROVED" upon typing into C1 any character lenght, I've added the IFS function len(C1) app script equivalent:</p>

```<code>/**
* Stores Status 'PENDING' As soon as B1>A1 changes to B1<=A1
*
* @param arg1: The "PENDING" status that will be stored as soon as B1>A1 changes to B1<=A1
* Unlocks 'PENDING' status to 'APPROVED" status when manual typing in C1
*
* @customfunction
*/

//The 'approveCell !== ""' status changes the 'PENDING' status to
//"APPROVED' in D1 when manually typing in C1

function STATUSPENDING(arg1) {

  var app = SpreadsheetApp;
  var activeSheet = app.getActiveSpreadsheet().getActiveSheet();

  var fixedvalueCell = activeSheet.getRange(1, 1).getValue();
  var changingvalueCell = activeSheet.getRange(1, 2).getValue();
  var approveCell = activeSheet.getRange(1, 3).getValue();
  var statusCell = activeSheet.getRange(1, 4).getValue();

  if
    (approveCell !== "") {
    activeSheet.getRange(1, 4).setValue("APPROVED");
  }
    else if
    (changingvalueCell <= fixedvalueCell) {
    activeSheet.getRange(1, 4).setValue("PENDING");
  }
    else {
    activeSheet.getRange(1, 4).setValue("VALID");
  }

  var result = arg1;

  return result;

}
</code>```

Body:
I'm looking to solve this situation:

Depending on the value —variable in time— in B1 (input cell), print a specific "status" in the output cell (D1).

With 3 possible status:

1st: "VALID"

2nd: "PENDING"

3rd: "APPROVED"

with the 3 main properties:

A1 = value fixed (doesn't change in time)

B1 = value changing in time

C1 = string "APPROVED" (to be inputted manually)

D1 = output cell

Following this formula:

=IFS(len(C1),"APPROVED",B1>A1,"VALID",B1<=A1,"PENDING",TRUE,"ERROR")

What I'm trying to do is:

As soon as B1>A1 ("VALID" status) changes to B1<=A1 ("PENDING" status), have the D1 cell status "PENDING" locked to "PENDING".
I.e. not reverting to "VALID" if/when B1<=A1 changes back to B1>A1.

Additionally, only unlocking the "PENDING" status to the "APPROVED" status if the condition for the Status "APPROVED" (len(C1)-manually inputting the string "APPROVED" into C1) is met subsequently.

Here a simple example of expected result:

At T1 (say, May 27 2019, 12:15pm):

B1>A1 -> Status= VALID

A1 = 1.2 (in A1, fixed number)

B1 = 1.5 (in B1, number variable in time)

C1 = (empty cell)

D1 = VALID

At T2 (say, May 27 2019, 1:15pm):

B1<=A1 -> Status= PENDING

A1 = 1.2 (say May 27 2019, 12:15pm)

B1 = 1.2 (or 1.1) (in B1, number variable in time)

C1 =  (empty cell)

D1 = PENDING

At T3 (say, May 27 2019, 2:15pm):

B1>A1 -> Status= PENDING (no revert back to VALID despite B1 reverting to B1>A1)

A1 = 1.2 (in A1, fixed number)

B1 = 1.4 (in B1, number variable in time)

C1 = (empty cell)

D1 = PENDING

At T4 (say, May 27 2019, 3:15pm):

A1 = 1.2 (in A1, fixed number)

B1 = 1.4 or 1.1 (in B1, number variable in time)

D1 = APPROVED (because of manual input of any character into C1)

C1 = (any lenght of character into C1)

(User manually input any character/string into C1 -> Status= APPROVED (because of len(C1), the PENDING Status gets unlocked to APPROVED status)

At T3 is the issue I'm currently facing.

With this formula:

=IFS(len(C1),"APPROVED",B1>A1,"VALID",B1<=A1,"PENDING",TRUE,"ERROR")

The "PENDING" status (gained from T2) reverts back to "VALID"

How can one lock the "PENDING" status as soon as B1>A1 ("VALID" status) changes to B1<=A1 ("PENDING" status)?

Then unlock the "PENDING" status when the "APPROVED" string is manually typed into D1?

New question:
Can we color and bold code the status as well?

For example:

Cells A22 to A25 in the sheet below.

Sheet here:

https://docs.google.com/spreadsheets/d/1UjjMnLmNbEDUfXjeCIOgBZwYqTeXdm_t_4N45OL0k6I/edit#gid=0

Thanks a lot for your help!

Body:
Regarding the 2nd argument to enable change of status from "PENDING" to "APPROVED" upon typing into C1 any character lenght, I've added the IFS function len(C1) app script equivalent:

/**
* Stores Status 'PENDING' As soon as B1>A1 changes to B1<=A1
*
* @param arg1: The "PENDING" status that will be stored as soon as B1>A1 changes to B1<=A1
* Unlocks 'PENDING' status to 'APPROVED" status when manual typing in C1
*
* @customfunction
*/

//The 'approveCell !== ""' status changes the 'PENDING' status to
//"APPROVED' in D1 when manually typing in C1

function STATUSPENDING(arg1) {

  var app = SpreadsheetApp;
  var activeSheet = app.getActiveSpreadsheet().getActiveSheet();

  var fixedvalueCell = activeSheet.getRange(1, 1).getValue();
  var changingvalueCell = activeSheet.getRange(1, 2).getValue();
  var approveCell = activeSheet.getRange(1, 3).getValue();
  var statusCell = activeSheet.getRange(1, 4).getValue();

  if
    (approveCell !== "") {
    activeSheet.getRange(1, 4).setValue("APPROVED");
  }
    else if
    (changingvalueCell <= fixedvalueCell) {
    activeSheet.getRange(1, 4).setValue("PENDING");
  }
    else {
    activeSheet.getRange(1, 4).setValue("VALID");
  }

  var result = arg1;

  return result;

}


问:
How do I get logs from all pods of a Kubernetes replication controller?
Running kubectl logs shows me the stderr/stdout of one Kubernetes container.

How can I get the aggregated stderr/stdout of a set of pods, preferably those created by a certain replication controller?

答:
You can get help from kubectl logs -h and according the info,

```<code>kubectl logs -f deployment/myapp -c myapp --tail 100
</code>```

-c is the container name and --tail will show the latest num lines，but this will choose one pod of the deployment, not all pods. This is something you have to bear in mind.

```<code>kubectl logs -l app=myapp -c myapp --tail 100
</code>```

If you want to show logs of all pods, you can use -l and specify a lable, but at the same time -f won't be used.

Body:
You can get help from kubectl logs -h and according the info,

kubectl logs -f deployment/myapp -c myapp --tail 100

-c is the container name and --tail will show the latest num lines，but this will choose one pod of the deployment, not all pods. This is something you have to bear in mind.

kubectl logs -l app=myapp -c myapp --tail 100

If you want to show logs of all pods, you can use -l and specify a lable, but at the same time -f won't be used.