问:
enabling Elasticsearch in JHipster results in UnsatisfiedDependencyException: Error creating bean with name ‘userService’
I've been trying to build an app with JHipster that can use some advanced filtering, in particular ElasticSearch. Why does it fail when I run it out of the box, without even editing the project ?

I am running the following software in Windows 10:

Java v15.0.2

node v14.17.4

NPM 6.14.14

Same happens in Ubuntu with:

Java v17.0.1

node v16.14.0

NPM 8.5.0

The problem I have is very easy to reproduce:

Go to the online version https://start.jhipster.tech/generate-application

Leave everything as it is, and mark the option "Search engine using Elasticsearch"

Click on Download as ZIP file

Unpack and run with ./mvnw

---> the build is compiled but it fails to launch because it can't instantiate the bean ‘userService’

Full trace:

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService' defined in file [C:\projects\JHipster\sample\target\classes\com\mycompany\myapp\service\UserService.class]: Unsatisfied dependency expressed through constructor parameter 2; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userSearchRepository' defined in com.mycompany.myapp.repository.search.UserSearchRepository defined in @EnableElasticsearchRepositories declared on DatabaseConfiguration: Invocation of init method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository]: Constructor threw exception; nested exception is org.springframework.data.elasticsearch.UncategorizedElasticsearchException: java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]; nested exception is ElasticsearchException[java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]]; nested: ExecutionException[java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]]; nested: ConnectException[Timeout connecting to [localhost/127.0.0.1:9200]];
        at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800)
        at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1372)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1222)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:953)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:732)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:414)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:302)
        at com.mycompany.myapp.JhipsterSampleApplicationApp.main(JhipsterSampleApplicationApp.java:69)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:564)
        at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userSearchRepository' defined in com.mycompany.myapp.repository.search.UserSearchRepository defined in @EnableElasticsearchRepositories declared on DatabaseConfiguration: Invocation of init method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository]: Constructor threw exception; nested exception is org.springframework.data.elasticsearch.UncategorizedElasticsearchException: java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]; nested exception is ElasticsearchException[java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]]; nested: ExecutionException[java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]]; nested: ConnectException[Timeout connecting to [localhost/127.0.0.1:9200]];
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
        at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1389)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1309)
        at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887)
        at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791)
        ... 22 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository]: Constructor threw exception; nested exception is org.springframework.data.elasticsearch.UncategorizedElasticsearchException: java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]; nested exception is ElasticsearchException[java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]]; nested: ExecutionException[java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]]; nested: ConnectException[Timeout connecting to [localhost/127.0.0.1:9200]];
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:224)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport.lambda$instantiateClass$5(RepositoryFactorySupport.java:578)
        at java.base/java.util.Optional.map(Optional.java:258)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport.instantiateClass(RepositoryFactorySupport.java:578)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport.getTargetRepositoryViaReflection(RepositoryFactorySupport.java:543)
        at org.springframework.data.elasticsearch.repository.support.ElasticsearchRepositoryFactory.getTargetRepository(ElasticsearchRepositoryFactory.java:74)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:324)
        at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:322)
        at org.springframework.data.util.Lazy.getNullable(Lazy.java:230)
        at org.springframework.data.util.Lazy.get(Lazy.java:114)
        at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:328)
        at org.springframework.data.elasticsearch.repository.support.ElasticsearchRepositoryFactoryBean.afterPropertiesSet(ElasticsearchRepositoryFactoryBean.java:69)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800)
        ... 33 common frames omitted
Caused by: org.springframework.data.elasticsearch.UncategorizedElasticsearchException: java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]; nested exception is ElasticsearchException[java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]]; nested: ExecutionException[java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]]; nested: ConnectException[Timeout connecting to [localhost/127.0.0.1:9200]];
        at org.springframework.data.elasticsearch.core.ElasticsearchExceptionTranslator.translateExceptionIfPossible(ElasticsearchExceptionTranslator.java:72)
        at org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate.translateException(ElasticsearchRestTemplate.java:427)
        at org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate.execute(ElasticsearchRestTemplate.java:410)
        at org.springframework.data.elasticsearch.core.RestIndexTemplate.doExists(RestIndexTemplate.java:103)
        at org.springframework.data.elasticsearch.core.AbstractIndexTemplate.exists(AbstractIndexTemplate.java:134)
        at org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository.<init>(SimpleElasticsearchRepository.java:92)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)
        at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
        at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:211)
        ... 46 common frames omitted
Caused by: org.elasticsearch.ElasticsearchException: java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]
        at org.elasticsearch.client.RestHighLevelClient.performClientRequest(RestHighLevelClient.java:2078)
        at org.elasticsearch.client.RestHighLevelClient.internalPerformRequest(RestHighLevelClient.java:1732)
        at org.elasticsearch.client.RestHighLevelClient.performRequest(RestHighLevelClient.java:1717)
        at org.elasticsearch.client.IndicesClient.exists(IndicesClient.java:963)
        at org.springframework.data.elasticsearch.core.RestIndexTemplate.lambda$doExists$2(RestIndexTemplate.java:103)
        at org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate.execute(ElasticsearchRestTemplate.java:408)
        ... 55 common frames omitted
Caused by: java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]
        at org.elasticsearch.common.util.concurrent.BaseFuture$Sync.getValue(BaseFuture.java:262)
        at org.elasticsearch.common.util.concurrent.BaseFuture$Sync.get(BaseFuture.java:249)
        at org.elasticsearch.common.util.concurrent.BaseFuture.get(BaseFuture.java:76)
        at org.elasticsearch.client.RestHighLevelClient.performClientRequest(RestHighLevelClient.java:2075)
        ... 60 common frames omitted
Caused by: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]
        at org.apache.http.nio.pool.RouteSpecificPool.timeout(RouteSpecificPool.java:169)
        at org.apache.http.nio.pool.AbstractNIOConnPool.requestTimeout(AbstractNIOConnPool.java:632)
        at org.apache.http.nio.pool.AbstractNIOConnPool$InternalSessionRequestCallback.timeout(AbstractNIOConnPool.java:898)
        at org.apache.http.impl.nio.reactor.SessionRequestImpl.timeout(SessionRequestImpl.java:198)
        at org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor.processTimeouts(DefaultConnectingIOReactor.java:213)
        at org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor.processEvents(DefaultConnectingIOReactor.java:158)
        at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor.execute(AbstractMultiworkerIOReactor.java:351)
        at org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager.execute(PoolingNHttpClientConnectionManager.java:221)
        at org.apache.http.impl.nio.client.CloseableHttpAsyncClientBase$1.run(CloseableHttpAsyncClientBase.java:64)
        at java.base/java.lang.Thread.run(Thread.java:832)

Exception in thread "Logback shutdown hook [default]" java.util.ConcurrentModificationException
        at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1013)
        at java.base/java.util.ArrayList$Itr.next(ArrayList.java:967)
        at ch.qos.logback.classic.LoggerContext.fireOnReset(LoggerContext.java:323)
        at ch.qos.logback.classic.LoggerContext.reset(LoggerContext.java:226)
        at ch.qos.logback.classic.LoggerContext.stop(LoggerContext.java:348)
        at ch.qos.logback.core.hook.ShutdownHookBase.stop(ShutdownHookBase.java:39)
        at ch.qos.logback.core.hook.DelayingShutdownHook.run(DelayingShutdownHook.java:57)
        at java.base/java.lang.Thread.run(Thread.java:832)
</code>```

答:
[java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]]; nested: ExecutionException[java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]];

If you look further in your stacktrace you can see that the application simply cannot connect to localhost:9200 which is the default address of an Elasticsearch local instance.

You firstly need to run elasticsearch on your machine in order for the application to work. You can do it quickly in docker
https://docs.docker.com/get-docker/

Install docker, then type to download the image:

```<code>docker pull docker.elastic.co/elasticsearch/elasticsearch:8.0.0
</code>```

After you can launch the container with elasticsearch

```<code>docker run --name es01 -p 9200:9200 -it docker.elastic.co/elasticsearch/elasticsearch:8.0.0
</code>```

Body:
I've been trying to build an app with JHipster that can use some advanced filtering, in particular ElasticSearch. Why does it fail when I run it out of the box, without even editing the project ?

I am running the following software in Windows 10:

Java v15.0.2

node v14.17.4

NPM 6.14.14

Same happens in Ubuntu with:

Java v17.0.1

node v16.14.0

NPM 8.5.0

The problem I have is very easy to reproduce:

Go to the online version https://start.jhipster.tech/generate-application

Leave everything as it is, and mark the option "Search engine using Elasticsearch"

Click on Download as ZIP file

Unpack and run with ./mvnw

---> the build is compiled but it fails to launch because it can't instantiate the bean ‘userService’

Full trace:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService' defined in file [C:\projects\JHipster\sample\target\classes\com\mycompany\myapp\service\UserService.class]: Unsatisfied dependency expressed through constructor parameter 2; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userSearchRepository' defined in com.mycompany.myapp.repository.search.UserSearchRepository defined in @EnableElasticsearchRepositories declared on DatabaseConfiguration: Invocation of init method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository]: Constructor threw exception; nested exception is org.springframework.data.elasticsearch.UncategorizedElasticsearchException: java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]; nested exception is ElasticsearchException[java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]]; nested: ExecutionException[java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]]; nested: ConnectException[Timeout connecting to [localhost/127.0.0.1:9200]];
        at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800)
        at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1372)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1222)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:953)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:732)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:414)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:302)
        at com.mycompany.myapp.JhipsterSampleApplicationApp.main(JhipsterSampleApplicationApp.java:69)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:564)
        at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userSearchRepository' defined in com.mycompany.myapp.repository.search.UserSearchRepository defined in @EnableElasticsearchRepositories declared on DatabaseConfiguration: Invocation of init method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository]: Constructor threw exception; nested exception is org.springframework.data.elasticsearch.UncategorizedElasticsearchException: java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]; nested exception is ElasticsearchException[java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]]; nested: ExecutionException[java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]]; nested: ConnectException[Timeout connecting to [localhost/127.0.0.1:9200]];
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
        at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1389)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1309)
        at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887)
        at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791)
        ... 22 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository]: Constructor threw exception; nested exception is org.springframework.data.elasticsearch.UncategorizedElasticsearchException: java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]; nested exception is ElasticsearchException[java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]]; nested: ExecutionException[java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]]; nested: ConnectException[Timeout connecting to [localhost/127.0.0.1:9200]];
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:224)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport.lambda$instantiateClass$5(RepositoryFactorySupport.java:578)
        at java.base/java.util.Optional.map(Optional.java:258)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport.instantiateClass(RepositoryFactorySupport.java:578)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport.getTargetRepositoryViaReflection(RepositoryFactorySupport.java:543)
        at org.springframework.data.elasticsearch.repository.support.ElasticsearchRepositoryFactory.getTargetRepository(ElasticsearchRepositoryFactory.java:74)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:324)
        at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:322)
        at org.springframework.data.util.Lazy.getNullable(Lazy.java:230)
        at org.springframework.data.util.Lazy.get(Lazy.java:114)
        at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:328)
        at org.springframework.data.elasticsearch.repository.support.ElasticsearchRepositoryFactoryBean.afterPropertiesSet(ElasticsearchRepositoryFactoryBean.java:69)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800)
        ... 33 common frames omitted
Caused by: org.springframework.data.elasticsearch.UncategorizedElasticsearchException: java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]; nested exception is ElasticsearchException[java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]]; nested: ExecutionException[java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]]; nested: ConnectException[Timeout connecting to [localhost/127.0.0.1:9200]];
        at org.springframework.data.elasticsearch.core.ElasticsearchExceptionTranslator.translateExceptionIfPossible(ElasticsearchExceptionTranslator.java:72)
        at org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate.translateException(ElasticsearchRestTemplate.java:427)
        at org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate.execute(ElasticsearchRestTemplate.java:410)
        at org.springframework.data.elasticsearch.core.RestIndexTemplate.doExists(RestIndexTemplate.java:103)
        at org.springframework.data.elasticsearch.core.AbstractIndexTemplate.exists(AbstractIndexTemplate.java:134)
        at org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository.<init>(SimpleElasticsearchRepository.java:92)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)
        at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
        at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:211)
        ... 46 common frames omitted
Caused by: org.elasticsearch.ElasticsearchException: java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]
        at org.elasticsearch.client.RestHighLevelClient.performClientRequest(RestHighLevelClient.java:2078)
        at org.elasticsearch.client.RestHighLevelClient.internalPerformRequest(RestHighLevelClient.java:1732)
        at org.elasticsearch.client.RestHighLevelClient.performRequest(RestHighLevelClient.java:1717)
        at org.elasticsearch.client.IndicesClient.exists(IndicesClient.java:963)
        at org.springframework.data.elasticsearch.core.RestIndexTemplate.lambda$doExists$2(RestIndexTemplate.java:103)
        at org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate.execute(ElasticsearchRestTemplate.java:408)
        ... 55 common frames omitted
Caused by: java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]
        at org.elasticsearch.common.util.concurrent.BaseFuture$Sync.getValue(BaseFuture.java:262)
        at org.elasticsearch.common.util.concurrent.BaseFuture$Sync.get(BaseFuture.java:249)
        at org.elasticsearch.common.util.concurrent.BaseFuture.get(BaseFuture.java:76)
        at org.elasticsearch.client.RestHighLevelClient.performClientRequest(RestHighLevelClient.java:2075)
        ... 60 common frames omitted
Caused by: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]
        at org.apache.http.nio.pool.RouteSpecificPool.timeout(RouteSpecificPool.java:169)
        at org.apache.http.nio.pool.AbstractNIOConnPool.requestTimeout(AbstractNIOConnPool.java:632)
        at org.apache.http.nio.pool.AbstractNIOConnPool$InternalSessionRequestCallback.timeout(AbstractNIOConnPool.java:898)
        at org.apache.http.impl.nio.reactor.SessionRequestImpl.timeout(SessionRequestImpl.java:198)
        at org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor.processTimeouts(DefaultConnectingIOReactor.java:213)
        at org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor.processEvents(DefaultConnectingIOReactor.java:158)
        at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor.execute(AbstractMultiworkerIOReactor.java:351)
        at org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager.execute(PoolingNHttpClientConnectionManager.java:221)
        at org.apache.http.impl.nio.client.CloseableHttpAsyncClientBase$1.run(CloseableHttpAsyncClientBase.java:64)
        at java.base/java.lang.Thread.run(Thread.java:832)

Exception in thread "Logback shutdown hook [default]" java.util.ConcurrentModificationException
        at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1013)
        at java.base/java.util.ArrayList$Itr.next(ArrayList.java:967)
        at ch.qos.logback.classic.LoggerContext.fireOnReset(LoggerContext.java:323)
        at ch.qos.logback.classic.LoggerContext.reset(LoggerContext.java:226)
        at ch.qos.logback.classic.LoggerContext.stop(LoggerContext.java:348)
        at ch.qos.logback.core.hook.ShutdownHookBase.stop(ShutdownHookBase.java:39)
        at ch.qos.logback.core.hook.DelayingShutdownHook.run(DelayingShutdownHook.java:57)
        at java.base/java.lang.Thread.run(Thread.java:832)

Body:
[java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]]; nested: ExecutionException[java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]];

If you look further in your stacktrace you can see that the application simply cannot connect to localhost:9200 which is the default address of an Elasticsearch local instance.

You firstly need to run elasticsearch on your machine in order for the application to work. You can do it quickly in docker
https://docs.docker.com/get-docker/

Install docker, then type to download the image:

docker pull docker.elastic.co/elasticsearch/elasticsearch:8.0.0

After you can launch the container with elasticsearch

docker run --name es01 -p 9200:9200 -it docker.elastic.co/elasticsearch/elasticsearch:8.0.0


来源: stackexchange

问:
How do you delete a document by timestamp in firestore flutter?

So I am trying to make a chat app with cloud Firestore and I don't how to delete a document by timestamp.

This is currently how I delete a document.but when I tried it deletes all the document:

```<code>onLongPress: () async {
  await FirebaseFirestore.instance
      .collection('messages')
      .doc(
          groupChatId)
      .collection(
      groupChatId)
      .orderBy("timestamp",descending: true).get().then((value) => {
        for(DocumentSnapshot ds in value.docs){
          ds.reference.delete()
        }
  });
},
</code>```

答:
try this code:</p>
```<code>await FirebaseFirestore.instance
      .collection('messages')
      .doc(
          groupChatId)
      .collection(
      groupChatId)
      .where("timestamp", isLessThan: DateTime.now().microsecondsSinceEpoch-TheNumberOfMicrosencundenTheDocumentCanBeOld).get().then((value) => {
        for(DocumentSnapshot ds in value.docs){
          ds.reference.delete()
        }
  });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
So I am trying to make a chat app with cloud Firestore and I don't how to delete a document by timestamp.

This is currently how I delete a document.but when I tried it deletes all the document:

onLongPress: () async {
  await FirebaseFirestore.instance
      .collection('messages')
      .doc(
          groupChatId)
      .collection(
      groupChatId)
      .orderBy("timestamp",descending: true).get().then((value) => {
        for(DocumentSnapshot ds in value.docs){
          ds.reference.delete()
        }
  });
},

Body:
try this code:

await FirebaseFirestore.instance
      .collection('messages')
      .doc(
          groupChatId)
      .collection(
      groupChatId)
      .where("timestamp", isLessThan: DateTime.now().microsecondsSinceEpoch-TheNumberOfMicrosencundenTheDocumentCanBeOld).get().then((value) => {
        for(DocumentSnapshot ds in value.docs){
          ds.reference.delete()
        }
  });


问:
How to improve performance of querying data from Salesforce with Python?
Is there any solution we can retrieve Salesforce data from Python with more than 2000 records for each chunk? I have used REST API to retrieve data and check nextRecordsUrl for the next chunk. But if it is a million records, this solution will take time. I tried to find a Salesforce parameter to increase the number of records for each chunk (>2000 records) but didn't find it yet.

Another idea is if we know how many nextRecordsUrl, we can use multi-threading in Python to retrieve data. But it seems we need to submit each nextRecordsUrl to get the next one.

If you have others ideas, pls suggest them. Currently, I can't use some filter conditions in SQL to limit data.

答:
You could look into using Bulk API query, it'd let you return data in 10K chunks. But it comes with a bit of thinking shift. Your normal API is synchronous (give me next chunk, wait, give me next chunk, wait). With Bulk API you submit the job and from time to time you ask "is it done yet".

There's even a feature called "PK chunking" (split the results by primary key)

Consider going through the trailhead: https://trailhead.salesforce.com/content/learn/modules/large-data-volumes

And maybe play with Salesforce's Data Loader. Query your stuff normal way and measure the time, then with bulk api option selected. should give you idea what's the bottleneck and whether the big rewrite will gain anything.

https://developer.salesforce.com/docs/atlas.en-us.230.0.api_asynch.meta/api_asynch/asynch_api_bulk_query_intro.htm


问:
How do I vertically center the text in an Excel label's caption?
In Excel 2007, I inserted an ActiveX label onto my worksheet.  I right-clicked on it and viewed Properties and managed to change the TextAlign property to 2 (frmTextAlignCenter).

This aligns the label caption's text to the center of the label (horizontally), but the text remains at the TOP of the label.  How do I center the caption's text VERTICALLY so that it is in the smack middle of the label?

I've searched "vertical alignment" in SO but nothing comes up for how to do this for an Excel label's caption.

答:
I just tried the approach outlined in the top voted answer and it worked perfectly. To add a little to the approach though - if you have many labels for example, I did the following:

Add a picture control somewhere on the userform (anywhere doesn't matter). Change the control's properties to the following:

Property
Value

Name
GIF

Picture
(set to be the 1x1 transparent gif picture [link])

Visible
False

Now for each of the Label controls which you want to receive the special alignment change the tag property:

Property
Value

Tag
"LabelAlignmentTheme"

Finally add the following code to UserForm_Initialize

```<code>Private Sub UserForm_Initialize()
    'Apply the fix in https://stackoverflow.com/questions/6859127/how-do-i-vertically-center-the-text-in-an-excel-labels-caption
    'To all labels with the matching Tag
    Dim ctrl As MSForms.control
    For Each ctrl In Me.controls
        If TypeOf ctrl Is MSForms.label And ctrl.Tag = "LabelAlignmentTheme" Then
            Dim label As MSForms.label
            Set label = ctrl
            Set label.Picture = Me.GIF.Picture 'read the picture from the picture control
            label.PicturePosition = fmPicturePositionLeftCenter
        End If
    Next
End Sub
</code>```

I like this use of Tag, it feels like a css style. Obviously you can skip the check for the tag (remove the second half of the And statement) and align absolutely everything but I think this is a more realistic scenario where you only want some aligned.

By storing the image in a shared hidden picture somewhere in the form, it is embedded in the file.

Body:
I just tried the approach outlined in the top voted answer and it worked perfectly. To add a little to the approach though - if you have many labels for example, I did the following:

Add a picture control somewhere on the userform (anywhere doesn't matter). Change the control's properties to the following:

Property
Value

Name
GIF

Picture
(set to be the 1x1 transparent gif picture [link])

Visible
False

Now for each of the Label controls which you want to receive the special alignment change the tag property:

Property
Value

Tag
"LabelAlignmentTheme"

Finally add the following code to UserForm_Initialize

Private Sub UserForm_Initialize()
    'Apply the fix in https://stackoverflow.com/questions/6859127/how-do-i-vertically-center-the-text-in-an-excel-labels-caption
    'To all labels with the matching Tag
    Dim ctrl As MSForms.control
    For Each ctrl In Me.controls
        If TypeOf ctrl Is MSForms.label And ctrl.Tag = "LabelAlignmentTheme" Then
            Dim label As MSForms.label
            Set label = ctrl
            Set label.Picture = Me.GIF.Picture 'read the picture from the picture control
            label.PicturePosition = fmPicturePositionLeftCenter
        End If
    Next
End Sub

I like this use of Tag, it feels like a css style. Obviously you can skip the check for the tag (remove the second half of the And statement) and align absolutely everything but I think this is a more realistic scenario where you only want some aligned.

By storing the image in a shared hidden picture somewhere in the form, it is embedded in the file.


问:
How to change just one parameter using Redux?
I try to update my global state using Redux, but I try to update just one paramter of five, not all.

My store code looks like:

```<code>const initialState = {
    loggedIn: false,
    thisUser: {}
}

export function usersReducer(state = initialState, action) {
    switch (action.type) {
        case 'users/loggedIn':
            return { ...state, loggedIn: action.payload }
        case 'users/addUser':
            return { ...state, thisUser: action.payload }
        default:
            return state
    }
}
</code>```

I tried to write a new case like, but doesn't work:

```<code>case 'users/setActivated':
            return { ...state, thisUser.activated: action.payload }
</code>```

VS Code doesn't let me write that ".activated"

My dispatch look like:

```<code>dispatch({ type: 'users/setActivated', payload: 1 })
</code>```

What is  wrong?

答:
I understand why you did this, it seemed logical to you, but it will not work.

```<code> const state = {
    ...state,
    [thisUser.activated]: action.payload
  };
</code>```

So your goal is to update the state to be like this:

```<code>{
    loggedIn: true,
    thisUser: {
      //other properties ,
      activated: 1,
    }
  }
</code>```

Firstly, this is the output of what you did:

```<code>{
    loggedIn: true,
    thisUser: {
      //other properties ,
      activated: 0,
    },
    activated: 1,
  };
</code>```

Secondly, JavaScript doesn't accept this thisUser.activated as a key.

The solution:

```<code> {
    ...state,
    thisUser: {
      ...state.thisUser,
      activated: action.payload
    },
  };
</code>```

Body:
I try to update my global state using Redux, but I try to update just one paramter of five, not all.

My store code looks like:

const initialState = {
    loggedIn: false,
    thisUser: {}
}

export function usersReducer(state = initialState, action) {
    switch (action.type) {
        case 'users/loggedIn':
            return { ...state, loggedIn: action.payload }
        case 'users/addUser':
            return { ...state, thisUser: action.payload }
        default:
            return state
    }
}

I tried to write a new case like, but doesn't work:

case 'users/setActivated':
            return { ...state, thisUser.activated: action.payload }

VS Code doesn't let me write that ".activated"

My dispatch look like:

dispatch({ type: 'users/setActivated', payload: 1 })

What is  wrong?

Body:
I understand why you did this, it seemed logical to you, but it will not work.

 const state = {
    ...state,
    [thisUser.activated]: action.payload
  };

So your goal is to update the state to be like this:

{
    loggedIn: true,
    thisUser: {
      //other properties ,
      activated: 1,
    }
  }

Firstly, this is the output of what you did:

{
    loggedIn: true,
    thisUser: {
      //other properties ,
      activated: 0,
    },
    activated: 1,
  };

Secondly, JavaScript doesn't accept this thisUser.activated as a key.

The solution:

 {
    ...state,
    thisUser: {
      ...state.thisUser,
      activated: action.payload
    },
  };


问:
How to better use the "def" function and not give "<function test_message at 0x7f5d198b3ca0>" error?
```<code>def test_message(ctx):
  ctx.send("testing")

@bot.command()
async def testa(ctx):
  await ctx.send(test_message)
</code>```

I have this down to test the "def" function but when I call in inside a Discord chat it send, "<function test_message at 0x7f5d198b3ca0>" and not "testing". Could someone better explain how t set this up?

答:
ctx.send takes the object you pass it and makes a string out of it. For functions, you'll get that representation.

Instead, you'll want to make test_message an async function (so you can call async functions such as ctx.send within it) and just call it.

```<code>async def test_message(ctx):
  await ctx.send("testing")

@bot.command()
async def testa(ctx):
  await test_message(ctx)
</code>```

Body:
def test_message(ctx):
  ctx.send("testing")

@bot.command()
async def testa(ctx):
  await ctx.send(test_message)

I have this down to test the "def" function but when I call in inside a Discord chat it send, "<function test_message at 0x7f5d198b3ca0>" and not "testing". Could someone better explain how t set this up?

Body:
ctx.send takes the object you pass it and makes a string out of it. For functions, you'll get that representation.

Instead, you'll want to make test_message an async function (so you can call async functions such as ctx.send within it) and just call it.

async def test_message(ctx):
  await ctx.send("testing")

@bot.command()
async def testa(ctx):
  await test_message(ctx)


问:
Firebase sendPasswordResetEmail never completes
I'm trying to send a password reset email with firebase but it doesn't work. It doesn't throw any exceptions either. It just never completes, and I see no errors in the console. I tried debugging it and I saw that the parameter action code is null, is it supposed to be? All guides covering this don't add any action codesettings. I've tried signing out the user first but that doesn't seem to work. What to do?

This await firebaseAuth.sendPasswordResetEmail(email: currentEmail); is nested in a try-catch block that's all.

Console output:

```<code>W/System  (  757): Ignoring header X-Firebase-Locale because its value was null.
I/System.out(  757): isEmailSend:POST
I/System.out(  757): port:443
D/GraphicBuffer(  757): register, handle(0x8240d540) (w:720 h:1504 s:720 f:0x1 u:f02)
I/System.out(  757): Check isMmsSendPdu
I/System.out(  757): [OkHttp] sendRequest<<
</code>```

This is all I see. The future just never completes.

答:
Firstly i was stuck too in this while doing my first attempt.I realized i didn't activated resetpassword method on firebase console authetication.
After this i got same result because while trying with email doesn't exist on firebase console user panel that mail adress.
My suggestion check turn on password reset method on console and try it with exist email user. and be sure you don't try with null in email
all of that if doesn't work maybe it can be about the port settings.
And one more try change this

```<code>firebaseAuth.sendPasswordResetEmail(email: currentEmail)
</code>```

to

```<code>firebaseAuth.sendPasswordResetEmail(currentEmail)
</code>```

Body:
I'm trying to send a password reset email with firebase but it doesn't work. It doesn't throw any exceptions either. It just never completes, and I see no errors in the console. I tried debugging it and I saw that the parameter action code is null, is it supposed to be? All guides covering this don't add any action codesettings. I've tried signing out the user first but that doesn't seem to work. What to do?

This await firebaseAuth.sendPasswordResetEmail(email: currentEmail); is nested in a try-catch block that's all.

Console output:

W/System  (  757): Ignoring header X-Firebase-Locale because its value was null.
I/System.out(  757): isEmailSend:POST
I/System.out(  757): port:443
D/GraphicBuffer(  757): register, handle(0x8240d540) (w:720 h:1504 s:720 f:0x1 u:f02)
I/System.out(  757): Check isMmsSendPdu
I/System.out(  757): [OkHttp] sendRequest<<

This is all I see. The future just never completes.

Body:
Firstly i was stuck too in this while doing my first attempt.I realized i didn't activated resetpassword method on firebase console authetication.
After this i got same result because while trying with email doesn't exist on firebase console user panel that mail adress.
My suggestion check turn on password reset method on console and try it with exist email user. and be sure you don't try with null in email
all of that if doesn't work maybe it can be about the port settings.
And one more try change this

firebaseAuth.sendPasswordResetEmail(email: currentEmail)

to

firebaseAuth.sendPasswordResetEmail(currentEmail)


问:
Why does this merge sort code gives zeroes instead of given elements in the resulting array
When I try to print the left and right subarrays some of the elements become zero instead of actual elements present in the array. The merge function works fine but the sorting function doesn't seem to work.

```<code>public static void mergeSort(int[] A) {
    int n = A.length;
    if (n < 2)
        return;
    int mid = n / 2;
    int[] left = new int[mid];
    int[] right = new int[n - mid];
    for (int i = 0; i < mid - 1; i++) {
        left[i] = A[i];
    }
    System.out.println(Arrays.toString(left));
    for (int j = 0; j < n - mid; j++) {
        right[j] = A[j + mid];
    }
    System.out.println(Arrays.toString(right));
    mergeSort(left);
    mergeSort(right);
    merge(left, right, A);
}

public static void merge(int[] l, int[] r, int[] A) {
    int nl = l.length;
    int nr = r.length;
    int i = 0, j = 0, k = 0;
    while (i < nl && j < nr) {
        if (l[i] <= r[i]) {
            A[k] = l[i];
            i++;
        } else {
            A[k] = r[j];
            j++;
        }
        k++;
    }
    while (i < nl) {
        A[k] = l[i];
        i++;
        k++;
    }
    while (j < nr) {
        A[k] = r[j];
        j++;
        k++;
    }
}
</code>```

答:
The loop to initialize the left subarray stops before the last element, you should write:

```<code>    for (int i = 0; i < mid; i++) {
        left[i] = A[i];
    }
</code>```

Body:
When I try to print the left and right subarrays some of the elements become zero instead of actual elements present in the array. The merge function works fine but the sorting function doesn't seem to work.

public static void mergeSort(int[] A) {
    int n = A.length;
    if (n < 2)
        return;
    int mid = n / 2;
    int[] left = new int[mid];
    int[] right = new int[n - mid];
    for (int i = 0; i < mid - 1; i++) {
        left[i] = A[i];
    }
    System.out.println(Arrays.toString(left));
    for (int j = 0; j < n - mid; j++) {
        right[j] = A[j + mid];
    }
    System.out.println(Arrays.toString(right));
    mergeSort(left);
    mergeSort(right);
    merge(left, right, A);
}

public static void merge(int[] l, int[] r, int[] A) {
    int nl = l.length;
    int nr = r.length;
    int i = 0, j = 0, k = 0;
    while (i < nl && j < nr) {
        if (l[i] <= r[i]) {
            A[k] = l[i];
            i++;
        } else {
            A[k] = r[j];
            j++;
        }
        k++;
    }
    while (i < nl) {
        A[k] = l[i];
        i++;
        k++;
    }
    while (j < nr) {
        A[k] = r[j];
        j++;
        k++;
    }
}

Body:
The loop to initialize the left subarray stops before the last element, you should write:

    for (int i = 0; i < mid; i++) {
        left[i] = A[i];
    }


问:
Is class.getName() expensive?
In many classes of a project I am working on, I see private static final members named CLASS_NAME, which are defined like this:

```<code>public class MyClass {
  private static final String CLASS_NAME = MyClass.class.getName();
  //...
}
</code>```

What are the benefits, if any, of doing this to get the class name, rather than doing the MyClass.class.getName() call directly where the name is needed?

答:
We would have to see all the code to see how CLASS_NAME is being used. However, it is likely used elsewhere, for instance you could use it with Log4J like this:

```<code>// Log4j . Logger --- Get class name in static context by creating an anonymous Throwable and
// getting the top of its stack-trace.
// NOTE you must use: getClassName() because getClass() just returns StackTraceElement.class
static final Logger logger = Logger.getLogger(new Throwable() .getStackTrace()[0].getClassName());
</code>```

It is not an expensive operation and is likely cached.

ContentLicense: CC BY-SA 3.0

Title: Is class.getName() expensive?

Body:
In many classes of a project I am working on, I see private static final members named CLASS_NAME, which are defined like this:

public class MyClass {
  private static final String CLASS_NAME = MyClass.class.getName();
  //...
}

What are the benefits, if any, of doing this to get the class name, rather than doing the MyClass.class.getName() call directly where the name is needed?

Body:
We would have to see all the code to see how CLASS_NAME is being used. However, it is likely used elsewhere, for instance you could use it with Log4J like this:

// Log4j . Logger --- Get class name in static context by creating an anonymous Throwable and
// getting the top of its stack-trace.
// NOTE you must use: getClassName() because getClass() just returns StackTraceElement.class
static final Logger logger = Logger.getLogger(new Throwable() .getStackTrace()[0].getClassName());

It is not an expensive operation and is likely cached.


问:
Tkinter SQlite - Search Function not working
Good evening,

This is a simple function reading the value of an entry widget and searching in the database for it. It won´t run.
Could someone kindly point me to my rookie mistake?

This is the Function:

```<code>def find_search_term(self, search_term):
    search_term = self.search_entry.get()
    conn=sqlite3.connect("KTRmini.db")
    c = conn.cursor()
    c.execute("SELECT * FROM KTRmini_table WHERE discription LIKE "%search_term%",")
    data=c.fetchone()[0]
    print(discription)
    conn.close()
</code>```

This is the Error:

c.execute("SELECT * FROM KTRmini_table WHERE discription LIKE "%search_term%",")
TypeError: not all arguments converted during string formatting

答:
```<code>c.execute("SELECT * FROM KTRmini_table WHERE discription LIKE %?%", search_term)
</code>```

Body:
Good evening,

This is a simple function reading the value of an entry widget and searching in the database for it. It won´t run.
Could someone kindly point me to my rookie mistake?

This is the Function:

def find_search_term(self, search_term):
    search_term = self.search_entry.get()
    conn=sqlite3.connect("KTRmini.db")
    c = conn.cursor()
    c.execute("SELECT * FROM KTRmini_table WHERE discription LIKE "%search_term%",")
    data=c.fetchone()[0]
    print(discription)
    conn.close()

This is the Error:

c.execute("SELECT * FROM KTRmini_table WHERE discription LIKE "%search_term%",")
TypeError: not all arguments converted during string formatting


问:
Pylint errors with @validator decorator from AWS Lambda Powertools Python
I'm getting some Pylint errors while using the Lambda Powertools for Python. If I download the three files from the Validator decorator example code,  and run pylint --errors-only validator_decorator.py, I get three errors:

```<code>************* Module validator_decorator
validator_decorator.py:5:1: E1120: No value for argument 'handler' in function call (no-value-for-parameter)
validator_decorator.py:5:1: E1120: No value for argument 'event' in function call (no-value-for-parameter)
validator_decorator.py:5:1: E1120: No value for argument 'context' in function call (no-value-for-parameter)
</code>```

Here is the code from validator_decorator.py:

```<code>from aws_lambda_powertools.utilities.validation import validator

import schemas

@validator(inbound_schema=schemas.INPUT, outbound_schema=schemas.OUTPUT)
def handler(event, context):
    return event
</code>```

Despite the errors, the code works just fine, but I'd like to understand if I'm doing something wrong. I could always add a # pylint: disable=no-value-for-parameter but I'd rather not if there's a better way to handle this. I've tried digging through the source but there's a lot of wrapping going on there, and since I'm at the level of just having read Primer on Python Decorators I could use a hand understanding this. Thanks.

```<code>(venv) $ python --version
Python 3.9.10
(venv) $ pylint --version
pylint 2.12.2
astroid 2.9.3
Python 3.9.10 (main, Jan 15 2022, 11:40:53)
[Clang 13.0.0 (clang-1300.0.29.3)]
</code>```

答:
Looking at the function documentation here if you click "expand source code", one of the suggestion of use is this:

from aws_lambda_powertools.utilities.validation import validate

def handler(event, context):
    validate(event=event, schema=json_schema_dict)
    return event
```

There are other suggestions, but non where it's used as a decorator, maybe it's not supposed to be used as one.

Body:
I'm getting some Pylint errors while using the Lambda Powertools for Python. If I download the three files from the Validator decorator example code,  and run pylint --errors-only validator_decorator.py, I get three errors:

************* Module validator_decorator
validator_decorator.py:5:1: E1120: No value for argument 'handler' in function call (no-value-for-parameter)
validator_decorator.py:5:1: E1120: No value for argument 'event' in function call (no-value-for-parameter)
validator_decorator.py:5:1: E1120: No value for argument 'context' in function call (no-value-for-parameter)

Here is the code from validator_decorator.py:

from aws_lambda_powertools.utilities.validation import validator

import schemas

@validator(inbound_schema=schemas.INPUT, outbound_schema=schemas.OUTPUT)
def handler(event, context):
    return event

Despite the errors, the code works just fine, but I'd like to understand if I'm doing something wrong. I could always add a # pylint: disable=no-value-for-parameter but I'd rather not if there's a better way to handle this. I've tried digging through the source but there's a lot of wrapping going on there, and since I'm at the level of just having read Primer on Python Decorators I could use a hand understanding this. Thanks.

(venv) $ python --version
Python 3.9.10
(venv) $ pylint --version
pylint 2.12.2
astroid 2.9.3
Python 3.9.10 (main, Jan 15 2022, 11:40:53)
[Clang 13.0.0 (clang-1300.0.29.3)]

Body:
Looking at the function documentation here if you click "expand source code", one of the suggestion of use is this:

from aws_lambda_powertools.utilities.validation import validate

def handler(event, context):
    validate(event=event, schema=json_schema_dict)
    return event

There are other suggestions, but non where it's used as a decorator, maybe it's not supposed to be used as one.


问:
How to create a named constant in the SystemVerilog generate block?
I need to transmit a set of values between the SystemVerilog and VHDL code. To do that, I have to flatten the SV structures into the bit vectors, transmit the bit vectors, and rebuild the structures at the VHDL side.
Unfortunately, I have faced a serious problem at the SV side. My "flattener" has the following code:

```<code>   generate
    for(genvar i=0;i<nlinks;i++)
      for(genvar j=0;j<2;j++)
        begin
        const int base = 2 * i + j;
           assign vf[base] = lct_aligned[i][j].vf;
           assign hs[(8*base+7):8*base] = lct_aligned[i][j].hs;
           assign wg[(7*base+6):7*base] = lct_aligned[i][j].wg;
           assign ql[(4*base+3):4*base] = lct_aligned[i][j].ql;
           assign cp[(4*base+3):4*base] = lct_aligned[i][j].cp;
           assign lr[base] = lct_aligned[i][j].lr;
           assign bc0[base] = lct_aligned[i][j].bc0;
           assign bx0[base] = lct_aligned[i][j].bx0;
           assign ser[base] = lct_aligned[i][j].ser;
           assign cid[(4*base+3):4*base] = lct_aligned[i][j].cid;
        end
     endgenerate
</code>```

Unfortunately, it gives "base is not a constant error" in each "assign" line.
When I replace "base" with "(2*i+j)" the code compiles correctly, but is significantly less visible and mantainable.

```<code>   generate
    for(genvar i=0;i<nlinks;i++)
      for(genvar j=0;j<2;j++)
        begin
           //const int base = 2 * i + j;
           assign vf[(2*i+j)] = lct_aligned[i][j].vf;
           assign hs[(8*(2*i+j)+7):8*(2*i+j)] = lct_aligned[i][j].hs;
           assign wg[(7*(2*i+j)+6):7*(2*i+j)] = lct_aligned[i][j].wg;
           assign ql[(4*(2*i+j)+3):4*(2*i+j)] = lct_aligned[i][j].ql;
           assign cp[(4*(2*i+j)+3):4*(2*i+j)] = lct_aligned[i][j].cp;
           assign lr[(2*i+j)] = lct_aligned[i][j].lr;
           assign bc0[(2*i+j)] = lct_aligned[i][j].bc0;
           assign bx0[(2*i+j)] = lct_aligned[i][j].bx0;
           assign ser[(2*i+j)] = lct_aligned[i][j].ser;
           assign cid[(4*(2*i+j)+3):4*(2*i+j)] = lct_aligned[i][j].cid;
        end
     endgenerate
</code>```

Is there any way to define constants for complex expressions in the SystemVerilog generate blocks?

答: A const variable is not really a constant. It's a variable with a write once at run-time value. A parameter or localparam is a compile time constant. Simply replace const with parameter.

Body:
I need to transmit a set of values between the SystemVerilog and VHDL code. To do that, I have to flatten the SV structures into the bit vectors, transmit the bit vectors, and rebuild the structures at the VHDL side.
Unfortunately, I have faced a serious problem at the SV side. My "flattener" has the following code:

   generate
    for(genvar i=0;i<nlinks;i++)
      for(genvar j=0;j<2;j++)
        begin
        const int base = 2 * i + j;
           assign vf[base] = lct_aligned[i][j].vf;
           assign hs[(8*base+7):8*base] = lct_aligned[i][j].hs;
           assign wg[(7*base+6):7*base] = lct_aligned[i][j].wg;
           assign ql[(4*base+3):4*base] = lct_aligned[i][j].ql;
           assign cp[(4*base+3):4*base] = lct_aligned[i][j].cp;
           assign lr[base] = lct_aligned[i][j].lr;
           assign bc0[base] = lct_aligned[i][j].bc0;
           assign bx0[base] = lct_aligned[i][j].bx0;
           assign ser[base] = lct_aligned[i][j].ser;
           assign cid[(4*base+3):4*base] = lct_aligned[i][j].cid;
        end
     endgenerate

Unfortunately, it gives "base is not a constant error" in each "assign" line.
When I replace "base" with "(2*i+j)" the code compiles correctly, but is significantly less visible and mantainable.

   generate
    for(genvar i=0;i<nlinks;i++)
      for(genvar j=0;j<2;j++)
        begin
           //const int base = 2 * i + j;
           assign vf[(2*i+j)] = lct_aligned[i][j].vf;
           assign hs[(8*(2*i+j)+7):8*(2*i+j)] = lct_aligned[i][j].hs;
           assign wg[(7*(2*i+j)+6):7*(2*i+j)] = lct_aligned[i][j].wg;
           assign ql[(4*(2*i+j)+3):4*(2*i+j)] = lct_aligned[i][j].ql;
           assign cp[(4*(2*i+j)+3):4*(2*i+j)] = lct_aligned[i][j].cp;
           assign lr[(2*i+j)] = lct_aligned[i][j].lr;
           assign bc0[(2*i+j)] = lct_aligned[i][j].bc0;
           assign bx0[(2*i+j)] = lct_aligned[i][j].bx0;
           assign ser[(2*i+j)] = lct_aligned[i][j].ser;
           assign cid[(4*(2*i+j)+3):4*(2*i+j)] = lct_aligned[i][j].cid;
        end
     endgenerate

Is there any way to define constants for complex expressions in the SystemVerilog generate blocks?


问:
Detect Vue SPA url changes (listen to route updates)
I have my JavaScript script injected to an existing website and running on top of it.

The website is a SPA built with Vue.js.

I would like to detect url changes (routes) in this SPA and call my own function, passing the new url as parameter.

I tried listening to the following events (based on this and this):

```<code>window.addEventListener("hashchange", myFunc);
window.addEventListener("popstate", myFunc);
</code>```

but myFunc doesn't get triggered at any point.

I also tried to do this with React (using react-router) but it didn't get any route update event.

Do I have to use Vue to achieve that?

答:
In vue you can use the watcher property to watch for changes in any variable and handle them. in your application including route path and route params.

```<code>watch:{
  $route: {
    handler: function(newRouteValue){
      // put your code here
    },
    deep: true
  }
}
</code>```

The deep in Vue watch is to watch for deep object changes. But you can remove it, if it is not necessary.

Body:
I have my JavaScript script injected to an existing website and running on top of it.

The website is a SPA built with Vue.js.

I would like to detect url changes (routes) in this SPA and call my own function, passing the new url as parameter.

I tried listening to the following events (based on this and this):

window.addEventListener("hashchange", myFunc);
window.addEventListener("popstate", myFunc);

but myFunc doesn't get triggered at any point.

I also tried to do this with React (using react-router) but it didn't get any route update event.

Do I have to use Vue to achieve that?

Body:
In vue you can use the watcher property to watch for changes in any variable and handle them. in your application including route path and route params.

watch:{
  $route: {
    handler: function(newRouteValue){
      // put your code here
    },
    deep: true
  }
}

The deep in Vue watch is to watch for deep object changes. But you can remove it, if it is not necessary.


问:
The difference between two dates
I have been writing some queries about SQL Server in order to learn.

I wonder that how can I get the difference of today between 90 days ago in a SQL query?

答:
try this to return the date and time for exactly 90 ago:

```<code>SELECT GETDATE()-90
</code>```

output:

```<code>-----------------------
2011-05-20 10:55:12.360

(1 row(s) affected)
</code>```

this will give you the date only for 90 days ago, with a time of 00:00:00.000:

```<code>SELECT DATEADD(day,DATEDIFF(day,0,GETDATE()),-90)
</code>```

output:

```<code>-----------------------
2011-05-20 00:00:00.000

(1 row(s) affected)
</code>```

Title: The difference between two dates

Body:
try this to return the date and time for exactly 90 ago:

SELECT GETDATE()-90

output:

-----------------------
2011-05-20 10:55:12.360

(1 row(s) affected)

this will give you the date only for 90 days ago, with a time of 00:00:00.000:

SELECT DATEADD(day,DATEDIFF(day,0,GETDATE()),-90)

output:

-----------------------
2011-05-20 00:00:00.000

(1 row(s) affected)


问:
Issues returning specific object from MongoDB Nested JSON Array
currently writing a flask api with python/pymongo.

Currently I am unable to return a specific object from this nested json array. I have been utilizing pymongo's db.collection.find(), and I either return the entire array or an empty set. Same thing happens in MongoDB  I will provide what I have tried below.

Sample of the JSON I am querying:

```<code>{
"elements": [
    {
        "type": "item",
        "id": 1,
        "geometry": {
            "type": "LineString",
            "coordinates": [

            ]
        },
        "tags": {
            "foot": "yes",
            "highway": "path",
            "mtb": "yes",
            "name": "Arch Cape to Cape Falcon Trail",
            "sac_scale": "hiking",
            "surface": "ground",
            "_osm_type": "way"
        }
    },
    {
        "type": "item",
        "id": 2,
        "geometry": {
            "type": "LineString",
            "coordinates": [

            ]
        },
        "tags": {
            "foot": "yes",
            "highway": "path",
            "mtb": "yes",
            "name": "Cape Falcon Trail",
            "sac_scale": "hiking",
            "surface": "ground",
            "_osm_type": "way"
        }
    }
]}
</code>```

I removed what was in coordinates for readability, due to it being thousands of lines long.

here is the python code. Note trailName does nothing here, as I have opted to test with individual IDs and names until I return the specific object I want.

```<code>@app.route('/<trailName>', methods = ['GET'])
def trail(trailName):
    try:
        # trails = db.output_data_retry.find({'elements.tags.name':"Arch Cape to Cape Falcon Trail"}) # returns entire collection
        # trails = db.output_data_retry.find_one({ "elements" : { "$elemMatch" : { "id":1 } } } ) # also just returns entire collection
        # trails = db.output_data_retry.aggregate({ "elements" : { "$elemMatch" : { "id":1 } } } ) # {"error": "pipeline must be a list"}
        # trails = db.output_data_retry.find({ "elements.tags" : { "$elemMatch" : { "name":"Arch Cape to Cape Falcon Trail" } } } ) # returns empty set
        # trails = db.output_data_retry.find({ "elements" : { "tags" : { "$elemMatch" : { "name":"Arch Cape to Cape Falcon Trail" } } }  } ) # empty set
        # trails = db.output_data_retry.find({ "elements.tags" : { "$elemMatch" : { "name":"Arch%20Cape%20to%20Cape%20Falcon%20Trail" } } } ) # empty set
        # trails = db.output_data_retry.find({ "elements.tags" : { "$elemMatch" : { "name":'Arch%20Cape%20to%20Cape%20Falcon%20Trail'} } } ) # empty set
        # trails = db.output_data_retry.find({ 'tags' : { "$elemMatch" : { 'name':"Arch Cape to Cape Falcon Trail" } } } ) # empty set
        # trails = db.output_data_retry.find({ "$match" : { "elements.tags" : { "$elemMatch" : { "name":"Arch Cape to Cape Falcon Trail" } } } } ) # empty set
        # trails = db.output_data_retry.find_one({'elements.tags.name':"Arch Cape to Cape Falcon Trail"}) # returns entire collection
        # trails = db.output_data_retry.find_one({'elements.tags.name':['Arch Cape to Cape Falcon Trail']}) #returns null
        # trails = db.output_data_retry.find_one({'elements.id':[1]}) #returns null
        trails = db.output_data_retry.find({'elements.id':[1]}) #returns an empty set
        return dumps(trails)
    except Exception as e:
       return dumps({'error' : str(e)})
</code>```

also note that the same thing happens in MongoDB compass when I attempt these queries. I eiether return the entire array, not the specific object attributes.

答:
One way to find your specific element:

db.collection.find({
  "elements.tags.name": "Arch Cape to Cape Falcon Trail"
},
{
  "elements.$": 1,
  "_id": 0
})
```

Try it on mongoplayground.net.

Body:
currently writing a flask api with python/pymongo.

Currently I am unable to return a specific object from this nested json array. I have been utilizing pymongo's db.collection.find(), and I either return the entire array or an empty set. Same thing happens in MongoDB  I will provide what I have tried below.

Sample of the JSON I am querying:

{
"elements": [
    {
        "type": "item",
        "id": 1,
        "geometry": {
            "type": "LineString",
            "coordinates": [

            ]
        },
        "tags": {
            "foot": "yes",
            "highway": "path",
            "mtb": "yes",
            "name": "Arch Cape to Cape Falcon Trail",
            "sac_scale": "hiking",
            "surface": "ground",
            "_osm_type": "way"
        }
    },
    {
        "type": "item",
        "id": 2,
        "geometry": {
            "type": "LineString",
            "coordinates": [

            ]
        },
        "tags": {
            "foot": "yes",
            "highway": "path",
            "mtb": "yes",
            "name": "Cape Falcon Trail",
            "sac_scale": "hiking",
            "surface": "ground",
            "_osm_type": "way"
        }
    }
]}

I removed what was in coordinates for readability, due to it being thousands of lines long.

here is the python code. Note trailName does nothing here, as I have opted to test with individual IDs and names until I return the specific object I want.

@app.route('/<trailName>', methods = ['GET'])
def trail(trailName):
    try:
        # trails = db.output_data_retry.find({'elements.tags.name':"Arch Cape to Cape Falcon Trail"}) # returns entire collection
        # trails = db.output_data_retry.find_one({ "elements" : { "$elemMatch" : { "id":1 } } } ) # also just returns entire collection
        # trails = db.output_data_retry.aggregate({ "elements" : { "$elemMatch" : { "id":1 } } } ) # {"error": "pipeline must be a list"}
        # trails = db.output_data_retry.find({ "elements.tags" : { "$elemMatch" : { "name":"Arch Cape to Cape Falcon Trail" } } } ) # returns empty set
        # trails = db.output_data_retry.find({ "elements" : { "tags" : { "$elemMatch" : { "name":"Arch Cape to Cape Falcon Trail" } } }  } ) # empty set
        # trails = db.output_data_retry.find({ "elements.tags" : { "$elemMatch" : { "name":"Arch%20Cape%20to%20Cape%20Falcon%20Trail" } } } ) # empty set
        # trails = db.output_data_retry.find({ "elements.tags" : { "$elemMatch" : { "name":'Arch%20Cape%20to%20Cape%20Falcon%20Trail'} } } ) # empty set
        # trails = db.output_data_retry.find({ 'tags' : { "$elemMatch" : { 'name':"Arch Cape to Cape Falcon Trail" } } } ) # empty set
        # trails = db.output_data_retry.find({ "$match" : { "elements.tags" : { "$elemMatch" : { "name":"Arch Cape to Cape Falcon Trail" } } } } ) # empty set
        # trails = db.output_data_retry.find_one({'elements.tags.name':"Arch Cape to Cape Falcon Trail"}) # returns entire collection
        # trails = db.output_data_retry.find_one({'elements.tags.name':['Arch Cape to Cape Falcon Trail']}) #returns null
        # trails = db.output_data_retry.find_one({'elements.id':[1]}) #returns null
        trails = db.output_data_retry.find({'elements.id':[1]}) #returns an empty set
        return dumps(trails)
    except Exception as e:
       return dumps({'error' : str(e)})

also note that the same thing happens in MongoDB compass when I attempt these queries. I eiether return the entire array, not the specific object attributes.

Body:
One way to find your specific element:

db.collection.find({
  "elements.tags.name": "Arch Cape to Cape Falcon Trail"
},
{
  "elements.$": 1,
  "_id": 0
})

Try it on mongoplayground.net.


问:
Is it better to send AJAX calls to a PHP script? Or use PHP in the page?
I'm wondering if I should let one php script do all of the sqli interactions and access the information with AJAX calls, or if I should handle those interactions as needed on the same page. Are there any security issues with either. What is best practice?</p>

答:
It is quite subjective, as there is a fair bit of personal preference. Without knowing exactly what is on the page, and how much time you you want to spend working on it, and you skill level, we can't say for sure which is best.

There are some advantages, and disadvantages

If you render everything in the page, then the page itself will be slower to initially load in the browser, so if initial load time is important to you, use ajax requests.

If you are writing basic admin pages, CRUD (Create Read Update Delete) records, and it is only used for a handful of users, maybe you can save time building them by using full page requests.

Personally I find it faster to write/debug full pages rendered in php, just because I am not also writing js/jquery/react or whatever flavour of client side scripting you are working with.

With ajax, you tend to end up doing validation both on the client side, and the server side, as you can never trust the data sent to your sever, the end user can easily work around js validation.

From an end user perspective, I find that ajax requests provide a nicer experience. The user gets to see a page load fast, with some spinners (so you know something is happening), then parts of the page load, think of the likes of facebook, scroll down and you have infinite scrolling, the next lot of stories load and append to the page, without reloading the whole lot.

Security wise, full page requests and ajax requests are generally as secure as each other, most rely on cookies for authentication, and cookies work equally for both methods.


问:
How to create interactive line graph in Shiny-R?

Problem

This is my first time writing shiny-R. Really sorry for being way off on this.

I have a dataset about Covid-19 Community Mobility in Thailand. I want to create multiple line graph (with difference color) from choosing dateRangeInput and checkboxGroupInput.But now I can't interact the data with the input.How can I write the code?

Data

This is my data structure
: https://i.stack.imgur.com/xR2j0.png

This is my data on Googlesheet

The data contain date(from 15-02-20 to 08-01-22),6 place categories.There are 7 column and 694 rows

My current code

```<code>library(shiny)
library(ggplot2)
library(shinyWidgets)
library(dslabs)
library(tidyverse)
library(plotly)

data(Data)
# Define UI ----
ui <- fluidPage(
  titlePanel("Covid-19 Community Mobility in Thailand"),

  sidebarLayout(
    sidebarPanel(
      dateRangeInput("Input$dateInput", h3("Date range"),
                     start = '2020-02-15',end = '2022-01-08',
                     min = '2020-02-15',max = '2022-01-08'),
      checkboxGroupInput("Input$placeInput",
                         h3("Place categories"),
                         choices = list("Retail & recreation" = Data$retail_and_recreation,
                                        "Grocery & pharmacy" = Data$grocery_and_pharmacy,
                                        "Parks" = Data$parks,
                                        "Transit stations" = Data$Transit_stations,
                                        "Workplaces" = Data$workplaces,
                                        "Residential" = Data$residential),
                         selected = Data$retail_and_recreation)),
    mainPanel(
      plotOutput("Placeplot")
    )
  )
)

# Define server logic ----
server <- function(input, output) {

  output$Placeplot <- renderPlot({
    ggplot(Data,aes(x=Input$dateInput,y=Input$PlaceInput))+geom_line(color="Blue")+theme_classic()
  })
}

# Run the app ----
shinyApp(ui = ui, server = server)
</code>```

Thank you very much for helping.

答:
Welcome to SO, Hong

Here is a first take on what you might want.
You can achieve this without any more libraries other than ggplot2 and tidyverse
I tried to add some comments inside that hopefully will give you some more guidance.

[Note: Replace the readxl::read_xlsx("C:/R-projects/Data.xlsx") part to
how you will bring your data into R. This part of code will only work on my pc]

```<code>library(shiny)
library(ggplot2)
library(tidyverse)

# Data preparation ----
dta <- readxl::read_xlsx("C:/R-projects/Data.xlsx")

# Long dataset. Works so much better with ggplot and for multi lines
dta_long <-
  dta %>%
  pivot_longer(cols = -date, names_to = "category", values_to = "value")

# I will use these to set the sart and end of the dateRange Input
date_min = min(dta$date)
date_max = max(dta$date)

# UI Definition ----
ui <- fluidPage(

  titlePanel("Covid-19 Community Mobility in Thailand"),

  sidebarLayout(
    sidebarPanel(
      dateRangeInput("date_range", h3("Date range"),
                     start = date_min, end = date_max,
                     min = date_min, max = date_max),
      checkboxGroupInput("categories",
                         h3("Place categories"),
                         choices = list(

                           # This list setup:
                           # The name is what is shown to the app user. [The left part of the `=`]
                           # This is best of it's something human readbale
                           # The value is what is going to be used when selected [The right part of the `=`]
                           # We want the value to be what the actual value of the category column of the dataset

                           "Retail & recreation" = "retail_and_recreation",
                           "Grocery & pharmacy"  = "grocery_and_pharmacy",
                           "Parks"               = "parks",
                           "Transit stations"    = "transit_stations",
                           "Workplaces"          = "workplaces",
                           "Residential"         = "residential"
                         ),
                         selected = "retail_and_recreation")),
    mainPanel(
      plotOutput("place_plot")
    )
  )
)

# Define server logic ----
server <- function(input, output) {

  # I prefer to get the plot as a reactive() first, and then render it with renderPlot()
  place_plot <- reactive({

    dta_long %>%
      # Here I filter on
      # - The categories the user selected
      # - The date range the user selected
      filter(category %in% input$categories,
             date >= input$date_range[[1]] & date <= input$date_range[[2]]
      ) %>%
      ggplot(
        aes(x = date, y = value, colour = category)
      ) +
      geom_line()+
      theme_classic()
  })

  output$place_plot <- renderPlot({
    place_plot()
  })
}

# Run the app ----
shinyApp(ui = ui, server = server)
</code>```

Body:
Problem

This is my first time writing shiny-R. Really sorry for being way off on this.

I have a dataset about Covid-19 Community Mobility in Thailand. I want to create multiple line graph (with difference color) from choosing dateRangeInput and checkboxGroupInput.But now I can't interact the data with the input.How can I write the code?

Data

This is my data structure
: https://i.stack.imgur.com/xR2j0.png

This is my data on Googlesheet

The data contain date(from 15-02-20 to 08-01-22),6 place categories.There are 7 column and 694 rows

My current code

library(shiny)
library(ggplot2)
library(shinyWidgets)
library(dslabs)
library(tidyverse)
library(plotly)

data(Data)
# Define UI ----
ui <- fluidPage(
  titlePanel("Covid-19 Community Mobility in Thailand"),

  sidebarLayout(
    sidebarPanel(
      dateRangeInput("Input$dateInput", h3("Date range"),
                     start = '2020-02-15',end = '2022-01-08',
                     min = '2020-02-15',max = '2022-01-08'),
      checkboxGroupInput("Input$placeInput",
                         h3("Place categories"),
                         choices = list("Retail & recreation" = Data$retail_and_recreation,
                                        "Grocery & pharmacy" = Data$grocery_and_pharmacy,
                                        "Parks" = Data$parks,
                                        "Transit stations" = Data$Transit_stations,
                                        "Workplaces" = Data$workplaces,
                                        "Residential" = Data$residential),
                         selected = Data$retail_and_recreation)),
    mainPanel(
      plotOutput("Placeplot")
    )
  )
)

# Define server logic ----
server <- function(input, output) {

  output$Placeplot <- renderPlot({
    ggplot(Data,aes(x=Input$dateInput,y=Input$PlaceInput))+geom_line(color="Blue")+theme_classic()
  })
}

# Run the app ----
shinyApp(ui = ui, server = server)

Thank you very much for helping.

Body:
Welcome to SO, Hong

Here is a first take on what you might want.
You can achieve this without any more libraries other than ggplot2 and tidyverse
I tried to add some comments inside that hopefully will give you some more guidance.

[Note: Replace the readxl::read_xlsx("C:/R-projects/Data.xlsx") part to
how you will bring your data into R. This part of code will only work on my pc]

library(shiny)
library(ggplot2)
library(tidyverse)

# Data preparation ----
dta <- readxl::read_xlsx("C:/R-projects/Data.xlsx")

# Long dataset. Works so much better with ggplot and for multi lines
dta_long <-
  dta %>%
  pivot_longer(cols = -date, names_to = "category", values_to = "value")

# I will use these to set the sart and end of the dateRange Input
date_min = min(dta$date)
date_max = max(dta$date)

# UI Definition ----
ui <- fluidPage(

  titlePanel("Covid-19 Community Mobility in Thailand"),

  sidebarLayout(
    sidebarPanel(
      dateRangeInput("date_range", h3("Date range"),
                     start = date_min, end = date_max,
                     min = date_min, max = date_max),
      checkboxGroupInput("categories",
                         h3("Place categories"),
                         choices = list(

                           # This list setup:
                           # The name is what is shown to the app user. [The left part of the `=`]
                           # This is best of it's something human readbale
                           # The value is what is going to be used when selected [The right part of the `=`]
                           # We want the value to be what the actual value of the category column of the dataset

                           "Retail & recreation" = "retail_and_recreation",
                           "Grocery & pharmacy"  = "grocery_and_pharmacy",
                           "Parks"               = "parks",
                           "Transit stations"    = "transit_stations",
                           "Workplaces"          = "workplaces",
                           "Residential"         = "residential"
                         ),
                         selected = "retail_and_recreation")),
    mainPanel(
      plotOutput("place_plot")
    )
  )
)

# Define server logic ----
server <- function(input, output) {

  # I prefer to get the plot as a reactive() first, and then render it with renderPlot()
  place_plot <- reactive({

    dta_long %>%
      # Here I filter on
      # - The categories the user selected
      # - The date range the user selected
      filter(category %in% input$categories,
             date >= input$date_range[[1]] & date <= input$date_range[[2]]
      ) %>%
      ggplot(
        aes(x = date, y = value, colour = category)
      ) +
      geom_line()+
      theme_classic()
  })

  output$place_plot <- renderPlot({
    place_plot()
  })
}

# Run the app ----
shinyApp(ui = ui, server = server)


问:
how to get count value in arraylist<object> for kotlin, if value in same array list will still count 1?
i want to get the count value of one of the children of arrayString . so i have Arraylist <resistance?>(), which contains {name, room_block, registration number} let's say the values

{Faisal, A-1, 628345}

{Agun, A-1, 932983}

{Jefri, B-1, 7820179}

then I want to get the count value from Room_Block so that it will return the value.

Number of Rooms = 2, namely A-1 and B-1

this is my temporary code which is false

this is my Arraylist value form

```<code>val dao = DAOTahanan()
    dao.get().addValueEventListener(object : ValueEventListener {
        @SuppressLint("NotifyDataSetChanged")
        override fun onDataChange(snapshot: DataSnapshot) {
            emps.clear()
            for (data in snapshot.children) {
                val emp = data.getValue(tahanan::class.java)
                emp!!.setkey(data.key)
                emps.add(emp)

            }
            temporay.sortWith { lhs, rhs ->
                rhs!!.name?.let {
                    lhs!!.name!!.compareTo(
                        it
                    )
                }!!
            }
                //filter jika nilai ada yang ganda
                temp.clear()
                for(item in tempora){

                    if (!temp.stream().anyMatch { t-> t?.blok_kamar == item?.blok_kamar }){

                        temp.add(item)
                    }else{
                        Log.e("Check duplikat value", "__${tempora.stream().count().toInt()}")
                    }
                }
                temp.sortWith { lhs, rhs ->
                    rhs!!.blok_kamar?.let {
                        lhs!!.blok_kamar!!.compareTo(
                            it
                        )
                    }!!
                }
                    //adapter & viewmodel cardslide
                adap = adaptercardslide_levelsdua(context!!, tempora)
                rec!!.layoutManager = LinearLayoutManager(context!!, LinearLayoutManager.HORIZONTAL, false)
                rec!!.adapter = adap
                adap?.setItems(temp)
</code>```

this is the code where i get the data Arraylist<Prisoner?>()
and this my code in adapter recycleview :

```<code>    package com.example.testing.model

import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.testing.Dashboard.detail.Ac_detail_tahanan
import com.example.testing.Database.tahanan
import com.example.testing.R
import com.example.testing.adapter.RVAdapter
import java.util.stream.Collectors
import kotlin.collections.ArrayList
import androidx.localbroadcastmanager.content.LocalBroadcastManager

class adaptercardslide(private val context: Context, tempora: ArrayList<tahanan?>): RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private val valueint = tempora
    var typeface_medium : Typeface? = null
    var typeface_bold: Typeface? = null
    var typefacesemi: Typeface? = null
    var typefacedefauld: Typeface?= null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val view: View = LayoutInflater.from(context).inflate(R.layout.card_item, parent, false)
        typeface_medium = ResourcesCompat.getFont(context, R.font.poppins_medium)
        typeface_bold = ResourcesCompat.getFont(context, R.font.poppins_bold)
        typefacesemi = ResourcesCompat.getFont(context, R.font.poppins_semibold)
        typefacedefauld = ResourcesCompat.getFont(context, R.font.poppins)
        return modelcardslide(view)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val vh: modelcardslide = holder as modelcardslide
        val emp: tahanan = list[position]!!
        val count = valueint.count {
            emp.blok_kamar?.let { it1 -> it?.blok_kamar?.contains(it1) }!!
        }

        vh.nameblok.text = emp.blok_kamar
        vh.nameblok.typeface = typeface_bold

        vh.jumlahorang.text = "$count, Tahanan"
        vh.jumlahorang.typeface = typefacesemi

        vh.titlejumlah.typeface = typeface_bold

        vh.btnclik.setOnClickListener {
            val ItemName: String = vh.nameblok.text.toString()
            val intent = Intent("blok-selected")
            //            intent.putExtra("quantity",Integer.parseInt(quantity.getText().toString()));
            //            intent.putExtra("quantity",Integer.parseInt(quantity.getText().toString()));
            intent.putExtra("item", ItemName)
            LocalBroadcastManager.getInstance(context).sendBroadcast(intent)
        }
    }

    override fun getItemCount(): Int {
        return list.size
    }

    var list: ArrayList<tahanan?> = ArrayList<tahanan?>()
    fun setItems(emp: ArrayList<tahanan?>) {
        list.addAll(emp)
    }
}
</code>```

答:
I have found the answer, and just filter by using startswith()
here is the code i use :</p>
```<code>var temporay = ArrayList<tahanan?>()
repeat(temp.size) {
                    temporay = (temp.stream()
                        .filter {
                            it?.blok_kamar!!.startsWith(emp.blok_kamar!![0])
                        }
                        .collect(Collectors.toList()) as ArrayList<tahanan?>)
                }
</code>```

Body:
i want to get the count value of one of the children of arrayString . so i have Arraylist <resistance?>(), which contains {name, room_block, registration number} let's say the values

{Faisal, A-1, 628345}

{Agun, A-1, 932983}

{Jefri, B-1, 7820179}

then I want to get the count value from Room_Block so that it will return the value.

Number of Rooms = 2, namely A-1 and B-1

this is my temporary code which is false

this is my Arraylist value form

val dao = DAOTahanan()
    dao.get().addValueEventListener(object : ValueEventListener {
        @SuppressLint("NotifyDataSetChanged")
        override fun onDataChange(snapshot: DataSnapshot) {
            emps.clear()
            for (data in snapshot.children) {
                val emp = data.getValue(tahanan::class.java)
                emp!!.setkey(data.key)
                emps.add(emp)

            }
            temporay.sortWith { lhs, rhs ->
                rhs!!.name?.let {
                    lhs!!.name!!.compareTo(
                        it
                    )
                }!!
            }
                //filter jika nilai ada yang ganda
                temp.clear()
                for(item in tempora){

                    if (!temp.stream().anyMatch { t-> t?.blok_kamar == item?.blok_kamar }){

                        temp.add(item)
                    }else{
                        Log.e("Check duplikat value", "__${tempora.stream().count().toInt()}")
                    }
                }
                temp.sortWith { lhs, rhs ->
                    rhs!!.blok_kamar?.let {
                        lhs!!.blok_kamar!!.compareTo(
                            it
                        )
                    }!!
                }
                    //adapter & viewmodel cardslide
                adap = adaptercardslide_levelsdua(context!!, tempora)
                rec!!.layoutManager = LinearLayoutManager(context!!, LinearLayoutManager.HORIZONTAL, false)
                rec!!.adapter = adap
                adap?.setItems(temp)

this is the code where i get the data Arraylist<Prisoner?>()
and this my code in adapter recycleview :

    package com.example.testing.model

import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.testing.Dashboard.detail.Ac_detail_tahanan
import com.example.testing.Database.tahanan
import com.example.testing.R
import com.example.testing.adapter.RVAdapter
import java.util.stream.Collectors
import kotlin.collections.ArrayList
import androidx.localbroadcastmanager.content.LocalBroadcastManager

class adaptercardslide(private val context: Context, tempora: ArrayList<tahanan?>): RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private val valueint = tempora
    var typeface_medium : Typeface? = null
    var typeface_bold: Typeface? = null
    var typefacesemi: Typeface? = null
    var typefacedefauld: Typeface?= null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val view: View = LayoutInflater.from(context).inflate(R.layout.card_item, parent, false)
        typeface_medium = ResourcesCompat.getFont(context, R.font.poppins_medium)
        typeface_bold = ResourcesCompat.getFont(context, R.font.poppins_bold)
        typefacesemi = ResourcesCompat.getFont(context, R.font.poppins_semibold)
        typefacedefauld = ResourcesCompat.getFont(context, R.font.poppins)
        return modelcardslide(view)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val vh: modelcardslide = holder as modelcardslide
        val emp: tahanan = list[position]!!
        val count = valueint.count {
            emp.blok_kamar?.let { it1 -> it?.blok_kamar?.contains(it1) }!!
        }

        vh.nameblok.text = emp.blok_kamar
        vh.nameblok.typeface = typeface_bold

        vh.jumlahorang.text = "$count, Tahanan"
        vh.jumlahorang.typeface = typefacesemi

        vh.titlejumlah.typeface = typeface_bold

        vh.btnclik.setOnClickListener {
            val ItemName: String = vh.nameblok.text.toString()
            val intent = Intent("blok-selected")
            //            intent.putExtra("quantity",Integer.parseInt(quantity.getText().toString()));
            //            intent.putExtra("quantity",Integer.parseInt(quantity.getText().toString()));
            intent.putExtra("item", ItemName)
            LocalBroadcastManager.getInstance(context).sendBroadcast(intent)
        }
    }

    override fun getItemCount(): Int {
        return list.size
    }

    var list: ArrayList<tahanan?> = ArrayList<tahanan?>()
    fun setItems(emp: ArrayList<tahanan?>) {
        list.addAll(emp)
    }
}

Body:
I have found the answer, and just filter by using startswith()
here is the code i use :

var temporay = ArrayList<tahanan?>()
repeat(temp.size) {
                    temporay = (temp.stream()
                        .filter {
                            it?.blok_kamar!!.startsWith(emp.blok_kamar!![0])
                        }
                        .collect(Collectors.toList()) as ArrayList<tahanan?>)
                }


问:
Combine similar columns with different character names data?
```<code>ID <- c("IDa", "IDb","IDc","IDe","IDd","IDe")
names1 <- c("robin", "bob", "eric", "charlie", "robin", "gabby")
matrix1 <- matrix(names1, 1, 6)
colnames(matrix1) <- c("IDa", "IDb", "IDc","IDe", "IDd", "IDe")

</code>```

This is the output:

IDa
IDb
IDc
IDe
IDd
IDe

robin
bob
eric
charlie
robin
gabby

But I want it to look like this:

IDa
IDb
IDc
IDe
IDd

robin
bob
eric
charlie
robin

gabby

答:
We may split and then cbind after padding with NA

```<code>lst1 <- split(names, ID)
do.call(cbind, lapply(lst1, `length<-`, max(lengths(lst1))))
</code>```

-output

```<code>     IDa     IDb   IDc    IDd     IDe
[1,] "robin" "bob" "eric" "robin" "charlie"
[2,] NA      NA    NA     NA      "gabby"
</code>```

Body:
ID <- c("IDa", "IDb","IDc","IDe","IDd","IDe")
names1 <- c("robin", "bob", "eric", "charlie", "robin", "gabby")
matrix1 <- matrix(names1, 1, 6)
colnames(matrix1) <- c("IDa", "IDb", "IDc","IDe", "IDd", "IDe")

This is the output:

IDa
IDb
IDc
IDe
IDd
IDe

robin
bob
eric
charlie
robin
gabby

But I want it to look like this:

IDa
IDb
IDc
IDe
IDd

robin
bob
eric
charlie
robin

gabby

Body:
We may split and then cbind after padding with NA

lst1 <- split(names, ID)
do.call(cbind, lapply(lst1, `length<-`, max(lengths(lst1))))

-output

     IDa     IDb   IDc    IDd     IDe
[1,] "robin" "bob" "eric" "robin" "charlie"
[2,] NA      NA    NA     NA      "gabby"