问:
Caused by: java.lang.IllegalArgumentException: Application Context cannot be null
can someone help me, that's my configuration class

```<code> package net.king.cofingWeb;

import org.apache.catalina.core.ApplicationContext;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.ITemplateEngine;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;

@Configuration
public class ThymeMvc extends WebMvcConfigurerAdapter {

      @Bean
      public ViewResolver viewResolver() {
            ThymeleafViewResolver resolver = new ThymeleafViewResolver();
            resolver.setTemplateEngine(templateEngine());
            resolver.setCharacterEncoding("UTF-8");
            return resolver;
          }

    @Bean
    public ITemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(templateResolver());
        return engine;
      }

    private ITemplateResolver templateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setTemplateMode(TemplateMode.HTML);
        resolver.setCharacterEncoding("UTF-8");
        resolver.setCacheable(false);
        resolver.setPrefix("classpath:/templates/");
        resolver.setSuffix(".html");
        return resolver;
      }

}
</code>```

my pom

```<code>    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf</artifactId>
        <version>3.0.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring4</artifactId>
        <version>3.0.9.RELEASE</version>
    </dependency>
</code>```

My Controller

```<code>    package net.king.web;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import net.king.entities.Candidate;

@Controller
@EnableWebMvc
public class HomeController {

    @RequestMapping(value="/")
    public String index() {
        return "index";
    }

}
</code>```

my index file is in the template folder

my index file is in the template folder, after starting the server here is the result, I spend time solving but still no solutions

```<code>java.lang.IllegalArgumentException: Application Context cannot be null
    at org.thymeleaf.util.Validate.notNull(Validate.java:37) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.templateresource.SpringResourceTemplateResource.<init>(SpringResourceTemplateResource.java:64) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver.computeTemplateResource(SpringResourceTemplateResolver.java:69) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.templateresolver.AbstractConfigurableTemplateResolver.computeTemplateResource(AbstractConfigurableTemplateResolver.java:1414) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.templateresolver.AbstractTemplateResolver.resolveTemplate(AbstractTemplateResolver.java:356) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.engine.TemplateManager.resolveTemplate(TemplateManager.java:845) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:607) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098) [thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072) [thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.view.ThymeleafView.renderFragment(ThymeleafView.java:352) [thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.view.ThymeleafView.render(ThymeleafView.java:190) [thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1372) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1118) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1057) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) [tomcat-embed-websocket-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) [spring-web-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_241]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_241]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_241]

2020-06-02 01:31:14.282 ERROR 9236 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception processing template (template: "index")] with root cause

java.lang.IllegalArgumentException: Application Context cannot be null
    at org.thymeleaf.util.Validate.notNull(Validate.java:37) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.templateresource.SpringResourceTemplateResource.<init>(SpringResourceTemplateResource.java:64) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver.computeTemplateResource(SpringResourceTemplateResolver.java:69) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.templateresolver.AbstractConfigurableTemplateResolver.computeTemplateResource(AbstractConfigurableTemplateResolver.java:1414) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.templateresolver.AbstractTemplateResolver.resolveTemplate(AbstractTemplateResolver.java:356) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.engine.TemplateManager.resolveTemplate(TemplateManager.java:845) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:607) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.view.ThymeleafView.renderFragment(ThymeleafView.java:352) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.view.ThymeleafView.render(ThymeleafView.java:190) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1372) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1118) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1057) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_241]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_241]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_241]
</code>```

答:
Since it's a spring mvc application as far as I understand, I think the issue is with your @configuration change the beans to :

```<code>@Bean
public SpringTemplateEngine templateEngine() {
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.setTemplateResolver(templateResolver());
    templateEngine.setTemplateEngineMessageSource(messageSource());
    return templateEngine;
}

@Bean
public SpringResourceTemplateResolver templateResolver(){
    // SpringResourceTemplateResolver automatically integrates with Spring's own
    // resource resolution infrastructure, which is highly recommended.
    SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
    templateResolver.setApplicationContext(this.applicationContext);
    templateResolver.setPrefix("/WEB-INF/templates/");
    templateResolver.setSuffix(".html");
    // HTML is the default value, added here for the sake of clarity.
    templateResolver.setTemplateMode(TemplateMode.HTML);
    // Template cache is true by default. Set to false if you want
    // templates to be automatically updated when modified.
    templateResolver.setCacheable(true);
    return templateResolver;
}
</code>```

The SpringTemplateEngine class performs all of the configuration steps. Try using Spring classes for configuration instead of the Thymeleaf dependency ones.Use Spring classes instead of the Thymeleaf classes for configuring Thymeleaf so that the application context gets injected during bean creation.You are returning a ThymeleafViewResolver for view resolver but it is perfectly alright as it implements the ViewResolver, but the other two beans should be changed.

Also, if you plan on upgrading the spring version from 4 to 5 , also change the configuration to following :

```<code>@Configuration
public WebConfig implements WebMvcConfigurer {
    // ...
}
</code>```

as WebMvcConfigurerAdapter is deprecated in Spring5.If your application was a springboot application instead of the dependencies that you provided , use the following dependency for thymeleaf :

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</code>```

Body:
can someone help me, that's my configuration class

 package net.king.cofingWeb;

import org.apache.catalina.core.ApplicationContext;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.ITemplateEngine;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;

@Configuration
public class ThymeMvc extends WebMvcConfigurerAdapter {

      @Bean
      public ViewResolver viewResolver() {
            ThymeleafViewResolver resolver = new ThymeleafViewResolver();
            resolver.setTemplateEngine(templateEngine());
            resolver.setCharacterEncoding("UTF-8");
            return resolver;
          }

    @Bean
    public ITemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(templateResolver());
        return engine;
      }

    private ITemplateResolver templateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setTemplateMode(TemplateMode.HTML);
        resolver.setCharacterEncoding("UTF-8");
        resolver.setCacheable(false);
        resolver.setPrefix("classpath:/templates/");
        resolver.setSuffix(".html");
        return resolver;
      }

}

my pom

    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf</artifactId>
        <version>3.0.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring4</artifactId>
        <version>3.0.9.RELEASE</version>
    </dependency>

My Controller

    package net.king.web;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import net.king.entities.Candidate;

@Controller
@EnableWebMvc
public class HomeController {

    @RequestMapping(value="/")
    public String index() {
        return "index";
    }

}

my index file is in the template folder

my index file is in the template folder, after starting the server here is the result, I spend time solving but still no solutions

java.lang.IllegalArgumentException: Application Context cannot be null
    at org.thymeleaf.util.Validate.notNull(Validate.java:37) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.templateresource.SpringResourceTemplateResource.<init>(SpringResourceTemplateResource.java:64) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver.computeTemplateResource(SpringResourceTemplateResolver.java:69) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.templateresolver.AbstractConfigurableTemplateResolver.computeTemplateResource(AbstractConfigurableTemplateResolver.java:1414) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.templateresolver.AbstractTemplateResolver.resolveTemplate(AbstractTemplateResolver.java:356) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.engine.TemplateManager.resolveTemplate(TemplateManager.java:845) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:607) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098) [thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072) [thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.view.ThymeleafView.renderFragment(ThymeleafView.java:352) [thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.view.ThymeleafView.render(ThymeleafView.java:190) [thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1372) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1118) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1057) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) [tomcat-embed-websocket-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) [spring-web-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_241]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_241]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_241]

2020-06-02 01:31:14.282 ERROR 9236 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception processing template (template: "index")] with root cause

java.lang.IllegalArgumentException: Application Context cannot be null
    at org.thymeleaf.util.Validate.notNull(Validate.java:37) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.templateresource.SpringResourceTemplateResource.<init>(SpringResourceTemplateResource.java:64) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver.computeTemplateResource(SpringResourceTemplateResolver.java:69) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.templateresolver.AbstractConfigurableTemplateResolver.computeTemplateResource(AbstractConfigurableTemplateResolver.java:1414) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.templateresolver.AbstractTemplateResolver.resolveTemplate(AbstractTemplateResolver.java:356) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.engine.TemplateManager.resolveTemplate(TemplateManager.java:845) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:607) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.view.ThymeleafView.renderFragment(ThymeleafView.java:352) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.view.ThymeleafView.render(ThymeleafView.java:190) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1372) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1118) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1057) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_241]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_241]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_241]

Body:
Since it's a spring mvc application as far as I understand, I think the issue is with your @configuration change the beans to :

@Bean
public SpringTemplateEngine templateEngine() {
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.setTemplateResolver(templateResolver());
    templateEngine.setTemplateEngineMessageSource(messageSource());
    return templateEngine;
}

@Bean
public SpringResourceTemplateResolver templateResolver(){
    // SpringResourceTemplateResolver automatically integrates with Spring's own
    // resource resolution infrastructure, which is highly recommended.
    SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
    templateResolver.setApplicationContext(this.applicationContext);
    templateResolver.setPrefix("/WEB-INF/templates/");
    templateResolver.setSuffix(".html");
    // HTML is the default value, added here for the sake of clarity.
    templateResolver.setTemplateMode(TemplateMode.HTML);
    // Template cache is true by default. Set to false if you want
    // templates to be automatically updated when modified.
    templateResolver.setCacheable(true);
    return templateResolver;
}

The SpringTemplateEngine class performs all of the configuration steps. Try using Spring classes for configuration instead of the Thymeleaf dependency ones.Use Spring classes instead of the Thymeleaf classes for configuring Thymeleaf so that the application context gets injected during bean creation.You are returning a ThymeleafViewResolver for view resolver but it is perfectly alright as it implements the ViewResolver, but the other two beans should be changed.

Also, if you plan on upgrading the spring version from 4 to 5 , also change the configuration to following :

@Configuration
public WebConfig implements WebMvcConfigurer {
    // ...
}

as WebMvcConfigurerAdapter is deprecated in Spring5.If your application was a springboot application instead of the dependencies that you provided , use the following dependency for thymeleaf :

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>


来源: stackexchange

问:
Elements in the array not recognized

    var userInput = prompt('Which fruit would you like?');
      var fruitList = ["banana", 'strawberries', "mango"];

      for(var i=0; i<fruitList.length; i++);
        if(userInput == fruitList[i]){
          alert("Sorry, we are out of " + userInput);
        }else{
          var userFruit = document.createElement('li');
          userFruit.textContent = userInput;
          var fruits = document.getElementById('list');
          fruits.appendChild(userFruit);
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div id="list"></div></code>```

It looks like for loop is not working as it's adding the user input into the list but it doesn't recognize elements from the array. The list which I didn't add here has id="list" and it has the three elements from the array. Thank you!

```<code>  var userInput = prompt('Which fruit would you like?');
  var fruitList = ["banana", 'strawberries', "mango"];

  for(var i=0; i<fruitList.length; i++);
    if(userInput == fruitList[i]){
      alert("Sorry, we are out of " + userInput);
    }else{
      var userFruit = document.createElement('li');
      userFruit.textContent = userInput;
      var fruits = document.getElementById('list');
      fruits.appendChild(userFruit);
    }
</code>```

答:
You should add the curly brackets to the for loop... It is not needed however it is tidier in nature. Your issue was syntax as you had a semi colon at the end of the for loops terminating the loop.

Change this --> for(var i=0; i<fruitList.length; i++);

To this --> for(var i=0; i<fruitList.length; i++){ or for(var i=0; i<fruitList.length; i++)

NOTE ON EDIT: Moved the variables outside the for loop and assigned the innerHTML or you could use textContent to the variable outside the loop. Then in the for loop, appended the created li item to the ul parent.

const userInput = prompt('Which fruit would you like?');
const fruitList = ["banana", 'strawberries', "mango"];
const fruits = document.getElementById('list');
const userFruit = document.createElement('li')
userFruit.innerHTML = userInput;

for (let i = 0; i < fruitList.length; i++) {
  if (userInput === fruitList[i]) {
    alert("Sorry, we are out of " + userInput);
  } else {
    fruits.append(userFruit);
  }
}  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="list"></ul></code>```

ContentLicense: CC BY-SA 4.0

Title: Elements in the array not recognized

Body:
    var userInput = prompt('Which fruit would you like?');
      var fruitList = ["banana", 'strawberries', "mango"];

      for(var i=0; i<fruitList.length; i++);
        if(userInput == fruitList[i]){
          alert("Sorry, we are out of " + userInput);
        }else{
          var userFruit = document.createElement('li');
          userFruit.textContent = userInput;
          var fruits = document.getElementById('list');
          fruits.appendChild(userFruit);
        }

It looks like for loop is not working as it's adding the user input into the list but it doesn't recognize elements from the array. The list which I didn't add here has id="list" and it has the three elements from the array. Thank you!

  var userInput = prompt('Which fruit would you like?');
  var fruitList = ["banana", 'strawberries', "mango"];

  for(var i=0; i<fruitList.length; i++);
    if(userInput == fruitList[i]){
      alert("Sorry, we are out of " + userInput);
    }else{
      var userFruit = document.createElement('li');
      userFruit.textContent = userInput;
      var fruits = document.getElementById('list');
      fruits.appendChild(userFruit);
    }

Body:
You should add the curly brackets to the for loop... It is not needed however it is tidier in nature. Your issue was syntax as you had a semi colon at the end of the for loops terminating the loop.

Change this --> for(var i=0; i<fruitList.length; i++);

To this --> for(var i=0; i<fruitList.length; i++){ or for(var i=0; i<fruitList.length; i++)

NOTE ON EDIT: Moved the variables outside the for loop and assigned the innerHTML or you could use textContent to the variable outside the loop. Then in the for loop, appended the created li item to the ul parent.

const userInput = prompt('Which fruit would you like?');
const fruitList = ["banana", 'strawberries', "mango"];
const fruits = document.getElementById('list');
const userFruit = document.createElement('li')
userFruit.innerHTML = userInput;

for (let i = 0; i < fruitList.length; i++) {
  if (userInput === fruitList[i]) {
    alert("Sorry, we are out of " + userInput);
  } else {
    fruits.append(userFruit);
  }
}

<ul id="list"></ul>


问:
Capybara with headless chrome doesn't clear session between test cases which use different subdomains
I switched my rails tests from capybara-webkit to headless chrome. When I run a test which visits not the default Capybara host the first case passes but the second one fails because the user are already logged in when they try to login

I use chromedriver v2.45, selenium-webdriver (3.141.0) and capybara (2.18.0)

I have the following setup:

```<code>require 'selenium-webdriver'

Capybara.register_driver :chrome do |app|
  options = Selenium::WebDriver::Chrome::Options.new(
    args: %w[headless disable-gpu no-sandbox]
  )
  Capybara::Selenium::Driver.new(app, browser: :chrome, options: options)
end

Capybara.javascript_driver = :chrome
</code>```

I tried to change the app host to the default domain after visiting another domain

```<code>using_app_host("http://another.lvh.me") do
  visit '/'

  # do something
end
</code>```

where using_app_host is

```<code>def using_app_host(host)
  original_host = Capybara.app_host
  Capybara.app_host = host
  yield
ensure
  Capybara.app_host = original_host
end
</code>```

but it didn't help.

The spec structure looks the following way:

```<code>feature "Use another subdomain", js: true do
  before { login } # use default Capybara app host http://root.lvh.me

  scenario "case 1" do
    using_app_host("http://another.lvh.me") do
      # do something
    end
  end

  scenario "case 2" do
    using_app_host("http://another.lvh.me") do
      # do something else
    end
  end
end
</code>```

Any ideas why capybara/headless chrome doesn't clean the user session between the test cases when navigating to another domain?

答:
I found this thread useful in a reverse context. I have a test setup wherein I'm storing session credentials in local storage. And so upgrading from capybara v3.11 to v3.12 broke the suite such that only the first scenario would pass and the rest of the scenarios would fail on the login page every time.
That's because the local storage was getting cleared based on the default behavior of capybara 3.12

I updated my suite to set clear_local_storage and clear_session_storage to false explicitly at time of registering the driver.

```<code>Capybara.register_driver :selenium_chrome do |app|
    Capybara::Selenium::Driver.new(app,
                                   browser: :chrome,
                                   clear_local_storage: false,
                                   clear_session_storage: false)
</code>```

Body:
I switched my rails tests from capybara-webkit to headless chrome. When I run a test which visits not the default Capybara host the first case passes but the second one fails because the user are already logged in when they try to login

I use chromedriver v2.45, selenium-webdriver (3.141.0) and capybara (2.18.0)

I have the following setup:

require 'selenium-webdriver'

Capybara.register_driver :chrome do |app|
  options = Selenium::WebDriver::Chrome::Options.new(
    args: %w[headless disable-gpu no-sandbox]
  )
  Capybara::Selenium::Driver.new(app, browser: :chrome, options: options)
end

Capybara.javascript_driver = :chrome

I tried to change the app host to the default domain after visiting another domain

using_app_host("http://another.lvh.me") do
  visit '/'

  # do something
end

where using_app_host is

def using_app_host(host)
  original_host = Capybara.app_host
  Capybara.app_host = host
  yield
ensure
  Capybara.app_host = original_host
end

but it didn't help.

The spec structure looks the following way:

feature "Use another subdomain", js: true do
  before { login } # use default Capybara app host http://root.lvh.me

  scenario "case 1" do
    using_app_host("http://another.lvh.me") do
      # do something
    end
  end

  scenario "case 2" do
    using_app_host("http://another.lvh.me") do
      # do something else
    end
  end
end

Any ideas why capybara/headless chrome doesn't clean the user session between the test cases when navigating to another domain?

Body:
I found this thread useful in a reverse context. I have a test setup wherein I'm storing session credentials in local storage. And so upgrading from capybara v3.11 to v3.12 broke the suite such that only the first scenario would pass and the rest of the scenarios would fail on the login page every time.
That's because the local storage was getting cleared based on the default behavior of capybara 3.12

I updated my suite to set clear_local_storage and clear_session_storage to false explicitly at time of registering the driver.

Capybara.register_driver :selenium_chrome do |app|
    Capybara::Selenium::Driver.new(app,
                                   browser: :chrome,
                                   clear_local_storage: false,
                                   clear_session_storage: false)


问:
Create json structure in Android
I'm trying to create a json structure like this in Android but cannot find any way to complete it.

```<code>{
  "FirstName": Fred,
  "LastName": "Poulsen",
  "Age": "18",
  "Phone": {
    "mobile": {}
  }
}
</code>```

This is what I have tried to do.

```<code>        Map<Object, Object> objectMap = new HashMap<>();
        Map<Object, Object> phone = new HashMap<>();

        objectMap.put("FirstName", "Fred");
        objectMap.put("LastName", "Poulsen");
        objectMap.put("Age", "18");
        objectMap.put("Phone", phone);
        input.put("mobile", body);
</code>```

答:
test it</p>

```<code>  JSONObject jsonParent = new JSONObject();
  JSONObject jsonMobile = new JSONObject();
        try {
            jsonMobile.put("mobile","");
            jsonParent.put("FirstName", "Fred");
            jsonParent.put("LastName", "Poulsen");
            jsonParent.put("Age", "18");
            jsonParent.put("Phone", jsonMobile);

        } catch (JSONException e) {
            e.printStackTrace();
        }
</code>```

Title: Create json structure in Android

Body:
I'm trying to create a json structure like this in Android but cannot find any way to complete it.

{
  "FirstName": Fred,
  "LastName": "Poulsen",
  "Age": "18",
  "Phone": {
    "mobile": {}
  }
}

This is what I have tried to do.

        Map<Object, Object> objectMap = new HashMap<>();
        Map<Object, Object> phone = new HashMap<>();

        objectMap.put("FirstName", "Fred");
        objectMap.put("LastName", "Poulsen");
        objectMap.put("Age", "18");
        objectMap.put("Phone", phone);
        input.put("mobile", body);

Body:
test it

  JSONObject jsonParent = new JSONObject();
  JSONObject jsonMobile = new JSONObject();
        try {
            jsonMobile.put("mobile","");
            jsonParent.put("FirstName", "Fred");
            jsonParent.put("LastName", "Poulsen");
            jsonParent.put("Age", "18");
            jsonParent.put("Phone", jsonMobile);

        } catch (JSONException e) {
            e.printStackTrace();
        }


问:
How to build a windows docker container for Azure pipeline container job?
Questions about migrating Jenkins to Azure pipeline:

My .net project building requires VS buildtool 2017, Windows SDK and WDK installed. If I use agent pool (MS hosted VM) to build project, are WDK and SDK of required version available in the agent pool (Hosted VM like vs2017-win2016)?

If hosted agent cannot do that, how can I build a Win container for Azure pipeling container job, whch is similar to below jenkins agent container, Is there any dockefile example available? thanks?

Dockerfile for jenkins windows agent:

```<code>FROM openjdk:8-jdk-windowsservercore-1809

ARG version

ENV VERSION ${version:-3.39}
ENV JENKINS_HOME="c:/jenkins"
ENV JENKINS_REMOTING_ENTRY_POINT="${JENKINS_HOME}/agent.jar"
ENV JENKINS_REMOTING_URL="https://repo.jenkins-ci.org/public/org/jenkins-ci/main/remoting/${VERSION}/remoting-${VERSION}.jar"
ENV SHA=AA1525E45DA5D8CFFD40B67B064C86F9F6CE8799A024EDF5D468D0DC2ABD062D
ENV JENKINS_MASTER_HOST="win-tc-docker"
ENV JENKINS_AGENT_ID="NET_00"
ENV JENKINS_AGENT_SECRET="0000000000000000000000000000000000000000000000000000000000000000"
ENV GIT_VERSION 2.25.0
ENV GIT_PATCH_VERSION 1

SHELL ["powershell", "-NoProfile", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; "]

# Install Jenkins agent
RUN \
    New-Item -ItemType Directory -Force -Path $env:JENKINS_HOME; \
    [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12; \
    Invoke-WebRequest -Uri $env:JENKINS_REMOTING_URL -OutFile $env:JENKINS_REMOTING_ENTRY_POINT -UseBasicParsing -Proxy http://proxy.compaq.com:8080 -ProxyUseDefaultCredentials;
#   if ((Get-FileHash -Path $env:JENKINS_REMOTING_ENTRY_POINT -Algorithm SHA256).Hash -ne $env:SHA) { throw 'Download hash does not match'}

# Create temp file for installers
RUN New-Item -ItemType Directory -Force -Path c:\temp;

# Install Subversion (x64) 1.13.1.28686
RUN \
    [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12; \
    Invoke-WebRequest "https://osdn.net/frs/redir.php?m=xtom_hk"""&"""f=%2Fstorage%2Fg%2Ft%2Fto%2Ftortoisesvn%2F1.13.1%2FApplication%2FTortoiseSVN-1.13.1.28686-x64-svn-1.13.0.msi" -OutFile "c:/temp/TortoiseSVN.msi" -UseBasicParsing -Proxy http://proxy.compaq.com:8080 -ProxyUseDefaultCredentials;  \
    Start-Process -FilePath "c:/temp/TortoiseSVN.msi" -ArgumentList '/Passive', '/NoRestart' -PassThru | Wait-Process;

# Install Git
RUN \
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 ; \
    Invoke-WebRequest $('https://github.com/git-for-windows/git/releases/download/v{0}.windows.{1}/MinGit-{0}-busybox-64-bit.zip' -f $env:GIT_VERSION, $env:GIT_PATCH_VERSION) -OutFile 'mingit.zip' -UseBasicParsing ; \
    Expand-Archive mingit.zip -DestinationPath c:\mingit ; \
    Remove-Item mingit.zip -Force ; \
    setx /M PATH $('c:\mingit\cmd;{0}' -f $env:PATH)

# Install Blend 4 SDK
RUN \
    [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12; \
    Invoke-WebRequest "https://download.microsoft.com/download/E/0/0/E0032698-8F1F-497D-B7BD-35275E1EB6FC/BlendWPFSDK_en.msi" -OutFile "c:/temp/Blend4SDK.msi" -UseBasicParsing -Proxy http://proxy.compaq.com:8080 -ProxyUseDefaultCredentials; \
    Start-Process -FilePath "c:/temp/Blend4SDK.msi" -ArgumentList '/passive', '/norestart' -PassThru | Wait-Process;

# Install Blend 4.5 SDK
COPY ./BlendSdk "c:/temp/BlendSdk"
RUN Start-Process -FilePath "c:/temp/BlendSdk/BlendWPFSDK.msi" -ArgumentList '/passive', '/norestart' -PassThru | Wait-Process;

# Install VS 2017 Build Tools
SHELL ["cmd", "/S", "/C" ]
COPY ./BuildTools2017 "c:/temp/BuildTools2017"
RUN C:\temp\BuildTools2017\vs_buildtools_2017.exe --quiet --wait --norestart --nocache --noWeb \
     --add Microsoft.VisualStudio.Workload.ManagedDesktopBuildTools \
     --add Microsoft.VisualStudio.Workload.VCTools \
     --add Microsoft.Net.Component.3.5.DeveloperTools \
     --add Microsoft.VisualStudio.Component.Windows10SDK.17763
SHELL ["powershell", "-NoProfile", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; "]

# Install Visual Studio 2012 Premium
COPY ./VS2012Premium "c:/temp/VS2012Premium"
RUN Start-Process -FilePath "c:/temp/VS2012Premium/vs_premium.exe" -ArgumentList '/passive', '/q', '/s', '/norestart', '/noweb', '/full', '/ProductKey HRFXPFH366KTVG9HXXV8QM3F8' -PassThru | Wait-Process;

# Install WDK 10 1703 (Windows 10.0.15063.0)
COPY ./WDK1703 "c:/temp/WDK1703"
RUN Start-Process -FilePath "c:/temp/WDK1703/wdksetup.exe" -ArgumentList '/q', '/norestart' -PassThru | Wait-Process;

# Install WDK 10 1809 (Windows 10.0.17763.1)
COPY ./WDK1809 "c:/temp/WDK1809"
RUN Start-Process -FilePath "c:/temp/WDK1809/wdksetup.exe" -ArgumentList '/q', '/norestart' -PassThru | Wait-Process;

# Delete temp file content
RUN dir c:\temp | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue;

COPY ./scripts "${JENKINS_HOME}/scripts"

#CMD powershell $env:JENKINS_HOME/scripts/startup.ps1
ENTRYPOINT ["powershell.exe", "-f", "c:/jenkins/scripts/jenkins-agent.ps1"]
</code>```

答:
are WDK and SDK of required version available in the agent pool (Hosted VM like vs2017-win2016)?

Here are some specific versions of SDK and WDK that are installed on the Hosted Agent by default, you can check whether their version meets your requirements:

virtual-environments for Hosted Agent vs2017-win2016

On the other hand, you could also create your private agent to install those components in the private agent.

Is there any dockefile example available? thanks?

You could create a container and install that components in that container. You could check this document for some more details:

Install Build Tools into a container

Hope this helps.

Body:
Questions about migrating Jenkins to Azure pipeline:

My .net project building requires VS buildtool 2017, Windows SDK and WDK installed. If I use agent pool (MS hosted VM) to build project, are WDK and SDK of required version available in the agent pool (Hosted VM like vs2017-win2016)?

If hosted agent cannot do that, how can I build a Win container for Azure pipeling container job, whch is similar to below jenkins agent container, Is there any dockefile example available? thanks?

Dockerfile for jenkins windows agent:

FROM openjdk:8-jdk-windowsservercore-1809

ARG version

ENV VERSION ${version:-3.39}
ENV JENKINS_HOME="c:/jenkins"
ENV JENKINS_REMOTING_ENTRY_POINT="${JENKINS_HOME}/agent.jar"
ENV JENKINS_REMOTING_URL="https://repo.jenkins-ci.org/public/org/jenkins-ci/main/remoting/${VERSION}/remoting-${VERSION}.jar"
ENV SHA=AA1525E45DA5D8CFFD40B67B064C86F9F6CE8799A024EDF5D468D0DC2ABD062D
ENV JENKINS_MASTER_HOST="win-tc-docker"
ENV JENKINS_AGENT_ID="NET_00"
ENV JENKINS_AGENT_SECRET="0000000000000000000000000000000000000000000000000000000000000000"
ENV GIT_VERSION 2.25.0
ENV GIT_PATCH_VERSION 1

SHELL ["powershell", "-NoProfile", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; "]

# Install Jenkins agent
RUN \
    New-Item -ItemType Directory -Force -Path $env:JENKINS_HOME; \
    [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12; \
    Invoke-WebRequest -Uri $env:JENKINS_REMOTING_URL -OutFile $env:JENKINS_REMOTING_ENTRY_POINT -UseBasicParsing -Proxy http://proxy.compaq.com:8080 -ProxyUseDefaultCredentials;
#   if ((Get-FileHash -Path $env:JENKINS_REMOTING_ENTRY_POINT -Algorithm SHA256).Hash -ne $env:SHA) { throw 'Download hash does not match'}

# Create temp file for installers
RUN New-Item -ItemType Directory -Force -Path c:\temp;

# Install Subversion (x64) 1.13.1.28686
RUN \
    [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12; \
    Invoke-WebRequest "https://osdn.net/frs/redir.php?m=xtom_hk"""&"""f=%2Fstorage%2Fg%2Ft%2Fto%2Ftortoisesvn%2F1.13.1%2FApplication%2FTortoiseSVN-1.13.1.28686-x64-svn-1.13.0.msi" -OutFile "c:/temp/TortoiseSVN.msi" -UseBasicParsing -Proxy http://proxy.compaq.com:8080 -ProxyUseDefaultCredentials;  \
    Start-Process -FilePath "c:/temp/TortoiseSVN.msi" -ArgumentList '/Passive', '/NoRestart' -PassThru | Wait-Process;

# Install Git
RUN \
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 ; \
    Invoke-WebRequest $('https://github.com/git-for-windows/git/releases/download/v{0}.windows.{1}/MinGit-{0}-busybox-64-bit.zip' -f $env:GIT_VERSION, $env:GIT_PATCH_VERSION) -OutFile 'mingit.zip' -UseBasicParsing ; \
    Expand-Archive mingit.zip -DestinationPath c:\mingit ; \
    Remove-Item mingit.zip -Force ; \
    setx /M PATH $('c:\mingit\cmd;{0}' -f $env:PATH)

# Install Blend 4 SDK
RUN \
    [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12; \
    Invoke-WebRequest "https://download.microsoft.com/download/E/0/0/E0032698-8F1F-497D-B7BD-35275E1EB6FC/BlendWPFSDK_en.msi" -OutFile "c:/temp/Blend4SDK.msi" -UseBasicParsing -Proxy http://proxy.compaq.com:8080 -ProxyUseDefaultCredentials; \
    Start-Process -FilePath "c:/temp/Blend4SDK.msi" -ArgumentList '/passive', '/norestart' -PassThru | Wait-Process;

# Install Blend 4.5 SDK
COPY ./BlendSdk "c:/temp/BlendSdk"
RUN Start-Process -FilePath "c:/temp/BlendSdk/BlendWPFSDK.msi" -ArgumentList '/passive', '/norestart' -PassThru | Wait-Process;

# Install VS 2017 Build Tools
SHELL ["cmd", "/S", "/C" ]
COPY ./BuildTools2017 "c:/temp/BuildTools2017"
RUN C:\temp\BuildTools2017\vs_buildtools_2017.exe --quiet --wait --norestart --nocache --noWeb \
     --add Microsoft.VisualStudio.Workload.ManagedDesktopBuildTools \
     --add Microsoft.VisualStudio.Workload.VCTools \
     --add Microsoft.Net.Component.3.5.DeveloperTools \
     --add Microsoft.VisualStudio.Component.Windows10SDK.17763
SHELL ["powershell", "-NoProfile", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; "]

# Install Visual Studio 2012 Premium
COPY ./VS2012Premium "c:/temp/VS2012Premium"
RUN Start-Process -FilePath "c:/temp/VS2012Premium/vs_premium.exe" -ArgumentList '/passive', '/q', '/s', '/norestart', '/noweb', '/full', '/ProductKey HRFXPFH366KTVG9HXXV8QM3F8' -PassThru | Wait-Process;

# Install WDK 10 1703 (Windows 10.0.15063.0)
COPY ./WDK1703 "c:/temp/WDK1703"
RUN Start-Process -FilePath "c:/temp/WDK1703/wdksetup.exe" -ArgumentList '/q', '/norestart' -PassThru | Wait-Process;

# Install WDK 10 1809 (Windows 10.0.17763.1)
COPY ./WDK1809 "c:/temp/WDK1809"
RUN Start-Process -FilePath "c:/temp/WDK1809/wdksetup.exe" -ArgumentList '/q', '/norestart' -PassThru | Wait-Process;

# Delete temp file content
RUN dir c:\temp | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue;

COPY ./scripts "${JENKINS_HOME}/scripts"

#CMD powershell $env:JENKINS_HOME/scripts/startup.ps1
ENTRYPOINT ["powershell.exe", "-f", "c:/jenkins/scripts/jenkins-agent.ps1"]


问:
How to change which C++ version compiler is used when installing an R package from source?
I'm trying to install an R package from source using remotes::install_github("pkgname"). I get the following error:

```<code>/bin/sh: /usr/local/Cellar/gcc/9.2.0/bin/g++-7: No such file or directory
</code>```

I checked and I have g++-9 instead. I've been looking for a way to change the settings to direct to the correct path but so far have had no luck. I'm not even sure which package to look in or whether to approach R config files. Any help would be greatly appreciated.

I'm using R version 3.6.3 on Mac OSX 10.15.5 (Catalina). I have XCode developer tools installed but whenever I run checks RStudio suggests that I install them as if it can't find it.

Many thanks

答:
It looks like R can't see your g++ compiler, as you suggest.

1 Checking if g++ is on PATH
Did you install R with homebrew? Since the error path is pointing at /usr/local/Cellar, that seems to be the case.

You can see if the g++ compiler is on path by opening the Terminal program on Mac OS and typing:

```<code>echo $CXX
</code>```

If it returns null (or nothing), there's nothing on path there.

2 Install g++ in brew
Let's install g++ in brew. Open your Terminal and run the following, pressing enter after each line:

```<code>brew update
brew install gcc48
brew doctor
</code>```

After this, please restart your computer.

3 Check if g++ is on PATH now

Run  echo $CXX again on Terminal. If that still doesn't work, see this current issue:

https://github.com/r-lib/rlang/issues/754

I suggest if that didn't work to try to install XCode developer tools again. You can do that as below:

```<code>xcode-select --install
</code>```

Body:
I'm trying to install an R package from source using remotes::install_github("pkgname"). I get the following error:

/bin/sh: /usr/local/Cellar/gcc/9.2.0/bin/g++-7: No such file or directory

I checked and I have g++-9 instead. I've been looking for a way to change the settings to direct to the correct path but so far have had no luck. I'm not even sure which package to look in or whether to approach R config files. Any help would be greatly appreciated.

I'm using R version 3.6.3 on Mac OSX 10.15.5 (Catalina). I have XCode developer tools installed but whenever I run checks RStudio suggests that I install them as if it can't find it.

Many thanks

Body:
It looks like R can't see your g++ compiler, as you suggest.

1 Checking if g++ is on PATH
Did you install R with homebrew? Since the error path is pointing at /usr/local/Cellar, that seems to be the case.

You can see if the g++ compiler is on path by opening the Terminal program on Mac OS and typing:

echo $CXX

If it returns null (or nothing), there's nothing on path there.

2 Install g++ in brew
Let's install g++ in brew. Open your Terminal and run the following, pressing enter after each line:

brew update
brew install gcc48
brew doctor

After this, please restart your computer.

3 Check if g++ is on PATH now

Run  echo $CXX again on Terminal. If that still doesn't work, see this current issue:

https://github.com/r-lib/rlang/issues/754

I suggest if that didn't work to try to install XCode developer tools again. You can do that as below:

xcode-select --install


问:
C++ Visual Studio Error: name followed by '::' must be a class or namespace name (DirectX 11)
I dont understand what's wrong here

manager.h

```<code>#pragma once
class CManager
{

public:
static void Init();
static void Uninit();
static void Update();
static void Draw();

};
</code>```

main.cpp

```<code>#include "main.h"
#include "manager.h"

...

CManager::Init(); //error here

...

CManager::Update(); //error here

CManager::Draw(); //and here
</code>```

But name followed by :: is already a class. Why does it show me an error?

答:
It seems like you want to call your functions, didn't you?
If I'm right, then you need first define your functions, before you can call them.

```<code>class CManager
{

public:
    static void Init();
    static void Uninit();
    static void Update();
    static void Draw();

};
</code>```

Here you only declared them.

You have to define them, either inside your class:

```<code>class CManager
{

public:
    static void Init()
    {
        //Do something...
    }
    static void Uninit()
    {
        //...
    }
    static void Update()
    {
        //...
    }
    static void Draw()
    {
        //...
    }

};
</code>```

... or outside your class:

```<code>void CManager::Init()
{
    //Do something...
}
//and so on...
</code>```

Body:
I dont understand what's wrong here

manager.h

#pragma once
class CManager
{

public:
static void Init();
static void Uninit();
static void Update();
static void Draw();

};

main.cpp

#include "main.h"
#include "manager.h"

...

CManager::Init(); //error here

...

CManager::Update(); //error here

CManager::Draw(); //and here

But name followed by :: is already a class. Why does it show me an error?

Body:
It seems like you want to call your functions, didn't you?
If I'm right, then you need first define your functions, before you can call them.

class CManager
{

public:
    static void Init();
    static void Uninit();
    static void Update();
    static void Draw();

};

Here you only declared them.

You have to define them, either inside your class:

class CManager
{

public:
    static void Init()
    {
        //Do something...
    }
    static void Uninit()
    {
        //...
    }
    static void Update()
    {
        //...
    }
    static void Draw()
    {
        //...
    }

};

... or outside your class:

void CManager::Init()
{
    //Do something...
}
//and so on...


问:
RabbitMQ + .NET C#: published message is never consumed in the same program, why?
I tried to publish and subscribe to the same queue within the same program, but nothing is ever consumed, am I missing out something?

The code:

using System;
using System.Text;

using RabbitMQ.Client;
using RabbitMQ.Client.Events;

namespace CSharpPlayground
{
    public static class Program
    {
        public static void Main()
        {
            const string queueName = "hello";
            var factory = new ConnectionFactory { HostName = "localhost" };
            using var connection = factory.CreateConnection();
            using var queueDeclareChannel = connection.CreateModel();

            queueDeclareChannel.QueueDeclare(
                queue: queueName,
                durable: false,
                exclusive: false,
                autoDelete: false,
                arguments: null);

            using var consumerChannel = connection.CreateModel();
            var consumer = new AsyncEventingBasicConsumer(consumerChannel);
            consumer.Received += async (sender, eventArgs) =>
            {
                var receivedBody = eventArgs.Body;
                var receivedMessage = Encoding.UTF8.GetString(receivedBody.ToArray());
                Console.WriteLine($"[x] Received {receivedMessage}");
            };
            consumerChannel.BasicConsume(
                queue: queueName,
                autoAck: true,
                consumer: consumer);

            const string messageToSend = "Hello World!";
            var bodyToSend = new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes(messageToSend));
            var publishChannel = connection.CreateModel();
            var basicProperties = publishChannel.CreateBasicProperties();
            queueDeclareChannel.BasicPublish(
                exchange: "",
                routingKey: queueName,
                mandatory: false,
                basicProperties: basicProperties,
                body: bodyToSend);
            Console.WriteLine($"[x] Sent {messageToSend}");

            Console.ReadKey();
        }
    }
}
```

```[x] Sent Hello World!
```

答:
You have an async consumer, which means you need to tell your ConnectionFactory that you are receiving your messages in async fashion.

Set DispatchConsumersAsync = true inside new ConnectionFactory {}

Body:
I tried to publish and subscribe to the same queue within the same program, but nothing is ever consumed, am I missing out something?

The code:

using System;
using System.Text;

using RabbitMQ.Client;
using RabbitMQ.Client.Events;

namespace CSharpPlayground
{
    public static class Program
    {
        public static void Main()
        {
            const string queueName = "hello";
            var factory = new ConnectionFactory { HostName = "localhost" };
            using var connection = factory.CreateConnection();
            using var queueDeclareChannel = connection.CreateModel();

            queueDeclareChannel.QueueDeclare(
                queue: queueName,
                durable: false,
                exclusive: false,
                autoDelete: false,
                arguments: null);

            using var consumerChannel = connection.CreateModel();
            var consumer = new AsyncEventingBasicConsumer(consumerChannel);
            consumer.Received += async (sender, eventArgs) =>
            {
                var receivedBody = eventArgs.Body;
                var receivedMessage = Encoding.UTF8.GetString(receivedBody.ToArray());
                Console.WriteLine($"[x] Received {receivedMessage}");
            };
            consumerChannel.BasicConsume(
                queue: queueName,
                autoAck: true,
                consumer: consumer);

            const string messageToSend = "Hello World!";
            var bodyToSend = new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes(messageToSend));
            var publishChannel = connection.CreateModel();
            var basicProperties = publishChannel.CreateBasicProperties();
            queueDeclareChannel.BasicPublish(
                exchange: "",
                routingKey: queueName,
                mandatory: false,
                basicProperties: basicProperties,
                body: bodyToSend);
            Console.WriteLine($"[x] Sent {messageToSend}");

            Console.ReadKey();
        }
    }
}

[x] Sent Hello World!


问:
Building Opencv4.3 Android shared libs error
I'm trying to compile Opencv4.3 to crosscompile with Android but if I user "DBUILD_SHARED_LIBS=ON" I got an error when running make command.

Command:

```<code>~/Android/Sdk/cmake/3.6.4111459/bin/cmake .. -DANDROID_ABI=arm64-v8a -DANDROID_NATIVE_API_LEVEL=23 -DANDROID_ARM_NEON=ON -DANDROID_TOOLCHAIN=clang -DCMAKE_TOOLCHAIN_FILE=/home/<UserName>/Android/Sdk/ndk-bundle/build/cmake/android.toolchain.cmake -DANDROID_NDK=/home/<UserName>/Android/Sdk/ndk-bundle -DANDROID_SDK=/home/<UserName>/Android/Sdk -DCMAKE_BUILD_TYPE=Release -DBUILD_ANDROID_PROJECTS=OFF -DWITH_OPENCL=ON -DWITH_TBB=ON -DENABLE_NEON=ON -DBUILD_TESTS=OFF -DBUILD_PERF_TESTS=OFF -DOPENCV_EXTRA_MODULES_PATH=/home/<UserName>/Transferências/Opencv4.3/opencv_contrib-4.3.0/modules -DINSTALL_ANDROID_EXAMPLES=OFF -DANDROID_EXAMPLES_WITH_LIBS=OFF -DBUILD_EXAMPLES=OFF -DBUILD_DOCS=OFF -DWITH_IPP=ON -DANDROID_STL=c++_shared -DBUILD_SHARED_LIBS=ON -DBUILD_ANDROID_EXAMPLES=OFF -DANDROID_SDK_TARGET=21 -DBUILD_ZLIB=ON
</code>```

Error:

```<code>[ 57%] Built target opencv_xphoto
[ 57%] Linking CXX shared library ../../lib/arm64-v8a/libopencv_dnn.so
../../3rdparty/lib/arm64-v8a/liblibprotobuf.a(common.cc.o): In function `google::protobuf::internal::DefaultLogHandler(google::protobuf::LogLevel, char const*, int, std::__ndk1::basic_string<char, std::__ndk1::char_traits<char>, std::__ndk1::allocator<char> > const&)':
/home/filipe/Transferências/Opencv4.3/opencv-4.3.0/3rdparty/protobuf/src/google/protobuf/stubs/common.cc:142: undefined reference to `__android_log_write'
/home/filipe/Transferências/Opencv4.3/opencv-4.3.0/3rdparty/protobuf/src/google/protobuf/stubs/common.cc:150: undefined reference to `__android_log_write'
clang++: error: linker command failed with exit code 1 (use -v to see invocation)
modules/dnn/CMakeFiles/opencv_dnn.dir/build.make:2701: recipe for target 'lib/arm64-v8a/libopencv_dnn.so' failed
make[2]: *** [lib/arm64-v8a/libopencv_dnn.so] Error 1
CMakeFiles/Makefile2:3591: recipe for target 'modules/dnn/CMakeFiles/opencv_dnn.dir/all' failed
make[1]: *** [modules/dnn/CMakeFiles/opencv_dnn.dir/all] Error 2
Makefile:160: recipe for target 'all' failed
make: *** [all] Error 2
</code>```

If I use DBUILD_SHARED_LIBS=OFF this compile fine.
What can I do?
Any ideas?

Thanks

答:
Try to add "-D ENABLE_PRECOMPILED_HEADERS=OFF" option to CMake command to workaround this GCC bug with "#include_next" processing.

Probably there is unsupported system protobuf installation with other compiler flags (c++11) is not used by default in OpenCV).
Try to run with this CMake option: -DBUILD_LIBPROTOBUF_FROM_SOURCES=ON or just disable dnn module (-DBUILD_opencv_dnn=OFF).

Body:
I'm trying to compile Opencv4.3 to crosscompile with Android but if I user "DBUILD_SHARED_LIBS=ON" I got an error when running make command.

Command:

~/Android/Sdk/cmake/3.6.4111459/bin/cmake .. -DANDROID_ABI=arm64-v8a -DANDROID_NATIVE_API_LEVEL=23 -DANDROID_ARM_NEON=ON -DANDROID_TOOLCHAIN=clang -DCMAKE_TOOLCHAIN_FILE=/home/<UserName>/Android/Sdk/ndk-bundle/build/cmake/android.toolchain.cmake -DANDROID_NDK=/home/<UserName>/Android/Sdk/ndk-bundle -DANDROID_SDK=/home/<UserName>/Android/Sdk -DCMAKE_BUILD_TYPE=Release -DBUILD_ANDROID_PROJECTS=OFF -DWITH_OPENCL=ON -DWITH_TBB=ON -DENABLE_NEON=ON -DBUILD_TESTS=OFF -DBUILD_PERF_TESTS=OFF -DOPENCV_EXTRA_MODULES_PATH=/home/<UserName>/Transferências/Opencv4.3/opencv_contrib-4.3.0/modules -DINSTALL_ANDROID_EXAMPLES=OFF -DANDROID_EXAMPLES_WITH_LIBS=OFF -DBUILD_EXAMPLES=OFF -DBUILD_DOCS=OFF -DWITH_IPP=ON -DANDROID_STL=c++_shared -DBUILD_SHARED_LIBS=ON -DBUILD_ANDROID_EXAMPLES=OFF -DANDROID_SDK_TARGET=21 -DBUILD_ZLIB=ON

Error:

[ 57%] Built target opencv_xphoto
[ 57%] Linking CXX shared library ../../lib/arm64-v8a/libopencv_dnn.so
../../3rdparty/lib/arm64-v8a/liblibprotobuf.a(common.cc.o): In function `google::protobuf::internal::DefaultLogHandler(google::protobuf::LogLevel, char const*, int, std::__ndk1::basic_string<char, std::__ndk1::char_traits<char>, std::__ndk1::allocator<char> > const&)':
/home/filipe/Transferências/Opencv4.3/opencv-4.3.0/3rdparty/protobuf/src/google/protobuf/stubs/common.cc:142: undefined reference to `__android_log_write'
/home/filipe/Transferências/Opencv4.3/opencv-4.3.0/3rdparty/protobuf/src/google/protobuf/stubs/common.cc:150: undefined reference to `__android_log_write'
clang++: error: linker command failed with exit code 1 (use -v to see invocation)
modules/dnn/CMakeFiles/opencv_dnn.dir/build.make:2701: recipe for target 'lib/arm64-v8a/libopencv_dnn.so' failed
make[2]: *** [lib/arm64-v8a/libopencv_dnn.so] Error 1
CMakeFiles/Makefile2:3591: recipe for target 'modules/dnn/CMakeFiles/opencv_dnn.dir/all' failed
make[1]: *** [modules/dnn/CMakeFiles/opencv_dnn.dir/all] Error 2
Makefile:160: recipe for target 'all' failed
make: *** [all] Error 2

If I use DBUILD_SHARED_LIBS=OFF this compile fine.
What can I do?
Any ideas?

Thanks


问:
Trie implementation using python - charToIndex
I'm trying to refer the Trie implementation python code in link
https://www.geeksforgeeks.org/trie-insert-and-search/

i'd a question regarding the following private method :

```<code>def _charToIndex(self,ch):
        # private helper function
        # Converts key current character into index
        # use only 'a' through 'z' and lower case

        return ord(ch)-ord('a')
</code>```

How is this helping to get the index of the character i.e. by converting the character ch to Unicode,  subtracting from it - Unicode value of 'a'

pls help clarify.
thanks!

答: I like the previous answer, but that's how it works, not why you do it. I think the intention is to use a list data structure, with 26 slots, to contain each node's child nodes. The function charToIndex converts an alpha to an int from 0 to 25 (hopefully), and you can check to see whether that child node exists or not, during add or search functions. It does beat using a list and possibly having to iterate through the whole list in order to find the one you want. It also may or may not beat a hashmap lookup for a child node, but the time difference would be minimal, I think. The list may speed up add and search functions, but not traversals... you still have to test all 26 child nodes during a traversal!</p>

Body:
I'm trying to refer the Trie implementation python code in link
https://www.geeksforgeeks.org/trie-insert-and-search/

i'd a question regarding the following private method :

def _charToIndex(self,ch):
        # private helper function
        # Converts key current character into index
        # use only 'a' through 'z' and lower case

        return ord(ch)-ord('a')

How is this helping to get the index of the character i.e. by converting the character ch to Unicode,  subtracting from it - Unicode value of 'a'

pls help clarify.
thanks!


问:
How can I implement this more efficiently
So I have a function (I'm writing this in a pseudo-functional language, I hope its clear):

```<code>dampen (lr : Num, x : Num) = x + lr*(1-x)
</code>```

And I wish to apply this n times to a value x.  I could implement it recursively:

```<code>dampenN (0, lr, x) = dampen(lr, x)
dampenN (n, lr, x) = dampenN(n-1, lr, dampen(x))
</code>```

But there must be a way I can do it mathematically without resorting to an iterative procedure (recursive, or a loop).

Unfortunately my algebra skills are rusty beyond belief, can anyone help?

答:
Actually, MarkusQ's post has an error.  The correct formula is:

```
x * (1-lr)^n + lr * ( (1-lr)^(n-1) + (1-lr)^n-2 + ... + (1-lr) + 1 )
= x * (1-lr)^n + lr * ( 1 - (1-lr)^n )/(1 - (1-lr))
= x * (1-lr)^n + (lr/lr) * (1 - (1-lr)^n)
= (x-1) * (1-lr)^n + 1
```

Also, note that "n" is the number of times you apply the function.  In your functional pseudocode above, the "n=0" case applies the function once, not zero times;  to match the above formula, it would have to go:

```
dampenN (0, lr, x) = x
dampenN (n, lr, x) = dampenN(n-1, lr, dampen(x))
```

OwnerDisplayName: sanity

ContentLicense: CC BY-SA 2.5

Body:
So I have a function (I'm writing this in a pseudo-functional language, I hope its clear):

dampen (lr : Num, x : Num) = x + lr*(1-x)

And I wish to apply this n times to a value x.  I could implement it recursively:

dampenN (0, lr, x) = dampen(lr, x)
dampenN (n, lr, x) = dampenN(n-1, lr, dampen(x))

But there must be a way I can do it mathematically without resorting to an iterative procedure (recursive, or a loop).

Unfortunately my algebra skills are rusty beyond belief, can anyone help?

Body:
Actually, MarkusQ's post has an error.  The correct formula is:

x * (1-lr)^n + lr * ( (1-lr)^(n-1) + (1-lr)^n-2 + ... + (1-lr) + 1 )
= x * (1-lr)^n + lr * ( 1 - (1-lr)^n )/(1 - (1-lr))
= x * (1-lr)^n + (lr/lr) * (1 - (1-lr)^n)
= (x-1) * (1-lr)^n + 1

Also, note that "n" is the number of times you apply the function.  In your functional pseudocode above, the "n=0" case applies the function once, not zero times;  to match the above formula, it would have to go:

dampenN (0, lr, x) = x
dampenN (n, lr, x) = dampenN(n-1, lr, dampen(x))

OwnerDisplayName: comingstorm


问:
How to share same Visual Studio project between different solutions? Different app.config and setttings.settings
The title doesn't entirely describe the actual question, since I was trying to fit a succinct enough description into a one-liner.

I have a C# project I want to share between two different solutions (.sln). The project is an application with a Main method. It requires use of settings.settings and app.config. Each of the two solutions requires  a reference to the same C# project, but for each solution, the app.config and settings.settings need to be specific to their solutions. So if project C is shared between solutions A and B, A includes C where C has an app.config specific to A, and B includes the same exact C project, but C has app.config specific to C.  Is there a way to do this? I'm trying to avoid having to copy the same project (i.e. C) to two different locations, because if I update that project in one solution, then I have to make the same changes in another solution.

Thanks

答: Maybe you can use one of the Open...() methods in ConfigurationManager to achieve this. Otherwise, the following hack could work (except that you need to duplicate the entire App.config file): Create a minimal console app D1 in A and D2 in B, and call C's main() method from here, and use D1 and D2 as the startup projects. Now, the App.config of D1 and D2 will be used in stead of C's App.config.

ContentLicense: CC BY-SA 3.0


问:
How can I run a function from a script in command line?
I have a script that has some functions.

Can I run one of the function directly from command line?

Something like this?

```<code>myScript.sh func()
</code>```

答:
Solved post but I'd like to mention my preferred solution. Namely, define a generic one-liner script eval_func.sh:

```<code>#!/bin/bash
source $1 && shift && "@a"
</code>```

Then call any function within any script via:

```<code>./eval_func.sh <any script> <any function> <any args>...
</code>```

An issue I ran into with the accepted solution is that when sourcing my function-containing script within another script, the arguments of the latter would be evaluated by the former, causing an error.

Body:
I have a script that has some functions.

Can I run one of the function directly from command line?

Something like this?

myScript.sh func()

Body:
Solved post but I'd like to mention my preferred solution. Namely, define a generic one-liner script eval_func.sh:

#!/bin/bash
source $1 && shift && "@a"

Then call any function within any script via:

./eval_func.sh <any script> <any function> <any args>...

An issue I ran into with the accepted solution is that when sourcing my function-containing script within another script, the arguments of the latter would be evaluated by the former, causing an error.


问:
"UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions"
I'm trying to code a bot that when a user joins the server it adds him the role "Banda canina", I tried to give him an admin role, but it continues giving this error. This is the code

```<code>bot.on('guildMemberAdd', member => {
    let wChannel = member.guild.channels.cache.find(channel => channel.name === botConfig.canale_benvenuto);
    if(!wChannel) return console.log('Canale di log non valido');

    let wRole = member.guild.roles.cache.find(role => role.name === botConfig.ruolo_base);
    if(!wRole) return console.log('Impossibile trovare il ruolo base');

    wChannel.send(`${member.user.username}#${member.user.discriminator} è entrato nel server`);
    member.roles.add(wRole);
});
</code>```

I tried the bot in another test server, and it works, but in the main server it doesn't. Here's the complete error:

```<code>UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions
    at RequestHandler.execute (C:\Users\Pc\Desktop\Bot Gio\node_modules\discord.js\src\rest\RequestHandler.js:170:25)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:8268) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
</code>```

答: Your bot should have the permission to manage roles in that server and also be over the role it's giving to new members.

Body:
I'm trying to code a bot that when a user joins the server it adds him the role "Banda canina", I tried to give him an admin role, but it continues giving this error. This is the code

bot.on('guildMemberAdd', member => {
    let wChannel = member.guild.channels.cache.find(channel => channel.name === botConfig.canale_benvenuto);
    if(!wChannel) return console.log('Canale di log non valido');

    let wRole = member.guild.roles.cache.find(role => role.name === botConfig.ruolo_base);
    if(!wRole) return console.log('Impossibile trovare il ruolo base');

    wChannel.send(`${member.user.username}#${member.user.discriminator} è entrato nel server`);
    member.roles.add(wRole);
});

I tried the bot in another test server, and it works, but in the main server it doesn't. Here's the complete error:

UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions
    at RequestHandler.execute (C:\Users\Pc\Desktop\Bot Gio\node_modules\discord.js\src\rest\RequestHandler.js:170:25)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:8268) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)


问:
How to get all documents from a filter in Elasticsearch?
If I deliver the empty params (see below) I would like to get all documents from Elasticsearch. How can I achieve this?

One solution is that I could write all the existing categories into an array. But I have more than 100 categories and this will not be a good solution.

Can someone please help me? Is it possible to ignore the terms if the array is empty?

```<code>POST _scripts/test{"script": {
"lang": "mustache",
"source": {
  "query": {
    "bool": {
      "must": {
        "match_all": {}
      },
      "filter": {
        "terms": {
          "category": [
            "{{#category}}",
            "{{.}}",
            "{{/category}}"
          ]}}}}}}}
</code>```

If I execute the below query the results will be empty:

```<code>GET poi/_search/template{
"id": "test",
"params": {
    "category" : [""]
}}
</code>```

答:
The best way to achieve this would be to proceed like this with a JSON array:

```<code>POST _scripts/test
{
  "script": {
    "lang": "mustache",
    "source": """
    {
      "query": {
        "bool": {
          "must": {
            "match_all": {}
          },
          "filter": [
            {{#category}}
            {
              "terms": {
                "category": {{#toJson}}category.values{{/toJson}}
              }
            }
            {{/category}}
          ]
        }
      }
    }
    """
  }
}
</code>```

Then you can execute this search template like this:

```<code>GET poi/_search/template
{
  "id": "test",
  "params": {
    "category" : {
      "values": ["cat1", "cat2", "cat3"]
    }
  }
}
</code>```

And if you don't want to specify any categories, like this:

```<code>GET poi/_search/template
{
  "id": "test",
  "params": {
  }
}
</code>```

Body:
If I deliver the empty params (see below) I would like to get all documents from Elasticsearch. How can I achieve this?

One solution is that I could write all the existing categories into an array. But I have more than 100 categories and this will not be a good solution.

Can someone please help me? Is it possible to ignore the terms if the array is empty?

POST _scripts/test{"script": {
"lang": "mustache",
"source": {
  "query": {
    "bool": {
      "must": {
        "match_all": {}
      },
      "filter": {
        "terms": {
          "category": [
            "{{#category}}",
            "{{.}}",
            "{{/category}}"
          ]}}}}}}}

If I execute the below query the results will be empty:

GET poi/_search/template{
"id": "test",
"params": {
    "category" : [""]
}}

Body:
The best way to achieve this would be to proceed like this with a JSON array:

POST _scripts/test
{
  "script": {
    "lang": "mustache",
    "source": """
    {
      "query": {
        "bool": {
          "must": {
            "match_all": {}
          },
          "filter": [
            {{#category}}
            {
              "terms": {
                "category": {{#toJson}}category.values{{/toJson}}
              }
            }
            {{/category}}
          ]
        }
      }
    }
    """
  }
}

Then you can execute this search template like this:

GET poi/_search/template
{
  "id": "test",
  "params": {
    "category" : {
      "values": ["cat1", "cat2", "cat3"]
    }
  }
}

And if you don't want to specify any categories, like this:

GET poi/_search/template
{
  "id": "test",
  "params": {
  }
}


问:
Gracefully stopping an std::thread?
I have a worker std::thread and I want its main loop to check if some other thread tells it to stop looping and exit.

What is a good cross platform way to do this? Does boost provide some event object for it?

Is using just a bool considered thread-safe?

答:
What you could have is a std::mutex that is shared between primary and your worker thread.

Your worker thread can acquire std::mutex::try_lock before commencing any work and release it intermittently . The main thread can lock this mutex when it wants your worker thread to shut down. Your worker thread can detect this using try_lock and exit

Title: Gracefully stopping an std::thread?


问:
.gitignore for Visual Studio Projects and Solutions
Which files should I include in .gitignore when using Git in conjunction with Visual Studio Solutions (.sln) and Projects?

答:
You can create or edit your .gitignore file for your repo by going to the Settings view in Team Explorer, then selecting Repository Settings. Select Edit for your .gitignore.

It automatically creates filters that will ignore all the VS specific build directories etc.

More info have a look here.


问:
How to use a regular expression in querySelectorAll?
On a page I'm doing I will be ending up with custom link elements like this:

<link rel="multiply" type="service/math" src="path/to/service">
<link rel="substract" type="service/math" src="path/to/service">
...
```
<p>I'm trying to use <code>querySelectorAll</code> to retrieve all link elements with a type <code>service/...</code> specified and am getting nowhere.</p>
<p>Currently I'm selecting this:</p>
<pre class="lang-js prettyprint-override"><code>root.querySelectorAll('link');
</code>```

which gives me all <link> elements when I only want the ones with type service/.*

Questions:

Can I add a regex to a QSA selector? If so, how to do it?

答:
I know this is 7 years old, but this is how you do it (for attribute values):

function DOMRegex(regex) {
    let output = [];
    for (let i of document.querySelectorAll('*')) {
        if (regex.test(i.type)) { // or whatever attribute you want to search
            output.push(i);
        }
    }
    return output;
}
console.log(DOMRegex(/^service\//)); // your regex here```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="multiply" type="service/math" src="path/to/service">
<link rel="substract" type="service/math" src="path/to/service">
<link rel="test" type="notservice/math" src="path/to/notservice">
<div id="some-other-node"></div></code>```

To search all element attributes, you can use this:

function DOMRegex(regex) {
    let output = [];
    for (let i of document.querySelectorAll('*')) {
        for (let j of i.attributes) {
            if (regex.test(j.value)) {
                output.push({
                    'element': i,
                    'attribute name': j.name,
                    'attribute value': j.value
                });
            }
        }
    }
    return output;
}
console.log(DOMRegex(/(?<!t)service/)); // your regex here```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="multiply" type="service/math" src="path/to/service">
<link rel="substract" type="service/math" src="path/to/service">
<link rel="test" type="notservice/math" src="path/to/notservice">
<div id="some-other-node"></div></code>```

I put it in a nice object layout for you.

Body:
On a page I'm doing I will be ending up with custom link elements like this:

<link rel="multiply" type="service/math" src="path/to/service">
<link rel="substract" type="service/math" src="path/to/service">
...

I'm trying to use querySelectorAll to retrieve all link elements with a type service/... specified and am getting nowhere.

Currently I'm selecting this:

root.querySelectorAll('link');

which gives me all <link> elements when I only want the ones with type service/.*

Questions:

Can I add a regex to a QSA selector? If so, how to do it?

Body:
I know this is 7 years old, but this is how you do it (for attribute values):

function DOMRegex(regex) {
    let output = [];
    for (let i of document.querySelectorAll('*')) {
        if (regex.test(i.type)) { // or whatever attribute you want to search
            output.push(i);
        }
    }
    return output;
}
console.log(DOMRegex(/^service\//)); // your regex here

<link rel="multiply" type="service/math" src="path/to/service">
<link rel="substract" type="service/math" src="path/to/service">
<link rel="test" type="notservice/math" src="path/to/notservice">
<div id="some-other-node"></div>

To search all element attributes, you can use this:

function DOMRegex(regex) {
    let output = [];
    for (let i of document.querySelectorAll('*')) {
        for (let j of i.attributes) {
            if (regex.test(j.value)) {
                output.push({
                    'element': i,
                    'attribute name': j.name,
                    'attribute value': j.value
                });
            }
        }
    }
    return output;
}
console.log(DOMRegex(/(?<!t)service/)); // your regex here

<link rel="multiply" type="service/math" src="path/to/service">
<link rel="substract" type="service/math" src="path/to/service">
<link rel="test" type="notservice/math" src="path/to/notservice">
<div id="some-other-node"></div>

I put it in a nice object layout for you.


问:
Iphone - Assigning properties and instance variables
Well, i am still confused about objective c properties and instance variables.
I create a LocationManager-object in my viewDidLoad. On the one hand the LocationMan is just an instance variable on the other hand it is declared as a property. Have a look at the examples:

First example:

Header:

```<code>CLLocationManager* _locationMan;
</code>```

Implementation:

```<code>CLLocationManager* theManager = [[[CLLocationManager alloc] init] autorelease];
_locationMan = theManager;
_locationMan.delegate = self;
</code>```

Second Example

Header:

```<code>CLLocationManager* _locationMan;
@property (retain, nonatomic) CLLocationManager* locationMan;
</code>```

Implementation:

```<code>self.locationMan = [[[CLLocationManager alloc] init] autorelease];
self.locationMan.delegate = self;
</code>```

Whats the difference between those examples except of that the second one is working and the first one not? What's going on there with the memory management?

答:
The problem you have in your first example:

```<code>CLLocationManager* theManager = [[[CLLocationManager alloc] init] autorelease];
</code>```

is caused by the use of autorelease. autorelease can be seen as meaning: at some point in the near future, release automatically this object. Given the way autorelease is implemented, by means of a release pool, this usually happens the next time the control flow return to the main loop and the release pool is emptied.

So, in your first case, you are creating the object and storing it in your ivar; but soon it will be released, and since you don't have explicitly retained it anywhere else, it will end up being deallocated. When you access it after that, you get the error. If you had not used autorelease, everything would have worked correctly:

```<code>CLLocationManager* theManager = [[CLLocationManager alloc] init]; //-- this is correct
_locationMan = theManager;  //-- because you assign directly to the ivar
</code>```

In your second example, creation is just the same, meaning, the object will also be flagged for autorelease. But, in this case, you assign it to a property which has got the retain modifier. This means that the object will be automatically retained when assigning to the property. So, when the autorelease is actually done (when you get back to the main look, roughly), your object will have already had its retain count incremented by 1; then auto releasing it will not make its retain count go to 0, and the object will not be deallocated.

What you have to know clearly is that:

alloc will set the retain count to 1;

retain properties will increment the retain count when assigning to them;

autorelease is like a delayed release, so that in the mean time (before the release is actually done, which means in the rest of your method and callers up  to the main loop) you can use the object safely and thereafter it will be released.

Body:
Well, i am still confused about objective c properties and instance variables.
I create a LocationManager-object in my viewDidLoad. On the one hand the LocationMan is just an instance variable on the other hand it is declared as a property. Have a look at the examples:

First example:

Header:

CLLocationManager* _locationMan;

Implementation:

CLLocationManager* theManager = [[[CLLocationManager alloc] init] autorelease];
_locationMan = theManager;
_locationMan.delegate = self;

Second Example

Header:

CLLocationManager* _locationMan;
@property (retain, nonatomic) CLLocationManager* locationMan;

Implementation:

self.locationMan = [[[CLLocationManager alloc] init] autorelease];
self.locationMan.delegate = self;

Whats the difference between those examples except of that the second one is working and the first one not? What's going on there with the memory management?

Body:
The problem you have in your first example:

CLLocationManager* theManager = [[[CLLocationManager alloc] init] autorelease];

is caused by the use of autorelease. autorelease can be seen as meaning: at some point in the near future, release automatically this object. Given the way autorelease is implemented, by means of a release pool, this usually happens the next time the control flow return to the main loop and the release pool is emptied.

So, in your first case, you are creating the object and storing it in your ivar; but soon it will be released, and since you don't have explicitly retained it anywhere else, it will end up being deallocated. When you access it after that, you get the error. If you had not used autorelease, everything would have worked correctly:

CLLocationManager* theManager = [[CLLocationManager alloc] init]; //-- this is correct
_locationMan = theManager;  //-- because you assign directly to the ivar

In your second example, creation is just the same, meaning, the object will also be flagged for autorelease. But, in this case, you assign it to a property which has got the retain modifier. This means that the object will be automatically retained when assigning to the property. So, when the autorelease is actually done (when you get back to the main look, roughly), your object will have already had its retain count incremented by 1; then auto releasing it will not make its retain count go to 0, and the object will not be deallocated.

What you have to know clearly is that:

alloc will set the retain count to 1;

retain properties will increment the retain count when assigning to them;

autorelease is like a delayed release, so that in the mean time (before the release is actually done, which means in the rest of your method and callers up  to the main loop) you can use the object safely and thereafter it will be released.