问:
Unable to create a table using Hibernate and MYSQL
I am new to hibernate and I have to get some strange behavior from it, below is the scenario.

My java files are,

UserDetails.java :-

```<code>package org.mahesh.test;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class UserDetails {
@Id
private int userId;
private String userName;
public String getUserName() {
    return userName;
}
public void setUserName(String userName) {
    this.userName = userName;
}
public int getUserId() {
    return userId;
}
public void setUserId(int userId) {
    this.userId = userId;
}
}
</code>```

HibernateTest.java is,

```<code> package org.mahesh.hibernate;
 import org.hibernate.Session;
 import org.hibernate.SessionFactory;
 import org.hibernate.cfg.Configuration;
 import org.mahesh.securifi.UserDetails;
 public class HibernateTest {

 public static void main(String[] args) {
    // TODO Auto-generated method stub
    UserDetails user = new UserDetails();
    user.setUserId(1);
    user.setUserName("Mahesh");

    SessionFactory sessionFactory = new   Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    session.save(user);
    session.getTransaction().commit();
  }
  }
</code>```

hibernate.cfg.xml is,

```<code>   <?xml version='1.0' encoding='utf-8'?>
   <!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

 <hibernate-configuration>

<session-factory>

    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/employee</property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

    <!-- Disable the second-level cache  -->
    <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>

    <!-- Drop and re-create the database schema on startup -->
    <property name="hibernate.hbm2ddl.auto">create</property>

    <!-- Names the annotated entity class -->
    <mapping class="org.mahesh.securifi.UserDetails"/>

</session-factory>

</hibernate-configuration>
</code>```

Full stack trace is,

```<code>Mar 24, 2017 10:28:20 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.9.Final}
Mar 24, 2017 10:28:20 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Mar 24, 2017 10:28:20 AM         org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Mar 24, 2017 10:28:20 AM     org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderIm    pl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for     production use!)
Mar 24, 2017 10:28:20 AM     org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderIm    pl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL     [jdbc:mysql://localhost:3306/employee]
Mar 24, 2017 10:28:20 AM     org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderIm    pl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Mar 24, 2017 10:28:20 AM     org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderIm    pl buildCreator
INFO: HHH10001003: Autocommit mode: false
Mar 24, 2017 10:28:20 AM     org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Mar 24, 2017 10:28:20 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Mar 24, 2017 10:28:20 AM     org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl     useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported     JDBC version [3] less than 4
Hibernate: drop table if exists UserDetails
Mar 24, 2017 10:28:21 AM     org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorN    onJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess     [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProvi    derJdbcConnectionAccess@40db2a24] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: create table UserDetails (userId integer not null, userName     varchar(255), primary key (userId)) type=MyISAM
Mar 24, 2017 10:28:21 AM     org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorN    onJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess     [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@22356acd] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Mar 24, 2017 10:28:21 AM     org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
WARN: GenerationTarget encountered exception accepting command : Error     executing DDL via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement
at     org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
at     org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreato    rImpl.java:440)
at     org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlStrings(SchemaCreat    orImpl.java:424)
at         org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCr    eatorImpl.java:315)
at     org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreat    orImpl.java:166)
at     org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImp    l.java:135)
at     org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImp    l.java:121)
at     org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAct    ion(SchemaManagementToolCoordinator.java:155)
at     org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaMana    gementToolCoordinator.java:72)
at org.hibernate.internal.SessionFactoryImpl.<init>    (SessionFactoryImpl.java:309)
at     org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilde    rImpl.java:445)
at     org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
at     org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at org.mahesh.hibernate.HibernateTest.main(HibernateTest.java:16)
Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an         error in your SQL syntax; check the manual that corresponds to your MySQL server     version for the right syntax to use near 'type=MyISAM' at line 1
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3277)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3206)
    at com.mysql.jdbc.Statement.execute(Statement.java:727)
    at     org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(Genera    tionTargetToDatabase.java:54)
... 13 more

Mar 24, 2017 10:28:21 AM     org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script     'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@6e4566    f1'
Hibernate: insert into UserDetails (userName, userId) values (?, ?)
Mar 24, 2017 10:28:21 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper         logExceptions
WARN: SQL Error: 1146, SQLState: 42S02
Mar 24, 2017 10:28:21 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper     logExceptions
ERROR: Table 'employee.userdetails' doesn't exist
Mar 24, 2017 10:28:21 AM     org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
Mar 24, 2017 10:28:21 AM org.hibernate.internal.ExceptionMapperStandardImpl     mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush     [org.hibernate.exception.SQLGrammarException: could not execute statement]
Exception in thread "main" javax.persistence.PersistenceException:     org.hibernate.exception.SQLGrammarException: could not execute statement
    at     org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.jav    a:147)
at     org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.jav    a:155)
at     org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.jav    a:162)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1434)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:484)
at     org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.    java:3190)
at     org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:    2404)
at     org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompleti    on(JdbcCoordinatorImpl.java:467)
at     org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransa        ctionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordi    natorImpl.java:146)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransa        ctionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java    :38)
at     org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransa    ctionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransa    ctionCoordinatorImpl.java:220)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl    .java:68)
at org.mahesh.hibernate.HibernateTest.main(HibernateTest.java:20)
Caused by: org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3003)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3503)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:586)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:460)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1428)
... 9 more
Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table     'employee.userdetails' doesn't exist
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3283)
at         com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1332)
at     com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1604)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1519)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1504)
at     org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetRe    turnImpl.java:205)
... 18 more
</code>```

Getting this error while running.

答:
I too had CommandAcceptanceException and SQLGrammarException, when I upgraded my DB from MySQL 5.1 to 5.7. I changed the dialect in hibernate.cfg.xml

```<code><!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
</code>```

It was earlier "org.hibernate.dialect.MySQLDialect ". It fixed the issue.

Body:
I am new to hibernate and I have to get some strange behavior from it, below is the scenario.

My java files are,

UserDetails.java :-

package org.mahesh.test;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class UserDetails {
@Id
private int userId;
private String userName;
public String getUserName() {
    return userName;
}
public void setUserName(String userName) {
    this.userName = userName;
}
public int getUserId() {
    return userId;
}
public void setUserId(int userId) {
    this.userId = userId;
}
}

HibernateTest.java is,

 package org.mahesh.hibernate;
 import org.hibernate.Session;
 import org.hibernate.SessionFactory;
 import org.hibernate.cfg.Configuration;
 import org.mahesh.securifi.UserDetails;
 public class HibernateTest {

 public static void main(String[] args) {
    // TODO Auto-generated method stub
    UserDetails user = new UserDetails();
    user.setUserId(1);
    user.setUserName("Mahesh");

    SessionFactory sessionFactory = new   Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    session.save(user);
    session.getTransaction().commit();
  }
  }

hibernate.cfg.xml is,

   <?xml version='1.0' encoding='utf-8'?>
   <!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

 <hibernate-configuration>

<session-factory>

    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/employee</property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>

    <property name="connection.pool_size">1</property>

    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

    <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

    <property name="show_sql">true</property>

    <property name="hibernate.hbm2ddl.auto">create</property>

    <mapping class="org.mahesh.securifi.UserDetails"/>

</session-factory>

</hibernate-configuration>

Full stack trace is,

Mar 24, 2017 10:28:20 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.9.Final}
Mar 24, 2017 10:28:20 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Mar 24, 2017 10:28:20 AM         org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Mar 24, 2017 10:28:20 AM     org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderIm    pl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for     production use!)
Mar 24, 2017 10:28:20 AM     org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderIm    pl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL     [jdbc:mysql://localhost:3306/employee]
Mar 24, 2017 10:28:20 AM     org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderIm    pl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Mar 24, 2017 10:28:20 AM     org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderIm    pl buildCreator
INFO: HHH10001003: Autocommit mode: false
Mar 24, 2017 10:28:20 AM     org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Mar 24, 2017 10:28:20 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Mar 24, 2017 10:28:20 AM     org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl     useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported     JDBC version [3] less than 4
Hibernate: drop table if exists UserDetails
Mar 24, 2017 10:28:21 AM     org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorN    onJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess     [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProvi    derJdbcConnectionAccess@40db2a24] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: create table UserDetails (userId integer not null, userName     varchar(255), primary key (userId)) type=MyISAM
Mar 24, 2017 10:28:21 AM     org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorN    onJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess     [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@22356acd] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Mar 24, 2017 10:28:21 AM     org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
WARN: GenerationTarget encountered exception accepting command : Error     executing DDL via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement
at     org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
at     org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreato    rImpl.java:440)
at     org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlStrings(SchemaCreat    orImpl.java:424)
at         org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCr    eatorImpl.java:315)
at     org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreat    orImpl.java:166)
at     org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImp    l.java:135)
at     org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImp    l.java:121)
at     org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAct    ion(SchemaManagementToolCoordinator.java:155)
at     org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaMana    gementToolCoordinator.java:72)
at org.hibernate.internal.SessionFactoryImpl.<init>    (SessionFactoryImpl.java:309)
at     org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilde    rImpl.java:445)
at     org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
at     org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at org.mahesh.hibernate.HibernateTest.main(HibernateTest.java:16)
Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an         error in your SQL syntax; check the manual that corresponds to your MySQL server     version for the right syntax to use near 'type=MyISAM' at line 1
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3277)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3206)
    at com.mysql.jdbc.Statement.execute(Statement.java:727)
    at     org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(Genera    tionTargetToDatabase.java:54)
... 13 more

Mar 24, 2017 10:28:21 AM     org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script     'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@6e4566    f1'
Hibernate: insert into UserDetails (userName, userId) values (?, ?)
Mar 24, 2017 10:28:21 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper         logExceptions
WARN: SQL Error: 1146, SQLState: 42S02
Mar 24, 2017 10:28:21 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper     logExceptions
ERROR: Table 'employee.userdetails' doesn't exist
Mar 24, 2017 10:28:21 AM     org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
Mar 24, 2017 10:28:21 AM org.hibernate.internal.ExceptionMapperStandardImpl     mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush     [org.hibernate.exception.SQLGrammarException: could not execute statement]
Exception in thread "main" javax.persistence.PersistenceException:     org.hibernate.exception.SQLGrammarException: could not execute statement
    at     org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.jav    a:147)
at     org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.jav    a:155)
at     org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.jav    a:162)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1434)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:484)
at     org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.    java:3190)
at     org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:    2404)
at     org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompleti    on(JdbcCoordinatorImpl.java:467)
at     org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransa        ctionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordi    natorImpl.java:146)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransa        ctionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java    :38)
at     org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransa    ctionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransa    ctionCoordinatorImpl.java:220)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl    .java:68)
at org.mahesh.hibernate.HibernateTest.main(HibernateTest.java:20)
Caused by: org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3003)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3503)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:586)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:460)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1428)
... 9 more
Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table     'employee.userdetails' doesn't exist
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3283)
at         com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1332)
at     com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1604)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1519)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1504)
at     org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetRe    turnImpl.java:205)
... 18 more

Getting this error while running.

Body:
I too had CommandAcceptanceException and SQLGrammarException, when I upgraded my DB from MySQL 5.1 to 5.7. I changed the dialect in hibernate.cfg.xml

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

It was earlier "org.hibernate.dialect.MySQLDialect ". It fixed the issue.


来源: stackexchange

问:
Is try-catch meant to prevent or handle errors? (in javascript)
Recently I had a discussion with my coworker, about using try and catch to notify errors or avoid them.

This is my coworker's approach:

```<code>import Config from 'config';

export const getUserFromLocalStorage = () => {
  const key = Object.keys(localStorage).find(value => value === `${Config.applicationId}/currentUser`);

  try {
    return key ? JSON.parse(localStorage[key]) : {};
  } catch (e) {
    return {};
  }
};
</code>```

Wich means, he doesn't care about the given error and he is just carrying of returning an object in order to continue the process

and mine is:

```<code>import Config from 'config';

export const getUserFromLocalStorage = () => {
  const key = Object.keys(localStorage).find(value => value === `${Config.applicationId}/currentUser`);

  try {
    return key ? JSON.parse(localStorage[key]) : {};
  } catch (e) {
    console.log('the given error', e); // Just simple notifier for this example
  }
};
</code>```

but my approach, still has a problem which is that it will return undefined (which can crash internaly my app), that can easily fix it using finally and returning a default value but it doesn't sound a good practice to me.

 THE QUESTION

So what will the balance using try catch and finally if needed, to make my application stable.

Is there something wrong with our approach?

In particular, we can't trust the data that is comming from the localStorage, so what will be the best approach for this implementation?

答:
In this specific case, where you are working with localStorage (which almost always inevitably means working with JSON.parse()), it's always best practice to wrap your processing in try-catch. This is because both localStorage and JSON.parse have exceptions as a normal part of their error handling and it is usually possible to fallback to a default or initial value gracefully.

A pattern I use is something like as follows:

```<code>const DEFAULT_VALUE = {};
try {
  const result = JSON.parse(result);
  return result || DEFAULT_VALUE;
} catch (e) {
  console.warn('Error parsing result', e);
}

return DEFAULT_VALUE;
</code>```

This way, you have consistent error handling and default value fallback.

In general, you shouldn't need use try-catch unless you can and will safely handle the error and generate a useful fallback. Most try-catch blocks tend to sit at the bottom of a call-stack for this reason, so that they catch unplanned errors, handle them gracefully for the user, but log them noisily with a call-stack to the console for the developer to investigate/handle correctly/workaround.

ContentLicense: CC BY-SA 3.0

Body:
Recently I had a discussion with my coworker, about using try and catch to notify errors or avoid them.

This is my coworker's approach:

import Config from 'config';

export const getUserFromLocalStorage = () => {
  const key = Object.keys(localStorage).find(value => value === `${Config.applicationId}/currentUser`);

  try {
    return key ? JSON.parse(localStorage[key]) : {};
  } catch (e) {
    return {};
  }
};

Wich means, he doesn't care about the given error and he is just carrying of returning an object in order to continue the process

and mine is:

import Config from 'config';

export const getUserFromLocalStorage = () => {
  const key = Object.keys(localStorage).find(value => value === `${Config.applicationId}/currentUser`);

  try {
    return key ? JSON.parse(localStorage[key]) : {};
  } catch (e) {
    console.log('the given error', e); // Just simple notifier for this example
  }
};

but my approach, still has a problem which is that it will return undefined (which can crash internaly my app), that can easily fix it using finally and returning a default value but it doesn't sound a good practice to me.

 THE QUESTION

So what will the balance using try catch and finally if needed, to make my application stable.

Is there something wrong with our approach?

In particular, we can't trust the data that is comming from the localStorage, so what will be the best approach for this implementation?

Body:
In this specific case, where you are working with localStorage (which almost always inevitably means working with JSON.parse()), it's always best practice to wrap your processing in try-catch. This is because both localStorage and JSON.parse have exceptions as a normal part of their error handling and it is usually possible to fallback to a default or initial value gracefully.

A pattern I use is something like as follows:

const DEFAULT_VALUE = {};
try {
  const result = JSON.parse(result);
  return result || DEFAULT_VALUE;
} catch (e) {
  console.warn('Error parsing result', e);
}

return DEFAULT_VALUE;

This way, you have consistent error handling and default value fallback.

In general, you shouldn't need use try-catch unless you can and will safely handle the error and generate a useful fallback. Most try-catch blocks tend to sit at the bottom of a call-stack for this reason, so that they catch unplanned errors, handle them gracefully for the user, but log them noisily with a call-stack to the console for the developer to investigate/handle correctly/workaround.


问:
How to draw dashed(-) radius on google maps swift?

I'm struggling to get dashed radius on google maps. Can anyone please help?. I need an output like attached image.

Thanks,

答:
Directly on circle is not possible </p>

<p>You could draw a polyline based on circle  </p>

```<code> var myCicle = new google.maps.Polyline({
               path: drawCircle(new google.maps.LatLng( 46.0,11.0), 50, 1),
               strokeOpacity: 0,
               icons: [{
                 icon: lineSymbol,
                 offset: '0',
                 repeat: '15px'
               }],
               strokeWeight: 1,
               fillColor: "#FFFF00",
               fillOpacity: 0.15,
               map:map
   });
</code>```

Body:
Directly on circle is not possible

You could draw a polyline based on circle

 var myCicle = new google.maps.Polyline({
               path: drawCircle(new google.maps.LatLng( 46.0,11.0), 50, 1),
               strokeOpacity: 0,
               icons: [{
                 icon: lineSymbol,
                 offset: '0',
                 repeat: '15px'
               }],
               strokeWeight: 1,
               fillColor: "#FFFF00",
               fillOpacity: 0.15,
               map:map
   });


Title: Express column as percent (xts)

Body:
There is an xts object with prices on which I calculate the log returns between periods/rows. I want to express the returns in percentage. The approach recommended here (i.e. using percent function of scales package) converts returns into a vector of characters. I want to convert returns to a vector of numbers, not characters.

So I used percent function of formattable package, which supposedly does that. Unfortunately, I get an error message and I'm stuck. Would anyone know what the issue is? Thanks in advance.

library('formattable')
DTT3 <- structure(c(126.33, 126.37, 126.42, 126.3, 126.31, 126.31, 126.31,126.37, 126.41, 126.42, 126.38, 126.33, 126.38, 126.38, 126.36, 126.39, 126.42, 126.42, 126.43, 126.43, 126.42, 126.39, 126.47, 126.56, 126.53, 126.5, 126.43, 126.45, 126.5, 126.42, 126.39, 126.39, 126.37, 126.24, 126.21, 126.15, 126.21, 126.24, 126.24, 126.25, 126.25, 126.2, 126.18, 126.21, 126.15, 126.16, 126.03, 125.94, 125.97, 125.97, 125.7, 125.73, 125.73, 125.55, 126.38, 126.47, 126.43, 126.35, 126.32, 126.37, 126.37, 126.43, 126.44, 126.43, 126.39, 126.39, 126.42, 126.38, 126.38, 126.44, 126.44, 126.44, 126.44, 126.44, 126.42, 126.5, 126.56, 126.57, 126.55, 126.52, 126.56, 126.5, 126.52, 126.44, 126.43, 126.42, 126.41, 126.29, 126.22, 126.29, 126.24, 126.3, 126.25, 126.27, 126.3, 126.2, 126.25, 126.21, 126.2, 126.17, 126.03, 126.04, 126.02, 125.97, 126.04, 125.89, 125.81, 125.6, 126.32, 126.36, 126.3, 126.25, 126.26, 126.29, 126.29, 126.36, 126.4, 126.37, 126.32, 126.28, 126.36, 126.34, 126.36, 126.39, 126.36, 126.37, 126.41, 126.41, 126.35, 126.39, 126.43, 126.52, 126.48, 126.42, 126.4, 126.41, 126.36, 126.34, 126.35, 126.3, 126.22, 126.2, 126.14, 126.15, 126.15, 126.22, 126.18, 126.23, 126.15, 126.14, 126.15, 126.15, 126.09, 125.91, 125.87, 125.94, 125.9, 125.7, 125.67, 125.63, 125.54, 125.35, 126.37, 126.42, 126.3, 126.32, 126.3, 126.32, 126.36, 126.41, 126.42, 126.38, 126.33, 126.39, 126.38, 126.36, 126.38, 126.42, 126.44, 126.42, 126.44, 126.41, 126.4, 126.47, 126.55, 126.53, 126.5, 126.43, 126.45, 126.49, 126.42, 126.39, 126.38, 126.36, 126.25, 126.22, 126.16, 126.21, 126.23, 126.24, 126.25, 126.26, 126.21, 126.18, 126.2, 126.15, 126.16, 126.02, 125.95, 125.98, 125.97, 125.7, 125.73, 125.72, 125.55, 125.38, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo"), index = structure(c(1403483400, 1403484300, 1403485200, 1403486100, 1403487000, 1403487900, 1403488800, 1403489700, 1403490600, 1403491500, 1403492400, 1403493300, 1403494200, 1403495100, 1403496000, 1403496900, 1403497800, 1403498700, 1403499600, 1403500500, 1403501400, 1403502300, 1403503200, 1403504100, 1403505000, 1403505900, 1403506800, 1403507700, 1403508600, 1403509500, 1403510400, 1403511300, 1403512200, 1403513100, 1403514000, 1403514900, 1403515800, 1403516700, 1403517600, 1403518500, 1403519400, 1403520300, 1403521200, 1403522100, 1403523000, 1403523900, 1403524800, 1403525700, 1403526600, 1403527500, 1403528400, 1403529300, 1403530200, 1403531100), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(54L, 5L), .Dimnames = list(NULL, c("Open", "High", "Low", "Close", "S_Base")))
lr <- diff(log(DTT3$Close))
lrpct <- percent(lr$Close,digits =2,format ="f")

#ERROR MESSAGE:
Error in create_obj(x, "formattable", list(formatter = formatter, format = list(...),  :
             argument "formatter" is missing, with no default

Body:
Is this what you want:

lrpct <- percent(lr, digits =2,format ="f", formatter = "formatC")
lrpct

## [1] 0.04%  -0.09% 0.02%  -0.02% 0.02%  0.03%  0.04%  0.01%  -0.03% -0.04%
## [11] 0.05%  -0.01% -0.02% 0.02%  0.03%  0.02%  -0.02% 0.02%  -0.02% -0.01%
## [21] 0.06%  0.06%  -0.02% -0.02% -0.06% 0.02%  0.03%  -0.06% -0.02% -0.01%
## [31] -0.02% -0.09% -0.02% -0.05% 0.04%  0.02%  0.01%  0.01%  0.01%  -0.04%
## [41] -0.02% 0.02%  -0.04% 0.01%  -0.11% -0.06% 0.02%  -0.01% -0.21% 0.02%
## [51] -0.01% -0.14% -0.14%


问:
ORACLE APEX Region footer text page item accessing inside page process
I have created a custom page item 'tot_credit' to get correct alignment below my tabular form report,  using the below code .
,it is written in the region 'footer text'.But I am unable to access this item 'tot_credit' inside my page process(pl/sql code). It is accessible in java script code. what is the solution?</p>

```<code><table>
<tr>
<label>Total Credit</label> <input type="text" style="text-align:right;width:120px"  name="tot_credit" id="tot_credit" >
</tr>
</table>
</code>```

答: You can't access the item in PL/SQL because you have not defined the item in Apex. You need to define it as an Apex page item, instead of just writing the raw HTML for it.</p>

Body:
I have created a custom page item 'tot_credit' to get correct alignment below my tabular form report,  using the below code .
,it is written in the region 'footer text'.But I am unable to access this item 'tot_credit' inside my page process(pl/sql code). It is accessible in java script code. what is the solution?

Total Credit <input type="text" style="text-align:right;width:120px"  name="tot_credit" id="tot_credit" >


问:
Byte[] to String java 1.5
I am trying the below code :-

```<code>private Charset charset = Charset.forName("UTF-8");
String decryptedtext = new String(decryptedValue, charset);
</code>```

where decryptedValue is of type byte[] but the above code is not working for java 1.5 version. I am getting the error as below :-

```<code>> ERROR: symbol : constructor String(byte[],java.nio.charset.Charset)
> ERROR: location: class java.lang.String
> ERROR: String decryptedtext = new String(decryptedValue, charset);
> ERROR: ^
</code>```

Can anyone help me on this ?

Apologies in advance if this is a repetitive or duplicate question.

答:
There is no String(byte[], Charset) constructor in Java 5. You can only use String(byte[], String). Then your code should look like:

```<code>String s = new String(decryptedValue, "UTF-8");
</code>```

Title: Byte[] to String java 1.5

Body:
I am trying the below code :-

private Charset charset = Charset.forName("UTF-8");
String decryptedtext = new String(decryptedValue, charset);

where decryptedValue is of type byte[] but the above code is not working for java 1.5 version. I am getting the error as below :-

> ERROR: symbol : constructor String(byte[],java.nio.charset.Charset)
> ERROR: location: class java.lang.String
> ERROR: String decryptedtext = new String(decryptedValue, charset);
> ERROR: ^

Can anyone help me on this ?

Apologies in advance if this is a repetitive or duplicate question.

Body:
There is no String(byte[], Charset) constructor in Java 5. You can only use String(byte[], String). Then your code should look like:

String s = new String(decryptedValue, "UTF-8");


问:
Framework for user defined relationships
I'm thinking about creating a Django-powered website where users would be able to relate entities to each other. Examples would for instance include: "John is married to Mary" or "John works at Google".

Users should be able to define the entities and their relationships themselves (and will typically define relations of other people, not of themselves). Ideally, users enter these relations as free text (where subject and object could perhaps be an autocomplete field, based on previously entered existing entities).

Django's model framework is ideal for storing the entities and their relations, but how would one make such a thing manageable on a higher level?

Is there a Python-powered ontological framework (thanks duffymo) that would help me derive structure out of these user-generated relationships? I'm looking for ways to for example derive reversible relations, aggregate relations (e.g. "3 persons are family relations of John"), classify into types of relations (family relations, work relations, ...), and this all based on user generated input and not a (known) predefined set of relations. It

Thanks in advance,

Mathieu

答:
Users are able to define the relationships themselves (and will typically define relations of other people, not of themselves);

Fine.

there is in other words no pre-defined set of possible relations.

So?  This isn't an interesting constraint.  Why mention it?

Ideally, users enter these relations as free text (where subject and object could perhaps be an autocomplete field).

Fine.

```<code> class Person( models.Model ):
     # whatever

 class RelatedTo( models.Model ):
     one_person= models.ForeignKey( Person, related_name="me" )
     other_person= models.ForeignKey( Person, related_name="them" )
     relationship = models.TextField( )
</code>```

That's one way to do it.  It's not difficult if you make the "relationship" a first-class object.

If you want multi-party relationships, it works like this.

```<code> class Person( models.Model ):
     # whatever

 class RelatedTo( models.Model ):
     relationship_type = models.TextField( )

 class Party( models.Model ):
     relationship = ForeignKeyField( RelatedTo )
     role = models.TextField()
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Users are able to define the relationships themselves (and will typically define relations of other people, not of themselves);

Fine.

there is in other words no pre-defined set of possible relations.

So?  This isn't an interesting constraint.  Why mention it?

Ideally, users enter these relations as free text (where subject and object could perhaps be an autocomplete field).

Fine.

 class Person( models.Model ):
     # whatever

 class RelatedTo( models.Model ):
     one_person= models.ForeignKey( Person, related_name="me" )
     other_person= models.ForeignKey( Person, related_name="them" )
     relationship = models.TextField( )

That's one way to do it.  It's not difficult if you make the "relationship" a first-class object.

If you want multi-party relationships, it works like this.

 class Person( models.Model ):
     # whatever

 class RelatedTo( models.Model ):
     relationship_type = models.TextField( )

 class Party( models.Model ):
     relationship = ForeignKeyField( RelatedTo )
     role = models.TextField()


问:
show alertController from a custom class
I'm trying to show an AlertController from a class that I've made.
Since AlertController is a subclass of UIResponder I'm using the following line of code that Xcode is suggesting me

```<code>superclass?.presentViewController(alertController, animated: true, completion: nil)
</code>```

But I cannot compile because AnyClass? does not have any member presentViewController.
My class is a subclass of NSObject.

Any other solution?
Thanks

答:
Latest Swift:</p>

```<code>    var topController:UIViewController = UIApplication.shared.keyWindow!.rootViewController!
    while ((topController.presentedViewController) != nil) {
        topController = topController.presentedViewController!;
    }
    topController.present(alertController, animated:true, completion:nil)
</code>```

Body:
I'm trying to show an AlertController from a class that I've made.
Since AlertController is a subclass of UIResponder I'm using the following line of code that Xcode is suggesting me

superclass?.presentViewController(alertController, animated: true, completion: nil)

But I cannot compile because AnyClass? does not have any member presentViewController.
My class is a subclass of NSObject.

Any other solution?
Thanks

Body:
Latest Swift:

    var topController:UIViewController = UIApplication.shared.keyWindow!.rootViewController!
    while ((topController.presentedViewController) != nil) {
        topController = topController.presentedViewController!;
    }
    topController.present(alertController, animated:true, completion:nil)


问:
how can i find out that a user is joined to a telegram channel?
i want when a user is joined to my channel , receive a
    notification or a text message from my bot .how can i do that?i cannot find
    something in telegram API. best wishes... .</p>

答: You can't get notification when user joined your channel, but you can use getChatMembersCount to know someone joined.


问:
using browserify-css with grunt
I currently have grunt-browserify to build a few js files into a bundle. I'm trying to add css into the bundle via require('./style.css'). I've been researching some options to do this and found the browserify-css library (https://www.npmjs.com/package/browserify-css). However there is no grunt support so I'm not sure how to add this to my existing grunt settings.

It seems that I need to add browserify-css as a transform option. The grunt-browserify says that the transform option takes an array of tasks (see below). However, I don't think browserify-css can be written as a grunt task. What's the best practice in this situation?

```<code>    browserify: {
        dist: {
            files: {
                'dist/bundle.js': 'js/index.js'
            }
        },
        transform: ['coffeify']
    }
</code>```

答:
I checked the source code of browserify, and I found this solution:

```<code>browserify: {
    dist: {
      src: 'js/index.js',
      dest: 'dist/bundle.js'
    },
    options: {
        transform: [['browserify-css', { global: true }]]
    }
}
</code>```

This works for me when I need to copy css files from node_modules folder. For make it work you only need to run:

```<code>npm install browserify browserify-css grunt-browserify --save-dev
</code>```

and that's it!.

Title: using browserify-css with grunt

Body:
I currently have grunt-browserify to build a few js files into a bundle. I'm trying to add css into the bundle via require('./style.css'). I've been researching some options to do this and found the browserify-css library (https://www.npmjs.com/package/browserify-css). However there is no grunt support so I'm not sure how to add this to my existing grunt settings.

It seems that I need to add browserify-css as a transform option. The grunt-browserify says that the transform option takes an array of tasks (see below). However, I don't think browserify-css can be written as a grunt task. What's the best practice in this situation?

    browserify: {
        dist: {
            files: {
                'dist/bundle.js': 'js/index.js'
            }
        },
        transform: ['coffeify']
    }

Body:
I checked the source code of browserify, and I found this solution:

browserify: {
    dist: {
      src: 'js/index.js',
      dest: 'dist/bundle.js'
    },
    options: {
        transform: [['browserify-css', { global: true }]]
    }
}

This works for me when I need to copy css files from node_modules folder. For make it work you only need to run:

npm install browserify browserify-css grunt-browserify --save-dev

and that's it!.


问:
python selenium unable to click on a tag
I'm trying to click on this button shown below named “Segment Metrix 2.0 Consumer Target Profile report“

and I found corresponding HTML as shown below.

I tried to write code as below:

```<code>elem = driver.find_elements_by_xpath("//*[contains(text(), 'Segment Metrix 2.0 Consumer Target Profile report ')]")
print (elem)
</code>```

it gives me:

```<code>[<selenium.webdriver.remote.webelement.WebElement (session="daf65f4e5ed0485027d04eed8db8aca7", element="0.8079987809618281-1")>]
</code>```

But I can't click on it by adding elem[0].click(), it throws me an "element not visible" error. What should I do?

答:
Try to wait until element become visible:</p>

```<code>from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as wait

wait(driver, 10).until(EC.visibility_of_element_located((By.LINK_TEXT, "Segment Metrix 2.0 Consumer Target Profile report"))).click()
</code>```

Body:
I'm trying to click on this button shown below named “Segment Metrix 2.0 Consumer Target Profile report“

and I found corresponding HTML as shown below.

I tried to write code as below:

elem = driver.find_elements_by_xpath("//*[contains(text(), 'Segment Metrix 2.0 Consumer Target Profile report ')]")
print (elem)

it gives me:

[<selenium.webdriver.remote.webelement.WebElement (session="daf65f4e5ed0485027d04eed8db8aca7", element="0.8079987809618281-1")>]

But I can't click on it by adding elem[0].click(), it throws me an "element not visible" error. What should I do?

Body:
Try to wait until element become visible:

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as wait

wait(driver, 10).until(EC.visibility_of_element_located((By.LINK_TEXT, "Segment Metrix 2.0 Consumer Target Profile report"))).click()


问:
Java for loop exceeds limits. Android
I'm doing a project in Android Studio and am getting a null pointer exception when I definitely shouldn't be. Here is the problem code:

```<code>public class PlayActivity extends AppCompatActivity{
boolean[][] cellClicked = new boolean[3][3];
boolean player1 = false;
boolean player2 = true;
boolean currentPlayer;
ImageView[][] cells = new ImageView[3][3];

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) throws NullPointerException{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_play);
    currentPlayer = player1;
    cells[0][0] = (ImageView) findViewById(R.id.cell_0);
    cells[0][1] = (ImageView) findViewById(R.id.cell_1);
    cells[0][2] = (ImageView) findViewById(R.id.cell_2);
    cells[1][0] = (ImageView) findViewById(R.id.cell_3);
    cells[1][1] = (ImageView) findViewById(R.id.cell_4);
    cells[1][2] = (ImageView) findViewById(R.id.cell_5);
    cells[2][0] = (ImageView) findViewById(R.id.cell_6);
    cells[2][1] = (ImageView) findViewById(R.id.cell_7);
    cells[2][2] = (ImageView) findViewById(R.id.cell_8);

    try {
        for(int i = 0; i < 3; i++) {
            for(int j = 0; i < 3; j++) {
                setListeners(i, j);
            }
        }
    } catch(NullPointerException e){
        throw new NullPointerException("cant access element");
    }

}
private void setListeners(int i, int j){
    final int row = i;
    final int col = j;
    cells[row][col].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!cellClicked[row][col]) {
                makeMove(cells[row][col], row, col);
            }
        }
    });
}
</code>```

When I run the app, as soon as I navigate to PlayActivity, the app crashes. When I look at the log errors, it shows:

```<code>FATAL EXCEPTION: main
 Process: net.drmcb.tictactoe, PID: 29345
 java.lang.RuntimeException: Unable to start activity ComponentInfo{net.drmcb.tictactoe/net.drmcb.tictactoe.PlayActivity}: java.lang.ArrayIndexOutOfBoundsException: length=3; index=3
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
     at android.app.ActivityThread.-wrap14(ActivityThread.java)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:154)
     at android.app.ActivityThread.main(ActivityThread.java:6682)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
  Caused by: java.lang.ArrayIndexOutOfBoundsException: length=3; index=3
     at net.drmcb.tictactoe.PlayActivity.setListeners(PlayActivity.java:55)
     at net.drmcb.tictactoe.PlayActivity.onCreate(PlayActivity.java:44)
     at android.app.Activity.performCreate(Activity.java:6942)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2880)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
     at android.app.ActivityThread.-wrap14(ActivityThread.java)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:154)
     at android.app.ActivityThread.main(ActivityThread.java:6682)
     at java.lang.reflect.Method.invoke(Native Method)
</code>```

The lines the errors are referring to are 44: setListeners(i, j); and  55:

```<code>cells[row][col].setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (!cellClicked[row][col]) {
            makeMove(cells[row][col], row, col);
        }
    }
});
</code>```

I commented out all the code in makeMoves() so that's not the problem.

In my for loops encasing the call to setListeners(), the i < 3 part is highlighted and when I hover over it, it tells me "Condition 'i < 3' is always true"...

In attempting to debug this for the last several hours, I have the following questions:

Why does the for loop exceed it's i < 3 conditional?

Why does any reference to cells.length or cells[0].length break the code?

答:
it's not Null Exception, its an ArrayIndexOutOfBoundsException
because you have a mistake in your inner for loop

for(int j = 0; i < 3; j++) {

note the i<3 should be j<3

```<code>for(int j = 0; j < 3; j++) {
</code>```

Title: Java for loop exceeds limits. Android

Body:
I'm doing a project in Android Studio and am getting a null pointer exception when I definitely shouldn't be. Here is the problem code:

public class PlayActivity extends AppCompatActivity{
boolean[][] cellClicked = new boolean[3][3];
boolean player1 = false;
boolean player2 = true;
boolean currentPlayer;
ImageView[][] cells = new ImageView[3][3];

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) throws NullPointerException{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_play);
    currentPlayer = player1;
    cells[0][0] = (ImageView) findViewById(R.id.cell_0);
    cells[0][1] = (ImageView) findViewById(R.id.cell_1);
    cells[0][2] = (ImageView) findViewById(R.id.cell_2);
    cells[1][0] = (ImageView) findViewById(R.id.cell_3);
    cells[1][1] = (ImageView) findViewById(R.id.cell_4);
    cells[1][2] = (ImageView) findViewById(R.id.cell_5);
    cells[2][0] = (ImageView) findViewById(R.id.cell_6);
    cells[2][1] = (ImageView) findViewById(R.id.cell_7);
    cells[2][2] = (ImageView) findViewById(R.id.cell_8);

    try {
        for(int i = 0; i < 3; i++) {
            for(int j = 0; i < 3; j++) {
                setListeners(i, j);
            }
        }
    } catch(NullPointerException e){
        throw new NullPointerException("cant access element");
    }

}
private void setListeners(int i, int j){
    final int row = i;
    final int col = j;
    cells[row][col].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!cellClicked[row][col]) {
                makeMove(cells[row][col], row, col);
            }
        }
    });
}

When I run the app, as soon as I navigate to PlayActivity, the app crashes. When I look at the log errors, it shows:

FATAL EXCEPTION: main
 Process: net.drmcb.tictactoe, PID: 29345
 java.lang.RuntimeException: Unable to start activity ComponentInfo{net.drmcb.tictactoe/net.drmcb.tictactoe.PlayActivity}: java.lang.ArrayIndexOutOfBoundsException: length=3; index=3
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
     at android.app.ActivityThread.-wrap14(ActivityThread.java)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:154)
     at android.app.ActivityThread.main(ActivityThread.java:6682)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
  Caused by: java.lang.ArrayIndexOutOfBoundsException: length=3; index=3
     at net.drmcb.tictactoe.PlayActivity.setListeners(PlayActivity.java:55)
     at net.drmcb.tictactoe.PlayActivity.onCreate(PlayActivity.java:44)
     at android.app.Activity.performCreate(Activity.java:6942)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2880)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
     at android.app.ActivityThread.-wrap14(ActivityThread.java)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:154)
     at android.app.ActivityThread.main(ActivityThread.java:6682)
     at java.lang.reflect.Method.invoke(Native Method)

The lines the errors are referring to are 44: setListeners(i, j); and  55:

cells[row][col].setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (!cellClicked[row][col]) {
            makeMove(cells[row][col], row, col);
        }
    }
});

I commented out all the code in makeMoves() so that's not the problem.

In my for loops encasing the call to setListeners(), the i < 3 part is highlighted and when I hover over it, it tells me "Condition 'i < 3' is always true"...

In attempting to debug this for the last several hours, I have the following questions:

Why does the for loop exceed it's i < 3 conditional?

Why does any reference to cells.length or cells[0].length break the code?

Body:
it's not Null Exception, its an ArrayIndexOutOfBoundsException
because you have a mistake in your inner for loop

for(int j = 0; i < 3; j++) {

note the i<3 should be j<3

for(int j = 0; j < 3; j++) {


问:
What's the magic of arrays in C#
```<code>int[] a = new int[5];
string[] b = new string[1];
</code>```

The types of both a and b inherit from the abstract System.Array, but there is no real classes in the built-in library(it seems that there are some runtime types, you can't find the type defination class of an int[]). Can you tell me what happens while compiling? And why did they(the c# team) make this design(I mean why it's not something like Array<T>,instead they are using an abstract class with compiler magics)?

答: I would recommend getting the ECMA 335 spec and looking for Arrays if you want to know the low level detail: http://www.ecma-international.org/publications/standards/Ecma-335.htm</p>

Title: What's the magic of arrays in C#

Body:
int[] a = new int[5];
string[] b = new string[1];

The types of both a and b inherit from the abstract System.Array, but there is no real classes in the built-in library(it seems that there are some runtime types, you can't find the type defination class of an int[]). Can you tell me what happens while compiling? And why did they(the c# team) make this design(I mean why it's not something like Array<T>,instead they are using an abstract class with compiler magics)?


问:
Why Umbraco replace hostname/subdomain in external link
I am using webforms with Umbraco 7.6.3 I have simple menu(not using template)  on my master page (/masterpages/Master.master) like this:

```<code>     <li class="dropdown">
        <a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown">Home</a>
          <ul class="dropdown-menu">
                 <li><a runat="server" href="https://sub1.test.mywebsite">Home</a></li>
           </ul>
     </li>
</code>```

if I don't add www In href Umbraco replace hostname/subdomain.
Am I missing any setting?

答: Uhm. You have to have a protocol, like http or https, in front of your link. So https://www.google.com is a valid link.</p>

Body:
I am using webforms with Umbraco 7.6.3 I have simple menu(not using template)  on my master page (/masterpages/Master.master) like this:

        Home

Home

if I don't add www In href Umbraco replace hostname/subdomain.
Am I missing any setting?


问:
PHP script only executing from command line when command is run from script's directory
I am trying to run this script from the command line:

```<code>#!/usr/local/bin/php
<?php
$myfile = fopen("cc.log", "a") or die("Unable to open file!");
$txt = "Success \n";
fwrite($myfile, $txt);
fclose($myfile);
?>
</code>```

And it works, but only when I cd into the directory of the script and run:

```<code>/usr/local/bin/php test_script.php
</code>```

This also works:

```<code>/usr/local/bin/php /home/<username>/public_html/test_script.php
</code>```

but not when I leave the directory.

答:
Solved by changing line 3 of test_script.php from:

```<code>$myfile = fopen("cc.log", "a") or die("Unable to open file!");
</code>```

to an absolute path:

```<code>$myfile = fopen("/home/<username>/public_html/cc.log", "a") or die("Unable to open file!");
</code>```

The original script created a cc.log file in the directory from where the command was called and appended about 50 "Success" messages xD

Body:
I am trying to run this script from the command line:

#!/usr/local/bin/php
<?php
$myfile = fopen("cc.log", "a") or die("Unable to open file!");
$txt = "Success \n";
fwrite($myfile, $txt);
fclose($myfile);
?>

And it works, but only when I cd into the directory of the script and run:

/usr/local/bin/php test_script.php

This also works:

/usr/local/bin/php /home/<username>/public_html/test_script.php

but not when I leave the directory.

Body:
Solved by changing line 3 of test_script.php from:

$myfile = fopen("cc.log", "a") or die("Unable to open file!");

to an absolute path:

$myfile = fopen("/home/<username>/public_html/cc.log", "a") or die("Unable to open file!");

The original script created a cc.log file in the directory from where the command was called and appended about 50 "Success" messages xD


问:
Print response json in jmeter using beanshell
I want print my json response in jmeter. I used beanshell but it shows error. Below is the line to print json object extracted in "data":</p>

```<code>log.info("========"+${data});
</code>```

答:
Don't ever inline JMeter Functions or Variables into scripts, they may resolve into something which will cause compilation/interpretation failure, use code-based equivalents instead or pass functions/variables via "Parameters" section.

Exhibit A: using vars shorthand

```<code>log.info("========" + vars.get("data"));
</code>```

Exhibit B: using "Parameters" section

Using Beanshell isn't the best scripting option, consider migrating to JSR223 Elements and Groovy language as Beanshell has known performance problems. Moreover, Groovy has built-in JSON support  See Apache Groovy - Why and How You Should Use It for details.

And finally your ${data} variable might not be defined (i.e. your extractor fails), in this case you will get interpretation failure on attempt to refer it as ${data}, double check its value using Debug Sampler and View Results Tree listener combination.

Body:
I want print my json response in jmeter. I used beanshell but it shows error. Below is the line to print json object extracted in "data":

log.info("========"+${data});

Body:
Don't ever inline JMeter Functions or Variables into scripts, they may resolve into something which will cause compilation/interpretation failure, use code-based equivalents instead or pass functions/variables via "Parameters" section.

Exhibit A: using vars shorthand

log.info("========" + vars.get("data"));

Exhibit B: using "Parameters" section

Using Beanshell isn't the best scripting option, consider migrating to JSR223 Elements and Groovy language as Beanshell has known performance problems. Moreover, Groovy has built-in JSON support  See Apache Groovy - Why and How You Should Use It for details.

And finally your ${data} variable might not be defined (i.e. your extractor fails), in this case you will get interpretation failure on attempt to refer it as ${data}, double check its value using Debug Sampler and View Results Tree listener combination.


问:
Dagger2 How to @Provide one type with two different implementations
I'm very new to Dagger2 just starting. I want to achieve something like this but no success.

Here is my module

```<code>@Module
public class UtilModule
{
    @Provides
    @Named("fragmentUtilActivity")
    public FragmentUtils providesFragmentUtilForActivity(Context context)
    {
        return new FragmentUtils(context);
    }

    @Provides
    @Named("fragmentUtilFragment")
    FragmentUtils providesFragmentUtilForFragment(Fragment fragment)
    {
        return new FragmentUtils(fragment);
    }

}
</code>```

And this is my component

```<code>@Component(modules = UtilModule.class)
public interface UtilComponent
{
    @Named("fragmentUtilActivity")
    FragmentUtils fragmentUtilsActivity(Context context);

    @Named("fragmentUtilFragment")
    FragmentUtils fragmentUtilsFragment(Fragment fragment);
}
</code>```

And this is my FragmentUtil class

```<code>package myms.utils;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;

import javax.inject.Inject;

import myms.R;

public class FragmentUtils
{
    private Context context;

    private Fragment hostFragment;

    public FragmentUtils(Context context)
    {
        this.context = context;
    }

    public FragmentUtils(Fragment hostFragment)
    {
        this.hostFragment = hostFragment;
    }

    public void addFragment(Fragment fragment, boolean addToBackStack)
    {
        FragmentTransaction transaction = ((Activity) context).getFragmentManager()
                                                              .beginTransaction();
        transaction.add(R.id.fragment_container, fragment, null);

        if(addToBackStack)
        {
            transaction.addToBackStack(null);
        }

        transaction.commit();
    }

    public void addNestedFragment(Fragment fragment, boolean addToBackStack)
    {
        FragmentTransaction transaction = hostFragment.getChildFragmentManager().beginTransaction();
        transaction.add(R.id.nested_fragment_container, fragment, null);

        if(addToBackStack)
        {
            transaction.addToBackStack(null);
        }

        transaction.commit();
    }

    public void replaceNestedFragment(Fragment fragment, boolean addToBackStack)
    {
        FragmentTransaction transaction = hostFragment.getChildFragmentManager().beginTransaction();
        transaction.replace(R.id.nested_fragment_container, fragment, null);

        if(addToBackStack)
        {
            transaction.addToBackStack(null);
        }

        transaction.commit();
    }
}
</code>```

What i want is to use the instance of fragmentUtils with two different implementation One is for activity and other for fragment. Please guide me what am i doing wrong.

Also can some one please help me understand the purpose of void inject(SomeClass) in @Component interface.

Regards

答:
Okay after trying hard i'm able to solve it by modifying my UtilMoudle class

```<code>package myms.modules;

import android.app.Fragment;
import android.content.Context;

import javax.inject.Named;

import dagger.Module;
import dagger.Provides;
import myms.utils.FragmentUtils;

@Module
public class UtilModule
{
    private Context context;

    private Fragment fragment;

    public UtilModule(Context context)
    {
        this.context = context;
    }

    public UtilModule(Fragment fragment)
    {
        this.fragment = fragment;
    }

    @Provides
    @Named("fragmentUtilActivity")
    public FragmentUtils providesFragmentUtilForActivity(Context context)
    {
        return new FragmentUtils(context);
    }

    @Provides
    @Named("fragmentUtilFragment")
    FragmentUtils providesFragmentUtilForFragment(Fragment fragment)
    {
        return new FragmentUtils(fragment);
    }

    @Provides
    Context provideContext()
    {
        return context;
    }

    @Provides
    Fragment provideFragment()
    {
        return fragment;
    }

}
</code>```

so basically i have to provide the dependencies for my methods like context and fragment in my case. Then finally to get the instance i have to do like this. For example for activity

```<code>UtilComponent component = DaggerUtilComponent.builder()
                                                     .utilModule(new UtilModule(this))
                                                     .build();
        FragmentUtils fragmentUtils = component.fragmentUtilsActivity();
</code>```

Please note .utilModule(new UtilModule(this)) as this will provide the context while building the graph.

I'm very new into this Dagger thing so please use this approach with care. No warranties / No claims applicable. Happy Daggering :)

Body:
I'm very new to Dagger2 just starting. I want to achieve something like this but no success.

Here is my module

@Module
public class UtilModule
{
    @Provides
    @Named("fragmentUtilActivity")
    public FragmentUtils providesFragmentUtilForActivity(Context context)
    {
        return new FragmentUtils(context);
    }

    @Provides
    @Named("fragmentUtilFragment")
    FragmentUtils providesFragmentUtilForFragment(Fragment fragment)
    {
        return new FragmentUtils(fragment);
    }

}

And this is my component

@Component(modules = UtilModule.class)
public interface UtilComponent
{
    @Named("fragmentUtilActivity")
    FragmentUtils fragmentUtilsActivity(Context context);

    @Named("fragmentUtilFragment")
    FragmentUtils fragmentUtilsFragment(Fragment fragment);
}

And this is my FragmentUtil class

package myms.utils;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;

import javax.inject.Inject;

import myms.R;

public class FragmentUtils
{
    private Context context;

    private Fragment hostFragment;

    public FragmentUtils(Context context)
    {
        this.context = context;
    }

    public FragmentUtils(Fragment hostFragment)
    {
        this.hostFragment = hostFragment;
    }

    public void addFragment(Fragment fragment, boolean addToBackStack)
    {
        FragmentTransaction transaction = ((Activity) context).getFragmentManager()
                                                              .beginTransaction();
        transaction.add(R.id.fragment_container, fragment, null);

        if(addToBackStack)
        {
            transaction.addToBackStack(null);
        }

        transaction.commit();
    }

    public void addNestedFragment(Fragment fragment, boolean addToBackStack)
    {
        FragmentTransaction transaction = hostFragment.getChildFragmentManager().beginTransaction();
        transaction.add(R.id.nested_fragment_container, fragment, null);

        if(addToBackStack)
        {
            transaction.addToBackStack(null);
        }

        transaction.commit();
    }

    public void replaceNestedFragment(Fragment fragment, boolean addToBackStack)
    {
        FragmentTransaction transaction = hostFragment.getChildFragmentManager().beginTransaction();
        transaction.replace(R.id.nested_fragment_container, fragment, null);

        if(addToBackStack)
        {
            transaction.addToBackStack(null);
        }

        transaction.commit();
    }
}

What i want is to use the instance of fragmentUtils with two different implementation One is for activity and other for fragment. Please guide me what am i doing wrong.

Also can some one please help me understand the purpose of void inject(SomeClass) in @Component interface.

Regards

Body:
Okay after trying hard i'm able to solve it by modifying my UtilMoudle class

package myms.modules;

import android.app.Fragment;
import android.content.Context;

import javax.inject.Named;

import dagger.Module;
import dagger.Provides;
import myms.utils.FragmentUtils;

@Module
public class UtilModule
{
    private Context context;

    private Fragment fragment;

    public UtilModule(Context context)
    {
        this.context = context;
    }

    public UtilModule(Fragment fragment)
    {
        this.fragment = fragment;
    }

    @Provides
    @Named("fragmentUtilActivity")
    public FragmentUtils providesFragmentUtilForActivity(Context context)
    {
        return new FragmentUtils(context);
    }

    @Provides
    @Named("fragmentUtilFragment")
    FragmentUtils providesFragmentUtilForFragment(Fragment fragment)
    {
        return new FragmentUtils(fragment);
    }

    @Provides
    Context provideContext()
    {
        return context;
    }

    @Provides
    Fragment provideFragment()
    {
        return fragment;
    }

}

so basically i have to provide the dependencies for my methods like context and fragment in my case. Then finally to get the instance i have to do like this. For example for activity

UtilComponent component = DaggerUtilComponent.builder()
                                                     .utilModule(new UtilModule(this))
                                                     .build();
        FragmentUtils fragmentUtils = component.fragmentUtilsActivity();

Please note .utilModule(new UtilModule(this)) as this will provide the context while building the graph.

I'm very new into this Dagger thing so please use this approach with care. No warranties / No claims applicable. Happy Daggering :)


问:
remove trailing slashes from .html but add trailing slash to everything else
I have an .htaccess task I can't accomplish. I need all pages ending in .html/ redirect to .html . All other pages must end with a trailing slash. And finally, these rules must not affect /adminstrator/ page. Can anyone help me with that?

Thanks.

答:
Just found a solution myself. Thanks :)

```<code>RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+).html/ http://somedomain.com/$1\.html [R=301,L]
RewriteCond %{REQUEST_URI} !^/administrator/
RewriteCond %{REQUEST_URI}  !\.(php|html?|jpg|gif)$
RewriteRule ^(.*)([^/])$ http://%{HTTP_HOST}/$1$2/ [L,R=301]
RewriteCond %{REQUEST_URI} !^/administrator/
RewriteCond %{REQUEST_FILENAME} !-d
</code>```

Couldn't do it before, because needed to exclude the /administrator/ rule twice

Body:
Just found a solution myself. Thanks :)

RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+).html/ http://somedomain.com/$1\.html [R=301,L]
RewriteCond %{REQUEST_URI} !^/administrator/
RewriteCond %{REQUEST_URI}  !\.(php|html?|jpg|gif)$
RewriteRule ^(.*)([^/])$ http://%{HTTP_HOST}/$1$2/ [L,R=301]
RewriteCond %{REQUEST_URI} !^/administrator/
RewriteCond %{REQUEST_FILENAME} !-d

Couldn't do it before, because needed to exclude the /administrator/ rule twice


问:
array value not being properly emptied on a button click
The goal I am trying to achieved is that when one of the two buttons(btn 1 or btn 2) are clicked the array needs to reset(emptied) and when button add is clicked value 1 needs to be pushed to the array. Here is what I came up so far:

$(document).ready(function(){
   var array = []
   $("#btn_1").click(function(){
       array = []
       add_to_array(array);
   })
   $("#btn_2").click(function(){
       array = []
       add_to_array(array);
   })
})

function add_to_array(array){

    $("#add").click(function(){

     array.push(1)
     alert(array)
   })
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn_1">
empty array: btn 1
</button>

<button id="btn_2">
empty array: btn 2
</button>

<button id="add">
Add
</button></code>```

The problem I am facing: when I click either btn 1 or btn 2 more than once followed by add button, alert shows up the number of times I clicked btn1 or btn 2.

What I am looking for instead is, no matter how many times I click either btn 1 or btn2 I want alert two show up only once. Do you think what I am trying to achieve is achievable?

答:
You can use .off('click') function to bind your event only once to add button.

$(document).ready(function(){
   var array = []
   $("#btn_1").click(function(){
       array = []
       add_to_array(array);
   })
   $("#btn_2").click(function(){
       array = []
       add_to_array(array);
   })
})

function add_to_array(array){

    $("#add").off('click').click(function(){
     array.push(1)
     alert(array)
   })
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn_1">
empty array: btn 1
</button>

<button id="btn_2">
empty array: btn 2
</button>

<button id="add">
Add
</button></code>```

Body:
The goal I am trying to achieved is that when one of the two buttons(btn 1 or btn 2) are clicked the array needs to reset(emptied) and when button add is clicked value 1 needs to be pushed to the array. Here is what I came up so far:

$(document).ready(function(){
   var array = []
   $("#btn_1").click(function(){
       array = []
       add_to_array(array);
   })
   $("#btn_2").click(function(){
       array = []
       add_to_array(array);
   })
})

function add_to_array(array){

    $("#add").click(function(){

     array.push(1)
     alert(array)
   })
}

<button id="btn_1">
empty array: btn 1
</button>

<button id="btn_2">
empty array: btn 2
</button>

<button id="add">
Add
</button>

The problem I am facing: when I click either btn 1 or btn 2 more than once followed by add button, alert shows up the number of times I clicked btn1 or btn 2.

What I am looking for instead is, no matter how many times I click either btn 1 or btn2 I want alert two show up only once. Do you think what I am trying to achieve is achievable?

Body:
You can use .off('click') function to bind your event only once to add button.

$(document).ready(function(){
   var array = []
   $("#btn_1").click(function(){
       array = []
       add_to_array(array);
   })
   $("#btn_2").click(function(){
       array = []
       add_to_array(array);
   })
})

function add_to_array(array){

    $("#add").off('click').click(function(){
     array.push(1)
     alert(array)
   })
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn_1">
empty array: btn 1
</button>

<button id="btn_2">
empty array: btn 2
</button>

<button id="add">
Add
</button>


问:
swift pull to refresh
i have my refreshcontroller with a scrollview..

```<code>  self.refreshControl = UIRefreshControl()
        self.refreshControl.attributedTitle = NSAttributedString(string: "Frissítéshez húzzad! :)")
        self.refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
        self.scrollView.addSubview(refreshControl)

func refresh(sender:AnyObject)
    {

//my refresh code here..

            self.refreshControl.endRefreshing()
    }
</code>```

I'm adding as a subview to a scrollView. It's working when the page content is overflowing the screen. but the issue arise  when i haven't received much data and it's not overflowing, the pull and refresh function is not working. :(

I'm not using tableview.

Can anybody help me how to solve this problem?

答:
Yes We can use refresh control to UIScrollView, UITableview, UicollectionVIew..

Here is the code for PULL TO REFRESH,

```<code>var refreshControl: UIRefreshControl!
override func viewDidLoad()  {
    super.viewDidLoad()

    scrollView.alwaysBounceVertical = true
    scrollView.bounces  = true
    refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action: #selector(didPullToRefresh), for: .valueChanged)
    self.scrollView.addSubview(refreshControl)
 }

@objc func didPullToRefresh() {

   print("Refersh")

  // For End refrshing
  refreshControl?.endRefreshing()

 }
</code>```

Title: swift pull to refresh

Body:
i have my refreshcontroller with a scrollview..

  self.refreshControl = UIRefreshControl()
        self.refreshControl.attributedTitle = NSAttributedString(string: "Frissítéshez húzzad! :)")
        self.refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
        self.scrollView.addSubview(refreshControl)

func refresh(sender:AnyObject)
    {

//my refresh code here..

            self.refreshControl.endRefreshing()
    }

I'm adding as a subview to a scrollView. It's working when the page content is overflowing the screen. but the issue arise  when i haven't received much data and it's not overflowing, the pull and refresh function is not working. :(

I'm not using tableview.

Can anybody help me how to solve this problem?

Body:
Yes We can use refresh control to UIScrollView, UITableview, UicollectionVIew..

Here is the code for PULL TO REFRESH,

var refreshControl: UIRefreshControl!
override func viewDidLoad()  {
    super.viewDidLoad()

    scrollView.alwaysBounceVertical = true
    scrollView.bounces  = true
    refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action: #selector(didPullToRefresh), for: .valueChanged)
    self.scrollView.addSubview(refreshControl)
 }

@objc func didPullToRefresh() {

   print("Refersh")

  // For End refrshing
  refreshControl?.endRefreshing()

 }

ContentLicense: CC BY-SA 4.0


问:
Multiple Activity or Single Activity and multiple fragments
I have one very general question, I did not find a concrete answer for my question hence putting it again.

I want to decide between two approaches

Dedicated activities for various various screens and tasks to avoid complexity and issues

Single Activities and multiple fragments for different tasks and user can navigate like Activity holding Fragment A user will navigate to Fragment B, Fragment C , this can be back and forth transaction.

What I want to know?

Is Activity transition is that costly for processor or to achieve simplicity memory overhead is negligible ?

Fragment has overhead of managing life cycle with transition, so what all problem can come with this life cycler management?

How easy is to deal with fragment transaction with saving state of the fragment?

We don't know right now what amount data will be there for fragment to hold.

答:
My question is same, till now in my all app, there is only one Activity, and the rests are Fragments. I agree it is hard to maintain Fragment, but using Fragment will increase your Performance.

Suppose, take one example,

I have 10 Activities, in each Activity, I'm calling Async Task to perform some background operations. In each Async Task's onPostExecute() you are updating your UI. But before completing the doInBackground() you switched the Activity and that Activity is destroyed, but remember the doInBackground() is still in progress, and once it is finished, onPostExecute will be called, and in onPostExecute() we are updating the UI, but the Activity is destroyed, so this will create a leak in your app.
But if you are maintaining only one Activity then it will be easy to maintain.

Waiting for others opinion also.


问:
OData-Client: How to Reset Link on new entity
I consume a OData-Service with the WCF OData client. In my application when an entity is created, a linked property is set by default to an object:

var defaultPackage = _service.GetDefaultPackage();
var newCar = new Car
{
    Key = "Unique identifier",
    Package = defaultPackage,
    Name = _name
};
_odata.AddToEntity(newCar);
_odata.SetLink(newCar, nameof(Car.Package), newCar.Package);
```

<p>Then the user can change the values of the car via an user interface. Changes of non primitive properties of instance are autransmitted to the service context. This is done automatically via the <code>INotifyPropertyChanged</code> interface of the <code>car</code> (This interface is automatically implemented for all entities by the odata code generator).
</p>

```private void PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    var car = (Car)sender;
    var newValue = GetPropertyValueByReflection(car, e.PropertyName);
    _odata.SetLink(car, e.PropertyName, newValue);
}
```

<p>Among other things the user can delete the package of the car. So the property <code>Package</code> gets the value <code>null</code>. </p>

<p>The problem with the solution is now, that the service context does not reset the link for <code>Package</code>, but transfers it at <code>_odata.SaveChanges(SaveChangesOptions.Batch)</code> to the server. This is the batch request:</p>

```--batch_0abebbdc-969a-475a-b1da-a94a1733c6ae
Content-Type: multipart/mixed; boundary=changeset_3e2db159-7696-44af-bb51-00d2f48ed944

--changeset_3e2db159-7696-44af-bb51-00d2f48ed944
Content-Type: application/http
Content-Transfer-Encoding: binary

POST http://some-url.to/odata/Cars/Car HTTP/1.1
Content-ID: 5
Content-Type: application/atom+xml
DataServiceVersion: 1.0;NetFx
MaxDataServiceVersion: 3.0;NetFx
Accept: application/atom+xml,application/xml
Accept-Charset: UTF-8
User-Agent: Microsoft ADO.NET Data Services

<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
    <id />
    <title />
    <updated>2017-06-21T10:58:55Z</updated>
    <author>
        <name />
    </author>
    <content type="application/xml">
        <m:properties>
            <d:Key>Unique identifier</d:Key>
            <d:Name>VW Caddy</d:Name>
        </m:properties>
    </content>
</entry>
--changeset_3e2db159-7696-44af-bb51-00d2f48ed944
Content-Type: application/http
Content-Transfer-Encoding: binary

DELETE $5/$links/Package HTTP/1.1
Content-ID: 10
DataServiceVersion: 1.0;NetFx
MaxDataServiceVersion: 3.0;NetFx
Accept: application/atom+xml,application/xml
Accept-Charset: UTF-8
User-Agent: Microsoft ADO.NET Data Services

--changeset_3e2db159-7696-44af-bb51-00d2f48ed944--
--batch_0abebbdc-969a-475a-b1da-a94a1733c6ae--
```

The server answers with an errer, because there is no link to be deleted. Does anybody know a solution for this problem as it is described here to use SetLink(source, propertyName, null) to remove the link.

答:
Finally I found a solution that now works for me. If the entity is new and there is a link set, SetLink(source, propertyName, null) cannot be used. Instead of that DetachLink(source, propertyName, oldTarget) must be used. I achieve this in the following way:

```<code>private void PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    var car = (Car)sender;
    var newValue = GetPropertyValueByReflection(car, e.PropertyName);
    object existingTarget;
    if ((newValue == null) && IsAdded(car) &&
         ThereExistsAnExistingLink(car, e.PropertyName, out existingTarget))
        _odata.DetachLink(car, e.PropertyName, existingTarget);
    else
        _odata.SetLink(car, e.PropertyName, newValue);
}

private bool IsAdded(object entity)
{
    return _odata.GetEntityDescriptor(entity).State.HasFlag(EntityStates.Added);
}

private bool ThereExistsAnExistingLink(object entity,
                                       string propertyName,
                                       out object existingTarget)
{
    var linkDescriptor = _context.Links.FirstOrDefault(
                           ld => ld.Source == _source &&
                                 ld.SourceProperty == _sourceProperty &&
                                !ld.HasStates(EntityStates.Detached)
                           );
    if (linkDescriptor != null)
    {
        existingTarget = linkDescriptor.Target;
        return true;
    }
    existingTarget = null;
    return false;
}
</code>```

Body:
I consume a OData-Service with the WCF OData client. In my application when an entity is created, a linked property is set by default to an object:

var defaultPackage = _service.GetDefaultPackage();
var newCar = new Car
{
    Key = "Unique identifier",
    Package = defaultPackage,
    Name = _name
};
_odata.AddToEntity(newCar);
_odata.SetLink(newCar, nameof(Car.Package), newCar.Package);

Then the user can change the values of the car via an user interface. Changes of non primitive properties of instance are autransmitted to the service context. This is done automatically via the INotifyPropertyChanged interface of the car (This interface is automatically implemented for all entities by the odata code generator).

private void PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    var car = (Car)sender;
    var newValue = GetPropertyValueByReflection(car, e.PropertyName);
    _odata.SetLink(car, e.PropertyName, newValue);
}

Among other things the user can delete the package of the car. So the property Package gets the value null.

The problem with the solution is now, that the service context does not reset the link for Package, but transfers it at _odata.SaveChanges(SaveChangesOptions.Batch) to the server. This is the batch request:

--batch_0abebbdc-969a-475a-b1da-a94a1733c6ae
Content-Type: multipart/mixed; boundary=changeset_3e2db159-7696-44af-bb51-00d2f48ed944

--changeset_3e2db159-7696-44af-bb51-00d2f48ed944
Content-Type: application/http
Content-Transfer-Encoding: binary

POST http://some-url.to/odata/Cars/Car HTTP/1.1
Content-ID: 5
Content-Type: application/atom+xml
DataServiceVersion: 1.0;NetFx
MaxDataServiceVersion: 3.0;NetFx
Accept: application/atom+xml,application/xml
Accept-Charset: UTF-8
User-Agent: Microsoft ADO.NET Data Services

<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
    <id />
    <title />
    <updated>2017-06-21T10:58:55Z</updated>
    <author>
        <name />
    </author>
    <content type="application/xml">
        <m:properties>
            <d:Key>Unique identifier</d:Key>
            <d:Name>VW Caddy</d:Name>
        </m:properties>
    </content>
</entry>
--changeset_3e2db159-7696-44af-bb51-00d2f48ed944
Content-Type: application/http
Content-Transfer-Encoding: binary

DELETE $5/$links/Package HTTP/1.1
Content-ID: 10
DataServiceVersion: 1.0;NetFx
MaxDataServiceVersion: 3.0;NetFx
Accept: application/atom+xml,application/xml
Accept-Charset: UTF-8
User-Agent: Microsoft ADO.NET Data Services

--changeset_3e2db159-7696-44af-bb51-00d2f48ed944--
--batch_0abebbdc-969a-475a-b1da-a94a1733c6ae--

The server answers with an errer, because there is no link to be deleted. Does anybody know a solution for this problem as it is described here to use SetLink(source, propertyName, null) to remove the link.

Body:
Finally I found a solution that now works for me. If the entity is new and there is a link set, SetLink(source, propertyName, null) cannot be used. Instead of that DetachLink(source, propertyName, oldTarget) must be used. I achieve this in the following way:

private void PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    var car = (Car)sender;
    var newValue = GetPropertyValueByReflection(car, e.PropertyName);
    object existingTarget;
    if ((newValue == null) && IsAdded(car) &&
         ThereExistsAnExistingLink(car, e.PropertyName, out existingTarget))
        _odata.DetachLink(car, e.PropertyName, existingTarget);
    else
        _odata.SetLink(car, e.PropertyName, newValue);
}

private bool IsAdded(object entity)
{
    return _odata.GetEntityDescriptor(entity).State.HasFlag(EntityStates.Added);
}

private bool ThereExistsAnExistingLink(object entity,
                                       string propertyName,
                                       out object existingTarget)
{
    var linkDescriptor = _context.Links.FirstOrDefault(
                           ld => ld.Source == _source &&
                                 ld.SourceProperty == _sourceProperty &&
                                !ld.HasStates(EntityStates.Detached)
                           );
    if (linkDescriptor != null)
    {
        existingTarget = linkDescriptor.Target;
        return true;
    }
    existingTarget = null;
    return false;
}


答:
This is what you need, i have just modified your code in jquery, Whenever the empty button click, it empties the array, only when add button is pressed it adds 1 to array and alerts.

array = [];
$(document).ready(function(){
    $("#btn_1").click(function(){
        array = []
      })
    $("#btn_2").click(function(){
        array = []
      })
    $("#add").click(function(){
        array.push(1)
        alert(array)
      })
  })
  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn_1">
empty array: btn 1
</button>

<button id="btn_2">
empty array: btn 2
</button>

<button id="add">
Add
</button></code>```

Hope this helps

Title: array value not being properly emptied on a button click

Body:
This is what you need, i have just modified your code in jquery, Whenever the empty button click, it empties the array, only when add button is pressed it adds 1 to array and alerts.

array = [];
$(document).ready(function(){
    $("#btn_1").click(function(){
        array = []
      })
    $("#btn_2").click(function(){
        array = []
      })
    $("#add").click(function(){
        array.push(1)
        alert(array)
      })
  })

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn_1">
empty array: btn 1
</button>

<button id="btn_2">
empty array: btn 2
</button>

<button id="add">
Add
</button>

Hope this helps


问:
SSDT projects and managing Integration tests with known data
I'm migrating over to SSDT for schema control of the DB structure for a large project with accompanying database. This project already has hundreds of integration tests inside of it that are in various states of brittleness. Many of these use what I would call "known data" to perform the integration tests with. The tests are relying on this data to be there for them to run successfully.

In the past, we've done a 1:1 copy of our integration test database for testing in feature branches, but i'm not wild about this process as it adds bloat to the server.

Using SSDT, is there a way to incorporate this "known data" into either a SSDT project, or a process that can be used to copy after the fact? I already have post-deploy scripts that load seed data into the system (types and the like), so I could put all known data there, but this could be dozens of extra sql files to potentially manage so i'm not wild about it.

Due to the complexities and the amount of known data, using the application sitting on top of the DB to insert it is not practical.

I was thinking about exploring a bacpac option, but before doing that wanted to see if there were any other ways people have managed integration testing of feature branches with known data in the past.

答:
There are a couple of approaches you could take:

Use backups/snapshots

Integration tests / test data in a separate .sqlproj / dacpac

Setup data as part of your tests

1. Use backups/snapshots

You could get a database in a known state and then use backups or snapshots. I am not a great fan of this as you always need to keep your base up to date or every now and then refresh it.

2. Integration tests / test data in a separate .sqlproj / dacpac

This is what I would usually do for unit tests (integration tests, for me, are normally in the language of the app that calls the database).

I would have a separate .sqlproj in my solution that has a "Same Database" reference to the main project. Put into this the integration tests and the Post-Deploy.sql for the test seed data.

If you have multiple files use ":r" imports to include those and also use an ":r" import to include the post-deploy from the main project as when the publish happens, dacpacs that are referenced do not have their pre/post-deploy scripts executed.

If you haven't used references like this before you deploy the test project and /p:IncludeCompositeObject=True

3. Setup data as part of your tests

This might be harder if you already have a large suite but I would normally advise that as part of the setup for each test that you get the data in a state that you know it is right for that test.

This way it stops any brittleness from running tests in different order etc.

I haven't looked at bacpac's for this, that might be an interesting way to deal with it as well.