问:
Using Aspect advice with wildcard leading to multiple triggers and exceptions
Im new to AOP and have created a simple SpringBoot project to learn it. I've created a logging aspect which simple logs a message before triggering a get method that returns String. Upon adding wildcards (so it triggers for all get methods, regardless of return-type), im seeing an odd behavior - it seems to be triggering for internal method calls spring uses to load the context and then runs into an NPE. Not sure how to resolve this, code is below:

```<code>@SpringBootApplication
@ComponentScan
@EnableAutoConfiguration
public class AspectOrientedProgrammingApplication implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public static void main(String[] args) {
        SpringApplication.run(AspectOrientedProgrammingApplication.class, args);
        ShapeService shapeService = applicationContext.getBean(ShapeService.class);
        System.out.println(shapeService.getCircle().getName());
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }
}
</code>```

My Circle class:

```<code>@Component
public class Circle {
    @Value("${spring.app.circleName}")
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
</code>```

ShapeService class:

```<code>@Component
public class ShapeService {
    @Autowired
    private Triangle triangle;

    @Autowired
    private Circle circle;

    public Triangle getTriangle() {
        return triangle;
    }

    public void setTriangle(Triangle triangle) {
        this.triangle = triangle;
    }

    public Circle getCircle() {
        return circle;
    }

    public void setCircle(Circle circle) {
        this.circle = circle;
    }
}
</code>```

Aspect class:

```<code>@Aspect
@Component
public class LoggingAspect {

    @Before("execution(public * get*())") // works fine with "execution(public String getName())"
    public void loggingAdvice(){
        System.out.println("Advice run: Get method called");
    }
}
</code>```

Running this results in following:

```<code>Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.springframework.cglib.core.ReflectUtils (file:/C:/Users/Arslan/.m2/repository/org/springframework/spring-core/5.3.15/spring-core-5.3.15.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of org.springframework.cglib.core.ReflectUtils
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
2022-02-06 08:14:28.566  INFO 8004 --- [           main] o.s.aop.framework.CglibAopProxy          : Unable to proxy interface-implementing method [public final void org.springframework.boot.web.servlet.RegistrationBean.onStartup(javax.servlet.ServletContext) throws javax.servlet.ServletException] because it is marked as final: Consider using interface-based JDK proxies instead!
Advice run: Get method called
2022-02-06 08:14:29.163  INFO 8004 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2022-02-06 08:14:29.179  INFO 8004 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-02-06 08:14:29.179  INFO 8004 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.56]
2022-02-06 08:14:29.327  INFO 8004 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-02-06 08:14:29.327  INFO 8004 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2959 ms
Advice run: Get method called
2022-02-06 08:14:29.339  INFO 8004 --- [           main] o.s.aop.framework.CglibAopProxy          : Unable to proxy interface-implementing method [public final void org.springframework.web.filter.OncePerRequestFilter.doFilter(javax.servlet.ServletRequest,javax.servlet.ServletResponse,javax.servlet.FilterChain) throws javax.servlet.ServletException,java.io.IOException] because it is marked as final: Consider using interface-based JDK proxies instead!
2022-02-06 08:14:29.339  INFO 8004 --- [           main] o.s.aop.framework.CglibAopProxy          : Unable to proxy interface-implementing method [public final void org.springframework.web.filter.GenericFilterBean.init(javax.servlet.FilterConfig) throws javax.servlet.ServletException] because it is marked as final: Consider using interface-based JDK proxies instead!
2022-02-06 08:14:29.363  INFO 8004 --- [           main] o.s.aop.framework.CglibAopProxy          : Unable to proxy interface-implementing method [public final void org.springframework.web.filter.OncePerRequestFilter.doFilter(javax.servlet.ServletRequest,javax.servlet.ServletResponse,javax.servlet.FilterChain) throws javax.servlet.ServletException,java.io.IOException] because it is marked as final: Consider using interface-based JDK proxies instead!
2022-02-06 08:14:29.363  INFO 8004 --- [           main] o.s.aop.framework.CglibAopProxy          : Unable to proxy interface-implementing method [public final void org.springframework.web.filter.GenericFilterBean.init(javax.servlet.FilterConfig) throws javax.servlet.ServletException] because it is marked as final: Consider using interface-based JDK proxies instead!
2022-02-06 08:14:29.391  INFO 8004 --- [           main] o.s.aop.framework.CglibAopProxy          : Unable to proxy interface-implementing method [public final void org.springframework.web.filter.OncePerRequestFilter.doFilter(javax.servlet.ServletRequest,javax.servlet.ServletResponse,javax.servlet.FilterChain) throws javax.servlet.ServletException,java.io.IOException] because it is marked as final: Consider using interface-based JDK proxies instead!
2022-02-06 08:14:29.391  INFO 8004 --- [           main] o.s.aop.framework.CglibAopProxy          : Unable to proxy interface-implementing method [public final void org.springframework.web.filter.GenericFilterBean.init(javax.servlet.FilterConfig) throws javax.servlet.ServletException] because it is marked as final: Consider using interface-based JDK proxies instead!
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
2022-02-06 08:14:29.548 ERROR 8004 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Exception starting filter [requestContextFilter]

java.lang.NullPointerException: null
    at org.springframework.web.filter.GenericFilterBean.init(GenericFilterBean.java:241) ~[spring-web-5.3.15.jar:5.3.15]
    at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:272) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:106) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4613) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5256) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140) ~[na:na]
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:919) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:835) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140) ~[na:na]
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:919) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:263) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:432) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:927) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.startup.Tomcat.start(Tomcat.java:486) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:123) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.<init>(TomcatWebServer.java:104) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getTomcatWebServer(TomcatServletWebServerFactory.java:478) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getWebServer(TomcatServletWebServerFactory.java:211) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory$$FastClassBySpringCGLIB$$9c83fa9f.invoke(<generated>) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.3.15.jar:5.3.15]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:783) ~[spring-aop-5.3.15.jar:5.3.15]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.3.15.jar:5.3.15]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:753) ~[spring-aop-5.3.15.jar:5.3.15]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.15.jar:5.3.15]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.15.jar:5.3.15]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:753) ~[spring-aop-5.3.15.jar:5.3.15]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:698) ~[spring-aop-5.3.15.jar:5.3.15]
    at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory$$EnhancerBySpringCGLIB$$e5201eaa.getWebServer(<generated>) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:182) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:160) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:577) ~[spring-context-5.3.15.jar:5.3.15]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:732) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:414) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1303) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1292) ~[spring-boot-2.6.3.jar:2.6.3]
    at com.arslan.javabrains.AspectOrientedProgrammingApplication.main(AspectOrientedProgrammingApplication.java:20) ~[classes/:na]

2022-02-06 08:14:29.548 ERROR 8004 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Exception starting filter [characterEncodingFilter]
</code>```

答:
It is a feature, not a bug of AOP that you can implement cross-cutting concerns which have a wide scope. The wide scope is a default, if you do not limit it. This applies to both native AspectJ and Spring AOP. We are talking about the latter here.

It is a typical AOP beginner's mistake to "weave the world", i.e. to write too widely-scoped pointcuts. In Spring AOP this can lead to intercepting internal Spring components or third-party ones, and sometimes that might be exactly what you want, depending on your aspect's purpose. In many cases, however, you simply want to apply the aspect to your own application, which hopefully lives in its own base package such as org.acme.myapp. Then you simply add && within(org.acme.myapp..*) to your pointcut in order to focus on everything in those packages (and their subpackages by virtue of ..*) as potential AOP targets.

So for your simple logging advice, it would look like this:

@Before("execution(public * get*()) && within(org.acme.myapp..*)")
public void loggingAdvice(JoinPoint joinPoint) {
  // Instead of a static message, log what we are actually intercepting
  System.out.println(joinPoint);
}
```

Of course, like you noticed, you could also extend the execution pointcut in order to add some scope, but firstly that makes the pointcut a bit harder to read and secondly it does not help you for pointcuts other than execution.

Body:
Im new to AOP and have created a simple SpringBoot project to learn it. I've created a logging aspect which simple logs a message before triggering a get method that returns String. Upon adding wildcards (so it triggers for all get methods, regardless of return-type), im seeing an odd behavior - it seems to be triggering for internal method calls spring uses to load the context and then runs into an NPE. Not sure how to resolve this, code is below:

@SpringBootApplication
@ComponentScan
@EnableAutoConfiguration
public class AspectOrientedProgrammingApplication implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public static void main(String[] args) {
        SpringApplication.run(AspectOrientedProgrammingApplication.class, args);
        ShapeService shapeService = applicationContext.getBean(ShapeService.class);
        System.out.println(shapeService.getCircle().getName());
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }
}

My Circle class:

@Component
public class Circle {
    @Value("${spring.app.circleName}")
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

ShapeService class:

@Component
public class ShapeService {
    @Autowired
    private Triangle triangle;

    @Autowired
    private Circle circle;

    public Triangle getTriangle() {
        return triangle;
    }

    public void setTriangle(Triangle triangle) {
        this.triangle = triangle;
    }

    public Circle getCircle() {
        return circle;
    }

    public void setCircle(Circle circle) {
        this.circle = circle;
    }
}

Aspect class:

@Aspect
@Component
public class LoggingAspect {

    @Before("execution(public * get*())") // works fine with "execution(public String getName())"
    public void loggingAdvice(){
        System.out.println("Advice run: Get method called");
    }
}

Running this results in following:

Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.springframework.cglib.core.ReflectUtils (file:/C:/Users/Arslan/.m2/repository/org/springframework/spring-core/5.3.15/spring-core-5.3.15.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of org.springframework.cglib.core.ReflectUtils
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
2022-02-06 08:14:28.566  INFO 8004 --- [           main] o.s.aop.framework.CglibAopProxy          : Unable to proxy interface-implementing method [public final void org.springframework.boot.web.servlet.RegistrationBean.onStartup(javax.servlet.ServletContext) throws javax.servlet.ServletException] because it is marked as final: Consider using interface-based JDK proxies instead!
Advice run: Get method called
2022-02-06 08:14:29.163  INFO 8004 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2022-02-06 08:14:29.179  INFO 8004 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-02-06 08:14:29.179  INFO 8004 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.56]
2022-02-06 08:14:29.327  INFO 8004 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-02-06 08:14:29.327  INFO 8004 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2959 ms
Advice run: Get method called
2022-02-06 08:14:29.339  INFO 8004 --- [           main] o.s.aop.framework.CglibAopProxy          : Unable to proxy interface-implementing method [public final void org.springframework.web.filter.OncePerRequestFilter.doFilter(javax.servlet.ServletRequest,javax.servlet.ServletResponse,javax.servlet.FilterChain) throws javax.servlet.ServletException,java.io.IOException] because it is marked as final: Consider using interface-based JDK proxies instead!
2022-02-06 08:14:29.339  INFO 8004 --- [           main] o.s.aop.framework.CglibAopProxy          : Unable to proxy interface-implementing method [public final void org.springframework.web.filter.GenericFilterBean.init(javax.servlet.FilterConfig) throws javax.servlet.ServletException] because it is marked as final: Consider using interface-based JDK proxies instead!
2022-02-06 08:14:29.363  INFO 8004 --- [           main] o.s.aop.framework.CglibAopProxy          : Unable to proxy interface-implementing method [public final void org.springframework.web.filter.OncePerRequestFilter.doFilter(javax.servlet.ServletRequest,javax.servlet.ServletResponse,javax.servlet.FilterChain) throws javax.servlet.ServletException,java.io.IOException] because it is marked as final: Consider using interface-based JDK proxies instead!
2022-02-06 08:14:29.363  INFO 8004 --- [           main] o.s.aop.framework.CglibAopProxy          : Unable to proxy interface-implementing method [public final void org.springframework.web.filter.GenericFilterBean.init(javax.servlet.FilterConfig) throws javax.servlet.ServletException] because it is marked as final: Consider using interface-based JDK proxies instead!
2022-02-06 08:14:29.391  INFO 8004 --- [           main] o.s.aop.framework.CglibAopProxy          : Unable to proxy interface-implementing method [public final void org.springframework.web.filter.OncePerRequestFilter.doFilter(javax.servlet.ServletRequest,javax.servlet.ServletResponse,javax.servlet.FilterChain) throws javax.servlet.ServletException,java.io.IOException] because it is marked as final: Consider using interface-based JDK proxies instead!
2022-02-06 08:14:29.391  INFO 8004 --- [           main] o.s.aop.framework.CglibAopProxy          : Unable to proxy interface-implementing method [public final void org.springframework.web.filter.GenericFilterBean.init(javax.servlet.FilterConfig) throws javax.servlet.ServletException] because it is marked as final: Consider using interface-based JDK proxies instead!
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
Advice run: Get method called
2022-02-06 08:14:29.548 ERROR 8004 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Exception starting filter [requestContextFilter]

java.lang.NullPointerException: null
    at org.springframework.web.filter.GenericFilterBean.init(GenericFilterBean.java:241) ~[spring-web-5.3.15.jar:5.3.15]
    at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:272) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:106) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4613) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5256) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140) ~[na:na]
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:919) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:835) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140) ~[na:na]
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:919) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:263) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:432) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:927) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.startup.Tomcat.start(Tomcat.java:486) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:123) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.<init>(TomcatWebServer.java:104) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getTomcatWebServer(TomcatServletWebServerFactory.java:478) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getWebServer(TomcatServletWebServerFactory.java:211) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory$$FastClassBySpringCGLIB$$9c83fa9f.invoke(<generated>) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.3.15.jar:5.3.15]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:783) ~[spring-aop-5.3.15.jar:5.3.15]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.3.15.jar:5.3.15]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:753) ~[spring-aop-5.3.15.jar:5.3.15]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.15.jar:5.3.15]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.15.jar:5.3.15]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:753) ~[spring-aop-5.3.15.jar:5.3.15]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:698) ~[spring-aop-5.3.15.jar:5.3.15]
    at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory$$EnhancerBySpringCGLIB$$e5201eaa.getWebServer(<generated>) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:182) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:160) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:577) ~[spring-context-5.3.15.jar:5.3.15]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:732) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:414) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1303) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1292) ~[spring-boot-2.6.3.jar:2.6.3]
    at com.arslan.javabrains.AspectOrientedProgrammingApplication.main(AspectOrientedProgrammingApplication.java:20) ~[classes/:na]

2022-02-06 08:14:29.548 ERROR 8004 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Exception starting filter [characterEncodingFilter]

Body:
It is a feature, not a bug of AOP that you can implement cross-cutting concerns which have a wide scope. The wide scope is a default, if you do not limit it. This applies to both native AspectJ and Spring AOP. We are talking about the latter here.

It is a typical AOP beginner's mistake to "weave the world", i.e. to write too widely-scoped pointcuts. In Spring AOP this can lead to intercepting internal Spring components or third-party ones, and sometimes that might be exactly what you want, depending on your aspect's purpose. In many cases, however, you simply want to apply the aspect to your own application, which hopefully lives in its own base package such as org.acme.myapp. Then you simply add && within(org.acme.myapp..*) to your pointcut in order to focus on everything in those packages (and their subpackages by virtue of ..*) as potential AOP targets.

So for your simple logging advice, it would look like this:

@Before("execution(public * get*()) && within(org.acme.myapp..*)")
public void loggingAdvice(JoinPoint joinPoint) {
  // Instead of a static message, log what we are actually intercepting
  System.out.println(joinPoint);
}

Of course, like you noticed, you could also extend the execution pointcut in order to add some scope, but firstly that makes the pointcut a bit harder to read and secondly it does not help you for pointcuts other than execution.


来源: stackexchange

问:
jquery-mobile backbone.js routing
I have a backbone.js / jquery mobile app:

when i make a GET to mydomain.com/#map, then jquery executes "/" and then loads #map.

because "/" is triggered first, all backbone.js scripts are loaded including the backbone.js routes in my map-controller.js ("map":  "functionForMapRoute").
since the URL contains /#map, the backbone.js route "map" gets triggered before jquery mobile has rendered the dom.

so "functionForMapRoute" can´t operate on divs cause the DOM isn´t fully loaded at this point.

how can i ensure, that the "map" route is triggered not until the DOM is fully loaded?

答: use something more integrated with jquery mobile, for instance jquerymobile-router (you can find it on github). It replaces backbone's router and it's to be used with jquery mobile and backbone.js or spine.js</p>

ContentLicense: CC BY-SA 3.0

Title: jquery-mobile backbone.js routing


问:
Why Won't My shape Show Up in the Turtle Module
I am trying to create a Pong game, but when I create the paddle, it won't show up. How can I  fix it?
Here's my code:</p>
```<code>import turtle

wm = turtle.Screen()
wm.title("Pong by Zachary Bye")
wm.bgcolor("black")
wm.setup(width=800, height=600)
wm.tracer(0)

#Paddle a
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("white")
paddle_a.shapesize
paddle_a.penup()
paddle_a.goto(-350,0)
</code>```

答:
when I create the paddle, it won't show up.

The reason is you invoked tracer(0) which says, "don't draw anything until I explicitly call update().  And then you didn't call update()!  This is how I would write your code fragment:

```<code>from turtle import Screen, Turtle

screen = Screen()
screen.title("Pong by Zachary Bye")
screen.setup(width=800, height=600)
screen.bgcolor('black')
screen.tracer(0)

# Paddle a
paddle_a = Turtle()
paddle_a.shape('square')
paddle_a.color('white')
paddle_a.shapesize(5, 1)
paddle_a.penup()
paddle_a.setx(-350)

screen.update()
screen.mainloop()
</code>```

My general rule is to avoid tracer() and update() until your code is basically working and you want to optimize the graphics.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create a Pong game, but when I create the paddle, it won't show up. How can I  fix it?
Here's my code:

import turtle

wm = turtle.Screen()
wm.title("Pong by Zachary Bye")
wm.bgcolor("black")
wm.setup(width=800, height=600)
wm.tracer(0)

#Paddle a
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("white")
paddle_a.shapesize
paddle_a.penup()
paddle_a.goto(-350,0)

Body:
when I create the paddle, it won't show up.

The reason is you invoked tracer(0) which says, "don't draw anything until I explicitly call update().  And then you didn't call update()!  This is how I would write your code fragment:

from turtle import Screen, Turtle

screen = Screen()
screen.title("Pong by Zachary Bye")
screen.setup(width=800, height=600)
screen.bgcolor('black')
screen.tracer(0)

# Paddle a
paddle_a = Turtle()
paddle_a.shape('square')
paddle_a.color('white')
paddle_a.shapesize(5, 1)
paddle_a.penup()
paddle_a.setx(-350)

screen.update()
screen.mainloop()

My general rule is to avoid tracer() and update() until your code is basically working and you want to optimize the graphics.


问:
How to manipulate a BLOB in Java?
I have a DB procedure which returns a BLOB. Can anyone tell me how to manipulate the BLOB? Is there any specific API for this?</p>

答:
Example</p>
```<code>public void Insert(Object obj){
        try {
            ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
            ObjectOutputStream oos=new ObjectOutputStream(byteArray);
            oos.writeObject(obj);
            PreparedStatement ps= conn1.prepareStatement("insert into vehiculos values(?)");
            ps.setBytes(1, byteArray.toByteArray());
            ps.execute();
            ps.close();
        } catch (SQLException ex) {
            System.out.println("ERROR:al hacer un Insert");
            ex.printStackTrace();
        } catch (IOException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void ShowData(){
        try {
            Statement stmt = conn1.createStatement();
            String query = "SELECT * FROM vehiculos";
            ResultSet rs = stmt.executeQuery(query);
            Object obj;
            while(rs.next()){
                //Coche c = (Coche)rs.getBlob("coches");
                Blob blob = rs.getBlob("coches");
                ObjectInputStream ois = new ObjectInputStream(blob.getBinaryStream());
                obj = ois.readObject();
                System.out.println(obj.toString());
                System.out.println("");
                /*Blob blob = rs.getBlob("coches");
                byte[] data = blob.getBytes(1, (int)blob.length());*/

            }
            rs.close();
            stmt.close();

      } catch (SQLException ex) {
            System.out.println("ERROR:al consultar");
            ex.printStackTrace();
      } catch (IOException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void cerrar_Conexion (){

        try {
        conn1.close();
      } catch (SQLException ex) {
            System.out.println("ERROR:al cerrar la conexión");
            ex.printStackTrace();
      }
    }
</code>```

Title: How to manipulate a BLOB in Java?

Body:
Example

public void Insert(Object obj){
        try {
            ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
            ObjectOutputStream oos=new ObjectOutputStream(byteArray);
            oos.writeObject(obj);
            PreparedStatement ps= conn1.prepareStatement("insert into vehiculos values(?)");
            ps.setBytes(1, byteArray.toByteArray());
            ps.execute();
            ps.close();
        } catch (SQLException ex) {
            System.out.println("ERROR:al hacer un Insert");
            ex.printStackTrace();
        } catch (IOException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void ShowData(){
        try {
            Statement stmt = conn1.createStatement();
            String query = "SELECT * FROM vehiculos";
            ResultSet rs = stmt.executeQuery(query);
            Object obj;
            while(rs.next()){
                //Coche c = (Coche)rs.getBlob("coches");
                Blob blob = rs.getBlob("coches");
                ObjectInputStream ois = new ObjectInputStream(blob.getBinaryStream());
                obj = ois.readObject();
                System.out.println(obj.toString());
                System.out.println("");
                /*Blob blob = rs.getBlob("coches");
                byte[] data = blob.getBytes(1, (int)blob.length());*/

            }
            rs.close();
            stmt.close();

      } catch (SQLException ex) {
            System.out.println("ERROR:al consultar");
            ex.printStackTrace();
      } catch (IOException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void cerrar_Conexion (){

        try {
        conn1.close();
      } catch (SQLException ex) {
            System.out.println("ERROR:al cerrar la conexión");
            ex.printStackTrace();
      }
    }


问:
How do I force the Xcode compiler to ignore a library when building for the iOS simulator
I am getting a series of linker errors when building a specific library for the iOS simulator.  The source of the issue seems to the be architecture that the library was build for which seems to cause issue when compiling for the iOS simulator.  The specific library is the Aurasma augmented reality library.

My question would be this, is there a way to not compile a library when the code is being compiled for the iOS simulator?  Although I do have some code that is dependent on that library I could easily use an #ifdef statement to only use that code when NOT in the iOS simulator.

I can easily admit I may not understand the full root of the issue.  I have attempted some solutions using a -weak_library linker flag with no specific progress or success.

答:
//:configuration = ReleaseForProfiling
CODE_SIGN_IDENTITY =
CODE_SIGN_IDENTITY[sdk=iphoneos*] =
DEVELOPMENT_TEAM =
PROVISIONING_PROFILE_SPECIFIER[sdk=iphonesimulator*] =
PROVISIONING_PROFILE[sdk=iphonesimulator*] =

//:configuration = Release
CODE_SIGN_IDENTITY =
CODE_SIGN_IDENTITY[sdk=iphoneos*] =
DEVELOPMENT_TEAM =
PROVISIONING_PROFILE_SPECIFIER[sdk=iphonesimulator*] =
PROVISIONING_PROFILE[sdk=iphonesimulator*] =

//:configuration = Debug
CODE_SIGN_IDENTITY =
CODE_SIGN_IDENTITY[sdk=iphoneos*] =
DEVELOPMENT_TEAM =
PROVISIONING_PROFILE_SPECIFIER[sdk=iphonesimulator*] =
PROVISIONING_PROFILE[sdk=iphonesimulator*] =

//:configuration = ReleaseForRunning
CODE_SIGN_IDENTITY =
CODE_SIGN_IDENTITY[sdk=iphoneos*] =
DEVELOPMENT_TEAM =
PROVISIONING_PROFILE_SPECIFIER[sdk=iphonesimulator*] =
PROVISIONING_PROFILE[sdk=iphonesimulator*] =

//:completeSettings = some
CODE_SIGN_ENTITLEMENTS
CODE_SIGN_IDENTITY
CODE_SIGN_STYLE
DEVELOPMENT_TEAM
OTHER_CODE_SIGN_FLAGS
PROVISIONING_PROFILE_SPECIFIER
PROVISIONING_PROFILE


问:
Check and see if video is available on YouTube Music using the YouTube API
Hey guys I'm working on a little project to automate some of my playlists on YouTube Music, although I am running into a problem where some of the songs I am finding are available on YouTube, but not YouTube Music specifically.

Right now I am just running a check to see if the page returns a 404 which sort of works, except YouTube music likes to just auto play the next song if the requested song is unavailable so I'll need a bit more robust system.

For a bit of an example, you can go to this video on YouTube with a video ID of Xge20AqKSRE on YouTube you can watch the video no problem, although it is unavailable on YouTube Music. If you try this other link you get a little popup in the bottom left saying "This song is unavailable. Skipping to the next one." which is a problem since right now I'm just checking to see if the page returns a 404, which this obviously wont.

I have been digging through the YouTube API but I cannot find anything specific to YouTube Music.

答:
AFAIK YouTube Data API v3 doesn't provide support for knowing whether or not a given video isn't supported in YouTube Music.

However the feature you are looking for is available in my YouTube operational API, indeed by requesting https://yt.lemnoslife.com/videos?part=music&id=Xge20AqKSRE you'll receive a JSON with available equals to true if the video is available on YouTube music, false otherwise. That way https://yt.lemnoslife.com/videos?part=music&id=ntG3GQdY_Ok returns available true while the first link returns available false.

If you have any question don't hesitate to comment or come to the Discord support.


问:
SQL - safely downcast BIGINT to INT
I have a CSV I'm importing into our database. One of the "columns" contains data that should be an INT but some rows have numbers that only fall in the BIGINT range (because they're test data from one of our partners). We store INT internally and have no desire to change.

I want to safely downcast from BIGINT to INT. By safely, I mean no errors should be raised if an arithmetic overflow happens. If the cast/conversion succeeds, I want my script to go on. If it fails, I want it to short-circuit. I can't seem to figure out the proper syntax. This is what I've got:

```<code>DECLARE @UserIDBigInt BIGINT = 9723021913; -- actually provided by query param
--Setting within the INT range successfully converts
--SET @UserIDBigInt = 5;
DECLARE @UserID INT = CONVERT(INT, @UserIDBigInt);
--DECLARE @UserID INT = CAST(@UserIDBigInt AS INT);
SELECT @UserIDBigInt
SELECT @UserID
IF @UserID IS NOT NULL BEGIN
    SELECT 'Handle it as reliable data'
END
</code>```

I've thought about comparing @UserIDBigInt to the valid range of an INT (-2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647)), but I really don't like that approach. That's my fallback. I was hoping for some language constructs or built-in functions I could use. If I absolutely have to compare to the valid range, are there at least some built-in constants (like C#'s int.MinValue & int.MaxValue)?

EDIT: Corrected typo.

答:
Add these to your script:

```<code>SET ARITHABORT OFF;
SET ARITHIGNORE ON;
</code>```

This will convert any overflow values to NULL.

More info here: http://msdn.microsoft.com/en-us/library/ms184341.aspx

Title: SQL - safely downcast BIGINT to INT

Body:
I have a CSV I'm importing into our database. One of the "columns" contains data that should be an INT but some rows have numbers that only fall in the BIGINT range (because they're test data from one of our partners). We store INT internally and have no desire to change.

I want to safely downcast from BIGINT to INT. By safely, I mean no errors should be raised if an arithmetic overflow happens. If the cast/conversion succeeds, I want my script to go on. If it fails, I want it to short-circuit. I can't seem to figure out the proper syntax. This is what I've got:

DECLARE @UserIDBigInt BIGINT = 9723021913; -- actually provided by query param
--Setting within the INT range successfully converts
--SET @UserIDBigInt = 5;
DECLARE @UserID INT = CONVERT(INT, @UserIDBigInt);
--DECLARE @UserID INT = CAST(@UserIDBigInt AS INT);
SELECT @UserIDBigInt
SELECT @UserID
IF @UserID IS NOT NULL BEGIN
    SELECT 'Handle it as reliable data'
END

I've thought about comparing @UserIDBigInt to the valid range of an INT (-2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647)), but I really don't like that approach. That's my fallback. I was hoping for some language constructs or built-in functions I could use. If I absolutely have to compare to the valid range, are there at least some built-in constants (like C#'s int.MinValue & int.MaxValue)?

EDIT: Corrected typo.

Body:
Add these to your script:

SET ARITHABORT OFF;
SET ARITHIGNORE ON;

This will convert any overflow values to NULL.

More info here: http://msdn.microsoft.com/en-us/library/ms184341.aspx


问:
How to set keyboard focus to a textbox inside a user control in WPF?
When I open the window MyWindow, I want to have the cursor of my keyboard pointing to the textbox contained in a user control that is contained in the window.

Usually, you would set FocusManager.FocusedElement={Binding ElementName=TextBoxToPutFocusOn}.

But here, my constraint is that the textbox is inside a user control that is inside my window.

How can my window set focus to this textbox?

To illustrate, here are my 2 files:

MyWindow.xaml

```<code><Window
xmlns:wpf="clr-namespace:MyWPFNamespace">
    <StackPanel>
        <TextBlock>Sample text</TextBlock>
        <wpf:SpecialTextBox/>
    </StackPanel>
</Window>
</code>```

SpecialTextBox.xaml

```<code><UserControl
    x:Class="MyWPFNamespace.SpecialTextBox"
    x:Name="SpecialName">
    <TextBox
        x:Name="TextBoxToPutFocusOn" />
</UserControl>
</code>```

Thank you

答:
WPF's UserControl inherits FrameworkElement which has FrameworkElement.OnGotFocus method. So you can use it as follows:

protected override void OnGotFocus(RoutedEventArgs e)
{
    base.OnGotFocus(e);

    FocusManager.SetFocusedElement(Window.GetWindow(this), this.TextBoxToPutFocusOn);
}
```

Body:
When I open the window MyWindow, I want to have the cursor of my keyboard pointing to the textbox contained in a user control that is contained in the window.

Usually, you would set FocusManager.FocusedElement={Binding ElementName=TextBoxToPutFocusOn}.

But here, my constraint is that the textbox is inside a user control that is inside my window.

How can my window set focus to this textbox?

To illustrate, here are my 2 files:

MyWindow.xaml

<Window
xmlns:wpf="clr-namespace:MyWPFNamespace">
    <StackPanel>
        <TextBlock>Sample text</TextBlock>
        <wpf:SpecialTextBox/>
    </StackPanel>
</Window>

SpecialTextBox.xaml

<UserControl
    x:Class="MyWPFNamespace.SpecialTextBox"
    x:Name="SpecialName">
    <TextBox
        x:Name="TextBoxToPutFocusOn" />
</UserControl>

Thank you


问:
Verilog ICE40 LED Driver as IO - SB_IO_OD, how to assign
New to verilog here.

The Ice40 has an RGB led driver that can also be assigned as a normal IO.

Trying to access the pin without setting it as IO will give this error one IceCube2

Error during constrained IO placement E2792: Instance
ipInertedIOPad_LED_B incorrectly constrained at SB_IO_OD location

To do so, the following verilog is used:

```<code>    SB_IO_OD #(             // open drain IP instance
    .PIN_TYPE(6'b011001)  // configure as output
    ) pin_out_driver (
    .PACKAGEPIN(LED_B), // connect to this pin
    .DOUT0(ledb)           // output the state of "led"
    );
</code>```

So the final verilog code looks like (simplified to 1 led):

```<code>module top (output LED_R, output LED_G, output LED_B);

    reg ledb = 0;

    reg [3:0] cnt;

    SB_IO_OD #(             // open drain IP instance
    .PIN_TYPE(6'b011001)  // configure as output
    ) pin_out_driver (
    .PACKAGEPIN(LED_B), // connect to this pin
    .DOUT0(ledb)           // output the state of "led"
    );

    always
    begin
        ledb = ~cnt[2];
    end

    always @(posedge clkout)
    begin
        cnt <= cnt + 1;
    end

endmodule
</code>```

and it does work.

However, I assign the led in an always block, which is sequential as I understand. Would the "correct" way to assign ledb as a wire, but then it is not compatible with the SB_IO_OD.

Is this the correct way to do it, or there is a non-sequential way to assign the led, basically not assigning in the always block.

答:
After some digging, I believe this is the correct way. It also uses much less logic cells

Working code on IceCube2, simple LED blinker:

```<code>module top (output LED_R, output LED_G, output LED_B);

wire [2:0] leds;
reg [2:0] cnt;

SB_IO_OD #(             // open drain IP instance
.PIN_TYPE(6'b011001)  // configure as output
) pin_out_driver (
.PACKAGEPIN(LED_B), // connect to this pin
.DOUT0(leds[0])           // output the state of "led"
);

SB_IO_OD #(             // open drain IP instance
.PIN_TYPE(6'b011001)  // configure as output
) pin_out_driver2 (
.PACKAGEPIN(LED_G), // connect to this pin
.DOUT0(leds[1])           // output the state of "led"
);

SB_IO_OD #(             // open drain IP instance
.PIN_TYPE(6'b011001)  // configure as output
) pin_out_driver3 (
.PACKAGEPIN(LED_R), // connect to this pin
.DOUT0(leds[2])           // output the state of "led"
);

wire sysclk;

SB_HFOSC #(.CLKHF_DIV("0b00")) osc (
.CLKHFEN(1'b1),
.CLKHFPU(1'b1),
.CLKHF(sysclk)
) /* synthesis ROUTE_THROUGH_FABRIC = 0 */;

wire clkout;
clockdivider #(.bits(28)) div(
.clkin(sysclk),
.clkout(clkout),
.div(28'd48000000)
);

assign leds  = {~cnt[2:0]};

always @(posedge clkout)
begin
    cnt <= cnt + 1;
end

endmodule
</code>```

Body:
New to verilog here.

The Ice40 has an RGB led driver that can also be assigned as a normal IO.

Trying to access the pin without setting it as IO will give this error one IceCube2

Error during constrained IO placement E2792: Instance
ipInertedIOPad_LED_B incorrectly constrained at SB_IO_OD location

To do so, the following verilog is used:

    SB_IO_OD #(             // open drain IP instance
    .PIN_TYPE(6'b011001)  // configure as output
    ) pin_out_driver (
    .PACKAGEPIN(LED_B), // connect to this pin
    .DOUT0(ledb)           // output the state of "led"
    );

So the final verilog code looks like (simplified to 1 led):

module top (output LED_R, output LED_G, output LED_B);

    reg ledb = 0;

    reg [3:0] cnt;

    SB_IO_OD #(             // open drain IP instance
    .PIN_TYPE(6'b011001)  // configure as output
    ) pin_out_driver (
    .PACKAGEPIN(LED_B), // connect to this pin
    .DOUT0(ledb)           // output the state of "led"
    );

    always
    begin
        ledb = ~cnt[2];
    end

    always @(posedge clkout)
    begin
        cnt <= cnt + 1;
    end

endmodule

and it does work.

However, I assign the led in an always block, which is sequential as I understand. Would the "correct" way to assign ledb as a wire, but then it is not compatible with the SB_IO_OD.

Is this the correct way to do it, or there is a non-sequential way to assign the led, basically not assigning in the always block.

Body:
After some digging, I believe this is the correct way. It also uses much less logic cells

Working code on IceCube2, simple LED blinker:

module top (output LED_R, output LED_G, output LED_B);

wire [2:0] leds;
reg [2:0] cnt;

SB_IO_OD #(             // open drain IP instance
.PIN_TYPE(6'b011001)  // configure as output
) pin_out_driver (
.PACKAGEPIN(LED_B), // connect to this pin
.DOUT0(leds[0])           // output the state of "led"
);

SB_IO_OD #(             // open drain IP instance
.PIN_TYPE(6'b011001)  // configure as output
) pin_out_driver2 (
.PACKAGEPIN(LED_G), // connect to this pin
.DOUT0(leds[1])           // output the state of "led"
);

SB_IO_OD #(             // open drain IP instance
.PIN_TYPE(6'b011001)  // configure as output
) pin_out_driver3 (
.PACKAGEPIN(LED_R), // connect to this pin
.DOUT0(leds[2])           // output the state of "led"
);

wire sysclk;

SB_HFOSC #(.CLKHF_DIV("0b00")) osc (
.CLKHFEN(1'b1),
.CLKHFPU(1'b1),
.CLKHF(sysclk)
) /* synthesis ROUTE_THROUGH_FABRIC = 0 */;

wire clkout;
clockdivider #(.bits(28)) div(
.clkin(sysclk),
.clkout(clkout),
.div(28'd48000000)
);

assign leds  = {~cnt[2:0]};

always @(posedge clkout)
begin
    cnt <= cnt + 1;
end

endmodule


问:
Laravel what does the session table column "payload" contain, and how can I access this data?
I grabbed the only value from my sessions table locally, it is me I'm the only logged in user.

```<code>$data = DB::table('sessions')->get();
</code>```

If I return the base64_decoded payload:

```<code>    return  base64_decode($data[0]->payload);
</code>```

I get what looks like encrypted json.

```<code>a:5:{s:6:"_token";s:40:"IlIvr7p3qxeMRg0NxSaITHvIZ1c2HGCh5QSj8wIG";s:9:"_previous";a:1:{s:3:"url";s:28:"http://mytestsite.dev/index.php";}s:5:"flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}s:8:"class_id";s:2:"14";s:9:"_sf2_meta";a:3:{s:1:"u";i:1453341204;s:1:"c";i:1453331047;s:1:"l";s:1:"0";}}
</code>```

Is there a secure way to decrypt this JSON to retrieve the user id using Laravels methods?

Upon further investigation it may be that the session table does not contain the user info, it is just used to match with the browser cookie?

If this is the case, my ultimate question is how can I reasonably determine which users are currently logged in without creating update/inserts on the user record constantly on every page load, as suggested here: Can someone explain session table laravel

_________________________UPDATE

Ok from my further research I found that the cookie in the browser is the encrypted id of the session record.

```<code>        return Crypt::decrypt($cookie);
</code>```

This leaves one final question, what does the payload column contain?

答:
In laravel 5.7
We can access payload data by

```<code>$actual = decrypt(base64_decode($payload));
</code>```

where $payload is the value of "payload" column in "sessions" table in DB.

I assume you use

```<code>SESSION_DRIVER=database
</code>```

Body:
I grabbed the only value from my sessions table locally, it is me I'm the only logged in user.

$data = DB::table('sessions')->get();

If I return the base64_decoded payload:

    return  base64_decode($data[0]->payload);

I get what looks like encrypted json.

a:5:{s:6:"_token";s:40:"IlIvr7p3qxeMRg0NxSaITHvIZ1c2HGCh5QSj8wIG";s:9:"_previous";a:1:{s:3:"url";s:28:"http://mytestsite.dev/index.php";}s:5:"flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}s:8:"class_id";s:2:"14";s:9:"_sf2_meta";a:3:{s:1:"u";i:1453341204;s:1:"c";i:1453331047;s:1:"l";s:1:"0";}}

Is there a secure way to decrypt this JSON to retrieve the user id using Laravels methods?

Upon further investigation it may be that the session table does not contain the user info, it is just used to match with the browser cookie?

If this is the case, my ultimate question is how can I reasonably determine which users are currently logged in without creating update/inserts on the user record constantly on every page load, as suggested here: Can someone explain session table laravel

_________________________UPDATE

Ok from my further research I found that the cookie in the browser is the encrypted id of the session record.

        return Crypt::decrypt($cookie);

This leaves one final question, what does the payload column contain?

Body:
In laravel 5.7
We can access payload data by

$actual = decrypt(base64_decode($payload));

where $payload is the value of "payload" column in "sessions" table in DB.

I assume you use

SESSION_DRIVER=database


问:
Efficient way to upload huge number of small files in S3
I'm encoding dash streams locally that I intend to stream through Cloudfront after, but when it comes to uploading the whole folder it get counted as +4000 PUT requests. So, I thought instead to compress it and upload the zip folder that would count as only 1 PUT request, and then Unzip it using lambda.

My question is, is lambda still going to use the PUT requests for unzipping the file ? And if so, what would be a better/cost effective way to achieve this ?

答:
No, there is no way around having to pay for the individual PUT/POST requests per-file.

S3 is expensive.  So is anything related to video streaming.  The bandwidth and storage costs will eclipse your HTTP request costs.  You might consider a more affordable provider.  AWS is the highest price out of all that do S3-compatible hosting.


问:
Why do I keep receiving an EOF error for my code?
I'm trying to solve this problem, but I keep running into the same EOF error and I'm stumped.

Here is the problem:

Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Done", "done", or "d" for the line of text.

Essentially if the user types in:

Hello

Hey

done

The output should be:

olleH

yeH

Here is my code:

```<code>user_inp = input()

while not (user_inp == 'done' or user_inp == 'Done' or user_inp == 'd'):

    for i in range(len(user_inp)):
        i += 1
        print(user_inp[-i], end='')

    if i == len(user_inp):
        print()
        user_inp = input() #EOF error here
</code>```

If I remove the user_inp = input() at the end of my code, then the code runs the first user_inp endlessly, but that's the line that gives me the EOF error.

答:
I'm sure this is too late for the asker, but for anyone else curious this is how I resolved it. I submitted this to zybooks too.</p>
```<code>message = input()

while (message != 'done' and message != 'Done' and message != 'd'):
    for i in range(len(message)):
         i += 1
         print(message[-i], end='')

    if i == len(message):
        print()
        message = input()
</code>```

Body:
I'm trying to solve this problem, but I keep running into the same EOF error and I'm stumped.

Here is the problem:

Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Done", "done", or "d" for the line of text.

Essentially if the user types in:

Hello

Hey

done

The output should be:

olleH

yeH

Here is my code:

user_inp = input()

while not (user_inp == 'done' or user_inp == 'Done' or user_inp == 'd'):

    for i in range(len(user_inp)):
        i += 1
        print(user_inp[-i], end='')

    if i == len(user_inp):
        print()
        user_inp = input() #EOF error here

If I remove the user_inp = input() at the end of my code, then the code runs the first user_inp endlessly, but that's the line that gives me the EOF error.

Body:
I'm sure this is too late for the asker, but for anyone else curious this is how I resolved it. I submitted this to zybooks too.

message = input()

while (message != 'done' and message != 'Done' and message != 'd'):
    for i in range(len(message)):
         i += 1
         print(message[-i], end='')

    if i == len(message):
        print()
        message = input()


问:
create-react-app bash: /usr/local/bin/create-react-app: No such file or directory
I had an origonal problem that I tried to fix and got another problem

1. ORIGONAL PROBLEM
I just tried to install a new react app using create-react-app and got this error first

```<code>Please note that global installs of create-react-app are no longer supported.
</code>```

The node modules were installed but none of the other files or directories that normally install.

2. What I did to fix Origonal problem
on the react app website it https://create-react-app.dev/docs/getting-started/  it was suggested that I do the following (which I did)

"If you've previously installed create-react-app globally via npm install -g create-react-app, we recommend you uninstall the package using npm uninstall -g create-react-app to ensure that npx always uses the latest version."

I tried to run the command npm uninstall -g create-react-app  but could not do it as my mac prevented it so ran sudo  npm uninstall -g create-react-app

3. New PROBLEM

When I now run create-react-app I get the message

```<code>bash: /usr/local/bin/create-react-app: No such file or directory
TDI-MacBook-Air:Active bob$
</code>```

What do I need to do to get create react App back. I am worried about messing up my installation more so am hesitant to go at it without some advice

答: This solved my error Just simply run npx create-react-app app_name to create your app. npx will fetch the latest version of create-react-app and setup your app.

Body:
I had an origonal problem that I tried to fix and got another problem

1. ORIGONAL PROBLEM
I just tried to install a new react app using create-react-app and got this error first

Please note that global installs of create-react-app are no longer supported.

The node modules were installed but none of the other files or directories that normally install.

2. What I did to fix Origonal problem
on the react app website it https://create-react-app.dev/docs/getting-started/  it was suggested that I do the following (which I did)

"If you've previously installed create-react-app globally via npm install -g create-react-app, we recommend you uninstall the package using npm uninstall -g create-react-app to ensure that npx always uses the latest version."

I tried to run the command npm uninstall -g create-react-app  but could not do it as my mac prevented it so ran sudo  npm uninstall -g create-react-app

3. New PROBLEM

When I now run create-react-app I get the message

bash: /usr/local/bin/create-react-app: No such file or directory
TDI-MacBook-Air:Active bob$

What do I need to do to get create react App back. I am worried about messing up my installation more so am hesitant to go at it without some advice


问:
Get an access token to Sharepoint and GraphAPI
I'd like to access both the Sharepoint Rest API and the GraphAPI using an access token acquired using the MSAL.js library.

I always get Exception of type 'Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException' was thrown.
On Sharepoint though.

How can I acquire 2 access tokens (one for Sharepoint one for Graph)?

This is my current authentication flow:

This is my current config in Azure:

答:
You seem to be using the default scopes, which is probably not what you want in case of SharePoint (you have not specified the scopes at all). BTW, looking at your app configuration, you seem to be not using graph api at all (scopes "openid" and "profile" are not exactly graph scopes, they are just openid scopes, even though they are listed under "graph" group). So assuming you have configuration like this:

const msalConfig = {
  auth: {
    <whatever>
    authority: "https://login.microsoftonline.com/<YOURDOMAIN>.onmicrosoft.com",
  }
}
```
<p>For accessing SharePoint, use the SharePoint scopes (this is important, or otherwise you'll get the "AudienceUriValidationFailedException"):</p>
<pre class="lang-js prettyprint-override"><code>const silentRequest = {
   <whatever>,
   scopes: ["https://<YOURDOMAIN>.sharepoint.com/AllSites.FullControl"]
}

const request = {
   <whatever>,
   scopes: ["https://<YOURDOMAIN>.sharepoint.com/AllSites.FullControl"]
}
</code>```

There is also "https://<YOURDOMAIN>.sharepoint.com/.default" to go for all scopes you have in the app registration. In your case, it does not seem to matter because you are asking for the highest access level possible anyway (full control).

Note: as far as I know, you cannot mix the scope "types", i.e. the following will not work (trying to get a token that would be suitable to read user profile using graph api and access SharePoint at the same time):

scopes: ["User.Read", "https://<YOURDOMAIN>.sharepoint.com/AllSites.FullControl"]

In case you want to call both graph and "specific" API such as SharePoint or DevOps API for example, you need to get two separate tokens, i.e. make two calls, one for "User.Read" and another for "https://<YOURDOMAIN>.sharepoint.com/AllSites.FullControl". In your case, it also does not matter because it looks you don't to need the graph api access at all.

Also, to access SharePoint, you can use the awesome pnpjs library, it can be easily configured to be used with MSAL as well: https://pnp.github.io/pnpjs/authentication/msaljsclient/#calling-sharepoint-via-msal

Body:
You seem to be using the default scopes, which is probably not what you want in case of SharePoint (you have not specified the scopes at all). BTW, looking at your app configuration, you seem to be not using graph api at all (scopes "openid" and "profile" are not exactly graph scopes, they are just openid scopes, even though they are listed under "graph" group). So assuming you have configuration like this:

const msalConfig = {
  auth: {
    <whatever>
    authority: "https://login.microsoftonline.com/<YOURDOMAIN>.onmicrosoft.com",
  }
}

For accessing SharePoint, use the SharePoint scopes (this is important, or otherwise you'll get the "AudienceUriValidationFailedException"):

const silentRequest = {
   <whatever>,
   scopes: ["https://<YOURDOMAIN>.sharepoint.com/AllSites.FullControl"]
}

const request = {
   <whatever>,
   scopes: ["https://<YOURDOMAIN>.sharepoint.com/AllSites.FullControl"]
}

There is also "https://<YOURDOMAIN>.sharepoint.com/.default" to go for all scopes you have in the app registration. In your case, it does not seem to matter because you are asking for the highest access level possible anyway (full control).

Note: as far as I know, you cannot mix the scope "types", i.e. the following will not work (trying to get a token that would be suitable to read user profile using graph api and access SharePoint at the same time):

scopes: ["User.Read", "https://<YOURDOMAIN>.sharepoint.com/AllSites.FullControl"]

In case you want to call both graph and "specific" API such as SharePoint or DevOps API for example, you need to get two separate tokens, i.e. make two calls, one for "User.Read" and another for "https://<YOURDOMAIN>.sharepoint.com/AllSites.FullControl". In your case, it also does not matter because it looks you don't to need the graph api access at all.

Also, to access SharePoint, you can use the awesome pnpjs library, it can be easily configured to be used with MSAL as well: https://pnp.github.io/pnpjs/authentication/msaljsclient/#calling-sharepoint-via-msal


问:
Twilio Friendly Verification From Name
I am using the Verification service and all working fine. My Service Name appears in the body of the Verification message correctly but how can I change the SMS From label?

In my SMS app I see a list of messages from various contacts and companies, the message from Twilio Verification Service shows as a 5 digit code e.g 12345. How can I change that from 12345 to "MyService"?

I get messages from other companies and a short company name appears as a contact name, how can I do the same with my twilio verification service?

Thanks

答:
Twilio developer evangelist here.

Twilio Verify uses a variety of short codes, alphanumeric sender IDs and other phone numbers in order to send the verification messages around the world. The Verify team work on ensuring the numbers/sender IDs have the best possible delivery by pre-registering them in various countries. This gives you the highest possible chances of getting authentication messages delivered swiftly. You can't customise the number by default.

If you are looking to customise the number that is used, I would recommend you talk to the Twilio sales team to see what you can arrange.

Title: Twilio Friendly Verification From Name


问:
Perl advice - Taking in a file and changing contents
I have a request for some advice on how to approach this script I want to write in Perl. Basically I have a file that looks like :

```<code>  id: 1
  Relationship: ""
  name: shelby
  pet: 1
  color:4
</code>```

There are certain keywords such as pet and color that have numbers after then. I want to be able to take in a file and look for these keywords (there are 5 or 6 of them) and then change the number to the word that number corresponds to. That is to say for the keyword "Pet"---> 0 =dog, 1 = cat, 2=fish. And for the keyword "color" 0 = red, 1=blue,2=purple,3=brown,4=white. The script should find and change these numbers. The goal should be an output file that looks like:

```<code>      id: 1
      Relationship: ""
      name: shelby
      pet: cat
      color:white
</code>```

I've been struggling with how to do this for a while. I looked up online maybe I could do an array of hashes or something but I'm relatively new to Perl and don't know exactly how to even approach this problem.... Any advice would be much appreciated!

Thanks

答:
Usage: script.pl file.txt > output.txt

```<code>use strict;
use warnings;

my %tags = (
    "pet" => [ qw(dog cat fish) ],
    "color" => [ qw(red blue purple brown white) ],
);

my $rx = join '|', keys %tags;

while (<>) {
    s/^\s*($rx):\s*(\d+)/$1: $tags{$1}[$2]/;
    print;
}
</code>```

Body:
I have a request for some advice on how to approach this script I want to write in Perl. Basically I have a file that looks like :

  id: 1
  Relationship: ""
  name: shelby
  pet: 1
  color:4

There are certain keywords such as pet and color that have numbers after then. I want to be able to take in a file and look for these keywords (there are 5 or 6 of them) and then change the number to the word that number corresponds to. That is to say for the keyword "Pet"---> 0 =dog, 1 = cat, 2=fish. And for the keyword "color" 0 = red, 1=blue,2=purple,3=brown,4=white. The script should find and change these numbers. The goal should be an output file that looks like:

      id: 1
      Relationship: ""
      name: shelby
      pet: cat
      color:white

I've been struggling with how to do this for a while. I looked up online maybe I could do an array of hashes or something but I'm relatively new to Perl and don't know exactly how to even approach this problem.... Any advice would be much appreciated!

Thanks

Body:
Usage: script.pl file.txt > output.txt

use strict;
use warnings;

my %tags = (
    "pet" => [ qw(dog cat fish) ],
    "color" => [ qw(red blue purple brown white) ],
);

my $rx = join '|', keys %tags;

while (<>) {
    s/^\s*($rx):\s*(\d+)/$1: $tags{$1}[$2]/;
    print;
}


问:
How do I install a pip package globally instead of locally?
I am trying to install flake8 package using pip3 and it seems that it refuses to install because is already installed in one local location.

How can I force it to install globally (system level)?

```<code>pip3 install flake8
Requirement already satisfied (use --upgrade to upgrade): flake8 in ./.local/lib/python3.4/site-packages
</code>```

Please note that I would prefer a generic solution (that should work on Debian, OS X maybe even Windows), one that should be used on any platform so I don't want to specify the destination myself.

For some weird reason it behaves like I already specified --user which in my case I didn't.

The only way I was able to install a package globally was to first remove it and install it again after this. Somehow it seems that pip (8.1.1) refuses to install a package globally if it exists locally.

Disclaimer: No virtual environments were used or harmed during the experiments.

答:
For windows 10:

Installing Python for all users is straight forward since when you install you have to click a checkbox for all users.

In order to install modules globally under C:\Program Files\Python310\Lib\site-packages
start CMD prompt as administrator and then install modules

```<code>python -m pip install selenium
</code>```

Body:
I am trying to install flake8 package using pip3 and it seems that it refuses to install because is already installed in one local location.

How can I force it to install globally (system level)?

pip3 install flake8
Requirement already satisfied (use --upgrade to upgrade): flake8 in ./.local/lib/python3.4/site-packages

Please note that I would prefer a generic solution (that should work on Debian, OS X maybe even Windows), one that should be used on any platform so I don't want to specify the destination myself.

For some weird reason it behaves like I already specified --user which in my case I didn't.

The only way I was able to install a package globally was to first remove it and install it again after this. Somehow it seems that pip (8.1.1) refuses to install a package globally if it exists locally.

Disclaimer: No virtual environments were used or harmed during the experiments.

Body:
For windows 10:

Installing Python for all users is straight forward since when you install you have to click a checkbox for all users.

In order to install modules globally under C:\Program Files\Python310\Lib\site-packages
start CMD prompt as administrator and then install modules

python -m pip install selenium


问:
Backslash vs. Forward slash in Java
Why does there need to be a forward slash in the path to the class file when using Windows Command Prompt?

Input:

C:\javafun>java --module-path C:\javafun\mod --module jdojo.intro/com.jdojo.intro.Welcome

Output:

Welcome to Java 17!

I've read that when running .jar files there needs to be a forward slash, but I've created a modular .jar file in C:\javafun\lib directory. Here I am just trying to go straight to the .class file in the C:\javafun\mod\jdojo.intro\com\jdojo\intro\Welcome.class

Why when I change the below to a backslash when using Windows I get the following error? This is confusing to know when to use specific slashes when dealing with file locations, packages or directories.

Input:

C:\javafun>java --module-path C:\javafun\mod --module jdojo.intro\com.jdojo.intro.Welcome

Output:

Error occurred during initialization of boot layer
java.lang.module.FindException: Module jdojo.intro\com.jdojo.intro.Welcome not found

答:
In Windows, file paths need to use the backslash as a separator.  However, this is not a file path:

```<code>--module jdojo.intro\com.jdojo.intro.Welcome
</code>```

The forward slash is a designated separator, on all platforms, between the module name and the class name.

The fact that, on non-Windows systems, file paths happen to use the forward slash character as a directory separator, but it’s a different character in Windows, does not mean that all non-file uses of the forward slash will also be different on Windows.

In fact, the documentation for the java command explicitly states that the character between the module name and the class name must be a forward slash:

To launch the main class in a module:

java [options] -m module[/mainclass] [args ...]

or

java [options] --module module[/mainclass] [args ...]

No matter what platform you’re running on, the character between a module name and a class name is a forward slash, because it’s not a file name and therefore is not platform dependent.

Title: Backslash vs. Forward slash in Java

Body:
In Windows, file paths need to use the backslash as a separator.  However, this is not a file path:

--module jdojo.intro\com.jdojo.intro.Welcome

The forward slash is a designated separator, on all platforms, between the module name and the class name.

The fact that, on non-Windows systems, file paths happen to use the forward slash character as a directory separator, but it’s a different character in Windows, does not mean that all non-file uses of the forward slash will also be different on Windows.

In fact, the documentation for the java command explicitly states that the character between the module name and the class name must be a forward slash:

To launch the main class in a module:

java [options] -m module[/mainclass] [args ...]

or

java [options] --module module[/mainclass] [args ...]

No matter what platform you’re running on, the character between a module name and a class name is a forward slash, because it’s not a file name and therefore is not platform dependent.


问:
List all records that were inserted during specific time of each day in datetime field
Would like to write a query that will list only the records, that were inserted between 8.00 PM and 11:59 PM for that day.

Note: The uploaddate field contains both date and time. Thus, the record could be inserted days earlier or later. I'm interested in filtering only records that was inserted on that day between 8.00 PM and 11.59 PM.

The uploadtime is available in the field uploaddate. I'm able to do it for a single day and also able to do it over multiple days using R/Python code.

In the above example, only the highlighted record should be include and the rest should be excluded.

Query to list for a single day.

```<code>select *
from dbo.table
where t = '20220204'
  and uploaddate between '2022-02-04 20:00:00' and '2022-02-04 23:59:00'
  and uploaddate is not null
order by uploaddate desc
</code>```

R code to list for multiple days

```<code>thisDate = Sys.Date()
currentDate = as.Date('2021-01-01', format("%Y-%m-%d"))
allRows = NULL
while ( currentDate < thisDate) {
  if ( format(currentDate, "%u") < 6 ) {
    thisDateStr = as.numeric(format(currentDate,"%Y"))*10000+as.numeric(format(currentDate,"%m"))*100+as.numeric(format(currentDate,"%d"))
    uploadDateStart = paste0(format(currentDate, format = "%Y-%m-%d") , " 20:00:00", sep="")
    uploadDateEnd= paste0(format(currentDate, format = "%Y-%m-%d") , " 23:59:00", sep="")
    query = paste0("select * from dbo.table where t = '", thisDateStr,"' and uploaddate is not null and uploaddate between '", uploadDateStart, "' and '", uploadDateEnd , "' order by uploaddate desc ", sep="")
    rowsToAdd =sqlQuery(dbhandle_prod,daily_market_data_query)
    if ( nrow(daily_market_data_results) > 0 ) {
      allRows = rbind(allRows, rowsToAdd )
    }
  }
  currentDate = currentDate + 1
}
</code>```

Wondering, if it is possible to do it in SQL Server without having to write R/Python code.

答:
It seems you just want to ensure that uploaddate is on the same day as t, and after 20:00:00. So you can just check that using date artithmetic

```<code>SELECT
  *
FROM dbo.[table] t
WHERE t.uploaddate >= DATEADD(hour, 20, CAST(t as datetime))
  AND t.uploaddate < DATEADD(day, 1, CAST(t as datetime))
ORDER BY
  uploaddate DESC;
</code>```

If t is already a datetime value you can remove the two casts.

Body:
Would like to write a query that will list only the records, that were inserted between 8.00 PM and 11:59 PM for that day.

Note: The uploaddate field contains both date and time. Thus, the record could be inserted days earlier or later. I'm interested in filtering only records that was inserted on that day between 8.00 PM and 11.59 PM.

The uploadtime is available in the field uploaddate. I'm able to do it for a single day and also able to do it over multiple days using R/Python code.

In the above example, only the highlighted record should be include and the rest should be excluded.

Query to list for a single day.

select *
from dbo.table
where t = '20220204'
  and uploaddate between '2022-02-04 20:00:00' and '2022-02-04 23:59:00'
  and uploaddate is not null
order by uploaddate desc

R code to list for multiple days

thisDate = Sys.Date()
currentDate = as.Date('2021-01-01', format("%Y-%m-%d"))
allRows = NULL
while ( currentDate < thisDate) {
  if ( format(currentDate, "%u") < 6 ) {
    thisDateStr = as.numeric(format(currentDate,"%Y"))*10000+as.numeric(format(currentDate,"%m"))*100+as.numeric(format(currentDate,"%d"))
    uploadDateStart = paste0(format(currentDate, format = "%Y-%m-%d") , " 20:00:00", sep="")
    uploadDateEnd= paste0(format(currentDate, format = "%Y-%m-%d") , " 23:59:00", sep="")
    query = paste0("select * from dbo.table where t = '", thisDateStr,"' and uploaddate is not null and uploaddate between '", uploadDateStart, "' and '", uploadDateEnd , "' order by uploaddate desc ", sep="")
    rowsToAdd =sqlQuery(dbhandle_prod,daily_market_data_query)
    if ( nrow(daily_market_data_results) > 0 ) {
      allRows = rbind(allRows, rowsToAdd )
    }
  }
  currentDate = currentDate + 1
}

Wondering, if it is possible to do it in SQL Server without having to write R/Python code.

Body:
It seems you just want to ensure that uploaddate is on the same day as t, and after 20:00:00. So you can just check that using date artithmetic

SELECT
  *
FROM dbo.[table] t
WHERE t.uploaddate >= DATEADD(hour, 20, CAST(t as datetime))
  AND t.uploaddate < DATEADD(day, 1, CAST(t as datetime))
ORDER BY
  uploaddate DESC;

If t is already a datetime value you can remove the two casts.


问:
Possible to detect when arithmetic overflow would occur before POWER(x,y) is executed?
Example:

```<code>-- inputs
declare @x decimal(28,10) = 10001.0
declare @y decimal(18,6) = 7.0

-- later on, inside a udf
select POWER(@x, @y)
</code>```

Result:

Msg 8115, Level 16, State 6, Line 13

Arithmetic overflow error converting float to data type numeric.

I understand why the overflow is occurring. My question is, is it possible to detect,
just before POWER is executed, whether the overflow would occur? Note that the code is run inside a UDF, so cannot use TRY...CATCH. If I can detect it in advance, I can take avoiding action (e.g. return NULL for the result, which is suitable for my requirements).

答:
You could use Try-Catch or you could use a formula to predict the output digits and return NULL instead. Formula to predict number of digits from here

Predict Number of Digits of Power Function

```<code>Declare @Num DECIMAL(28,10) = 10001
    ,@Exponent DECIMAL(28,10) = 7
    ,@NumOfDigits INT

/*Predict number of digits from power function*/
SELECT @NumOfDigits = FLOOR(1 + @exponent* CAST(LOG(@Num,10) AS DECIMAL(38,10)))

SELECT
    CASE WHEN @NumOfDigits <= 38 /*Max decimal precision, return type from POWER function according to https://learn.microsoft.com/en-us/sql/t-sql/functions/power-transact-sql?view=sql-server-ver15*/
              - 10 /*Scale of @Num. Need to leave enough digits to record decimal places*/
        THEN POWER(@Num,@Exponent) /*If less than or equal to precision, return value*/
    ELSE NULL /*If outside precision, just returns NULL. Could update to return something else*/
END
</code>```

Body:
Example:

-- inputs
declare @x decimal(28,10) = 10001.0
declare @y decimal(18,6) = 7.0

-- later on, inside a udf
select POWER(@x, @y)

Result:

Msg 8115, Level 16, State 6, Line 13

Arithmetic overflow error converting float to data type numeric.

I understand why the overflow is occurring. My question is, is it possible to detect,
just before POWER is executed, whether the overflow would occur? Note that the code is run inside a UDF, so cannot use TRY...CATCH. If I can detect it in advance, I can take avoiding action (e.g. return NULL for the result, which is suitable for my requirements).

Body:
You could use Try-Catch or you could use a formula to predict the output digits and return NULL instead. Formula to predict number of digits from here

Predict Number of Digits of Power Function

Declare @Num DECIMAL(28,10) = 10001
    ,@Exponent DECIMAL(28,10) = 7
    ,@NumOfDigits INT

/*Predict number of digits from power function*/
SELECT @NumOfDigits = FLOOR(1 + @exponent* CAST(LOG(@Num,10) AS DECIMAL(38,10)))

SELECT
    CASE WHEN @NumOfDigits <= 38 /*Max decimal precision, return type from POWER function according to https://learn.microsoft.com/en-us/sql/t-sql/functions/power-transact-sql?view=sql-server-ver15*/
              - 10 /*Scale of @Num. Need to leave enough digits to record decimal places*/
        THEN POWER(@Num,@Exponent) /*If less than or equal to precision, return value*/
    ELSE NULL /*If outside precision, just returns NULL. Could update to return something else*/
END


问:
Refresh StatefulBuilder Dialog without using onPressed
I need to update the text of my dialog while my report is loading. setState doest not work here.

```<code>class ReportW extends StatefulWidget {
  const ReportW({Key key}) : super(key: key);

  @override
  _ReportWState createState() => _ReportWState();
}

class _ReportWState extends State<ReportMenuDownloadW> {

  String loadingText;

  void updateLoadingText(text){
    setState(() {loadingText = text;});
  }

  @override
  Widget build(BuildContext context) {

    return MyWidget(
      label:REPORT_LABEL,
      onTap: () async {
        showDialog(context: context,
            builder: (BuildContext context) {
              return StatefulBuilder(
                  builder: (context, setState) {
                    return Dialog(
                      child: Column(
                        children: [
                          CircularProgressIndicator(),
                          Text(loadingText),
                        ],
                      ),
                    );});
            });
        await loadPDF(context,updateLoadingText);
        Navigator.pop(context);
      },
    );
  }
}
</code>```

Is there an alternative solution if it is not possible ? I just need a progress text indicator over my screen while loading.

答:
In your case you can use GlobalKey. For your code:

Define globalKey inside your widget:

```<code>// Global key for dialog
final GlobalKey _dialogKey = GlobalKey();
</code>```

Set globalKey for your StatefulBuilder:

```<code>return StatefulBuilder(
  key: _dialogKey,
  builder: (context, setState) {
    return Dialog(
      child: Column(
        children: [
          CircularProgressIndicator(),
          Text(loadingText),
        ],
      ),
    );
  },
);
</code>```

Now you can update UI of your dialog like this:

```<code>void updateLoadingText(text) {
  // Check if dialog displayed, we can't call setState when dialog not displayed
  if (_dialogKey.currentState != null && _dialogKey.currentState!.mounted) {
    _dialogKey.currentState!.setState(() {
      loadingText = text;
    });
  }
}
</code>```

Pay attention, you get unexpected behavior if user will close dialog manually.

How to prevent closing dialog by user: in showDialog use barrierDismissible: false and also wrap your dialog to WillPopScope with onWillPop: () async {return false;}

Possible question:
Why we check _dialogKey.currentState != null?
Because opening dialog and set globalKey take some time and while it's not opened currentState is null. If updateLoadingText will be call before dialog will be open, we shouldn't update UI for dialog.

Full code of your widget:

```<code>class OriginalHomePage extends StatefulWidget {
  OriginalHomePage({Key? key}) : super(key: key);

  @override
  _OriginalHomePageState createState() => _OriginalHomePageState();
}

class _OriginalHomePageState extends State<OriginalHomePage> {
  String loadingText = "Start";

  // Global key for dialog
  final GlobalKey _dialogKey = GlobalKey();

  void updateLoadingText(text) {
    // Check if dialog displayed, we can't call setState when dialog not displayed
    if (_dialogKey.currentState != null && _dialogKey.currentState!.mounted) {
      _dialogKey.currentState!.setState(() {
        loadingText = text;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () async {
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return StatefulBuilder(
              key: _dialogKey,
              builder: (context, setState) {
                return Dialog(
                  child: Column(
                    children: [
                      CircularProgressIndicator(),
                      Text(loadingText),
                    ],
                  ),
                );
              },
            );
          },
        );
        await loadPDF(context, updateLoadingText);
        Navigator.pop(context);
      },
      child: Text("Open"),
    );
  }
}

</code>```

Also i rewrote your code a bit, it seems to me more correct:

```<code>class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          child: Text("Open"),
          onPressed: () => _showDialog(),
        ),
      ),
    );
  }

  // Global key for dialog
  final GlobalKey _dialogKey = GlobalKey();

  // Text for update in dialog
  String _loadingText = "Start";

  _showDialog() async {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return WillPopScope(
          onWillPop: () async {
            return false;
          },
          child: StatefulBuilder(
            key: _dialogKey,
            builder: (context, setState) {
              return Dialog(
                child: Padding(
                  padding: EdgeInsets.all(8),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      CircularProgressIndicator(),
                      Text(_loadingText),
                    ],
                  ),
                ),
              );
            },
          ),
        );
      },
    );

    // Call some function from service
    await myLoadPDF(context, _setStateDialog);

    // Close dialog
    Navigator.pop(context);
  }

  // Update dialog
  _setStateDialog(String newText) {
    // Check if dialog displayed, we can't call setState when dialog not displayed
    if (_dialogKey.currentState != null && _dialogKey.currentState!.mounted) {
      _dialogKey.currentState!.setState(() {
        _loadingText = newText;
      });
    }
  }
}
</code>```

Result:

Updated dialog

Body:
I need to update the text of my dialog while my report is loading. setState doest not work here.

class ReportW extends StatefulWidget {
  const ReportW({Key key}) : super(key: key);

  @override
  _ReportWState createState() => _ReportWState();
}

class _ReportWState extends State<ReportMenuDownloadW> {

  String loadingText;

  void updateLoadingText(text){
    setState(() {loadingText = text;});
  }

  @override
  Widget build(BuildContext context) {

    return MyWidget(
      label:REPORT_LABEL,
      onTap: () async {
        showDialog(context: context,
            builder: (BuildContext context) {
              return StatefulBuilder(
                  builder: (context, setState) {
                    return Dialog(
                      child: Column(
                        children: [
                          CircularProgressIndicator(),
                          Text(loadingText),
                        ],
                      ),
                    );});
            });
        await loadPDF(context,updateLoadingText);
        Navigator.pop(context);
      },
    );
  }
}

Is there an alternative solution if it is not possible ? I just need a progress text indicator over my screen while loading.

Body:
In your case you can use GlobalKey. For your code:

Define globalKey inside your widget:

// Global key for dialog
final GlobalKey _dialogKey = GlobalKey();

Set globalKey for your StatefulBuilder:

return StatefulBuilder(
  key: _dialogKey,
  builder: (context, setState) {
    return Dialog(
      child: Column(
        children: [
          CircularProgressIndicator(),
          Text(loadingText),
        ],
      ),
    );
  },
);

Now you can update UI of your dialog like this:

void updateLoadingText(text) {
  // Check if dialog displayed, we can't call setState when dialog not displayed
  if (_dialogKey.currentState != null && _dialogKey.currentState!.mounted) {
    _dialogKey.currentState!.setState(() {
      loadingText = text;
    });
  }
}

Pay attention, you get unexpected behavior if user will close dialog manually.

How to prevent closing dialog by user: in showDialog use barrierDismissible: false and also wrap your dialog to WillPopScope with onWillPop: () async {return false;}

Possible question:
Why we check _dialogKey.currentState != null?
Because opening dialog and set globalKey take some time and while it's not opened currentState is null. If updateLoadingText will be call before dialog will be open, we shouldn't update UI for dialog.

Full code of your widget:

class OriginalHomePage extends StatefulWidget {
  OriginalHomePage({Key? key}) : super(key: key);

  @override
  _OriginalHomePageState createState() => _OriginalHomePageState();
}

class _OriginalHomePageState extends State<OriginalHomePage> {
  String loadingText = "Start";

  // Global key for dialog
  final GlobalKey _dialogKey = GlobalKey();

  void updateLoadingText(text) {
    // Check if dialog displayed, we can't call setState when dialog not displayed
    if (_dialogKey.currentState != null && _dialogKey.currentState!.mounted) {
      _dialogKey.currentState!.setState(() {
        loadingText = text;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () async {
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return StatefulBuilder(
              key: _dialogKey,
              builder: (context, setState) {
                return Dialog(
                  child: Column(
                    children: [
                      CircularProgressIndicator(),
                      Text(loadingText),
                    ],
                  ),
                );
              },
            );
          },
        );
        await loadPDF(context, updateLoadingText);
        Navigator.pop(context);
      },
      child: Text("Open"),
    );
  }
}

Also i rewrote your code a bit, it seems to me more correct:

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          child: Text("Open"),
          onPressed: () => _showDialog(),
        ),
      ),
    );
  }

  // Global key for dialog
  final GlobalKey _dialogKey = GlobalKey();

  // Text for update in dialog
  String _loadingText = "Start";

  _showDialog() async {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return WillPopScope(
          onWillPop: () async {
            return false;
          },
          child: StatefulBuilder(
            key: _dialogKey,
            builder: (context, setState) {
              return Dialog(
                child: Padding(
                  padding: EdgeInsets.all(8),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      CircularProgressIndicator(),
                      Text(_loadingText),
                    ],
                  ),
                ),
              );
            },
          ),
        );
      },
    );

    // Call some function from service
    await myLoadPDF(context, _setStateDialog);

    // Close dialog
    Navigator.pop(context);
  }

  // Update dialog
  _setStateDialog(String newText) {
    // Check if dialog displayed, we can't call setState when dialog not displayed
    if (_dialogKey.currentState != null && _dialogKey.currentState!.mounted) {
      _dialogKey.currentState!.setState(() {
        _loadingText = newText;
      });
    }
  }
}

Result:

Updated dialog


问:
What does :& argument mean?
I don't understand the :& argument for the inject method in this example:

```<code>[1, 2].map do |id|
  my_custom_method(MyModel.find(id))
end).inject(:&).map(&:category).uniq.compact.sort
</code>```

:+ makes sense to me:

```<code>[1, 2, 3].inject(:+)
</code>```

is the same as:

```<code>[1, 2, 3].inject { |sum, number| sum + number }
</code>```

What does :& mean, as in the example above?

答:
Enumerable#inject

If you specify a symbol instead, then each element in the collection will be passed to the named method of memo

So & is just Integer#& method

Bitwise AND; each bit in the result is 1 if both corresponding bits in self and other are 1, 0 otherwise

```<code>[7, 5].inject(:&) # => 5
</code>```

It's the same as

```<code>7 & 5 # => 5
</code>```

And how it works

```<code>7.to_s(2) # => "111"
5.to_s(2) # => "101"
</code>```
```<code>7: 1 1 1
   & & &
5: 1 0 1
--------
5: 1 0 1
</code>```

Title: What does :& argument mean?

Body:
I don't understand the :& argument for the inject method in this example:

[1, 2].map do |id|
  my_custom_method(MyModel.find(id))
end).inject(:&).map(&:category).uniq.compact.sort

:+ makes sense to me:

[1, 2, 3].inject(:+)

is the same as:

[1, 2, 3].inject { |sum, number| sum + number }

What does :& mean, as in the example above?

Body:
Enumerable#inject

If you specify a symbol instead, then each element in the collection will be passed to the named method of memo

So & is just Integer#& method

Bitwise AND; each bit in the result is 1 if both corresponding bits in self and other are 1, 0 otherwise

[7, 5].inject(:&) # => 5

It's the same as

7 & 5 # => 5

And how it works

7.to_s(2) # => "111"
5.to_s(2) # => "101"

7: 1 1 1
   & & &
5: 1 0 1
--------
5: 1 0 1