问:
The performance comparison of multi-threaded inserts(updates) on database and single-threaded sequential inserts(updates)?
Let's imagine an environment: there are one db client and one db server. The db client could be a Java program or other, etc; the db server can be mysql, oracle, etc.

The requirement is inserting a large amount of records into one table on the db server.

The simplest way is having a loop inside which the client inserts one record each time until all records are inserted. This is single threaded sequential inserts.

There is another multi-threaded concurrent inserts way that let client fire up multiple threads simultaneously each of which inserts one record into the table. Intuitively, because those records are independent and there is an assumption that modern db servers come with RAID in which the concurrent IO is well-supported, they seem to be able to gain practical and true concurrency for multiple inserts, therefore, this way could improve performance, compared to the above method.

However, as soon as I dived into more details, it turns out that's probably not the case. This link -- Multi threaded insert using ORM? says inserts on the same table require a lock for every single write on the whole table. Therefore, every insert just blocks another following insert, eventually, this way is just another type of sequential multiple inserts, no performance gain at all.

My question are as follows:

Why do most DBs treat multi threaded inserts on same table like this way?

Why is the insert lock on the whole table compulsory?

Are multiple threaded updates treated similarly as multi threaded inserts?

Despite it seems that the best way to deal with a large amount inserts is to have batch insert enabled, I'm still very curious of the grounds of locking whole table while inserting happens.

Thanks in advance!

=====================================================================

After plenty of readings and research, it shows that my questions were actually wrong. The real thing is one insert doesn't block another insert at the same time.(at least it is true for Oracle).

答:
Nothing is better than writing a demo to prove a theory.

I've worked out a following demo to compare the performance between single thread sequential inserts(without batch) and multi-thread inserts against Oracle.

```<code>import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
  * Created by boy on 14/03/17.
*/
public class DatabasePerformanceTest {
  //constants
  private static final String DBURL ="jdbc:oracle:thin:@xxxxxxxx:1521:xxxxx";
  private static final String DBUSER = "xxx";
  private static final String DBPASS = "xxxx";
  private static final Integer INSERT_AMOUNT = 10000;
  private static final String INSERT_PERSON = "insert into Persons values(1, 'xx', 'xx', 'xxxxxxx', 'xxxxxxx')";
  //pools
  private DataSource ds;
  private ExecutorService executor;

public static void main(String[] args) throws SQLException, InterruptedException {
    DatabasePerformanceTest test = new DatabasePerformanceTest();
    test.setUp();
    long begin = System.currentTimeMillis();
    //test.insertByRowByRow();
    test.insertByMultipleThreads();
    long end = System.currentTimeMillis();
    System.out.println("Time spent:" + (end - begin) + "ms");
}

private void setUp() {
    HikariConfig config = new HikariConfig();
    config.setJdbcUrl(DBURL);
    config.setUsername(DBUSER);
    config.setPassword(DBPASS);
    config.addDataSourceProperty("cachePrepStmts", "true");
    config.addDataSourceProperty("prepStmtCacheSize", "250");
    config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
    config.addDataSourceProperty("dataSourceClassName", "oracle.jdbc.driver.OracleDriver");
    ds = new HikariDataSource(config);
    this.executor = Executors.newFixedThreadPool(128);
}

private void insertOnePerson(Connection connection) throws SQLException {
    Statement statement = null;
    try {
        statement = connection.createStatement();
        statement.execute(INSERT_PERSON);
    } finally {
        try {
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    System.out.println("Inserting one person is done.");
}

private void insertByRowByRow() throws SQLException {
    for (int i = 0; i < INSERT_AMOUNT; i++) {
        this.insertOnePerson(ds.getConnection());
    }
}

private void insertByMultipleThreads() throws InterruptedException {
    for (int i = 0; i < INSERT_AMOUNT; i++) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    insertOnePerson(ds.getConnection());
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    executor.shutdown();
    executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
   }
}
</code>```

After testing, it clearly showed the multi-threading inserts is about 4 times faster than single-threading serialised inserts(without batch).

Therefore, the first answer for the link -- Multi threaded insert using ORM? is wrong.

That being said, like BobC mentioned, the above approach is a "home-grown" way, the best approach for dealing with a large amount of inserts is batch inserts.(loading sets of rows)

Body:
Nothing is better than writing a demo to prove a theory.

I've worked out a following demo to compare the performance between single thread sequential inserts(without batch) and multi-thread inserts against Oracle.

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
  * Created by boy on 14/03/17.
*/
public class DatabasePerformanceTest {
  //constants
  private static final String DBURL ="jdbc:oracle:thin:@xxxxxxxx:1521:xxxxx";
  private static final String DBUSER = "xxx";
  private static final String DBPASS = "xxxx";
  private static final Integer INSERT_AMOUNT = 10000;
  private static final String INSERT_PERSON = "insert into Persons values(1, 'xx', 'xx', 'xxxxxxx', 'xxxxxxx')";
  //pools
  private DataSource ds;
  private ExecutorService executor;

public static void main(String[] args) throws SQLException, InterruptedException {
    DatabasePerformanceTest test = new DatabasePerformanceTest();
    test.setUp();
    long begin = System.currentTimeMillis();
    //test.insertByRowByRow();
    test.insertByMultipleThreads();
    long end = System.currentTimeMillis();
    System.out.println("Time spent:" + (end - begin) + "ms");
}

private void setUp() {
    HikariConfig config = new HikariConfig();
    config.setJdbcUrl(DBURL);
    config.setUsername(DBUSER);
    config.setPassword(DBPASS);
    config.addDataSourceProperty("cachePrepStmts", "true");
    config.addDataSourceProperty("prepStmtCacheSize", "250");
    config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
    config.addDataSourceProperty("dataSourceClassName", "oracle.jdbc.driver.OracleDriver");
    ds = new HikariDataSource(config);
    this.executor = Executors.newFixedThreadPool(128);
}

private void insertOnePerson(Connection connection) throws SQLException {
    Statement statement = null;
    try {
        statement = connection.createStatement();
        statement.execute(INSERT_PERSON);
    } finally {
        try {
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    System.out.println("Inserting one person is done.");
}

private void insertByRowByRow() throws SQLException {
    for (int i = 0; i < INSERT_AMOUNT; i++) {
        this.insertOnePerson(ds.getConnection());
    }
}

private void insertByMultipleThreads() throws InterruptedException {
    for (int i = 0; i < INSERT_AMOUNT; i++) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    insertOnePerson(ds.getConnection());
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    executor.shutdown();
    executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
   }
}

After testing, it clearly showed the multi-threading inserts is about 4 times faster than single-threading serialised inserts(without batch).

Therefore, the first answer for the link -- Multi threaded insert using ORM? is wrong.

That being said, like BobC mentioned, the above approach is a "home-grown" way, the best approach for dealing with a large amount of inserts is batch inserts.(loading sets of rows)


来源: stackexchange

问:
Adding property to function with TypeScript
Say I have a function expression called run:

```<code>let run = function(){

};
</code>```

I want to add a property called "default" to this run function, a reference to itself.

```<code>run.default = run;
</code>```

this is to support multiple module export formats in JS.

I hear the best way to do this is with a namespace.

Here is my actual code:

```<code>namespace run {

  export interface Run {
    (paths: Array<string>, opts: run.IOpts, cb: Function): void
    default: Run;
  }

  export interface IOpts {
    babelExec?: string,
    all?: boolean
  }
}

  const run : run.Run = function (paths: Array<string>, opts: run.IOpts, cb: Function): void {

    //....

  }

run.default = run;
export = run;
</code>```

but I get this warning:

Does anyone know why that error message occurs?

As you can see, TS thinks I don't have the property typings for the default property, but I am pretty sure I do with the namespace declaration...or not? So confused by this error - the error/warning seems incorrect.

答:
The error is effected because the function you are assigning to default does not have a default property - it's just a function.

You've declared default as Run, so anything assigned to it will also have to have a default property.

You could either make default optional:

```<code>default?: Run;
</code>```

Or could declare it as a function:

```<code>default: (paths: Array<string>, opts: run.IOpts, cb: Function) => void;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Say I have a function expression called run:

let run = function(){

};

I want to add a property called "default" to this run function, a reference to itself.

run.default = run;

this is to support multiple module export formats in JS.

I hear the best way to do this is with a namespace.

Here is my actual code:

namespace run {

  export interface Run {
    (paths: Array<string>, opts: run.IOpts, cb: Function): void
    default: Run;
  }

  export interface IOpts {
    babelExec?: string,
    all?: boolean
  }
}

  const run : run.Run = function (paths: Array<string>, opts: run.IOpts, cb: Function): void {

    //....

  }

run.default = run;
export = run;

but I get this warning:

Does anyone know why that error message occurs?

As you can see, TS thinks I don't have the property typings for the default property, but I am pretty sure I do with the namespace declaration...or not? So confused by this error - the error/warning seems incorrect.

Body:
The error is effected because the function you are assigning to default does not have a default property - it's just a function.

You've declared default as Run, so anything assigned to it will also have to have a default property.

You could either make default optional:

default?: Run;

Or could declare it as a function:

default: (paths: Array<string>, opts: run.IOpts, cb: Function) => void;


问:
Spring boot JUNIT test fails for service test
I am trying to perform a Junit 4 test from a service in a spring boot application and I keep getting an entityManagerFactory its with init.

I also want connect using my application.properties file, but it wants to connect using the embedded hsqldb.

Can someone point me in the right direction?

Below is the pertinent code:

APPLICATION.PROPERTIES:

```<code>    # ===============================
# = DATA SOURCE
# ===============================

# Set here configurations for the database connection

# Connection url for the database "netgloo_blog"
spring.datasource.url = jdbc:mysql://localhost:3306/finra?useSSL=false

# Username and password
spring.datasource.username = finra
spring.datasource.password = finra

# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1

# ===============================
# = JPA / HIBERNATE
# ===============================

# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager).

# Show or not log for each sql query
spring.jpa.show-sql = true

# Hibernate ddl auto (create, create-drop, update): with "update" the database
# schema will be automatically updated accordingly to java entities found in
# the project
spring.jpa.hibernate.ddl-auto = update

# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
</code>```

MAIN:

```<code>    package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@EnableTransactionManagement
@ComponentScan(basePackages = {"com.example"})
@EntityScan(basePackages = {"com.example.entity"})
//@ImportResource("classpath:application.properties")
//@Configuration
//@EnableAutoConfiguration
//@ComponentScan
//@EnableScheduling
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
</code>```

ENTITY:

```<code>    package com.example.entity;

import java.io.Serializable;

public interface UserInterface extends Serializable{
    public long getId();
    public long setId(long value);
    public String getEMail();
    public void setEmail( String value );
    public String getName();
    public void setName(String value);
}

    package com.example.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
//import javax.persistence.Table;
import javax.validation.constraints.NotNull;

@Entity
//@Table(name = "users")
@Table(
        uniqueConstraints = {
                @UniqueConstraint(columnNames = {"email"})
        }
)
public class User implements UserInterface {

    /**
     *
     */
    private static final long serialVersionUID = -507606192667894785L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @NotNull
    private String email;

    @NotNull
    private String name;

    @Override
    public long getId() {
        // TODO Auto-generated method stub
        return id;
    }

    @Override
    public long setId(long value) {
        // TODO Auto-generated method stub
        return id = value;
    }

    @Override
    public String getEMail() {
        // TODO Auto-generated method stub
        return email;
    }

    @Override
    public void setEmail(String value) {
        // TODO Auto-generated method stub
        email = value;

    }

    @Override
    public String getName() {
        // TODO Auto-generated method stub
        return name;
    }

    @Override
    public void setName(String value) {
        // TODO Auto-generated method stub
        name = value;

    }

}
</code>```

DAO/REPOSITORY:

```<code>    package com.example.dao;

import javax.transaction.Transactional;

import org.springframework.data.repository.CrudRepository;

import com.example.entity.User;

@Transactional
public interface UserDao extends CrudRepository<User, Long> {
    public User findByEmail( String email );
    public void setUserDao(UserDao userDao);

}
</code>```

SERVICE:

```<code>    package com.example.service;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.dao.UserDao;
import com.example.entity.User;

@Service("userService")
public class UserService {
    private final Logger log = Logger.getLogger (this.getClass());

    @Autowired UserDao userDao;

    public void setUserDao( UserDao userDao ){
        this.userDao = userDao;
    }

    public List<User> findAll(){
        return (List<User>) userDao.findAll();
    }

    public User findOne( long id ){
        return userDao.findOne(id);
    }

    public User getByEmail(String email) throws Exception{

        String userId = null;
        User user = null;
        try{
            user = userDao.findByEmail(email);
            userId = String.valueOf(user.getId());
        }catch(Exception e){
            log.error("User not found");
            e.printStackTrace();
            throw new Exception(e);
        }
        log.info("The user id is: " + userId);
        return user;
    }

    public User create( String email, String name ){
        User user = null;
        try{
            user = new User();
            user.setEmail(email);
            user.setName(name);
            userDao.save(user);
        }catch( Exception e ){
            log.error("Error creating the user: " + e.getMessage());
        }
        log.info("User id: " + user.getId() + " saved.");
        return user;
    }

    public User updateUser(long id, String email, String name ){
        User user = null;
        try{
            user = userDao.findOne(id);
            user.setEmail(email);
            user.setName(name);
            userDao.save(user);
        }catch( Exception e ){
            log.error("Error updating the user: " + e.getMessage());
        }
        return user;
    }

    public User delete( long id ) throws Exception{
        User user = null;

        user = userDao.findOne(id);
        userDao.delete(user);
        return user;
    }
}
</code>```

TEST:

```<code>    /**
 *
 */
package com.example.service;

import static org.junit.Assert.*;

import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.Assert;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;

import com.example.DemoApplication;
import com.example.dao.UserDao;
import com.example.entity.User;

/**
 * @author denisputnam
 *
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
//@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
//@SpringBootConfiguration
@DataJpaTest
@Transactional
public class UserServiceTest {

    @Autowired
    private UserDao userDao;

    private UserService userService;

//  @Autowired
//  public void setUserService( UserService userService ){
//      this.userService = userService;
//  }

    /**
     * @throws java.lang.Exception
     */
    @Before
    public void setUp() throws Exception {

//      userDao = EasyMock.createMock(UserDao.class);
//
        userService = new UserService();
        userService.setUserDao(userDao);
//      testEntityManager = new TestEntityManager(emf);
//      this.testContextManager = new TestContextManager(getClass());
//      this.testContextManager.prepareTestInstance(this);
    }

    /**
     * Test method for {@link com.example.service.UserService#findAll()}.
     */
    @Test
    public void testFindAll() {
//      EasyMock.reset(userDao);
//      final List<User> users = new ArrayList<User>();
//      EasyMock.expect(userDao.findAll()).andReturn(users);
//      EasyMock.replay(userDao);
//      EasyMock.verify(userDao);
//      Assert.notEmpty(users, "findAll() failed.");
//      User user = new User();
//      user.setEmail("bogus@bogus.com");
//      user.setName("bogus");
//      UserService userService = new UserService();
//      this.setUserService(userService);
        User user = this.userService.create("bogus@bogus.com", "bogus");
        final List<User> users = (List<User>) this.userDao.findAll();
        Assert.notEmpty(users, "Found no users.");

    }

    /**
     * Test method for {@link com.example.service.UserService#findOne(long)}.
     */
    @Test
    public void testFindOne() {
        fail("Not yet implemented");
    }

    /**
     * Test method for {@link com.example.service.UserService#getByEmail(java.lang.String)}.
     */
    @Test
    public void testGetByEmail() {
        fail("Not yet implemented");
    }

    /**
     * Test method for {@link com.example.service.UserService#create(java.lang.String, java.lang.String)}.
     */
    @Test
    public void testCreate() {
        fail("Not yet implemented");
    }

    /**
     * Test method for {@link com.example.service.UserService#updateUser(long, java.lang.String, java.lang.String)}.
     */
    @Test
    public void testUpdateUser() {
        fail("Not yet implemented");
    }

    /**
     * Test method for {@link com.example.service.UserService#delete(long)}.
     */
    @Test
    public void testDelete() {
        fail("Not yet implemented");
    }

}
</code>```

SHOULD HAVE INCLUDED THIS:

```<code>    2017-04-02 16:30:00.627  INFO 93661 --- [           main] com.example.service.UserServiceTest      : Starting UserServiceTest on Deniss-IMAC.home with PID 93661 (started by denisputnam in /Users/denisputnam/git/springboot/demo)
2017-04-02 16:30:00.627  INFO 93661 --- [           main] com.example.service.UserServiceTest      : No active profile set, falling back to default profiles: default
2017-04-02 16:30:00.630  INFO 93661 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Refreshing org.springframework.web.context.support.GenericWebApplicationContext@3111631d: startup date [Sun Apr 02 16:30:00 EDT 2017]; root of context hierarchy
2017-04-02 16:30:00.694  INFO 93661 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'userService' with a different definition: replacing [Generic bean: class [com.example.service.UserService]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [/Users/denisputnam/git/springboot/demo/target/classes/com/example/service/UserService.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=userServiceTest.Config; factoryMethodName=userService; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/example/service/UserServiceTest$Config.class]]
2017-04-02 16:30:00.705  INFO 93661 --- [           main] beddedDataSourceBeanFactoryPostProcessor : Replacing 'dataSource' DataSource bean with embedded version
2017-04-02 16:30:00.705  INFO 93661 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'dataSource' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]] with [Root bean: class [org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration$EmbeddedDataSourceFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
2017-04-02 16:30:00.705  WARN 93661 --- [           main] o.s.c.a.ConfigurationClassPostProcessor  : Cannot enhance @Configuration bean definition 'embeddedDataSourceBeanFactoryPostProcessor' since its singleton instance has been created too early. The typical cause is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'.
2017-04-02 16:30:00.740  INFO 93661 --- [           main] o.s.j.d.e.EmbeddedDatabaseFactory        : Starting embedded database: url='jdbc:hsqldb:mem:77b77b83-0034-41be-ab58-3f5d9490ea80', username='sa'
2017-04-02 16:30:00.805  INFO 93661 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-04-02 16:30:00.805  INFO 93661 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2017-04-02 16:30:00.810  INFO 93661 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-04-02 16:30:00.825  INFO 93661 --- [           main] org.hibernate.tool.hbm2ddl.SchemaUpdate  : HHH000228: Running hbm2ddl schema update
2017-04-02 16:30:00.827  INFO 93661 --- [           main] rmationExtractorJdbcDatabaseMetaDataImpl : HHH000262: Table not found: user
2017-04-02 16:30:00.828  INFO 93661 --- [           main] rmationExtractorJdbcDatabaseMetaDataImpl : HHH000262: Table not found: user
2017-04-02 16:30:00.829  WARN 93661 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
2017-04-02 16:30:00.829  INFO 93661 --- [           main] utoConfigurationReportLoggingInitializer :
</code>```

STACK:

```<code>    2017-04-02 16:05:44.625 ERROR 92739 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120) [spring-boot-test-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) [.cp/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
</code>```

答:
I found the solution here:

spring boot configuration example

Body:
I am trying to perform a Junit 4 test from a service in a spring boot application and I keep getting an entityManagerFactory its with init.

I also want connect using my application.properties file, but it wants to connect using the embedded hsqldb.

Can someone point me in the right direction?

Below is the pertinent code:

APPLICATION.PROPERTIES:

    # ===============================
# = DATA SOURCE
# ===============================

# Set here configurations for the database connection

# Connection url for the database "netgloo_blog"
spring.datasource.url = jdbc:mysql://localhost:3306/finra?useSSL=false

# Username and password
spring.datasource.username = finra
spring.datasource.password = finra

# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1

# ===============================
# = JPA / HIBERNATE
# ===============================

# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager).

# Show or not log for each sql query
spring.jpa.show-sql = true

# Hibernate ddl auto (create, create-drop, update): with "update" the database
# schema will be automatically updated accordingly to java entities found in
# the project
spring.jpa.hibernate.ddl-auto = update

# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

MAIN:

    package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@EnableTransactionManagement
@ComponentScan(basePackages = {"com.example"})
@EntityScan(basePackages = {"com.example.entity"})
//@ImportResource("classpath:application.properties")
//@Configuration
//@EnableAutoConfiguration
//@ComponentScan
//@EnableScheduling
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

ENTITY:

    package com.example.entity;

import java.io.Serializable;

public interface UserInterface extends Serializable{
    public long getId();
    public long setId(long value);
    public String getEMail();
    public void setEmail( String value );
    public String getName();
    public void setName(String value);
}

    package com.example.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
//import javax.persistence.Table;
import javax.validation.constraints.NotNull;

@Entity
//@Table(name = "users")
@Table(
        uniqueConstraints = {
                @UniqueConstraint(columnNames = {"email"})
        }
)
public class User implements UserInterface {

    /**
     *
     */
    private static final long serialVersionUID = -507606192667894785L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @NotNull
    private String email;

    @NotNull
    private String name;

    @Override
    public long getId() {
        // TODO Auto-generated method stub
        return id;
    }

    @Override
    public long setId(long value) {
        // TODO Auto-generated method stub
        return id = value;
    }

    @Override
    public String getEMail() {
        // TODO Auto-generated method stub
        return email;
    }

    @Override
    public void setEmail(String value) {
        // TODO Auto-generated method stub
        email = value;

    }

    @Override
    public String getName() {
        // TODO Auto-generated method stub
        return name;
    }

    @Override
    public void setName(String value) {
        // TODO Auto-generated method stub
        name = value;

    }

}

DAO/REPOSITORY:

    package com.example.dao;

import javax.transaction.Transactional;

import org.springframework.data.repository.CrudRepository;

import com.example.entity.User;

@Transactional
public interface UserDao extends CrudRepository<User, Long> {
    public User findByEmail( String email );
    public void setUserDao(UserDao userDao);

}

SERVICE:

    package com.example.service;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.dao.UserDao;
import com.example.entity.User;

@Service("userService")
public class UserService {
    private final Logger log = Logger.getLogger (this.getClass());

    @Autowired UserDao userDao;

    public void setUserDao( UserDao userDao ){
        this.userDao = userDao;
    }

    public List<User> findAll(){
        return (List<User>) userDao.findAll();
    }

    public User findOne( long id ){
        return userDao.findOne(id);
    }

    public User getByEmail(String email) throws Exception{

        String userId = null;
        User user = null;
        try{
            user = userDao.findByEmail(email);
            userId = String.valueOf(user.getId());
        }catch(Exception e){
            log.error("User not found");
            e.printStackTrace();
            throw new Exception(e);
        }
        log.info("The user id is: " + userId);
        return user;
    }

    public User create( String email, String name ){
        User user = null;
        try{
            user = new User();
            user.setEmail(email);
            user.setName(name);
            userDao.save(user);
        }catch( Exception e ){
            log.error("Error creating the user: " + e.getMessage());
        }
        log.info("User id: " + user.getId() + " saved.");
        return user;
    }

    public User updateUser(long id, String email, String name ){
        User user = null;
        try{
            user = userDao.findOne(id);
            user.setEmail(email);
            user.setName(name);
            userDao.save(user);
        }catch( Exception e ){
            log.error("Error updating the user: " + e.getMessage());
        }
        return user;
    }

    public User delete( long id ) throws Exception{
        User user = null;

        user = userDao.findOne(id);
        userDao.delete(user);
        return user;
    }
}

TEST:

    /**
 *
 */
package com.example.service;

import static org.junit.Assert.*;

import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.Assert;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;

import com.example.DemoApplication;
import com.example.dao.UserDao;
import com.example.entity.User;

/**
 * @author denisputnam
 *
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
//@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
//@SpringBootConfiguration
@DataJpaTest
@Transactional
public class UserServiceTest {

    @Autowired
    private UserDao userDao;

    private UserService userService;

//  @Autowired
//  public void setUserService( UserService userService ){
//      this.userService = userService;
//  }

    /**
     * @throws java.lang.Exception
     */
    @Before
    public void setUp() throws Exception {

//      userDao = EasyMock.createMock(UserDao.class);
//
        userService = new UserService();
        userService.setUserDao(userDao);
//      testEntityManager = new TestEntityManager(emf);
//      this.testContextManager = new TestContextManager(getClass());
//      this.testContextManager.prepareTestInstance(this);
    }

    /**
     * Test method for {@link com.example.service.UserService#findAll()}.
     */
    @Test
    public void testFindAll() {
//      EasyMock.reset(userDao);
//      final List<User> users = new ArrayList<User>();
//      EasyMock.expect(userDao.findAll()).andReturn(users);
//      EasyMock.replay(userDao);
//      EasyMock.verify(userDao);
//      Assert.notEmpty(users, "findAll() failed.");
//      User user = new User();
//      user.setEmail("bogus@bogus.com");
//      user.setName("bogus");
//      UserService userService = new UserService();
//      this.setUserService(userService);
        User user = this.userService.create("bogus@bogus.com", "bogus");
        final List<User> users = (List<User>) this.userDao.findAll();
        Assert.notEmpty(users, "Found no users.");

    }

    /**
     * Test method for {@link com.example.service.UserService#findOne(long)}.
     */
    @Test
    public void testFindOne() {
        fail("Not yet implemented");
    }

    /**
     * Test method for {@link com.example.service.UserService#getByEmail(java.lang.String)}.
     */
    @Test
    public void testGetByEmail() {
        fail("Not yet implemented");
    }

    /**
     * Test method for {@link com.example.service.UserService#create(java.lang.String, java.lang.String)}.
     */
    @Test
    public void testCreate() {
        fail("Not yet implemented");
    }

    /**
     * Test method for {@link com.example.service.UserService#updateUser(long, java.lang.String, java.lang.String)}.
     */
    @Test
    public void testUpdateUser() {
        fail("Not yet implemented");
    }

    /**
     * Test method for {@link com.example.service.UserService#delete(long)}.
     */
    @Test
    public void testDelete() {
        fail("Not yet implemented");
    }

}

SHOULD HAVE INCLUDED THIS:

    2017-04-02 16:30:00.627  INFO 93661 --- [           main] com.example.service.UserServiceTest      : Starting UserServiceTest on Deniss-IMAC.home with PID 93661 (started by denisputnam in /Users/denisputnam/git/springboot/demo)
2017-04-02 16:30:00.627  INFO 93661 --- [           main] com.example.service.UserServiceTest      : No active profile set, falling back to default profiles: default
2017-04-02 16:30:00.630  INFO 93661 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Refreshing org.springframework.web.context.support.GenericWebApplicationContext@3111631d: startup date [Sun Apr 02 16:30:00 EDT 2017]; root of context hierarchy
2017-04-02 16:30:00.694  INFO 93661 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'userService' with a different definition: replacing [Generic bean: class [com.example.service.UserService]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [/Users/denisputnam/git/springboot/demo/target/classes/com/example/service/UserService.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=userServiceTest.Config; factoryMethodName=userService; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/example/service/UserServiceTest$Config.class]]
2017-04-02 16:30:00.705  INFO 93661 --- [           main] beddedDataSourceBeanFactoryPostProcessor : Replacing 'dataSource' DataSource bean with embedded version
2017-04-02 16:30:00.705  INFO 93661 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'dataSource' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]] with [Root bean: class [org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration$EmbeddedDataSourceFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
2017-04-02 16:30:00.705  WARN 93661 --- [           main] o.s.c.a.ConfigurationClassPostProcessor  : Cannot enhance @Configuration bean definition 'embeddedDataSourceBeanFactoryPostProcessor' since its singleton instance has been created too early. The typical cause is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'.
2017-04-02 16:30:00.740  INFO 93661 --- [           main] o.s.j.d.e.EmbeddedDatabaseFactory        : Starting embedded database: url='jdbc:hsqldb:mem:77b77b83-0034-41be-ab58-3f5d9490ea80', username='sa'
2017-04-02 16:30:00.805  INFO 93661 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-04-02 16:30:00.805  INFO 93661 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2017-04-02 16:30:00.810  INFO 93661 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-04-02 16:30:00.825  INFO 93661 --- [           main] org.hibernate.tool.hbm2ddl.SchemaUpdate  : HHH000228: Running hbm2ddl schema update
2017-04-02 16:30:00.827  INFO 93661 --- [           main] rmationExtractorJdbcDatabaseMetaDataImpl : HHH000262: Table not found: user
2017-04-02 16:30:00.828  INFO 93661 --- [           main] rmationExtractorJdbcDatabaseMetaDataImpl : HHH000262: Table not found: user
2017-04-02 16:30:00.829  WARN 93661 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
2017-04-02 16:30:00.829  INFO 93661 --- [           main] utoConfigurationReportLoggingInitializer :

STACK:

    2017-04-02 16:05:44.625 ERROR 92739 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120) [spring-boot-test-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) [.cp/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory


问:
Connect to external server by using phpMyAdmin
I have phpMyAdmin installed on my local machine. How can I make it connect to an external server?</p>

答:
using PhpMyAdmin version 4.5.4.1deb2ubuntu2, you can set the variables in /etc/phpmyadmin/config-db.php

so set $dbserver to your server name, e.g. $dbserver='mysql.example.com';

<?php
##
## database access settings in php format
## automatically generated from /etc/dbconfig-common/phpmyadmin.conf
## by /usr/sbin/dbconfig-generate-include
##
## by default this file is managed via ucf, so you shouldn't have to
## worry about manual changes being silently discarded.  *however*,
## you'll probably also want to edit the configuration file mentioned
## above too.
##
$dbuser='phpmyadmin';
$dbpass='P@55w0rd';
$basepath='';
$dbname='phpmyadmin';
$dbserver='localhost';
$dbport='';
$dbtype='mysql';
```


问:
Java encrypting and decryption of image files using AES and a hashed password as key
I've looked at several posts on this topic, such as this post to actually encrypt/decrypt, and this post on generating a key using a string as a seed to generate a random key. The encryption reduces my filesize from 3mb to 16 bytes and the decryption reduces it further to 0 bytes. I also watched this YouTube video on the topic and my code had the same issues with the file size being reduced to zero in the decryption process, while his worked fine.

This is my function generating a key based on a SHA256 hash passed as k:

```<code> public static Key keyGen(String k) throws Exception {
     SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
     KeySpec spec = new PBEKeySpec(k.toCharArray(), k.getBytes(), 12, 128);
     SecretKey tmp = factory.generateSecret(spec);
     return new SecretKeySpec(tmp.getEncoded(), "AES");
 }
</code>```

These are the functions I'm using to encrypt and decrypt:

```<code>public static void encrypt(Key key, byte[] content) throws Exception {
        Cipher cipher;
        byte[] encrypted = null;
        try {
            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE,  key);
            encrypted = cipher.doFinal(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        saveFile(encrypted);
        JOptionPane.showMessageDialog(null, "Encryption complete");
    }

 public static void decrypt(Key key, byte[] textCryp) throws Exception {
        Cipher cipher;
        byte[] decrypted = null;
        try {
            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key);
            decrypted = cipher.doFinal(textCryp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        saveFile(decrypted);
        JOptionPane.showMessageDialog(null, "Decryption complete");
    }
</code>```

The function I'm using to write the contents back into the file:

```<code>   public static void saveFile(byte[] bytes) throws IOException {
        FileOutputStream fos = new FileOutputStream("filepath/test.jpg");
        fos.write(bytes);
        fos.close();
    }
</code>```

And finally, the function that gets the byte representation of the image file, passed into the encrypt/decrypt functions as "content":

```<code>public static byte[] getFile() {

    File f = new File("filepath/test.jpg");
    InputStream is = null;
    try {
        is = new FileInputStream(f);
    } catch (FileNotFoundException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }
    byte[] content = null;
    try {
        content = new byte[is.available()];
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        is.read(content);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return content;
}
</code>```

And the main function calling these functions:

```<code>public static void main(String[] args) throws Exception {
    Key key = keyGen("1234567812345678");
    byte[] fileContents = getFile();
    //I change to decrypt after I call encrypt
    encrypt(key,fileContents);

 }
</code>```

No errors or exceptions are thrown, and the posts and video I referenced while writing this code seems to be working fine.

I would really appreciate an advice on this as this is the final part of a project I've been working on for a long time.

答: After more trials, I realized the test file I was trying to run the code on was in a cloud drive. I copied the file to a local directory, reran the code and it worked perfectly. </p>

Body:
I've looked at several posts on this topic, such as this post to actually encrypt/decrypt, and this post on generating a key using a string as a seed to generate a random key. The encryption reduces my filesize from 3mb to 16 bytes and the decryption reduces it further to 0 bytes. I also watched this YouTube video on the topic and my code had the same issues with the file size being reduced to zero in the decryption process, while his worked fine.

This is my function generating a key based on a SHA256 hash passed as k:

 public static Key keyGen(String k) throws Exception {
     SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
     KeySpec spec = new PBEKeySpec(k.toCharArray(), k.getBytes(), 12, 128);
     SecretKey tmp = factory.generateSecret(spec);
     return new SecretKeySpec(tmp.getEncoded(), "AES");
 }

These are the functions I'm using to encrypt and decrypt:

public static void encrypt(Key key, byte[] content) throws Exception {
        Cipher cipher;
        byte[] encrypted = null;
        try {
            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE,  key);
            encrypted = cipher.doFinal(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        saveFile(encrypted);
        JOptionPane.showMessageDialog(null, "Encryption complete");
    }

 public static void decrypt(Key key, byte[] textCryp) throws Exception {
        Cipher cipher;
        byte[] decrypted = null;
        try {
            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key);
            decrypted = cipher.doFinal(textCryp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        saveFile(decrypted);
        JOptionPane.showMessageDialog(null, "Decryption complete");
    }

The function I'm using to write the contents back into the file:

   public static void saveFile(byte[] bytes) throws IOException {
        FileOutputStream fos = new FileOutputStream("filepath/test.jpg");
        fos.write(bytes);
        fos.close();
    }

And finally, the function that gets the byte representation of the image file, passed into the encrypt/decrypt functions as "content":

public static byte[] getFile() {

    File f = new File("filepath/test.jpg");
    InputStream is = null;
    try {
        is = new FileInputStream(f);
    } catch (FileNotFoundException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }
    byte[] content = null;
    try {
        content = new byte[is.available()];
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        is.read(content);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return content;
}

And the main function calling these functions:

public static void main(String[] args) throws Exception {
    Key key = keyGen("1234567812345678");
    byte[] fileContents = getFile();
    //I change to decrypt after I call encrypt
    encrypt(key,fileContents);

 }

No errors or exceptions are thrown, and the posts and video I referenced while writing this code seems to be working fine.

I would really appreciate an advice on this as this is the final part of a project I've been working on for a long time.


问:
How do I pass an std::string to a function that expects char*?

Possible Duplicate:

  Can I get a non-const C string back from a C++ string?

Do I need to convert it first? I saw in another post that .c_str() can be used if the function expected const char*. What about for just char*?

答:
```<code>std::vector<char> buffer(s.begin(), s.end());
foo(&buffer[0], buffer.size());
s.assign(buffer.begin(), buffer.end());
</code>```

ContentLicense: CC BY-SA 2.5


问:
Is it possible to use `impl Trait` as a function's return type in a trait definition?
Is it at all possible to define functions inside of traits as having impl Trait return types?  I want to create a trait that can be implemented by multiple structs so that the new() functions of all of them returns an object that they can all be used in the same way without having to write code specific to each one.

```<code>trait A {
    fn new() -> impl A;
}
</code>```

However, I get the following error:

error[E0562]: `impl Trait` not allowed outside of function and inherent method return types
 --> src/lib.rs:2:17
  |
2 |     fn new() -> impl A;
  |                 ^^^^^^
```

Is this a limitation of the current implementation of impl Trait or am I using it wrong?

答:
You can get something similar even in the case where it's not returning Self by using an associated type and explicitly naming the return type:

```<code>trait B {}
struct C;

impl B for C {}

trait A {
    type FReturn: B;
    fn f() -> Self::FReturn;
}

struct Person;

impl A for Person {
    type FReturn = C;
    fn f() -> C {
        C
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Is it at all possible to define functions inside of traits as having impl Trait return types?  I want to create a trait that can be implemented by multiple structs so that the new() functions of all of them returns an object that they can all be used in the same way without having to write code specific to each one.

trait A {
    fn new() -> impl A;
}

However, I get the following error:

error[E0562]: `impl Trait` not allowed outside of function and inherent method return types
 --> src/lib.rs:2:17
  |
2 |     fn new() -> impl A;
  |                 ^^^^^^

Is this a limitation of the current implementation of impl Trait or am I using it wrong?

Body:
You can get something similar even in the case where it's not returning Self by using an associated type and explicitly naming the return type:

trait B {}
struct C;

impl B for C {}

trait A {
    type FReturn: B;
    fn f() -> Self::FReturn;
}

struct Person;

impl A for Person {
    type FReturn = C;
    fn f() -> C {
        C
    }
}


问:
Memcpy takes the same time as memset
I want to measure memory bandwidth using memcpy. I modified the code from this answer:why vectorizing the loop does not have performance improvement which used memset to measure the bandwidth. The problem is that memcpy is only slighly slower than memset when I expect it to be about two times slower since it operations on twice the memory.

More specifically, I run over 1 GB arrays a and b (allocated will calloc) 100 times with the following operations.

```<code>operation             time(s)
-----------------------------
memset(a,0xff,LEN)    3.7
memcpy(a,b,LEN)       3.9
a[j] += b[j]          9.4
memcpy(a,b,LEN)       3.8
</code>```

Notice that memcpy is only slightly slower then memset. The operations a[j] += b[j] (where j goes over [0,LEN)) should take three times longer than memcpy because it operates on three times as much data.  However it's only about 2.5 as slow as memset.

Then I initialized b to zero with memset(b,0,LEN) and test again:

```<code>operation             time(s)
-----------------------------
memcpy(a,b,LEN)       8.2
a[j] += b[j]          11.5
</code>```

Now we see that memcpy is about twice as slow as memset and a[j] += b[j] is about thrice as slow as memset like I expect.

At the very least I would have expected that before memset(b,0,LEN) that memcpy would be slower because the of lazy allocation (first touch) on the first of the 100 iterations.

Why do I only get the time I expect after memset(b,0,LEN)?

test.c

```<code>#include <time.h>
#include <string.h>
#include <stdio.h>

void tests(char *a, char *b, const int LEN){
    clock_t time0, time1;
    time0 = clock();
    for (int i = 0; i < 100; i++) memset(a,0xff,LEN);
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);

    time0 = clock();
    for (int i = 0; i < 100; i++) memcpy(a,b,LEN);
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);

    time0 = clock();
    for (int i = 0; i < 100; i++) for(int j=0; j<LEN; j++) a[j] += b[j];
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);

    time0 = clock();
    for (int i = 0; i < 100; i++) memcpy(a,b,LEN);
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);

    memset(b,0,LEN);
    time0 = clock();
    for (int i = 0; i < 100; i++) memcpy(a,b,LEN);
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);

    time0 = clock();
    for (int i = 0; i < 100; i++) for(int j=0; j<LEN; j++) a[j] += b[j];
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);
}
</code>```

main.c

```<code>#include <stdlib.h>

int tests(char *a, char *b, const int LEN);

int main(void) {
    const int LEN = 1 << 30;    //  1GB
    char *a = (char*)calloc(LEN,1);
    char *b = (char*)calloc(LEN,1);
    tests(a, b, LEN);
}
</code>```

Compile with (gcc 6.2) gcc -O3 test.c main.c. Clang 3.8 gives essentially the same result.

Test system: i7-6700HQ@2.60GHz (Skylake), 32 GB DDR4, Ubuntu 16.10. On my Haswell system the bandwidths make sense before memset(b,0,LEN) i.e. I only see a problem on my Skylake system.

I first discovered this issue from the a[j] += b[k] operations in this answer which was overestimating the bandwidth.

I came up with a simpler test

```<code>#include <time.h>
#include <string.h>
#include <stdio.h>

void __attribute__ ((noinline))  foo(char *a, char *b, const int LEN) {
  for (int i = 0; i < 100; i++) for(int j=0; j<LEN; j++) a[j] += b[j];
}

void tests(char *a, char *b, const int LEN) {
    foo(a, b, LEN);
    memset(b,0,LEN);
    foo(a, b, LEN);
}
</code>```

This outputs.

```<code>9.472976
12.728426
</code>```

However, if I do memset(b,1,LEN) in main after calloc (see below) then it outputs

```<code>12.5
12.5
</code>```

This leads me to to think this is a OS allocation issue and not a compiler issue.

```<code>#include <stdlib.h>

int tests(char *a, char *b, const int LEN);

int main(void) {
    const int LEN = 1 << 30;    //  1GB
    char *a = (char*)calloc(LEN,1);
    char *b = (char*)calloc(LEN,1);
    //GCC optimizes memset(b,0,LEN) away after calloc but Clang does not.
    memset(b,1,LEN);
    tests(a, b, LEN);
}
</code>```

答:
The point is that malloc and calloc on most platforms don't allocate memory; they allocate address space.

malloc etc work by:

if the request can be fulfilled by the freelist, carve a chunk out of it

in case of calloc: the equivalent ofmemset(ptr, 0, size) is issued

if not: ask the OS to extend the address space.

For systems with demand paging (COW) (an MMU could help here), the second options winds downto:

create enough page table entries for the request, and fill them with a (COW) reference to /dev/zero

add these PTEs to the address space of the process

This will consume no physical memory, except only for the Page Tables.

Once the new memory is referenced for read, the read will come from /dev/zero. The /dev/zero device is a very special device, in this case mapped to every page of the new memory.

but, if the new page is written, the COW logic kicks in (via a page fault):

physical memory is allocated

the /dev/zero page is copied to the new page

the new page is detached from the mother page

and the calling process can finally do the update which started all this

Title: Memcpy takes the same time as memset

Body:
I want to measure memory bandwidth using memcpy. I modified the code from this answer:why vectorizing the loop does not have performance improvement which used memset to measure the bandwidth. The problem is that memcpy is only slighly slower than memset when I expect it to be about two times slower since it operations on twice the memory.

More specifically, I run over 1 GB arrays a and b (allocated will calloc) 100 times with the following operations.

operation             time(s)
-----------------------------
memset(a,0xff,LEN)    3.7
memcpy(a,b,LEN)       3.9
a[j] += b[j]          9.4
memcpy(a,b,LEN)       3.8

Notice that memcpy is only slightly slower then memset. The operations a[j] += b[j] (where j goes over [0,LEN)) should take three times longer than memcpy because it operates on three times as much data.  However it's only about 2.5 as slow as memset.

Then I initialized b to zero with memset(b,0,LEN) and test again:

operation             time(s)
-----------------------------
memcpy(a,b,LEN)       8.2
a[j] += b[j]          11.5

Now we see that memcpy is about twice as slow as memset and a[j] += b[j] is about thrice as slow as memset like I expect.

At the very least I would have expected that before memset(b,0,LEN) that memcpy would be slower because the of lazy allocation (first touch) on the first of the 100 iterations.

Why do I only get the time I expect after memset(b,0,LEN)?

test.c

#include <time.h>
#include <string.h>
#include <stdio.h>

void tests(char *a, char *b, const int LEN){
    clock_t time0, time1;
    time0 = clock();
    for (int i = 0; i < 100; i++) memset(a,0xff,LEN);
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);

    time0 = clock();
    for (int i = 0; i < 100; i++) memcpy(a,b,LEN);
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);

    time0 = clock();
    for (int i = 0; i < 100; i++) for(int j=0; j<LEN; j++) a[j] += b[j];
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);

    time0 = clock();
    for (int i = 0; i < 100; i++) memcpy(a,b,LEN);
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);

    memset(b,0,LEN);
    time0 = clock();
    for (int i = 0; i < 100; i++) memcpy(a,b,LEN);
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);

    time0 = clock();
    for (int i = 0; i < 100; i++) for(int j=0; j<LEN; j++) a[j] += b[j];
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);
}

main.c

#include <stdlib.h>

int tests(char *a, char *b, const int LEN);

int main(void) {
    const int LEN = 1 << 30;    //  1GB
    char *a = (char*)calloc(LEN,1);
    char *b = (char*)calloc(LEN,1);
    tests(a, b, LEN);
}

Compile with (gcc 6.2) gcc -O3 test.c main.c. Clang 3.8 gives essentially the same result.

Test system: i7-6700HQ@2.60GHz (Skylake), 32 GB DDR4, Ubuntu 16.10. On my Haswell system the bandwidths make sense before memset(b,0,LEN) i.e. I only see a problem on my Skylake system.

I first discovered this issue from the a[j] += b[k] operations in this answer which was overestimating the bandwidth.

I came up with a simpler test

#include <time.h>
#include <string.h>
#include <stdio.h>

void __attribute__ ((noinline))  foo(char *a, char *b, const int LEN) {
  for (int i = 0; i < 100; i++) for(int j=0; j<LEN; j++) a[j] += b[j];
}

void tests(char *a, char *b, const int LEN) {
    foo(a, b, LEN);
    memset(b,0,LEN);
    foo(a, b, LEN);
}

This outputs.

9.472976
12.728426

However, if I do memset(b,1,LEN) in main after calloc (see below) then it outputs

12.5
12.5

This leads me to to think this is a OS allocation issue and not a compiler issue.

#include <stdlib.h>

int tests(char *a, char *b, const int LEN);

int main(void) {
    const int LEN = 1 << 30;    //  1GB
    char *a = (char*)calloc(LEN,1);
    char *b = (char*)calloc(LEN,1);
    //GCC optimizes memset(b,0,LEN) away after calloc but Clang does not.
    memset(b,1,LEN);
    tests(a, b, LEN);
}


问:
Calculation of QF and BF in Solr Edimax
I'm trying to use both the qf and bf fields however, I can't comprehend the results of the score. May I know how the score is calculated?

Below is the query I've made:
    http://localhost:8983/solr/core name/select?bf=likes^0.8%20created_time^0.8&debugQuery=on&defType=edismax&indent=on&q=Samsung&qf=description^0.8&wt=json

And the score I've gotten

```<code>"rawquerystring":"Samsung"

"querystring":"Samsung"

"parsedquery":"(+DisjunctionMaxQuery(((description:samsung)^0.8)) FunctionQuery(date(created_time))^0.8 FunctionQuery(int(likes))^0.8)/no_coord"
"parsedquery_toString":"+((description:samsung)^0.8) (date(created_time))^0.8 (int(likes))^0.8"

"explain":{
  "23379598044_10154409629363045":"\n1.19288942E12 = sum of:\n  4.6113086 = weight(description:samsung in 61828) [SchemaSimilarity], result of:\n    4.6113086 = score(doc=61828,freq=1.0 = termFreq=1.0\n), product of:\n      0.8 = boost\n      4.2966447 = idf(docFreq=780, docCount=57329)\n      1.3415436 = tfNorm, computed from:\n        1.0 = termFreq=1.0\n        1.2 = parameter k1\n        0.75 = parameter b\n        13.833522 = avgFieldLength\n        5.2244897 = fieldLength\n  1.19288942E12 = FunctionQuery(date(created_time)), product of:\n    1.49111177E12 = date(created_time)=2017-04-02T05:43:00Z\n    0.8 = boost\n    1.0 = queryNorm\n  22.4 = FunctionQuery(int(likes)), product of:\n    28.0 = int(likes)=28\n    0.8 = boost\n    1.0 = queryNorm\n",
</code>```

答:
Ok, let's decipher it - first things first and it's always easier to transform your explain into something more readable, e.g. replace \n into real carriage returns so it'd look like:

```<code>1.19288942E12 = sum of:
  4.6113086 = weight(description:samsung in 61828) [SchemaSimilarity], result of:
    4.6113086 = score(doc=61828,freq=1.0 = termFreq=1.0), product of:
      0.8 = boost
      4.2966447 = idf(docFreq=780, docCount=57329)
      1.3415436 = tfNorm, computed from:
        1.0 = termFreq=1.0
        1.2 = parameter k1
        0.75 = parameter b
        13.833522 = avgFieldLength
        5.2244897 = fieldLength
  1.19288942E12 = FunctionQuery(date(created_time)), product of:
    1.49111177E12 = date(created_time)=2017-04-02T05:43:00Z
    0.8 = boost
    1.0 = queryNorm
  22.4 = FunctionQuery(int(likes)), product of:
    28.0 = int(likes)=28
    0.8 = boost
    1.0 = queryNorm
</code>```

Just to make it clear - this explain applies only for document with id= 23379598044_10154409629363045 from your result-set.

Let's break down the overall score of 1.19288942E12. As it says - it is sum of 3 parts:

4.6113086 = weight(description:samsung in 61828) - this part is strongly related to your query per se. Since your query is q=Samsung and qf=description^0.8 it will mean that if document will be matched into field description - then DisMax will boost the value by factor of 0.8 (here is reference for qf param). And this is what explain says: 4.6113086 ... is product of: 0.8 = boost, 4.2966447 = idf and 1.3415436 = tfNorm. Please note, that default scoring model in Solr < 6.0 is TF/IDF.

1.19288942E12 = FunctionQuery(date(created_time)) - this part is related to bf=created_time^0.8 part (I excluded likes^0.8 for sake of explanation - basically it will be covered in last bullet-point). What Solr (DisMax) is doing here - it takes the value of created_time for this particular document (2017-04-02T05:43:00Z), then converts it to UNIX timestamp (1.49111177E12) and then multiplies it by factor of 0.8. As you might notice 1.19288942E12 is quite big number if you compare it with initial TF/IDF. Usually it is practically inefficient and I would suggest using some normalizing function like reciprocal for such purposes.

22.4 = FunctionQuery(int(likes)) - this part is related to bf=likes^0.8. Basically Solr will also take the value of the field for this particular document (28) and multiply it by factor of 0.8. Here is my little note: if you know the distribution of the values for this field - that's pretty good - maybe this is useful in practice. But sometimes you never know your distribution and it's worth to normalize your field as well - apply some scale function for instance. I'm not insisting - just some piece of advice :)

Hopefully it should give you some hints for better 'explain' comprehension :)

Title: Calculation of QF and BF in Solr Edimax

Body:
I'm trying to use both the qf and bf fields however, I can't comprehend the results of the score. May I know how the score is calculated?

Below is the query I've made:
    http://localhost:8983/solr/core name/select?bf=likes^0.8%20created_time^0.8&debugQuery=on&defType=edismax&indent=on&q=Samsung&qf=description^0.8&wt=json

And the score I've gotten

"rawquerystring":"Samsung"

"querystring":"Samsung"

"parsedquery":"(+DisjunctionMaxQuery(((description:samsung)^0.8)) FunctionQuery(date(created_time))^0.8 FunctionQuery(int(likes))^0.8)/no_coord"
"parsedquery_toString":"+((description:samsung)^0.8) (date(created_time))^0.8 (int(likes))^0.8"

"explain":{
  "23379598044_10154409629363045":"\n1.19288942E12 = sum of:\n  4.6113086 = weight(description:samsung in 61828) [SchemaSimilarity], result of:\n    4.6113086 = score(doc=61828,freq=1.0 = termFreq=1.0\n), product of:\n      0.8 = boost\n      4.2966447 = idf(docFreq=780, docCount=57329)\n      1.3415436 = tfNorm, computed from:\n        1.0 = termFreq=1.0\n        1.2 = parameter k1\n        0.75 = parameter b\n        13.833522 = avgFieldLength\n        5.2244897 = fieldLength\n  1.19288942E12 = FunctionQuery(date(created_time)), product of:\n    1.49111177E12 = date(created_time)=2017-04-02T05:43:00Z\n    0.8 = boost\n    1.0 = queryNorm\n  22.4 = FunctionQuery(int(likes)), product of:\n    28.0 = int(likes)=28\n    0.8 = boost\n    1.0 = queryNorm\n",

Body:
Ok, let's decipher it - first things first and it's always easier to transform your explain into something more readable, e.g. replace \n into real carriage returns so it'd look like:

1.19288942E12 = sum of:
  4.6113086 = weight(description:samsung in 61828) [SchemaSimilarity], result of:
    4.6113086 = score(doc=61828,freq=1.0 = termFreq=1.0), product of:
      0.8 = boost
      4.2966447 = idf(docFreq=780, docCount=57329)
      1.3415436 = tfNorm, computed from:
        1.0 = termFreq=1.0
        1.2 = parameter k1
        0.75 = parameter b
        13.833522 = avgFieldLength
        5.2244897 = fieldLength
  1.19288942E12 = FunctionQuery(date(created_time)), product of:
    1.49111177E12 = date(created_time)=2017-04-02T05:43:00Z
    0.8 = boost
    1.0 = queryNorm
  22.4 = FunctionQuery(int(likes)), product of:
    28.0 = int(likes)=28
    0.8 = boost
    1.0 = queryNorm

Just to make it clear - this explain applies only for document with id= 23379598044_10154409629363045 from your result-set.

Let's break down the overall score of 1.19288942E12. As it says - it is sum of 3 parts:

4.6113086 = weight(description:samsung in 61828) - this part is strongly related to your query per se. Since your query is q=Samsung and qf=description^0.8 it will mean that if document will be matched into field description - then DisMax will boost the value by factor of 0.8 (here is reference for qf param). And this is what explain says: 4.6113086 ... is product of: 0.8 = boost, 4.2966447 = idf and 1.3415436 = tfNorm. Please note, that default scoring model in Solr < 6.0 is TF/IDF.

1.19288942E12 = FunctionQuery(date(created_time)) - this part is related to bf=created_time^0.8 part (I excluded likes^0.8 for sake of explanation - basically it will be covered in last bullet-point). What Solr (DisMax) is doing here - it takes the value of created_time for this particular document (2017-04-02T05:43:00Z), then converts it to UNIX timestamp (1.49111177E12) and then multiplies it by factor of 0.8. As you might notice 1.19288942E12 is quite big number if you compare it with initial TF/IDF. Usually it is practically inefficient and I would suggest using some normalizing function like reciprocal for such purposes.

22.4 = FunctionQuery(int(likes)) - this part is related to bf=likes^0.8. Basically Solr will also take the value of the field for this particular document (28) and multiply it by factor of 0.8. Here is my little note: if you know the distribution of the values for this field - that's pretty good - maybe this is useful in practice. But sometimes you never know your distribution and it's worth to normalize your field as well - apply some scale function for instance. I'm not insisting - just some piece of advice :)

Hopefully it should give you some hints for better 'explain' comprehension :)


问:
Button sound effect only works 28 times
I have set a gunshot sound to play every time I press a button (It is a fire button so it needs to be clicked many times).
When I run the program, the gunshot sound plays every time I press it, but after the 28th time the button is pressed, the sound is no longer played. However, the Toast I added still works. Any idea why this is?

activity_main.xml:

```<code> <Button
        android:id="@+id/fire"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="fire"
        android:onClick="fire"
        android:textSize="35sp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />
</code>```

Main.java:

```<code>package com.example.brans.zoombie;

import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class Main extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void fire(View v){
    MediaPlayer mp = MediaPlayer.create(Main.this, R.raw.pistol);
    mp.start();
    Toast.makeText(this, "shot fired", Toast.LENGTH_SHORT).show();
}
}
</code>```

After the 29th Time, the logcat says this.

```<code>04-02 16:07:56.371 23703-23717/com.example.brans.zoombie       V/MediaPlayer:message received msg=100, ext1=1, ext2=-19
04-02 16:07:56.371 23703-23717/com.example.brans.zoombie E/MediaPlayer: error (1, -19)
04-02 16:07:56.371 23703-23717/com.example.brans.zoombie V/MediaPlayer: callback application
04-02 16:07:56.371 23703-23717/com.example.brans.zoombie V/MediaPlayer: back from callback
</code>```

答:
You should remove media player from RAM to avoid out of memory exceptions. </p>

```<code>public void fire(View v){
    MediaPlayer mp = MediaPlayer.create(Main.this, R.raw.pistol);
    mp.start();
    Toast.makeText(this, "shot fired", Toast.LENGTH_SHORT).show();
    mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        mp.stop();
        if (mp != null) {
            mp.release();
        }

      }
    });
}
</code>```

Title: Button sound effect only works 28 times

Body:
I have set a gunshot sound to play every time I press a button (It is a fire button so it needs to be clicked many times).
When I run the program, the gunshot sound plays every time I press it, but after the 28th time the button is pressed, the sound is no longer played. However, the Toast I added still works. Any idea why this is?

activity_main.xml:

 <Button
        android:id="@+id/fire"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="fire"
        android:onClick="fire"
        android:textSize="35sp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

Main.java:

package com.example.brans.zoombie;

import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class Main extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void fire(View v){
    MediaPlayer mp = MediaPlayer.create(Main.this, R.raw.pistol);
    mp.start();
    Toast.makeText(this, "shot fired", Toast.LENGTH_SHORT).show();
}
}

After the 29th Time, the logcat says this.

04-02 16:07:56.371 23703-23717/com.example.brans.zoombie       V/MediaPlayer:message received msg=100, ext1=1, ext2=-19
04-02 16:07:56.371 23703-23717/com.example.brans.zoombie E/MediaPlayer: error (1, -19)
04-02 16:07:56.371 23703-23717/com.example.brans.zoombie V/MediaPlayer: callback application
04-02 16:07:56.371 23703-23717/com.example.brans.zoombie V/MediaPlayer: back from callback

Body:
You should remove media player from RAM to avoid out of memory exceptions.

public void fire(View v){
    MediaPlayer mp = MediaPlayer.create(Main.this, R.raw.pistol);
    mp.start();
    Toast.makeText(this, "shot fired", Toast.LENGTH_SHORT).show();
    mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        mp.stop();
        if (mp != null) {
            mp.release();
        }

      }
    });
}