问:
Failed to generate dataobject with mybatis generator（Error Info：Communications link failure）
I'm a rookie in JAVA, and I'm searching for a long time on net. But the answer didn't work. Please help or try to give some ideas how to achieve this.

Firstly I'll show the version infomation:

JAVA：1.8.0_321
MySQL:5.7.37
mysql-connector-java:5.1.46
Maven:3.8.1
Windows 11

Next it's the configuration information about mybatis generator:

Mybatis generator related insettings.xml:

```<code><localRepository>D:\桌面\qzh\repository</localRepository>
</code>```

Mybatis generator related in pom.xml:

```<code><dependencies>
    <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>

        <dependency>
            <groupId>net.sourceforge.jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6.12</version>
        </dependency>

        <dependency>
            <groupId>org.python</groupId>
            <artifactId>jython-standalone</artifactId>
            <version>2.7.0</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
</dependencies>

<build>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.7</version>
                <dependencies>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.7</version>
                    </dependency>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.46</version>
                    </dependency>
                    <dependency>
                        <groupId>tk.mybatis</groupId>
                        <artifactId>mapper</artifactId>
                        <version>3.5.3</version>
                    </dependency>
                </dependencies>

                <executions>
                    <execution>
                        <id>mybatis generator</id>
                        <phase>package</phase>
                        <!--<phase>deploy</phase>-->
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>

                <configuration>
                    <verbose>true</verbose>
                    <overwrite>false</overwrite>
                    <configurationFile>
                        src/main/resources/mybatis-generator.xml
                    </configurationFile>
                </configuration>
            </plugin>

        </plugins>
</build>
</code>```

application.yml:

```<code>spring:
  datasource:
    druid:
      filters: stat
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/X?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2B8
      username: root
      password: 123456
</code>```

mybatis-generator.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <classPathEntry location="D:/桌面/qzh/repository/mysql/mysql-connector-java/5.1.46/mysql-connector-java-5.1.46.jar"/>

    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/X"
                        userId="root" password="123456">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <javaModelGenerator targetPackage="com.example.demo.dataobject" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="false"/>
        </javaModelGenerator>
        <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.demo.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
    </context>
</generatorConfiguration>
</code>```

When I run the command "mybatis-generator:generate -e" I got the following error:

[INFO] Error stacktraces are turned on.
[INFO] Scanning for projects...
[INFO]
[INFO] --------------------------< com.example:demo >--------------------------
[INFO] Building demo 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- mybatis-generator-maven-plugin:1.3.7:generate (default-cli) @ demo ---
[INFO] Connecting to the Database
Sun Dec 25 15:53:44 GMT+08:00 2022 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  1.134 s
[INFO] Finished at: 2022-12-25T15:53:44+08:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.7:generate (default-cli) on project demo: Communications link failure
[ERROR]
[ERROR] The last packet successfully received from the server was 283 milliseconds ago.  The last packet sent successfully to the server was 279 milliseconds ago.
[ERROR] -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.7:generate (default-cli) on project demo: Communications link failure

The last packet successfully received from the server was 283 milliseconds ago.  The last packet sent successfully to the server was 279 milliseconds ago.
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:498)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
at org.codehaus.classworlds.Launcher.main (Launcher.java:47)
Caused by: org.apache.maven.plugin.MojoExecutionException: Communications link failure

The last packet successfully received from the server was 283 milliseconds ago.  The last packet sent successfully to the server was 279 milliseconds ago.
at org.mybatis.generator.maven.MyBatisGeneratorMojo.execute (MyBatisGeneratorMojo.java:239)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:498)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
at org.codehaus.classworlds.Launcher.main (Launcher.java:47)
[ERROR]
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

I've tried to solve the problem, but what I was searching it's all about "how to connect MySQL". however, I just need to connect my local MySQL and my connection on Navicat is feasible, so I think the problem is not with MySQL.I'm looking forward to getting a right solution.

Thanks in advance.

I've tried to change the url with suffix:

```<code>?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2B8
</code>```

But error information still has a warn:

Tue Dec 27 11:23:25 GMT+08:00 2022 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

I don't know if this means the url didn't work

Body:
I'm a rookie in JAVA, and I'm searching for a long time on net. But the answer didn't work. Please help or try to give some ideas how to achieve this.

Firstly I'll show the version infomation:

JAVA：1.8.0_321
MySQL:5.7.37
mysql-connector-java:5.1.46
Maven:3.8.1
Windows 11

Next it's the configuration information about mybatis generator:

Mybatis generator related insettings.xml:

<localRepository>D:\桌面\qzh\repository</localRepository>

Mybatis generator related in pom.xml:

<dependencies>
    <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>

        <dependency>
            <groupId>net.sourceforge.jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6.12</version>
        </dependency>

        <dependency>
            <groupId>org.python</groupId>
            <artifactId>jython-standalone</artifactId>
            <version>2.7.0</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
</dependencies>

<build>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.7</version>
                <dependencies>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.7</version>
                    </dependency>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.46</version>
                    </dependency>
                    <dependency>
                        <groupId>tk.mybatis</groupId>
                        <artifactId>mapper</artifactId>
                        <version>3.5.3</version>
                    </dependency>
                </dependencies>

                <executions>
                    <execution>
                        <id>mybatis generator</id>
                        <phase>package</phase>

                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>

                <configuration>
                    <verbose>true</verbose>
                    <overwrite>false</overwrite>
                    <configurationFile>
                        src/main/resources/mybatis-generator.xml
                    </configurationFile>
                </configuration>
            </plugin>

        </plugins>
</build>

application.yml:

spring:
  datasource:
    druid:
      filters: stat
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/X?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2B8
      username: root
      password: 123456

mybatis-generator.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <classPathEntry location="D:/桌面/qzh/repository/mysql/mysql-connector-java/5.1.46/mysql-connector-java-5.1.46.jar"/>

    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/X"
                        userId="root" password="123456">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <javaModelGenerator targetPackage="com.example.demo.dataobject" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="false"/>
        </javaModelGenerator>
        <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.demo.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
    </context>
</generatorConfiguration>

When I run the command "mybatis-generator:generate -e" I got the following error:

[INFO] Error stacktraces are turned on.
[INFO] Scanning for projects...
[INFO]
[INFO] --------------------------< com.example:demo >--------------------------
[INFO] Building demo 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- mybatis-generator-maven-plugin:1.3.7:generate (default-cli) @ demo ---
[INFO] Connecting to the Database
Sun Dec 25 15:53:44 GMT+08:00 2022 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  1.134 s
[INFO] Finished at: 2022-12-25T15:53:44+08:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.7:generate (default-cli) on project demo: Communications link failure
[ERROR]
[ERROR] The last packet successfully received from the server was 283 milliseconds ago.  The last packet sent successfully to the server was 279 milliseconds ago.
[ERROR] -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.7:generate (default-cli) on project demo: Communications link failure

The last packet successfully received from the server was 283 milliseconds ago.  The last packet sent successfully to the server was 279 milliseconds ago.
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:498)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
at org.codehaus.classworlds.Launcher.main (Launcher.java:47)
Caused by: org.apache.maven.plugin.MojoExecutionException: Communications link failure

The last packet successfully received from the server was 283 milliseconds ago.  The last packet sent successfully to the server was 279 milliseconds ago.
at org.mybatis.generator.maven.MyBatisGeneratorMojo.execute (MyBatisGeneratorMojo.java:239)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:498)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
at org.codehaus.classworlds.Launcher.main (Launcher.java:47)
[ERROR]
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

I've tried to solve the problem, but what I was searching it's all about "how to connect MySQL". however, I just need to connect my local MySQL and my connection on Navicat is feasible, so I think the problem is not with MySQL.I'm looking forward to getting a right solution.

Thanks in advance.

I've tried to change the url with suffix:

?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2B8

But error information still has a warn:

Tue Dec 27 11:23:25 GMT+08:00 2022 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

I don't know if this means the url didn't work


来源: stackexchange

问:
How to enable GPU acceleration when using loudnorm filter in FFmpeg
I'm building a service to automatically normalize the loudness of audio to -16LUFS using FFmpeg, but it takes too much time to process audio using the loudnorm filter of FFmpeg. Is there any way to use loudnorm with GPU? I installed GPU-supported FFmpeg following this guide from NVIDA but do not know how to enable GPU acceleration.

My code:

```<code>ffmpeg -i /path/to/input.mp4 -af loudnorm=I=-16:dual_mono=true:TP=-1.5:LRA=11 /path/to/output.mp4
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm building a service to automatically normalize the loudness of audio to -16LUFS using FFmpeg, but it takes too much time to process audio using the loudnorm filter of FFmpeg. Is there any way to use loudnorm with GPU? I installed GPU-supported FFmpeg following this guide from NVIDA but do not know how to enable GPU acceleration.

My code:

ffmpeg -i /path/to/input.mp4 -af loudnorm=I=-16:dual_mono=true:TP=-1.5:LRA=11 /path/to/output.mp4


问:
How to load sub index.html page to localhost in cordova ios
I am working on an ios project with cordova wkwebkit.
Of course, I know that cordova recommends spa.
In the case of the main index.html file, the page was opened on localhost as shown below in config.xml.

```<code>   <content src="index.html" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />

    <platform name="ios">
        <preference name="scheme" value="app" />
        <preference name="hostname" value="localhost" />
    </platform>
</code>```

Then you can see that the result of checking in Chrome developer mode is applied successfully.

enter image description here

But in the case of the sub index.html file, I don't know how to load it on localhost.
solution is required.

Currently, we are loading the sub index.html file with the file protocol.

enter image description here

file path:
(main) index.html path : www/index.html
(sub) index.html path : www/world/wikitude_AR/inedex.html

version:
cordova  - 11
cordova ios - 6.2

Body:
I am working on an ios project with cordova wkwebkit.
Of course, I know that cordova recommends spa.
In the case of the main index.html file, the page was opened on localhost as shown below in config.xml.

   <content src="index.html" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />

    <platform name="ios">
        <preference name="scheme" value="app" />
        <preference name="hostname" value="localhost" />
    </platform>

Then you can see that the result of checking in Chrome developer mode is applied successfully.

enter image description here

But in the case of the sub index.html file, I don't know how to load it on localhost.
solution is required.

Currently, we are loading the sub index.html file with the file protocol.

enter image description here

file path:
(main) index.html path : www/index.html
(sub) index.html path : www/world/wikitude_AR/inedex.html

version:
cordova  - 11
cordova ios - 6.2


问:
How to get data reuse distance based on JAVA bytecode?
I have got java bytecode by hotspot ./hotspot -XX:+TraceBytecodes -jar HelloWorld.jar. Now I want to get the data reuse distance, but opcode does not give variable name. So I have to trace stack values to define variable. How to trace stack values of java bytecode?
The bytecode is like this:

```<code>    [1435280] static void ZFArray.main(jobject)
    [1435280]  4028364     0  iconst_3
    [1435280]  4028365     1  newarray int
    [1435280]  4028366     3  astore_1
    [1435280]  4028367     4  iconst_0
    [1435280]  4028368     5  istore_2
    [1435280]  4028369     6  iload_2
    [1435280]  4028370     7  aload_1
    [1435280]  4028371     8  arraylength
    [1435280]  4028372     9  if_icmpge 22
    [1435280]  4028373    12  aload_1
    [1435280]  4028374    13  iload_2
    [1435280]  4028375    14  iconst_5
    [1435280]  4028376    15  iastore
    [1435280]  4028377    16  iinc #2 1
    [1435280]  4028378    19  goto 6
    [1435280]  4028379     6  iload_2
</code>```

It seems like "ASM" can be used to manipulate java bytecode, but I don't know how to trace stack values for each bytecode instruction.

Body:
I have got java bytecode by hotspot ./hotspot -XX:+TraceBytecodes -jar HelloWorld.jar. Now I want to get the data reuse distance, but opcode does not give variable name. So I have to trace stack values to define variable. How to trace stack values of java bytecode?
The bytecode is like this:

    [1435280] static void ZFArray.main(jobject)
    [1435280]  4028364     0  iconst_3
    [1435280]  4028365     1  newarray int
    [1435280]  4028366     3  astore_1
    [1435280]  4028367     4  iconst_0
    [1435280]  4028368     5  istore_2
    [1435280]  4028369     6  iload_2
    [1435280]  4028370     7  aload_1
    [1435280]  4028371     8  arraylength
    [1435280]  4028372     9  if_icmpge 22
    [1435280]  4028373    12  aload_1
    [1435280]  4028374    13  iload_2
    [1435280]  4028375    14  iconst_5
    [1435280]  4028376    15  iastore
    [1435280]  4028377    16  iinc #2 1
    [1435280]  4028378    19  goto 6
    [1435280]  4028379     6  iload_2

It seems like "ASM" can be used to manipulate java bytecode, but I don't know how to trace stack values for each bytecode instruction.


问:
print pdf page from html, next page overlap with first page overflowed content
I have created (dynamically) html page, placing divs position absolutely; looks like following

But, when printing it by chrome, first page content overflow to second page, and second page overlap with it;

Anyway to avoid this? let the content just flows?


问:
Cloud Firebase Functions take a long time to response
I have created a flutter project using google firebase, and recently I have learned about Cloud Functions to create REST API to perform some tasks (I run Cloud Functions on Emulator). Everything went very smoothly but it took a long time to respond. Here is my Cloud Functions code:

```<code>const functions = require("firebase-functions");

exports.access_token = functions.https.onRequest((req, res) => {
    return res.json({ 'token': '12345678' });
});
</code>```

Then, i run this command to deploy it:

firebase emulators:start --only functions

Next, i write some code (dart programming), using http library to get the json response:

```<code>// ignore_for_file: avoid_print

import 'package:http/http.dart' as http;

void main() async {
  var startTime = DateTime.now().millisecondsSinceEpoch;
  Uri uri = Uri.parse(
      'http://127.0.0.1:5001/myapp/us-central1/access_token');
  var response = await http.get(uri);
  if (response.statusCode == 200) {
    print("data: ${response.body}");
  } else {
    print('Request failed with status: ${response.statusCode}.');
  }

  print(
      "End time: ${(DateTime.now().millisecondsSinceEpoch - startTime) / 1000}");
}
</code>```

And it returns this result:

C:\Users\iamca\StudioProjects\cauli_app\lib\test>dart dart.dart

data: {"token":"12345678"}

End time: 9.061

It returned response after 9s, It was so long. And I checked the log of Cloud Functions:

```<code>10:57:35 function[us-central1-access_token]  Beginning execution of "access_token"
10:57:35 function[us-central1-access_token]  Finished "access_token" in 11.7878ms
10:57:40 function[us-central1-access_token]  Your function timed out after ~60s. To configure this timeout, see https://firebase.google.com/docs/functions/manage-functions#set_timeout_and_memory_allocation.
10:57:40 function[us-central1-access_token]  Your function was killed because it raised an unhandled error.
</code>```

I see it was finished after 11.8ms, but why http response in my dart code response so long? What did I do wrong?

I try set time out seconds for functions:

```<code>const functions = require("firebase-functions");

exports.access_token = functions.runWith({
    timeoutSeconds: 50,
}).https.onRequest((req, res) => {
    return res.json({ 'token': '12345678' });
});
</code>```

But the result is even worse with end time (on dart code) is 12.75 s

Body:
I have created a flutter project using google firebase, and recently I have learned about Cloud Functions to create REST API to perform some tasks (I run Cloud Functions on Emulator). Everything went very smoothly but it took a long time to respond. Here is my Cloud Functions code:

const functions = require("firebase-functions");

exports.access_token = functions.https.onRequest((req, res) => {
    return res.json({ 'token': '12345678' });
});

Then, i run this command to deploy it:

firebase emulators:start --only functions

Next, i write some code (dart programming), using http library to get the json response:

// ignore_for_file: avoid_print

import 'package:http/http.dart' as http;

void main() async {
  var startTime = DateTime.now().millisecondsSinceEpoch;
  Uri uri = Uri.parse(
      'http://127.0.0.1:5001/myapp/us-central1/access_token');
  var response = await http.get(uri);
  if (response.statusCode == 200) {
    print("data: ${response.body}");
  } else {
    print('Request failed with status: ${response.statusCode}.');
  }

  print(
      "End time: ${(DateTime.now().millisecondsSinceEpoch - startTime) / 1000}");
}

And it returns this result:

C:\Users\iamca\StudioProjects\cauli_app\lib\test>dart dart.dart

data: {"token":"12345678"}

End time: 9.061

It returned response after 9s, It was so long. And I checked the log of Cloud Functions:

10:57:35 function[us-central1-access_token]  Beginning execution of "access_token"
10:57:35 function[us-central1-access_token]  Finished "access_token" in 11.7878ms
10:57:40 function[us-central1-access_token]  Your function timed out after ~60s. To configure this timeout, see https://firebase.google.com/docs/functions/manage-functions#set_timeout_and_memory_allocation.
10:57:40 function[us-central1-access_token]  Your function was killed because it raised an unhandled error.

I see it was finished after 11.8ms, but why http response in my dart code response so long? What did I do wrong?

I try set time out seconds for functions:

const functions = require("firebase-functions");

exports.access_token = functions.runWith({
    timeoutSeconds: 50,
}).https.onRequest((req, res) => {
    return res.json({ 'token': '12345678' });
});

But the result is even worse with end time (on dart code) is 12.75 s


问:
Retrieve the private IP address of an Azure Database for PostgreSQL Flexible Server using Bicep/ARM
I want to retrieve the private IP address of an Azure Database for PostgreSQL Flexible Server during deployment with Bicep/ARM.

Is there a property on the Flexible Server object, a child resource, or the private DNS zone that might have that IP?


问:
Decrypt method throws undefined on Buffer node package with xxtea.js
we have been using xxtea-node npm package for encryption and decryption, as we can see the plugin is depended on Buffer node package, but during the decryption process, it throws Undefined error as below.

Environment :

Node : V14.17.3,

NPM : 6.14.13,

Encryption plugin : xxtea-nodejs

Decyption method which throwing error :

```<code>function decrypt(data, key) {
    if (typeof data === 'string') data = new Buffer(data, 'base64'); //This line throws Undefined error
    if (typeof key === 'string') key = toBytes(key);
    if (data === undefined || data === null || data.length === 0) {
        return data;
    }
    return toUint8Array(decryptUint32Array(toUint32Array(data, false), toUint32Array(fixk(key), false)), true);
}
</code>```

In the Decrypt method new Buffer line is throwing "ReferenceError: Buffer is not defined", but if I replace this line with the following line it works fine require('buffer/').Buffer.from()

Whats the difference between both and how to fix the first said issue?

Body:
we have been using xxtea-node npm package for encryption and decryption, as we can see the plugin is depended on Buffer node package, but during the decryption process, it throws Undefined error as below.

Environment :

Node : V14.17.3,

NPM : 6.14.13,

Encryption plugin : xxtea-nodejs

Decyption method which throwing error :

function decrypt(data, key) {
    if (typeof data === 'string') data = new Buffer(data, 'base64'); //This line throws Undefined error
    if (typeof key === 'string') key = toBytes(key);
    if (data === undefined || data === null || data.length === 0) {
        return data;
    }
    return toUint8Array(decryptUint32Array(toUint32Array(data, false), toUint32Array(fixk(key), false)), true);
}

In the Decrypt method new Buffer line is throwing "ReferenceError: Buffer is not defined", but if I replace this line with the following line it works fine require('buffer/').Buffer.from()

Whats the difference between both and how to fix the first said issue?


问:
How to write a script to check if an ftp server allows anonymous logins
FTP anonymous logins
Need a script which will check that ftp server allows anonymous logins

I have no idea about this issue


问:
Non-zero exit status 1, when using subprocess
I'm creating my first Flask API. I'm using recasepunc model.

This is my code:

```<code>import subprocess

text = "Hello"
cased = subprocess.check_output('python recasepunc/recasepunc.py predict recasepunc/checkpoint', shell=True, text=True, input=text)
return cased
</code>```

I get the error:
python recasepunc/recasepunc.py predict recasepunc/checkpoint' returned non-zero exit status 1

I've already checked, if I installed all the requirements. I don't know, what else I can do.

Body:
I'm creating my first Flask API. I'm using recasepunc model.

This is my code:

import subprocess

text = "Hello"
cased = subprocess.check_output('python recasepunc/recasepunc.py predict recasepunc/checkpoint', shell=True, text=True, input=text)
return cased

I get the error:
python recasepunc/recasepunc.py predict recasepunc/checkpoint' returned non-zero exit status 1

I've already checked, if I installed all the requirements. I don't know, what else I can do.


问:
SpringBoot JPA Bulk insertion is not woking - Master/Slave Database
Entity:

```<code>public class CapacityConfig {

    @Id
    @GeneratedValue(generator = "abc")
    @GenericGenerator(name = "abc", strategy = "increment")
    @Column(name = "id")
    private Long id;

    @Column(name = "sap_id")
    private Long SapId;
}
</code>```

Properties File:

```<code>spring.jpa.properties.hibernate.generate_statistics=true
spring.jpa.properties.hibernate.jdbc.batch_size=100000
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates=true

spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.use_sql_comments=true
spring.jpa.properties.hibernate.format_sql=true

#Master config
spring.oms.master.datasource.jdbcUrl=jdbc:mysql://****?reWriteBatchedInserts=true&useUnicode=yes&characterEncoding=UTF-8
spring.oms.master.datasource.username=**
spring.oms.master.datasource.password=**
spring.oms.master.datasource.maxconnection=2
spring.oms.master.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.oms.master.datasource.hikari.maxLifeTime=600000

#Slave config
spring.oms.master.datasource.jdbcUrl=jdbc:mysql://****?reWriteBatchedInserts=true&useUnicode=yes&characterEncoding=UTF-8
spring.oms.master.datasource.username=**
spring.oms.master.datasource.password=**
spring.oms.master.datasource.maxconnection=2
spring.oms.master.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.oms.master.datasource.hikari.maxLifeTime=600000
</code>```

I am saving data like:

```<code>`CapacityConfigDAO.saveAllAndFlush(CapacityConfigList);
</code>```

While saving data batch operations are not performing. Idk why?
Mat be there is some issue with configuration because I am using master/slave architecture.

Body:
Entity:

public class CapacityConfig {

    @Id
    @GeneratedValue(generator = "abc")
    @GenericGenerator(name = "abc", strategy = "increment")
    @Column(name = "id")
    private Long id;

    @Column(name = "sap_id")
    private Long SapId;
}

Properties File:

spring.jpa.properties.hibernate.generate_statistics=true
spring.jpa.properties.hibernate.jdbc.batch_size=100000
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates=true

spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.use_sql_comments=true
spring.jpa.properties.hibernate.format_sql=true

#Master config
spring.oms.master.datasource.jdbcUrl=jdbc:mysql://****?reWriteBatchedInserts=true&useUnicode=yes&characterEncoding=UTF-8
spring.oms.master.datasource.username=**
spring.oms.master.datasource.password=**
spring.oms.master.datasource.maxconnection=2
spring.oms.master.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.oms.master.datasource.hikari.maxLifeTime=600000

#Slave config
spring.oms.master.datasource.jdbcUrl=jdbc:mysql://****?reWriteBatchedInserts=true&useUnicode=yes&characterEncoding=UTF-8
spring.oms.master.datasource.username=**
spring.oms.master.datasource.password=**
spring.oms.master.datasource.maxconnection=2
spring.oms.master.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.oms.master.datasource.hikari.maxLifeTime=600000

I am saving data like:

`CapacityConfigDAO.saveAllAndFlush(CapacityConfigList);

While saving data batch operations are not performing. Idk why?
Mat be there is some issue with configuration because I am using master/slave architecture.


问:
How to check if the touch event is within the range of the image
I have an image of a half court half court and I want to check how the user can determine if the made or missed shot was a 2pt or a 3pt, also determine the plot coordinate of an actual size of a basketball half court not just the touch coordinate of the screen.

What can be the the possible functions for this? I'm using kivy python.

Here are my codes used for plotting the touch coordinates for X and Y.

```<code>    savefile = ObjectProperty(None)
    text_input = ObjectProperty(None)
    open('save_file.csv', 'w').write("Shot type,X,Y\n")

    def on_touch_down(self, touch):
        self.canvas.add(Color(rgb=(46/255.0, 172/255.0, 88/255.0)))
        d = 10
        self.canvas.add(Ellipse(pos=(touch.x - d / 2, touch.y), size=(d, d)))
        with open('save_file.csv', 'a', newline='') as f:
            print("Made," + str(touch.x) + "," + str(touch.y), file=f)

            if touch.is_double_tap:
                self.canvas.add(Color(rgb=(220/255.0, 8/255.0, 8/255.0)))
                d = 10
                self.canvas.add(
                    Ellipse(pos=(touch.x - d / 2, touch.y), size=(d, d)))
                print("Missed," + str(touch.x) + "," + str(touch.y), file=f)

    def clear_screen(self):
        self.canvas.clear()

    def save(self, path, filename):
        with open(os.path.join(path, filename), 'w') as stream:
            stream.write(self.text_input.text)

        self.dismiss_popup()
</code>```

Body:
I have an image of a half court half court and I want to check how the user can determine if the made or missed shot was a 2pt or a 3pt, also determine the plot coordinate of an actual size of a basketball half court not just the touch coordinate of the screen.

What can be the the possible functions for this? I'm using kivy python.

Here are my codes used for plotting the touch coordinates for X and Y.

    savefile = ObjectProperty(None)
    text_input = ObjectProperty(None)
    open('save_file.csv', 'w').write("Shot type,X,Y\n")

    def on_touch_down(self, touch):
        self.canvas.add(Color(rgb=(46/255.0, 172/255.0, 88/255.0)))
        d = 10
        self.canvas.add(Ellipse(pos=(touch.x - d / 2, touch.y), size=(d, d)))
        with open('save_file.csv', 'a', newline='') as f:
            print("Made," + str(touch.x) + "," + str(touch.y), file=f)

            if touch.is_double_tap:
                self.canvas.add(Color(rgb=(220/255.0, 8/255.0, 8/255.0)))
                d = 10
                self.canvas.add(
                    Ellipse(pos=(touch.x - d / 2, touch.y), size=(d, d)))
                print("Missed," + str(touch.x) + "," + str(touch.y), file=f)

    def clear_screen(self):
        self.canvas.clear()

    def save(self, path, filename):
        with open(os.path.join(path, filename), 'w') as stream:
            stream.write(self.text_input.text)

        self.dismiss_popup()


问:
`Function` works asynchronously in javascript
I have a function that makes buttons slide from right to left by assigning css to a button using javascript. It works fine when I call the onclick event to trigger that function. Function like this:

```<code>function btnToggle() {
    document.querySelectorAll('.btnClass').forEach(el => {
      if (el.style.marginRight === "250px") {
          el.style.marginRight = "0px";
      } else {
          el.style.marginRight = "250px";
      }
   });

   var btnID = document.getElementById('btn3');
   if (btnID.style.marginRight === "250px") {
       btnID.style.marginRight = "0px";
   } else {
       btnID.style.marginRight = "250px";
   }
}
</code>```

And I have a slideToggle slide from right to left that is automatically expanded on the web page reload by another function. I put it inside the function automatically expanded for slideToggle so that it fires automatically the css i assign to the button but it works asynchronously, only btnID  is active, .btnClass is still in place :

```<code>function anotherFunction() {
   ......
   btnToggle();
}
</code>```

I think the error is caused by forEach but haven't found a fix yet, for some reason I can only use class for some buttons but cannot use their id for btnToggle() function. How can they work together or anchor them to the div element of the slideToggle function so that when slideToggle is activated manually or automatically they will slide along.

This is my slideToggle slide from right to left if you need to see

Body:
I have a function that makes buttons slide from right to left by assigning css to a button using javascript. It works fine when I call the onclick event to trigger that function. Function like this:

function btnToggle() {
    document.querySelectorAll('.btnClass').forEach(el => {
      if (el.style.marginRight === "250px") {
          el.style.marginRight = "0px";
      } else {
          el.style.marginRight = "250px";
      }
   });

   var btnID = document.getElementById('btn3');
   if (btnID.style.marginRight === "250px") {
       btnID.style.marginRight = "0px";
   } else {
       btnID.style.marginRight = "250px";
   }
}

And I have a slideToggle slide from right to left that is automatically expanded on the web page reload by another function. I put it inside the function automatically expanded for slideToggle so that it fires automatically the css i assign to the button but it works asynchronously, only btnID  is active, .btnClass is still in place :

function anotherFunction() {
   ......
   btnToggle();
}

I think the error is caused by forEach but haven't found a fix yet, for some reason I can only use class for some buttons but cannot use their id for btnToggle() function. How can they work together or anchor them to the div element of the slideToggle function so that when slideToggle is activated manually or automatically they will slide along.

This is my slideToggle slide from right to left if you need to see


问:
Increase in the number of connections gives 504 gateway timeout error in Nginx
I have a mail server running nginx. Whenever the number of connections increase, nginx fails and give Upstream connection error in the error.log. On the browser, it gives 504 Timeout error. How can I resolve this?

I have checked the resources that are being used by my server. They are in the optimal state. Still, I am facing this issue.


问:
Could not spawn process for application - he application process exited prematurely
I have a problem, apparently the website doesn't want to load using NodeJS as I would like. The whole thing is done on Plesk. Does anyone know or had someone similar problems?

It would be ideal if reactjs works. File architecture "reactjs" adapted.

Website:

Protocols:

Architecture

NodeJS Configuration


问:
How can I open another console window
I am trying to open a new console terminal from Rust. With the help of documentation, I was capable of starting a terminal in the current terminal window, but not in another one.

For example, imagine I have one folder with two files main.py and bb.py and the following code does the thing I want

import os
os.system("start cmd /K python bb.py")
```

It opens a new terminal, and in this new terminal the command python bb.py is executed. How can I do this in Rust?

Title: How can I open another console window

Body:
I am trying to open a new console terminal from Rust. With the help of documentation, I was capable of starting a terminal in the current terminal window, but not in another one.

For example, imagine I have one folder with two files main.py and bb.py and the following code does the thing I want

import os
os.system("start cmd /K python bb.py")

It opens a new terminal, and in this new terminal the command python bb.py is executed. How can I do this in Rust?


问:
TWA not working, still showing Custom tab URL bar
Trying to hide the URL bar in debug mode but no hope:-

Followed:

Old Stackoverflow Guide (Answer didn't work for the OP also):
Is it possible to hide URL bar on Chrome Custom Tabs

Followed (Not Working!):
https://developer.chrome.com/docs/android/trusted-web-activity/integration-guide/

The device is Rooted but I have still enabled #enable-command-line-on-non-rooted-devices, the file at

```<code>/data/local/tmp/chrome-command-line
</code>```

with

```<code>_ --disable-digital-asset-link-verification-for-url="https://example.com"
</code>```

but still not working.

I tried to hide the URL bar from Custom Chrome Tab but not working,
followed google's dev guide but still not working.

Body:
Trying to hide the URL bar in debug mode but no hope:-

Followed:

Old Stackoverflow Guide (Answer didn't work for the OP also):
Is it possible to hide URL bar on Chrome Custom Tabs

Followed (Not Working!):
https://developer.chrome.com/docs/android/trusted-web-activity/integration-guide/

The device is Rooted but I have still enabled #enable-command-line-on-non-rooted-devices, the file at

/data/local/tmp/chrome-command-line

with

_ --disable-digital-asset-link-verification-for-url="https://example.com"

but still not working.

I tried to hide the URL bar from Custom Chrome Tab but not working,
followed google's dev guide but still not working.


问:
Run-time error '91' trying to create a dynamic embedded chart with a scrollbar
I'm trying to write a VBA subroutine that adds an embedded line chart to a sheet, and because there's a great deal of data, I'd like to show 200 datapoints and scroll through the entire series using a scrollbar. Rather than having to edit the data series by clicking on the Formulas ribbon tab and then Use in Formula and changing the series values by pasting named ranges, I recorded the macro so that I could cut and paste the generated code to automate the process. Unfortunately, it is these last 2 lines of VBA generated code that are the problem.

Here is my code-

```<code>Sub dynamic_chart()
Dim lastRow As Long
Dim embedCht As Chart

    Set embedCht = ActiveSheet.Shapes.AddChart(xlLine).Chart
    ActiveWorkbook.Names.Add Name:="Dates", RefersToR1C1:="=OFFSET(Sheet1!R1C1,Sheet1!R1C3+1,0,200,1)"
    ActiveWorkbook.Names.Add Name:="Close", RefersToR1C1:="=OFFSET(Sheet1!R1C2,Sheet1!R1C3+1,0,200,1)"
    embedCht.Axes(xlCategory).TickLabels.Orientation = 45

    ActiveSheet.ScrollBars.Add(5, 374, 1110, 20).Select
    lastRow = ActiveSheet.Range("A1").CurrentRegion.Rows.Count
    ActiveSheet.Shapes.Range(Array("Scroll Bar 1")).Select
    With Selection
        .Value = 0
        .Min = 0
        .Max = lastRow - 200
        .SmallChange = 50
        .LargeChange = 200
        .LinkedCell = "$C$1"
        .Display3DShading = True
    End With

    ActiveChart.FullSeriesCollection(1).Values = "==scrolling.xlsm!Close"
    ActiveChart.FullSeriesCollection(1).XValues = "==scrolling.xlsm!Dates"

End Sub
</code>```

It's the last 2 lines of code that prompt the Run-time error '91'
Thanks for any help.

Body:
I'm trying to write a VBA subroutine that adds an embedded line chart to a sheet, and because there's a great deal of data, I'd like to show 200 datapoints and scroll through the entire series using a scrollbar. Rather than having to edit the data series by clicking on the Formulas ribbon tab and then Use in Formula and changing the series values by pasting named ranges, I recorded the macro so that I could cut and paste the generated code to automate the process. Unfortunately, it is these last 2 lines of VBA generated code that are the problem.

Here is my code-

Sub dynamic_chart()
Dim lastRow As Long
Dim embedCht As Chart

    Set embedCht = ActiveSheet.Shapes.AddChart(xlLine).Chart
    ActiveWorkbook.Names.Add Name:="Dates", RefersToR1C1:="=OFFSET(Sheet1!R1C1,Sheet1!R1C3+1,0,200,1)"
    ActiveWorkbook.Names.Add Name:="Close", RefersToR1C1:="=OFFSET(Sheet1!R1C2,Sheet1!R1C3+1,0,200,1)"
    embedCht.Axes(xlCategory).TickLabels.Orientation = 45

    ActiveSheet.ScrollBars.Add(5, 374, 1110, 20).Select
    lastRow = ActiveSheet.Range("A1").CurrentRegion.Rows.Count
    ActiveSheet.Shapes.Range(Array("Scroll Bar 1")).Select
    With Selection
        .Value = 0
        .Min = 0
        .Max = lastRow - 200
        .SmallChange = 50
        .LargeChange = 200
        .LinkedCell = "$C$1"
        .Display3DShading = True
    End With

    ActiveChart.FullSeriesCollection(1).Values = "==scrolling.xlsm!Close"
    ActiveChart.FullSeriesCollection(1).XValues = "==scrolling.xlsm!Dates"

End Sub

It's the last 2 lines of code that prompt the Run-time error '91'
Thanks for any help.


问:
How to import JSON file with embedded array into Mongodb using Compass
the JSON file is like :

```<code>{
"A": [
  {"above average": "more than average, esp. in amount, age, height, weight etc."},
  {"absolutely necessary": "totally or completely necessary"},
  ],
"G":[
  {"get back together": "to become a couple or a group again after being apart"},
  {"get better": "to improve"},
  {"get better (at)": "to improve in skill or ability"},
  ],
}
</code>```

I encounter the error: "Operation passed in cannot be an Array", when use the "import file" function provided by the Compass.

What can I do or any alternative approach(python)?

I am expecting a easy approach.

Thanks!

Body:
the JSON file is like :

{
"A": [
  {"above average": "more than average, esp. in amount, age, height, weight etc."},
  {"absolutely necessary": "totally or completely necessary"},
  ],
"G":[
  {"get back together": "to become a couple or a group again after being apart"},
  {"get better": "to improve"},
  {"get better (at)": "to improve in skill or ability"},
  ],
}

I encounter the error: "Operation passed in cannot be an Array", when use the "import file" function provided by the Compass.

What can I do or any alternative approach(python)?

I am expecting a easy approach.

Thanks!


问:
PubSub "Connection reset by peer" on gcp
I encountered the exception.

"System.IO.IOException: Unable to read data from the transport connection: Connection reset by peer.\n ---> System.Net.Sockets.SocketException (104): Connection reset by peer\n   --- End of inner exception stack trace ---\n   at Google.Cloud.PubSub.V1.SubscriberClientImpl.SingleChannel.HandleRpcFailure(Exception e)\n   at Google.Cloud.PubSub.V1.SubscriberClientImpl.SingleChannel.HandlePullMoveNext(Task initTask)\n   at Google.Cloud.PubSub.V1.SubscriberClientImpl.SingleChannel.StartAsync()\n   at Google.Cloud.PubSub.V1.Tasks.ForwardingAwaiter.GetResult()\n   at Google.Cloud.PubSub.V1.Tasks.Extensions.<>c__DisplayClass4_0.<g__Inner|0>d.MoveNext()\n--- End of stack trace from previous location ---\n

"Invoke" function was executed to pull a message from my topic per 5 seconds in the scheduler

public async Task Invoke()
{
  var subscriber = await SubscriberClient.CreateAsync(CreateSubscriptionName());
   await subscriber.StartAsync((msg, cancellationToken) =>
   {

      //....
      return Task.FromResult(SubscriberClient.Reply.Ack);
   });
   await subscriber.StopAsync(CancellationToken.None);
}
```

How did I fix this ?

Thanks!

I've already checked the doc

PublisherClient and SubscriberClient are expensive to create, so when regularly publishing or subscribing to the same topic or subscription then a singleton client instance should be created and used for the lifetime of the application.

But I still don't know how to do ...
I guessed I left too many open connections ?

Body:
I encountered the exception.

"System.IO.IOException: Unable to read data from the transport connection: Connection reset by peer.\n ---> System.Net.Sockets.SocketException (104): Connection reset by peer\n   --- End of inner exception stack trace ---\n   at Google.Cloud.PubSub.V1.SubscriberClientImpl.SingleChannel.HandleRpcFailure(Exception e)\n   at Google.Cloud.PubSub.V1.SubscriberClientImpl.SingleChannel.HandlePullMoveNext(Task initTask)\n   at Google.Cloud.PubSub.V1.SubscriberClientImpl.SingleChannel.StartAsync()\n   at Google.Cloud.PubSub.V1.Tasks.ForwardingAwaiter.GetResult()\n   at Google.Cloud.PubSub.V1.Tasks.Extensions.<>c__DisplayClass4_0.<g__Inner|0>d.MoveNext()\n--- End of stack trace from previous location ---\n

"Invoke" function was executed to pull a message from my topic per 5 seconds in the scheduler

public async Task Invoke()
{
  var subscriber = await SubscriberClient.CreateAsync(CreateSubscriptionName());
   await subscriber.StartAsync((msg, cancellationToken) =>
   {

      //....
      return Task.FromResult(SubscriberClient.Reply.Ack);
   });
   await subscriber.StopAsync(CancellationToken.None);
}

How did I fix this ?

Thanks!

I've already checked the doc

PublisherClient and SubscriberClient are expensive to create, so when regularly publishing or subscribing to the same topic or subscription then a singleton client instance should be created and used for the lifetime of the application.

But I still don't know how to do ...
I guessed I left too many open connections ?


问:
Running ocrmypdf with tesseract, ghostscript on windows without admin rights
I have built a python script based on ocrmypdf which requires both tesseract and ghostscript to be installed locally.

This script is to be run on a laptop without administrative rights and hence I will not be able to install tesseract and ghostscript on the laptop separately.

I have attempted to use CX_Freeze to freeze up the environment and try running it on the laptop. However, I've encountered an error stating that gswin64c cannot be found on path. I've also tried to set up a temporary os.environment for ghostscript as per the following: os.environ['GS_PROG'] = r"gs10.00.0\bin" when building the exe using cx_freeze. However, I can't seem to get it to work.

Now, I could explore uploading it to the cloud and run it off it. However, that's really the last resort as it is slow and would be expensive as I require the user to upload tons of PDF onto the cloud to analyze and extract information before returning it, and then finally downloading the extracted information again.

Any advice would be good on how I should proceed forward. Thank you!


问:
Cucumber with Spring Integration tests Multiple server restarts
I have integrated cucumber tests with spring integration tests. I see that

```<code>@Suite
@IncludeEngines("cucumber")
@SelectClasspathResource("features")
@ConfigurationParameters({
    @ConfigurationParameter(key = Constants.PLUGIN_PROPERTY_NAME,
        value = "html:build/cucumber/cucumber.html"),
    @ConfigurationParameter(key = Constants.GLUE_PROPERTY_NAME, value = "com.app.bdd"),
    @ConfigurationParameter(key = Constants.FILTER_TAGS_PROPERTY_NAME, value = "not @Disabled"),
    @ConfigurationParameter(key = Constants.PLUGIN_PUBLISH_QUIET_PROPERTY_NAME, value = "true"),
    @ConfigurationParameter(key = Constants.JUNIT_PLATFORM_NAMING_STRATEGY_PROPERTY_NAME, value = "long")
})
public class MyBddFeatures {

}

@CucumberContextConfiguration
@SpringBootTest(classes = DealerConsumerApplication.class, webEnvironment = WebEnvironment.DEFINED_PORT)
@AutoConfigureMockMvc
@FlywayTest
@AutoConfigureWireMock
@AutoConfigureEmbeddedDatabase(type = AutoConfigureEmbeddedDatabase.DatabaseType.POSTGRES, provider = ZONKY)
@TestPropertySource("classpath:test-application.properties")
public class SpringGlue {

  @TestConfiguration
  public static class TestConfig {

    // any mock beans would go here
  }
}
</code>```

And placed feature files under resources/features

```<code>Feature: Users Test

  As a user
  I want to test the changes in users

  Scenario: Load to create the new users
    Given I send request to create the new users
    Then I receive response 200 and users created in database

  Scenario: Load to update the users
    Given I send request to update the old users
    Then I receive response 200 and users updated in database

  Scenario: Load to delete the users
    Given I send request to delete the users
    Then I receive response 200 and users deleted in database
</code>```

What I am seeing is that cucumber

```<code>1. Server restart for every scenario, so I am loosing data between scenario in a single feature file
2. Server restart across feature files
</code>```

Is there any way so that I can start my server once and run all tests in all feature files.

Body:
I have integrated cucumber tests with spring integration tests. I see that

@Suite
@IncludeEngines("cucumber")
@SelectClasspathResource("features")
@ConfigurationParameters({
    @ConfigurationParameter(key = Constants.PLUGIN_PROPERTY_NAME,
        value = "html:build/cucumber/cucumber.html"),
    @ConfigurationParameter(key = Constants.GLUE_PROPERTY_NAME, value = "com.app.bdd"),
    @ConfigurationParameter(key = Constants.FILTER_TAGS_PROPERTY_NAME, value = "not @Disabled"),
    @ConfigurationParameter(key = Constants.PLUGIN_PUBLISH_QUIET_PROPERTY_NAME, value = "true"),
    @ConfigurationParameter(key = Constants.JUNIT_PLATFORM_NAMING_STRATEGY_PROPERTY_NAME, value = "long")
})
public class MyBddFeatures {

}

@CucumberContextConfiguration
@SpringBootTest(classes = DealerConsumerApplication.class, webEnvironment = WebEnvironment.DEFINED_PORT)
@AutoConfigureMockMvc
@FlywayTest
@AutoConfigureWireMock
@AutoConfigureEmbeddedDatabase(type = AutoConfigureEmbeddedDatabase.DatabaseType.POSTGRES, provider = ZONKY)
@TestPropertySource("classpath:test-application.properties")
public class SpringGlue {

  @TestConfiguration
  public static class TestConfig {

    // any mock beans would go here
  }
}

And placed feature files under resources/features

Feature: Users Test

  As a user
  I want to test the changes in users

  Scenario: Load to create the new users
    Given I send request to create the new users
    Then I receive response 200 and users created in database

  Scenario: Load to update the users
    Given I send request to update the old users
    Then I receive response 200 and users updated in database

  Scenario: Load to delete the users
    Given I send request to delete the users
    Then I receive response 200 and users deleted in database

What I am seeing is that cucumber

1. Server restart for every scenario, so I am loosing data between scenario in a single feature file
2. Server restart across feature files

Is there any way so that I can start my server once and run all tests in all feature files.


问:
When I try to import and use a mui avatar in react, it makes the whole div disappears
This is my code:

```<code>import React from 'react';
import './Post.css';
import Avatar from "@mui/material/Avatar"

function Post() {
  return (
    <div className="post">

      <h3>Username</h3>
      <Avatar
          className="post__avatar"
          alt="Materialzz"
          src="/static/images/avatar/1.jpg"
        />
        {/* header -> avatar + username */}
        <img
         className="post__image" src="https://images.unsplash.com/photo-1481349518771-20055b2a7b24?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8cmFuZG9tfGVufDB8fDB8fA%3D%3D&w=1000&q=80"
         alt=""
         />
        {/* image */}
        <h4 className="post__text"><strong>Username:</strong> WOW look how cool this banana looks with a pink background!</h4>
        {/* username + caption */}
    </div>

  )
}

export default Post
</code>```

I was trying to make an avatar by using material ui in react. Whenever I try the examples of how to import an avatar on the Material Ui website, everything from div disappears and my screen is blank. I believe this is just a simple coding error, but I'm not sure.

Body:
This is my code:

import React from 'react';
import './Post.css';
import Avatar from "@mui/material/Avatar"

function Post() {
  return (

Username

      <Avatar
          className="post__avatar"
          alt="Materialzz"
          src="/static/images/avatar/1.jpg"
        />
        {/* header -> avatar + username */}

        {/* image */}

Username: WOW look how cool this banana looks with a pink background!

        {/* username + caption */}

  )
}

export default Post

I was trying to make an avatar by using material ui in react. Whenever I try the examples of how to import an avatar on the Material Ui website, everything from div disappears and my screen is blank. I believe this is just a simple coding error, but I'm not sure.


问:
Website elements reposition viewed through safari, works on other browsers
Links below are accurate and match up with attached images. Reproduction is possible as described below.

I am developing a website using HTML, CSS, and JavaScript: https://github.com/nkozlo3/PortfolioWebsite.git
Website: https://nkozlo3.github.io/PortfolioWebsite/

The website looks correct on Chrome, Firefox, and Microsoft Edge. Also on laptops of different sizes: Chrome view 1 Microsoft Edge view 1
Firefox view is the same.

But when viewed through Safari, the elements reposition themselves like so:
Safari view 1

To reproduce the problem simply visit the website on Safari through the above link or pull the code from my GitHub (link above) and run it through Safari.

I tried putting this wrapper around the body of my HTML

```
<p>and adding this meta tag</p>
<pre class="lang-html prettyprint-override"><code><meta name="viewport" content="width=device-width, initial-scale=1.0" />
</code>```

I was expecting this to force the content to stay in the correct spots across devices and websites, but it did not solve the issue on Safari.

I also tried adding the below reset.css file to my style.css file to normalize across different browsers. This also did not solve the issue on Safari:

/***
    The new CSS reset - version 1.8.2 (last updated 23.12.2022)
    GitHub page: https://github.com/elad2412/the-new-css-reset
***/

/*
    Remove all the styles of the "User-Agent-Stylesheet", except for the 'display' property
    - The "symbol *" part is to solve Firefox SVG sprite bug
 */
*:where(:not(html, iframe, canvas, img, svg, video, audio):not(svg *, symbol *)) {
    all: unset;
    display: revert;
}

/* Preferred box-sizing value */
*,
*::before,
*::after {
    box-sizing: border-box;
}

/* Reapply the pointer cursor for anchor tags */
a, button {
    cursor: revert;
}

/* Remove list styles (bullets/numbers) */
ol, ul, menu {
    list-style: none;
}

/* For images to not be able to exceed their container */
img {
    max-inline-size: 100%;
    max-block-size: 100%;
}

/* removes spacing between cells in tables */
table {
    border-collapse: collapse;
}

/* Safari - solving issue when using user-select:none on the  text input doesn't working */
input, textarea {
    -webkit-user-select: auto;
}

/* revert the 'white-space' property for textarea elements on Safari */
textarea {
    white-space: revert;
}

/* minimum style to allow to style meter element */
meter {
    -webkit-appearance: revert;
    appearance: revert;
}

/* preformatted text - use only for this feature */
pre {
    all: revert;
}

/* reset default text opacity of input placeholder */
::placeholder {
    color: unset;
}

/* remove default dot (•) sign */
::marker {
    content: "";
}

/* fix the feature of 'hidden' attribute.
   display:revert; revert to element instead of attribute */
:where([hidden]) {
    display: none;
}

/* revert for bug in Chromium browsers
   - fix for the content editable attribute will work properly.
   - webkit-user-select: auto; added for Safari in case of using user-select:none on wrapper element*/
:where([contenteditable]:not([contenteditable="false"])) {
    -moz-user-modify: read-write;
    -webkit-user-modify: read-write;
    overflow-wrap: break-word;
    -webkit-line-break: after-white-space;
    -webkit-user-select: auto;
}

/* apply back the draggable feature - exist only in Chromium and Safari */
:where([draggable="true"]) {
    -webkit-user-drag: element;
}

/* Revert Modal native behavior */
:where(dialog:modal) {
    all: revert;
}```

Body:
Links below are accurate and match up with attached images. Reproduction is possible as described below.

I am developing a website using HTML, CSS, and JavaScript: https://github.com/nkozlo3/PortfolioWebsite.git
Website: https://nkozlo3.github.io/PortfolioWebsite/

The website looks correct on Chrome, Firefox, and Microsoft Edge. Also on laptops of different sizes: Chrome view 1 Microsoft Edge view 1
Firefox view is the same.

But when viewed through Safari, the elements reposition themselves like so:
Safari view 1

To reproduce the problem simply visit the website on Safari through the above link or pull the code from my GitHub (link above) and run it through Safari.

I tried putting this wrapper around the body of my HTML

and adding this meta tag

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

I was expecting this to force the content to stay in the correct spots across devices and websites, but it did not solve the issue on Safari.

I also tried adding the below reset.css file to my style.css file to normalize across different browsers. This also did not solve the issue on Safari:

/***
    The new CSS reset - version 1.8.2 (last updated 23.12.2022)
    GitHub page: https://github.com/elad2412/the-new-css-reset
***/

/*
    Remove all the styles of the "User-Agent-Stylesheet", except for the 'display' property
    - The "symbol *" part is to solve Firefox SVG sprite bug
 */
*:where(:not(html, iframe, canvas, img, svg, video, audio):not(svg *, symbol *)) {
    all: unset;
    display: revert;
}

/* Preferred box-sizing value */
*,
*::before,
*::after {
    box-sizing: border-box;
}

/* Reapply the pointer cursor for anchor tags */
a, button {
    cursor: revert;
}

/* Remove list styles (bullets/numbers) */
ol, ul, menu {
    list-style: none;
}

/* For images to not be able to exceed their container */
img {
    max-inline-size: 100%;
    max-block-size: 100%;
}

/* removes spacing between cells in tables */
table {
    border-collapse: collapse;
}

/* Safari - solving issue when using user-select:none on the  text input doesn't working */
input, textarea {
    -webkit-user-select: auto;
}

/* revert the 'white-space' property for textarea elements on Safari */
textarea {
    white-space: revert;
}

/* minimum style to allow to style meter element */
meter {
    -webkit-appearance: revert;
    appearance: revert;
}

/* preformatted text - use only for this feature */
pre {
    all: revert;
}

/* reset default text opacity of input placeholder */
::placeholder {
    color: unset;
}

/* remove default dot (•) sign */
::marker {
    content: "";
}

/* fix the feature of 'hidden' attribute.
   display:revert; revert to element instead of attribute */
:where([hidden]) {
    display: none;
}

/* revert for bug in Chromium browsers
   - fix for the content editable attribute will work properly.
   - webkit-user-select: auto; added for Safari in case of using user-select:none on wrapper element*/
:where([contenteditable]:not([contenteditable="false"])) {
    -moz-user-modify: read-write;
    -webkit-user-modify: read-write;
    overflow-wrap: break-word;
    -webkit-line-break: after-white-space;
    -webkit-user-select: auto;
}

/* apply back the draggable feature - exist only in Chromium and Safari */
:where([draggable="true"]) {
    -webkit-user-drag: element;
}

/* Revert Modal native behavior */
:where(dialog:modal) {
    all: revert;
}


问:
EC2 is asking to change password after successful SSH logins
My ec2 machine was running since couple of years and i was able to ssh in that machine using public key, but all of sudden yesterday after successfully logged in through SSH it is asking to change password as password has been expired.
I never set any password expiry policy.

after login screen

I have deattach the root volume and attached to other instance and checked the password expiry using command chage -i ununtu output shows this


问:
Is there any way to check if the declared type of a method parameter were consistent with the declared generic type?
Consider a generic type baseclass:

```<code>from abc import ABC, abstractmethod

class Reader(ABC, Generic[S]):

    @abstractmethod
    def get_resource(self) -> S:
       pass
</code>```

Also let's set up some dummy classes for trying this out:

```<code>
class ResourceA():
    def uri(self) -> str:
        return "uri:ResourceA"

class ResourceB():
    def uri(self) -> str:
        return "uri:ResourceB"
</code>```

Now let's cause some nonsense and mayhem. Yet no warnings/notifications are provided!

```<code>from abc import ABC, abstractmethod
from typing import Generic, TypeVar

from typing_extensions import override

class Resource:

    @abstractmethod
    def uri(self) -> str:
        raise NotImplementedError

class ResourceA(Resource):
    @override
    def uri(self) -> str:
        return "uri:ResourceA"

class ResourceB(Resource):
    @override
    def uri(self) -> str:
        return "uri:ResourceB"

class ResourceC(Resource):
    @override
    def uri(self) -> str:
        return "uri:ResourceC"

S = TypeVar("S", bound=Resource)

class Reader(ABC, Generic[S]):

    @abstractmethod
    def get_resource(self) -> S:
       pass

class ReaderA(Reader[ResourceA]):

    def __init__(self, resource: ResourceA):
        self.resource = resource

    @override
    def get_resource(self) -> ResourceA:
        return self.resource # Incorrect on purpose to kick tires on warnings

class ReaderB(Reader[ResourceB]):

    def __init__(self, resource: ResourceA):
        self.resource = resource

    @override
    def get_resource(self) -> ResourceA: # incorrect on purpose to kick tires
        return self.resource

</code>```

Now let's send in some messy stuff..

```<code>fr1 = ReaderA(ResourceB())
print('resourceA', fr1.get_resource().uri())

fr2 = ReaderB(ResourceC())
print('resourceB', fr2.get_resource().uri())
</code>```

We get only the following output:

```<code>resourceA uri:ResourceB
resourceB uri:ResourceC
</code>```

I realize these are generic type hints but still.. is there not some way to at least be notified /warned of the typing mismatch?  This is after all a compile time visibility situation.

Body:
Consider a generic type baseclass:

from abc import ABC, abstractmethod

class Reader(ABC, Generic[S]):

    @abstractmethod
    def get_resource(self) -> S:
       pass

Also let's set up some dummy classes for trying this out:

class ResourceA():
    def uri(self) -> str:
        return "uri:ResourceA"

class ResourceB():
    def uri(self) -> str:
        return "uri:ResourceB"

Now let's cause some nonsense and mayhem. Yet no warnings/notifications are provided!

from abc import ABC, abstractmethod
from typing import Generic, TypeVar

from typing_extensions import override

class Resource:

    @abstractmethod
    def uri(self) -> str:
        raise NotImplementedError

class ResourceA(Resource):
    @override
    def uri(self) -> str:
        return "uri:ResourceA"

class ResourceB(Resource):
    @override
    def uri(self) -> str:
        return "uri:ResourceB"

class ResourceC(Resource):
    @override
    def uri(self) -> str:
        return "uri:ResourceC"

S = TypeVar("S", bound=Resource)

class Reader(ABC, Generic[S]):

    @abstractmethod
    def get_resource(self) -> S:
       pass

class ReaderA(Reader[ResourceA]):

    def __init__(self, resource: ResourceA):
        self.resource = resource

    @override
    def get_resource(self) -> ResourceA:
        return self.resource # Incorrect on purpose to kick tires on warnings

class ReaderB(Reader[ResourceB]):

    def __init__(self, resource: ResourceA):
        self.resource = resource

    @override
    def get_resource(self) -> ResourceA: # incorrect on purpose to kick tires
        return self.resource

Now let's send in some messy stuff..

fr1 = ReaderA(ResourceB())
print('resourceA', fr1.get_resource().uri())

fr2 = ReaderB(ResourceC())
print('resourceB', fr2.get_resource().uri())

We get only the following output:

resourceA uri:ResourceB
resourceB uri:ResourceC

I realize these are generic type hints but still.. is there not some way to at least be notified /warned of the typing mismatch?  This is after all a compile time visibility situation.


问:
In Pandas, what is the correct dtype for binary (dummy) variables?
In Pandas, what is the correct dtype for binary (dummy) variables?

There are obviously lots of dtypes in Pandas, some of which are:
float64, int64, category, or simply object. To me, these all seem like correct dtypes for binary (dummy) variables. Which one is the right answer?

If the correct dtype is category, I have a follow-up question which is basically I am unable to cast a column in pandas as dtype='category', but we will cross that bridge when we get there.


问:
Crontab won't launch Node.js Discord bot on Ubuntu
I have a bot running on an Ubuntu machine which I'd like to autorun on boot, and so I'm using crontab's @reboot scheduled line for it:

@reboot ~/Bot/run

It works perfectly for all other scripts I have running on boot on my machine, but for this specific script, every line is seemingly being executed correctly, except for the one involving the actual node . command, which launches my Discord bot. The script works perfectly fine when I run it myself from a terminal. Here's the script in question, run.sh, very simple and short in nature:

```<code>#!/bin/bash

cd ~/Bot

echo "Launching Discord Bot"
screen -dmS BOT node .
</code>```

To sum it up, I first enter the correct working directory, send a basic echo, then create a new detached screen session called BOT, to which I pass the node . command, in which the period . implies the index.js file found in my bot's directory. And yes, I intend the screen session to automatically close if/when the bot's process stops.

As mentioned, it seems to actually run the script as intended, but just failing to launch the node.js server. I've tried adding other test lines to the script, including one that sends a message to said Discord server using a webhook, and it correctly sends the messages when placed before and after the node . line.

I've been troubleshooting this for a little while, and I've tried adding a task as a system service in /etc/systemd/system instead of using Crontab, to no avail. I've also tried setting the cronjob to use a login shell with bash -lc to set the proper environment variables for Crontab, still to no avail. I'm all out of solutions, would anyone know how to solve this issue?

Body:
I have a bot running on an Ubuntu machine which I'd like to autorun on boot, and so I'm using crontab's @reboot scheduled line for it:

@reboot ~/Bot/run

It works perfectly for all other scripts I have running on boot on my machine, but for this specific script, every line is seemingly being executed correctly, except for the one involving the actual node . command, which launches my Discord bot. The script works perfectly fine when I run it myself from a terminal. Here's the script in question, run.sh, very simple and short in nature:

#!/bin/bash

cd ~/Bot

echo "Launching Discord Bot"
screen -dmS BOT node .

To sum it up, I first enter the correct working directory, send a basic echo, then create a new detached screen session called BOT, to which I pass the node . command, in which the period . implies the index.js file found in my bot's directory. And yes, I intend the screen session to automatically close if/when the bot's process stops.

As mentioned, it seems to actually run the script as intended, but just failing to launch the node.js server. I've tried adding other test lines to the script, including one that sends a message to said Discord server using a webhook, and it correctly sends the messages when placed before and after the node . line.

I've been troubleshooting this for a little while, and I've tried adding a task as a system service in /etc/systemd/system instead of using Crontab, to no avail. I've also tried setting the cronjob to use a login shell with bash -lc to set the proper environment variables for Crontab, still to no avail. I'm all out of solutions, would anyone know how to solve this issue?


问:
Is there any way to detect or track the api call while building SSR page on server side render in next.js?
I am working on a complex system in which I am using useTranslation() hook. BTS it is a api call but while working SSR I want to track that api calls for performance while I hit that website on my browser. So is there any tool or any way available to track those kind of problems ?

I tried devtools of chrome browser but as it is SSR we can not track API call while building page on server side.


问:
How to run create-react-app dev server behind nginx proxy?
Previously create-react-app ok with Nginx. Straightforward Nginx configuration was doing the job. The dev server connection goes through /sockjs-node configuration. API connection goes through /api. Everything was fine. Simulates production-like environment without hassle.

```<code>        location / {
                proxy_pass http://127.0.0.1:3000;

                location /sockjs-node {
                        proxy_pass http://127.0.0.1:3000;
                        proxy_set_header Upgrade $http_upgrade;
                        proxy_set_header Connection "upgrade";
                        proxy_read_timeout 7d;
                }

                location /api {
                        proxy_pass http://127.0.0.1:8080/api;
                }
        }
</code>```

But now the latest version has a slight change. It tries to connect wss://my_local_domain:3000/ws. It skipped my proxy setup and tries directly connect to the dev server. And failed because it is cross-origin and has no SSL support.

The question is Is there a way to tell the dev server to use a path-relative URL?

Body:
Previously create-react-app ok with Nginx. Straightforward Nginx configuration was doing the job. The dev server connection goes through /sockjs-node configuration. API connection goes through /api. Everything was fine. Simulates production-like environment without hassle.

        location / {
                proxy_pass http://127.0.0.1:3000;

                location /sockjs-node {
                        proxy_pass http://127.0.0.1:3000;
                        proxy_set_header Upgrade $http_upgrade;
                        proxy_set_header Connection "upgrade";
                        proxy_read_timeout 7d;
                }

                location /api {
                        proxy_pass http://127.0.0.1:8080/api;
                }
        }

But now the latest version has a slight change. It tries to connect wss://my_local_domain:3000/ws. It skipped my proxy setup and tries directly connect to the dev server. And failed because it is cross-origin and has no SSL support.

The question is Is there a way to tell the dev server to use a path-relative URL?


问:
Custom CSS in Bokeh server embedded in Flask Application
I want to change the way tabs are rendered in a bokeh application embedded within a Flask Application, and cannot seem to find a way to do this with my current schema, which is as follows:

Bokeh is created in create_app(), borrowed from their server embed example:

```<code>def create_app():
        #------------------IRRELEVANT FLASK APP STUFF--------------------------------

        bkapp = Application(FunctionHandler(my_gui))

        # This is so that if this app is run using something like "gunicorn -w 4" then
        # each process will listen on its own port
        sockets, port = bind_sockets("localhost", 0)
        app._bokehport = port

        def bk_worker():

            asyncio.set_event_loop(asyncio.new_event_loop())

            bokeh_tornado = BokehTornado({'/bkapp': bkapp},
                                        extra_websocket_origins=["localhost:8000"])
            bokeh_http = HTTPServer(bokeh_tornado)
            bokeh_http.add_sockets(sockets)

            server = BaseServer(IOLoop.current(), bokeh_tornado, bokeh_http)
            server.start()
            server.io_loop.start()

        from threading import Thread
        Thread(target=bk_worker).start()
        return app
</code>```

my_gui is a bokeh app, very simplified version here:

```<code>def my_gui(doc):
    def toggleMakeCallback():
        rootLayout = doc.get_model_by_name('rootLayout')
        listOfSubLayouts = rootLayout.children

        p1 = figure(width=300, height=300)
        p1.circle([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], size=20, color="navy", alpha=0.5)
        tab1 = TabPanel(child=p1, title="circle")

        p2 = figure(width=300, height=300)
        p2.line([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], line_width=3, color="navy", alpha=0.5)
        tab2 = TabPanel(child=p2, title="line")
        tabs = Tabs(tabs=[ tab1, tab2 ])
        listOfSubLayouts.append(tabs)

    make_piece = Button(label="Make Piece", button_type="success")
    make_piece.on_click(toggleMakeCallback)
    rootLayout = layout(make_piece, name='rootLayout', sizing_mode="scale_both")
    doc.add_root(rootLayout)
    return doc
</code>```

In my Flask application this is how I route to the app.

```<code>@main_bp.route('/bokehexample', methods = ['GET', 'POST'])
@login_required
def bokehRoute():
    script = server_document('http://localhost:%d/bkapp' % current_app._bokehport,
                                arguments={"id": unsplitId, "teamId": teamId})
    return render_template("embed.html", script=script, template="Flask")
</code>```

Finally, this is embed.html:

```<code><!DOCTYPE html>
<html lang='en'>
    <head>
        <link rel="stylesheet" href="{{ url_for('static', filename='css/embed.css') }}">
        <title>PeachPortal - Split Pieces</title>
    </head>
    <body>
        {{ script|safe }}
  </body>
  </html>
</code>```

An example of a component of end goal CSS to change the tab design would be as follows:

```<code>.bk-root .bk-tabs-header .bk-tab.bk-active{
    background-color: green;
    color: red;
    font-style: normal;
    font-weight: bold;
}
</code>```

I've read and tried and failed with several ways of accomplishing custom CSS (the app just renders the default way no matter what I try):

Adding this css directly in a  tag in the head of embed.html

Adding this css into the embed.css file referenced in the head of embed.html

Adding this css in the head of embed.html with a django {%include customcss.css%}

Adding a css class such as css_classes =['custom_tab_bokeh'] to my tabs

I've seen another example using curstate, which I don't know how to use in an app context.

I am hoping somebody has successfully changed the CSS for a Bokeh widget using this schema or something similar.

Thank you.

Body:
I want to change the way tabs are rendered in a bokeh application embedded within a Flask Application, and cannot seem to find a way to do this with my current schema, which is as follows:

Bokeh is created in create_app(), borrowed from their server embed example:

def create_app():
        #------------------IRRELEVANT FLASK APP STUFF--------------------------------

        bkapp = Application(FunctionHandler(my_gui))

        # This is so that if this app is run using something like "gunicorn -w 4" then
        # each process will listen on its own port
        sockets, port = bind_sockets("localhost", 0)
        app._bokehport = port

        def bk_worker():

            asyncio.set_event_loop(asyncio.new_event_loop())

            bokeh_tornado = BokehTornado({'/bkapp': bkapp},
                                        extra_websocket_origins=["localhost:8000"])
            bokeh_http = HTTPServer(bokeh_tornado)
            bokeh_http.add_sockets(sockets)

            server = BaseServer(IOLoop.current(), bokeh_tornado, bokeh_http)
            server.start()
            server.io_loop.start()

        from threading import Thread
        Thread(target=bk_worker).start()
        return app

my_gui is a bokeh app, very simplified version here:

def my_gui(doc):
    def toggleMakeCallback():
        rootLayout = doc.get_model_by_name('rootLayout')
        listOfSubLayouts = rootLayout.children

        p1 = figure(width=300, height=300)
        p1.circle([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], size=20, color="navy", alpha=0.5)
        tab1 = TabPanel(child=p1, title="circle")

        p2 = figure(width=300, height=300)
        p2.line([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], line_width=3, color="navy", alpha=0.5)
        tab2 = TabPanel(child=p2, title="line")
        tabs = Tabs(tabs=[ tab1, tab2 ])
        listOfSubLayouts.append(tabs)

    make_piece = Button(label="Make Piece", button_type="success")
    make_piece.on_click(toggleMakeCallback)
    rootLayout = layout(make_piece, name='rootLayout', sizing_mode="scale_both")
    doc.add_root(rootLayout)
    return doc

In my Flask application this is how I route to the app.

@main_bp.route('/bokehexample', methods = ['GET', 'POST'])
@login_required
def bokehRoute():
    script = server_document('http://localhost:%d/bkapp' % current_app._bokehport,
                                arguments={"id": unsplitId, "teamId": teamId})
    return render_template("embed.html", script=script, template="Flask")

Finally, this is embed.html:

<!DOCTYPE html>

        <link rel="stylesheet" href="{{ url_for('static', filename='css/embed.css') }}">
        <title>PeachPortal - Split Pieces</title>

        {{ script|safe }}

An example of a component of end goal CSS to change the tab design would be as follows:

.bk-root .bk-tabs-header .bk-tab.bk-active{
    background-color: green;
    color: red;
    font-style: normal;
    font-weight: bold;
}

I've read and tried and failed with several ways of accomplishing custom CSS (the app just renders the default way no matter what I try):

Adding this css directly in a  tag in the head of embed.html

Adding this css into the embed.css file referenced in the head of embed.html

Adding this css in the head of embed.html with a django {%include customcss.css%}

Adding a css class such as css_classes =['custom_tab_bokeh'] to my tabs

I've seen another example using curstate, which I don't know how to use in an app context.

I am hoping somebody has successfully changed the CSS for a Bokeh widget using this schema or something similar.

Thank you.


问:
Why doesn't HttpContext.SignOutAsync invalidate the authentication cookie?
I am using ASP.NET Core 2.1, and I am building a website which uses the pretty basic kind of authentication, with cookies. I am using the builtin functionality for this, i.e. HTTPContext.SignInAsync and HTTPContext.SignOutAsync. It works well in the browser, I sign in, sign out, the ControllerBase.User property works as expected.

But I am also going to use that authentication for a REST API, and I am encountering a strange behavior. I am not sure whether it is a bug, or a feature, or just a misunderstanding, but after I sign out, if I keep the cookie in the headers, the User property still remains set, and access is allowed, even with [Authorize].

Is that supposed to happen? It does not seem logical. Signing out means closing the session, which means you have to sign in again to perform actions which require authentication.

But if this behavior is normal, what do I have to do to manually invalidate the authentication cookie on sign-out?

I can provide a minimal code to replicate this behavior on request.


问:
using environment variables in flywayMigrate with intellij
I configured flyway to use environment variables like so

```<code>flyway.url=${JDBC_DATABASE_URL}
flyway.locations=filesystem:db/migrations
</code>```

running JDBC_DATABASE_URL=... ./gradlew flyMigrate is working as expected. similarly, set -a && source dev.env && ./gradlew flyMigrate is working as expected.

The challange is using Intellij. I've set the environment varables with the command set -a && source dev.env && idea When I run the flyMigrate gradle task, it is not able to read the env variables.

However the following code is working as expected

```<code>public class TestEnv {
  public static void main(String[] args) {
    System.out.println(System.getenv("JDBC_DATABASE_URL"));
  }
}
</code>```

What am I missing?

Body:
I configured flyway to use environment variables like so

flyway.url=${JDBC_DATABASE_URL}
flyway.locations=filesystem:db/migrations

running JDBC_DATABASE_URL=... ./gradlew flyMigrate is working as expected. similarly, set -a && source dev.env && ./gradlew flyMigrate is working as expected.

The challange is using Intellij. I've set the environment varables with the command set -a && source dev.env && idea When I run the flyMigrate gradle task, it is not able to read the env variables.

However the following code is working as expected

public class TestEnv {
  public static void main(String[] args) {
    System.out.println(System.getenv("JDBC_DATABASE_URL"));
  }
}

What am I missing?


问:
How to generate token with JWT on Laravel 9
The problem is that it does not generate the TOKEN, throwing the following error
TypeError: Lcobucci\JWT\Token\Builder::relatedTo(): Argument #1 ($subject) must be of type string, null given

When I make the request through the post verb, it performs all the previous validation but when it comes to generating the token, the error occurs.

`

```<code>public function login(Request $request)
    {
        $credentials = $request->only('usuario', 'password');

        $validator = Validator::make($request->all(), [
            'usuario' => 'required',
            'password' => 'required'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => $validator->errors(),
                'token' => null
            ], 404);
        }

        $user = usuarios::where('usuario', $request->usuario)->first();

        if (!$user) {
            return response()->json([
                'message' => 'Usuario no registrado.',
                'token' => null
            ], 401);
        }

        $isValid = Hash::check($request->password, $user->password);

        if (!$isValid) {
            return response()->json([
                'message' => 'Contraseña incorrecta.'
            ]);
        }

        $token = JWTAuth::fromUser($user);

        return response()->json([
            'message' => 'Usuario logueado correctamente',
            'token' => $token
        ]);
    }
</code>```

`

And my code mode is this

`

```<code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
    //Añadimos la clase JWTSubject
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;

class usuarios extends Model implements JWTSubject
{
    use HasFactory, HasApiTokens, Notifiable;

    protected $table = 'usuarios';
    protected $fillable = [
        'tipo_usuario',
        'acceso_pv',
        'nombre',
        'usuario',
        'password',

    ];

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return [];
    }

    public $timestamps = false;
}

</code>```

`

Body:
The problem is that it does not generate the TOKEN, throwing the following error
TypeError: Lcobucci\JWT\Token\Builder::relatedTo(): Argument #1 ($subject) must be of type string, null given

When I make the request through the post verb, it performs all the previous validation but when it comes to generating the token, the error occurs.

`

public function login(Request $request)
    {
        $credentials = $request->only('usuario', 'password');

        $validator = Validator::make($request->all(), [
            'usuario' => 'required',
            'password' => 'required'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => $validator->errors(),
                'token' => null
            ], 404);
        }

        $user = usuarios::where('usuario', $request->usuario)->first();

        if (!$user) {
            return response()->json([
                'message' => 'Usuario no registrado.',
                'token' => null
            ], 401);
        }

        $isValid = Hash::check($request->password, $user->password);

        if (!$isValid) {
            return response()->json([
                'message' => 'Contraseña incorrecta.'
            ]);
        }

        $token = JWTAuth::fromUser($user);

        return response()->json([
            'message' => 'Usuario logueado correctamente',
            'token' => $token
        ]);
    }

`

And my code mode is this

`

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
    //Añadimos la clase JWTSubject
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;

class usuarios extends Model implements JWTSubject
{
    use HasFactory, HasApiTokens, Notifiable;

    protected $table = 'usuarios';
    protected $fillable = [
        'tipo_usuario',
        'acceso_pv',
        'nombre',
        'usuario',
        'password',

    ];

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return [];
    }

    public $timestamps = false;
}

`