问:
Not able a connect to Datastax Cassandra with Spring boot version 2.3.0.Release
I am not able to establish a connection with the datastax cassandra instance with spring boot version 2.3.0.RELEASE. The same code works fine with spring boot 2.6 version.

Error while running the spring boot app

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration': \
  Unsatisfied dependency expressed through constructor parameter 0; \
  nested exception is org.springframework.beans.factory.BeanCreationException: \
  Error creating bean with name 'cassandraSession' defined in class path resource [org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.class]: \
  Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: \
  Failed to instantiate [com.datastax.oss.driver.api.core.CqlSession]: \
  Factory method 'cassandraSession' threw exception; \
  nested exception is java.lang.IllegalStateException: \
    Can't use withCloudSecureConnectBundle and explicitly specify ssl configuration. They are mutually exclusive.
        at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:797) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
        at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:227) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
        ...
</code>```
```<code>@Configuration
public class CassandraConfig {

    @Value("${spring.data.cassandra.contact-points}")
    private String contactPoints;

    @Value("${astra.secure-connect-bundle:none}")
    private String astraSecureConnectBundle;

    @Value("${spring.data.cassandra.username}")
    private String cassandraUsername;

    @Value("${spring.data.cassandra.password}")
    private String cassandraPassword;

    @Value("${spring.data.cassandra.port}")
    private int port;

    @Value("${spring.data.cassandra.keyspace-name}")
    private String keySpace;

    @Value("${spring.data.cassandra.local-datacenter}")
    private String dataCenter;

    @Bean
    public CqlSessionBuilderCustomizer sessionBuilderCustomizer() {
        /*
         * When using DataStax Astra, we must pass the secure connect bundle to the
         * CqlSession
         * See documentation:
         * https://docs.datastax.com/en/astra/aws/doc/dscloud/astra/dscloudUsingDrivers.
         * html
         */
        if (!astraSecureConnectBundle.equals("none")) {
            return builder -> builder
                    .withCloudSecureConnectBundle(Paths
                            .get("C:/projects/****/****/**/secure-connect-###.zip"))//zip file provided by datastax
                    .withAuthCredentials(this.cassandraUsername, this.cassandraPassword);
        } else {
            return builder -> builder
                    .addContactPoint(new InetSocketAddress(this.contactPoints, this.port))
                    .withLocalDatacenter(this.dataCenter)
                    .withAuthCredentials(this.cassandraUsername, this.cassandraUsername);
        }
    }

    @Bean
    public DriverConfigLoaderBuilderCustomizer driverConfigLoaderBuilderCustomizer() {
        /*
         * When using DataStax Astra, we do not have to pass contact points like we
         * normally would because
         * this metadata is contained in the secure connect bundle.
         */
        if (!astraSecureConnectBundle.equals("none")) {
            return builder -> builder.without(DefaultDriverOption.CONTACT_POINTS);
        }
        return builder -> builder
                .withString(DefaultDriverOption.SESSION_NAME, "spring-boot-service");
    }

}
</code>```

application.properties

```<code>spring.data.cassandra.keyspace-name="KeySpaceSpace"
spring.data.cassandra.contact-points=#########.db.astra.datastax.com
spring.data.cassandra.port=32392
spring.data.cassandra.local-datacenter=dc-1
spring.data.cassandra.username=###########
spring.data.cassandra.password=###########
spring.data.cassandra.ssl=true
astra.secure-connect-bundle=${ASTRA_SECURE_CONNECT_BUNDLE:/app/astra/creds}
spring.data.cassandra.schema-action=CREATE_IF_NOT_EXISTS
spring.main.allow-circular-references=true
</code>```

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <!-- <version>2.6.0</version> -->
        <version>2.3.1.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.sample</groupId>
    <artifactId>sample-one-poc-svc</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sample-one-poc-svc</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-cassandra</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.logging.log4j</groupId>
                    <artifactId>log4j-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.17.1 </version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.17.1 </version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.datastax.oss</groupId>
            <artifactId>java-driver-query-builder</artifactId>
        </dependency>
        <dependency>
            <groupId>com.datastax.oss</groupId>
            <artifactId>java-driver-mapper-processor</artifactId>
        </dependency>
        <dependency>
            <groupId>com.datastax.oss</groupId>
            <artifactId>java-driver-mapper-runtime</artifactId>
        </dependency>
        <dependency>
            <groupId>com.datastax.oss</groupId>
            <artifactId>java-driver-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.datastax.cassandra</groupId>
            <artifactId>cassandra-driver-mapping</artifactId>
            <version>3.11.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-to-slf4j</artifactId>
            <version>2.17.1</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

I am not sure if it is the same issue as this
https://github.com/spring-projects/spring-boot/issues/21487
The issue says its fixedin 2.3.1 version of spring boot, but I aget same exception if I use 2.3.1 version.

答:
Andrew is on the right track with his comment. The problem is that the secure connect bundle contains connection metadata plus SSL (TLS) credentials so the driver already expects that encryption is enabled which is the reason the resolver throws this exception:

```<code>  nested exception is java.lang.IllegalStateException: \
    Can't use withCloudSecureConnectBundle and explicitly specify ssl configuration. \
    They are mutually exclusive.
</code>```

You can resolve the conflict by removing this line from application.properties:

```<code>spring.data.cassandra.ssl=true
</code>```

I'm not familiar with the Spring code base so I'm not able verify why it works in 2.6 but not 2.3.

Credit to Cédric Lunven for pointers on the issue. Cheers!

Body:
I am not able to establish a connection with the datastax cassandra instance with spring boot version 2.3.0.RELEASE. The same code works fine with spring boot 2.6 version.

Error while running the spring boot app

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration': \
  Unsatisfied dependency expressed through constructor parameter 0; \
  nested exception is org.springframework.beans.factory.BeanCreationException: \
  Error creating bean with name 'cassandraSession' defined in class path resource [org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.class]: \
  Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: \
  Failed to instantiate [com.datastax.oss.driver.api.core.CqlSession]: \
  Factory method 'cassandraSession' threw exception; \
  nested exception is java.lang.IllegalStateException: \
    Can't use withCloudSecureConnectBundle and explicitly specify ssl configuration. They are mutually exclusive.
        at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:797) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
        at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:227) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
        ...

@Configuration
public class CassandraConfig {

    @Value("${spring.data.cassandra.contact-points}")
    private String contactPoints;

    @Value("${astra.secure-connect-bundle:none}")
    private String astraSecureConnectBundle;

    @Value("${spring.data.cassandra.username}")
    private String cassandraUsername;

    @Value("${spring.data.cassandra.password}")
    private String cassandraPassword;

    @Value("${spring.data.cassandra.port}")
    private int port;

    @Value("${spring.data.cassandra.keyspace-name}")
    private String keySpace;

    @Value("${spring.data.cassandra.local-datacenter}")
    private String dataCenter;

    @Bean
    public CqlSessionBuilderCustomizer sessionBuilderCustomizer() {
        /*
         * When using DataStax Astra, we must pass the secure connect bundle to the
         * CqlSession
         * See documentation:
         * https://docs.datastax.com/en/astra/aws/doc/dscloud/astra/dscloudUsingDrivers.
         * html
         */
        if (!astraSecureConnectBundle.equals("none")) {
            return builder -> builder
                    .withCloudSecureConnectBundle(Paths
                            .get("C:/projects/****/****/**/secure-connect-###.zip"))//zip file provided by datastax
                    .withAuthCredentials(this.cassandraUsername, this.cassandraPassword);
        } else {
            return builder -> builder
                    .addContactPoint(new InetSocketAddress(this.contactPoints, this.port))
                    .withLocalDatacenter(this.dataCenter)
                    .withAuthCredentials(this.cassandraUsername, this.cassandraUsername);
        }
    }

    @Bean
    public DriverConfigLoaderBuilderCustomizer driverConfigLoaderBuilderCustomizer() {
        /*
         * When using DataStax Astra, we do not have to pass contact points like we
         * normally would because
         * this metadata is contained in the secure connect bundle.
         */
        if (!astraSecureConnectBundle.equals("none")) {
            return builder -> builder.without(DefaultDriverOption.CONTACT_POINTS);
        }
        return builder -> builder
                .withString(DefaultDriverOption.SESSION_NAME, "spring-boot-service");
    }

}

application.properties

spring.data.cassandra.keyspace-name="KeySpaceSpace"
spring.data.cassandra.contact-points=#########.db.astra.datastax.com
spring.data.cassandra.port=32392
spring.data.cassandra.local-datacenter=dc-1
spring.data.cassandra.username=###########
spring.data.cassandra.password=###########
spring.data.cassandra.ssl=true
astra.secure-connect-bundle=${ASTRA_SECURE_CONNECT_BUNDLE:/app/astra/creds}
spring.data.cassandra.schema-action=CREATE_IF_NOT_EXISTS
spring.main.allow-circular-references=true

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>

        <version>2.3.1.RELEASE</version>
        <relativePath />
    </parent>
    <groupId>com.sample</groupId>
    <artifactId>sample-one-poc-svc</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sample-one-poc-svc</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-cassandra</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.logging.log4j</groupId>
                    <artifactId>log4j-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.17.1 </version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.17.1 </version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.datastax.oss</groupId>
            <artifactId>java-driver-query-builder</artifactId>
        </dependency>
        <dependency>
            <groupId>com.datastax.oss</groupId>
            <artifactId>java-driver-mapper-processor</artifactId>
        </dependency>
        <dependency>
            <groupId>com.datastax.oss</groupId>
            <artifactId>java-driver-mapper-runtime</artifactId>
        </dependency>
        <dependency>
            <groupId>com.datastax.oss</groupId>
            <artifactId>java-driver-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.datastax.cassandra</groupId>
            <artifactId>cassandra-driver-mapping</artifactId>
            <version>3.11.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-to-slf4j</artifactId>
            <version>2.17.1</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

I am not sure if it is the same issue as this
https://github.com/spring-projects/spring-boot/issues/21487
The issue says its fixedin 2.3.1 version of spring boot, but I aget same exception if I use 2.3.1 version.

Body:
Andrew is on the right track with his comment. The problem is that the secure connect bundle contains connection metadata plus SSL (TLS) credentials so the driver already expects that encryption is enabled which is the reason the resolver throws this exception:

  nested exception is java.lang.IllegalStateException: \
    Can't use withCloudSecureConnectBundle and explicitly specify ssl configuration. \
    They are mutually exclusive.

You can resolve the conflict by removing this line from application.properties:

spring.data.cassandra.ssl=true

I'm not familiar with the Spring code base so I'm not able verify why it works in 2.6 but not 2.3.

Credit to Cédric Lunven for pointers on the issue. Cheers!


来源: stackexchange

问:
If I type Ctrl-C on the command line, will the finally block in Java still execute?
I'm running my Java application in cmd.exe in Windows. If I stop the process forcefully by pressing Ctrl-C, and the code at that moment was running in the try block, will the finally block still be executed?

In my tests it seems that, yes, it is executed.

答:
No, the finally block is not being run for me when I Ctrl-C (in Linux).

I recommend moving your finally logic to a method "shutdown". Then calling it from both the finally block as well as from a Ctrl-C handler. Like this:

```<code>private void registerSigIntHandler() {
    final SignalHandler defaultSigIntHandler = Signal.handle(new Signal("INT"), SignalHandler.SIG_DFL);

    Signal.handle(new Signal("INT"), new SignalHandler() {
        public void handle(Signal signal) {
            log.info("SIGINT received");
            Signal.handle(new Signal("INT"), SignalHandler.SIG_DFL);
            shutdown();
            defaultSigIntHandler.handle(signal);        }
    });
}
</code>```

The benefit of doing it this way is that after shutdown completes, the SIG_DFL handler executes, terminating the program via the default OS SIGINT handler. This terminates the main thread and the entire process. Otherwise, if you do not use SIG_DFL, you have to somehow signal the main thread to exit. My main thread does not listen/poll for shutdown signals/messages. It is a long-running data-migration job. I want to shut down certain things but terminate the main thread and subthreads.

Also if shutdown hangs (hopefully should not happen), a second ctrl-c will terminate the program via the SIG_DFL handler.

In shutdown, I also set an AtomicBoolean to ensure shutdown is only run once.

```<code>boolean isShuttingDown = this.isShuttingDown.getAndSet(true);
if (isShuttingDown) {
    return;
}
</code>```

I also tried addShutdownHook (an alternative to Signal.handle) but ran into trouble with it not running my shutdown routine fully. I was messaging and joining with subthreads.

Note: Do not call SignalHandler.SIG_DFL.handle(new Signal("INT"));. It gives me SIGSEGV every time (which does exit the program). - How do I trigger the default signal handling behavior?

ContentLicense: CC BY-SA 3.0

Body:
No, the finally block is not being run for me when I Ctrl-C (in Linux).

I recommend moving your finally logic to a method "shutdown". Then calling it from both the finally block as well as from a Ctrl-C handler. Like this:

private void registerSigIntHandler() {
    final SignalHandler defaultSigIntHandler = Signal.handle(new Signal("INT"), SignalHandler.SIG_DFL);

    Signal.handle(new Signal("INT"), new SignalHandler() {
        public void handle(Signal signal) {
            log.info("SIGINT received");
            Signal.handle(new Signal("INT"), SignalHandler.SIG_DFL);
            shutdown();
            defaultSigIntHandler.handle(signal);        }
    });
}

The benefit of doing it this way is that after shutdown completes, the SIG_DFL handler executes, terminating the program via the default OS SIGINT handler. This terminates the main thread and the entire process. Otherwise, if you do not use SIG_DFL, you have to somehow signal the main thread to exit. My main thread does not listen/poll for shutdown signals/messages. It is a long-running data-migration job. I want to shut down certain things but terminate the main thread and subthreads.

Also if shutdown hangs (hopefully should not happen), a second ctrl-c will terminate the program via the SIG_DFL handler.

In shutdown, I also set an AtomicBoolean to ensure shutdown is only run once.

boolean isShuttingDown = this.isShuttingDown.getAndSet(true);
if (isShuttingDown) {
    return;
}

I also tried addShutdownHook (an alternative to Signal.handle) but ran into trouble with it not running my shutdown routine fully. I was messaging and joining with subthreads.

Note: Do not call SignalHandler.SIG_DFL.handle(new Signal("INT"));. It gives me SIGSEGV every time (which does exit the program). - How do I trigger the default signal handling behavior?

ContentLicense: CC BY-SA 4.0


问:
How to truncate a table which has replication activated on it
I have a database that once a week, I need to kill and feel its data. The tables in this database are being replicated into another database.

So whenever I try to truncate the tables, I get the error "Cannot truncate table 'Test' because it is published for replication or enabled for Change Data Capture."

My guess is I should drop this table/article from the publication/replication list, and then truncate and add it back onto the list of publication/replication, How can I do this using T-SQL?

Questions Modified:

In addition to what was asked above, I need to say, currently, I am deleting data from the tables, but because I have millions of records in some of my tables it's a very time-consuming process.

What solution do you suggest for this situation?

答:
For the record, I do not recommend replication. It is slow, finicky, and has a lot of quirks like this that make it painful to manage. Mirroring/AG/Log Shipping are much better options if you can use them.

Don't have a setup on my person laptop so can't test this, but I have used this script numerous times at my previous company and it never failed. We had native replication (SQL Server to SQL Server) and I believe it was push so it may need to be tweaked for your environment

Steps to Remove, then Reinitialize Article (table)

Pull table out of replication

Do whatever you need to do. Truncate, DDL, etc...

Add table back into replication and re-snapshot (reinitializes replication)

```<code>/*Run in context of publisher database where the article is located*/
Use YourDatabase
Go

/*Step 1: Inactivate the Article's Subscription*/
Exec sp_changesubstatus
    @publication = 'YourPublicationName'
    ,@article = N'YourTableName'
    ,@status = N'inactive'
Go

/*Step 2: Truncate table*/

/*Step 3: Put table back in replication*/
Exec sp_changesubstatus
    @publication = N'YourPublication'
    ,@article = N'YourTableName',
    @status = N'active'
Go

/*Invalidate old snapshot*/
Exec sp_reinitsubscription
    @publication = 'YourPublication'
    ,@article = 'YourTableName'
    ,@subscriber = 'DestinationServerName'
    ,@destination_db = 'YourDatabaseName'
    ,@invalidate_snapshot = 1

/*Kick off the snapshot job. This identifies any tables with invalid snapshots and re-snapshots them.
WARNING this may re-snaphsot other tables that are also waiting for a snapshot, probably unlikely, but worth noting*/
Exec sp_startpublication_snapshot @Publication = 'YourPublication'
Go
</code>```

WARNING: Be Careful Running Snapshot in Production

One major warning I will give is be very careful running the snapshot job in a production environment. My previous company used to truncate and re-snapshot tables for years and years. Then one day, we found the snapshot job started high level table locks across every table in the subscription for significant periods of time. This caused massive deadlocking issues, and because replication is a system process, it was very tricky to identify the culprit in the deadlock analysis since it looked like our scripts were just conflicting with the database engine.

Body:
For the record, I do not recommend replication. It is slow, finicky, and has a lot of quirks like this that make it painful to manage. Mirroring/AG/Log Shipping are much better options if you can use them.

Don't have a setup on my person laptop so can't test this, but I have used this script numerous times at my previous company and it never failed. We had native replication (SQL Server to SQL Server) and I believe it was push so it may need to be tweaked for your environment

Steps to Remove, then Reinitialize Article (table)

Pull table out of replication

Do whatever you need to do. Truncate, DDL, etc...

Add table back into replication and re-snapshot (reinitializes replication)

/*Run in context of publisher database where the article is located*/
Use YourDatabase
Go

/*Step 1: Inactivate the Article's Subscription*/
Exec sp_changesubstatus
    @publication = 'YourPublicationName'
    ,@article = N'YourTableName'
    ,@status = N'inactive'
Go

/*Step 2: Truncate table*/

/*Step 3: Put table back in replication*/
Exec sp_changesubstatus
    @publication = N'YourPublication'
    ,@article = N'YourTableName',
    @status = N'active'
Go

/*Invalidate old snapshot*/
Exec sp_reinitsubscription
    @publication = 'YourPublication'
    ,@article = 'YourTableName'
    ,@subscriber = 'DestinationServerName'
    ,@destination_db = 'YourDatabaseName'
    ,@invalidate_snapshot = 1

/*Kick off the snapshot job. This identifies any tables with invalid snapshots and re-snapshots them.
WARNING this may re-snaphsot other tables that are also waiting for a snapshot, probably unlikely, but worth noting*/
Exec sp_startpublication_snapshot @Publication = 'YourPublication'
Go

WARNING: Be Careful Running Snapshot in Production

One major warning I will give is be very careful running the snapshot job in a production environment. My previous company used to truncate and re-snapshot tables for years and years. Then one day, we found the snapshot job started high level table locks across every table in the subscription for significant periods of time. This caused massive deadlocking issues, and because replication is a system process, it was very tricky to identify the culprit in the deadlock analysis since it looked like our scripts were just conflicting with the database engine.


问:
How to test Connection Pooling in nodeJS using mogoDB Database?
How to test Connection Pooling in NodeJS using MongoDB Database?</p>

答:
Instead of having our app wait around for a request before connecting to the database we're going to have it connect when the application starts, and we're going to give ourselves a pool of connections to draw from as and when we need them.

Here we're using the node-mongodb-native driver, which like most available MongoDB drivers has an option that you can use to set the size of your connection pool. For this driver, it's called poolSize, and has a default value of 5. We can make use of the poolsize option by creating a database connection variable in advance, and letting the driver allocate available spaces as new connection requests come in:

// This is a global variable we'll use for handing the MongoDB client
var mongodb;

// Connection URL
var url = '[connectionString]';

// Create the db connection
MongoClient.connect(url, function(err, db) {
    assert.equal(null, err);
    mongodb=db;
    }
);
```
<p>To change the size of the connection pool from the default, we can pass <code>poolSize</code> in as an option:</p>
<pre class="lang-js prettyprint-override"><code>// Create the database connection
MongoClient.connect(url, {
  poolSize: 10
  // other options can go here
},function(err, db) {
    assert.equal(null, err);
    mongodb=db;
    }
);
</code>```

Now we have a connection ready and waiting. To use our new connection, we just need to make use of our new global variable, mongodb when a request is made:

// Use the connect method to connect to the server when the page is requested
app.get('/', function(request, response) {
    mongodb.listCollections({}).toArray(function(err, collections) {
        assert.equal(null, err);
        collections.forEach(function(collection) {
            console.log(collection);
        });
    })
    response.send('See console for a list of available collections');
});
```

Body:
Instead of having our app wait around for a request before connecting to the database we're going to have it connect when the application starts, and we're going to give ourselves a pool of connections to draw from as and when we need them.

Here we're using the node-mongodb-native driver, which like most available MongoDB drivers has an option that you can use to set the size of your connection pool. For this driver, it's called poolSize, and has a default value of 5. We can make use of the poolsize option by creating a database connection variable in advance, and letting the driver allocate available spaces as new connection requests come in:

// This is a global variable we'll use for handing the MongoDB client
var mongodb;

// Connection URL
var url = '[connectionString]';

// Create the db connection
MongoClient.connect(url, function(err, db) {
    assert.equal(null, err);
    mongodb=db;
    }
);

To change the size of the connection pool from the default, we can pass poolSize in as an option:

// Create the database connection
MongoClient.connect(url, {
  poolSize: 10
  // other options can go here
},function(err, db) {
    assert.equal(null, err);
    mongodb=db;
    }
);

Now we have a connection ready and waiting. To use our new connection, we just need to make use of our new global variable, mongodb when a request is made:

// Use the connect method to connect to the server when the page is requested
app.get('/', function(request, response) {
    mongodb.listCollections({}).toArray(function(err, collections) {
        assert.equal(null, err);
        collections.forEach(function(collection) {
            console.log(collection);
        });
    })
    response.send('See console for a list of available collections');
});


问:
react-router v6: get path pattern for current route
Is it possible to get the path pattern for the currently matched route? Example:

```<code><Route
    path=":state/:city*"
    element={
        <Page />
    }
/>
</code>```

// Page.jsx

function Page() {
    ...
    // usePathPattern doesn't actually exist
    const pathPattern = usePathPattern(); // pathPattern = ":state/:city*"
    ...
}
```

I know I can use useMatch to check if the current location matches a specific path pattern, but then the component has to know what the path pattern is.

答:
This seems to work with what they actually export as of 6.2.1, however it uses a component they export as UNSAFE_</p>
```<code>import { UNSAFE_RouteContext } from 'react-router-dom';

const reconstructPath = (matches) =>
  matches
    .map(({ route: { path } }) =>
      path.endsWith('/*') ? path.slice(0, -1) : path ? path + '/' : ''
    )
    .join('');

const findLastNode = (node) =>
  node.outlet ? findLastNode(node.outlet.props.value) : node;

const usePathPattern = () =>
  reconstructPath(
    findLastNode(React.useContext(UNSAFE_RouteContext)).matches
  );
</code>```

Body:
Is it possible to get the path pattern for the currently matched route? Example:

<Route
    path=":state/:city*"
    element={
        <Page />
    }
/>

// Page.jsx

function Page() {
    ...
    // usePathPattern doesn't actually exist
    const pathPattern = usePathPattern(); // pathPattern = ":state/:city*"
    ...
}

I know I can use useMatch to check if the current location matches a specific path pattern, but then the component has to know what the path pattern is.

Body:
This seems to work with what they actually export as of 6.2.1, however it uses a component they export as UNSAFE_

import { UNSAFE_RouteContext } from 'react-router-dom';

const reconstructPath = (matches) =>
  matches
    .map(({ route: { path } }) =>
      path.endsWith('/*') ? path.slice(0, -1) : path ? path + '/' : ''
    )
    .join('');

const findLastNode = (node) =>
  node.outlet ? findLastNode(node.outlet.props.value) : node;

const usePathPattern = () =>
  reconstructPath(
    findLastNode(React.useContext(UNSAFE_RouteContext)).matches
  );


问:
Test execution gets stopped after an assertion error in pytest With Fixtures
I am new to Python ,

For the data driven testing, if there is 10tests , and the assertion fails   [  AssertionError.  ] for 4th  test ,  then the rest of the 6 data sets are not considered for execution and the program gets stopped at that point completely. I want test to continue even if one dataset fails ? How can we achieve with fixtures ? Or is there any other way ?

We set up a fixture for Data Driven Testing  using Fixtures.

========== TEST DATA ============

```<code>Test data is defined in Json  File [ array of JSON Objects ]
</code>```

==============. Fixture Code =========

```<code>from _pytest.fixtures import fixture

users_json_files_path=. “//Pathto_Input_Json_File”.

@fixture(params=load_jsondata(users_json_files_path))
def users_testdata(request):

    user_test_data=request.param
    return user_test_data
</code>```

=========== Passing Fixture to Test Method . ==============

```<code>def test_one(users_testdata):
      assert len(users_not_present == 0 ,"Following Users not present :: " + str(users_not_present)
</code>```

Thanks,
Deepti

答:
Not exactly sure what you are asserting. You can use this for your case:
https://pypi.org/project/pytest_check/</p>

Body:
I am new to Python ,

For the data driven testing, if there is 10tests , and the assertion fails   [  AssertionError.  ] for 4th  test ,  then the rest of the 6 data sets are not considered for execution and the program gets stopped at that point completely. I want test to continue even if one dataset fails ? How can we achieve with fixtures ? Or is there any other way ?

We set up a fixture for Data Driven Testing  using Fixtures.

========== TEST DATA ============

Test data is defined in Json  File [ array of JSON Objects ]

==============. Fixture Code =========

from _pytest.fixtures import fixture

users_json_files_path=. “//Pathto_Input_Json_File”.

@fixture(params=load_jsondata(users_json_files_path))
def users_testdata(request):

    user_test_data=request.param
    return user_test_data

=========== Passing Fixture to Test Method . ==============

def test_one(users_testdata):
      assert len(users_not_present == 0 ,"Following Users not present :: " + str(users_not_present)

Thanks,
Deepti


问:
Program runs infinitely on typing ctrl C instead of stopping in c++
I have the following code. It runs infinitely after typing ctrl + c and executes the default section of code.

```<code>// Program to build a simple calculator using switch Statement
#include <iostream>
using namespace std;

int main() {
    char oper;
    float num1, num2;
    while(true){
        cout << "Enter an operator (+, -, *, /): ";
        cin >> oper;
        cout << "Enter two numbers: " << endl;
        cin >> num1 >> num2;

        switch (oper) {
            case '+':
                cout << num1 << " + " << num2 << " = " << num1 + num2;
                break;
            case '-':
                cout << num1 << " - " << num2 << " = " << num1 - num2;
                break;
            case '*':
                cout << num1 << " * " << num2 << " = " << num1 * num2;
                break;
            case '/':
                cout << num1 << " / " << num2 << " = " << num1 / num2;
                break;
            default:
                // operator is doesn't match any case constant (+, -, *, /)
                cout << "Error! The operator is not correct";
                break;
        }
        cout<<endl;
    }
    return 0;
}
</code>```

The result after typing ctrl + c is as shown in the image.

So my question is: is it normal behavior in c++? If it is, then, how may we interpret it?

答:
Pressing ^C at a terminal causes the kernel to send the SIGINT signal to all processes in the foreground process group of the session controlled by the terminal. In the case that you are running the process in a terminal emulator, sending ^C on the master end causes the foreground processes on the slave end to receive SIGINT.

This behaviour is configurable via the tcsetattr system call.

By default, a process that receives SIGINT will immediately terminate, though a process can choose to ignore or handle this signal. Stay blessed

Body:
I have the following code. It runs infinitely after typing ctrl + c and executes the default section of code.

// Program to build a simple calculator using switch Statement
#include <iostream>
using namespace std;

int main() {
    char oper;
    float num1, num2;
    while(true){
        cout << "Enter an operator (+, -, *, /): ";
        cin >> oper;
        cout << "Enter two numbers: " << endl;
        cin >> num1 >> num2;

        switch (oper) {
            case '+':
                cout << num1 << " + " << num2 << " = " << num1 + num2;
                break;
            case '-':
                cout << num1 << " - " << num2 << " = " << num1 - num2;
                break;
            case '*':
                cout << num1 << " * " << num2 << " = " << num1 * num2;
                break;
            case '/':
                cout << num1 << " / " << num2 << " = " << num1 / num2;
                break;
            default:
                // operator is doesn't match any case constant (+, -, *, /)
                cout << "Error! The operator is not correct";
                break;
        }
        cout<<endl;
    }
    return 0;
}

The result after typing ctrl + c is as shown in the image.

So my question is: is it normal behavior in c++? If it is, then, how may we interpret it?


问:
Download a zip file that is created when a URL is passed to domain site, but I have tried for 4 days 30-50 different ways, and no luck. CAISO OASIS
The site is the CAISO OASIS and they use an old way of querying and returning datasets. 30 days at a time, zip file with enclosed *.csv files. I have tried for 4 days coming up with a way to automate this download first of the zip file but i cant even get past there.

If I populate the url string I want and enter it myself in the address bar a zip file will start downloading, I cannot for the life of me get it to do the same through code.

I need to use php to accomplish this task.
I have tried, fopen, file_get_contents, file_put_contents, cURL, ziparchive class.  I have tried changing all sorts of things. The best I get is a download of a corrupt zip file that is empty.

Ideally i would love to extract the *.csv or xml file but I cannot even do the first basic step.

The following variable I populate, $url_caiso_qry,  if you take the echo string and past in the browser and enter the zip file will start downloading, but I cannot download it automatically.

http://oasis.caiso.com/oasisapi/SingleZip?startdatetime=20220109T7:00-0000&enddatetime=20220207T7:00-0000&resultformat=6&queryname=SLD_FCST&market_run_id=ACTUAL&version=1

<?php

$public_end = strpos($_SERVER['SCRIPT_NAME'], '/public') + 13;
$doc_root = substr($_SERVER['SCRIPT_NAME'], 0, $public_end);
define("WWW_ROOT", $doc_root);

// creates data array for precio de carga SIN
// function create_dataarrayp_chrt($zona) {

$ayer = date("Ymd\T7:00-0000", strtotime('now - 1 day'));
$mespasado = date("Ymd\T7:00-0000",strtotime('-30 days'));

$sdate = $mespasado;  //startdatetime=
$edate = $ayer;   //enddatetime=
$resultformat = '6';
$queryname='SLD_FCST';
$version='1';
$marketrunid='ACTUAL';

$fields = [
    'startdatetime' => $sdate,
    'enddatetime' => $edate,
    'resultformat' => $resultformat,
    'queryname' => $queryname,
    'market_run_id' => $marketrunid,
    'version' => $version,
];

//post fields
$postparam = urldecode(http_build_query($fields));

//PRECIOS   url base string
$urlcaiso = 'http://oasis.caiso.com/oasisapi/SingleZip?';
//$urlcaiso = 'http://oasis.caiso.com/oasisapi/SingleZip?resultformat=6&queryname=SLD_FCST&version=1&market_run_id=ACTUAL&startdatetime=' . $sdate . 'T07:00-0000&enddatetime=' . $edate . 'T07:00-0000';

$url_caiso_qry = $urlcaiso . $postparam;

$caisofile = file_get_contents($url_caiso_qry, "rb");

//attempt to write file to destination path, but no file is written.  Instead the following warning
//Warning: file_put_contents(/name1/name2/private/test/):
// failed to open stream: No such file or directory in C:\xampp\htdocs\name1\name2\private\test.php on line 94

$destination_path = WWW_ROOT . 'name2/private/test/';
$newfile = file_put_contents($destination_path, $caisofile);

echo $newfile . '

';
?>
```

答:
Clean & tested code. Your csv file will be extracted to your script's directory.</p>
```<code><?php

define('PATH_ZIP', __DIR__ . '/archive.zip');

$url = 'http://oasis.caiso.com/oasisapi/SingleZip?' . http_build_query
([
    'startdatetime' => '20220109T7:00-0000',
    'enddatetime'   => '20220207T7:00-0000',
    'resultformat'  => '6',
    'queryname'     => 'SLD_FCST',
    'market_run_id' => 'ACTUAL',
    'version'       => '1',
]);

$data = file_get_contents($url);

file_put_contents(PATH_ZIP, $data);

$zip = new ZipArchive;

if ($zip->open(PATH_ZIP) === true)
{
    $zip->extractTo(__DIR__);
    $zip->close();
}
</code>```

Body:
Clean & tested code. Your csv file will be extracted to your script's directory.

<?php

define('PATH_ZIP', __DIR__ . '/archive.zip');

$url = 'http://oasis.caiso.com/oasisapi/SingleZip?' . http_build_query
([
    'startdatetime' => '20220109T7:00-0000',
    'enddatetime'   => '20220207T7:00-0000',
    'resultformat'  => '6',
    'queryname'     => 'SLD_FCST',
    'market_run_id' => 'ACTUAL',
    'version'       => '1',
]);

$data = file_get_contents($url);

file_put_contents(PATH_ZIP, $data);

$zip = new ZipArchive;

if ($zip->open(PATH_ZIP) === true)
{
    $zip->extractTo(__DIR__);
    $zip->close();
}


问:
How do I list all currently available GPUs with pytorch?
I know I can access the current GPU using torch.cuda.current_device(), but how can I get a list of all the currently available GPUs?

答:
Check how many GPUs are available with PyTorch

```<code>import torch

num_of_gpus = torch.cuda.device_count()
print(num_of_gpus)
</code>```

In case you want to use the first GPU from it.

```<code>device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
</code>```

Replace 0 in the above command with another number If you want to use another GPU.

Body:
Check how many GPUs are available with PyTorch

import torch

num_of_gpus = torch.cuda.device_count()
print(num_of_gpus)

In case you want to use the first GPU from it.

device = 'cuda:0' if torch.cuda.is_available() else 'cpu'

Replace 0 in the above command with another number If you want to use another GPU.


问:
How to use \COPY command inside a function in PostgreSQL
I want to export the table into a .CSV file using \COPY command. I can able to do that as a stand-alone command. I can't embed the same line inside a function in PostgreSQL. Actually that call should come from a ECPG. I chose \COPY over COPY command as I don't have super-user account! Please guide me on this.

Thanks and Regards,
Siva.

答: Unfortunately, all of the \ commands are psql commands. You can run psql -E to see what those commands expand into and get sent to the server as, but if you need a super-user account to run COPY, you're going to need a super-user account to do this.


问:
why I can not get input from console javascript
Trying to finish find the hat game in vanilla js but I can not get input from console either way. When I try to use prompt sync I get "Uncaught Error: ENXIO: no such device or address, open '/dev/tty'" error and "Uncaught Error: Cannot find module 'prompt-sync" even though npm and node are installed and up-to-date. When I try to use readline method it works but it does not continue even after my input.

[codebyte]

```<code>const hat = '^';
const hole = 'O';
const fieldCharacter = '░';
const pathCharacter = '*';
let prompt = require('prompt-sync')();

class Field {

constructor(map) {
    this._map = [
        ["*","░","░"],
        ["░","0","░"],
        ["0","^","0"]
    ];
    this._uinput = "";

}

falldown(){
}

printgame(){

    let str = "";

    for (const element of this._map) {
        for (const element2 of element) {
            str += element2;
        }
        console.log(str);
        str = "";

    }
}

 getUserInput(){

     this._uinput = prompt("Where do we move?");

 }

game(){
    let pcursor = this._map[0][0];
    let xaxis = 0;
    let yaxis = 0;
    let counter = 1;

    console.log("Welcome to the hat game! Find the hat using WASD.")

    do{
        this.printgame();
        this.getUserInput();

            if (this._uinput.toLowerCase() === "w"){
                yaxis +=1;
                switch (yaxis) {
                    case yaxis<0:
                        console.log("You have fallen out of cliff");
                        return;
                    case (yaxis)>this._map.length:
                        console.log("You have fallen out of cliff");
                        return;
                }
                if (this._map[yaxis][xaxis] === "0"){
                    console.log("You have fallen in hole");
                    return;
                }else if (this._map[yaxis][xaxis] === "░"){
                    console.log("you can Continue...")
                    this._map[yaxis].splice(xaxis,1,"*");
                    this.printgame();

                }

            }else if (this._uinput.toLowerCase() === "s"){
                yaxis +=1;
                switch (yaxis) {
                    case yaxis<0:
                        console.log("You have fallen out of cliff");
                        return;
                    case (yaxis)>this._map.length:
                        console.log("You have fallen out of cliff");
                        return;

                }

                if (this._map[yaxis][xaxis] === "0"){
                    console.log("You have fallen in hole");
                    return;
                }else if (this._map[yaxis][xaxis] === "░"){
                    this._map[yaxis].splice(xaxis,1,"*");
                    return;

                }

            }
            this._uinput = "";

    }while(this._uinput !== "");

}

}

const gamee = new Field([
    ["*","░","░"],
    ["░","0","░"],
    ["0","^","0"]
]);
gamee.game();
</code>```

[/codebyte]

[codebyte]

```<code>const hat = '^';
const hole = 'O';
const fieldCharacter = '░';
const pathCharacter = '*';
const readline = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
  });

class Field {

constructor(map) {
    this._map = [
        ["*","░","░"],
        ["░","0","░"],
        ["0","^","0"]
    ];
    this._uinput = "";

}

falldown(){
}

printgame(){

    let str = "";

    for (const element of this._map) {
        for (const element2 of element) {
            str += element2;
        }
        console.log(str);
        str = "";

    }
}

 getUserInput(){
    let uinputt = "";

    readline.question('Who are you?', uinputt => {
        console.log("uinput");
        readline.close();
        readline.close();
        return uinputt
      });

 }

game(){
    let pcursor = this._map[0][0];
    let xaxis = 0;
    let yaxis = 0;
    let counter = 1;

    console.log("Welcome to the hat game! Find the hat using WASD.");
    this.printgame();
    let uput = this.getUserInput();

    do{

            if (uput === "w"){
                yaxis +=1;
                switch (yaxis) {
                    case yaxis<0:
                        console.log("You have fallen out of cliff");
                        return;
                    case (yaxis)>this._map.length:
                        console.log("You have fallen out of cliff");
                        return;
                }
                if (this._map[yaxis][xaxis] === "0"){
                    console.log("You have fallen in hole");
                    return;
                }else if (this._map[yaxis][xaxis] === "░"){
                    console.log("you can Continue...")
                    this._map[yaxis].splice(xaxis,1,"*");
                    this.printgame();

                }

            }else if (uput === "s"){
                yaxis +=1;
                switch (yaxis) {
                    case yaxis<0:
                        console.log("You have fallen out of cliff");
                        return;
                    case (yaxis)>this._map.length:
                        console.log("You have fallen out of cliff");
                        return;

                }

                if (this._map[yaxis][xaxis] === "0"){
                    console.log("You have fallen in hole");
                    return;
                }else if (this._map[yaxis][xaxis] === "░"){
                    this._map[yaxis].splice(xaxis,1,"*");
                    return;

                }

            }
            this._uinput = "";

    }while(this._uinput !== "");

}

}
const gamee = new Field([
    ["*","░","░"],
    ["░","0","░"],
    ["0","^","0"]
]);
gamee.game();
</code>```

[/codebyte]

答:
if you want to use prompt sync you first have to install it with npm in your project dir:

```<code>npm install prompt-sync
</code>```

then you should use it like this:

```<code>var prompt = require('prompt-sync')();
var n = prompt('My input! ');
</code>```

Body:
Trying to finish find the hat game in vanilla js but I can not get input from console either way. When I try to use prompt sync I get "Uncaught Error: ENXIO: no such device or address, open '/dev/tty'" error and "Uncaught Error: Cannot find module 'prompt-sync" even though npm and node are installed and up-to-date. When I try to use readline method it works but it does not continue even after my input.

[codebyte]

const hat = '^';
const hole = 'O';
const fieldCharacter = '░';
const pathCharacter = '*';
let prompt = require('prompt-sync')();

class Field {

constructor(map) {
    this._map = [
        ["*","░","░"],
        ["░","0","░"],
        ["0","^","0"]
    ];
    this._uinput = "";

}

falldown(){
}

printgame(){

    let str = "";

    for (const element of this._map) {
        for (const element2 of element) {
            str += element2;
        }
        console.log(str);
        str = "";

    }
}

 getUserInput(){

     this._uinput = prompt("Where do we move?");

 }

game(){
    let pcursor = this._map[0][0];
    let xaxis = 0;
    let yaxis = 0;
    let counter = 1;

    console.log("Welcome to the hat game! Find the hat using WASD.")

    do{
        this.printgame();
        this.getUserInput();

            if (this._uinput.toLowerCase() === "w"){
                yaxis +=1;
                switch (yaxis) {
                    case yaxis<0:
                        console.log("You have fallen out of cliff");
                        return;
                    case (yaxis)>this._map.length:
                        console.log("You have fallen out of cliff");
                        return;
                }
                if (this._map[yaxis][xaxis] === "0"){
                    console.log("You have fallen in hole");
                    return;
                }else if (this._map[yaxis][xaxis] === "░"){
                    console.log("you can Continue...")
                    this._map[yaxis].splice(xaxis,1,"*");
                    this.printgame();

                }

            }else if (this._uinput.toLowerCase() === "s"){
                yaxis +=1;
                switch (yaxis) {
                    case yaxis<0:
                        console.log("You have fallen out of cliff");
                        return;
                    case (yaxis)>this._map.length:
                        console.log("You have fallen out of cliff");
                        return;

                }

                if (this._map[yaxis][xaxis] === "0"){
                    console.log("You have fallen in hole");
                    return;
                }else if (this._map[yaxis][xaxis] === "░"){
                    this._map[yaxis].splice(xaxis,1,"*");
                    return;

                }

            }
            this._uinput = "";

    }while(this._uinput !== "");

}

}

const gamee = new Field([
    ["*","░","░"],
    ["░","0","░"],
    ["0","^","0"]
]);
gamee.game();

[/codebyte]

[codebyte]

const hat = '^';
const hole = 'O';
const fieldCharacter = '░';
const pathCharacter = '*';
const readline = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
  });

class Field {

constructor(map) {
    this._map = [
        ["*","░","░"],
        ["░","0","░"],
        ["0","^","0"]
    ];
    this._uinput = "";

}

falldown(){
}

printgame(){

    let str = "";

    for (const element of this._map) {
        for (const element2 of element) {
            str += element2;
        }
        console.log(str);
        str = "";

    }
}

 getUserInput(){
    let uinputt = "";

    readline.question('Who are you?', uinputt => {
        console.log("uinput");
        readline.close();
        readline.close();
        return uinputt
      });

 }

game(){
    let pcursor = this._map[0][0];
    let xaxis = 0;
    let yaxis = 0;
    let counter = 1;

    console.log("Welcome to the hat game! Find the hat using WASD.");
    this.printgame();
    let uput = this.getUserInput();

    do{

            if (uput === "w"){
                yaxis +=1;
                switch (yaxis) {
                    case yaxis<0:
                        console.log("You have fallen out of cliff");
                        return;
                    case (yaxis)>this._map.length:
                        console.log("You have fallen out of cliff");
                        return;
                }
                if (this._map[yaxis][xaxis] === "0"){
                    console.log("You have fallen in hole");
                    return;
                }else if (this._map[yaxis][xaxis] === "░"){
                    console.log("you can Continue...")
                    this._map[yaxis].splice(xaxis,1,"*");
                    this.printgame();

                }

            }else if (uput === "s"){
                yaxis +=1;
                switch (yaxis) {
                    case yaxis<0:
                        console.log("You have fallen out of cliff");
                        return;
                    case (yaxis)>this._map.length:
                        console.log("You have fallen out of cliff");
                        return;

                }

                if (this._map[yaxis][xaxis] === "0"){
                    console.log("You have fallen in hole");
                    return;
                }else if (this._map[yaxis][xaxis] === "░"){
                    this._map[yaxis].splice(xaxis,1,"*");
                    return;

                }

            }
            this._uinput = "";

    }while(this._uinput !== "");

}

}
const gamee = new Field([
    ["*","░","░"],
    ["░","0","░"],
    ["0","^","0"]
]);
gamee.game();

[/codebyte]

Body:
if you want to use prompt sync you first have to install it with npm in your project dir:

npm install prompt-sync

then you should use it like this:

var prompt = require('prompt-sync')();
var n = prompt('My input! ');


问:
How do I change the color of the line highlight in vscode when using findNext
I have customized my theme in vscode to use the lineHighlight color as follows...

```<code>    "editor.lineHighlightBackground": "#3c3c3c",
</code>```

This change works, with the exception of when I use find next.

If I open the find window, and end a value that matches with multiple lines, and then use the findNext command to cycle through them, there is a line highlight that draws, but it is not using the line highlight that I specified.

I have looked through the vscode theme colors documentation and they only specify the following line highlight values..

```<code>editor.lineHighlightBackground: Background color for the highlight of line at the cursor position.
editor.lineHighlightBorder: Background color for the border around the line at the cursor position.
</code>```

How can I change the color of the line highlight when using find next?

答:
Use:

"editor.rangeHighlightBackground": "#ff0000"

editor.findRangeHighlightBackground: Color the range limiting the
search (Enable 'Find in Selection' in the find widget). The color must
not be opaque so as not to hide underlying decorations.

It is more specific than a line highlight so it is the one applied.  It applies whether the Find in Selection option is enabled or not - not sure why it implies that.

Body:
I have customized my theme in vscode to use the lineHighlight color as follows...

    "editor.lineHighlightBackground": "#3c3c3c",

This change works, with the exception of when I use find next.

If I open the find window, and end a value that matches with multiple lines, and then use the findNext command to cycle through them, there is a line highlight that draws, but it is not using the line highlight that I specified.

I have looked through the vscode theme colors documentation and they only specify the following line highlight values..

editor.lineHighlightBackground: Background color for the highlight of line at the cursor position.
editor.lineHighlightBorder: Background color for the border around the line at the cursor position.

How can I change the color of the line highlight when using find next?


问:
new to python having trouble printing 4 variables
```<code>adding = int(5+3)
subtract = int(10-2)
multiplication = int(2*4)
division = int(16/2)
print (str(adding,"\n",subtract,"\n",multiplication,"\n",division))
</code>```

im getting a typeError: TypeError: str() takes at most 3 arguments (7 given)

答:
Solution:
Just change this piece of code from this

```<code>print (str(adding,"\n",subtract,"\n",multiplication,"\n",division))
</code>```

To this.

```<code>print (adding,"\n",subtract,"\n",multiplication,"\n",division)
</code>```

Reason: str() is a typecast method. You don't need to typecast each and everything.

For Reference:
https://www.geeksforgeeks.org/type-casting-in-python-implicit-and-explicit-with-examples/

Body:
adding = int(5+3)
subtract = int(10-2)
multiplication = int(2*4)
division = int(16/2)
print (str(adding,"\n",subtract,"\n",multiplication,"\n",division))

im getting a typeError: TypeError: str() takes at most 3 arguments (7 given)

Body:
Solution:
Just change this piece of code from this

print (str(adding,"\n",subtract,"\n",multiplication,"\n",division))

To this.

print (adding,"\n",subtract,"\n",multiplication,"\n",division)

Reason: str() is a typecast method. You don't need to typecast each and everything.

For Reference:
https://www.geeksforgeeks.org/type-casting-in-python-implicit-and-explicit-with-examples/


问:
When div is visible on screen add .active class to li
I am trying to build a page:
Like This

When a div gets into the view on the screen, then a class gets added to the right side of the "table of contents", then when it's scrolled off the screen and another div shows up the class gets moved to the next "title" of the content.

So far I have a list of divs stacked on the top of each other and some basic JS but it does not work. I am not even sure if this is a good approach to get this done?

```<code>$(window).scroll(function(){
  if ( $('#field-wrap1').offset().top <= 100 ) {
    $('#slide-li1').addClass("active");
  }else{
    $('#slide-li1').removeClass("active");
  }
});
</code>```

JSFiddle

答:
In the solution below, I divided the value of this.scrollY by 200, since the height of the containers is 200px. I added the result of this action to the end of the slide-li statement to use as the id of the targeted item.

function removeClass() {
  for(let i = 0 ; i < 6 ; i++)
    $(`#slide-li${i + 1}`).removeClass("active");
}

$(window).scroll(function(){
    console.clear();
    console.log(`Scroll: ${this.scrollY}`);

    removeClass();
    let visibleElement = Math.floor(this.scrollY / 200);
    $(`#slide-li${visibleElement + 1}`).addClass("active");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
     width: 800px;
     margin: auto;
     text-align: left;
     display: inline-flex;
     margin: 0;
     margin: 100px 0;
}
 #field {
     width: 500px;
     float: left;
     font-weight: 500;
     color: #001737;
}
 .field-wrap {
     padding: 0;
     border-bottom: 1px solid #8392A5;
     height: 200px;
     background-color: #FF000030;
}
 #slidecart {
     position: fixed;
     top: 10px;
     right: 0px;
     width: 300px;
     display: inline-block;
     padding: 20px;
     border-left: 1px solid #8392A5;
}
 #slide-ul {
     list-style-type: none;
     margin: 0;
     padding: 5px 0 0 5px;
}
 .slide-li {
     margin: 0;
     padding: 0 0 0 10px;
     cursor: pointer;
}
 .active {
     padding: 0 0 0 5px;
     border-left: 5px solid #0168FA;
     color: #0168FA;
}</code>```

      1.) - Hello World!

      2.) - Hello World!

      3.) - Hello World!

      4.) - Hello World!

      5.) - Hello World!

      6.) - Hello World!

    TABLE OF CONTENTS

LIST

1.) - Hello World!

2.) - Hello World!

3.) - Hello World!

4.) - Hello World!

5.) - Hello World!

6.) - Hello World!

```

Body:
I am trying to build a page:
Like This

When a div gets into the view on the screen, then a class gets added to the right side of the "table of contents", then when it's scrolled off the screen and another div shows up the class gets moved to the next "title" of the content.

So far I have a list of divs stacked on the top of each other and some basic JS but it does not work. I am not even sure if this is a good approach to get this done?

$(window).scroll(function(){
  if ( $('#field-wrap1').offset().top <= 100 ) {
    $('#slide-li1').addClass("active");
  }else{
    $('#slide-li1').removeClass("active");
  }
});

JSFiddle

Body:
In the solution below, I divided the value of this.scrollY by 200, since the height of the containers is 200px. I added the result of this action to the end of the slide-li statement to use as the id of the targeted item.

function removeClass() {
  for(let i = 0 ; i < 6 ; i++)
    $(`#slide-li${i + 1}`).removeClass("active");
}

$(window).scroll(function(){
    console.clear();
    console.log(`Scroll: ${this.scrollY}`);

    removeClass();
    let visibleElement = Math.floor(this.scrollY / 200);
    $(`#slide-li${visibleElement + 1}`).addClass("active");
});

#container {
     width: 800px;
     margin: auto;
     text-align: left;
     display: inline-flex;
     margin: 0;
     margin: 100px 0;
}
 #field {
     width: 500px;
     float: left;
     font-weight: 500;
     color: #001737;
}
 .field-wrap {
     padding: 0;
     border-bottom: 1px solid #8392A5;
     height: 200px;
     background-color: #FF000030;
}
 #slidecart {
     position: fixed;
     top: 10px;
     right: 0px;
     width: 300px;
     display: inline-block;
     padding: 20px;
     border-left: 1px solid #8392A5;
}
 #slide-ul {
     list-style-type: none;
     margin: 0;
     padding: 5px 0 0 5px;
}
 .slide-li {
     margin: 0;
     padding: 0 0 0 10px;
     cursor: pointer;
}
 .active {
     padding: 0 0 0 5px;
     border-left: 5px solid #0168FA;
     color: #0168FA;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="container">
  <div id="field">
    <div id="field-wrap1" class="field-wrap">
      1.) - Hello World!
    </div>

    <div id="field-wrap2" class="field-wrap">
      2.) - Hello World!
    </div>

    <div id="field-wrap3" class="field-wrap">
      3.) - Hello World!
    </div>

    <div id="field-wrap4" class="field-wrap">
      4.) - Hello World!
    </div>

    <div id="field-wrap5" class="field-wrap">
      5.) - Hello World!
    </div>

    <div id="field-wrap6" class="field-wrap">
      6.) - Hello World!
    </div>

  </div>

  <div id="slidecart">
    TABLE OF CONTENTS
    <ul id="slide-ul">LIST
      <li id="slide-li1" class="slide-li">1.) - Hello World!</li>
      <li id="slide-li2" class="slide-li">2.) - Hello World!</li>
      <li id="slide-li3" class="slide-li">3.) - Hello World!</li>
      <li id="slide-li4" class="slide-li">4.) - Hello World!</li>
      <li id="slide-li5" class="slide-li">5.) - Hello World!</li>
      <li id="slide-li6" class="slide-li">6.) - Hello World!</li>
    </ul>
  </div>

</div>


问:
Catch multiple Ctrl+C keypresses in Java to do graceful and forced shutdowns
In my Java console application I catch a Ctrl+C key press and add a thread performing graceful shutdown using Runtime.getRuntime().addShutdownHook()

In this thread I process all oustanding work in some internal queues and exit my application gracefully which is normally what I want.

However, sometimes the application can have internal queues that take a while to proces (several minutes), if so I would like an option to press Ctrl+C a second time to forcibly exit the application.

I have seen other applications working this way but I cannot find myself how to catch the second Ctrl+C in Java?

答:
Use Signal.handle on SIGINT and in the handler, restore the original default SIG_DFL handler. So if it is hit a second time, it will terminate the program using the SIG_DFL handler (supplied by the OS).

```<code>private void registerSigIntHandler() {
    Signal.handle(new Signal("INT"), new SignalHandler() {
        public void handle(Signal sig) {
            log.info("SIGINT received");
            Signal.handle(new Signal("INT"), SignalHandler.SIG_DFL);
            shutdown();
            SignalHandler.SIG_DFL.handle(new Signal("INT"));
        }
    });
}
</code>```

This also calls the SIG_DFL handler to terminate the process once your shutdown method completes.

https://stackoverflow.com/a/71028985/854342

Body:
Use Signal.handle on SIGINT and in the handler, restore the original default SIG_DFL handler. So if it is hit a second time, it will terminate the program using the SIG_DFL handler (supplied by the OS).

private void registerSigIntHandler() {
    Signal.handle(new Signal("INT"), new SignalHandler() {
        public void handle(Signal sig) {
            log.info("SIGINT received");
            Signal.handle(new Signal("INT"), SignalHandler.SIG_DFL);
            shutdown();
            SignalHandler.SIG_DFL.handle(new Signal("INT"));
        }
    });
}

This also calls the SIG_DFL handler to terminate the process once your shutdown method completes.

https://stackoverflow.com/a/71028985/854342


答:
Think of str as a function that takes in a variable and converts it into a string. Passing multiple variables to str() separated by comma will not apply string function to each variable. It will instead mean that they are arguments to the function.
If you want to convert each variable into

```<code>adding = str(int(5+3))
subtract = str(int(10-2))
multiplication = str(int(2*4))
division = str(int(16/2))
print (adding,"\n",subtract,"\n",multiplication,"\n",division)
</code>```

Note that print function accepts multiple arguments for printing purposes.

Title: new to python having trouble printing 4 variables

Body:
Think of str as a function that takes in a variable and converts it into a string. Passing multiple variables to str() separated by comma will not apply string function to each variable. It will instead mean that they are arguments to the function.
If you want to convert each variable into

adding = str(int(5+3))
subtract = str(int(10-2))
multiplication = str(int(2*4))
division = str(int(16/2))
print (adding,"\n",subtract,"\n",multiplication,"\n",division)

Note that print function accepts multiple arguments for printing purposes.


问:
File Download via API using Guzzle
I'm still on the learning slopes with Guzzle, but am stumped with this issue...

I'm trying to retrieve an audio file from a 3rd party API using Guzzle.  I've written a class with a number of functions and they all work apart from the very last stage of the 'download' function - the browser does not prompt to save the audio file

Call to get audio file, using AJAX

```<code>$callRows.on("click", ".download", function() {

    const $this = $(this);
    $this.parent().hide().next().show();

    $.ajax({
        type : "POST",
        url  : "submgmt",
        data : {
            task   : "getMedia",
            target : $this.data("id")
        },
        success  : function(data) {

            $this.parent().show().next().hide();

        },
        error : function (XMLHttpRequest, textStatus, errorThrown) {
            $dialog.attr("title", textStatus);
            $dialog.html("<br>" + errorThrown + "<br><br><h4>Click OK to continue</h4>");
            $dialog.dialog({
                buttons  : {
                    "OK" : function () {
                        $dialog.dialog("destroy");
                    }
                },
                dialogClass : "no-close",
                modal       : true,
                resizable   : false
            });
            $this.parent().show().next().hide();
        }
    });
});
</code>```

FIRST TRY
Function to call download function

```<code>$ucCall = new ucCalls($ucAuth);

try {

    $response = $ucCall->getMedia($target);

    if ($response['code']===404) {
        $result['ERROR'] = "1";
        $result['DETAILS'] = "File is no longer available";
        echo json_encode($result);
        exit();
    } else {
        header("Date: " . $response['headers']['Date'][0]);
        header("Cache-Control: " . $response['headers']['Cache-Control'][0]);
        header("Pragma: " . $response['headers']['Pragma'][0]);
        header("Expires: " . $response['headers']['Expires'][0]);
        header("Content-Type: " . $response['headers']['Content-Type'][0]);
        header('Content-Disposition: attachment; filename="' . basename($response['filename']) . '"');
        header("Content-Length: " . filesize($response['filename']));
        ob_clean();
        flush();
        readfile($response['filename']);
        exit;
    }
} catch (Exception $e) {
    $result['ERROR']   = "1";
    $result['DETAILS'] = $e->getCode() . " - " . $e->getMessage();
    echo json_encode($result);
    exit();
}
</code>```

Class to retrieve audio files from 3rd party API

```<code>class ucCalls {

private Client $client;

public function __construct($authString)
{
    $this->client = new Client([
        'base_uri' => 'https://url-of-host',
        'timeout'  => 5,
        'headers' => [
            'Authorization' => 'Basic ' . $authString,
            'Accept' => 'application/json'
        ],
    ]);
}

/**
 * Retrieves the unencrypted MP3 media for a (completed) recording
 * @param string $id
 * @return array
 * @throws Exception
 */
public function getMedia(string $id): array
{

    try {

        $temp_file = sys_get_temp_dir() . "\uc" . make_id(6) . ".mp3";
        $resource = Utils::tryFopen($temp_file, 'w');

        $response = $this->client->request('GET','fw/path/to/audio/file/store/' . $id . '/Media', ['sink' => $resource]);

        return [
            'code'     => $response->getStatusCode(),
            'headers'  => $response->getHeaders(),
            'filename' => $temp_file
        ];

    } catch (ConnectException $e) {
        error_log(print_r("## EXCEPTION ## ucCalls (getMedia) - ConnectException -> " . $e->getMessage(),true));
        throw new Exception ("Connection Error",500);
    } catch (ServerException|ClientException $e) {
        error_log(print_r("## EXCEPTION ## ucCalls (getMedia) - ServerException|ClientException -> " . $e->getMessage(),true));
        throw new Exception ($e->getResponse()->getReasonPhrase(),$e->getResponse()->getStatusCode());
    } catch (GuzzleException $e) {
        error_log(print_r("## EXCEPTION ## ucCalls (getMedia) - GuzzleException -> " . $e->getMessage(),true));
        throw new Exception ("Unhandled Exception",400);
    }

}
</code>```

}

SECOND TRY was to try using the Guzzle Stream

Function to call download function

```<code>$ucCall = new ucCalls($ucAuth);

try {

    $ucCall->getMedia($target);

} catch (Exception $e) {
    $result['ERROR']   = "1";
    $result['DETAILS'] = $e->getCode() . " - " . $e->getMessage();
    echo json_encode($result);
    exit();
}
</code>```

Class

```<code>public function getMedia(string $id)
{

    try {

        $temp_file = sys_get_temp_dir() . "\uc" . make_id(6) . ".mp3";
        $resource = Utils::tryFopen($temp_file, 'w+');
        $stream = Utils::streamFor($resource);

        $this->client->request('GET','fw/path/to/audio/file/store/' . $id . '/Media', ['sink' => $stream]);

        header("Cache-Control: no-cache");
        header("Content-Type: audio/mp3");
        header('Content-Disposition: attachment; filename="' . basename($stream->getMetadata('uri')) . '"');
        header('Content-Length: ' . filesize($stream->getMetadata('uri')));

        echo $stream;

    } catch (ConnectException $e) {
        error_log(print_r("## EXCEPTION ## ucCalls (getMedia) - ConnectException -> " . $e->getMessage(),true));
        throw new Exception ("Connection Error",500);
    } catch (ServerException|ClientException $e) {
        error_log(print_r("## EXCEPTION ## ucCalls (getMedia) - ServerException|ClientException -> " . $e->getMessage(),true));
        throw new Exception ($e->getResponse()->getReasonPhrase(),$e->getResponse()->getStatusCode());
    } catch (GuzzleException $e) {
        error_log(print_r("## EXCEPTION ## ucCalls (getMedia) - GuzzleException -> " . $e->getMessage(),true));
        throw new Exception ("Unhandled Exception",400);
    }
}
</code>```

Both these functions create the audio file in a temp store on my local web server, so the audio file retrieval from the 3rd party works.  This is where I get stumped...

The file appears to transfer to the client, the header attributes are recognised and the correct amount of data is transfer (filesize) - but the client browser (tested in Edge and Firefox) is not prompting to save the file.  Just getting an encoded string, as per the screenshots...

Any thoughts or guidance would be appreciated...

答:
Once you get the encoded response you can check it whether it is base64 encoded or not or use base64_encode($content) provided by php.

```<code>$encoded_response = 'your encoded string';
$base64 = base64_encode($encoded_response);
$mime = "audio/mpeg";
$img = ('data:' . $mime . ';base64,' . $base64); // would be like data:audio/mpeg;base64,YxAAEaAIEeUAQAgBgNg...
<audio autoplay controls src="data:audio/mpeg;base64,YxAAEaAIEeUAQAgBgNg...">
  The “audio” tag is not supported by your browser.
</audio>
</code>```

Title: File Download via API using Guzzle

Body:
I'm still on the learning slopes with Guzzle, but am stumped with this issue...

I'm trying to retrieve an audio file from a 3rd party API using Guzzle.  I've written a class with a number of functions and they all work apart from the very last stage of the 'download' function - the browser does not prompt to save the audio file

Call to get audio file, using AJAX

$callRows.on("click", ".download", function() {

    const $this = $(this);
    $this.parent().hide().next().show();

    $.ajax({
        type : "POST",
        url  : "submgmt",
        data : {
            task   : "getMedia",
            target : $this.data("id")
        },
        success  : function(data) {

            $this.parent().show().next().hide();

        },
        error : function (XMLHttpRequest, textStatus, errorThrown) {
            $dialog.attr("title", textStatus);
            $dialog.html("
" + errorThrown + "

Click OK to continue
");
            $dialog.dialog({
                buttons  : {
                    "OK" : function () {
                        $dialog.dialog("destroy");
                    }
                },
                dialogClass : "no-close",
                modal       : true,
                resizable   : false
            });
            $this.parent().show().next().hide();
        }
    });
});

FIRST TRY
Function to call download function

$ucCall = new ucCalls($ucAuth);

try {

    $response = $ucCall->getMedia($target);

    if ($response['code']===404) {
        $result['ERROR'] = "1";
        $result['DETAILS'] = "File is no longer available";
        echo json_encode($result);
        exit();
    } else {
        header("Date: " . $response['headers']['Date'][0]);
        header("Cache-Control: " . $response['headers']['Cache-Control'][0]);
        header("Pragma: " . $response['headers']['Pragma'][0]);
        header("Expires: " . $response['headers']['Expires'][0]);
        header("Content-Type: " . $response['headers']['Content-Type'][0]);
        header('Content-Disposition: attachment; filename="' . basename($response['filename']) . '"');
        header("Content-Length: " . filesize($response['filename']));
        ob_clean();
        flush();
        readfile($response['filename']);
        exit;
    }
} catch (Exception $e) {
    $result['ERROR']   = "1";
    $result['DETAILS'] = $e->getCode() . " - " . $e->getMessage();
    echo json_encode($result);
    exit();
}

Class to retrieve audio files from 3rd party API

class ucCalls {

private Client $client;

public function __construct($authString)
{
    $this->client = new Client([
        'base_uri' => 'https://url-of-host',
        'timeout'  => 5,
        'headers' => [
            'Authorization' => 'Basic ' . $authString,
            'Accept' => 'application/json'
        ],
    ]);
}

/**
 * Retrieves the unencrypted MP3 media for a (completed) recording
 * @param string $id
 * @return array
 * @throws Exception
 */
public function getMedia(string $id): array
{

    try {

        $temp_file = sys_get_temp_dir() . "\uc" . make_id(6) . ".mp3";
        $resource = Utils::tryFopen($temp_file, 'w');

        $response = $this->client->request('GET','fw/path/to/audio/file/store/' . $id . '/Media', ['sink' => $resource]);

        return [
            'code'     => $response->getStatusCode(),
            'headers'  => $response->getHeaders(),
            'filename' => $temp_file
        ];

    } catch (ConnectException $e) {
        error_log(print_r("## EXCEPTION ## ucCalls (getMedia) - ConnectException -> " . $e->getMessage(),true));
        throw new Exception ("Connection Error",500);
    } catch (ServerException|ClientException $e) {
        error_log(print_r("## EXCEPTION ## ucCalls (getMedia) - ServerException|ClientException -> " . $e->getMessage(),true));
        throw new Exception ($e->getResponse()->getReasonPhrase(),$e->getResponse()->getStatusCode());
    } catch (GuzzleException $e) {
        error_log(print_r("## EXCEPTION ## ucCalls (getMedia) - GuzzleException -> " . $e->getMessage(),true));
        throw new Exception ("Unhandled Exception",400);
    }

}

}

SECOND TRY was to try using the Guzzle Stream

Function to call download function

$ucCall = new ucCalls($ucAuth);

try {

    $ucCall->getMedia($target);

} catch (Exception $e) {
    $result['ERROR']   = "1";
    $result['DETAILS'] = $e->getCode() . " - " . $e->getMessage();
    echo json_encode($result);
    exit();
}

Class

public function getMedia(string $id)
{

    try {

        $temp_file = sys_get_temp_dir() . "\uc" . make_id(6) . ".mp3";
        $resource = Utils::tryFopen($temp_file, 'w+');
        $stream = Utils::streamFor($resource);

        $this->client->request('GET','fw/path/to/audio/file/store/' . $id . '/Media', ['sink' => $stream]);

        header("Cache-Control: no-cache");
        header("Content-Type: audio/mp3");
        header('Content-Disposition: attachment; filename="' . basename($stream->getMetadata('uri')) . '"');
        header('Content-Length: ' . filesize($stream->getMetadata('uri')));

        echo $stream;

    } catch (ConnectException $e) {
        error_log(print_r("## EXCEPTION ## ucCalls (getMedia) - ConnectException -> " . $e->getMessage(),true));
        throw new Exception ("Connection Error",500);
    } catch (ServerException|ClientException $e) {
        error_log(print_r("## EXCEPTION ## ucCalls (getMedia) - ServerException|ClientException -> " . $e->getMessage(),true));
        throw new Exception ($e->getResponse()->getReasonPhrase(),$e->getResponse()->getStatusCode());
    } catch (GuzzleException $e) {
        error_log(print_r("## EXCEPTION ## ucCalls (getMedia) - GuzzleException -> " . $e->getMessage(),true));
        throw new Exception ("Unhandled Exception",400);
    }
}

Both these functions create the audio file in a temp store on my local web server, so the audio file retrieval from the 3rd party works.  This is where I get stumped...

The file appears to transfer to the client, the header attributes are recognised and the correct amount of data is transfer (filesize) - but the client browser (tested in Edge and Firefox) is not prompting to save the file.  Just getting an encoded string, as per the screenshots...

Any thoughts or guidance would be appreciated...

Body:
Once you get the encoded response you can check it whether it is base64 encoded or not or use base64_encode($content) provided by php.

$encoded_response = 'your encoded string';
$base64 = base64_encode($encoded_response);
$mime = "audio/mpeg";
$img = ('data:' . $mime . ';base64,' . $base64); // would be like data:audio/mpeg;base64,YxAAEaAIEeUAQAgBgNg...
<audio autoplay controls src="data:audio/mpeg;base64,YxAAEaAIEeUAQAgBgNg...">
  The “audio” tag is not supported by your browser.
</audio>


问:
Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF
I have the below error when I execute the following script. What is the error about, and how it can be resolved?

```<code>Insert table(OperationID,OpDescription,FilterID)
values (20,'Hierachy Update',1)
</code>```

Error:

Server: Msg 544, Level 16, State 1, Line 1

Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF.

答: Put break point on your [HttpPost] method and check what value is being passed to Id property. If it is other than zero then this error will occur.</p>

OwnerDisplayName: Jaison

Body:
I have the below error when I execute the following script. What is the error about, and how it can be resolved?

Insert table(OperationID,OpDescription,FilterID)
values (20,'Hierachy Update',1)

Error:

Server: Msg 544, Level 16, State 1, Line 1

Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF.


问:
Jupyter kernel dies when importing pipeline function from transformers class on Mac OS
I'm unable to import pipeline function of transformers class as my jupyter kernel keeps dying. Tried on transformers-4.15.0 and 4.16.2. Anyone faced this issue?

I tried importing the class in a new notebook as you can see in the image and it keeps killing the kernel.

答:
It works fine for me.

You could try creating a fresh conda environment and reinstalling the app.

You could also try using jupyterlab instead of jupyter-notebook.

Are you on Mac OS? I couldn't get it to run at first using conda install transformers my jupyterlab kept hanging as well.

Then I did this, conda install -c huggingface transformers and here is the result.

It works fine for me on linux and Mac now.


问:
Calculating the 3 largest colums in excel and summing them
I am trying to calculate the total for the PT colums. I want it to calculate the top 3 PT colums and add them together. Excell noob so hoping someone can point me in the right direction. You can see my attempt in the screenshot below

答:
=SUM(LARGE(IF(B1:P1="PT",B2:P2),{1,2,3}))

which may or may not require committing with CTRL+SHIFT+ENTER, depending on your version of Excel.


问:
What's the Big-O-notation for this algorithm for printing the prime numbers?
I am trying to figure out the time complexity of the below problem.

```<code>import math
def prime(n):
    for i in range(2,n+1):
        for j in range(2, int(math.sqrt(i))+1):
            if i%j == 0:
                break
        else:
            print(i)

prime(36)
</code>```

This problem prints the prime numbers until 36.

My understanding of the above program:
for every n the inner loop runs for sqrt(n) times so on until n.

so the Big-o-Notation is O(n sqrt(n)).

Does my understanding is right? Please correct me if I am wrong...

答:
Time complexity measures the increase in number or steps (basic operations) as the input scales up:

```<code>O(1)     : constant (hash look-up)
O(log n) : logarithmic in base 2 (binary search)
O(n)     : linear (search for an element in unsorted list)
O(n^2)   : quadratic (bubble sort)
</code>```

To determine the exact complexity of an algorithm requires a lot of math and algorithms knowledge. You can find a detailed description of them here: time complexity

Also keep in mind that these values are considered for very large values of n, so as a rule of thumb, whenever you see nested for loops, think O(n^2).

You can add a steps counter inside your inner for loop and record its value for different values of n, then print the relation in a graph. Then you can compare your graph with the graphs of n, log n, n * sqrt(n) and n^2 to determine exactly where your algorithm is placed.

Body:
I am trying to figure out the time complexity of the below problem.

import math
def prime(n):
    for i in range(2,n+1):
        for j in range(2, int(math.sqrt(i))+1):
            if i%j == 0:
                break
        else:
            print(i)

prime(36)

This problem prints the prime numbers until 36.

My understanding of the above program:
for every n the inner loop runs for sqrt(n) times so on until n.

so the Big-o-Notation is O(n sqrt(n)).

Does my understanding is right? Please correct me if I am wrong...

Body:
Time complexity measures the increase in number or steps (basic operations) as the input scales up:

O(1)     : constant (hash look-up)
O(log n) : logarithmic in base 2 (binary search)
O(n)     : linear (search for an element in unsorted list)
O(n^2)   : quadratic (bubble sort)

To determine the exact complexity of an algorithm requires a lot of math and algorithms knowledge. You can find a detailed description of them here: time complexity

Also keep in mind that these values are considered for very large values of n, so as a rule of thumb, whenever you see nested for loops, think O(n^2).

You can add a steps counter inside your inner for loop and record its value for different values of n, then print the relation in a graph. Then you can compare your graph with the graphs of n, log n, n * sqrt(n) and n^2 to determine exactly where your algorithm is placed.


问:
how do I disable triggering of a Azure DevOps build pipeline every time it is saved?
Not only is the build pipeline I save triggered, but all my others are triggered as well every time I edit the YAML of any of my pipelines. How might I make this not happen?  It's inconvenient to have to manually stop all the running jobs that automatically are spawned by the saving of one of my many pipelines.

LATER ON: The "answer" below doesn't really answer the question.  What I discovered is that the pipleline YAML is actually stored in the repository with the code it works on, so any change to a pipeline triggers all the pipelines triggered by changes to the repo.  This is why ALL the pipelines then go into action. It's not what I want, but at least I understand it.  I'm putting this here for anyone who stumbles across this via a search.

答:
how do I disable triggering of a Azure DevOps build pipeline every time it is saved?

You can opt out of CI triggers entirely by specifying trigger: none.

Or you could set the specify trigger for each pipeline by filters, like: CI triggers, Batching CI runs, Paths:

Build Azure Repos Git or TFS Git repositories

Besides, you could also skipping CI for individual pushes by including [skip ci] in the message or description of any of the commits that are part of a push, and Azure Pipelines will skip running CI for this push. You can also use any of the following variations:

[skip ci] or [ci skip]

skip-checks: true or skip-checks:true

[skip azurepipelines] or [azurepipelines skip]

[skip azpipelines] or [azpipelines skip]

[skip azp] or [azp skip]

***NO_CI***


问:
Time complexity with a logarithmic recursive function
Could someone please explain the time complexity of the following bit of code:

def fn(n):
    if n==0:
       linear_time_fn(n) #some function that does work in O(n) time
    else:
       linear_time_fn(n)
       fn(n//5)
```

I was under the impression that the complexity of the code is O(nlogn) while the actual complexity is be O(n). How is this function different from one like merge sort which has an O(nlogn) complexity? Thanks.

答:
It's O(n) because n is smaller in each recursive level. So you have O(log n) calls to the function, but you don't do n units of work each time. The first call is O(n), the second call is O(n//5), the next call is O(n//5//5), and so on.

When you combine these, it's O(n).

Body:
Could someone please explain the time complexity of the following bit of code:

def fn(n):
    if n==0:
       linear_time_fn(n) #some function that does work in O(n) time
    else:
       linear_time_fn(n)
       fn(n//5)

I was under the impression that the complexity of the code is O(nlogn) while the actual complexity is be O(n). How is this function different from one like merge sort which has an O(nlogn) complexity? Thanks.


问:
Calculate the total occurences of a list values in pandas column
I want to calculate the numbers of occurrences of list values in a pandas column

```<code>lst = ['place','wait','ok','amazing','beautiful']
</code>```

ID
TEXT

1
beautiful place ,me

1
ok ,good work

2
wait for me ,ok

2
amazing place

3
amazing day

3
amazing country

3
amazing world

3
thank you

the output should be like

ID
OCCURENCES

1
2

1
1

2
2

2
2

3
1

3
1

3
1

3
0

my solution :

```<code>df['occurences'] =pd.DataFrame([df['text'].str.count(c) for c in list]).sum()
</code>```

答:
split the words and use a set intersection for efficiency:

```<code>lst = ['place','wait','ok','amazing','beautiful']
words = set(lst)

df['OCCURENCES'] = [len(words.intersection(x)) for x in df['TEXT'].str.split('\W+')]
</code>```

output:

```<code>   ID                  TEXT  OCCURENCES
0    1  beautiful place ,me           2
1    1        ok ,good work           1
2    2      wait for me ,ok           2
3    2        amazing place           2
4    3          amazing day           1
5    3      amazing country           1
6    3        amazing world           1
7    3            thank you           0
</code>```

Body:
I want to calculate the numbers of occurrences of list values in a pandas column

lst = ['place','wait','ok','amazing','beautiful']

ID
TEXT

1
beautiful place ,me

1
ok ,good work

2
wait for me ,ok

2
amazing place

3
amazing day

3
amazing country

3
amazing world

3
thank you

the output should be like

ID
OCCURENCES

1
2

1
1

2
2

2
2

3
1

3
1

3
1

3
0

my solution :

df['occurences'] =pd.DataFrame([df['text'].str.count(c) for c in list]).sum()

Body:
split the words and use a set intersection for efficiency:

lst = ['place','wait','ok','amazing','beautiful']
words = set(lst)

df['OCCURENCES'] = [len(words.intersection(x)) for x in df['TEXT'].str.split('\W+')]

output:

   ID                  TEXT  OCCURENCES
0    1  beautiful place ,me           2
1    1        ok ,good work           1
2    2      wait for me ,ok           2
3    2        amazing place           2
4    3          amazing day           1
5    3      amazing country           1
6    3        amazing world           1
7    3            thank you           0


问:
Algolia backend search with Algolia Search Helper library for Angular.js
I'm planning to send the search request to Algolia through the backend for a security issue.
I discovered here that Instantsearch supports this where you can specify your own customSearchClient, pass it as a parameter and it sends the request there.

Although Instansearch doesn't support Angular.js, I'm using the Algolia Search Helper library which comes with some helpers for Angular.js. I was wondering if this is possible there also.

In short I want to implement Algolia backend search with Angular.js without having to worry about building the search query.

This is how they instantiated the regular search client in their official example

'use strict';
// First let's define the usual configuration variables for our index
var applicationId = 'latency';
var apiKey = '249078a3d4337a8231f1665ec5a44966';
var index = 'bestbuy';
var client = algoliasearch(applicationId, apiKey);

// Define the `AgoliaSearchHelper` module
angular.module('AlgoliaSearchHelper', ['ngSanitize']).

// Expose the helper
factory('helper', function() {
  return algoliasearchHelper(client, index, {
    disjunctiveFacets: ['category'],
    hitsPerPage: 7,
    maxValuesPerFacet: 3
  });
}).
...
```

答:
In case anyone looking for this. It is possible to define a custom search client using Algolia Search Helper library as well. Github issue

You can create a custom search client in this manner and pass it to the factory

const customSearchClient = {
  search(requests, cb) {
    return fetch('https://algolia-backend-search.herokuapp.com/search', {
      method: 'post',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ requests }),
    }).then(function(res){return res.json()}).then(cb)
  }
};

var alSH = angular.module('AlgoliaSearchHelper', ['ngSanitize']);

// Expose the helper
alSH.factory('helper', function() {
  return algoliasearchHelper(customSearchClient, index, {
    disjunctiveFacets: ['category'],
    hitsPerPage: 7,
    maxValuesPerFacet: 3
  });
});

```

working demo for more understanding

If you want to work with Angular.js libraries such as $http and $q instead of the fetch API. It is also possible (make sure to remove the $scope.applys else will trigger a warning) - demo using $http and $q

If you want to return multiple Helpers from the same factory for querying different indices that is also possible - demo for multiple returns in factory

The search request will be sent to the backend and can be accessed within the request body. You can do relevant modifications to the request and to the results as well. That part is covered here. You can even add the index name from the backend if you want by setting an empty string for the index in the frontend and modifying the search request in backend (if you are concerned about exposing index name).

Body:
In case anyone looking for this. It is possible to define a custom search client using Algolia Search Helper library as well. Github issue

You can create a custom search client in this manner and pass it to the factory

const customSearchClient = {
  search(requests, cb) {
    return fetch('https://algolia-backend-search.herokuapp.com/search', {
      method: 'post',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ requests }),
    }).then(function(res){return res.json()}).then(cb)
  }
};

var alSH = angular.module('AlgoliaSearchHelper', ['ngSanitize']);

// Expose the helper
alSH.factory('helper', function() {
  return algoliasearchHelper(customSearchClient, index, {
    disjunctiveFacets: ['category'],
    hitsPerPage: 7,
    maxValuesPerFacet: 3
  });
});

working demo for more understanding

If you want to work with Angular.js libraries such as $http and $q instead of the fetch API. It is also possible (make sure to remove the $scope.applys else will trigger a warning) - demo using $http and $q

If you want to return multiple Helpers from the same factory for querying different indices that is also possible - demo for multiple returns in factory

The search request will be sent to the backend and can be accessed within the request body. You can do relevant modifications to the request and to the results as well. That part is covered here. You can even add the index name from the backend if you want by setting an empty string for the index in the frontend and modifying the search request in backend (if you are concerned about exposing index name).