问:
How to fix Eclipse Maven Package Error injecting constructor, java.lang.ExceptionInInitializerError
I am trying to build a simple Servlet, that should only return me the content that was sent with the request. It does not build though I did not do anything different then before qhen I made another Servlet a year ago (that does not compile anymore either).

I do not understand the Problem as I haven't made anything different then before. Has anyone an Idea what it might be?

I suspect it might have something to do with the maven-war-plugin as it sais in the errors something about an maven-war-plugin:2.2, which seam odd to me as I am not using that version. Does someone know how I could enforce the use of the current version I put in the pom.xml, to see if that would solve it?

It sais:

Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.2:war (default-war) on project LoginTest: Execution default-war of goal org.apache.maven.plugins:maven-war-plugin:2.2:war failed: Unable to load the mojo 'war' in the plugin 'org.apache.maven.plugins:maven-war-plugin:2.2' due to an API incompatibility: org.codehaus.plexus.component.repository.exception.ComponentLookupException: Cannot access defaults field of Properties

After this Error I get:

```<code>[WARNING] Error injecting: org.apache.maven.plugin.war.WarMojo
com.google.inject.ProvisionException: Unable to provision, see the following errors:

1) Error injecting constructor, java.lang.ExceptionInInitializerError: Cannot access defaults field of Properties
  at org.apache.maven.plugin.war.WarMojo.<init>(Unknown Source)
  while locating org.apache.maven.plugin.war.WarMojo

1 error
    at com.google.inject.internal.InternalProvisionException.toProvisionException(InternalProvisionException.java:226)
    at com.google.inject.internal.InjectorImpl$1.get(InjectorImpl.java:1053)
    at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1086)
    at org.eclipse.sisu.space.AbstractDeferredClass.get(AbstractDeferredClass.java:48)
    at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:85)
    at com.google.inject.internal.InternalFactoryToInitializableAdapter.provision(InternalFactoryToInitializableAdapter.java:57)
    at com.google.inject.internal.ProviderInternalFactory$1.call(ProviderInternalFactory.java:66)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:112)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:127)
    at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:66)
    at com.google.inject.internal.ProviderInternalFactory.circularGet(ProviderInternalFactory.java:61)
    at com.google.inject.internal.InternalFactoryToInitializableAdapter.get(InternalFactoryToInitializableAdapter.java:47)
    at com.google.inject.internal.InjectorImpl$1.get(InjectorImpl.java:1050)
    at org.eclipse.sisu.inject.Guice4$1.get(Guice4.java:162)
    at org.eclipse.sisu.inject.LazyBeanEntry.getValue(LazyBeanEntry.java:81)
    at org.eclipse.sisu.plexus.LazyPlexusBean.getValue(LazyPlexusBean.java:51)
    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:263)
    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:255)
    at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getConfiguredMojo(DefaultMavenPluginManager.java:520)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:124)
    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 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    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)
Caused by: java.lang.ExceptionInInitializerError: Cannot access defaults field of Properties
    at com.thoughtworks.xstream.converters.collections.PropertiesConverter.<clinit>(PropertiesConverter.java:46)
    at com.thoughtworks.xstream.XStream.setupConverters(XStream.java:647)
    at com.thoughtworks.xstream.XStream.<init>(XStream.java:445)
    at com.thoughtworks.xstream.XStream.<init>(XStream.java:385)
    at com.thoughtworks.xstream.XStream.<init>(XStream.java:342)
    at org.apache.maven.plugin.war.util.WebappStructureSerializer.<clinit>(WebappStructureSerializer.java:47)
    at org.apache.maven.plugin.war.AbstractWarMojo.<init>(AbstractWarMojo.java:316)
    at org.apache.maven.plugin.war.WarMojo.<init>(WarMojo.java:49)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
    at com.google.inject.internal.DefaultConstructionProxyFactory$ReflectiveProxy.newInstance(DefaultConstructionProxyFactory.java:126)
    at com.google.inject.internal.ConstructorInjector.provision(ConstructorInjector.java:114)
    at com.google.inject.internal.ConstructorInjector.access$000(ConstructorInjector.java:32)
    at com.google.inject.internal.ConstructorInjector$1.call(ConstructorInjector.java:98)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:112)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:127)
    at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:66)
    at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:93)
    at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:306)
    at com.google.inject.internal.InjectorImpl$1.get(InjectorImpl.java:1050)
    ... 39 more
</code>```

My pom.xml looks like that:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>eu.jlmb</groupId>
    <artifactId>ServletTest</artifactId>
    <packaging>war</packaging>
    <version>0.0.1</version>
    <name>ServletTest Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

    <dependencies>

        <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.8.2</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.9.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-war-plugin -->
        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>3.3.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.json/json -->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20211205</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>ServletTest</finalName>
    </build>
</project>
</code>```

答:
As pointed out by khmarbaise, my problem was that I had the plugins listed as dependencies in the pom file. Adding them correctly as plugins and removing their information from the dependecies fixed it for me.

My pom depnedencies and build now look like this:

```<code><dependencies>

    <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.8.2</version>
        <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
    <!-- <dependency>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.9.0</version>
    </dependency>-->

    <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-war-plugin -->
    <!--<dependency>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.3.2</version>
    </dependency>-->

</dependencies>

<build>
    <finalName>LoginTest</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>3.3.2</version>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.9.0</version>
        </plugin>
    </plugins>
</build>
</code>```

Body:
I am trying to build a simple Servlet, that should only return me the content that was sent with the request. It does not build though I did not do anything different then before qhen I made another Servlet a year ago (that does not compile anymore either).

I do not understand the Problem as I haven't made anything different then before. Has anyone an Idea what it might be?

I suspect it might have something to do with the maven-war-plugin as it sais in the errors something about an maven-war-plugin:2.2, which seam odd to me as I am not using that version. Does someone know how I could enforce the use of the current version I put in the pom.xml, to see if that would solve it?

It sais:

Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.2:war (default-war) on project LoginTest: Execution default-war of goal org.apache.maven.plugins:maven-war-plugin:2.2:war failed: Unable to load the mojo 'war' in the plugin 'org.apache.maven.plugins:maven-war-plugin:2.2' due to an API incompatibility: org.codehaus.plexus.component.repository.exception.ComponentLookupException: Cannot access defaults field of Properties

After this Error I get:

[WARNING] Error injecting: org.apache.maven.plugin.war.WarMojo
com.google.inject.ProvisionException: Unable to provision, see the following errors:

1) Error injecting constructor, java.lang.ExceptionInInitializerError: Cannot access defaults field of Properties
  at org.apache.maven.plugin.war.WarMojo.<init>(Unknown Source)
  while locating org.apache.maven.plugin.war.WarMojo

1 error
    at com.google.inject.internal.InternalProvisionException.toProvisionException(InternalProvisionException.java:226)
    at com.google.inject.internal.InjectorImpl$1.get(InjectorImpl.java:1053)
    at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1086)
    at org.eclipse.sisu.space.AbstractDeferredClass.get(AbstractDeferredClass.java:48)
    at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:85)
    at com.google.inject.internal.InternalFactoryToInitializableAdapter.provision(InternalFactoryToInitializableAdapter.java:57)
    at com.google.inject.internal.ProviderInternalFactory$1.call(ProviderInternalFactory.java:66)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:112)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:127)
    at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:66)
    at com.google.inject.internal.ProviderInternalFactory.circularGet(ProviderInternalFactory.java:61)
    at com.google.inject.internal.InternalFactoryToInitializableAdapter.get(InternalFactoryToInitializableAdapter.java:47)
    at com.google.inject.internal.InjectorImpl$1.get(InjectorImpl.java:1050)
    at org.eclipse.sisu.inject.Guice4$1.get(Guice4.java:162)
    at org.eclipse.sisu.inject.LazyBeanEntry.getValue(LazyBeanEntry.java:81)
    at org.eclipse.sisu.plexus.LazyPlexusBean.getValue(LazyPlexusBean.java:51)
    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:263)
    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:255)
    at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getConfiguredMojo(DefaultMavenPluginManager.java:520)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:124)
    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 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    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)
Caused by: java.lang.ExceptionInInitializerError: Cannot access defaults field of Properties
    at com.thoughtworks.xstream.converters.collections.PropertiesConverter.<clinit>(PropertiesConverter.java:46)
    at com.thoughtworks.xstream.XStream.setupConverters(XStream.java:647)
    at com.thoughtworks.xstream.XStream.<init>(XStream.java:445)
    at com.thoughtworks.xstream.XStream.<init>(XStream.java:385)
    at com.thoughtworks.xstream.XStream.<init>(XStream.java:342)
    at org.apache.maven.plugin.war.util.WebappStructureSerializer.<clinit>(WebappStructureSerializer.java:47)
    at org.apache.maven.plugin.war.AbstractWarMojo.<init>(AbstractWarMojo.java:316)
    at org.apache.maven.plugin.war.WarMojo.<init>(WarMojo.java:49)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
    at com.google.inject.internal.DefaultConstructionProxyFactory$ReflectiveProxy.newInstance(DefaultConstructionProxyFactory.java:126)
    at com.google.inject.internal.ConstructorInjector.provision(ConstructorInjector.java:114)
    at com.google.inject.internal.ConstructorInjector.access$000(ConstructorInjector.java:32)
    at com.google.inject.internal.ConstructorInjector$1.call(ConstructorInjector.java:98)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:112)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:127)
    at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:66)
    at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:93)
    at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:306)
    at com.google.inject.internal.InjectorImpl$1.get(InjectorImpl.java:1050)
    ... 39 more

My pom.xml looks like that:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>eu.jlmb</groupId>
    <artifactId>ServletTest</artifactId>
    <packaging>war</packaging>
    <version>0.0.1</version>
    <name>ServletTest Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.8.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.9.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>3.3.2</version>
        </dependency>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20211205</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>ServletTest</finalName>
    </build>
</project>

Body:
As pointed out by khmarbaise, my problem was that I had the plugins listed as dependencies in the pom file. Adding them correctly as plugins and removing their information from the dependecies fixed it for me.

My pom depnedencies and build now look like this:

<dependencies>

    <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.8.2</version>
        <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
    <!-- <dependency>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.9.0</version>
    </dependency>-->

    <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-war-plugin -->
    <!--<dependency>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.3.2</version>
    </dependency>-->

</dependencies>

<build>
    <finalName>LoginTest</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>3.3.2</version>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.9.0</version>
        </plugin>
    </plugins>
</build>


来源: stackexchange

问:
Comparing dates with getTime() in EST timezone
I am looking if there is a better way (other than below solution) of comparing dates for all users (in different countries) in EST timezone. Need your inputs/help.

Basically I have to display three UI's based on  three different dates. Till June, 1st UI has to render, June to July second UI and from July 3rd UI has to display. These dates while comparing should be in EST timezone.

```<code>  const JulyDate = new Date("2022-07-01T00:00:00.000-05:00");
  const JuneDate = new Date("2022-06-01T00:00:00.000-05:00");
  if(new Date().getTime() < JuneDate.getTime()){
    renderUIPriorJune= true;
    renderUIJune= false;
    renderUIJuly= false;
  }
  else if(new Date().getTime() >= JuneDate.getTime() && new Date().getTime() < JulyDate.getTime()){
    renderUIPriorJune= false;
    renderUIJune= true;
    renderUIJuly= false;

  }
  else if(new Date().getTime() >= JulyDate.getTime()){
    renderUIPriorJune= false;
    renderUIJune= false;
    renderUIJuly= true;

  }

</code>```

I have defined June and July dates in EST timezone i.e. -5 hours as offset and then current date is compared with those dates.

Could you please let me know if this is the correct way of comparing or Is there a better way of doing. I am rather new to Java script.

Thank you in advance.

答:
For any date manipulation or comparison, you should be using a library. A good one is dayjs.

To find if a date is before june 1st, you don't have to care about the time, just compare the dates. Dayjs has a method isBefore which takes granularity as one of the arguments. If you set the granularity to day, it will compare year, month and day, but not hour, minute, etc.

```<code>const now = dayjs();
const isBeforeJune = now.isBefore('2022-06-01', 'month')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am looking if there is a better way (other than below solution) of comparing dates for all users (in different countries) in EST timezone. Need your inputs/help.

Basically I have to display three UI's based on  three different dates. Till June, 1st UI has to render, June to July second UI and from July 3rd UI has to display. These dates while comparing should be in EST timezone.

  const JulyDate = new Date("2022-07-01T00:00:00.000-05:00");
  const JuneDate = new Date("2022-06-01T00:00:00.000-05:00");
  if(new Date().getTime() < JuneDate.getTime()){
    renderUIPriorJune= true;
    renderUIJune= false;
    renderUIJuly= false;
  }
  else if(new Date().getTime() >= JuneDate.getTime() && new Date().getTime() < JulyDate.getTime()){
    renderUIPriorJune= false;
    renderUIJune= true;
    renderUIJuly= false;

  }
  else if(new Date().getTime() >= JulyDate.getTime()){
    renderUIPriorJune= false;
    renderUIJune= false;
    renderUIJuly= true;

  }

I have defined June and July dates in EST timezone i.e. -5 hours as offset and then current date is compared with those dates.

Could you please let me know if this is the correct way of comparing or Is there a better way of doing. I am rather new to Java script.

Thank you in advance.

Body:
For any date manipulation or comparison, you should be using a library. A good one is dayjs.

To find if a date is before june 1st, you don't have to care about the time, just compare the dates. Dayjs has a method isBefore which takes granularity as one of the arguments. If you set the granularity to day, it will compare year, month and day, but not hour, minute, etc.

const now = dayjs();
const isBeforeJune = now.isBefore('2022-06-01', 'month')


问:
How do I access consecutive elements in an IQueryable<T> object?
I need to access the current and previous element in an IQueryable object. If I had an int array, I would do the following:

```<code>var array = new int[]{0,1,2,3,4};
for(var i = 1; i<array.Length ; i++)
{
    method1(array[i-1], array[i]);
}
</code>```

I don't know to do the same with IQueryable, since it does not implement IList.

答:
Using extension methods makes this fairly easy.

```<code>public static class IEnumerableExtensions
{
  public static IEnumerable<ValueWithPrevious<T>> WithPrevious<T>(this IEnumerable<T> @this)
  {
    using (var e = @this.GetEnumerator())
    {
      if (!e.MoveNext())
        yield break;

      var previous = e.Current;

      while (e.MoveNext())
      {
        yield return new ValueWithPrevious<T>(e.Current, previous);
        previous = e.Current;
      }
    }
  }
}

public struct ValueWithPrevious<T>
{
  public readonly T Value, Previous;

  public ValueWithPrevious(T value, T previous)
  {
    Value = value;
    Previous = previous;
  }
}
</code>```

Usage:

```<code>var array = new int[] { 1, 2, 3, 4, 5 };
foreach (var value in array.WithPrevious())
{
  Console.WriteLine("{0}, {1}", value.Previous, value.Value);
  // Results: 1, 2
  //          2, 3
  //          3, 4
  //          4, 5
}
</code>```

OwnerDisplayName: Jader Dias

ContentLicense: CC BY-SA 2.5

Body:
I need to access the current and previous element in an IQueryable object. If I had an int array, I would do the following:

var array = new int[]{0,1,2,3,4};
for(var i = 1; i<array.Length ; i++)
{
    method1(array[i-1], array[i]);
}

I don't know to do the same with IQueryable, since it does not implement IList.

LastEditorDisplayName: JaredPar

Body:
Using extension methods makes this fairly easy.

public static class IEnumerableExtensions
{
  public static IEnumerable<ValueWithPrevious<T>> WithPrevious<T>(this IEnumerable<T> @this)
  {
    using (var e = @this.GetEnumerator())
    {
      if (!e.MoveNext())
        yield break;

      var previous = e.Current;

      while (e.MoveNext())
      {
        yield return new ValueWithPrevious<T>(e.Current, previous);
        previous = e.Current;
      }
    }
  }
}

public struct ValueWithPrevious<T>
{
  public readonly T Value, Previous;

  public ValueWithPrevious(T value, T previous)
  {
    Value = value;
    Previous = previous;
  }
}

Usage:

var array = new int[] { 1, 2, 3, 4, 5 };
foreach (var value in array.WithPrevious())
{
  Console.WriteLine("{0}, {1}", value.Previous, value.Value);
  // Results: 1, 2
  //          2, 3
  //          3, 4
  //          4, 5
}

OwnerDisplayName: Samuel

LastEditorDisplayName: Samuel


问:
How can I set httpOnly enabled cookie in react js?
I have generated and set cookie at frontend itself (React JS) using js-cookie library which was working fine until I was using it with httpOnly set as false.
Now, my condition is set httpOnly as true but I'm not able to achieve this because I found on internet that if we will set the cookie with httpOnly = true then I will not able to get the cookie using javascript (viz. React JS) which is just a feature of httpOnly cookie.

I searched and found one related library called "react-cookie" can
be found https://www.npmjs.com/package/react-cookie but with
this library also I don't know how my javascript will able to get
the cookie.

Also, I found somewhere that we can use express server
as middleware between actual processing server and we can set and
get our secured cookie at express server but I would be large task
to switch at this stage.

Can anyone suggest me some other better approach to set and get my cookie with httpOnly set as true using react js.
All the suggestions are welcomed! Thanks in advance.

答:
You should set httpOnly to in the backend, also no need to send cookie by each request because it's included in every request.
also to work in react app you should set sameSite to "None", secure to true along with httpOnly to true</p>


问:
Whitespace as a value in .ini file
I want my .ini file to have an option to specify a certain character as a splitter for the parameters which is then handled with Python. That is:

```<code>[meta]
split_char = " "

[stuff]
field = value_1 value_2
</code>```

How can I specify a whitespace as a split char so it is recognizable? I have tried " " or [ ] and some other oprions, neither of them works.

As I've been asked, here is the Python scripts to read the .ini file:

```<code>from configparser import ConfigParser

config = ConfigParser()
config.read('config.ini')

# I need a nested dictionary, but this is not the point
split_char = config["meta"]["split_char"]
config = {section: dict(config.items(section)) for section in config.sections() if section != "meta"}
for section in config:
    for parameter in config[section]:
        config[section][parameter] = config[section][parameter].split(split_char)
</code>```

If I place a whitespace as it is, Python considers the splitter empty, adding quotes or any other auxiliary signs does not get the things done.

Update

The thing is that I would also like to be able to require splitters like ', ', which is a string with a whitespace.

答:
I'm afraid you are out of luck with the whitespace as separator. ConfigParser calls str.strip on the value after the delimiter.

But this means essentially that whenever you specify a whitespace as split_car you will get '' as value for it. Since '' is not a valid separator in a string you could simply replace '' with ' ' when getting split_char from config["meta"]["split_char"].

Basically you could adapt the line split_char = config["meta"]["split_char"] to:

```<code>split_char = config["meta"]["split_char"] or ' '
</code>```

and you are good to go!

Title: Whitespace as a value in .ini file

Body:
I want my .ini file to have an option to specify a certain character as a splitter for the parameters which is then handled with Python. That is:

[meta]
split_char = " "

[stuff]
field = value_1 value_2

How can I specify a whitespace as a split char so it is recognizable? I have tried " " or [ ] and some other oprions, neither of them works.

As I've been asked, here is the Python scripts to read the .ini file:

from configparser import ConfigParser

config = ConfigParser()
config.read('config.ini')

# I need a nested dictionary, but this is not the point
split_char = config["meta"]["split_char"]
config = {section: dict(config.items(section)) for section in config.sections() if section != "meta"}
for section in config:
    for parameter in config[section]:
        config[section][parameter] = config[section][parameter].split(split_char)

If I place a whitespace as it is, Python considers the splitter empty, adding quotes or any other auxiliary signs does not get the things done.

Update

The thing is that I would also like to be able to require splitters like ', ', which is a string with a whitespace.

Body:
I'm afraid you are out of luck with the whitespace as separator. ConfigParser calls str.strip on the value after the delimiter.

But this means essentially that whenever you specify a whitespace as split_car you will get '' as value for it. Since '' is not a valid separator in a string you could simply replace '' with ' ' when getting split_char from config["meta"]["split_char"].

Basically you could adapt the line split_char = config["meta"]["split_char"] to:

split_char = config["meta"]["split_char"] or ' '

and you are good to go!


问:
Shift elements in a numpy array
This question contains its own answer at the bottom. Use preallocated arrays.

Following-up from this question years ago, is there a canonical "shift" function in numpy? I don't see anything from the documentation.

Here's a simple version of what I'm looking for:

```<code>def shift(xs, n):
    if n >= 0:
        return np.r_[np.full(n, np.nan), xs[:-n]]
    else:
        return np.r_[xs[-n:], np.full(-n, np.nan)]
</code>```

Using this is like:

```<code>In [76]: xs
Out[76]: array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.])

In [77]: shift(xs, 3)
Out[77]: array([ nan,  nan,  nan,   0.,   1.,   2.,   3.,   4.,   5.,   6.])

In [78]: shift(xs, -3)
Out[78]: array([  3.,   4.,   5.,   6.,   7.,   8.,   9.,  nan,  nan,  nan])
</code>```

This question came from my attempt to write a fast rolling_product yesterday. I needed a way to "shift" a cumulative product and all I could think of was to replicate the logic in np.roll().

So np.concatenate() is much faster than np.r_[]. This version of the function performs a lot better:

```<code>def shift(xs, n):
    if n >= 0:
        return np.concatenate((np.full(n, np.nan), xs[:-n]))
    else:
        return np.concatenate((xs[-n:], np.full(-n, np.nan)))
</code>```

An even faster version simply pre-allocates the array:

```<code>def shift(xs, n):
    e = np.empty_like(xs)
    if n >= 0:
        e[:n] = np.nan
        e[n:] = xs[:-n]
    else:
        e[n:] = np.nan
        e[:n] = xs[-n:]
    return e
</code>```

The above proposal is the answer. Use preallocated arrays.

答:
I think I have a quicker solution: why don't just use deque ?
I added 2 benchmark to the benchmarked solution from @gzc:

```<code>def shift6(arr, num, fill_value=np.nan):
    for _ in range(num):
        darr.appendleft(fill_value)

def shift7(arr, num, fill_value=np.nan):
    darr = deque(arr)
    for _ in range(num):
        darr.appendleft(fill_value)

darr = deque(arr)

def benchmark_shift6():
    shift6(arr, 3)

def benchmark_shift7():
    shift6(arr, 3)

benchmark_set = ['benchmark_shift1', 'benchmark_shift2', 'benchmark_shift3', 'benchmark_shift4', 'benchmark_shift5', 'benchmark_shift6', 'benchmark_shift7']
</code>```

And on my laptop the output is a lot of better than any other solutions proposed:

```<code>%s time: ('benchmark_shift1', 0.08232757700170623)
%s time: ('benchmark_shift2', 0.0934765400015749)
%s time: ('benchmark_shift3', 0.14349375600431813)
%s time: ('benchmark_shift4', 0.03575193700089585)
%s time: ('benchmark_shift5', 0.01389261399890529)
%s time: ('benchmark_shift6', 0.0025887360025080852)
%s time: ('benchmark_shift7', 0.0024806019937386736)
</code>```

Title: Shift elements in a numpy array

Body:
This question contains its own answer at the bottom. Use preallocated arrays.

Following-up from this question years ago, is there a canonical "shift" function in numpy? I don't see anything from the documentation.

Here's a simple version of what I'm looking for:

def shift(xs, n):
    if n >= 0:
        return np.r_[np.full(n, np.nan), xs[:-n]]
    else:
        return np.r_[xs[-n:], np.full(-n, np.nan)]

Using this is like:

In [76]: xs
Out[76]: array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.])

In [77]: shift(xs, 3)
Out[77]: array([ nan,  nan,  nan,   0.,   1.,   2.,   3.,   4.,   5.,   6.])

In [78]: shift(xs, -3)
Out[78]: array([  3.,   4.,   5.,   6.,   7.,   8.,   9.,  nan,  nan,  nan])

This question came from my attempt to write a fast rolling_product yesterday. I needed a way to "shift" a cumulative product and all I could think of was to replicate the logic in np.roll().

So np.concatenate() is much faster than np.r_[]. This version of the function performs a lot better:

def shift(xs, n):
    if n >= 0:
        return np.concatenate((np.full(n, np.nan), xs[:-n]))
    else:
        return np.concatenate((xs[-n:], np.full(-n, np.nan)))

An even faster version simply pre-allocates the array:

def shift(xs, n):
    e = np.empty_like(xs)
    if n >= 0:
        e[:n] = np.nan
        e[n:] = xs[:-n]
    else:
        e[n:] = np.nan
        e[:n] = xs[-n:]
    return e

The above proposal is the answer. Use preallocated arrays.

Body:
I think I have a quicker solution: why don't just use deque ?
I added 2 benchmark to the benchmarked solution from @gzc:

def shift6(arr, num, fill_value=np.nan):
    for _ in range(num):
        darr.appendleft(fill_value)

def shift7(arr, num, fill_value=np.nan):
    darr = deque(arr)
    for _ in range(num):
        darr.appendleft(fill_value)

darr = deque(arr)

def benchmark_shift6():
    shift6(arr, 3)

def benchmark_shift7():
    shift6(arr, 3)

benchmark_set = ['benchmark_shift1', 'benchmark_shift2', 'benchmark_shift3', 'benchmark_shift4', 'benchmark_shift5', 'benchmark_shift6', 'benchmark_shift7']

And on my laptop the output is a lot of better than any other solutions proposed:

%s time: ('benchmark_shift1', 0.08232757700170623)
%s time: ('benchmark_shift2', 0.0934765400015749)
%s time: ('benchmark_shift3', 0.14349375600431813)
%s time: ('benchmark_shift4', 0.03575193700089585)
%s time: ('benchmark_shift5', 0.01389261399890529)
%s time: ('benchmark_shift6', 0.0025887360025080852)
%s time: ('benchmark_shift7', 0.0024806019937386736)


问:
how to count the num of ports in docker ps cmd?
```<code>docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                           NAMES
f56084659b2a        nginx:alpine        "/docker-entrypoint.…"   35 seconds ago      Up 33 seconds       0.0.0.0:3456->3456/tcp, 0.0.0.0:38080->80/tcp   xenodochial_perlman
</code>```

what is the cmd to actually count num of ports from PORTS column in 1 line?

答:
Ports in itself is a long string, even though it looks like a list. You can see that by using {{ json . }} or {{ json .Ports }}.

You can work around that by using the split function and then calling len on the resulting slice.

docker ps --format '{{ len (split .Ports ",") }}'
```
<p>Furthermore, you can still show it in a table, but the column name for that <code>len</code> column will be a number. I have not found out yet how to rename columns with the table function. I did ask one time in the slack group, but didn't get an answer to that.</p>
```docker ps --format 'table {{.Names }}\t{{ len (split .Ports ",") }}'
```

Body:
docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                           NAMES
f56084659b2a        nginx:alpine        "/docker-entrypoint.…"   35 seconds ago      Up 33 seconds       0.0.0.0:3456->3456/tcp, 0.0.0.0:38080->80/tcp   xenodochial_perlman

what is the cmd to actually count num of ports from PORTS column in 1 line?

Body:
Ports in itself is a long string, even though it looks like a list. You can see that by using {{ json . }} or {{ json .Ports }}.

You can work around that by using the split function and then calling len on the resulting slice.

docker ps --format '{{ len (split .Ports ",") }}'

Furthermore, you can still show it in a table, but the column name for that len column will be a number. I have not found out yet how to rename columns with the table function. I did ask one time in the slack group, but didn't get an answer to that.

docker ps --format 'table {{.Names }}\t{{ len (split .Ports ",") }}'


问:
VBA find same cell values, count and calculate
I want to count all the same values in column C and calculate something from the number of the same values * 10 / the associated B value of the cells.

example

If C3, C6 and C8 are the same then

Number of same values -> (3) * 10 / (B3B6B8)/4

So far I've only found one way to compare the whole thing.

```<code>Sub Check()

Dim CRange As Range
Dim myValue
Dim allSame As Boolean

Set CRange = Range("C1:C30")

myValue = CRange(1, 1).Value

allSame = (WorksheetFunction.CountA(CRange) = WorksheetFunction.CountIf(CRange, myValue))
MsgBox allSame
</code>```

End Sub

答:
Are you looking for something like the following?

```<code>Dim RunningTotal , NumberCells, MyValue as Integer
MyValue = sheets(1).range("C1").value
For i = 2 to 30
    If (sheets(1).range("C" & i).value=MyValue)
    Then
        RunningTotal = RunningTotal + (sheets(1).range("B"&I).value
        NumberCells = NumberCells + 1
    End if
End for
MsgBox(RunningTotal & " : " & NumberCells)
</code>```

The final calcule is not clearly explained but this retrieves the values needed to find it.

Body:
I want to count all the same values in column C and calculate something from the number of the same values * 10 / the associated B value of the cells.

example

If C3, C6 and C8 are the same then

Number of same values -> (3) * 10 / (B3B6B8)/4

So far I've only found one way to compare the whole thing.

Sub Check()

Dim CRange As Range
Dim myValue
Dim allSame As Boolean

Set CRange = Range("C1:C30")

myValue = CRange(1, 1).Value

allSame = (WorksheetFunction.CountA(CRange) = WorksheetFunction.CountIf(CRange, myValue))
MsgBox allSame

End Sub

Body:
Are you looking for something like the following?

Dim RunningTotal , NumberCells, MyValue as Integer
MyValue = sheets(1).range("C1").value
For i = 2 to 30
    If (sheets(1).range("C" & i).value=MyValue)
    Then
        RunningTotal = RunningTotal + (sheets(1).range("B"&I).value
        NumberCells = NumberCells + 1
    End if
End for
MsgBox(RunningTotal & " : " & NumberCells)

The final calcule is not clearly explained but this retrieves the values needed to find it.


问:
How to use Moq to return a List of data or values?
Can anyone tell me how to return List of data using mock object using Moq framework and assigning the so returned list of data to another List<> variable.??</p>

答:
@Richard Banks gave the correct answer. For completeness, if you want to use Moq v4 functional specifications and get rid of the .Object:</p>

```<code>void Main()
{
    var list = new List<int> { 1, 2, 3 };

    ISomeInterface implementation =
        Mock.Of<ISomeInterface>(si => si.GimmeSomeData() == list);

    List<int> resultList = implementation.GimmeSomeData();

    foreach (int i in resultList)
    {
        Console.WriteLine(i);
    }
}

public interface ISomeInterface
{
    List<int> GimmeSomeData();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
@Richard Banks gave the correct answer. For completeness, if you want to use Moq v4 functional specifications and get rid of the .Object:

void Main()
{
    var list = new List<int> { 1, 2, 3 };

    ISomeInterface implementation =
        Mock.Of<ISomeInterface>(si => si.GimmeSomeData() == list);

    List<int> resultList = implementation.GimmeSomeData();

    foreach (int i in resultList)
    {
        Console.WriteLine(i);
    }
}

public interface ISomeInterface
{
    List<int> GimmeSomeData();
}


问:
React Native SectionList scroll to section
I just changed my ListView to React Native's new SectionList and now the app crashes when I attempt to use the scrollTo function, stating that it's undefined. I tried looking up new/alternative functions that may help, but none of them seem to be working.

What's the proper protocol for programmatically scrolling to a specific section with the new SectionList?

Links I've been consulting thus far:
https://github.com/facebook/react-native/issues/13151
https://facebook.github.io/react-native/releases/0.43/docs/virtualizedlist.html#scrolltoend

My current attempt:

```<code>var params = {animated:true,offset:Platform.OS == "ios" ? 244 : 264}
_mainListView.scrollToOffset(params)
</code>```

答:
This is how I scroll to end

listRef.current?.scrollToLocation({
  animated: true,
  sectionIndex: sections.length - 1,
  itemIndex: sections[sections.length - 1].data.length - 1,
})
```
<p>This is how I scroll to top</p>
<pre class="lang-js prettyprint-override"><code>listRef.current?.scrollToLocation({
  animated: true,
  sectionIndex: 0,
  itemIndex: 0,
})
</code>```

Body:
I just changed my ListView to React Native's new SectionList and now the app crashes when I attempt to use the scrollTo function, stating that it's undefined. I tried looking up new/alternative functions that may help, but none of them seem to be working.

What's the proper protocol for programmatically scrolling to a specific section with the new SectionList?

Links I've been consulting thus far:
https://github.com/facebook/react-native/issues/13151
https://facebook.github.io/react-native/releases/0.43/docs/virtualizedlist.html#scrolltoend

My current attempt:

var params = {animated:true,offset:Platform.OS == "ios" ? 244 : 264}
_mainListView.scrollToOffset(params)

Body:
This is how I scroll to end

listRef.current?.scrollToLocation({
  animated: true,
  sectionIndex: sections.length - 1,
  itemIndex: sections[sections.length - 1].data.length - 1,
})

This is how I scroll to top

listRef.current?.scrollToLocation({
  animated: true,
  sectionIndex: 0,
  itemIndex: 0,
})


问:
append string to string array if not array yet
I want to create a array of strings by appending, but it matters if the origin is an array or yet a string.
Therefore I need to convert a string like "abc" to a string array.

if I use

```<code>Array.from()
</code>```

it makes me something like this ["a","b","c"]
but I want to have ["abc"];

Is there a easy way that takes an input like
"abc"
and at the same time ["a","abc"]
I so that I can append later one one more string with push for example?

some constraints:
I cannot create

```<code>let a = [];
</code>```

because it is coming from extern.
And sure, I can add some code to check what is its, but I search for a simple mechanism.

I think i need something like
arr1.flat();

答:
I'm not quite sure if I understand your question correctly, you want to either append the source to an existing array if it's a string or concatenate the source if it's already an array?

Have you tried typeof? See the MDN typeof docs

```<code>if (typeof origin === 'string') {
   mylist.push(origin)
} else {
   mylist = mylist.concat(origin)
}
</code>```

EDIT:
As per NiceBooks comment:

```<code>let str = new String('Hello, world')
typeof str // 'object'
</code>```

(source)

Therefore, as they suggested the following might be better:

```<code>if (Array.isArray(origin)) {
   mylist = mylist.concat(origin) // there are more cleaner ways, for starters this should be fine
} else {
   mylist.push(origin)
}
</code>```

Body:
I want to create a array of strings by appending, but it matters if the origin is an array or yet a string.
Therefore I need to convert a string like "abc" to a string array.

if I use

Array.from()

it makes me something like this ["a","b","c"]
but I want to have ["abc"];

Is there a easy way that takes an input like
"abc"
and at the same time ["a","abc"]
I so that I can append later one one more string with push for example?

some constraints:
I cannot create

let a = [];

because it is coming from extern.
And sure, I can add some code to check what is its, but I search for a simple mechanism.

I think i need something like
arr1.flat();

Body:
I'm not quite sure if I understand your question correctly, you want to either append the source to an existing array if it's a string or concatenate the source if it's already an array?

Have you tried typeof? See the MDN typeof docs

if (typeof origin === 'string') {
   mylist.push(origin)
} else {
   mylist = mylist.concat(origin)
}

EDIT:
As per NiceBooks comment:

let str = new String('Hello, world')
typeof str // 'object'

(source)

Therefore, as they suggested the following might be better:

if (Array.isArray(origin)) {
   mylist = mylist.concat(origin) // there are more cleaner ways, for starters this should be fine
} else {
   mylist.push(origin)
}


问:
How to filter some results in JSON while parsing it
I'm parsing the JSON from this page with the following .net framework code:

```<code>Dim jsonString As String
       Using http As HttpClient = New HttpClient
           Dim url As String = "https://api-cloud.bitmart.com/account/v1/currencies"

           Dim streamData As Stream = Await http.GetStreamAsync(url)

           Using sr As StreamReader = New StreamReader(streamData)
               jsonString = sr.ReadToEnd
           End Using
           streamData.Close()
       End Using

       Dim jsonResponse As JObject = JObject.Parse(jsonString)
       Dim jsonData As JObject = CType(jsonResponse("data"), JObject)
       Dim jsonCurrencies As JArray = CType(jsonData("currencies"), JArray)

       Dim c As String = String.Empty
       Dim n As String = String.Empty
       For Each jsonCurrency As JObject In jsonCurrencies
           c += jsonCurrency("currency").ToString + " - " & jsonCurrency("network").ToString + vbLf

       Next
       RichTextBox1.Text += c
</code>```

it is working perfectly, but I thought all the results were on "true, true"
but the now I sow there are also results like

"withdraw_enabled":false,"deposit_enabled":false}
which I really don't need to be parsed.

the results I'm interested on are firstly

"withdraw_enabled":true,"deposit_enabled":true}

and in cases like the following, I would like to parse them but I want to know which between withdraw and deposit is on true and/or false

"withdraw_enabled":false,"deposit_enabled":true}

As a summary:

if JSON is

```<code>[{"currency":"DFC","name":"DefiConnect","network":"BEP20","withdraw_enabled":true,"deposit_enabled":true},
</code>```

the output is

DFC - BEP20 ( my code is already working for this case)

if JSON is

```<code>{"currency":"HOG","name":"HOG Finance","network":"BEP20(BSC)","withdraw_enabled":true,"deposit_enabled":false},
</code>```

the output should be

HOG - BEP20(BSC) [withdraw: Yes - deposit: NO]

and if JSON is

```<code>{"currency":"SGE","name":"Society of Galactic Exploration","network":"ERC20","withdraw_enabled":false,"deposit_enabled":false}
</code>```

I dont need to parse it.

Do you think It could be possible?
Hope I've been clear.
Thanks

答:
Instead of using the generic JObject, you can deserialize into an actual class.

    Public Class RootObject
        Public Property Message As String
        Public Property Code As Integer
        Public Property Trace As String
        Public Property Data As Data
    End Class

    Public Class Data
        Public Property Currencies As Currency()
    End Class

    Public Class Currency
        Public Property Currency As String
        Public Property Name As String
        Public Property Network As String
        Public Property Withdraw_enabled As Boolean
        Public Property Deposit_enabled As Boolean
    End Class
```
<p>Then in your processing, just check if either property is true.</p>
<pre class="lang-vb prettyprint-override"><code>    Dim root = JsonConvert.DeserializeObject(Of RootObject)(jsonString)
    Dim builder As New StringBuilder()

    For Each currency As Currency In root.Data.Currencies
        'Only consider the currency if at least one enabled is true
        If currency.Withdraw_enabled OrElse currency.Deposit_enabled Then
            builder.Append(currency.Currency)
            builder.Append(" - ")
            builder.AppendLine(currency.Network)
        End If
    Next

    RichTextBox1.Append(builder.ToString())
</code>```

Body:
I'm parsing the JSON from this page with the following .net framework code:

Dim jsonString As String
       Using http As HttpClient = New HttpClient
           Dim url As String = "https://api-cloud.bitmart.com/account/v1/currencies"

           Dim streamData As Stream = Await http.GetStreamAsync(url)

           Using sr As StreamReader = New StreamReader(streamData)
               jsonString = sr.ReadToEnd
           End Using
           streamData.Close()
       End Using

       Dim jsonResponse As JObject = JObject.Parse(jsonString)
       Dim jsonData As JObject = CType(jsonResponse("data"), JObject)
       Dim jsonCurrencies As JArray = CType(jsonData("currencies"), JArray)

       Dim c As String = String.Empty
       Dim n As String = String.Empty
       For Each jsonCurrency As JObject In jsonCurrencies
           c += jsonCurrency("currency").ToString + " - " & jsonCurrency("network").ToString + vbLf

       Next
       RichTextBox1.Text += c

it is working perfectly, but I thought all the results were on "true, true"
but the now I sow there are also results like

"withdraw_enabled":false,"deposit_enabled":false}
which I really don't need to be parsed.

the results I'm interested on are firstly

"withdraw_enabled":true,"deposit_enabled":true}

and in cases like the following, I would like to parse them but I want to know which between withdraw and deposit is on true and/or false

"withdraw_enabled":false,"deposit_enabled":true}

As a summary:

if JSON is

[{"currency":"DFC","name":"DefiConnect","network":"BEP20","withdraw_enabled":true,"deposit_enabled":true},

the output is

DFC - BEP20 ( my code is already working for this case)

if JSON is

{"currency":"HOG","name":"HOG Finance","network":"BEP20(BSC)","withdraw_enabled":true,"deposit_enabled":false},

the output should be

HOG - BEP20(BSC) [withdraw: Yes - deposit: NO]

and if JSON is

{"currency":"SGE","name":"Society of Galactic Exploration","network":"ERC20","withdraw_enabled":false,"deposit_enabled":false}

I dont need to parse it.

Do you think It could be possible?
Hope I've been clear.
Thanks

Body:
Instead of using the generic JObject, you can deserialize into an actual class.

    Public Class RootObject
        Public Property Message As String
        Public Property Code As Integer
        Public Property Trace As String
        Public Property Data As Data
    End Class

    Public Class Data
        Public Property Currencies As Currency()
    End Class

    Public Class Currency
        Public Property Currency As String
        Public Property Name As String
        Public Property Network As String
        Public Property Withdraw_enabled As Boolean
        Public Property Deposit_enabled As Boolean
    End Class

Then in your processing, just check if either property is true.

    Dim root = JsonConvert.DeserializeObject(Of RootObject)(jsonString)
    Dim builder As New StringBuilder()

    For Each currency As Currency In root.Data.Currencies
        'Only consider the currency if at least one enabled is true
        If currency.Withdraw_enabled OrElse currency.Deposit_enabled Then
            builder.Append(currency.Currency)
            builder.Append(" - ")
            builder.AppendLine(currency.Network)
        End If
    Next

    RichTextBox1.Append(builder.ToString())


问:
RxSwift Swift - Select/Deselect multiple rows in tableView
I can select rows in tableView.rx but I'm wonder how to get array of final selection. I mean the result array of selecting some rows and then deselecting some rows.

Here's my code:

```<code> Observable.zip(tableView.rx.modelSelected(Country.self), tableView.rx.itemSelected).subscribe(onNext: { (selectedCountry, indexPath) in
            print("2 selected Country is \(selectedCountry) and indexPath is \(indexPath.row)")
            self.selectedCountries.append(selectedCountry)
</code>```

I want also see selected rows as marked.

I appreciate for your helping. thanks

答:
First you have to use this:

```<code>tableView.allowsMultipleSelection = true
</code>```

Then you could use these to do what ever you want:

```<code>  let selectedItems = tableView.rx.modelSelected(Country.self).subscribe { item in
        print("selected: \(item)")
        print("selected rows: \(self.tableView.indexPathsForSelectedRows)")
  }
  let deselectedItems = tableView.rx.modelDeselected(Country.self).subscribe { item in
        print("deselected: \(item)")
  }
</code>```

Body:
I can select rows in tableView.rx but I'm wonder how to get array of final selection. I mean the result array of selecting some rows and then deselecting some rows.

Here's my code:

 Observable.zip(tableView.rx.modelSelected(Country.self), tableView.rx.itemSelected).subscribe(onNext: { (selectedCountry, indexPath) in
            print("2 selected Country is \(selectedCountry) and indexPath is \(indexPath.row)")
            self.selectedCountries.append(selectedCountry)

I want also see selected rows as marked.

I appreciate for your helping. thanks

Body:
First you have to use this:

tableView.allowsMultipleSelection = true

Then you could use these to do what ever you want:

  let selectedItems = tableView.rx.modelSelected(Country.self).subscribe { item in
        print("selected: \(item)")
        print("selected rows: \(self.tableView.indexPathsForSelectedRows)")
  }
  let deselectedItems = tableView.rx.modelDeselected(Country.self).subscribe { item in
        print("deselected: \(item)")
  }


问:
Different results when applying feColorMatrix SVG filter in CSS or in javascript
Let's say we want to apply a SVG filter on a canvas element. According to this we can apply a SVG filter to the CanvasRenderingContext2D in javascript like this, the filter will only affect shapes drawn after that call:

```<code>ctx.filter = "url(#bar)";
</code>```

We can also just apply the filter in CSS on the whole canvas:

```<code>#canvas {
  filter: url(#bar);
}
</code>```

I need to apply the filter in javascript since I only want part of my canvas to be filtered. When applying a feColorMatrix to some or all of the shapes the results differ depending on the filter having been applied on the 2D Context in JS or on the whole canvas element in CSS.

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.filter = "url(#bar)";
ctx.fillRect(10,10,100,100);
ctx.fillRect(10,120,100,100);
ctx.fillRect(120,10,100,100);
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.ellipse(170, 170, 50, 50, Math.PI / 4, 0, 2 * Math.PI);
ctx.fill();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#canvas {
  /* remove comment to see difference */
  /* filter: url(#bar); */
}</code>```

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
  <defs>
    <filter id="bar">
      <fegaussianblur in="SourceGraphic" stdDeviation="10" result="blur"></fegaussianblur>
      <fecolormatrix in="blur" mode="matrix" values="1 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 18 -7"></fecolormatrix>
    </filter>
  </defs>
</svg>
<canvas id="canvas" width="400" height="400"></canvas>```

When you remove the comment that applies the SVG filter on the whole canvas it gives this great gooey effect, I can't seem to achieve that effect only with JS. What am I missing here, shouldn't the two methods give the same result?

答:
The CSS filter applies on the canvas image as a whole. This is fundamentally different than in your JS code where you apply the filter on each rectangle separately.

Take for instance this code where I draw rectangles with some transparency. Each rectangle on the left side is drawn one by one, while the ones on the right side are all drawn in a single draw operation. You can see how the globalAlpha didn't produce the same result at all.

const ctx = document.querySelector("canvas").getContext("2d");

ctx.globalAlpha = 0.25;
for(let y = 0; y<150; y+=10) {
  // draws each rectangle one after the other
  ctx.fillRect(0, 0, 50, y);
}
for(let y = 0; y<150; y+=10) {
  ctx.rect(100, 0, 50, y);
}
// draws all the right-side rectangles in one go
ctx.fill();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas></canvas></code>```

Well, exactly the same thing happens with the filter.

To get the same effect, draw all your rectangles once and then redraw the canvas over itself with the filter so that it applies to the whole image.

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.fillRect(10,10,100,100);
ctx.fillRect(10,120,100,100);
ctx.fillRect(120,10,100,100);
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.ellipse(170, 170, 50, 50, Math.PI / 4, 0, 2 * Math.PI);
ctx.fill();
ctx.filter = "url(#bar)";
// clears what was there, alternatively we could have used a second canvas
ctx.globalCompositeOperation = "copy";
ctx.drawImage(canvas, 0, 0);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg xmlns="http://www.w3.org/2000/svg" version="1.1" style="position:absolute;z-index:-1">
  <defs>
    <filter id="bar">
      <fegaussianblur in="SourceGraphic" stdDeviation="10" result="blur"></fegaussianblur>
      <fecolormatrix in="blur" mode="matrix" values="1 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 18 -7"></fecolormatrix>
    </filter>
  </defs>
</svg>
<canvas id="canvas" width="400" height="400"></canvas></code>```

Body:
Let's say we want to apply a SVG filter on a canvas element. According to this we can apply a SVG filter to the CanvasRenderingContext2D in javascript like this, the filter will only affect shapes drawn after that call:

ctx.filter = "url(#bar)";

We can also just apply the filter in CSS on the whole canvas:

#canvas {
  filter: url(#bar);
}

I need to apply the filter in javascript since I only want part of my canvas to be filtered. When applying a feColorMatrix to some or all of the shapes the results differ depending on the filter having been applied on the 2D Context in JS or on the whole canvas element in CSS.

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.filter = "url(#bar)";
ctx.fillRect(10,10,100,100);
ctx.fillRect(10,120,100,100);
ctx.fillRect(120,10,100,100);
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.ellipse(170, 170, 50, 50, Math.PI / 4, 0, 2 * Math.PI);
ctx.fill();

#canvas {
  /* remove comment to see difference */
  /* filter: url(#bar); */
}

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
  <defs>
    <filter id="bar">
      <fegaussianblur in="SourceGraphic" stdDeviation="10" result="blur"></fegaussianblur>
      <fecolormatrix in="blur" mode="matrix" values="1 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 18 -7"></fecolormatrix>
    </filter>
  </defs>
</svg>
<canvas id="canvas" width="400" height="400"></canvas>

When you remove the comment that applies the SVG filter on the whole canvas it gives this great gooey effect, I can't seem to achieve that effect only with JS. What am I missing here, shouldn't the two methods give the same result?

Body:
The CSS filter applies on the canvas image as a whole. This is fundamentally different than in your JS code where you apply the filter on each rectangle separately.

Take for instance this code where I draw rectangles with some transparency. Each rectangle on the left side is drawn one by one, while the ones on the right side are all drawn in a single draw operation. You can see how the globalAlpha didn't produce the same result at all.

const ctx = document.querySelector("canvas").getContext("2d");

ctx.globalAlpha = 0.25;
for(let y = 0; y<150; y+=10) {
  // draws each rectangle one after the other
  ctx.fillRect(0, 0, 50, y);
}
for(let y = 0; y<150; y+=10) {
  ctx.rect(100, 0, 50, y);
}
// draws all the right-side rectangles in one go
ctx.fill();

<canvas></canvas>

Well, exactly the same thing happens with the filter.

To get the same effect, draw all your rectangles once and then redraw the canvas over itself with the filter so that it applies to the whole image.

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.fillRect(10,10,100,100);
ctx.fillRect(10,120,100,100);
ctx.fillRect(120,10,100,100);
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.ellipse(170, 170, 50, 50, Math.PI / 4, 0, 2 * Math.PI);
ctx.fill();
ctx.filter = "url(#bar)";
// clears what was there, alternatively we could have used a second canvas
ctx.globalCompositeOperation = "copy";
ctx.drawImage(canvas, 0, 0);

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" style="position:absolute;z-index:-1">
  <defs>
    <filter id="bar">
      <fegaussianblur in="SourceGraphic" stdDeviation="10" result="blur"></fegaussianblur>
      <fecolormatrix in="blur" mode="matrix" values="1 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 18 -7"></fecolormatrix>
    </filter>
  </defs>
</svg>
<canvas id="canvas" width="400" height="400"></canvas>


答: The getTime() method always returns the number of milliseconds in UTC time zone - and this is exactly what you need in order to compare 2 timestamp values because UTC timezone does not have daylight saving periods.

Title: Comparing dates with getTime() in EST timezone

Body:
I am looking if there is a better way (other than below solution) of comparing dates for all users (in different countries) in EST timezone. Need your inputs/help.

Basically I have to display three UI's based on  three different dates. Till June, 1st UI has to render, June to July second UI and from July 3rd UI has to display. These dates while comparing should be in EST timezone.

  const JulyDate = new Date("2022-07-01T00:00:00.000-05:00");
  const JuneDate = new Date("2022-06-01T00:00:00.000-05:00");
  if(new Date().getTime() < JuneDate.getTime()){
    renderUIPriorJune= true;
    renderUIJune= false;
    renderUIJuly= false;
  }
  else if(new Date().getTime() >= JuneDate.getTime() && new Date().getTime() < JulyDate.getTime()){
    renderUIPriorJune= false;
    renderUIJune= true;
    renderUIJuly= false;

  }
  else if(new Date().getTime() >= JulyDate.getTime()){
    renderUIPriorJune= false;
    renderUIJune= false;
    renderUIJuly= true;

  }

I have defined June and July dates in EST timezone i.e. -5 hours as offset and then current date is compared with those dates.

Could you please let me know if this is the correct way of comparing or Is there a better way of doing. I am rather new to Java script.

Thank you in advance.


问:
Using the Yoast API on Wordpress.com
We have a headless Wordpress CMS hosted on wordpress.com, and I am having trouble retrieving Yoast SEO tags using the Wordpress API.

The vanilla Wordpress API uses URLs like so:

https://example.com/wp-json/wp/v2/posts/1

but on sites hosted on wordpress.com they are rather different:

public-api.wordpress.com/rest/v1.1/sites/example.wordpress.com/posts/1

I have two possibly-related issues:

When querying the main API, the additional Yoast field described here is not included.

When trying to query Yoast directly, I do not know how to transform Yoast’s API URLs to the wordpress.com structure.

I believe solving either of the issues would be enough for us to get the tags needed. We’re using Yoast 18.0, the Yoast output does appear in directly-rendered pages, and the Yoast REST API head endpoint is switched on in settings.

答:
I have been able to solve this on our production site very simply: the normal API paths do in fact work (at least the /v2/ paths) for our production site.

It seems that the path transformation only applies to the free/cheaper hosting packages on wordpress.com. We are using a free site as an integration testing target so in fact this only fails in testing, not in production with a paid wordpress.com package.

Presumably this is because the cheaper packages are all on some kind of shared instance: when we initially upgraded it did not help, but when we installed Yoast it moved us to a different subdomain and the normal API paths started working. I guess at this point we had been moved to a dedicated instance.

Title: Using the Yoast API on Wordpress.com


问:
What's the cache_ok flag in SQLAlchemy?
I have the next custom type decorator for SQLAlchemy:

```<code>class TimeStamp(TypeDecorator):
    impl = DateTime
    cache_ok = True
    LOCAL_TIMEZONE = datetime.utcnow().astimezone().tzinfo

    def process_literal_param(self, value, dialect):
        return self.imple.process_literal_param(value, dialect)

    @property
    def python_type(self):
        return self.impl.python_type

    def process_bind_param(self, value: datetime, dialect):
        if value is None:
            return None
        if value.tzinfo is None:
            value = value.astimezone(self.LOCAL_TIMEZONE)
        return value.astimezone(timezone.utc)

    def process_result_value(self, value, dialect):
        if value is None:
            return None
        if value.tzinfo is None:
            return value.replace(tzinfo=timezone.utc)
        return value.astimezone(timezone.utc)
</code>```

The problem is that SQLAlchemy asks me to setup the cache_ok flag... I've tried to read about this flag in docs but it's still not clear for me. I can't get how SQLAlchemy uses it.

What does it cache? Is my type decorator suitable for caching?

答:
Ran into this recently, found your question, no answer :( .. looked further, looked into the docs ..

The TypeDecorator.cache_ok class-level flag indicates if this custom TypeDecorator is safe to be used as part of a cache key. This flag defaults to None which will initially generate a warning when the SQL compiler attempts to generate a cache key for a statement that uses this type. If the TypeDecorator is not guaranteed to produce the same bind/result behavior and SQL generation every time, this flag should be set to False; otherwise if the class produces the same behavior each time, it may be set to True. See TypeDecorator.cache_ok for further notes on how this works.

https://docs.sqlalchemy.org/en/14/core/custom_types.html#sqlalchemy.types.TypeDecorator

.. so if you're confident that your TypeDecorator always produces the same bind/result for a given value then go ahead and issue that statement by setting the value cache_ok = True in your TypeDecorator class.

Title: What's the cache_ok flag in SQLAlchemy?

Body:
I have the next custom type decorator for SQLAlchemy:

class TimeStamp(TypeDecorator):
    impl = DateTime
    cache_ok = True
    LOCAL_TIMEZONE = datetime.utcnow().astimezone().tzinfo

    def process_literal_param(self, value, dialect):
        return self.imple.process_literal_param(value, dialect)

    @property
    def python_type(self):
        return self.impl.python_type

    def process_bind_param(self, value: datetime, dialect):
        if value is None:
            return None
        if value.tzinfo is None:
            value = value.astimezone(self.LOCAL_TIMEZONE)
        return value.astimezone(timezone.utc)

    def process_result_value(self, value, dialect):
        if value is None:
            return None
        if value.tzinfo is None:
            return value.replace(tzinfo=timezone.utc)
        return value.astimezone(timezone.utc)

The problem is that SQLAlchemy asks me to setup the cache_ok flag... I've tried to read about this flag in docs but it's still not clear for me. I can't get how SQLAlchemy uses it.

What does it cache? Is my type decorator suitable for caching?


问:
how to handle events: array of controls with c sharp (old com control)
I'm trying to work with an old com control (a control array), the following samples: 5435293, 39541, 5497403, 5738092 explain (or at least what I understand) how to handle events of control arrays with .net controls, so they have Sender and EventArgs.

My question will be: How can you handle the events of an old com control array?.

EDIT:
The array will be created dynamically at the start, for example: Q. How many connections do you want? A. 5

example:
the control has this event: control_connected(int status, string description)

I can make some function with the same arguments and asign it to the connected event, but i cant figure out how to do it with a control array.

Ty so much for your help, and sorry about the crappy English... I'm not a navite English speaker

答:
COM events have a different modal, you do not have one handler per event, you have an event sink object that hooks every event the COM server plan to raise. If you just hook the ActiveX events with delegates, event sink RCWs will be created and may cause crashes later, so I assume you are creating your own event sink class.

Since you have your own event sink class, you must follow the event publisher's event signature. The signatures do not have a sender argument, since the COM server assumes you have a reference to the sender, thus there is no need to send it again every time an event is raised.

You can, of cause, cache the server's reference in your event sink object for later use. Your event sink object can declare its own version of managed events with a sender parameter, and pass the cached COM server as the sender argument when it raises events.

Something like

```<code>[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
[TypeLibType(TypeLibTypeFlags.FHidden)]
[Guid("eventGuid")]
[CLSCompliant(false)]
public interface IEvent
{
   [DispId(123)]
   void control_connected(int status, string description);
}
public class EventSink:IEvent
{
   object control;
   public EventSink (object control)
   {
        this.control=control;
   }
   public event EventHandler<ControlConnectedEventArgs> ControlConnected;
   void control_connected(int status, string description);
   {
       EventHandler<ControlConnectedEventArgs> temp=this.ControlConnected;
       if(temp!=null)
           temp(this.control, new ControlConnectedEventArgs(status,description));
   }
}
</code>```

If you have an array of COM servers, just declare an array of event sinks, attach each sink to each COM server with ConnectionPointCookie, and wire the event handlers from the event sink instead of the COM servers.

Body:
COM events have a different modal, you do not have one handler per event, you have an event sink object that hooks every event the COM server plan to raise. If you just hook the ActiveX events with delegates, event sink RCWs will be created and may cause crashes later, so I assume you are creating your own event sink class.

Since you have your own event sink class, you must follow the event publisher's event signature. The signatures do not have a sender argument, since the COM server assumes you have a reference to the sender, thus there is no need to send it again every time an event is raised.

You can, of cause, cache the server's reference in your event sink object for later use. Your event sink object can declare its own version of managed events with a sender parameter, and pass the cached COM server as the sender argument when it raises events.

Something like

[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
[TypeLibType(TypeLibTypeFlags.FHidden)]
[Guid("eventGuid")]
[CLSCompliant(false)]
public interface IEvent
{
   [DispId(123)]
   void control_connected(int status, string description);
}
public class EventSink:IEvent
{
   object control;
   public EventSink (object control)
   {
        this.control=control;
   }
   public event EventHandler<ControlConnectedEventArgs> ControlConnected;
   void control_connected(int status, string description);
   {
       EventHandler<ControlConnectedEventArgs> temp=this.ControlConnected;
       if(temp!=null)
           temp(this.control, new ControlConnectedEventArgs(status,description));
   }
}

If you have an array of COM servers, just declare an array of event sinks, attach each sink to each COM server with ConnectionPointCookie, and wire the event handlers from the event sink instead of the COM servers.


问:
Error installing sparse-dot-topn on AWS EC2 : Could not build wheels for sparse-dot-topn,which is required to install pyproject.toml-based projects
Helllo,

I am facing issue in installing sparse-dot-topn on AWS EC2 with below error.
Things I tried:

Upgraded pip

upgrade wheel

install cython

install cpython

install gcc

but nothing seems to work. Kindly advice where I am going wrong.

```<code>pip3 install sparse-dot-topn
Defaulting to user installation because normal site-packages is not writeable
Collecting sparse-dot-topn
  Using cached sparse_dot_topn-0.3.1.tar.gz (17 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Installing backend dependencies ... done
  Preparing metadata (pyproject.toml) ... done
Requirement already satisfied: numpy>=1.16.6 in ./.local/lib/python3.7/site-packages (from sparse-dot-topn) (1.20.3)
Requirement already satisfied: setuptools>=42 in ./.local/lib/python3.7/site-packages (from sparse-dot-topn) (60.5.0)
Requirement already satisfied: scipy>=1.2.3 in ./.local/lib/python3.7/site-packages (from sparse-dot-topn) (1.6.3)
Requirement already satisfied: cython>=0.29.15 in ./.local/lib/python3.7/site-packages (from sparse-dot-topn) (0.29.26)
Building wheels for collected packages: sparse-dot-topn
  Building wheel for sparse-dot-topn (pyproject.toml) ... error
  ERROR: Command errored out with exit status 1:
   command: /usr/bin/python3 /home/ec2-user/.local/lib/python3.7/site-packages/pip/_vendor/pep517/in_process/_in_process.py build_wheel /tmp/tmpkxql22kh
       cwd: /tmp/pip-install-dr3dy2db/sparse-dot-topn_a4e8b8ecc1b44350860d0dcdde789cf0
  Complete output (27 lines):
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build/lib.linux-x86_64-3.7
  creating build/lib.linux-x86_64-3.7/sparse_dot_topn
  copying sparse_dot_topn/__init__.py -> build/lib.linux-x86_64-3.7/sparse_dot_topn
  copying sparse_dot_topn/awesome_cossim_topn.py -> build/lib.linux-x86_64-3.7/sparse_dot_topn
  running egg_info
  writing manifest file 'sparse_dot_topn.egg-info/SOURCES.txt'
  copying sparse_dot_topn/array_wrappers.pxd -> build/lib.linux-x86_64-3.7/sparse_dot_topn
  copying sparse_dot_topn/array_wrappers.pyx -> build/lib.linux-x86_64-3.7/sparse_dot_topn
  copying sparse_dot_topn/sparse_dot_topn.pyx -> build/lib.linux-x86_64-3.7/sparse_dot_topn
  copying sparse_dot_topn/sparse_dot_topn_parallel.h -> build/lib.linux-x86_64-3.7/sparse_dot_topn
  copying sparse_dot_topn/sparse_dot_topn_source.h -> build/lib.linux-x86_64-3.7/sparse_dot_topn
  copying sparse_dot_topn/sparse_dot_topn_threaded.pyx -> build/lib.linux-x86_64-3.7/sparse_dot_topn
  running build_ext
  creating build/temp.linux-x86_64-3.7
  creating build/temp.linux-x86_64-3.7/sparse_dot_topn
  /usr/local/bin/gcc-8 -Wno-unused-result -Wsign-compare -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/usr/include/python3.7m -I/tmp/pip-build-env-6grtk5m0/normal/lib64/python3.7/site-packages/numpy/core/include -c ./sparse_dot_topn/array_wrappers.cpp -o build/temp.linux-x86_64-3.7/./sparse_dot_topn/array_wrappers.o -std=c++0x -pthread -O3
  /tmp/pip-build-env-6grtk5m0/normal/lib64/python3.7/site-packages/Cython/Compiler/Main.py:369: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: /tmp/pip-install-dr3dy2db/sparse-dot-topn_a4e8b8ecc1b44350860d0dcdde789cf0/sparse_dot_topn/array_wrappers.pxd
    tree = Parsing.p_module(s, pxd, full_module_name)
  /tmp/pip-build-env-6grtk5m0/normal/lib64/python3.7/site-packages/Cython/Compiler/Main.py:369: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: /tmp/pip-install-dr3dy2db/sparse-dot-topn_a4e8b8ecc1b44350860d0dcdde789cf0/sparse_dot_topn/sparse_dot_topn.pyx
    tree = Parsing.p_module(s, pxd, full_module_name)
  /tmp/pip-build-env-6grtk5m0/normal/lib64/python3.7/site-packages/Cython/Compiler/Main.py:369: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: /tmp/pip-install-dr3dy2db/sparse-dot-topn_a4e8b8ecc1b44350860d0dcdde789cf0/sparse_dot_topn/sparse_dot_topn_threaded.pyx
    tree = Parsing.p_module(s, pxd, full_module_name)
  error: command '/usr/local/bin/gcc-8' failed: No such file or directory: '/usr/local/bin/gcc-8'
  ----------------------------------------
  ERROR: Failed building wheel for sparse-dot-topn
Failed to build sparse-dot-topn
ERROR: Could not build wheels for sparse-dot-topn, which is required to install pyproject.toml-based projects
</code>```

答:
For me what worked is to ensure the numpy version is 1.19.5.
Also ensure cython is installed as per the official documentation</p>
```<code>pip install cython
pip install numpy==1.19.5
pip install sparse-dot-topn
</code>```

Body:
Helllo,

I am facing issue in installing sparse-dot-topn on AWS EC2 with below error.
Things I tried:

Upgraded pip

upgrade wheel

install cython

install cpython

install gcc

but nothing seems to work. Kindly advice where I am going wrong.

pip3 install sparse-dot-topn
Defaulting to user installation because normal site-packages is not writeable
Collecting sparse-dot-topn
  Using cached sparse_dot_topn-0.3.1.tar.gz (17 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Installing backend dependencies ... done
  Preparing metadata (pyproject.toml) ... done
Requirement already satisfied: numpy>=1.16.6 in ./.local/lib/python3.7/site-packages (from sparse-dot-topn) (1.20.3)
Requirement already satisfied: setuptools>=42 in ./.local/lib/python3.7/site-packages (from sparse-dot-topn) (60.5.0)
Requirement already satisfied: scipy>=1.2.3 in ./.local/lib/python3.7/site-packages (from sparse-dot-topn) (1.6.3)
Requirement already satisfied: cython>=0.29.15 in ./.local/lib/python3.7/site-packages (from sparse-dot-topn) (0.29.26)
Building wheels for collected packages: sparse-dot-topn
  Building wheel for sparse-dot-topn (pyproject.toml) ... error
  ERROR: Command errored out with exit status 1:
   command: /usr/bin/python3 /home/ec2-user/.local/lib/python3.7/site-packages/pip/_vendor/pep517/in_process/_in_process.py build_wheel /tmp/tmpkxql22kh
       cwd: /tmp/pip-install-dr3dy2db/sparse-dot-topn_a4e8b8ecc1b44350860d0dcdde789cf0
  Complete output (27 lines):
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build/lib.linux-x86_64-3.7
  creating build/lib.linux-x86_64-3.7/sparse_dot_topn
  copying sparse_dot_topn/__init__.py -> build/lib.linux-x86_64-3.7/sparse_dot_topn
  copying sparse_dot_topn/awesome_cossim_topn.py -> build/lib.linux-x86_64-3.7/sparse_dot_topn
  running egg_info
  writing manifest file 'sparse_dot_topn.egg-info/SOURCES.txt'
  copying sparse_dot_topn/array_wrappers.pxd -> build/lib.linux-x86_64-3.7/sparse_dot_topn
  copying sparse_dot_topn/array_wrappers.pyx -> build/lib.linux-x86_64-3.7/sparse_dot_topn
  copying sparse_dot_topn/sparse_dot_topn.pyx -> build/lib.linux-x86_64-3.7/sparse_dot_topn
  copying sparse_dot_topn/sparse_dot_topn_parallel.h -> build/lib.linux-x86_64-3.7/sparse_dot_topn
  copying sparse_dot_topn/sparse_dot_topn_source.h -> build/lib.linux-x86_64-3.7/sparse_dot_topn
  copying sparse_dot_topn/sparse_dot_topn_threaded.pyx -> build/lib.linux-x86_64-3.7/sparse_dot_topn
  running build_ext
  creating build/temp.linux-x86_64-3.7
  creating build/temp.linux-x86_64-3.7/sparse_dot_topn
  /usr/local/bin/gcc-8 -Wno-unused-result -Wsign-compare -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/usr/include/python3.7m -I/tmp/pip-build-env-6grtk5m0/normal/lib64/python3.7/site-packages/numpy/core/include -c ./sparse_dot_topn/array_wrappers.cpp -o build/temp.linux-x86_64-3.7/./sparse_dot_topn/array_wrappers.o -std=c++0x -pthread -O3
  /tmp/pip-build-env-6grtk5m0/normal/lib64/python3.7/site-packages/Cython/Compiler/Main.py:369: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: /tmp/pip-install-dr3dy2db/sparse-dot-topn_a4e8b8ecc1b44350860d0dcdde789cf0/sparse_dot_topn/array_wrappers.pxd
    tree = Parsing.p_module(s, pxd, full_module_name)
  /tmp/pip-build-env-6grtk5m0/normal/lib64/python3.7/site-packages/Cython/Compiler/Main.py:369: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: /tmp/pip-install-dr3dy2db/sparse-dot-topn_a4e8b8ecc1b44350860d0dcdde789cf0/sparse_dot_topn/sparse_dot_topn.pyx
    tree = Parsing.p_module(s, pxd, full_module_name)
  /tmp/pip-build-env-6grtk5m0/normal/lib64/python3.7/site-packages/Cython/Compiler/Main.py:369: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: /tmp/pip-install-dr3dy2db/sparse-dot-topn_a4e8b8ecc1b44350860d0dcdde789cf0/sparse_dot_topn/sparse_dot_topn_threaded.pyx
    tree = Parsing.p_module(s, pxd, full_module_name)
  error: command '/usr/local/bin/gcc-8' failed: No such file or directory: '/usr/local/bin/gcc-8'
  ----------------------------------------
  ERROR: Failed building wheel for sparse-dot-topn
Failed to build sparse-dot-topn
ERROR: Could not build wheels for sparse-dot-topn, which is required to install pyproject.toml-based projects

Body:
For me what worked is to ensure the numpy version is 1.19.5.
Also ensure cython is installed as per the official documentation

pip install cython
pip install numpy==1.19.5
pip install sparse-dot-topn


问:
Why up and running web service returns 500 Internal Server Error?
I'm learning back-end and decided to write a simple web service using FastAPI. The idea is, the front-end does the request to the webserver, then the webserver communicates with Postgresql DB to retrieve the data, and then the webserver returns that data to the front-end. I'm using FastAPI for creating a web service, Nginx to expose that service to the internet, Postgresql for storing the data.

Here is my code for that service:

```<code>from fastapi import FastAPI, HTTPException
import psycopg2
import time

app = FastAPI()

while True:
    try:
        # Connect to your postgres DB
        conn = psycopg2.connect(host='hostIP', database='postgres',user='postgres',password='passwd')

        # Open a cursor to perform database operations
        cursor = conn.cursor()
        print('DB connection was successfull!')
        break
    except Exception as error:
        print('Connection to DB failed')
        print("Error: ", error)
        time.sleep(2)

@app.get("/")
async def root():
    cursor.execute("""SELECT * FROM characters""")
    flags = cursor.fetchall()
    return {'data': flags}
</code>```

hostIP = is IP address of my ubuntu server (for security purpose I'm not showing actual IP here) which is installed on VirtualBox VM. So my web service and database both are deployed on this VM.

Then I created a gunicorn.service to run fastAPI service:

[Unit]   Description=Gunicorn Web Server as Unit Service Systemd
After=network.target

[Service]

User=ubuntuserver

Group=ubuntuserver

WorkingDirectory=/home/ubuntuserver/test

Environment="PATH=/home/ubuntuserver/test/venv/bin"

ExecStart=/home/ubuntuserver/test/venv/bin/gunicorn --config
/home/ubuntuserver/test/main.py main:app

[Install]

WantedBy=multi-user.target

For nginx, I configured default.conf file like below:

```<code>server {
  listen 80;
  server_name hostIP;
  location / {
    proxy_pass http://localhost:8000;
  }
}
</code>```

So I expect to type in on another computer's browser, hostIP:80 and get database information or at least some success message etc.  but instead I get Internal Server Error.

On server-side, I ran below command to check the services:

```<code>systemctl status postgresql
systemctl status gunicorn.service
systemctl status nginx
</code>```

And they all appear to be normally activated.

Below I checked all ports in use by services:

Am I missing something ?

EDIT

After using suggestion by Thomas and running below command:

```<code>sudo journalctl -f -u nginx -u gunicorn
</code>```

I got folowing output:

Feb 06 12:08:31 ubuntuserver gunicorn[3975]: [2022-02-06 12:08:31
+0000] [3975] [ERROR] Error handling request /

Feb 06 12:08:31 ubuntuserver gunicorn[3975]: Traceback (most recent call last):

Feb 06 12:08:31 ubuntuserver gunicorn[3975]: File "/home/ubuntuserver/test/venv/lib/python3.8/site-packages/gunicorn/workers/sync.py", line 136, in handle

Feb 06 12:08:31 ubuntuserver gunicorn[3975]: self.handle_request(listener, req, client, addr)

Feb 06 12:08:31 ubuntuserver gunicorn[3975]:File "/home/ubuntuserver/test/venv/lib/python3.8/site-packages/gunicorn/workers/sync.py", line 179, in handle_request

Feb 06 12:08:31 ubuntuserver gunicorn[3975]: respiter = self.wsgi(environ, resp.start_response)

Feb 06 12:08:31 ubuntuserver gunicorn[3975]: TypeError: _call_() missing 1 required positional argument: 'send'

答:
Finally, resolved the issue, so FastAPI uses ASGI which is asynchronous, and gunicorn, where I run my FastAPI application, uses WSGI which is synchronous. When executing gunicorn command you should add uvicorn's workers. In my case, I've edited my gunicorn.service file:

```<code>[Unit] Description=Gunicorn Web Server as Unit Service Systemd After=network.target

[Service]
User=ubuntuserver
Group=ubuntuserver
WorkingDirectory=/home/ubuntuserver/test
Environment="PATH=/home/ubuntuserver/test/venv/bin"
ExecStart=/home/ubuntuserver/test/venv/bin/gunicorn --config /home/ubuntuserver/test/main.py main:app -w 4 -k uvicorn.workers.UvicornWorker

[Install]
WantedBy=multi-user.target
</code>```

Note that to use uvicorn workers, you need to install the below components first:

uvloop

httptools

Body:
I'm learning back-end and decided to write a simple web service using FastAPI. The idea is, the front-end does the request to the webserver, then the webserver communicates with Postgresql DB to retrieve the data, and then the webserver returns that data to the front-end. I'm using FastAPI for creating a web service, Nginx to expose that service to the internet, Postgresql for storing the data.

Here is my code for that service:

from fastapi import FastAPI, HTTPException
import psycopg2
import time

app = FastAPI()

while True:
    try:
        # Connect to your postgres DB
        conn = psycopg2.connect(host='hostIP', database='postgres',user='postgres',password='passwd')

        # Open a cursor to perform database operations
        cursor = conn.cursor()
        print('DB connection was successfull!')
        break
    except Exception as error:
        print('Connection to DB failed')
        print("Error: ", error)
        time.sleep(2)

@app.get("/")
async def root():
    cursor.execute("""SELECT * FROM characters""")
    flags = cursor.fetchall()
    return {'data': flags}

hostIP = is IP address of my ubuntu server (for security purpose I'm not showing actual IP here) which is installed on VirtualBox VM. So my web service and database both are deployed on this VM.

Then I created a gunicorn.service to run fastAPI service:

[Unit]   Description=Gunicorn Web Server as Unit Service Systemd
After=network.target

[Service]

User=ubuntuserver

Group=ubuntuserver

WorkingDirectory=/home/ubuntuserver/test

Environment="PATH=/home/ubuntuserver/test/venv/bin"

ExecStart=/home/ubuntuserver/test/venv/bin/gunicorn --config
/home/ubuntuserver/test/main.py main:app

[Install]

WantedBy=multi-user.target

For nginx, I configured default.conf file like below:

server {
  listen 80;
  server_name hostIP;
  location / {
    proxy_pass http://localhost:8000;
  }
}

So I expect to type in on another computer's browser, hostIP:80 and get database information or at least some success message etc.  but instead I get Internal Server Error.

On server-side, I ran below command to check the services:

systemctl status postgresql
systemctl status gunicorn.service
systemctl status nginx

And they all appear to be normally activated.

Below I checked all ports in use by services:

Am I missing something ?

EDIT

After using suggestion by Thomas and running below command:

sudo journalctl -f -u nginx -u gunicorn

I got folowing output:

Feb 06 12:08:31 ubuntuserver gunicorn[3975]: [2022-02-06 12:08:31
+0000] [3975] [ERROR] Error handling request /

Feb 06 12:08:31 ubuntuserver gunicorn[3975]: Traceback (most recent call last):

Feb 06 12:08:31 ubuntuserver gunicorn[3975]: File "/home/ubuntuserver/test/venv/lib/python3.8/site-packages/gunicorn/workers/sync.py", line 136, in handle

Feb 06 12:08:31 ubuntuserver gunicorn[3975]: self.handle_request(listener, req, client, addr)

Feb 06 12:08:31 ubuntuserver gunicorn[3975]:File "/home/ubuntuserver/test/venv/lib/python3.8/site-packages/gunicorn/workers/sync.py", line 179, in handle_request

Feb 06 12:08:31 ubuntuserver gunicorn[3975]: respiter = self.wsgi(environ, resp.start_response)

Feb 06 12:08:31 ubuntuserver gunicorn[3975]: TypeError: _call_() missing 1 required positional argument: 'send'

Body:
Finally, resolved the issue, so FastAPI uses ASGI which is asynchronous, and gunicorn, where I run my FastAPI application, uses WSGI which is synchronous. When executing gunicorn command you should add uvicorn's workers. In my case, I've edited my gunicorn.service file:

[Unit] Description=Gunicorn Web Server as Unit Service Systemd After=network.target

[Service]
User=ubuntuserver
Group=ubuntuserver
WorkingDirectory=/home/ubuntuserver/test
Environment="PATH=/home/ubuntuserver/test/venv/bin"
ExecStart=/home/ubuntuserver/test/venv/bin/gunicorn --config /home/ubuntuserver/test/main.py main:app -w 4 -k uvicorn.workers.UvicornWorker

[Install]
WantedBy=multi-user.target

Note that to use uvicorn workers, you need to install the below components first:

uvloop

httptools


问:
FFMPEG mux video and audio (from another video) - mapping issue
I would like to place the audio from a video to another video without an audio (in one command):

```<code>ffmpeg.exe -i video1_noAudio.mov -i video2_wAudio.mov -vcodec copy -acodec copy video1_audioFromVideo2.mov
</code>```

I guess "-map" is the correct way to do it but I got confused with it.

Can you suggest how to resolve it?

答:
The accepted answer is an excellent explanation of ffmpeg's flexible stream selection using the -map option.

However, the documentation linked above also describes a simpler syntax to do what the questioner asks, without -map:

```<code>ffmpeg -an -i video1_noAudio.mov -vn -i video2_wAudio.mov -c:a copy -c:v copy video1_audioFromVideo2.mov
</code>```

Here -an means discard any audio from the first input file, -vn discards any video from the audio recording. ffmpeg then combines them in the obvious way to produce a single output file.

(-c:a and -c:v are just alternatives for
-acodec and -vcodec in the question, which can be used to copy for speed, or re-encode a stream if needed. -c copy matches all streams, so is a shorter equivalent for both options.)

Extra options to consider

Without any further options, if the two streams are of different length, they are included in their entirety. If the audio stream is shorter than the video, the player should continue silently. If the video is shorter it should display the final frame or black.

If you want to stop with the shortest stream, add -shortest, or to stop at another point, use -to and a position argument. If an audio track is incidental music, you can also repeat it one or more times with -stream_loop.  For example:

```<code>ffmpeg -an -i video1_noAudio.mov -vn -stream_loop 1 -i video2_wAudio.mov -to 8:02 -c copy video1_audioFromVideo2.mov
</code>```

Re-encoding options can also be added in place of copy if a particular format of finished file is required.

Body:
I would like to place the audio from a video to another video without an audio (in one command):

ffmpeg.exe -i video1_noAudio.mov -i video2_wAudio.mov -vcodec copy -acodec copy video1_audioFromVideo2.mov

I guess "-map" is the correct way to do it but I got confused with it.

Can you suggest how to resolve it?

Body:
The accepted answer is an excellent explanation of ffmpeg's flexible stream selection using the -map option.

However, the documentation linked above also describes a simpler syntax to do what the questioner asks, without -map:

ffmpeg -an -i video1_noAudio.mov -vn -i video2_wAudio.mov -c:a copy -c:v copy video1_audioFromVideo2.mov

Here -an means discard any audio from the first input file, -vn discards any video from the audio recording. ffmpeg then combines them in the obvious way to produce a single output file.

(-c:a and -c:v are just alternatives for
-acodec and -vcodec in the question, which can be used to copy for speed, or re-encode a stream if needed. -c copy matches all streams, so is a shorter equivalent for both options.)

Extra options to consider

Without any further options, if the two streams are of different length, they are included in their entirety. If the audio stream is shorter than the video, the player should continue silently. If the video is shorter it should display the final frame or black.

If you want to stop with the shortest stream, add -shortest, or to stop at another point, use -to and a position argument. If an audio track is incidental music, you can also repeat it one or more times with -stream_loop.  For example:

ffmpeg -an -i video1_noAudio.mov -vn -stream_loop 1 -i video2_wAudio.mov -to 8:02 -c copy video1_audioFromVideo2.mov

Re-encoding options can also be added in place of copy if a particular format of finished file is required.