问:
To develop the ui on Spring Boot Admin Server
I would like to do some personalized development on spring-boot-admin-server-ui.According to README prompt,my configuration file is as follows:

```<code>spring:
 boot:
  admin:
   ui:
    cache:
     no-cache: true
    resource-locations: file://D:/WorkSpace/UseIDEA/GIT/ai-server/springbootadmin/spring-boot-admin-server-ui/target/dist/
    template-location: file://D:/WorkSpace/UseIDEA/GIT/ai-server/springbootadmin/spring-boot-admin-server-ui/target/dist/
    cache-templates: false
</code>```

I'm sure the file path is correct and the execution of the "npm run watch" was also successful.
But always has an error as follows:

```<code>2020-02-17 21:40:41.249 ERROR 13216 --- [nio-8766-exec-8] org.thymeleaf.TemplateEngine             : [THYMELEAF][http-nio-8766-exec-8] Exception processing template "login": An error happened during template parsing (template: "URL [file://D:/WorkSpace/UseIDEA/GIT/ai-[...]i/target/dist/login.html]")

org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "URL [file://D:/WorkSpace/UseIDEA/GIT/ai-[...]i/target/dist/login.html]")
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:235) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parseStandalone(AbstractMarkupTemplateParser.java:100) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:666) ~[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.spring5.view.ThymeleafView.renderFragment(ThymeleafView.java:354) [thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring5.view.ThymeleafView.render(ThymeleafView.java:187) [thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1325) [spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1069) [spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1008) [spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) [spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) [spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866) [spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) [spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at com.alibaba.druid.support.http.WebStatFilter.doFilter(WebStatFilter.java:123) [druid-1.1.10.jar:1.1.10]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter.doFilterInternal(HttpTraceFilter.java:90) [spring-boot-actuator-2.0.4.RELEASE.jar:2.0.4.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:158) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:155) [spring-boot-actuator-2.0.4.RELEASE.jar:2.0.4.RELEASE]
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:123) [spring-boot-actuator-2.0.4.RELEASE.jar:2.0.4.RELEASE]
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:108) [spring-boot-actuator-2.0.4.RELEASE.jar:2.0.4.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_212]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_212]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_212]
Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method) ~[na:1.8.0_212]
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85) ~[na:1.8.0_212]
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) ~[na:1.8.0_212]
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[na:1.8.0_212]
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[na:1.8.0_212]
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) ~[na:1.8.0_212]
    at java.net.Socket.connect(Socket.java:589) ~[na:1.8.0_212]
    at sun.net.ftp.impl.FtpClient.doConnect(FtpClient.java:962) ~[na:1.8.0_212]
    at sun.net.ftp.impl.FtpClient.tryConnect(FtpClient.java:924) ~[na:1.8.0_212]
    at sun.net.ftp.impl.FtpClient.connect(FtpClient.java:1019) ~[na:1.8.0_212]
    at sun.net.ftp.impl.FtpClient.connect(FtpClient.java:1005) ~[na:1.8.0_212]
    at sun.net.www.protocol.ftp.FtpURLConnection.connect(FtpURLConnection.java:294) ~[na:1.8.0_212]
    at sun.net.www.protocol.ftp.FtpURLConnection.getInputStream(FtpURLConnection.java:400) ~[na:1.8.0_212]
    at org.springframework.core.io.UrlResource.getInputStream(UrlResource.java:171) ~[spring-core-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.thymeleaf.spring5.templateresource.SpringResourceTemplateResource.reader(SpringResourceTemplateResource.java:103) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:223) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    ... 100 common frames omitted

</code>```

Please give me some help,Thank you!

答:
Your resource-locations and  template-location have absolute path, but your files should lie in resources folder, then they're packed to your jar. The props should look like

(I'm not sure if setting this props should work for customizing admin UI, I only help you handle resources.)

resource-locations: /static/

template-location:  /templates/

the folder structure like this

Body:
I would like to do some personalized development on spring-boot-admin-server-ui.According to README prompt,my configuration file is as follows:

spring:
 boot:
  admin:
   ui:
    cache:
     no-cache: true
    resource-locations: file://D:/WorkSpace/UseIDEA/GIT/ai-server/springbootadmin/spring-boot-admin-server-ui/target/dist/
    template-location: file://D:/WorkSpace/UseIDEA/GIT/ai-server/springbootadmin/spring-boot-admin-server-ui/target/dist/
    cache-templates: false

I'm sure the file path is correct and the execution of the "npm run watch" was also successful.
But always has an error as follows:

2020-02-17 21:40:41.249 ERROR 13216 --- [nio-8766-exec-8] org.thymeleaf.TemplateEngine             : [THYMELEAF][http-nio-8766-exec-8] Exception processing template "login": An error happened during template parsing (template: "URL [file://D:/WorkSpace/UseIDEA/GIT/ai-[...]i/target/dist/login.html]")

org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "URL [file://D:/WorkSpace/UseIDEA/GIT/ai-[...]i/target/dist/login.html]")
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:235) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parseStandalone(AbstractMarkupTemplateParser.java:100) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:666) ~[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.spring5.view.ThymeleafView.renderFragment(ThymeleafView.java:354) [thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring5.view.ThymeleafView.render(ThymeleafView.java:187) [thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1325) [spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1069) [spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1008) [spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) [spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) [spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866) [spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) [spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at com.alibaba.druid.support.http.WebStatFilter.doFilter(WebStatFilter.java:123) [druid-1.1.10.jar:1.1.10]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter.doFilterInternal(HttpTraceFilter.java:90) [spring-boot-actuator-2.0.4.RELEASE.jar:2.0.4.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:158) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) [spring-security-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:155) [spring-boot-actuator-2.0.4.RELEASE.jar:2.0.4.RELEASE]
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:123) [spring-boot-actuator-2.0.4.RELEASE.jar:2.0.4.RELEASE]
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:108) [spring-boot-actuator-2.0.4.RELEASE.jar:2.0.4.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_212]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_212]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_212]
Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method) ~[na:1.8.0_212]
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85) ~[na:1.8.0_212]
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) ~[na:1.8.0_212]
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[na:1.8.0_212]
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[na:1.8.0_212]
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) ~[na:1.8.0_212]
    at java.net.Socket.connect(Socket.java:589) ~[na:1.8.0_212]
    at sun.net.ftp.impl.FtpClient.doConnect(FtpClient.java:962) ~[na:1.8.0_212]
    at sun.net.ftp.impl.FtpClient.tryConnect(FtpClient.java:924) ~[na:1.8.0_212]
    at sun.net.ftp.impl.FtpClient.connect(FtpClient.java:1019) ~[na:1.8.0_212]
    at sun.net.ftp.impl.FtpClient.connect(FtpClient.java:1005) ~[na:1.8.0_212]
    at sun.net.www.protocol.ftp.FtpURLConnection.connect(FtpURLConnection.java:294) ~[na:1.8.0_212]
    at sun.net.www.protocol.ftp.FtpURLConnection.getInputStream(FtpURLConnection.java:400) ~[na:1.8.0_212]
    at org.springframework.core.io.UrlResource.getInputStream(UrlResource.java:171) ~[spring-core-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.thymeleaf.spring5.templateresource.SpringResourceTemplateResource.reader(SpringResourceTemplateResource.java:103) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:223) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    ... 100 common frames omitted

Please give me some help,Thank you!


来源: stackexchange

问:
Query select elements everytime partial is loaded by Vanilla Javascript in Rails
I have a partial inside a partial which has radio buttons or check boxes. What I want to do is to get the radio button or checkboxes which are clicked. Now initially when the page is loaded I am able to get the buttons but when I go to the next partial I am not able to get the new buttons. How can I get the buttons of the new partial everytime some button is clicked in a separate js. If I use onclick function inline with radio button or checkbox then the function is called correctly but I want to get the present displayed elements in a separate js file.

I tried to use window.addEventListener('change'). If I use this then the function is not called on first click but in the subsequent clicks it calls that many number of times i.e., on second click the function is called once, on third click the function is called twice and so on.

```<code>// window.addEventListener('change', () => {
window.addEventListener('DOMContentLoaded', () => {
  if (document.querySelectorAll('[name="question[answer_id]"]').length !== 0) {
    document.querySelectorAll('[name="question[answer_id]"]').forEach((questionAnswerButton) => {
      questionAnswerButton.addEventListener('click', (event) => {
        console.log(event);
        fetchCall(event.target.value);
      });
    });
  }
});

</code>```

radio_button_partial.html.erb

```<code><%= radio_button_tag 'question[answer_id]',
                                  answer.id,
                                  (user_answer == answer.id),
                                  {
                                    class: 'answer_opt',
                                    // onclick: fetchCall("<%= answer.id %>")
                                  } %>
</code>```

Here if I uncomment the onclick function then I get the desired functionality. But what should I change in this that I get the present displayed radio buttons from the separate js file?

答:
Instead of attaching a listener directly to the elements you want to use event bubbling:

```<code>document.addEventListener('click', (event) => {
  if (event.target.matches('[name="question[answer_id]"]')) {
    console.log(event);
    fetchCall(event.target.value);
  }
});
</code>```

When an event is fired it up bubbles up the DOM until a handler is found. Unlike attaching event handlers directly to the elements this is idempotent and the handler will work for elements dynamically inserted into the page. Its also compatible with turbolinks.

This code should not be placed in a script tag or .js.erb abomination as it will add a handler every time the code is executed. Put it in the assets pipeline.

If fetchCall does an ajax call you will want to use a debouncing technique such as disabling the input and re-enabling it when the promise is resolved.

```<code>document.addEventListener('click', (event) => {
  if (event.target.matches('[name="question[answer_id]"]')) {
    console.log(event);
    // Todo refactor fetchCall so that it returns a promise
    let promise = fetchCall(event.target.value);
    event.target.disabled = true;
    promise.then((successMessage) => {
      event.target.disabled = false;
    });
  }
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a partial inside a partial which has radio buttons or check boxes. What I want to do is to get the radio button or checkboxes which are clicked. Now initially when the page is loaded I am able to get the buttons but when I go to the next partial I am not able to get the new buttons. How can I get the buttons of the new partial everytime some button is clicked in a separate js. If I use onclick function inline with radio button or checkbox then the function is called correctly but I want to get the present displayed elements in a separate js file.

I tried to use window.addEventListener('change'). If I use this then the function is not called on first click but in the subsequent clicks it calls that many number of times i.e., on second click the function is called once, on third click the function is called twice and so on.

// window.addEventListener('change', () => {
window.addEventListener('DOMContentLoaded', () => {
  if (document.querySelectorAll('[name="question[answer_id]"]').length !== 0) {
    document.querySelectorAll('[name="question[answer_id]"]').forEach((questionAnswerButton) => {
      questionAnswerButton.addEventListener('click', (event) => {
        console.log(event);
        fetchCall(event.target.value);
      });
    });
  }
});

radio_button_partial.html.erb

<%= radio_button_tag 'question[answer_id]',
                                  answer.id,
                                  (user_answer == answer.id),
                                  {
                                    class: 'answer_opt',
                                    // onclick: fetchCall("<%= answer.id %>")
                                  } %>

Here if I uncomment the onclick function then I get the desired functionality. But what should I change in this that I get the present displayed radio buttons from the separate js file?

Body:
Instead of attaching a listener directly to the elements you want to use event bubbling:

document.addEventListener('click', (event) => {
  if (event.target.matches('[name="question[answer_id]"]')) {
    console.log(event);
    fetchCall(event.target.value);
  }
});

When an event is fired it up bubbles up the DOM until a handler is found. Unlike attaching event handlers directly to the elements this is idempotent and the handler will work for elements dynamically inserted into the page. Its also compatible with turbolinks.

This code should not be placed in a script tag or .js.erb abomination as it will add a handler every time the code is executed. Put it in the assets pipeline.

If fetchCall does an ajax call you will want to use a debouncing technique such as disabling the input and re-enabling it when the promise is resolved.

document.addEventListener('click', (event) => {
  if (event.target.matches('[name="question[answer_id]"]')) {
    console.log(event);
    // Todo refactor fetchCall so that it returns a promise
    let promise = fetchCall(event.target.value);
    event.target.disabled = true;
    promise.then((successMessage) => {
      event.target.disabled = false;
    });
  }
});


问:
Microsoft.Office.Interop.Excel cells remain null after setting them
I have an application in which I'm trying to write to an Excel file. It doesn't seem to be working.

Here is my code:

```<code>using System;
using System.Drawing;
using Microsoft.Office.Interop.Excel;

namespace Image2Excel {
class Engine {
    public static void go(string imageFilename, string excelFilename = null) {
        //Image img = Image.FromFile(imageFilename);
        Bitmap btm = (Bitmap)Bitmap.FromFile(imageFilename, false);
        Image img = Image.FromFile(imageFilename, false);

        if (btm != null) {
            Color[][] colorArray = new Color[btm.Width][];
            for (int x = 0; x < btm.Width; x++) {
                colorArray[x] = new Color[btm.Height];
                for (int y = 0; y < btm.Height; y++) {
                    colorArray[x][y] = btm.GetPixel(x, y);
                }
            }

            var excel = new Microsoft.Office.Interop.Excel.Application();
            var workbook = excel.Workbooks.Add(Type.Missing);
            var worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.ActiveSheet;
            worksheet.Name = "sheet1";

            worksheet.Cells[1,1] = "top left";
            worksheet.Cells[1,2] = "top right";
            worksheet.Cells[2,1] = "bottom left";
            worksheet.Cells[2,2] = "bottom right";

            workbook.SaveAs("temp.xlsx");
            workbook.Close();
            excel.Quit();

            Marshal.ReleaseComObject(worksheet);
            Marshal.ReleaseComObject(workbook);
            Marshal.ReleaseComObject(excel);
        }
    }
}
}
</code>```

I'm trying to write some text to the first 4 cells in the spreadsheet. It's not working. When I open the file, I see nothing in the cells.

I do see that the sheet name is set to what I set it to so I know it's writing to the files.

One thing I noticed when I debug is that worksheet.Cells[1,1] is null after I set it. I'm wondering if I need to set the cell to an object before writing to it. But I'm not sure how. I don't seem to be able to do this:

```<code>worksheet.Cells[1,1] = new Microsoft.Office.Interop.Excel.Cell();
</code>```

Hovering over Cells tells me it's a Range object, but I'm not sure how to set it to a range either. I tried this:

```<code>worksheet.Range["A1"].Value = "hello";
worksheet.Range["A1"].Value2 = "hello";
</code>```

...but those don't work either. worksheet.Range remains null just like worksheet.Cells.

How can I make sure worksheet.Cells[1,1] or worksheet.Range["A1"] is set to an object that will take a string value? Thanks.

You can find my application on github: https://github.com/gibran-shah/Image2Excel

I'm using Microsoft.Office.Interop.Excel version 15.0.4795.1000.

I have Excel 2010 installed on my computer.

答:
I haven't tried yours but could you try these methods? it worked for me.

1st method with Worksheets.Cells

```<code>// CREATE EXCEL OBJECTS.
Excel.Application xlApp;

Excel.Workbook xlWB;
Excel.Worksheet xlWS;

xlApp = new Excel.Application();

// Specify the path to the excel file
xlWB= xlApp.Workbooks.Open("path/to/xlFile.xls");

// Choose the sheet you want to open
xlWS = xlWB.Worksheets["Sheet1"];

// Write on the single cell
xlWS.Cells["1", "D"] = "Example";

// Save the change and quit
xlWB.Close(true);
xlApp.Quit();
</code>```

2nd method with Worksheets.get_Range()

```<code>// CREATE EXCEL OBJECTS.
Excel.Application xlApp;

Excel.Workbook xlWB;
Excel.Worksheet xlWS;

xlApp = new Excel.Application();

// Specify the path to the excel file
xlWB= xlApp.Workbooks.Open("path/to/xlFile.xls");

// Choose the sheet you want to open
xlWS = xlWB.Worksheets["Sheet1"];

// Write on the range of cells
xlWS.get_Range["A3", "D5"] = "Example";

// Save the change and quit
xlWB.Close(true);
xlApp.Quit();
</code>```

Body:
I have an application in which I'm trying to write to an Excel file. It doesn't seem to be working.

Here is my code:

using System;
using System.Drawing;
using Microsoft.Office.Interop.Excel;

namespace Image2Excel {
class Engine {
    public static void go(string imageFilename, string excelFilename = null) {
        //Image img = Image.FromFile(imageFilename);
        Bitmap btm = (Bitmap)Bitmap.FromFile(imageFilename, false);
        Image img = Image.FromFile(imageFilename, false);

        if (btm != null) {
            Color[][] colorArray = new Color[btm.Width][];
            for (int x = 0; x < btm.Width; x++) {
                colorArray[x] = new Color[btm.Height];
                for (int y = 0; y < btm.Height; y++) {
                    colorArray[x][y] = btm.GetPixel(x, y);
                }
            }

            var excel = new Microsoft.Office.Interop.Excel.Application();
            var workbook = excel.Workbooks.Add(Type.Missing);
            var worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.ActiveSheet;
            worksheet.Name = "sheet1";

            worksheet.Cells[1,1] = "top left";
            worksheet.Cells[1,2] = "top right";
            worksheet.Cells[2,1] = "bottom left";
            worksheet.Cells[2,2] = "bottom right";

            workbook.SaveAs("temp.xlsx");
            workbook.Close();
            excel.Quit();

            Marshal.ReleaseComObject(worksheet);
            Marshal.ReleaseComObject(workbook);
            Marshal.ReleaseComObject(excel);
        }
    }
}
}

I'm trying to write some text to the first 4 cells in the spreadsheet. It's not working. When I open the file, I see nothing in the cells.

I do see that the sheet name is set to what I set it to so I know it's writing to the files.

One thing I noticed when I debug is that worksheet.Cells[1,1] is null after I set it. I'm wondering if I need to set the cell to an object before writing to it. But I'm not sure how. I don't seem to be able to do this:

worksheet.Cells[1,1] = new Microsoft.Office.Interop.Excel.Cell();

Hovering over Cells tells me it's a Range object, but I'm not sure how to set it to a range either. I tried this:

worksheet.Range["A1"].Value = "hello";
worksheet.Range["A1"].Value2 = "hello";

...but those don't work either. worksheet.Range remains null just like worksheet.Cells.

How can I make sure worksheet.Cells[1,1] or worksheet.Range["A1"] is set to an object that will take a string value? Thanks.

You can find my application on github: https://github.com/gibran-shah/Image2Excel

I'm using Microsoft.Office.Interop.Excel version 15.0.4795.1000.

I have Excel 2010 installed on my computer.

Body:
I haven't tried yours but could you try these methods? it worked for me.

1st method with Worksheets.Cells

// CREATE EXCEL OBJECTS.
Excel.Application xlApp;

Excel.Workbook xlWB;
Excel.Worksheet xlWS;

xlApp = new Excel.Application();

// Specify the path to the excel file
xlWB= xlApp.Workbooks.Open("path/to/xlFile.xls");

// Choose the sheet you want to open
xlWS = xlWB.Worksheets["Sheet1"];

// Write on the single cell
xlWS.Cells["1", "D"] = "Example";

// Save the change and quit
xlWB.Close(true);
xlApp.Quit();

2nd method with Worksheets.get_Range()

// CREATE EXCEL OBJECTS.
Excel.Application xlApp;

Excel.Workbook xlWB;
Excel.Worksheet xlWS;

xlApp = new Excel.Application();

// Specify the path to the excel file
xlWB= xlApp.Workbooks.Open("path/to/xlFile.xls");

// Choose the sheet you want to open
xlWS = xlWB.Worksheets["Sheet1"];

// Write on the range of cells
xlWS.get_Range["A3", "D5"] = "Example";

// Save the change and quit
xlWB.Close(true);
xlApp.Quit();


问:
Facebook demo app fails to build on iOS
iOS beginner here. I'm trying to build the Facebook Demo App but I keep getting the following error:

```<code>Check dependencies

[BEROR]No architectures to compile for (ARCHS=i386, VALID_ARCHS=armv7 armv6).
</code>```

Any idea what causes this?

答:
For whatever reason it seems that your project doesn't have an architecture set. Click on the project name, then on Build Settings, and select the architectures as shown below:

Edited to add

Also ensure the "Valid Architectures" include all three architectures:

ContentLicense: CC BY-SA 3.0

Title: Facebook demo app fails to build on iOS

Body:
iOS beginner here. I'm trying to build the Facebook Demo App but I keep getting the following error:

Check dependencies

[BEROR]No architectures to compile for (ARCHS=i386, VALID_ARCHS=armv7 armv6).

Any idea what causes this?


问:
Get value from Instance in Flutter
I am making a search request on the List with the Provider pattern.

```<code>List<Device> _devices = [
    Device(one: 'Apple', two: 'iphone'),
    Device(one: 'Samsung', two: 'Galaxy')
];
</code>```

And Query is like this

```<code>List<Device> queryQuery(String value) {
return _devices
    .where((device) => device.one.toLowerCase().contains(value.toLowerCase()))
    .toList();
</code>```

the result I expect to get is iphone when I passed the value Apple.

But the result on the screen that I got is [instance of ‘Device’]
when I code like this

```<code>child: Text('${deviceData.getDevice('Apple')}'
</code>```

I do know I should be using some kind of key using two... but I have no idea :-(

答:
You serialized the wrong object.

What you did end-up being similar to:

Text(Device(one: 'Apple', two: 'iphone').toString());
```

<p>But you don't want to do <code>Device.toString()</code>. What you want instead is to pass <code>Device.two</code> to your <code>Text</code>.</p>

<p>As such your end result is:</p>

<pre class="lang-dart prettyprint-override"><code>Text('${chordData.chordExpand('Apple').two}')
</code>```

Title: Get value from Instance in Flutter

Body:
I am making a search request on the List with the Provider pattern.

List<Device> _devices = [
    Device(one: 'Apple', two: 'iphone'),
    Device(one: 'Samsung', two: 'Galaxy')
];

And Query is like this

List<Device> queryQuery(String value) {
return _devices
    .where((device) => device.one.toLowerCase().contains(value.toLowerCase()))
    .toList();

the result I expect to get is iphone when I passed the value Apple.

But the result on the screen that I got is [instance of ‘Device’]
when I code like this

child: Text('${deviceData.getDevice('Apple')}'

I do know I should be using some kind of key using two... but I have no idea :-(

Body:
You serialized the wrong object.

What you did end-up being similar to:

Text(Device(one: 'Apple', two: 'iphone').toString());

But you don't want to do Device.toString(). What you want instead is to pass Device.two to your Text.

As such your end result is:

Text('${chordData.chordExpand('Apple').two}')


问:
How can I add exception for when user inputs a negative number
I'm trying to add an exception to recognise when someone inputs a negative number, and respond with something to say you can only input a positive number

```<code>print('How many cats do you have?')
numCats = input()
try:
    if int(numCats) >=4:
        print('Thats a lot of cats.')
    else:
        print('Thats not that many cats.')
except ValueError:
    print('You did not enter a number.')
</code>```

At the moment it will respond to the user inputting a string instead of an integer but I want it to be able to respond to the user inputting something like -4 by printing 'You cant use negative numbers'.

Totally new to Python, so any advice on how to add this in would be very much appreciated, thank you.

答:
It's just

raise ValueError("you must give a positive number")

Body:
I'm trying to add an exception to recognise when someone inputs a negative number, and respond with something to say you can only input a positive number

print('How many cats do you have?')
numCats = input()
try:
    if int(numCats) >=4:
        print('Thats a lot of cats.')
    else:
        print('Thats not that many cats.')
except ValueError:
    print('You did not enter a number.')

At the moment it will respond to the user inputting a string instead of an integer but I want it to be able to respond to the user inputting something like -4 by printing 'You cant use negative numbers'.

Totally new to Python, so any advice on how to add this in would be very much appreciated, thank you.


问:
Calculate total Amount Paid on Prepare Payments
Good day
Page: AP503000
Build 19.104.0024

I am trying to calculate the Total Amount paid for all recorded in the APAdjust grid on the bottom of the Prepare Payments. This total I want to show on top in the Form area.

DAC

```<code>namespace PX.Objects.AP
{
    public class PayBillsFilterExt : PXCacheExtension<PX.Objects.AP.PayBillsFilter>
    {
        #region UsrTotalAmountForPayment
        [PXDecimal]
        [PXUIField(DisplayName = "Total Amount For Payment")]
        public virtual Decimal? UsrTotalAmountForPayment { get; set; }
        public abstract class usrTotalAmountForPayment :
        PX.Data.BQL.BqlDecimal.Field<usrTotalAmountForPayment> { }
        #endregion
     }
}
</code>```

My first attempt I tried to add an unbound formula to my DAC for the below to work you will also need to add a new class decimal_0

```<code>namespace PX.Objects.AP
{
    public class PayBillsFilterExt : PXCacheExtension<PX.Objects.AP.PayBillsFilter>
    {
        #region UsrTotalAmountForPayment
        [PXDecimal]
        [PXUIField(DisplayName = "Total Amount For Payment")]
        // add this to the DAC
        [PXUnboundFormula(typeof(Where<APAdjust.curyAdjdAmt,Greater<decimal_0>>)
        ,typeof(SumCalc<APAdjust.curyAdjdAmt>))]
        public virtual Decimal? UsrTotalAmountForPayment { get; set; }
        public abstract class usrTotalAmountForPayment :
        PX.Data.BQL.BqlDecimal.Field<usrTotalAmountForPayment> { }
        #endregion

        //Class decimal_0
        public class decimal_0 : Constant<decimal>
        {
            public decimal_0()
            : base(0)
             { }
        }

     }
}
</code>```

I have also tried adding an event to do the calculation:

```<code>namespace PX.Objects.AP
{
  public class APPayBills_Extension : PXGraphExtension<APPayBills>
  {
     #region Event Handlers
     protected void APAdjust_RowInserted(PXCache cache, PXRowInsertedEventArgs e)
     {
        var row = (APAdjust)e.Row;
        PayBillsFilter filter = this.Base.Filter.Current;
        PayBillsFilterExt FilExt = PXCache<PayBillsFilter>.GetExtension<PayBillsFilterExt>(filter);

        if (filter != null)
        {
            FilExt.UsrTotalAmountForPayment += row.CuryAdjdAmt;

        }
      }
   }
 }
</code>```

答:
For accurate results I recommend you sum all the records at the same time.
You can use the DataView.Select method to iterate all records.

```<code>public void PayBillsFilter_UsrTotalAmountForPayment_FieldSelecting(PXCache sender, PXFieldSelectingEventArgs e)
{
    decimal total = 0;

    foreach (APAdjust adjustment in this.Base.APDocumentList.Select())
    {
        total += (adjustment.CuryAdjdAmt != null ? adjustment.CuryAdjdAmt.Value : 0M);
    }

    e.ReturnValue = total;
}
</code>```

Body:
Good day
Page: AP503000
Build 19.104.0024

I am trying to calculate the Total Amount paid for all recorded in the APAdjust grid on the bottom of the Prepare Payments. This total I want to show on top in the Form area.

DAC

namespace PX.Objects.AP
{
    public class PayBillsFilterExt : PXCacheExtension<PX.Objects.AP.PayBillsFilter>
    {
        #region UsrTotalAmountForPayment
        [PXDecimal]
        [PXUIField(DisplayName = "Total Amount For Payment")]
        public virtual Decimal? UsrTotalAmountForPayment { get; set; }
        public abstract class usrTotalAmountForPayment :
        PX.Data.BQL.BqlDecimal.Field<usrTotalAmountForPayment> { }
        #endregion
     }
}

My first attempt I tried to add an unbound formula to my DAC for the below to work you will also need to add a new class decimal_0

namespace PX.Objects.AP
{
    public class PayBillsFilterExt : PXCacheExtension<PX.Objects.AP.PayBillsFilter>
    {
        #region UsrTotalAmountForPayment
        [PXDecimal]
        [PXUIField(DisplayName = "Total Amount For Payment")]
        // add this to the DAC
        [PXUnboundFormula(typeof(Where<APAdjust.curyAdjdAmt,Greater<decimal_0>>)
        ,typeof(SumCalc<APAdjust.curyAdjdAmt>))]
        public virtual Decimal? UsrTotalAmountForPayment { get; set; }
        public abstract class usrTotalAmountForPayment :
        PX.Data.BQL.BqlDecimal.Field<usrTotalAmountForPayment> { }
        #endregion

        //Class decimal_0
        public class decimal_0 : Constant<decimal>
        {
            public decimal_0()
            : base(0)
             { }
        }

     }
}

I have also tried adding an event to do the calculation:

namespace PX.Objects.AP
{
  public class APPayBills_Extension : PXGraphExtension<APPayBills>
  {
     #region Event Handlers
     protected void APAdjust_RowInserted(PXCache cache, PXRowInsertedEventArgs e)
     {
        var row = (APAdjust)e.Row;
        PayBillsFilter filter = this.Base.Filter.Current;
        PayBillsFilterExt FilExt = PXCache<PayBillsFilter>.GetExtension<PayBillsFilterExt>(filter);

        if (filter != null)
        {
            FilExt.UsrTotalAmountForPayment += row.CuryAdjdAmt;

        }
      }
   }
 }

Body:
For accurate results I recommend you sum all the records at the same time.
You can use the DataView.Select method to iterate all records.

public void PayBillsFilter_UsrTotalAmountForPayment_FieldSelecting(PXCache sender, PXFieldSelectingEventArgs e)
{
    decimal total = 0;

    foreach (APAdjust adjustment in this.Base.APDocumentList.Select())
    {
        total += (adjustment.CuryAdjdAmt != null ? adjustment.CuryAdjdAmt.Value : 0M);
    }

    e.ReturnValue = total;
}


问:
exclude directories with the same name ending
I'm trying to write a shell script that runs commands on all folders except the ones with  names ending with "_long" and "_wavs".

This is what I have tried:

```<code>dirs=($(find /Volumes/exchange -type d))

for dir in "${dirs[@]}/!(`basename "$dir"`_long|`basename "$dir"`_wavs)/";
do
   *commands*
done
</code>```

答:
When you can't modify the input like the excellent answer of @nullPointer, you can check inside the loop:</p>

```<code>for dir in "${dirs[@]}"; do
   [[ $dir =~ _long$|_wavs$ ]] && continue;
   *commands*
done
</code>```

Body:
I'm trying to write a shell script that runs commands on all folders except the ones with  names ending with "_long" and "_wavs".

This is what I have tried:

dirs=($(find /Volumes/exchange -type d))

for dir in "${dirs[@]}/!(`basename "$dir"`_long|`basename "$dir"`_wavs)/";
do
   *commands*
done

Body:
When you can't modify the input like the excellent answer of @nullPointer, you can check inside the loop:

for dir in "${dirs[@]}"; do
   [[ $dir =~ _long$|_wavs$ ]] && continue;
   *commands*
done


问:
Laravel with Arabic Slugs
i'm using Laravel 6 to build a blog application
and the language of this app is Arabic
but there is a problem with slug ,it looks like that Laravel doesn't support Arabic.

any idea to fix this?

Controller

```<code>public function post($slug)
{
    $post = Post::where('slug',$slug)->first();
    return view('content.post',compact('post'));
}
</code>```

Store Method

```<code>public function store(Request $request)
{
    $this->validate($request, array(
        'title'         => 'required|max:255',
        'slug'          => 'required|min:3|max:255|unique:posts',
        'body'          => 'required',
    ));
    $post = new Post;
    $post->title = $request->input('title');
    $post->slug = Str::slug($request->slug, '-');
    $post->body = $request->input('body');
    $post->save();

    return redirect('admin/posts')->with('success', 'post is successfully saved');
}
</code>```

Route

```<code>Route::get('post/{slug}', 'PagesController@post')->name('post.show');
</code>```

答:
You can use this function

```<code>public function slug($string, $separator = '-') {
    if (is_null($string)) {
        return "";
    }

    $string = trim($string);

    $string = mb_strtolower($string, "UTF-8");;

    $string = preg_replace("/[^a-z0-9_\sءاأإآؤئبتثجحخدذرزسشصضطظعغفقكلمنهويةى]#u/", "", $string);

    $string = preg_replace("/[\s-]+/", " ", $string);

    $string = preg_replace("/[\s_]/", $separator, $string);

    return $string;
}
public function store(Request $request)
{
    $this->validate($request, array(
        'title'         => 'required|max:255',
        'slug'          => 'required|min:3|max:255|unique:posts',
        'body'          => 'required',
    ));
    $post = new Post;
    $post->title = $request->input('title');
    $post->slug = $this->slug($request->slug);
    $post->body = $request->input('body');
    $post->save();

    return redirect('admin/posts')->with('success', 'post is successfully saved');
}
</code>```

It will make slug for each language arabic or english.
and it will work fine.

Title: Laravel with Arabic Slugs

Body:
i'm using Laravel 6 to build a blog application
and the language of this app is Arabic
but there is a problem with slug ,it looks like that Laravel doesn't support Arabic.

any idea to fix this?

Controller

public function post($slug)
{
    $post = Post::where('slug',$slug)->first();
    return view('content.post',compact('post'));
}

Store Method

public function store(Request $request)
{
    $this->validate($request, array(
        'title'         => 'required|max:255',
        'slug'          => 'required|min:3|max:255|unique:posts',
        'body'          => 'required',
    ));
    $post = new Post;
    $post->title = $request->input('title');
    $post->slug = Str::slug($request->slug, '-');
    $post->body = $request->input('body');
    $post->save();

    return redirect('admin/posts')->with('success', 'post is successfully saved');
}

Route

Route::get('post/{slug}', 'PagesController@post')->name('post.show');

Body:
You can use this function

public function slug($string, $separator = '-') {
    if (is_null($string)) {
        return "";
    }

    $string = trim($string);

    $string = mb_strtolower($string, "UTF-8");;

    $string = preg_replace("/[^a-z0-9_\sءاأإآؤئبتثجحخدذرزسشصضطظعغفقكلمنهويةى]#u/", "", $string);

    $string = preg_replace("/[\s-]+/", " ", $string);

    $string = preg_replace("/[\s_]/", $separator, $string);

    return $string;
}
public function store(Request $request)
{
    $this->validate($request, array(
        'title'         => 'required|max:255',
        'slug'          => 'required|min:3|max:255|unique:posts',
        'body'          => 'required',
    ));
    $post = new Post;
    $post->title = $request->input('title');
    $post->slug = $this->slug($request->slug);
    $post->body = $request->input('body');
    $post->save();

    return redirect('admin/posts')->with('success', 'post is successfully saved');
}

It will make slug for each language arabic or english.
and it will work fine.


问:
Split Comma Separated values into multiple column
I have a requirement where I have a column in my SQL table in this format:

How to split the data using comma delimiter and insert it into newly added columns in the same table?

答:
Your sample data may not need any splitting. You want to move the data to a column based on the value it finds. You can do this a bit simpler than splitting the data. This works just fine for your sample data.</p>

```<code>declare @Something table
(
    Combined_Column varchar(10)
)

insert @Something values
('1,2,3')
, ('2')
, ('1,3')
, ('1,2,3,4')
, ('1,3,4')
, ('1')
, ('4')

select *
    , col1 = case when charindex('1', s.Combined_Column) > 0 then 1 end
    , col2 = case when charindex('2', s.Combined_Column) > 0 then 2 end
    , col3 = case when charindex('3', s.Combined_Column) > 0 then 3 end
    , col4 = case when charindex('4', s.Combined_Column) > 0 then 4 end
from @Something s
</code>```

Body:
Your sample data may not need any splitting. You want to move the data to a column based on the value it finds. You can do this a bit simpler than splitting the data. This works just fine for your sample data.

declare @Something table
(
    Combined_Column varchar(10)
)

insert @Something values
('1,2,3')
, ('2')
, ('1,3')
, ('1,2,3,4')
, ('1,3,4')
, ('1')
, ('4')

select *
    , col1 = case when charindex('1', s.Combined_Column) > 0 then 1 end
    , col2 = case when charindex('2', s.Combined_Column) > 0 then 2 end
    , col3 = case when charindex('3', s.Combined_Column) > 0 then 3 end
    , col4 = case when charindex('4', s.Combined_Column) > 0 then 4 end
from @Something s


问:
FormGroup expects a FormGroup instance. Please pass one in Ionic 4
I cannot get an instance of Formbuilder in Ionic 4

I have imported the Formbuilder in the Class and in the constructor of the component.

It seems i cannot access the Formbuilder within a new function or within the storage or anything else ....

I can instanciate Formbuilder only in the constructor

This code below shows this error

```<code>// ERROR Error: formGroup expects a FormGroup instance. Please pass one in.

this.storage.get('culture').then((val) => {

    this.subscriptionForm = this.formBuilder.group({
      UserName: ['', Validators.required],
      Password: ['', Validators.required],
      Email: ['', Validators.required],
      FirstName: ['', Validators.required],
      LastName: ['', Validators.required]
    });
}
</code>```

I can get it if i call formbuilder before the storage function:

This code below shows no error !

```<code>this.subscriptionForm = this.formBuilder.group({
    UserName: ['', Validators.required],
    Password: ['', Validators.required],
    Email: ['', Validators.required],
    FirstName: ['', Validators.required],
    LastName: ['', Validators.required]
});

this.storage.get('culture').then((val) => {
    //  code...
}
</code>```

This is the view :

```<code><form [formGroup]="subscriptionForm">
    <h3 style="color: gray; text-align: center;">Registration</h3>

    <div class="row">
        <div class="col-md-6">
            <div class="md-form">
                <i class="fa fa-user prefix grey-text"></i>
                <input type="text" formControlName="UserName" id="UserNam" class="form-control">
                <label for="UserName">Your UserName</label>
            </div>
            <br>
            <div class="md-form">
                <i class="fa fa-user prefix grey-text"></i>
                <input type="text" formControlName="FirstName" id="FirstName" class="form-control">
                <label for="FirstName">Your First name</label>
            </div>
        </div>
        <div class="col-md-6">
            <div class="md-form">
                <i class="fa fa-user-secret prefix grey-text"></i>
                <input type="password" id="Password" formControlName="Password" class="form-control">
                <label for="Password">Your password</label>
            </div>
            <br>
            <div class="md-form">
                <i class="fa fa-user-user prefix grey-text"></i>
                <input type="text" id="LastName" formControlName="LastName" class="form-control">
                <label for="LastName">Your Last name</label>
            </div>
        </div>
    </div>
    <br>
    <div class="row">
        <div class="col-md-12">
            <div class="md-form">
                <i class="fa fa-envelope prefix grey-text"></i>
                <input type="email" id="Email" formControlName="Email" class="form-control">
                <label for="Email">Your Email</label>
            </div>
            <br>
            <br>
            <div class="text-center">
                <button class="btn btn-indigo btn-lg btn-block waves-light" type="button" (click)="OnSubmit()">Send
                    <i class="fa fa-paper-plane-o ml-1"></i>
                </button>
            </div>
        </div>
    </div>
</form>
</code>```

答:
The error is present because of <form [formGroup]="subscriptionForm">.

Since you are passing undefined to form's formGroup, it says that it needs a value.

You can simply fix it by adding *ngIf="subscriptionForm".

<form *ngIf="subscriptionForm;else loading" [formGroup]="subscriptionForm">
  ...
</form>

<ng-template #loading>
Loading...
</ng-template>
```

Body:
I cannot get an instance of Formbuilder in Ionic 4

I have imported the Formbuilder in the Class and in the constructor of the component.

It seems i cannot access the Formbuilder within a new function or within the storage or anything else ....

I can instanciate Formbuilder only in the constructor

This code below shows this error

// ERROR Error: formGroup expects a FormGroup instance. Please pass one in.

this.storage.get('culture').then((val) => {

    this.subscriptionForm = this.formBuilder.group({
      UserName: ['', Validators.required],
      Password: ['', Validators.required],
      Email: ['', Validators.required],
      FirstName: ['', Validators.required],
      LastName: ['', Validators.required]
    });
}

I can get it if i call formbuilder before the storage function:

This code below shows no error !

this.subscriptionForm = this.formBuilder.group({
    UserName: ['', Validators.required],
    Password: ['', Validators.required],
    Email: ['', Validators.required],
    FirstName: ['', Validators.required],
    LastName: ['', Validators.required]
});

this.storage.get('culture').then((val) => {
    //  code...
}

This is the view :

<form [formGroup]="subscriptionForm">

Registration

                <input type="text" formControlName="UserName" id="UserNam" class="form-control">
                Your UserName

                <input type="text" formControlName="FirstName" id="FirstName" class="form-control">
                Your First name

                <input type="password" id="Password" formControlName="Password" class="form-control">
                Your password

                <input type="text" id="LastName" formControlName="LastName" class="form-control">
                Your Last name

                <input type="email" id="Email" formControlName="Email" class="form-control">
                Your Email

                <button class="btn btn-indigo btn-lg btn-block waves-light" type="button" (click)="OnSubmit()">Send

                </button>

</form>

Body:
The error is present because of <form [formGroup]="subscriptionForm">.

Since you are passing undefined to form's formGroup, it says that it needs a value.

You can simply fix it by adding *ngIf="subscriptionForm".

<form *ngIf="subscriptionForm;else loading" [formGroup]="subscriptionForm">
  ...
</form>

<ng-template #loading><div>Loading...</div></ng-template>


问:
Changing a data column from varchar(max) to nvarchar(max) in SQL Server 2008
I have to change the data type in a SQL Server 2008 table from varchar(max) to nvarchar(max).  This table has data in it.  Is there a way to change the data type without losing the data?</p>

答:
As of SQL Server 2016, this can now be an ONLINE operation

SQL 2016 ALTER COLUMN online


问:
Get the actual position of element in XSLT
I want to get the actual position of the
 using XSLT.

Input:

```<code><root>
    <p>
        <pPr>
            <pStyle val="EQsolutionlist1"/>
        </pPr>
    </p>
   <p>
       <pPr>
           <pStyle val="AAA"/>
       </pPr>
   </p>
   <p>
       <pPr>
           <pStyle val="EQsolutionlist1"/>
       </pPr>
   </p>
</root>
</code>```

Output should be:

```<code><abc>
  <q>1</q>
  <q>2</q>
</abc>
</code>```

Tried code:

```<code><xsl:template match="p/pPr[pStyle[@val = 'EQsolutionlist1']]">
   <abc>
     <q>
        <xsl:value-of select="ancestor::root//pPr[pStyle[val = 'EQsolutionlist1']]/position()"/>
     </q>
   </abc>
  </xsl:template>
</code>```

The Output I am getting:

```<code><abc>
  <q>1 2</q>
  <q>1 2</q>
</abc>
</code>```

This means, there are two p[pPr[pStyle[@val = 'EQsolutionlist1']]] in input. I want to print the position separately. As my code all positions printing in the output. How can I solve this.

I am using XSLT 2.0

答:
As a first step, consider doing:

```<code>  <xsl:template match="p/pPr[pStyle[@val = 'EQsolutionlist1']]">
   <abc>
     <q>
        <xsl:value-of select="position()"/>
     </q>
   </abc>
  </xsl:template>
</code>```

However, this isn't quite right, because position() here gives you the position of a node in the set of nodes selected by xsl:apply-templates, not the position of the node in the set of nodes matched by this particular template rule.

So you need to change the xsl:apply-templates that triggers this template rule so that it only selects the nodes you want to be numbered: that is, move the predicate [pStyle[@val = 'EQsolutionlist1']] to the xsl:apply-templates instruction.

Remember that position() gives you the position of the context item in the sequence of items you are currently processing.

If you use position() on the right-hand side of "/", as in A/position(), the "/" means evaluate the expression on the right once for every item selected by the expression on the left; the "sequence of items you are currently processing" is the set of nodes selected by A, and their positions are 1, 2, 3, ... N where N is the number of nodes selected by the expression A. Which is not what you want at all.

If you use position() in the outermost code of a template rule, the "sequence of items you are currently processing" is the sequence selected by the xsl:apply-templates instruction that triggered execution of this template rule.

Body:
I want to get the actual position of the
 using XSLT.

Input:

<root>

        <pPr>
            <pStyle val="EQsolutionlist1"/>
        </pPr>

       <pPr>
           <pStyle val="AAA"/>
       </pPr>

       <pPr>
           <pStyle val="EQsolutionlist1"/>
       </pPr>

</root>

Output should be:

<abc>
  <q>1</q>
  <q>2</q>
</abc>

Tried code:

<xsl:template match="p/pPr[pStyle[@val = 'EQsolutionlist1']]">
   <abc>
     <q>
        <xsl:value-of select="ancestor::root//pPr[pStyle[val = 'EQsolutionlist1']]/position()"/>
     </q>
   </abc>
  </xsl:template>

The Output I am getting:

<abc>
  <q>1 2</q>
  <q>1 2</q>
</abc>

This means, there are two p[pPr[pStyle[@val = 'EQsolutionlist1']]] in input. I want to print the position separately. As my code all positions printing in the output. How can I solve this.

I am using XSLT 2.0

Body:
As a first step, consider doing:

  <xsl:template match="p/pPr[pStyle[@val = 'EQsolutionlist1']]">
   <abc>
     <q>
        <xsl:value-of select="position()"/>
     </q>
   </abc>
  </xsl:template>

However, this isn't quite right, because position() here gives you the position of a node in the set of nodes selected by xsl:apply-templates, not the position of the node in the set of nodes matched by this particular template rule.

So you need to change the xsl:apply-templates that triggers this template rule so that it only selects the nodes you want to be numbered: that is, move the predicate [pStyle[@val = 'EQsolutionlist1']] to the xsl:apply-templates instruction.

Remember that position() gives you the position of the context item in the sequence of items you are currently processing.

If you use position() on the right-hand side of "/", as in A/position(), the "/" means evaluate the expression on the right once for every item selected by the expression on the left; the "sequence of items you are currently processing" is the set of nodes selected by A, and their positions are 1, 2, 3, ... N where N is the number of nodes selected by the expression A. Which is not what you want at all.

If you use position() in the outermost code of a template rule, the "sequence of items you are currently processing" is the sequence selected by the xsl:apply-templates instruction that triggered execution of this template rule.


问:
Searchable Dropdown value in Dynamically added rows
Im using php and simple js to add searchable dropdown list in Dynamically added rows, My problem is that, When i add the first rows, the searchable dropdown works fine, but when i add another row, dropdown does not work... Can anyone help me solving this

```<code>$(document).ready(function(){
      $(document).on('click','.btn_addOrder', function(){
        var html='';
        html+='<tr>';
        html+='<td><input type="text" class="form-control productname" style="display:none" name="productname[]" readonly></td>';
        html+='<td><input type="text" class="form-control totalcp" style="display:none" name="totalcp[]" readonly></td>';
        html+='<td><input type="text" class="form-control unitcode" style="display:none" name="unitcode[]" readonly></td>';
        html+='<td><input type="hidden" class="form-control productcode" name="productcode[]" readonly></td>';
        html+='<td><select class="form-control productid" name="productid[]" id="productid"  required><option value="0">--Select Product--</option></select></td>';
        html+='<td><input type="text" class="form-control productstock" name="productstock[]" readonly></td>';
        html+='<td><input type="number"  class="form-control quantity_product" name="quantity[]" required></td>';
        html+='<td><input type="text" class="form-control productsatuan"  name="productsatuan[]" readonly></td>';
        html+='<td><button type="button" name="remove" class="btn btn-danger btn-sm btn-remove"><i class="fa fa-remove"></i></button></td>';

        $('#myStock').append(html);
        $("#productid").select2({
        ajax:{
          url:"prod.php",
          type:"post",
          dataType:"json",
          delay:250,
          data:function(params){     return{   searchTerm:params.term        };      },
          processResults:function(response){   return{       results:response          };    },
          cache:true
          }
        });

        $('.productid').on('change', function(e){
          var productid = this.value;
          var tr=$(this).parent().parent();
          $.ajax({
            url:"getproduct.php",
            method:"post",
            data:{id:productid},
            success:function(data){
              //console.log(data);
              tr.find(".productcode").val(data["product_code"]);
              tr.find(".productname").val(data["product_name"]);
              tr.find(".productstock").val(data["stock"]);
              tr.find(".productsatuan").val(data["nm_satuan"]);
              tr.find(".unitcode").val(data["kd_satuan"]);
              tr.find(".totalcp").val(data["total_cp"]);
              tr.find(".quantity_product").val(0);
             }
          })
        })
      })
      //Remove Row
      $(document).on('click','.btn-remove', function(){
        $(this).closest('tr').remove();
      });
</code>```

答:
The problem is that in that you use an id to initialize and select your select2 searchable dropdown and ids should be unique, so it is used only once.

An easy way to fix this without updating your code much would be to add an index and increment it every time you click the btn_addOrder button. Then you can attach this index to your selector and it will work.

Your code then would look like the following:

```<code>let i=0;
$(document).on('click','.btn_addOrder', function(){
    var html='';
    html+='<tr>';
    html+='<td><input type="text" class="form-control productname" style="display:none" name="productname[]" readonly></td>';
    html+='<td><input type="text" class="form-control totalcp" style="display:none" name="totalcp[]" readonly></td>';
    html+='<td><input type="text" class="form-control unitcode" style="display:none" name="unitcode[]" readonly></td>';
    html+='<td><input type="hidden" class="form-control productcode" name="productcode[]" readonly></td>';
    html+='<td><select class="form-control productid" name="productid[]" id="productid'+i+'"  required><option value="0">--Select Product--</option></select></td>';
    html+='<td><input type="text" class="form-control productstock" name="productstock[]" readonly></td>';
    html+='<td><input type="number"  class="form-control quantity_product" name="quantity[]" required></td>';
    html+='<td><input type="text" class="form-control productsatuan"  name="productsatuan[]" readonly></td>';
    html+='<td><button type="button" name="remove" class="btn btn-danger btn-sm btn-remove"><i class="fa fa-remove"></i></button></td>';

    $('#myStock').append(html);

    $("#productid"+i).select2({
        ajax:{
            url:"prod.php",
            type:"post",
            dataType:"json",
            delay:250,
            data:function(params){     return{   searchTerm:params.term        };      },
            processResults:function(response){   return{       results:response          };    },
            cache:true
            }
        });
    i++;
});
</code>```

So first I define a variable i=0;

Then on the html line where you append the dropdown I edit the id to id="productid'+i+'".

I rename the selector to $("#productid"+i).select2({ to select the right item.

Finally I add the i++; at the end of the btn_addOrder function to make sure that the i auto increments every time you click the button.

Body:
Im using php and simple js to add searchable dropdown list in Dynamically added rows, My problem is that, When i add the first rows, the searchable dropdown works fine, but when i add another row, dropdown does not work... Can anyone help me solving this

$(document).ready(function(){
      $(document).on('click','.btn_addOrder', function(){
        var html='';
        html+='
';
        html+='<input type="text" class="form-control productname" style="display:none" name="productname[]" readonly>	';
        html+='<input type="text" class="form-control totalcp" style="display:none" name="totalcp[]" readonly>	';
        html+='<input type="text" class="form-control unitcode" style="display:none" name="unitcode[]" readonly>	';
        html+='<input type="hidden" class="form-control productcode" name="productcode[]" readonly>	';
        html+='<select class="form-control productid" name="productid[]" id="productid"  required><option value="0">--Select Product--</option></select>	';
        html+='<input type="text" class="form-control productstock" name="productstock[]" readonly>	';
        html+='<input type="number"  class="form-control quantity_product" name="quantity[]" required>	';
        html+='<input type="text" class="form-control productsatuan"  name="productsatuan[]" readonly>	';
        html+='<button type="button" name="remove" class="btn btn-danger btn-sm btn-remove"></button>	';

        $('#myStock').append(html);
        $("#productid").select2({
        ajax:{
          url:"prod.php",
          type:"post",
          dataType:"json",
          delay:250,
          data:function(params){     return{   searchTerm:params.term        };      },
          processResults:function(response){   return{       results:response          };    },
          cache:true
          }
        });

        $('.productid').on('change', function(e){
          var productid = this.value;
          var tr=$(this).parent().parent();
          $.ajax({
            url:"getproduct.php",
            method:"post",
            data:{id:productid},
            success:function(data){
              //console.log(data);
              tr.find(".productcode").val(data["product_code"]);
              tr.find(".productname").val(data["product_name"]);
              tr.find(".productstock").val(data["stock"]);
              tr.find(".productsatuan").val(data["nm_satuan"]);
              tr.find(".unitcode").val(data["kd_satuan"]);
              tr.find(".totalcp").val(data["total_cp"]);
              tr.find(".quantity_product").val(0);
             }
          })
        })
      })
      //Remove Row
      $(document).on('click','.btn-remove', function(){
        $(this).closest('tr').remove();
      });

Body:
The problem is that in that you use an id to initialize and select your select2 searchable dropdown and ids should be unique, so it is used only once.

An easy way to fix this without updating your code much would be to add an index and increment it every time you click the btn_addOrder button. Then you can attach this index to your selector and it will work.

Your code then would look like the following:

let i=0;
$(document).on('click','.btn_addOrder', function(){
    var html='';
    html+='<tr>';
    html+='<td><input type="text" class="form-control productname" style="display:none" name="productname[]" readonly></td>';
    html+='<td><input type="text" class="form-control totalcp" style="display:none" name="totalcp[]" readonly></td>';
    html+='<td><input type="text" class="form-control unitcode" style="display:none" name="unitcode[]" readonly></td>';
    html+='<td><input type="hidden" class="form-control productcode" name="productcode[]" readonly></td>';
    html+='<td><select class="form-control productid" name="productid[]" id="productid'+i+'"  required><option value="0">--Select Product--</option></select></td>';
    html+='<td><input type="text" class="form-control productstock" name="productstock[]" readonly></td>';
    html+='<td><input type="number"  class="form-control quantity_product" name="quantity[]" required></td>';
    html+='<td><input type="text" class="form-control productsatuan"  name="productsatuan[]" readonly></td>';
    html+='<td><button type="button" name="remove" class="btn btn-danger btn-sm btn-remove"><i class="fa fa-remove"></i></button></td>';

    $('#myStock').append(html);

    $("#productid"+i).select2({
        ajax:{
            url:"prod.php",
            type:"post",
            dataType:"json",
            delay:250,
            data:function(params){     return{   searchTerm:params.term        };      },
            processResults:function(response){   return{       results:response          };    },
            cache:true
            }
        });
    i++;
});

So first I define a variable i=0;

Then on the html line where you append the dropdown I edit the id to id="productid'+i+'".

I rename the selector to $("#productid"+i).select2({ to select the right item.

Finally I add the i++; at the end of the btn_addOrder function to make sure that the i auto increments every time you click the button.


问:
Wordpress Permalinks Redirect htaccess
In my old wordpress blog are the permalinks day and title for example /2020/02/17/example-title/.
I will change it to /example-title/.

Now I need a redirect code for all the old links with the date in the URL.
I didn't find here or elsewhere a solution for this problem.

Thank you.

Title: Wordpress Permalinks Redirect htaccess

Body:
I have found a working solution:

RedirectMatch 301 ^/blog/([0-9]{4})/([0-9]{2})/([0-9]{2})/([^/]+)/$ https://www.example.com/$4


问:
How to fetch json data using vuejs component?
I want to access json data from external file using vue component but I am not able to get any output in web page.The below is my code which I have tried.Can  anyone help me out?

The below is Json data that included the models which I want to display on web page

```<code>{
    "models": [
      {
        "title": "IRIS",
        "project": "ABC",
        "category": "SINGLES",
        "bedrooms": 3

      },
      {
        "title": "LILAC",
        "project": "ABC",
        "category": "DOUBLE",
        "bedrooms": 4

      },
      {
        "title": "ASTER",
        "project": "ABC",
        "category": "SINGLES",
        "bedrooms": 4

      }
    ]
  }
</code>```

Vue.component('single-model', {

  data: function() {
    return {
      myData: []

    }
  },
  template: `

{{model.title}}

`,

  created: function() {
    this.fetchData();
  },

  methods: {
    fetchData: function() {
      var url = 'j.json';
      axios.get(url)
        .then(function(res) {
          this.myData = res.data.models;

        });
    }
  }
});
var vm = new Vue({
  el: '#app',
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>

    <div id="app">
      <single-model></single-model>

    </div></code>```

答:
As you might have noticed white running the provided snippet, template can have only one child element, using a v-for on the outermost element will create multiple children.

this in your case is not referring to the vue-component in fetchData function.

methods:{
 fetchData() {
      var url = '';
      axios.get(url)
        .then((res) => {
          this.myData = res.data;
  });
    }
  },```

Try replacing with the above snippet in your code.

Body:
I want to access json data from external file using vue component but I am not able to get any output in web page.The below is my code which I have tried.Can  anyone help me out?

The below is Json data that included the models which I want to display on web page

{
    "models": [
      {
        "title": "IRIS",
        "project": "ABC",
        "category": "SINGLES",
        "bedrooms": 3

      },
      {
        "title": "LILAC",
        "project": "ABC",
        "category": "DOUBLE",
        "bedrooms": 4

      },
      {
        "title": "ASTER",
        "project": "ABC",
        "category": "SINGLES",
        "bedrooms": 4

      }
    ]
  }

Vue.component('single-model', {

  data: function() {
    return {
      myData: []

    }
  },
  template: `

{{model.title}}

`,

  created: function() {
    this.fetchData();
  },

  methods: {
    fetchData: function() {
      var url = 'j.json';
      axios.get(url)
        .then(function(res) {
          this.myData = res.data.models;

        });
    }
  }
});
var vm = new Vue({
  el: '#app',
});

      <single-model></single-model>

Body:
As you might have noticed white running the provided snippet, template can have only one child element, using a v-for on the outermost element will create multiple children.

this in your case is not referring to the vue-component in fetchData function.

methods:{
 fetchData() {
      var url = '';
      axios.get(url)
        .then((res) => {
          this.myData = res.data;
  });
    }
  },

Try replacing with the above snippet in your code.