问:
Why am I obtaining this exception trying to configure DB connection on a Spring Boot application? Error creating bean with name 'dataSource'
I am pretty new in Spring Boot and I have some problem trying to set the connection with a Maria DB.

I am working on a Spring Boot 1.5.9.RELEASE project, I see the version into the pom.xml file containing this information:

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
</code>```

Into the pom.xml file I set also these dependencies:

```<code><dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
  <groupId>org.mariadb.jdbc</groupId>
  <artifactId>mariadb-java-client</artifactId>
  <version>1.5.7</version>
</dependency>
</code>```

Then I have the application.yml file that should contains the database configuration. Following some tutorial I configured it in this way:

```<code>spring:
    application:
            name: Spring Boot Excel API
            datasource:
                platform: mariadb
                driverClassName: org.mariadb.jdbc.Driver
                url: mysql://localhost:3306/energydb
                username: root
                password: password
                timeBetweenEvictionRunsMillis: 1000
                testWhileIdle: true
                validationQuery: SELECT 1
debug: true
</code>```

The problem is that when I start my application by this command:

```<code>mvn spring-boot:run
</code>```

I obtain the following errors into the stacktrace:

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Cannot determine embedded database driver class for database type NONE

Action:

If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).

[WARNING]
java.lang.reflect.InvocationTargetException
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:567)
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run (AbstractRunMojo.java:527)
    at java.lang.Thread.run (Thread.java:830)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod (ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod (AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance (AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean (AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean (AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject (AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton (DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean (AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean (AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons (DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization (AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh (AbstractApplicationContext.java:543)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh (EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh (SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext (SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:303)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1118)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1107)
    at com.springboot.excelapi.Application.main (Application.java:12)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:567)
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run (AbstractRunMojo.java:527)
    at java.lang.Thread.run (Thread.java:830)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate (SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod (ConstructorResolver.java:588)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod (AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance (AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean (AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean (AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject (AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton (DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean (AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean (AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons (DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization (AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh (AbstractApplicationContext.java:543)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh (EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh (SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext (SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:303)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1118)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1107)
    at com.springboot.excelapi.Application.main (Application.java:12)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:567)
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run (AbstractRunMojo.java:527)
    at java.lang.Thread.run (Thread.java:830)
Caused by: org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
    at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.determineDriverClassName (DataSourceProperties.java:247)
    at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.initializeDataSourceBuilder (DataSourceProperties.java:184)
    at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.createDataSource (DataSourceConfiguration.java:42)
    at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat.dataSource (DataSourceConfiguration.java:56)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:567)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate (SimpleInstantiationStrategy.java:162)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod (ConstructorResolver.java:588)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod (AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance (AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean (AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean (AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject (AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton (DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean (AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean (AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons (DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization (AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh (AbstractApplicationContext.java:543)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh (EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh (SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext (SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:303)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1118)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1107)
    at com.springboot.excelapi.Application.main (Application.java:12)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:567)
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run (AbstractRunMojo.java:527)
    at java.lang.Thread.run (Thread.java:830)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  4.316 s
[INFO] Finished at: 2020-02-15T22:01:40+01:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.5.9.RELEASE:run (default-cli) on project excel-api: An exception occurred while running. null: InvocationTargetException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active). -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
</code>```

Why? What is wrong? What am I missing? How can I try to fix this issue?

答:
It seems your config file is not well formatted, I think you are looking for :</p>

```<code>spring:
  application:
    name: Spring Boot Excel API
  # note the datasource should be part of spring: not spring:application:
  datasource:
    driverClassName: org.mariadb.jdbc.Driver
    # it seems also that the url you are using is not correct, try this
    url: jdbc:mariadb://localhost:3306/energydb
    username: root
    password: password
    timeBetweenEvictionRunsMillis: 1000
    testWhileIdle: true
    validationQuery: SELECT 1
</code>```

Body:
I am pretty new in Spring Boot and I have some problem trying to set the connection with a Maria DB.

I am working on a Spring Boot 1.5.9.RELEASE project, I see the version into the pom.xml file containing this information:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath/>
</parent>

Into the pom.xml file I set also these dependencies:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
  <groupId>org.mariadb.jdbc</groupId>
  <artifactId>mariadb-java-client</artifactId>
  <version>1.5.7</version>
</dependency>

Then I have the application.yml file that should contains the database configuration. Following some tutorial I configured it in this way:

spring:
    application:
            name: Spring Boot Excel API
            datasource:
                platform: mariadb
                driverClassName: org.mariadb.jdbc.Driver
                url: mysql://localhost:3306/energydb
                username: root
                password: password
                timeBetweenEvictionRunsMillis: 1000
                testWhileIdle: true
                validationQuery: SELECT 1
debug: true

The problem is that when I start my application by this command:

mvn spring-boot:run

I obtain the following errors into the stacktrace:

***************************
APPLICATION FAILED TO START
***************************

Description:

Cannot determine embedded database driver class for database type NONE

Action:

If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).

[WARNING]
java.lang.reflect.InvocationTargetException
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:567)
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run (AbstractRunMojo.java:527)
    at java.lang.Thread.run (Thread.java:830)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod (ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod (AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance (AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean (AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean (AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject (AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton (DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean (AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean (AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons (DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization (AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh (AbstractApplicationContext.java:543)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh (EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh (SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext (SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:303)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1118)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1107)
    at com.springboot.excelapi.Application.main (Application.java:12)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:567)
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run (AbstractRunMojo.java:527)
    at java.lang.Thread.run (Thread.java:830)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate (SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod (ConstructorResolver.java:588)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod (AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance (AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean (AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean (AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject (AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton (DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean (AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean (AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons (DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization (AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh (AbstractApplicationContext.java:543)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh (EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh (SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext (SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:303)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1118)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1107)
    at com.springboot.excelapi.Application.main (Application.java:12)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:567)
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run (AbstractRunMojo.java:527)
    at java.lang.Thread.run (Thread.java:830)
Caused by: org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
    at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.determineDriverClassName (DataSourceProperties.java:247)
    at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.initializeDataSourceBuilder (DataSourceProperties.java:184)
    at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.createDataSource (DataSourceConfiguration.java:42)
    at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat.dataSource (DataSourceConfiguration.java:56)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:567)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate (SimpleInstantiationStrategy.java:162)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod (ConstructorResolver.java:588)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod (AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance (AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean (AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean (AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject (AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton (DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean (AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean (AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons (DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization (AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh (AbstractApplicationContext.java:543)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh (EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh (SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext (SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:303)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1118)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1107)
    at com.springboot.excelapi.Application.main (Application.java:12)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:567)
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run (AbstractRunMojo.java:527)
    at java.lang.Thread.run (Thread.java:830)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  4.316 s
[INFO] Finished at: 2020-02-15T22:01:40+01:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.5.9.RELEASE:run (default-cli) on project excel-api: An exception occurred while running. null: InvocationTargetException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active). -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

Why? What is wrong? What am I missing? How can I try to fix this issue?

Body:
It seems your config file is not well formatted, I think you are looking for :

spring:
  application:
    name: Spring Boot Excel API
  # note the datasource should be part of spring: not spring:application:
  datasource:
    driverClassName: org.mariadb.jdbc.Driver
    # it seems also that the url you are using is not correct, try this
    url: jdbc:mariadb://localhost:3306/energydb
    username: root
    password: password
    timeBetweenEvictionRunsMillis: 1000
    testWhileIdle: true
    validationQuery: SELECT 1


来源: stackexchange

问:
PHP foreach array and compare with GET
I'm trying to resolve my problem.

I store array in json file

I try to foreach array and compare it with my GET arguments

Problem was that only last of array filed works but other not.

auth.json

```<code>[{"License":"21X2-214X-SSDF-3215-SFFA","IP":"111111111","Note":"x1"},{"License":"S31S-SAF3-XF22-SLLT-341D","IP":"1111111","Note":"x2"}]
</code>```

PHP Code

```<code>$license = json_decode(file_get_contents('auth.json'), true);
foreach ($license as $cec) {

        if ($_GET["license"] == $cec["License"] AND $_GET["IP"] == $cec["IP"]){

            $user_auth = array(
            "user_info" => array(

                "auth" => 1
                ),
            );

        }else{
            $user_auth = array(
            "user_info" => array(

                "auth" => 0

                ),
            );
        }

    }
</code>```

答:
You can use in_array() function to check if a value exists in an array:

```<code>$json = '[{"License":"21X2-214X-SSDF-3215-SFFA","IP":"111111111","Note":"x1"},{"License":"S31S-SAF3-XF22-SLLT-341D","IP":"1111111","Note":"x2"}]';
$array = json_decode($json, true);
$test_data = array("21X2-214X-SSDF-3215-SFFA","111111111");//This is you test GET request
$test_data2 = array("S31S-SAF3-XF22-SLLT-341D", "1111111");//This is you test 2 GET request

foreach( $array as $cer){
    if(in_array($test_data[0], $cer) && in_array($test_data[1], $cer)){
        echo "Pair 1 exist";
    } else if (in_array($test_data2[0], $cer) && in_array($test_data2[1], $cer)){
        echo "Pair 2 exist";
    } else {
        echo "No match found";
    }
}
</code>```

Output:

```<code>Pair 1 exist
Pair 2 exist
</code>```

ContentLicense: CC BY-SA 4.0

Title: PHP foreach array and compare with GET

Body:
I'm trying to resolve my problem.

I store array in json file

I try to foreach array and compare it with my GET arguments

Problem was that only last of array filed works but other not.

auth.json

[{"License":"21X2-214X-SSDF-3215-SFFA","IP":"111111111","Note":"x1"},{"License":"S31S-SAF3-XF22-SLLT-341D","IP":"1111111","Note":"x2"}]

PHP Code

$license = json_decode(file_get_contents('auth.json'), true);
foreach ($license as $cec) {

        if ($_GET["license"] == $cec["License"] AND $_GET["IP"] == $cec["IP"]){

            $user_auth = array(
            "user_info" => array(

                "auth" => 1
                ),
            );

        }else{
            $user_auth = array(
            "user_info" => array(

                "auth" => 0

                ),
            );
        }

    }

Body:
You can use in_array() function to check if a value exists in an array:

$json = '[{"License":"21X2-214X-SSDF-3215-SFFA","IP":"111111111","Note":"x1"},{"License":"S31S-SAF3-XF22-SLLT-341D","IP":"1111111","Note":"x2"}]';
$array = json_decode($json, true);
$test_data = array("21X2-214X-SSDF-3215-SFFA","111111111");//This is you test GET request
$test_data2 = array("S31S-SAF3-XF22-SLLT-341D", "1111111");//This is you test 2 GET request

foreach( $array as $cer){
    if(in_array($test_data[0], $cer) && in_array($test_data[1], $cer)){
        echo "Pair 1 exist";
    } else if (in_array($test_data2[0], $cer) && in_array($test_data2[1], $cer)){
        echo "Pair 2 exist";
    } else {
        echo "No match found";
    }
}

Output:

Pair 1 exist
Pair 2 exist


问:
Why am I getting Typeerror super expression must either be null or a function?
So I just started learning React Native last week to try and learn to develop apps. I've been learning from a Udemy course and it has been going pretty well until I tried to create a new component. I've rewatched the lesson 3 times to try and find my mistake but I can't seem to see a difference between code. Please forgive my amateur mistake wherever it is. The main app.js file contains this:

```<code>import React from 'react';
import { StyleSheet, Text, View, Platform, Image, ImageBackground } from 'react-native';
import {Button} from 'native-base';
import Landing from './src/Landing'
import { render } from 'react-dom';

var myBackground = require('./assets/icons/landing.jpg');

export default class App extends React.Component() {
  render() {
  return (
    <View style={styles.container}>
      <Landing />
    </View>
  );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: Platform.OS === "android" ? 50 : 0
  },
});
</code>```

and my component code is this:

```<code>import React from 'react';
import {View, Text, Image, StyleSheet} from 'react-native';
import {Button} from 'native-base';

var myBackground = require('../assets/icons/landing.jpg');

class Landing extends React.Component {
    render() {
        return(
            <View>
                <ImageBackground style={ styles.imgBackground } source={myBackground}>
                    <View style={styles.viewStyle}>
                    <Text style={styles.titleStyle}>Welcome to PokeSearch</Text>
                    <Button block={true} style={styles.buttonStyle} onPress={()=>{}}>
                        <Text style={styles.buttonText}>Start Searching for Pokemon!</Text>
                    </Button>
                    </View>
                </ImageBackground>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
      flex: 1,
      marginTop: Platform.OS === "android" ? 50 : 0
    },
    imgBackground: {
      width: '100%',
      height: '100%',
      flex: 1
  },
  viewStyle: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: "center",
    alignItems: "center"
  },
  titleStyle: {
    fontSize: 30,
    color: 'red',
    alignItems: 'center',
  },
  buttonStyle: {
    margin: 10
  },
  buttonText: {
    color: 'red'
  },
  });

export default Landing;
</code>```

Any help would be greatly appreciated, I can't seem to find where I am going wrong...
Here is the full error in the emulator:

Thanks in advance!

答: change export default class App extends React.Component() to export default class App extends React.Component, you don't need parentheses in a class component.

Body:
So I just started learning React Native last week to try and learn to develop apps. I've been learning from a Udemy course and it has been going pretty well until I tried to create a new component. I've rewatched the lesson 3 times to try and find my mistake but I can't seem to see a difference between code. Please forgive my amateur mistake wherever it is. The main app.js file contains this:

import React from 'react';
import { StyleSheet, Text, View, Platform, Image, ImageBackground } from 'react-native';
import {Button} from 'native-base';
import Landing from './src/Landing'
import { render } from 'react-dom';

var myBackground = require('./assets/icons/landing.jpg');

export default class App extends React.Component() {
  render() {
  return (
    <View style={styles.container}>
      <Landing />
    </View>
  );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: Platform.OS === "android" ? 50 : 0
  },
});

and my component code is this:

import React from 'react';
import {View, Text, Image, StyleSheet} from 'react-native';
import {Button} from 'native-base';

var myBackground = require('../assets/icons/landing.jpg');

class Landing extends React.Component {
    render() {
        return(
            <View>
                <ImageBackground style={ styles.imgBackground } source={myBackground}>
                    <View style={styles.viewStyle}>
                    <Text style={styles.titleStyle}>Welcome to PokeSearch</Text>
                    <Button block={true} style={styles.buttonStyle} onPress={()=>{}}>
                        <Text style={styles.buttonText}>Start Searching for Pokemon!</Text>
                    </Button>
                    </View>
                </ImageBackground>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
      flex: 1,
      marginTop: Platform.OS === "android" ? 50 : 0
    },
    imgBackground: {
      width: '100%',
      height: '100%',
      flex: 1
  },
  viewStyle: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: "center",
    alignItems: "center"
  },
  titleStyle: {
    fontSize: 30,
    color: 'red',
    alignItems: 'center',
  },
  buttonStyle: {
    margin: 10
  },
  buttonText: {
    color: 'red'
  },
  });

export default Landing;

Any help would be greatly appreciated, I can't seem to find where I am going wrong...
Here is the full error in the emulator:

Thanks in advance!


问:
Android Studio with Kotlin gives "Unresolved reference" to plus sign in two lines but not in one
In Android Studio, programming in Kotlin, if you write:

```<code>val t = listOf("A","B") + listOf("C","D")
</code>```

everything is fine and dandy. However, if you write:

```<code>val t = listOf("A","B")
        + listOf("C","D")
</code>```

the IDE will report a "Unresolved reference" in the plus sign. The compiler also won't compile. Why is the line break meaningful in this case? Am I missing something?

答:
As shown here, you need to add parentheses or move your plus sign at the end of the first line for it to compile. Since kotlin doesn't use semi-colons, if the first line works as a valid statement, it won't connect the next line with it.

Here are your two options:

```<code>val t = (listOf("A","B")
    + listOf("C","D"))

val t = listOf("A","B") +
    listOf("C","D")
</code>```

By adding the parentheses or the plus sign at the end of the first line, you're telling the compiler that the statement isn't complete. Therefore, it is going to link the next line to the statement.

Body:
In Android Studio, programming in Kotlin, if you write:

val t = listOf("A","B") + listOf("C","D")

everything is fine and dandy. However, if you write:

val t = listOf("A","B")
        + listOf("C","D")

the IDE will report a "Unresolved reference" in the plus sign. The compiler also won't compile. Why is the line break meaningful in this case? Am I missing something?

Body:
As shown here, you need to add parentheses or move your plus sign at the end of the first line for it to compile. Since kotlin doesn't use semi-colons, if the first line works as a valid statement, it won't connect the next line with it.

Here are your two options:

val t = (listOf("A","B")
    + listOf("C","D"))

val t = listOf("A","B") +
    listOf("C","D")

By adding the parentheses or the plus sign at the end of the first line, you're telling the compiler that the statement isn't complete. Therefore, it is going to link the next line to the statement.


问:
Convert Java Map<Obj1, Collection<Obj2>> to Map<Obj2, Collection<Obj1>>
What would be a good practice to convert Map<Obj1, Collection<Obj2>> to Map<Obj2, Collection<Obj1>>?

I tried doing it with MultiMap.

```<code>    Map<Obj1, Collection<Obj2>> originalMap = ...;
    Multimap<Obj1, Obj2> multiMap = ArrayListMultimap.create();
    originalMap.forEach(multiMap::putAll);
    Map<Obj2, Collection<Obj1>> convertedMap = Multimaps.invertFrom(multiMap, ArrayListMultimap.create()).asMap();
</code>```

Is there a better way to do this?

答:
You can achieve the same with Java 8 Streams;

```<code>Map<Obj1, List<Obj2>> originalMap = ...

Map<Obj2, List<Obj1>> reversedMap = originalMap.entrySet().stream()
        .flatMap(obj2s -> obj2s.getValue().stream()
                .map(obj2 -> Map.entry(obj2, obj2s.getKey())))
        .collect(
                Collectors.groupingBy(
                        Map.Entry::getKey,
                        Collectors.mapping(Map.Entry::getValue, Collectors.toList())
                )
        );

</code>```

The fltMap coverts Map<Obj1, List<Obj2>> into a tuple like <Obj2, Obj1>, then collect the result grouping by Obj2.

Body:
What would be a good practice to convert Map<Obj1, Collection<Obj2>> to Map<Obj2, Collection<Obj1>>?

I tried doing it with MultiMap.

    Map<Obj1, Collection<Obj2>> originalMap = ...;
    Multimap<Obj1, Obj2> multiMap = ArrayListMultimap.create();
    originalMap.forEach(multiMap::putAll);
    Map<Obj2, Collection<Obj1>> convertedMap = Multimaps.invertFrom(multiMap, ArrayListMultimap.create()).asMap();

Is there a better way to do this?

Body:
You can achieve the same with Java 8 Streams;

Map<Obj1, List<Obj2>> originalMap = ...

Map<Obj2, List<Obj1>> reversedMap = originalMap.entrySet().stream()
        .flatMap(obj2s -> obj2s.getValue().stream()
                .map(obj2 -> Map.entry(obj2, obj2s.getKey())))
        .collect(
                Collectors.groupingBy(
                        Map.Entry::getKey,
                        Collectors.mapping(Map.Entry::getValue, Collectors.toList())
                )
        );

The fltMap coverts Map<Obj1, List<Obj2>> into a tuple like <Obj2, Obj1>, then collect the result grouping by Obj2.


问:
Oracle SQL select query compare 2 columns
I have a table with these two columns:

```<code>USERNAME    EMAIL_ADDRESS
------------------------------
username1   username1@abc.com
username2   username2@abc.com
username3   username3@abc.com
</code>```

The first column is the username and the second column is <username> with email domain along with it.

How can I compare the two columns using Oracle SQL to find if there are any rows where the email_address column doesn't have the correct corresponding username in the email address format?

答:
find if there are any rows where the email_address column doesn't have the correct corresponding username in the email address format?

Presumably, you want:

```<code>select t.*
from mytable t
where t.email_address not like t.username || '%'
</code>```

This will return all records for which the email_address does not start with username.

You can try and match on the entire user name with an expression like:

```<code>where t.email_address not like t.username || '@%'
</code>```

Body:
I have a table with these two columns:

USERNAME    EMAIL_ADDRESS
------------------------------
username1   username1@abc.com
username2   username2@abc.com
username3   username3@abc.com

The first column is the username and the second column is <username> with email domain along with it.

How can I compare the two columns using Oracle SQL to find if there are any rows where the email_address column doesn't have the correct corresponding username in the email address format?

Body:
find if there are any rows where the email_address column doesn't have the correct corresponding username in the email address format?

Presumably, you want:

select t.*
from mytable t
where t.email_address not like t.username || '%'

This will return all records for which the email_address does not start with username.

You can try and match on the entire user name with an expression like:

where t.email_address not like t.username || '@%'


问:
Applescript can't make <list> into type specifier -1700 error
Can anyone explain why the following piece of Applescript code returns an error:

```<code>tell application "Photos"
    set idList to {"v3xzjwPQT0y8a844gLHLHWg", "v3w3twPQT0y%%844gLgf4Wg"}
    set itemList to every media item in application "Photos" where its id is in idList
    log (count of itemList)
end tell
</code>```

The error is:

```<code>error "Photos got an error: Can’t make {\"v3xzjwPQT0y8a844gLHLHWg\", \"v3w3twPQT0y%%844gLgf4Wg\"} into type specifier." number -1700 from {"v3xzjwPQT0y8a844gLHLHWg", "v3w3twPQT0y%%844gLgf4Wg"} to specifier
</code>```

答:
I have the same issue. My goal is to get all images that are not in a certain album.
The error rises in the line

```<code>set itemList to every media item in application "Photos" where its id is in idList
</code>```

Also this one-liner results in an error

```<code>set itemList to every media item in application "Photos" where its name is in {"bla"}
</code>```

What works is the following line

```<code>set itemList to every media item in application "Photos" where its name is "bla"
</code>```

But that does not solve the problem. Maybe someone has a suggestion how to do it.

ContentLicense: CC BY-SA 3.0

Body:
Can anyone explain why the following piece of Applescript code returns an error:

tell application "Photos"
    set idList to {"v3xzjwPQT0y8a844gLHLHWg", "v3w3twPQT0y%%844gLgf4Wg"}
    set itemList to every media item in application "Photos" where its id is in idList
    log (count of itemList)
end tell

The error is:

error "Photos got an error: Can’t make {\"v3xzjwPQT0y8a844gLHLHWg\", \"v3w3twPQT0y%%844gLgf4Wg\"} into type specifier." number -1700 from {"v3xzjwPQT0y8a844gLHLHWg", "v3w3twPQT0y%%844gLgf4Wg"} to specifier

Body:
I have the same issue. My goal is to get all images that are not in a certain album.
The error rises in the line

set itemList to every media item in application "Photos" where its id is in idList

Also this one-liner results in an error

set itemList to every media item in application "Photos" where its name is in {"bla"}

What works is the following line

set itemList to every media item in application "Photos" where its name is "bla"

But that does not solve the problem. Maybe someone has a suggestion how to do it.


问:
Equivalent LINQ to SQL query
Can anyone help me with the equivalent LINQ query for the SQL below?
I am new to LINQ

```<code>Select * From Students_History SH
Where SH.Active = 1 and SH.ModifiedAt in (
select MAX(SH1.ModifiedAt)from Students_History SH1
group by SH1.StudentId)
</code>```

This is what I have tried

```<code>var q =
    from h in Students_History
    where h.Active=1
    group h by h.StudentId into g
    select new
    {
        StudentID = g.Key,
        LatestModified = g.Max (x => x.ModifiedAt)
    }
</code>```

This linq query does not give me the right result and somehow the active=1  is ignored

I have about dozen fields in my Students_History table and I want all those fields not just studentId and ModifiedAt.

答: You need to compare using the == operator.

Title: Equivalent LINQ to SQL query

Body:
Can anyone help me with the equivalent LINQ query for the SQL below?
I am new to LINQ

Select * From Students_History SH
Where SH.Active = 1 and SH.ModifiedAt in (
select MAX(SH1.ModifiedAt)from Students_History SH1
group by SH1.StudentId)

This is what I have tried

var q =
    from h in Students_History
    where h.Active=1
    group h by h.StudentId into g
    select new
    {
        StudentID = g.Key,
        LatestModified = g.Max (x => x.ModifiedAt)
    }

This linq query does not give me the right result and somehow the active=1  is ignored

I have about dozen fields in my Students_History table and I want all those fields not just studentId and ModifiedAt.


问:
Javascript: Creating Multiple Li Items with Button Onclick Function
I am trying to create an application to display a certain number of list items based on the number input (i.e 3 = 3 list items). So far I have only been able to create a function that displays one list item with the onClick function. No matter what code I use, I cannot find a way to create multiple list items from one button click. Here is my current code, HTML:

```<code><html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
   <section>
       <header>Week 5 Assignment</header>
       <section>
           <label>Name: <input type="text" id="nameInput" value="Enter a Name"></label>
       </section>
    <section>
        <label>Num of Times: <input type="number" id="numInput" value="Enter Number"></label>
        <section>
           <ol id="nameOutput"></ol>
           <hr>
          <button onclick="displayName();">Display Name!</button>
          <button>Reset</button>
       </section>
    </section>
   </section>

    <script src="script.js"></script>
</body>
</html>
</code>```

And my JS:

```<code>    var name = document.getElementById("nameInput").value;
    console.log(name);

    var num = document.getElementById("numInput").value;

    var list = document.getElementById("nameOutput");

    var item = document.createElement("li");

    item.innerText = name;
    list.append(item);
}
</code>```

答:
Javascript For loop should work for what you are trying to achieve

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>

           Week 5 Assignment

               Name: <input type="text" id="nameInput" value="Enter a Name">

            Num of Times: <input type="number" id="numInput" value="Enter Number">

              <button onclick="displayName();">Display Name!</button>
              <button>Reset</button>

    ```

Body:
I am trying to create an application to display a certain number of list items based on the number input (i.e 3 = 3 list items). So far I have only been able to create a function that displays one list item with the onClick function. No matter what code I use, I cannot find a way to create multiple list items from one button click. Here is my current code, HTML:

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

       Week 5 Assignment

           Name: <input type="text" id="nameInput" value="Enter a Name">

        Num of Times: <input type="number" id="numInput" value="Enter Number">

          <button onclick="displayName();">Display Name!</button>
          <button>Reset</button>

And my JS:

    var name = document.getElementById("nameInput").value;
    console.log(name);

    var num = document.getElementById("numInput").value;

    var list = document.getElementById("nameOutput");

    var item = document.createElement("li");

    item.innerText = name;
    list.append(item);
}

Body:
Javascript For loop should work for what you are trying to achieve

  <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
       <section>
           <header>Week 5 Assignment</header>
           <section>
               <label>Name: <input type="text" id="nameInput" value="Enter a Name"></label>
           </section>
        <section>
            <label>Num of Times: <input type="number" id="numInput" value="Enter Number"></label>
            <section>
               <ol id="nameOutput"></ol>
               <hr>
              <button onclick="displayName();">Display Name!</button>
              <button>Reset</button>
           </section>
        </section>
       </section>

        <script src="script.js"></script>
    </body>
    </html>
    <script>
    function displayName() {
        var name = document.getElementById("nameInput").value;

        var num = document.getElementById("numInput").value;

        var item = document.createElement("li");

        item.innerText = name;

        document.getElementById("nameOutput").innerHTML = '';

        for (i = 0; i < num; i++) {
        document.getElementById("nameOutput").innerHTML += '<li>'+name+'</li>';
        }

    }
    </script>


问:
im having trouble with git push ive t
```<code>stizz@Stizzys-Mac code % cd homework
stizz@Stizzys-Mac homework % cd work-day-scheduler
stizz@Stizzys-Mac work-day-scheduler % git status
On branch master
Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    deleted:    Work-Day-Schedule
    modified:   script.js

no changes added to commit (use "git add" and/or "git commit -a")
stizz@Stizzys-Mac work-day-scheduler % git add .
stizz@Stizzys-Mac work-day-scheduler % git commit -m "script.js update"
[master eba02ca] script.js update
 2 files changed, 2 deletions(-)
 delete mode 160000 Work-Day-Schedule
stizz@Stizzys-Mac work-day-scheduler % git push
fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin master

stizz@Stizzys-Mac work-day-scheduler %
</code>```

答:
```<code>% git push
fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin master
</code>```

Git told you what to do to fix the problem, but let's go over what that means.

git push needs to know which remote to push it to and what branch on that remote to push it to. The remote is usually origin and in this case you want to push to its master branch. Spelling it out explicitly is git push origin master.

But a branch can have an "upstream branch" meaning it already knows where to push to. Then you can git push and Git knows where to push to. git push --set-upstream origin master pushes your branch to the master branch on origin and remembers that for the future. From then onward you can git push and it will go to origin's master branch.

You can also do this without pushing: git branch -u origin master.

Title: im having trouble with git push ive t

Body:
% git push
fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin master

Git told you what to do to fix the problem, but let's go over what that means.

git push needs to know which remote to push it to and what branch on that remote to push it to. The remote is usually origin and in this case you want to push to its master branch. Spelling it out explicitly is git push origin master.

But a branch can have an "upstream branch" meaning it already knows where to push to. Then you can git push and Git knows where to push to. git push --set-upstream origin master pushes your branch to the master branch on origin and remembers that for the future. From then onward you can git push and it will go to origin's master branch.

You can also do this without pushing: git branch -u origin master.


问:
HttpClient not returning data
I have the following scenario:

api.service.ts

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

const baseUrl: string = 'https://example.com/api/v1';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private http: HttpClient) { }

  getSingleUser(mail: string) {
    console.log('Getting info from:');
    var url: string = baseUrl + '/users/' + mail;
    console.log(url);
    return this.http.get(url);
  }
}
</code>```

login.component.ts

```<code>import { Component, OnInit } from "@angular/core";
import { Router } from "@angular/router";
import { ApiService } from 'app/api.service';

@Component({
  selector: "login-cmp",
  moduleId: module.id,
  templateUrl: "login.component.html"
})
export class LoginComponent implements OnInit {
  private userProfile: any = [];
  private email: string = 'mail@example.com';

  constructor(private router: Router,
              private apiService: ApiService) {}

  ngOnInit() { }

  signIn(provider: String): void {
        console.log('Starting http for ' + this.email);

        this.apiService.getSingleUser(this.email)
          .subscribe(data => {
            console.log('entered subscribe');
            console.log(data);
          });
        console.log('Finished getting data.');
      }
    });
  }
}
</code>```

And this is the output on my console:

```<code>Starting http for mail@example.com
Getting info from:
https://example.com/api/v1/users/mail@example.com
Finished getting data.
</code>```

What I can see in the log is that the method getSingleUser is being called (messages 2 and 3 are generated by the method), but the commands inside the subscribe block are not being executed and I do not understand why.

答:
It's likely your HTTP request is returning an error, and in your subscribe you are not specifying what to do when you get an error response.

Try changing this:

```<code>this.apiService.getSingleUser(this.email)
    .subscribe(data => {
        console.log('entered subscribe');
        console.log(data);
    });
</code>```

To this:

```<code>this.apiService.getSingleUser(this.email)
    .subscribe(
        data => {
            console.log('entered subscribe');
            console.log(data);
        },
        error => {
            console.log('received an error', error);
        },
    );
</code>```

As a rule of thumb, always do something with error responses from promises/observables, even if that's just printing them to the browser's console as that will help you find issues easier.

Also, check the "DevTools" of your browser (Network tab) you'll see the GET response is going out, and it's ending with an error.

Title: HttpClient not returning data

Body:
I have the following scenario:

api.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

const baseUrl: string = 'https://example.com/api/v1';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private http: HttpClient) { }

  getSingleUser(mail: string) {
    console.log('Getting info from:');
    var url: string = baseUrl + '/users/' + mail;
    console.log(url);
    return this.http.get(url);
  }
}

login.component.ts

import { Component, OnInit } from "@angular/core";
import { Router } from "@angular/router";
import { ApiService } from 'app/api.service';

@Component({
  selector: "login-cmp",
  moduleId: module.id,
  templateUrl: "login.component.html"
})
export class LoginComponent implements OnInit {
  private userProfile: any = [];
  private email: string = 'mail@example.com';

  constructor(private router: Router,
              private apiService: ApiService) {}

  ngOnInit() { }

  signIn(provider: String): void {
        console.log('Starting http for ' + this.email);

        this.apiService.getSingleUser(this.email)
          .subscribe(data => {
            console.log('entered subscribe');
            console.log(data);
          });
        console.log('Finished getting data.');
      }
    });
  }
}

And this is the output on my console:

Starting http for mail@example.com
Getting info from:
https://example.com/api/v1/users/mail@example.com
Finished getting data.

What I can see in the log is that the method getSingleUser is being called (messages 2 and 3 are generated by the method), but the commands inside the subscribe block are not being executed and I do not understand why.

Body:
It's likely your HTTP request is returning an error, and in your subscribe you are not specifying what to do when you get an error response.

Try changing this:

this.apiService.getSingleUser(this.email)
    .subscribe(data => {
        console.log('entered subscribe');
        console.log(data);
    });

To this:

this.apiService.getSingleUser(this.email)
    .subscribe(
        data => {
            console.log('entered subscribe');
            console.log(data);
        },
        error => {
            console.log('received an error', error);
        },
    );

As a rule of thumb, always do something with error responses from promises/observables, even if that's just printing them to the browser's console as that will help you find issues easier.

Also, check the "DevTools" of your browser (Network tab) you'll see the GET response is going out, and it's ending with an error.


问:
Matlab - ODE Function - Integrating myself vs ode45 Function
I am confused as to what the matlab ODE function does. If i have the system dynamics, why can't i just manually integrate it myself and get the result. What exactly is the purpose of the ode45 function?</p>

答:
Quoting the official docs:

All MATLAB® ODE solvers can solve systems of equations of the form
  y′=f(t,y), or problems that involve a mass matrix, M(t,y)y′=f(t,y).
  The solvers all use similar syntaxes.

The ode23s solver only can solve
  problems with a mass matrix if the mass matrix is constant.

ode15s and
  ode23t can solve problems with a mass matrix that is singular, known
  as differential-algebraic equations (DAEs). Specify the mass matrix
  using the Mass option of odeset.

ode45 is a versatile ODE solver and is the first solver you should try
  for most problems. However, if the problem is stiff or requires high
  accuracy, then there are other ODE solvers that might be better suited
  to the problem. See Choose an ODE Solver for more information.

https://www.mathworks.com/help/matlab/ref/ode45.html


问:
AppleScript to launch and loop a video full screen avoiding menu bar
I'm trying to run this applescript:

```<code>tell application "QuickTime Player"
    activate
    open alias "Users:ebowen:Desktop:MOUND_1.32GB_h264.mov"
    play the front document
end tell
tell application "System Events" to tell process "QuickTime Player"
    set frontmost to true
    tell menu bar item 5 of menu bar 1
        click menu item "Enter Full Screen" of menu 1
        click menu item "Loop" of menu 1
    end tell
end tell
</code>```

on a mac mini running OSX 10.6.8 and it works except if it runs automatically when starting up.

When running from start-up, the mac's mouse pointer defaults to positioning itself over the apple menu and this leaves the menu bar still visible over the full-screen mov

I need to avoid all that and have it play full-screen with no menu bar automatically. Any pointers?
Thanks

答:
You can try this, although I haven't gone to the effort of restarting my computer and seeing if it solves the specific issue.</p>

```<code>tell application "QuickTime Player"
    tell (open POSIX file "/Users/ebowen/Desktop/MOUND_1.32GB_h264.mov")
        set looping to true
        present
        play
    end tell
end tell
</code>```

Body:
I'm trying to run this applescript:

tell application "QuickTime Player"
    activate
    open alias "Users:ebowen:Desktop:MOUND_1.32GB_h264.mov"
    play the front document
end tell
tell application "System Events" to tell process "QuickTime Player"
    set frontmost to true
    tell menu bar item 5 of menu bar 1
        click menu item "Enter Full Screen" of menu 1
        click menu item "Loop" of menu 1
    end tell
end tell

on a mac mini running OSX 10.6.8 and it works except if it runs automatically when starting up.

When running from start-up, the mac's mouse pointer defaults to positioning itself over the apple menu and this leaves the menu bar still visible over the full-screen mov

I need to avoid all that and have it play full-screen with no menu bar automatically. Any pointers?
Thanks

Body:
You can try this, although I haven't gone to the effort of restarting my computer and seeing if it solves the specific issue.

tell application "QuickTime Player"
    tell (open POSIX file "/Users/ebowen/Desktop/MOUND_1.32GB_h264.mov")
        set looping to true
        present
        play
    end tell
end tell


问:
Version control for binaries with timestamps
I need a version control system that works like Subversion but is able to keep the 'modified' timestamp (date) of each file.

We need to version our setup projects. In this case it is imporatant that the input files (dll/exe's) keep their timestamp.

What is the best tool to do this? (OS: Windows)

Updated:

Here's an example of what I would like it to do:

put "foo.dll" (modified 1/1/2009) and "bar.dll" (modified 2/2/2009) into the working directory

create/test the setup and do a single commit

when another developer checks out the project both foo.dll and bar.dll should have their orginal modified date (1/1/2009 and 2/2/2009)

Our current workaround is to zip each dll (the modified date is kept in the zip) but I would prefer something easier.

答: Subversion has use-commit-times option which makes local copy use timestamps of last commit time of every file. Also svn export always sets last commit time.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Tometzky


问:
How to sum the result at the end of table row in react table
[![enter image description here][1]][1]

I have a table that shows employee wages detail with values from API multiply by some constant values to get the total wages for each employee.I want to achieve the following; I want to sum the total wages of all the employees as it is and show the result. I have tried using map method and reduce, but I guess I wasn't using it well because it didn't work

I have taken off part of the code to show the action part

```<code>

  renderTable() {

    var totalCount = 0;
    var shownCount = 0;
    var lowerBound = 0;
    var upperBound = 0;
    var filtered = [];

    filtered = this.state.data.map( (row, i,) => {
      const calWage=row.numberofPresentAttendances * row.wages* 8;
   const calWageOvertime = row.numberofPresentAttendances * [row.wages*8]+row.wages*1.5*row.overtime;

      if(row.department.toLowerCase().indexOf(this.state.departmentFilter) > -1){
        return (
          <tr key={"employeeData"+i}>
            <td>{i+1}</td>

            <td>{row.name}</td>
            <td>{row.numberofPresentAttendances}</td>
            <td>{row.department}</td>
            <td>{row.wages}</td>
            <td>
            <Link to={"/employee/overtime/"+row._id}>
                <Button className="btn btn-light"><Overtime/></Button>
              </Link>

            </td>
            <td>{row.overtime}</td>
            <td>
              {row.overtime<1?calWage
            : calWageOvertime}

            </td>

          </tr>
        );
      } else {
        return undefined;
      }

````

Any assistance would be appreciated.

  [1]: https://i.stack.imgur.com/Tgnj5.jpg
```

答:
Add this code after generating filtered and before returning it. First we need to do a sum on all the wages, then we add a new row to the table, only with the total fields.

```<code>const totalWages = this.state.data.map((row) => row.wages).reduce((a, b) => a + b, 0);
filtered.push(
    <tr className="totalRow">
        <td></td>
        <td></td>
        ... // go to the wage td
        <td>{totalWages}</td>
        ...
    </tr>
);
</code>```

Body:
[![enter image description here][1]][1]

I have a table that shows employee wages detail with values from API multiply by some constant values to get the total wages for each employee.I want to achieve the following; I want to sum the total wages of all the employees as it is and show the result. I have tried using map method and reduce, but I guess I wasn't using it well because it didn't work

I have taken off part of the code to show the action part

  renderTable() {

    var totalCount = 0;
    var shownCount = 0;
    var lowerBound = 0;
    var upperBound = 0;
    var filtered = [];

    filtered = this.state.data.map( (row, i,) => {
      const calWage=row.numberofPresentAttendances * row.wages* 8;
   const calWageOvertime = row.numberofPresentAttendances * [row.wages*8]+row.wages*1.5*row.overtime;

      if(row.department.toLowerCase().indexOf(this.state.departmentFilter) > -1){
        return (

            {i+1}

            {row.name}
            {row.numberofPresentAttendances}
            {row.department}
            {row.wages}

            <Link to={"/employee/overtime/"+row._id}>
                <Button className="btn btn-light"><Overtime/></Button>
              </Link>

            {row.overtime}

              {row.overtime<1?calWage
            : calWageOvertime}

        );
      } else {
        return undefined;
      }

````

Any assistance would be appreciated.

  [1]: https://i.stack.imgur.com/Tgnj5.jpg

Body:
Add this code after generating filtered and before returning it. First we need to do a sum on all the wages, then we add a new row to the table, only with the total fields.

const totalWages = this.state.data.map((row) => row.wages).reduce((a, b) => a + b, 0);
filtered.push(
    <tr className="totalRow">
        <td></td>
        <td></td>
        ... // go to the wage td
        <td>{totalWages}</td>
        ...
    </tr>
);


问:
How to prompt the user that they already made an election in this condition
At the end of this code, I'm trying to prevent the user from inputting another entry for menuID 2. I need to prompt that they've already made an election and then redisplay my table.

I'm aware my else statement is incorrect.

```<code>menuID = -1
totalPrice = 0
while (menuID != 0)
  puts ("Menu ID \tMenu Item")
  puts ("-------\t\t----------")
  puts ("1\t\tAdd Item Charge")
  puts ("2\t\tAdd Labor Charge")
  puts ("3\t\tApply Discount")
  puts ("4\t\tApply Gift Card")
  puts ("5\t\tTotal")
  puts ("9\t\tNew Transaction")
  puts ("0\t\tExit Application")

  print ("Enter Menu ID: ")
  menuID = gets().to_i()
  if (menuID == 1)
    print ("Enter item's charge amount: $")
    chargeAmount = gets().to_f()
    chargeAmount = chargeAmount.round(2)
    totalPrice += chargeAmount
    if (chargeAmount <= 0)
      puts ("Item charge amount must be greater than 0. You entered $#{chargeAmount}")
    end

  elsif (menuID == 2)
    print ("Enter labor charge amount: $")
    laborCharge = gets().to_f()
    laborCharge = laborCharge.round(2)
    if (laborCharge <= 0)
      puts ("Labor charge amount must be greater than 0. You entered $#{laborCharge}")
    else
      puts ("Labor charge has already been applied")
    end
  end

end
</code>```

答:
You might want to maintain an array of menu_items and fill out the menuID for them every time they start entering a new item.

Remember that array items are 0-indexed, so you will want set menu_items[0] equal to the menu item with menuID 1, and menu_items[1] equal to the menu item with menuID 2, and so on.

Body:
At the end of this code, I'm trying to prevent the user from inputting another entry for menuID 2. I need to prompt that they've already made an election and then redisplay my table.

I'm aware my else statement is incorrect.

menuID = -1
totalPrice = 0
while (menuID != 0)
  puts ("Menu ID \tMenu Item")
  puts ("-------\t\t----------")
  puts ("1\t\tAdd Item Charge")
  puts ("2\t\tAdd Labor Charge")
  puts ("3\t\tApply Discount")
  puts ("4\t\tApply Gift Card")
  puts ("5\t\tTotal")
  puts ("9\t\tNew Transaction")
  puts ("0\t\tExit Application")

  print ("Enter Menu ID: ")
  menuID = gets().to_i()
  if (menuID == 1)
    print ("Enter item's charge amount: $")
    chargeAmount = gets().to_f()
    chargeAmount = chargeAmount.round(2)
    totalPrice += chargeAmount
    if (chargeAmount <= 0)
      puts ("Item charge amount must be greater than 0. You entered $#{chargeAmount}")
    end

  elsif (menuID == 2)
    print ("Enter labor charge amount: $")
    laborCharge = gets().to_f()
    laborCharge = laborCharge.round(2)
    if (laborCharge <= 0)
      puts ("Labor charge amount must be greater than 0. You entered $#{laborCharge}")
    else
      puts ("Labor charge has already been applied")
    end
  end

end


问:
Attempted import error: 'react-table' does not contain a default export (imported as 'ReactTable')
React Table Import error

Code import style below :

```<code>import ReactTable from 'react-table'
import 'react-table/react-table.css'
</code>```

While its running, its showing error message like this

Attempted import error: 'react-table' does not contain a default export (imported as 'ReactTable').

What to do now?

答:
The new version of react-table supports/uses hooks. to import react-table like import ReactTable from 'react-table' use react-table-6 which is react-table version 6.11.0

Install

```<code># Yarn
$ yarn add react-table-v6

# NPM
$ npm install react-table-v6
</code>```

Import

```<code>// ES6
import ReactTable from 'react-table-v6'
// ES5
var ReactTable = require('react-table-v6').default
</code>```

or use the latest version which is 7.0.0-rc.15

```<code>import {
 useTable,
 useGroupBy,
 useFilters,
 useSortBy,
 useExpanded,
 usePagination,

} from 'react-table'
</code>```

Body:
React Table Import error

Code import style below :

import ReactTable from 'react-table'
import 'react-table/react-table.css'

While its running, its showing error message like this

Attempted import error: 'react-table' does not contain a default export (imported as 'ReactTable').

What to do now?

Body:
The new version of react-table supports/uses hooks. to import react-table like import ReactTable from 'react-table' use react-table-6 which is react-table version 6.11.0

Install

# Yarn
$ yarn add react-table-v6

# NPM
$ npm install react-table-v6

Import

// ES6
import ReactTable from 'react-table-v6'
// ES5
var ReactTable = require('react-table-v6').default

or use the latest version which is 7.0.0-rc.15

import {
 useTable,
 useGroupBy,
 useFilters,
 useSortBy,
 useExpanded,
 usePagination,

} from 'react-table'


问:
How to use the "how" function for an unbalanced repeated design
I have a set of control and treated plots which had been sampled during years. I run the prc function in the vegan package and want to perform a permutation test to check whether control vs treated plots significantly differ during years. As my data is unbalanced, I can not use strata function. my code look like:

```<code>library(vegan)
year=as.factor(c(rep(1995,8),rep(1999,8),rep(2001,8),rep(2013,4),rep(1995,4),
       rep(1999,4),rep(2001,4),rep(2013,4)))
treatment=as.factor(c(rep("control",28),rep("treated",16)))
</code>```

I've written this, but I'm sure that it is wrong because the treatment is missing here:

```<code>h1 <- how(within = Within(type = "series", mirror = F),
          blocks = year, nperm = 999
)
</code>```

Any suggestions is greatly appreciated.

答:
Under the null hypothesis, samples from the control or treated groups are exchangeable and hence you don't want them in the permutation design; you really want to permute them to generate the permutation-based null distribution for the test statistic.

The permutation design is there to indicate what isn't exchangeable.

You haven't explained why you want samples within the blocks to be permuted in series; why are samples within years also time series? If they're not, you don't want this.

You only need to worry about imbalance if you want to permute the strata. Whilst using blocks is similar in some respects to strata, blocks are never permuted so if you can use blocks you can use strata as you won't be permuting them.

If you want to permute the years as groups of samples, then you'll need strata and you'll need balance at the year level, which you don't have.

What you have defined with your call to how() is:

groups samples by year and as such samples will never be swapped between years, and

samples within the levels of year will be permuted in series, keeping their temporal order intact after applying cyclic shift permutations.

If that's not what you want to do, you need to explain in words what you want to do. By "do" I mean what is it you want to test? What is your model in vegan?

Body:
I have a set of control and treated plots which had been sampled during years. I run the prc function in the vegan package and want to perform a permutation test to check whether control vs treated plots significantly differ during years. As my data is unbalanced, I can not use strata function. my code look like:

library(vegan)
year=as.factor(c(rep(1995,8),rep(1999,8),rep(2001,8),rep(2013,4),rep(1995,4),
       rep(1999,4),rep(2001,4),rep(2013,4)))
treatment=as.factor(c(rep("control",28),rep("treated",16)))

I've written this, but I'm sure that it is wrong because the treatment is missing here:

h1 <- how(within = Within(type = "series", mirror = F),
          blocks = year, nperm = 999
)

Any suggestions is greatly appreciated.


问:
Refactoring PL/SQL: many cursors with same rowtype (in theory)
I am writing some PL/SQL and found myself falling into a repeptitive pattern:

```<code>cursor c_curs1 is
   select a, b, c
   from (...) big_subquery_1
   where big_subquery_1.a_ind = 'Y'

cursor c_curs2 is
   select a, b, c
   from (...) big_subquery_2
   where big_subquery_2.b_ind = 'R'

cursor c_curs3 is
   select a, b, c
   from (...) big_subquery_3
   where big_subquery_3.c_ind = 'M'

...
type t_curs1_tab is table of c_curs1;
type t_curs2_tab is table of c_curs2;
type t_curs3_tab is table of c_curs3;
...
v_curs1_results t_curs1_tab := t_curs1_tab();
v_curs2_results t_curs2_tab := t_curs2_tab();
v_curs3_results t_curs3_tab := t_curs3_tab();
</code>```

Then when processing the results, I have code like this:

```<code>    open c_curs1;
    fetch c_curs1 bulk collect into v_curs1_results;
    close c_curs1;

    if v_curs1_results.first is not null and v_curs1_results.last is not null then
       for i in v_curs1_results.first .. v_curs1_results.last loop
           /*Do something with field a in the results
             Do something with field b in the results
             Do something with field c in the results*/
           ....
       end loop;
    end if;
</code>```

The code in the processing loop is the same for all cursors, as all 3 cursors return a,b,c - the only difference being which cursor is referenced. I wanted to refactor this into some sort of generic result-set processor, but I'm stuck here:

```<code>procedure sp_process_collection(in_collection t_curs1_tab) is ...
</code>```

I can only call this with v_curs1_results, I can't call it with v_curs2_results or I get a PLS-00306 wrong number of types or arguments... compiler error. Is there any way to do this generically so I only have to write one collection processing procedure? I have this pattern of cursor (returning the same three columns, always the same types) appears in several other parts of the same package, and the processing loop, while semantically the same is sometimes written with slightly different code. I'd very much like to centralize the processing in one procedure, I just can'd figure out how to do it in PL/SQL. I know PL/SQL doesn't have generics (Which I think would have made a Java/C# solution fairly trivial), but I'm wondering if there's another way to approach this problem that I just haven't thought of.

(using Oracle 10g)

答:
If you are willing and permitted to do so, you can create a TYPE to represent a record returned by any of the cursors. For example:

```<code>CREATE TYPE TRIPLE_TYPE IS OBJECT
(
  a NUMBER,
  b NUMBER,
  c NUMBER
);
</code>```

And another type to hold a collection of TRIPLE_TYPE:

```<code>CREATE TYPE TRIPLES_TYPE IS TABLE OF TRIPLE_TYPE;
</code>```

Finally, you define your cursors to return TRIPLE_TYPE records:

```<code>DECLARE

  cursor c_curs1 is
    select TRIPLE_TYPE(a, b, c)
    from (...) big_subquery_1
    where big_subquery_1.a_ind = 'Y';

  triples TRIPLES_TYPE;

BEGIN
  OPEN c_curs1;
  FETCH c_curs1 BULK COLLECT INTO triples;
  CLOSE c_curs1;
END;
</code>```

This technique allows you to write a procedure that accepts a TRIPLES_TYPE collection:

```<code>procedure sp_process_collection(in_collection TRIPLES_TYPE) is ...
</code>```

Body:
I am writing some PL/SQL and found myself falling into a repeptitive pattern:

cursor c_curs1 is
   select a, b, c
   from (...) big_subquery_1
   where big_subquery_1.a_ind = 'Y'

cursor c_curs2 is
   select a, b, c
   from (...) big_subquery_2
   where big_subquery_2.b_ind = 'R'

cursor c_curs3 is
   select a, b, c
   from (...) big_subquery_3
   where big_subquery_3.c_ind = 'M'

...
type t_curs1_tab is table of c_curs1;
type t_curs2_tab is table of c_curs2;
type t_curs3_tab is table of c_curs3;
...
v_curs1_results t_curs1_tab := t_curs1_tab();
v_curs2_results t_curs2_tab := t_curs2_tab();
v_curs3_results t_curs3_tab := t_curs3_tab();

Then when processing the results, I have code like this:

    open c_curs1;
    fetch c_curs1 bulk collect into v_curs1_results;
    close c_curs1;

    if v_curs1_results.first is not null and v_curs1_results.last is not null then
       for i in v_curs1_results.first .. v_curs1_results.last loop
           /*Do something with field a in the results
             Do something with field b in the results
             Do something with field c in the results*/
           ....
       end loop;
    end if;

The code in the processing loop is the same for all cursors, as all 3 cursors return a,b,c - the only difference being which cursor is referenced. I wanted to refactor this into some sort of generic result-set processor, but I'm stuck here:

procedure sp_process_collection(in_collection t_curs1_tab) is ...

I can only call this with v_curs1_results, I can't call it with v_curs2_results or I get a PLS-00306 wrong number of types or arguments... compiler error. Is there any way to do this generically so I only have to write one collection processing procedure? I have this pattern of cursor (returning the same three columns, always the same types) appears in several other parts of the same package, and the processing loop, while semantically the same is sometimes written with slightly different code. I'd very much like to centralize the processing in one procedure, I just can'd figure out how to do it in PL/SQL. I know PL/SQL doesn't have generics (Which I think would have made a Java/C# solution fairly trivial), but I'm wondering if there's another way to approach this problem that I just haven't thought of.

(using Oracle 10g)

Body:
If you are willing and permitted to do so, you can create a TYPE to represent a record returned by any of the cursors. For example:

CREATE TYPE TRIPLE_TYPE IS OBJECT
(
  a NUMBER,
  b NUMBER,
  c NUMBER
);

And another type to hold a collection of TRIPLE_TYPE:

CREATE TYPE TRIPLES_TYPE IS TABLE OF TRIPLE_TYPE;

Finally, you define your cursors to return TRIPLE_TYPE records:

DECLARE

  cursor c_curs1 is
    select TRIPLE_TYPE(a, b, c)
    from (...) big_subquery_1
    where big_subquery_1.a_ind = 'Y';

  triples TRIPLES_TYPE;

BEGIN
  OPEN c_curs1;
  FETCH c_curs1 BULK COLLECT INTO triples;
  CLOSE c_curs1;
END;

This technique allows you to write a procedure that accepts a TRIPLES_TYPE collection:

procedure sp_process_collection(in_collection TRIPLES_TYPE) is ...


问:
PHP foreach array and compare with GET
I'm trying to resolve my problem.

I store array in json file

I try to foreach array and compare it with my GET arguments

Problem was that only last of array filed works but other not.

auth.json

```<code>[{"License":"21X2-214X-SSDF-3215-SFFA","IP":"111111111","Note":"x1"},{"License":"S31S-SAF3-XF22-SLLT-341D","IP":"1111111","Note":"x2"}]
</code>```

PHP Code

```<code>$license = json_decode(file_get_contents('auth.json'), true);
foreach ($license as $cec) {

        if ($_GET["license"] == $cec["License"] AND $_GET["IP"] == $cec["IP"]){

            $user_auth = array(
            "user_info" => array(

                "auth" => 1
                ),
            );

        }else{
            $user_auth = array(
            "user_info" => array(

                "auth" => 0

                ),
            );
        }

    }
</code>```

答:
Thats because it overrides the results. It works fine you just want a break point when it finds someone authorized. </p>

```<code>foreach ($license as $cec) {

        if ($_GET["license"] == $cec["License"] AND $_GET["IP"] == $cec["IP"]){

            $user_auth = array(
                "user_info" => array(

                    "auth" => 1
                ),
            );

            break;

        }else{
            $user_auth = array(
                "user_info" => array(

                    "auth" => 0

                ),
            );
        }

}
</code>```

Title: PHP foreach array and compare with GET

Body:
I'm trying to resolve my problem.

I store array in json file

I try to foreach array and compare it with my GET arguments

Problem was that only last of array filed works but other not.

auth.json

[{"License":"21X2-214X-SSDF-3215-SFFA","IP":"111111111","Note":"x1"},{"License":"S31S-SAF3-XF22-SLLT-341D","IP":"1111111","Note":"x2"}]

PHP Code

$license = json_decode(file_get_contents('auth.json'), true);
foreach ($license as $cec) {

        if ($_GET["license"] == $cec["License"] AND $_GET["IP"] == $cec["IP"]){

            $user_auth = array(
            "user_info" => array(

                "auth" => 1
                ),
            );

        }else{
            $user_auth = array(
            "user_info" => array(

                "auth" => 0

                ),
            );
        }

    }

Body:
Thats because it overrides the results. It works fine you just want a break point when it finds someone authorized.

foreach ($license as $cec) {

        if ($_GET["license"] == $cec["License"] AND $_GET["IP"] == $cec["IP"]){

            $user_auth = array(
                "user_info" => array(

                    "auth" => 1
                ),
            );

            break;

        }else{
            $user_auth = array(
                "user_info" => array(

                    "auth" => 0

                ),
            );
        }

}


问:
Efficiently picking combinations of Integers
Let's say we have a 5x5 matrix, filled with 0s.

```<code>myMatrix <- matrix(rep(0, 25), ncol = 5)
</code>```

Now, let's pick a triplet of integers between 1 and 5.

```<code>triplet <- c(1,2,3)
</code>```

For all combinations of this triplet we now add 1 in the matrix,
with this function:

```<code>addCombinationsToMatrix <- function(.matrix, .triplet){
    indexesToChange <- as.matrix(expand.grid(.triplet, .triplet))
    .matrix[indexesToChange] <- .matrix[indexesToChange] + 1
    .matrix
}
</code>```

Using the function, we go from

```<code>myMatrix

     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    0    0
[2,]    0    0    0    0    0
[3,]    0    0    0    0    0
[4,]    0    0    0    0    0
[5,]    0    0    0    0    0
</code>```

to

```<code>myMatrix <- addCombinationsToMatrix(myMatrix, triplet)
myMatrix

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    0    0
[2,]    1    1    1    0    0
[3,]    1    1    1    0    0
[4,]    0    0    0    0    0
[5,]    0    0    0    0    0
</code>```

If we pick another triplet we move on to

```<code>nextTriplet <- 2:4
myMatrix <- addCombinationsToMatrix(myMatrix, nextTriplet)
myMatrix

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    0    0
[2,]    1    2    2    1    0
[3,]    1    2    2    1    0
[4,]    0    1    1    1    0
[5,]    0    0    0    0    0
</code>```

So, row-column combinations represent how often two integers have been shown
together in a triplet: 3 and 4 have been shown together once, 2 and 3 have
been shown together twice.

Question: How can one pick triplets, such that
every combination (1-2, 1-3, 1-4...) was picked at least once
and the number of triplets is minimized.

I'm looking for an algorithm here that picks the next triplet.

Ideally it can be extended to

arbitrarily big matrices (10x10, 100x100 ...)

arbitrarily big vectors (quadruplets, quintuplets, n-tuplets)

an arbitrary number of times a combination must have been picked at least

Example:

```<code>myMatrix
myMatrix <- addCombinationsToMatrix(myMatrix, 1:3)
myMatrix
myMatrix <- addCombinationsToMatrix(myMatrix, 3:5)
myMatrix
myMatrix <- addCombinationsToMatrix(myMatrix, c(1,4,5))
myMatrix
myMatrix <- addCombinationsToMatrix(myMatrix, c(2,4,5))
myMatrix
</code>```

EDIT:
Just to be sure: the answer doesn't have to be R code. It can be some other language as well or even pseudo code.

EDIT 2:
It occured to me now, that there are different ways of measuring efficiency. I actually meant, the algorithm should take as little iterations as possible. The algorithm being fast is also very cool, but not the main goal here.

答:
Since this question asks for algorithmic approaches to covering designs, I'll provide one that gives exact answers (aka the best possible design) using integer programming in R. For every single k-tuple that you are considering (k=3 for you, since you are selecting triplets), define a decision variable that takes value 1 if you include it in your design and 0 if not. So in your case, you would define x_123 to indicate if tuple (1,2,3) is selected, x_345 for (3,4,5), and so on.

The objective of the optimization model is to minimize the number of tuples selected, aka the sum of all your decision variables. However, for every t-tuple (t=2 in your case), you need to include a decision variable that contains that t-tuple. This yields a constraint for every t-tuple. As an example, we would have x_123+x_124+x_125 >= 1 would be the constraint that requires the pair 12 to be in some selected tuple.

This yields the following optimization model:

```<code>min  x_123+x_124+...+x_345
s.t. x_123+x_124+x_125 >= 1  # constraint for 12
     x_123+x_134+x_135 >= 1  # constraint for 13
     ...
     x_145+x_245+x_345 >= 1  # constraint for 45
     x_ijk binary for all i, j, k
</code>```

You could extend this to requiring r repeats of every t-tuple by changing the right-hand side of every inequality to "r" and requiring all the variables to be integer instead of binary.

This is easy to solve with a package like lpSolve in R:

```<code>library(lpSolve)
C <- function(v, k, tt, r) {
  k.tuples <- combn(v, k)
  t.tuples <- combn(v, tt)
  mod <- lp(direction="min",
            objective.in=rep(1, ncol(k.tuples)),
            const.mat=t(apply(t.tuples, 2, function(x) {
              apply(k.tuples, 2, function(y) as.numeric(sum(x %in% y) == tt))
            })),
            const.dir=rep(">=", ncol(t.tuples)),
            const.rhs=rep(r, ncol(t.tuples)),
            all.int=TRUE)
  k.tuples[,rep(seq_len(ncol(k.tuples)), round(mod$solution))]
}
C(5, 3, 2, 1)
#      [,1] [,2] [,3] [,4]
# [1,]    1    1    1    3
# [2,]    2    2    2    4
# [3,]    3    4    5    5
C(5, 3, 2, 3)
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,]    1    1    1    1    1    1    2    2    2     3
# [2,]    2    2    2    3    3    4    3    3    4     4
# [3,]    3    4    5    4    5    5    4    5    5     5
</code>```

While this solves your problem exactly, it will not scale well to large problem sizes. This is because the problem is NP-hard -- no known exact algorithm will scale well. If you need to solve large problem instances, then the heuristics recommended in other answers here are your best bet. Or you could solve with integer programming (as we do here) and set a timeout; then you will be working with the best solution found by your timeout, which is a heuristic solution to the problem overall.

Body:
Let's say we have a 5x5 matrix, filled with 0s.

myMatrix <- matrix(rep(0, 25), ncol = 5)

Now, let's pick a triplet of integers between 1 and 5.

triplet <- c(1,2,3)

For all combinations of this triplet we now add 1 in the matrix,
with this function:

addCombinationsToMatrix <- function(.matrix, .triplet){
    indexesToChange <- as.matrix(expand.grid(.triplet, .triplet))
    .matrix[indexesToChange] <- .matrix[indexesToChange] + 1
    .matrix
}

Using the function, we go from

myMatrix

     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    0    0
[2,]    0    0    0    0    0
[3,]    0    0    0    0    0
[4,]    0    0    0    0    0
[5,]    0    0    0    0    0

to

myMatrix <- addCombinationsToMatrix(myMatrix, triplet)
myMatrix

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    0    0
[2,]    1    1    1    0    0
[3,]    1    1    1    0    0
[4,]    0    0    0    0    0
[5,]    0    0    0    0    0

If we pick another triplet we move on to

nextTriplet <- 2:4
myMatrix <- addCombinationsToMatrix(myMatrix, nextTriplet)
myMatrix

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    0    0
[2,]    1    2    2    1    0
[3,]    1    2    2    1    0
[4,]    0    1    1    1    0
[5,]    0    0    0    0    0

So, row-column combinations represent how often two integers have been shown
together in a triplet: 3 and 4 have been shown together once, 2 and 3 have
been shown together twice.

Question: How can one pick triplets, such that
every combination (1-2, 1-3, 1-4...) was picked at least once
and the number of triplets is minimized.

I'm looking for an algorithm here that picks the next triplet.

Ideally it can be extended to

arbitrarily big matrices (10x10, 100x100 ...)

arbitrarily big vectors (quadruplets, quintuplets, n-tuplets)

an arbitrary number of times a combination must have been picked at least

Example:

myMatrix
myMatrix <- addCombinationsToMatrix(myMatrix, 1:3)
myMatrix
myMatrix <- addCombinationsToMatrix(myMatrix, 3:5)
myMatrix
myMatrix <- addCombinationsToMatrix(myMatrix, c(1,4,5))
myMatrix
myMatrix <- addCombinationsToMatrix(myMatrix, c(2,4,5))
myMatrix

EDIT:
Just to be sure: the answer doesn't have to be R code. It can be some other language as well or even pseudo code.

EDIT 2:
It occured to me now, that there are different ways of measuring efficiency. I actually meant, the algorithm should take as little iterations as possible. The algorithm being fast is also very cool, but not the main goal here.

Body:
Since this question asks for algorithmic approaches to covering designs, I'll provide one that gives exact answers (aka the best possible design) using integer programming in R. For every single k-tuple that you are considering (k=3 for you, since you are selecting triplets), define a decision variable that takes value 1 if you include it in your design and 0 if not. So in your case, you would define x_123 to indicate if tuple (1,2,3) is selected, x_345 for (3,4,5), and so on.

The objective of the optimization model is to minimize the number of tuples selected, aka the sum of all your decision variables. However, for every t-tuple (t=2 in your case), you need to include a decision variable that contains that t-tuple. This yields a constraint for every t-tuple. As an example, we would have x_123+x_124+x_125 >= 1 would be the constraint that requires the pair 12 to be in some selected tuple.

This yields the following optimization model:

min  x_123+x_124+...+x_345
s.t. x_123+x_124+x_125 >= 1  # constraint for 12
     x_123+x_134+x_135 >= 1  # constraint for 13
     ...
     x_145+x_245+x_345 >= 1  # constraint for 45
     x_ijk binary for all i, j, k

You could extend this to requiring r repeats of every t-tuple by changing the right-hand side of every inequality to "r" and requiring all the variables to be integer instead of binary.

This is easy to solve with a package like lpSolve in R:

library(lpSolve)
C <- function(v, k, tt, r) {
  k.tuples <- combn(v, k)
  t.tuples <- combn(v, tt)
  mod <- lp(direction="min",
            objective.in=rep(1, ncol(k.tuples)),
            const.mat=t(apply(t.tuples, 2, function(x) {
              apply(k.tuples, 2, function(y) as.numeric(sum(x %in% y) == tt))
            })),
            const.dir=rep(">=", ncol(t.tuples)),
            const.rhs=rep(r, ncol(t.tuples)),
            all.int=TRUE)
  k.tuples[,rep(seq_len(ncol(k.tuples)), round(mod$solution))]
}
C(5, 3, 2, 1)
#      [,1] [,2] [,3] [,4]
# [1,]    1    1    1    3
# [2,]    2    2    2    4
# [3,]    3    4    5    5
C(5, 3, 2, 3)
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,]    1    1    1    1    1    1    2    2    2     3
# [2,]    2    2    2    3    3    4    3    3    4     4
# [3,]    3    4    5    4    5    5    4    5    5     5

While this solves your problem exactly, it will not scale well to large problem sizes. This is because the problem is NP-hard -- no known exact algorithm will scale well. If you need to solve large problem instances, then the heuristics recommended in other answers here are your best bet. Or you could solve with integer programming (as we do here) and set a timeout; then you will be working with the best solution found by your timeout, which is a heuristic solution to the problem overall.