问:
Hibernate "APPARENT DEADLOCK!!! Creating emergency threads for unassigned pending tasks!"
I recently got the following messages in our logs followed by a JVM crash (Due to OOME). I am not sure what to make of this and would really appreciate any guidance.

```<code>2015-03-19 21:15:02,457 [Timer-0] WARN  (ThreadPoolAsynchronousRunner.java [run]:608) - com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@6824f21c -- APPARENT DEADLOCK!!! Creating emergency threads for unassigned pending tasks!
2015-03-19 21:26:29,543 [Timer-0] WARN  (ThreadPoolAsynchronousRunner.java [run]:624) - com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@6824f21c -- APPARENT DEADLOCK!!! Complete Status:
    Managed Threads: 3
    Active Threads: 3
    Active Tasks:
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@15da1b6b (com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#2)
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@b35b08a (com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#1)
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@51cfdd17 (com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#0)
    Pending Tasks:
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@19397937
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@5c7d3838
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@7aea62dd
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@55622ff2
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@74004a8
Pool thread stack traces:
    Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#0,5,main]
        com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:560)
    Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#2,5,main]
        java.net.SocketOutputStream.socketWrite0(Native Method)
        java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109)
        java.net.SocketOutputStream.write(SocketOutputStream.java:153)
        java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
        java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
        com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3227)
        com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1917)
        com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2060)
        com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2536)
        com.mysql.jdbc.ConnectionImpl.configureClientCharacterSet(ConnectionImpl.java:1751)
        com.mysql.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:3425)
        com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2196)
        com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:718)
        com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
        sun.reflect.GeneratedConstructorAccessor306.newInstance(Unknown Source)
        sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        java.lang.reflect.Constructor.newInstance(Constructor.java:408)
        com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
        com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
        com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:282)
        com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:135)
        com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:182)
        com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:171)
        com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137)
        com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014)
        com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32)
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810)
        com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547)
    Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#1,5,main]
        com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:560)

2015-03-19 21:56:59,137 [Timer-0] WARN  (ThreadPoolAsynchronousRunner.java [run]:608) - com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@6824f21c -- APPARENT DEADLOCK!!! Creating emergency threads for unassigned pending tasks!
2015-03-19 21:56:59,143 [eXistThread-18676] ERROR (XQueryServlet.java [process]:566) - Java heap space
java.lang.OutOfMemoryError: Java heap space
    at org.exist.storage.btree.BTree$BTreeNode.read(BTree.java:1269)
    at org.exist.storage.btree.BTree$BTreeNode.access$16(BTree.java:1239)
    at org.exist.storage.btree.BTree.getBTreeNode(BTree.java:460)
    at org.exist.storage.btree.BTree.scanSequential(BTree.java:413)
    at org.exist.storage.btree.BTree$BTreeNode.scanNextPage(BTree.java:2039)
    at org.exist.storage.btree.BTree$BTreeNode.query(BTree.java:1835)
    at org.exist.storage.btree.BTree$BTreeNode.query(BTree.java:1759)
    at org.exist.storage.btree.BTree$BTreeNode.query(BTree.java:1759)
    at org.exist.storage.btree.BTree$BTreeNode.query(BTree.java:1759)
    at org.exist.storage.btree.BTree$BTreeNode.access$12(BTree.java:1734)
    at org.exist.storage.btree.BTree.query(BTree.java:379)
    at org.exist.storage.structural.NativeStructuralIndexWorker.scanByType(NativeStructuralIndexWorker.java:259)
    at org.exist.dom.VirtualNodeSet.getNodesFromIndex(VirtualNodeSet.java:457)
    at org.exist.dom.VirtualNodeSet.realize(VirtualNodeSet.java:585)
    at org.exist.dom.VirtualNodeSet.iterator(VirtualNodeSet.java:860)
    at org.exist.dom.AbstractNodeSet.iterator(AbstractNodeSet.java:1)
    at org.exist.storage.structural.NativeStructuralIndexWorker.findDescendantsByTagName(NativeStructuralIndexWorker.java:162)
    at org.exist.xquery.LocationStep.getAttributes(LocationStep.java:645)
    at org.exist.xquery.LocationStep.eval(LocationStep.java:434)
    at org.exist.xquery.AbstractExpression.eval(AbstractExpression.java:71)
    at org.exist.xquery.PathExpr.eval(PathExpr.java:264)
    at org.exist.xquery.Predicate.selectByNodeSet(Predicate.java:446)
    at org.exist.xquery.Predicate.evalPredicate(Predicate.java:326)
    at org.exist.xquery.LocationStep.processPredicate(LocationStep.java:251)
    at org.exist.xquery.LocationStep.applyPredicate(LocationStep.java:238)
    at org.exist.xquery.LocationStep.eval(LocationStep.java:462)
    at org.exist.xquery.AbstractExpression.eval(AbstractExpression.java:71)
    at org.exist.xquery.PathExpr.eval(PathExpr.java:264)
    at org.exist.xquery.LetExpr.eval(LetExpr.java:142)
    at org.exist.xquery.LetExpr.eval(LetExpr.java:187)
    at org.exist.xquery.LetExpr.eval(LetExpr.java:187)
    at org.exist.xquery.BindingExpression.eval(BindingExpression.java:164)
2015-03-19 21:56:59,147 [Timer-0] WARN  (ThreadPoolAsynchronousRunner.java [run]:624) - com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@6824f21c -- APPARENT DEADLOCK!!! Complete Status:
    Managed Threads: 3
    Active Threads: 3
    Active Tasks:
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@79180a12 (com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#0)
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@243c6d0c (com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#1)
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@50191373 (com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#2)
    Pending Tasks:
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@3a9d08ca
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@3ecdd11
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@44ff846d
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@5ce5850a
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@eec1d04
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@6b8d4d9d
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@53e9706d
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@23d472cf
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@4dbe4f8c
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@4c5e0203
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@54ac79fd
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@546e2bad
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@6b13cc83
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@57e185f8
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@60357d68
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@45231180
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@3021aa73
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@6bb437ca
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@2021c9e9
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@7d53637c
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@409c2c97
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@adc5929
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@241ca71a
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@42b26866
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@636b1c33
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@b160466
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@4af34669
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@1b53e609
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@2062ebd4
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@1b6cfe8a
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@4b7c2380
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@4f9be748
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@78108924
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@474b002
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@2ebee32f
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@3e0fe017
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@42aa175b
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@637f5bac
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@3a017b77
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@7b4f2b78
Pool thread stack traces:
    Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#1,5,main]
        sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        java.lang.reflect.Constructor.newInstance(Constructor.java:408)
        com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
        com.mysql.jdbc.ResultSetImpl.getInstance(ResultSetImpl.java:370)
        com.mysql.jdbc.MysqlIO.buildResultSetWithRows(MysqlIO.java:2532)
        com.mysql.jdbc.MysqlIO.getResultSet(MysqlIO.java:477)
        com.mysql.jdbc.MysqlIO.readResultsForQueryOrUpdate(MysqlIO.java:2510)
        com.mysql.jdbc.MysqlIO.readAllResults(MysqlIO.java:1746)
        com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2135)
        com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2536)
        com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2465)
        com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1383)
        com.mysql.jdbc.DatabaseMetaData$9.forEach(DatabaseMetaData.java:4826)
        com.mysql.jdbc.IterateBlock.doForAll(IterateBlock.java:50)
        com.mysql.jdbc.DatabaseMetaData.getTables(DatabaseMetaData.java:4804)
        com.mchange.v2.c3p0.impl.DefaultConnectionTester.activeCheckConnectionNoQuery(DefaultConnectionTester.java:185)
        com.mchange.v2.c3p0.impl.DefaultConnectionTester.activeCheckConnection(DefaultConnectionTester.java:62)
        com.mchange.v2.c3p0.AbstractConnectionTester.activeCheckConnection(AbstractConnectionTester.java:67)
        com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.testPooledConnection(C3P0PooledConnectionPool.java:368)
        com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.refurbishIdleResource(C3P0PooledConnectionPool.java:310)
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask.run(BasicResourcePool.java:1999)
        com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547)
    Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#2,5,main]
        com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2596)
        com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2465)
        com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1383)
        com.mysql.jdbc.DatabaseMetaData$9.forEach(DatabaseMetaData.java:4826)
        com.mysql.jdbc.IterateBlock.doForAll(IterateBlock.java:50)
        com.mysql.jdbc.DatabaseMetaData.getTables(DatabaseMetaData.java:4804)
        com.mchange.v2.c3p0.impl.DefaultConnectionTester.activeCheckConnectionNoQuery(DefaultConnectionTester.java:185)
        com.mchange.v2.c3p0.impl.DefaultConnectionTester.activeCheckConnection(DefaultConnectionTester.java:62)
        com.mchange.v2.c3p0.AbstractConnectionTester.activeCheckConnection(AbstractConnectionTester.java:67)
        com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.testPooledConnection(C3P0PooledConnectionPool.java:368)
        com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.refurbishIdleResource(C3P0PooledConnectionPool.java:310)
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask.run(BasicResourcePool.java:1999)
        com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547)
    Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#0,5,main]
        java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1012)
        java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:1006)
        com.newrelic.agent.TransactionService.addTransaction(TransactionService.java:142)
        com.newrelic.agent.Transaction.getTransaction(Transaction.java:1104)
        com.newrelic.agent.Transaction.getTransaction(Transaction.java:1087)
        com.newrelic.agent.TracerService$TracerServiceImpl.getTracer(TracerService.java:136)
        com.newrelic.agent.TracerService.getTracer(TracerService.java:41)
        com.newrelic.agent.instrumentation.InvocationPoint.invoke(InvocationPoint.java:55)
        com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java)
        com.mysql.jdbc.DatabaseMetaData$9.forEach(DatabaseMetaData.java:4826)
        com.mysql.jdbc.IterateBlock.doForAll(IterateBlock.java:50)
        com.mysql.jdbc.DatabaseMetaData.getTables(DatabaseMetaData.java:4804)
        com.mchange.v2.c3p0.impl.DefaultConnectionTester.activeCheckConnectionNoQuery(DefaultConnectionTester.java:185)
        com.mchange.v2.c3p0.impl.DefaultConnectionTester.activeCheckConnection(DefaultConnectionTester.java:62)
        com.mchange.v2.c3p0.AbstractConnectionTester.activeCheckConnection(AbstractConnectionTester.java:67)
        com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.testPooledConnection(C3P0PooledConnectionPool.java:368)
        com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.refurbishIdleResource(C3P0PooledConnectionPool.java:310)
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask.run(BasicResourcePool.java:1999)
        com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547)
</code>```

We are using hiberanate and c3p0 with the following c3p0 configuration:

We are using the following maven artifacts for hibernate and c3p0:

```<code> <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.6.Final</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-c3p0</artifactId>
            <version>4.3.6.Final</version>
        </dependency>
</code>```

with the following c3p0 configuration:

```<code>  configuration = new Configuration().setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect")
  .setProperty("hibernate.connection.provider_class", "org.hibernate.connection.C3P0ConnectionProvider")
  .setProperty("hibernate.c3p0.idle_test_period", "1000")
  .setProperty("hibernate.c3p0.min_size", "20")
  .setProperty("hibernate.c3p0.max_size", "50")
  .setProperty("hibernate.c3p0.timeout", "1800")
  .setProperty("hibernate.c3p0.max_statements", "50")
</code>```

The server is under very light load ~5 queries a second. (Java 8)

答: Authentication issue for me too. I just added the domain part to the database server name and it all worked. Very misleading error.</p>

Body:
I recently got the following messages in our logs followed by a JVM crash (Due to OOME). I am not sure what to make of this and would really appreciate any guidance.

2015-03-19 21:15:02,457 [Timer-0] WARN  (ThreadPoolAsynchronousRunner.java [run]:608) - com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@6824f21c -- APPARENT DEADLOCK!!! Creating emergency threads for unassigned pending tasks!
2015-03-19 21:26:29,543 [Timer-0] WARN  (ThreadPoolAsynchronousRunner.java [run]:624) - com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@6824f21c -- APPARENT DEADLOCK!!! Complete Status:
    Managed Threads: 3
    Active Threads: 3
    Active Tasks:
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@15da1b6b (com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#2)
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@b35b08a (com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#1)
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@51cfdd17 (com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#0)
    Pending Tasks:
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@19397937
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@5c7d3838
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@7aea62dd
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@55622ff2
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@74004a8
Pool thread stack traces:
    Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#0,5,main]
        com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:560)
    Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#2,5,main]
        java.net.SocketOutputStream.socketWrite0(Native Method)
        java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109)
        java.net.SocketOutputStream.write(SocketOutputStream.java:153)
        java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
        java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
        com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3227)
        com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1917)
        com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2060)
        com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2536)
        com.mysql.jdbc.ConnectionImpl.configureClientCharacterSet(ConnectionImpl.java:1751)
        com.mysql.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:3425)
        com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2196)
        com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:718)
        com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
        sun.reflect.GeneratedConstructorAccessor306.newInstance(Unknown Source)
        sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        java.lang.reflect.Constructor.newInstance(Constructor.java:408)
        com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
        com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
        com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:282)
        com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:135)
        com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:182)
        com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:171)
        com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137)
        com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014)
        com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32)
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810)
        com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547)
    Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#1,5,main]
        com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:560)

2015-03-19 21:56:59,137 [Timer-0] WARN  (ThreadPoolAsynchronousRunner.java [run]:608) - com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@6824f21c -- APPARENT DEADLOCK!!! Creating emergency threads for unassigned pending tasks!
2015-03-19 21:56:59,143 [eXistThread-18676] ERROR (XQueryServlet.java [process]:566) - Java heap space
java.lang.OutOfMemoryError: Java heap space
    at org.exist.storage.btree.BTree$BTreeNode.read(BTree.java:1269)
    at org.exist.storage.btree.BTree$BTreeNode.access$16(BTree.java:1239)
    at org.exist.storage.btree.BTree.getBTreeNode(BTree.java:460)
    at org.exist.storage.btree.BTree.scanSequential(BTree.java:413)
    at org.exist.storage.btree.BTree$BTreeNode.scanNextPage(BTree.java:2039)
    at org.exist.storage.btree.BTree$BTreeNode.query(BTree.java:1835)
    at org.exist.storage.btree.BTree$BTreeNode.query(BTree.java:1759)
    at org.exist.storage.btree.BTree$BTreeNode.query(BTree.java:1759)
    at org.exist.storage.btree.BTree$BTreeNode.query(BTree.java:1759)
    at org.exist.storage.btree.BTree$BTreeNode.access$12(BTree.java:1734)
    at org.exist.storage.btree.BTree.query(BTree.java:379)
    at org.exist.storage.structural.NativeStructuralIndexWorker.scanByType(NativeStructuralIndexWorker.java:259)
    at org.exist.dom.VirtualNodeSet.getNodesFromIndex(VirtualNodeSet.java:457)
    at org.exist.dom.VirtualNodeSet.realize(VirtualNodeSet.java:585)
    at org.exist.dom.VirtualNodeSet.iterator(VirtualNodeSet.java:860)
    at org.exist.dom.AbstractNodeSet.iterator(AbstractNodeSet.java:1)
    at org.exist.storage.structural.NativeStructuralIndexWorker.findDescendantsByTagName(NativeStructuralIndexWorker.java:162)
    at org.exist.xquery.LocationStep.getAttributes(LocationStep.java:645)
    at org.exist.xquery.LocationStep.eval(LocationStep.java:434)
    at org.exist.xquery.AbstractExpression.eval(AbstractExpression.java:71)
    at org.exist.xquery.PathExpr.eval(PathExpr.java:264)
    at org.exist.xquery.Predicate.selectByNodeSet(Predicate.java:446)
    at org.exist.xquery.Predicate.evalPredicate(Predicate.java:326)
    at org.exist.xquery.LocationStep.processPredicate(LocationStep.java:251)
    at org.exist.xquery.LocationStep.applyPredicate(LocationStep.java:238)
    at org.exist.xquery.LocationStep.eval(LocationStep.java:462)
    at org.exist.xquery.AbstractExpression.eval(AbstractExpression.java:71)
    at org.exist.xquery.PathExpr.eval(PathExpr.java:264)
    at org.exist.xquery.LetExpr.eval(LetExpr.java:142)
    at org.exist.xquery.LetExpr.eval(LetExpr.java:187)
    at org.exist.xquery.LetExpr.eval(LetExpr.java:187)
    at org.exist.xquery.BindingExpression.eval(BindingExpression.java:164)
2015-03-19 21:56:59,147 [Timer-0] WARN  (ThreadPoolAsynchronousRunner.java [run]:624) - com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@6824f21c -- APPARENT DEADLOCK!!! Complete Status:
    Managed Threads: 3
    Active Threads: 3
    Active Tasks:
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@79180a12 (com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#0)
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@243c6d0c (com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#1)
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@50191373 (com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#2)
    Pending Tasks:
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@3a9d08ca
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@3ecdd11
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@44ff846d
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@5ce5850a
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@eec1d04
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@6b8d4d9d
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@53e9706d
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@23d472cf
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@4dbe4f8c
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@4c5e0203
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@54ac79fd
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask@546e2bad
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@6b13cc83
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@57e185f8
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@60357d68
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@45231180
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@3021aa73
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@6bb437ca
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@2021c9e9
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@7d53637c
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@409c2c97
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@adc5929
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@241ca71a
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@42b26866
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@636b1c33
        com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@b160466
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@4af34669
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@1b53e609
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@2062ebd4
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@1b6cfe8a
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@4b7c2380
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@4f9be748
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@78108924
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@474b002
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@2ebee32f
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@3e0fe017
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@42aa175b
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@637f5bac
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@3a017b77
        com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@7b4f2b78
Pool thread stack traces:
    Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#1,5,main]
        sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        java.lang.reflect.Constructor.newInstance(Constructor.java:408)
        com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
        com.mysql.jdbc.ResultSetImpl.getInstance(ResultSetImpl.java:370)
        com.mysql.jdbc.MysqlIO.buildResultSetWithRows(MysqlIO.java:2532)
        com.mysql.jdbc.MysqlIO.getResultSet(MysqlIO.java:477)
        com.mysql.jdbc.MysqlIO.readResultsForQueryOrUpdate(MysqlIO.java:2510)
        com.mysql.jdbc.MysqlIO.readAllResults(MysqlIO.java:1746)
        com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2135)
        com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2536)
        com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2465)
        com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1383)
        com.mysql.jdbc.DatabaseMetaData$9.forEach(DatabaseMetaData.java:4826)
        com.mysql.jdbc.IterateBlock.doForAll(IterateBlock.java:50)
        com.mysql.jdbc.DatabaseMetaData.getTables(DatabaseMetaData.java:4804)
        com.mchange.v2.c3p0.impl.DefaultConnectionTester.activeCheckConnectionNoQuery(DefaultConnectionTester.java:185)
        com.mchange.v2.c3p0.impl.DefaultConnectionTester.activeCheckConnection(DefaultConnectionTester.java:62)
        com.mchange.v2.c3p0.AbstractConnectionTester.activeCheckConnection(AbstractConnectionTester.java:67)
        com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.testPooledConnection(C3P0PooledConnectionPool.java:368)
        com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.refurbishIdleResource(C3P0PooledConnectionPool.java:310)
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask.run(BasicResourcePool.java:1999)
        com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547)
    Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#2,5,main]
        com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2596)
        com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2465)
        com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1383)
        com.mysql.jdbc.DatabaseMetaData$9.forEach(DatabaseMetaData.java:4826)
        com.mysql.jdbc.IterateBlock.doForAll(IterateBlock.java:50)
        com.mysql.jdbc.DatabaseMetaData.getTables(DatabaseMetaData.java:4804)
        com.mchange.v2.c3p0.impl.DefaultConnectionTester.activeCheckConnectionNoQuery(DefaultConnectionTester.java:185)
        com.mchange.v2.c3p0.impl.DefaultConnectionTester.activeCheckConnection(DefaultConnectionTester.java:62)
        com.mchange.v2.c3p0.AbstractConnectionTester.activeCheckConnection(AbstractConnectionTester.java:67)
        com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.testPooledConnection(C3P0PooledConnectionPool.java:368)
        com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.refurbishIdleResource(C3P0PooledConnectionPool.java:310)
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask.run(BasicResourcePool.java:1999)
        com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547)
    Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#0,5,main]
        java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1012)
        java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:1006)
        com.newrelic.agent.TransactionService.addTransaction(TransactionService.java:142)
        com.newrelic.agent.Transaction.getTransaction(Transaction.java:1104)
        com.newrelic.agent.Transaction.getTransaction(Transaction.java:1087)
        com.newrelic.agent.TracerService$TracerServiceImpl.getTracer(TracerService.java:136)
        com.newrelic.agent.TracerService.getTracer(TracerService.java:41)
        com.newrelic.agent.instrumentation.InvocationPoint.invoke(InvocationPoint.java:55)
        com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java)
        com.mysql.jdbc.DatabaseMetaData$9.forEach(DatabaseMetaData.java:4826)
        com.mysql.jdbc.IterateBlock.doForAll(IterateBlock.java:50)
        com.mysql.jdbc.DatabaseMetaData.getTables(DatabaseMetaData.java:4804)
        com.mchange.v2.c3p0.impl.DefaultConnectionTester.activeCheckConnectionNoQuery(DefaultConnectionTester.java:185)
        com.mchange.v2.c3p0.impl.DefaultConnectionTester.activeCheckConnection(DefaultConnectionTester.java:62)
        com.mchange.v2.c3p0.AbstractConnectionTester.activeCheckConnection(AbstractConnectionTester.java:67)
        com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.testPooledConnection(C3P0PooledConnectionPool.java:368)
        com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.refurbishIdleResource(C3P0PooledConnectionPool.java:310)
        com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTask.run(BasicResourcePool.java:1999)
        com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547)

We are using hiberanate and c3p0 with the following c3p0 configuration:

We are using the following maven artifacts for hibernate and c3p0:

 <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.6.Final</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-c3p0</artifactId>
            <version>4.3.6.Final</version>
        </dependency>

with the following c3p0 configuration:

  configuration = new Configuration().setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect")
  .setProperty("hibernate.connection.provider_class", "org.hibernate.connection.C3P0ConnectionProvider")
  .setProperty("hibernate.c3p0.idle_test_period", "1000")
  .setProperty("hibernate.c3p0.min_size", "20")
  .setProperty("hibernate.c3p0.max_size", "50")
  .setProperty("hibernate.c3p0.timeout", "1800")
  .setProperty("hibernate.c3p0.max_statements", "50")

The server is under very light load ~5 queries a second. (Java 8)


来源: stackexchange

问:
Can't get background gradient to fill entire screen upon rotation
I have a background gradient that draws nicely when the screen is initially rendered in portrait mode. However, when the device is rotated to landscape mode, the right 40% of the screen is black (i.e. the background is not drawn on the part of the screen that wasn't previously drawn). I don't know how to get the background to redraw to fill the entire screen.

Can anyone tell me what I am doing wrong? Thanks!

Here is how it looks when initially drawn.

And here is now it looks when I rotate it:

Here is the code for my background gradient class:

```<code>#import "BackgroundGradient.h"

@interface BackgroundGradient()
@property (strong, nonatomic) UIView *view;
@end

@implementation BackgroundGradient

- (id) initWithView:(UIView *) view
{
    if (!_view)
        _view = view;

    return self;
}

- (void) makeGradient
{
    UIColor *darkOp = [UIColor colorWithRed:(193.0 / 255.0) green:(215.0 / 255.0) blue:(46.0 / 255.0) alpha: 1];
    UIColor *lightOp = [UIColor colorWithRed:(222.0 / 255.0) green:(233.0 / 255.0) blue:(143.0 / 255.0) alpha: 1];

    // Create the gradient
    CAGradientLayer *gradient = [CAGradientLayer layer];

    // Set colors
    gradient.colors = [NSArray arrayWithObjects:
                       (id)darkOp.CGColor,
                       (id)lightOp.CGColor,
                       (id)darkOp.CGColor,
                       nil];

    // Update the start and end points
    gradient.startPoint = CGPointMake(0.5, 0.0);
    gradient.endPoint = CGPointMake(0.5, 1.0);

    // Set bounds
    gradient.frame = self.view.bounds;

    // Add the gradient to the view
    [self.view.layer insertSublayer:gradient atIndex:0];

    gradient.locations = [NSArray arrayWithObjects:
                          [NSNumber numberWithFloat:0.0f],
                          [NSNumber numberWithFloat:0.7],
                          [NSNumber numberWithFloat:0.9],
                          nil];

}

@end
</code>```

And finally, here is how I instantiate the background object:

```<code>- (void)viewDidLoad
{
    [super viewDidLoad];

    self.background = [[BackgroundGradient alloc] initWithView:self.view];
    [self.background makeGradient];

}
</code>```

EDIT: I've added the following code and included updates to the start and end points (above):

```<code>- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [self.background makeGradient];
}
</code>```

I'm almost there, but now, I get this. Notice how there is still a vertical line. It looks to me like the new background is getting drawn behing the previous background such that the previous background is still there and is blocking the new background. This is particularly noticeable as the animation from portrait to landscape is occurring.

答:
Update gradient's frame in viewDidLayoutSubviews:

```<code>override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    // find gradient layer
    let gradLayers = gradientView.layer.sublayers?.flatMap { $0 as? CAGradientLayer }
    // this assumes there is only one gradient layer
    gradLayers?.first?.frame = gradientView.bounds
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a background gradient that draws nicely when the screen is initially rendered in portrait mode. However, when the device is rotated to landscape mode, the right 40% of the screen is black (i.e. the background is not drawn on the part of the screen that wasn't previously drawn). I don't know how to get the background to redraw to fill the entire screen.

Can anyone tell me what I am doing wrong? Thanks!

Here is how it looks when initially drawn.

And here is now it looks when I rotate it:

Here is the code for my background gradient class:

#import "BackgroundGradient.h"

@interface BackgroundGradient()
@property (strong, nonatomic) UIView *view;
@end

@implementation BackgroundGradient

- (id) initWithView:(UIView *) view
{
    if (!_view)
        _view = view;

    return self;
}

- (void) makeGradient
{
    UIColor *darkOp = [UIColor colorWithRed:(193.0 / 255.0) green:(215.0 / 255.0) blue:(46.0 / 255.0) alpha: 1];
    UIColor *lightOp = [UIColor colorWithRed:(222.0 / 255.0) green:(233.0 / 255.0) blue:(143.0 / 255.0) alpha: 1];

    // Create the gradient
    CAGradientLayer *gradient = [CAGradientLayer layer];

    // Set colors
    gradient.colors = [NSArray arrayWithObjects:
                       (id)darkOp.CGColor,
                       (id)lightOp.CGColor,
                       (id)darkOp.CGColor,
                       nil];

    // Update the start and end points
    gradient.startPoint = CGPointMake(0.5, 0.0);
    gradient.endPoint = CGPointMake(0.5, 1.0);

    // Set bounds
    gradient.frame = self.view.bounds;

    // Add the gradient to the view
    [self.view.layer insertSublayer:gradient atIndex:0];

    gradient.locations = [NSArray arrayWithObjects:
                          [NSNumber numberWithFloat:0.0f],
                          [NSNumber numberWithFloat:0.7],
                          [NSNumber numberWithFloat:0.9],
                          nil];

}

@end

And finally, here is how I instantiate the background object:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.background = [[BackgroundGradient alloc] initWithView:self.view];
    [self.background makeGradient];

}

EDIT: I've added the following code and included updates to the start and end points (above):

- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [self.background makeGradient];
}

I'm almost there, but now, I get this. Notice how there is still a vertical line. It looks to me like the new background is getting drawn behing the previous background such that the previous background is still there and is blocking the new background. This is particularly noticeable as the animation from portrait to landscape is occurring.

Body:
Update gradient's frame in viewDidLayoutSubviews:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    // find gradient layer
    let gradLayers = gradientView.layer.sublayers?.flatMap { $0 as? CAGradientLayer }
    // this assumes there is only one gradient layer
    gradLayers?.first?.frame = gradientView.bounds
}


问:
How to change firefox developer edition inspector background colour
Just started using Firefox Developer Edition and the background colour in Inspector was a lovely black background. Now it's changed to a white colour. Any idea how I can change it back?

I'm on an Apple Mac OS Sierra 10.12.6 and using Firefox Dev Ed 58.0b1

Thanks,

Djuro

答:
doh! there it is in the settings wheel for the inspector element.

inspector setting screenshot


问:
How to Set OnClickListener to Card in PlaceholderView?
I am using PlaceHolderView library to show an Infinite List of contents like the Facebook Android app. I was using InfinitePlaceHolderView for it. It looks like this:

And here is how it looks like output

Now If the story is large then a user can click on the card view and it will take him to a new activity where there will be a detail of that story. For this, I need to add a Listener. But I could not find any documentation at all, how to implement it. The documentation shows that all those cards are dynamically created and not any of those cards have any id so that I can put a listener.

How to implement it?

答:
So, what I did is given below:

In my feed.xml file which contain the above view, I set an id for the whole view. Then I used that id and used it ItemView.java from here:

feed.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/home_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/grey_100"
    android:orientation="vertical"
    android:weightSum="4"
    tools:context="com.example.shamsad.tutionhub.activities.FeedActivity">

    <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?android:attr/actionBarSize"
        android:id="@+id/tbHome"
        android:background="@color/colorPrimary"
        app:titleTextColor="@color/grey_100">
    </android.support.v7.widget.Toolbar>

    <com.mindorks.placeholderview.InfinitePlaceHolderView
        android:id="@+id/loadMoreView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>
</code>```

ItemView.java

```<code>@Click(R.id.rootView)
    public void onCardClick() {
        Intent intent = new Intent(mContext, DetailActivity.class);
        intent.putExtra("title", mInfo.getTitle());
        intent.putExtra("caption", mInfo.getCaption());
        intent.putExtra("salary", mInfo.getSalary());
        intent.putExtra("routine", mInfo.getRoutine());
        intent.putExtra("time", mInfo.getTime());
        Log.d("sajid", "onClick");
        mContext.startActivity(intent);
    }
</code>```

So, in this onCardClick() method, the clickable id is set up by this code @Click(R.id.rootView). And that's all. It basically sets the whole card-view as a clickable thing.

And also thanks to the writer of this great library Janisher Ali. I contacted him and he helped a lot, and it worked.

This is a great library. To me much better than RecyclerView. You can try it out :)

Body:
So, what I did is given below:

In my feed.xml file which contain the above view, I set an id for the whole view. Then I used that id and used it ItemView.java from here:

feed.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/home_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/grey_100"
    android:orientation="vertical"
    android:weightSum="4"
    tools:context="com.example.shamsad.tutionhub.activities.FeedActivity">

    <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?android:attr/actionBarSize"
        android:id="@+id/tbHome"
        android:background="@color/colorPrimary"
        app:titleTextColor="@color/grey_100">
    </android.support.v7.widget.Toolbar>

    <com.mindorks.placeholderview.InfinitePlaceHolderView
        android:id="@+id/loadMoreView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

ItemView.java

@Click(R.id.rootView)
    public void onCardClick() {
        Intent intent = new Intent(mContext, DetailActivity.class);
        intent.putExtra("title", mInfo.getTitle());
        intent.putExtra("caption", mInfo.getCaption());
        intent.putExtra("salary", mInfo.getSalary());
        intent.putExtra("routine", mInfo.getRoutine());
        intent.putExtra("time", mInfo.getTime());
        Log.d("sajid", "onClick");
        mContext.startActivity(intent);
    }

So, in this onCardClick() method, the clickable id is set up by this code @Click(R.id.rootView). And that's all. It basically sets the whole card-view as a clickable thing.

And also thanks to the writer of this great library Janisher Ali. I contacted him and he helped a lot, and it worked.

This is a great library. To me much better than RecyclerView. You can try it out :)


问:
How to determine from which class a method was inherited from?
Is it possible to tell, from which class an method was inherited from. take an example below

```<code>class A:
   def foo():
     pass
class B(A):
   def boo(A):
     pass
class C(B):
   def coo()
     pass
class D(C):
   def doo()
      pass

>>> dir (D)
['__doc__', '__module__', 'boo', 'coo', 'doo', 'foo']
</code>```

Is there any method to tell me form which classes boo, coo, foo where inherited from?

答:
Use the inspect module:</p>

```<code>class A:
   def foo(self):
     pass
class B(A):
   def boo(Aself):
     pass
class C(B):
   def coo(self):
     pass
class D(C):
   def doo(self):
      pass

import inspect
inspect.classify_class_attrs(D)

[('__doc__', 'data', <class __main__.D at 0x85fb8fc>, None),
 ('__module__', 'data', <class __main__.D at 0x85fb8fc>, '__main__'),
 ('boo',
  'method',
  <class __main__.B at 0x85fb44c>,
  <function boo at 0x8612bfc>),
 ('coo',
  'method',
  <class __main__.C at 0x85fb8cc>,
  <function coo at 0x8612ca4>),
 ('doo',
  'method',
  <class __main__.D at 0x85fb8fc>,
  <function doo at 0x8612f0c>),
 ('foo',
  'method',
  <class __main__.A at 0x85fb71c>,
  <function foo at 0x8612f7c>)]
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Is it possible to tell, from which class an method was inherited from. take an example below

class A:
   def foo():
     pass
class B(A):
   def boo(A):
     pass
class C(B):
   def coo()
     pass
class D(C):
   def doo()
      pass

>>> dir (D)
['__doc__', '__module__', 'boo', 'coo', 'doo', 'foo']

Is there any method to tell me form which classes boo, coo, foo where inherited from?

Body:
Use the inspect module:

class A:
   def foo(self):
     pass
class B(A):
   def boo(Aself):
     pass
class C(B):
   def coo(self):
     pass
class D(C):
   def doo(self):
      pass

import inspect
inspect.classify_class_attrs(D)

[('__doc__', 'data', <class __main__.D at 0x85fb8fc>, None),
 ('__module__', 'data', <class __main__.D at 0x85fb8fc>, '__main__'),
 ('boo',
  'method',
  <class __main__.B at 0x85fb44c>,
  <function boo at 0x8612bfc>),
 ('coo',
  'method',
  <class __main__.C at 0x85fb8cc>,
  <function coo at 0x8612ca4>),
 ('doo',
  'method',
  <class __main__.D at 0x85fb8fc>,
  <function doo at 0x8612f0c>),
 ('foo',
  'method',
  <class __main__.A at 0x85fb71c>,
  <function foo at 0x8612f7c>)]


问:
Does .Any with a predicate have to generate the resulting list before it looks for .Any
I've got a List with 1,000,000 complex objects.  I need to create another list with a subset of those objects, keeping the original list unchanged.  At this point in the code, I know for certain that bigList is not null, and that it has at least 1 item.

My original code:

```<code>var smallList = bigList.Where(csvrec => csvrec.PreApprovalAmount <= 0 || csvrec.PreApprovalAmount > csvrec.ReplacementAmount).ToList();
</code>```

My team lead said that there were several problems with my code.  He said that .Where could result in null, and that calling .ToList() would cause a null exception.  So, in order to avoid that, he said I needed to change my code to:

```<code>var smallList = new List<CSVLines>();
if(bigList.Any(csvrec => csvrec.PreApprovalAmount <= 0 || csvrec.PreApprovalAmount > csvrec.ReplacementAmount))
{
    smallList = bigList.Where(csvrec => csvrec.PreApprovalAmount <= 0 || csvrec.PreApprovalAmount > csvrec.ReplacementAmount).ToList();
}
</code>```

I don't think that .Where can ever result in a null exception.

I don't think that smallList will not ever be null.  It could be a
list with 0 elements, but not null.

Doing .Any with a predicate means it has to generate the list, then
determine if it has at least 1 element, and then my code will have
to generate the same list again to assign it to smallList.

Am I correct?  Are the proposed changes from my team lead basically doubling the amount of work to create this list with no real benefit?

答:
.Where() should only cause an exception if bigList was null to begin with.

However, doing .Any() does not have to generate the list. It will go through a collection and stop as soon as first item that matches the predicate is found.

The one change you probably should make is to remove the ToList() call. Try to stick with IEnumerable as much as possible and avoid creating the List objects, especially when working with larger sets. This is to improve memory use and avoid causing OutOfMemoryExceptions rather than NullReferenceExceptions.

Body:
I've got a List with 1,000,000 complex objects.  I need to create another list with a subset of those objects, keeping the original list unchanged.  At this point in the code, I know for certain that bigList is not null, and that it has at least 1 item.

My original code:

var smallList = bigList.Where(csvrec => csvrec.PreApprovalAmount <= 0 || csvrec.PreApprovalAmount > csvrec.ReplacementAmount).ToList();

My team lead said that there were several problems with my code.  He said that .Where could result in null, and that calling .ToList() would cause a null exception.  So, in order to avoid that, he said I needed to change my code to:

var smallList = new List<CSVLines>();
if(bigList.Any(csvrec => csvrec.PreApprovalAmount <= 0 || csvrec.PreApprovalAmount > csvrec.ReplacementAmount))
{
    smallList = bigList.Where(csvrec => csvrec.PreApprovalAmount <= 0 || csvrec.PreApprovalAmount > csvrec.ReplacementAmount).ToList();
}

I don't think that .Where can ever result in a null exception.

I don't think that smallList will not ever be null.  It could be a
list with 0 elements, but not null.

Doing .Any with a predicate means it has to generate the list, then
determine if it has at least 1 element, and then my code will have
to generate the same list again to assign it to smallList.

Am I correct?  Are the proposed changes from my team lead basically doubling the amount of work to create this list with no real benefit?


问:
Cannot call plugin Controllers in Cakephp
I have a plugin named as PanelAdmin. It has Controller UsersController.php and inside it there are different actions defined.
I have called the default controller within the plugin through this code

```<code>$routes->connect('/PanelAdmin', ['plugin' => 'PanelAdmin','controller' => 'default','action' => 'index']);
</code>```

but cannot call other controller if i hit this url:

```<code>http://localhost/multi_shopping/PanelAdmin/Users/
</code>```

One thing more i want to clear is i have to define routes for all controllers actions in routes.php. Please solve my issue. Thanks

答:
In your plugin routes.php make sure you are setting a fallback route.

routes.php

```<code><?php
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;

Router::plugin(
    'PanelAdmin',
    ['path' => '/PanelAdmin'],
    function (RouteBuilder $routes) {
        $routes->fallbacks(DashedRoute::class);
    }
);
</code>```

From the DashedRoute class:

```<code>/**
 * This route class will transparently inflect the controller, action and plugin
 * routing parameters, so that requesting `/my-plugin/my-controller/my-action`
 * is parsed as `['plugin' => 'MyPlugin', 'controller' => 'MyController', 'action' => 'myAction']`
 */
</code>```

Body:
I have a plugin named as PanelAdmin. It has Controller UsersController.php and inside it there are different actions defined.
I have called the default controller within the plugin through this code

$routes->connect('/PanelAdmin', ['plugin' => 'PanelAdmin','controller' => 'default','action' => 'index']);

but cannot call other controller if i hit this url:

http://localhost/multi_shopping/PanelAdmin/Users/

One thing more i want to clear is i have to define routes for all controllers actions in routes.php. Please solve my issue. Thanks

Body:
In your plugin routes.php make sure you are setting a fallback route.

routes.php

<?php
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;

Router::plugin(
    'PanelAdmin',
    ['path' => '/PanelAdmin'],
    function (RouteBuilder $routes) {
        $routes->fallbacks(DashedRoute::class);
    }
);

From the DashedRoute class:

/**
 * This route class will transparently inflect the controller, action and plugin
 * routing parameters, so that requesting `/my-plugin/my-controller/my-action`
 * is parsed as `['plugin' => 'MyPlugin', 'controller' => 'MyController', 'action' => 'myAction']`
 */


问:
bash - how to extract all of the same tag in xml
givin this file.xml

```<code>  <session id = 1111>

    <query text = text1 >
            <response>
                    firstresponse1
            </response>
            <response>
                    secondresponse1
            </response>
    </query>
    <query text = secondtext >
            <response>
                    !!!aresponse2!!!
            </response>
            <response>
                    !!!aresponse3!!!
            </response>
    </query>
    <query text = thirdtext>
            <response>
                    firstreponse3
            </response>
            <response>
                    secondresponese4
            </response>
    </query>
    </session>
</code>```

i want to get both response tags in secondtext

output :

!!!aresponse2!!!

!!!aresponse3!!!

.

what is the most efficient way to do that ?

答:
The right way is to use XML/HTML parsers like xmllint or xmlstarlet.

xmllint solution:

```<code>xmllint --html --xpath "//query[@text='secondtext']/response/text()" file.xml 2>/dev/null
</code>```

The output:

```<code>            !!!aresponse2!!!

            !!!aresponse3!!!
</code>```

Body:
givin this file.xml

  <session id = 1111>

    <query text = text1 >
            <response>
                    firstresponse1
            </response>
            <response>
                    secondresponse1
            </response>
    </query>
    <query text = secondtext >
            <response>
                    !!!aresponse2!!!
            </response>
            <response>
                    !!!aresponse3!!!
            </response>
    </query>
    <query text = thirdtext>
            <response>
                    firstreponse3
            </response>
            <response>
                    secondresponese4
            </response>
    </query>
    </session>

i want to get both response tags in secondtext

output :

!!!aresponse2!!!

!!!aresponse3!!!

.

what is the most efficient way to do that ?

Body:
The right way is to use XML/HTML parsers like xmllint or xmlstarlet.

xmllint solution:

xmllint --html --xpath "//query[@text='secondtext']/response/text()" file.xml 2>/dev/null

The output:

            !!!aresponse2!!!

            !!!aresponse3!!!


问:
Catch the event when a youtube flash video is done playing using javascript
I'm supposed to create a sort of youtube video rotator using jquery. I've looked around and there seemed to be no plugin that's fit for the requirement. Not even a solution.

Maybe I'll just try to make this. So now, how can I determine that a youtube video is done playing and automatically play the next, using Jquery, or simply just javascript?

And if you happen to know a plugin which may help, please point out.

Thanks

答:
First you have to make sure the youtube player you're embedding supports javascript by passing enablejsapi=1 as a get param. Here's how I insert a (chromeless) player using SWFObject:

```<code>    var player_id = "your_player_id";
    var params = { allowScriptAccess: "always" };
    var url = "http://www.youtube.com/apiplayer?enablejsapi=1&version=3&playerapiid=" + player_id;
    swfobject.embedSWF(url, player_id, '320', '240', "9.0.0", null, null, params, {'id': player_id});
</code>```

Then you need to add a global function that is called when the player is ready, and in that add a listener for when a video is complete:

```<code>    var player = null;

    function onYouTubePlayerReady(player_id) {
      player = document.getElementById(player_id);
      player.addEventListener('onStateChange', 'playerStateChanged');
      player.loadVideoById(youtube_video_id);
    };

    function playerStateChanged(state) {
      // State code 0 means playback ended
      if (state == 0) {
        player.loadVideoById(next_video_id);
      }
    };
</code>```

I wrote this code for my youtube playlist bookmarklet. Here's a link if you want a working example: http://zaius.github.com/youtube_playlist/

And if you want to do anything more in depth, here's the youtube javascript reference where I worked out how to do all this: http://code.google.com/apis/youtube/js_api_reference.html

Body:
First you have to make sure the youtube player you're embedding supports javascript by passing enablejsapi=1 as a get param. Here's how I insert a (chromeless) player using SWFObject:

    var player_id = "your_player_id";
    var params = { allowScriptAccess: "always" };
    var url = "http://www.youtube.com/apiplayer?enablejsapi=1&version=3&playerapiid=" + player_id;
    swfobject.embedSWF(url, player_id, '320', '240', "9.0.0", null, null, params, {'id': player_id});

Then you need to add a global function that is called when the player is ready, and in that add a listener for when a video is complete:

    var player = null;

    function onYouTubePlayerReady(player_id) {
      player = document.getElementById(player_id);
      player.addEventListener('onStateChange', 'playerStateChanged');
      player.loadVideoById(youtube_video_id);
    };

    function playerStateChanged(state) {
      // State code 0 means playback ended
      if (state == 0) {
        player.loadVideoById(next_video_id);
      }
    };

I wrote this code for my youtube playlist bookmarklet. Here's a link if you want a working example: http://zaius.github.com/youtube_playlist/

And if you want to do anything more in depth, here's the youtube javascript reference where I worked out how to do all this: http://code.google.com/apis/youtube/js_api_reference.html


问:
Displaying data with php depending on what is selected in select option
Is it possible to display data of the current selected option, from mysql using php only?. So my select option works fine and it displays good results. But I want 2 other form-group divs to display data depending on what is currently selected in select option. Is that possible using php only or is javascript necessary?

Html

```<code><div class="form-group">
    <label for="naslov">Naslov</label>
    <input type="text" class="form-control" id="naslov" name="naslov" value="<?php echo $titedit; ?>">
</div>

<div class="form-group">
    <label for="oglas">Sadržaj</label>
    <textarea class="form-control" id="oglas" name="oglas" rows="5" ><?php echo $contedit; ?></textarea>
</div>
</code>```

PHP

```<code><?php
session_start();
include_once("db.php");

$sql = "SELECT * FROM news";
$query = mysqli_query($conn, $sql);
$title = $row['title'];
$mxnr = mysqli_num_rows('$query');

if ($mxnr > 0) {

    echo '<select class="form-control">';

    $counter = 1;

    while($row = mysqli_fetch_array($query)) {

        if($counter == 1){
            echo '<option ' . ($counter == 1 ? 'selected' : '') . ' value="opt' . $counter . '">' . $row["id"] . '. ' . $row["title"] . '</option>';
            $titedit = $row['title'];
            $contedit = $row['content'];

        }else{
            echo '<option value="opt' . $counter . '">' . $row["id"] . '. ' . $row["title"] . '</option>';
        }

        $counter++;

    }

    echo '</select>';

} else {
    echo "0 results";
}
?>
</code>```

答:
You will need javascript for that, since PHP loads before everything else, you can use JQuery to change the divs when you select something making it interactive and responsive.

If i may add my opinion, rely on javascript, its really usefull most of the time and will help you a lot. Consider JQuery.

Body:
Is it possible to display data of the current selected option, from mysql using php only?. So my select option works fine and it displays good results. But I want 2 other form-group divs to display data depending on what is currently selected in select option. Is that possible using php only or is javascript necessary?

Html

    Naslov
    <input type="text" class="form-control" id="naslov" name="naslov" value="<?php echo $titedit; ?>">

    Sadržaj
    <textarea class="form-control" id="oglas" name="oglas" rows="5" ><?php echo $contedit; ?></textarea>

PHP

<?php
session_start();
include_once("db.php");

$sql = "SELECT * FROM news";
$query = mysqli_query($conn, $sql);
$title = $row['title'];
$mxnr = mysqli_num_rows('$query');

if ($mxnr > 0) {

    echo '<select class="form-control">';

    $counter = 1;

    while($row = mysqli_fetch_array($query)) {

        if($counter == 1){
            echo '<option ' . ($counter == 1 ? 'selected' : '') . ' value="opt' . $counter . '">' . $row["id"] . '. ' . $row["title"] . '</option>';
            $titedit = $row['title'];
            $contedit = $row['content'];

        }else{
            echo '<option value="opt' . $counter . '">' . $row["id"] . '. ' . $row["title"] . '</option>';
        }

        $counter++;

    }

    echo '</select>';

} else {
    echo "0 results";
}
?>


问:
How do I generate Diagrams and UML of Kotlin code?
How do I generate UML and diagrams for Kotlin code? I don't think getting the paid version of Intellij is an option for me. I have been trying Intellij plugins and I haven't found anything that works yet.

I would like to generate the diagrams and uml from the Kotlin code I have already written. A tool like this would save me a lot of time.

Thanks

答: you can click only on a package in the project tree and click "Show Diagram...". Also it generates diagram from the Java point of view (shows Java's signatures and facade classes)


问:
Access 10 sql query
I want to use LIKE operator in access 10 sql query with variable.

Example:

```<code>temporary variable var contains value bs
var = "bs"
</code>```

I want to match every String that starts with value of temporary variable followed by zero or more numbers.

I am trying to fire the query:

```<code>select * from xyz where variety LIKE "@[tempvars]![var] + [0-9]*"
</code>```

It is returning 0 records.
Thankz for the help.

答:
You need to refer to your tempvar outside of the quotes, and use & for concatenation:

```<code>select * from xyz where variety LIKE "@" & [tempvars]![var] & "[0-9]*"
</code>```

This will return all records where variety starts with a literal @, then whatever is in [tempvars]![var], then a number, and then any amount of characters.

Title: Access 10 sql query

Body:
I want to use LIKE operator in access 10 sql query with variable.

Example:

temporary variable var contains value bs
var = "bs"

I want to match every String that starts with value of temporary variable followed by zero or more numbers.

I am trying to fire the query:

select * from xyz where variety LIKE "@[tempvars]![var] + [0-9]*"

It is returning 0 records.
Thankz for the help.

Body:
You need to refer to your tempvar outside of the quotes, and use & for concatenation:

select * from xyz where variety LIKE "@" & [tempvars]![var] & "[0-9]*"

This will return all records where variety starts with a literal @, then whatever is in [tempvars]![var], then a number, and then any amount of characters.


问:
Need to get Start Menu Paths in Java
Using java, I would like some code that could get me the paths for:
1) Start Menu for Current User
2) Start Menu for All User

I need the answer for both WinXP and Win7. So hopefully there is a general answer that can get me both.

答:
In my program I used a simple System.getProperty("user.home") + "/Start Menu/Programs" This gave me the user's Start Menu folder.

It worked on windows 7 and windows 10. I tried this because in order to get a user's desktop, all I had to do was call System.getProperty("user.home") + "/Desktop". SO I figured that it might work for the Start Menu as well, and seemed to have worked fine. I can delete and write files to the Start Menu just like I can with the desktop. Whether this is the right way to do something like this or not, I have no idea. But I'm just sharing what worked for me.

Title: Need to get Start Menu Paths in Java


问:
What is the most efficient to run certain lines of code only when a boolean is true?
If I had code that looked like the following:

```<code>if (bool1) {
    statement1
    statement2
} else if (bool2) {
    statement3
    statement4
}
</code>```

and I only want to run statement 2 and 4 given another boolean (say bool3) is true, what is the best way to format that. I understand that I could add a nested if statement, but that seems bad from a maintainability perspective if I have 5 or more else ifs.

Any suggestions?

答:
A nested if sounds perfectly fine to me at least. If none of the statements mess with bool1, bool3 and bool4 though and you really don't want to use nested ifs you could put them after eachother with conjunctions:

```<code>if (bool1) {
    statement1
}
if (bool1 && bool3) {
    statement2
}
if (bool2 && !bool1) {
    statement3
}
if (bool2 && !bool1 && bool3) {
    statement4
}
</code>```

This looks terrible though so I'd just go with a plain and simple nested if.

Body:
If I had code that looked like the following:

if (bool1) {
    statement1
    statement2
} else if (bool2) {
    statement3
    statement4
}

and I only want to run statement 2 and 4 given another boolean (say bool3) is true, what is the best way to format that. I understand that I could add a nested if statement, but that seems bad from a maintainability perspective if I have 5 or more else ifs.

Any suggestions?

Body:
A nested if sounds perfectly fine to me at least. If none of the statements mess with bool1, bool3 and bool4 though and you really don't want to use nested ifs you could put them after eachother with conjunctions:

if (bool1) {
    statement1
}
if (bool1 && bool3) {
    statement2
}
if (bool2 && !bool1) {
    statement3
}
if (bool2 && !bool1 && bool3) {
    statement4
}

This looks terrible though so I'd just go with a plain and simple nested if.


问:
how to get cookie from urlrequest in iOS wkwebview
```<code>func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    var req = navigationAction.request;
    let cookie = req.value(forHTTPHeaderField: "Cookie");
    print(cookie) // always nil

    decisionHandler(.allow);
}
</code>```

I want to get the session after user login, but the cookie is always nil;how can I get it ?

答:
Why don't use WKWebView's API that appeared since iOS 11

```<code>webView.configuration.websiteDataStore.httpCookieStore.getAllCookies() { cookies in
    // do what you need with cookies
}
</code>```

One advantage is that this method tracks HttpOnly cookies as well.

Body:
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    var req = navigationAction.request;
    let cookie = req.value(forHTTPHeaderField: "Cookie");
    print(cookie) // always nil

    decisionHandler(.allow);
}

I want to get the session after user login, but the cookie is always nil;how can I get it ?

Body:
Why don't use WKWebView's API that appeared since iOS 11

webView.configuration.websiteDataStore.httpCookieStore.getAllCookies() { cookies in
    // do what you need with cookies
}

One advantage is that this method tracks HttpOnly cookies as well.


问:
Git bash Error: Could not fork child process: There are no available terminals (-1)
I have had up to 8 git bash terminals running at the same time before.

Currently I have only 2 up.

I have not seen this error before and I am not understanding what is causing it.

Any help would be appreciated!

Picture attached:

答:
Restart your machine.

(The other answers did not work for me. (I didn't try reinstalling. Restarting is probably faster.))


问:
What is the difference between randi(x,y,1) and randsample(x,y,true)?
I usually use randsample, but I came across randi, and I'm wondering if there is any difference.

For example, these seem to be both picking random numbers from [1,10] and returning a 10 x 1 vector:

```<code>n = randi(10,10,1);
n2 = randsample(10,10,true);
</code>```

What is the difference between these two lines of code?

答:
Let us consider two sources:

The documentation of randsample, where we see:

y = randsample(s,...) uses the stream s for random number generation. s is a member of the RandStream class. Default is the MATLAB® default random number stream.

The source code of randsample (Copyright 1993-2010 The MathWorks, Inc.) we find the following behavior for the case when the 3rd input is true:

```<code>% Sample with replacement
case {true, 'true', 1}
    if n == 0
        if k == 0
            y = zeros(0,1);
        else
            error(message('stats:randsample:EmptyPopulation'));
        end
    elseif isempty(w)
        if defaultStream
            y = randi(n,k,1);
        else
            y = randi(s,n,k,1);
        end

    else
        % Irrelevant case as it concerns weighting which randi doesn't support.
    end
...
</code>```

So from the above we learn the following:

In some cases the input of randsample is just redirected to randi.

There's a slightly different behavior for edge cases, like randi(0,0,1) (which errors) vs. randsample(0,0,true) (which outputs an empty array).

Generally  randsample has more features: it is able to handle a non-default RandStream, and weighting.

Body:
I usually use randsample, but I came across randi, and I'm wondering if there is any difference.

For example, these seem to be both picking random numbers from [1,10] and returning a 10 x 1 vector:

n = randi(10,10,1);
n2 = randsample(10,10,true);

What is the difference between these two lines of code?

Body:
Let us consider two sources:

The documentation of randsample, where we see:

y = randsample(s,...) uses the stream s for random number generation. s is a member of the RandStream class. Default is the MATLAB® default random number stream.

The source code of randsample (Copyright 1993-2010 The MathWorks, Inc.) we find the following behavior for the case when the 3rd input is true:

% Sample with replacement
case {true, 'true', 1}
    if n == 0
        if k == 0
            y = zeros(0,1);
        else
            error(message('stats:randsample:EmptyPopulation'));
        end
    elseif isempty(w)
        if defaultStream
            y = randi(n,k,1);
        else
            y = randi(s,n,k,1);
        end

    else
        % Irrelevant case as it concerns weighting which randi doesn't support.
    end
...

So from the above we learn the following:

In some cases the input of randsample is just redirected to randi.

There's a slightly different behavior for edge cases, like randi(0,0,1) (which errors) vs. randsample(0,0,true) (which outputs an empty array).

Generally  randsample has more features: it is able to handle a non-default RandStream, and weighting.


问:
Deserializing json in Angular 2/4 using HttpClientModule
So I'm getting the following JSON structure from my asp.net core api:

```<code>{
  "contentType": null,
  "serializerSettings": null,
  "statusCode": null,
  "value": {
     "productName": "Test",
     "shortDescription": "Test 123",
     "imageUri": "https://bla.com/bla",
     "productCode": null,
     "continuationToken": null
  }
}
</code>```

I have the following typescript function that invokes the API to get the above response:

```<code>public externalProduct: ProductVM;

getProductExternal(code: string): Observable<ProductVM> {
    return this.http.get("api/product?productCode=" + code)
        .map((data: ProductVM) => {
            this.externalProduct = data; //not working...
            console.log("DATA: " + data);
            console.log("DATA: " + data['value']);
            return data;
        });
}
</code>```

ProductVM:

```<code>export interface ProductVM {

    productName: string;
    shortDescription: string;
    imageUri: string;
    productCode: string;
    continuationToken: string;
}
</code>```

My problem is that I can't deserialize it to ProductVM. The console logs just produce [object Object]

How can I actually map the contents of the value in my json response to a ProductVM object?

Is it wrong to say that data is a ProductVM in the map function? I have tried lots of different combinations but I cannot get it to work!

I'm unsure whether I can somehow automatically tell angular to map the value array in the json response to a ProductVM object or if I should provide a constructor to the ProductVM class (it's an interface right now), and extract the specific values in the json manually?

答:
From angular documentation: Typechecking http response

You have to set the type of returned data when using new httpClient ( since angular 4.3 ) => this.http.get<ProductVM>(...

```<code>public externalProduct: ProductVM;
getProductExternal(code: string): Observable<ProductVM> {
        return this.http.get<ProductVM>("api/product?productCode=" + code)
            .map((data: ProductVM) => {
                this.externalProduct = data; // should be allowed by typescript now
                return data;
            });
    }
</code>```

thus typescript should leave you in peace

Body:
So I'm getting the following JSON structure from my asp.net core api:

{
  "contentType": null,
  "serializerSettings": null,
  "statusCode": null,
  "value": {
     "productName": "Test",
     "shortDescription": "Test 123",
     "imageUri": "https://bla.com/bla",
     "productCode": null,
     "continuationToken": null
  }
}

I have the following typescript function that invokes the API to get the above response:

public externalProduct: ProductVM;

getProductExternal(code: string): Observable<ProductVM> {
    return this.http.get("api/product?productCode=" + code)
        .map((data: ProductVM) => {
            this.externalProduct = data; //not working...
            console.log("DATA: " + data);
            console.log("DATA: " + data['value']);
            return data;
        });
}

ProductVM:

export interface ProductVM {

    productName: string;
    shortDescription: string;
    imageUri: string;
    productCode: string;
    continuationToken: string;
}

My problem is that I can't deserialize it to ProductVM. The console logs just produce [object Object]

How can I actually map the contents of the value in my json response to a ProductVM object?

Is it wrong to say that data is a ProductVM in the map function? I have tried lots of different combinations but I cannot get it to work!

I'm unsure whether I can somehow automatically tell angular to map the value array in the json response to a ProductVM object or if I should provide a constructor to the ProductVM class (it's an interface right now), and extract the specific values in the json manually?

Body:
From angular documentation: Typechecking http response

You have to set the type of returned data when using new httpClient ( since angular 4.3 ) => this.http.get<ProductVM>(...

public externalProduct: ProductVM;
getProductExternal(code: string): Observable<ProductVM> {
        return this.http.get<ProductVM>("api/product?productCode=" + code)
            .map((data: ProductVM) => {
                this.externalProduct = data; // should be allowed by typescript now
                return data;
            });
    }

thus typescript should leave you in peace


问:
Checking value in an array from another array
So I wanted to see if it was possible to find values of two array's that are equal to each other but I am unsure how to do that.
This is what I have so far:

```<code>unusedArray = ["AS", "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "10S", "JS", "QS", "KS", "AD", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "10D", "JD", "QD", "KD", "AH", "2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H", "10H", "JH", "QH", "KH", "AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "10C", "JC", "QC", "KC"]
</code>```

value10 = ["10S", "10C", "10H", "10D"]

```<code>x = 0

for value10 in unusedArray:
   print(x)
   x += 1
</code>```

The printing of x is just to see how many times the for loop is running. Instead of the loop only running 4 times it runs 52(amount of values in the unusedArray)

答:
You could convert your lists to sets and use intersection()

```<code>u = set(list_1).intersection(set(list_2))
print(u)
print(len(u))
</code>```

Notice you can do this for more lists, e.g.

```<code>u = set(list_1).intersection(set(list_2), set(list_3))
print(u)
print(len(u))
</code>```

Otherwise:

```<code>u = [x for x in list_1 if x in list_2]
print(u)
print(len(u))
</code>```

Body:
So I wanted to see if it was possible to find values of two array's that are equal to each other but I am unsure how to do that.
This is what I have so far:

unusedArray = ["AS", "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "10S", "JS", "QS", "KS", "AD", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "10D", "JD", "QD", "KD", "AH", "2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H", "10H", "JH", "QH", "KH", "AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "10C", "JC", "QC", "KC"]

value10 = ["10S", "10C", "10H", "10D"]

x = 0

for value10 in unusedArray:
   print(x)
   x += 1

The printing of x is just to see how many times the for loop is running. Instead of the loop only running 4 times it runs 52(amount of values in the unusedArray)

Body:
You could convert your lists to sets and use intersection()

u = set(list_1).intersection(set(list_2))
print(u)
print(len(u))

Notice you can do this for more lists, e.g.

u = set(list_1).intersection(set(list_2), set(list_3))
print(u)
print(len(u))

Otherwise:

u = [x for x in list_1 if x in list_2]
print(u)
print(len(u))


问:
python GTK+ action in many files
I spread my code in several files but I do not know how to make the child file interact with the main file.

example fichier1:

```<code>#!/usr/bin/env python3
# coding: utf-8

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from TestMenu import Menu

class MainWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self)

        self.grid = Gtk.Grid()
        self.add(self.grid)

        self.label = Gtk.Label("An example of a Label widget.")

        self.menuBar = Menu()

        self.grid.attach(self.menuBar, 0, 0, 1, 1)
        self.grid.attach(self.label, 1, 0, 1, 1)

    def onClick(self, button):
        self.label.set_label('Test OK')

win = MainWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
</code>```

Fichier2:

```<code>import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class Menu(Gtk.Grid):

menuUi= "/home/vianney/programmes/Menu.ui"

def __init__(self):
    Gtk.Grid.__init__(self)

    action_group = Gtk.ActionGroup("my_actions")

    self.AddActionMenu(action_group)

    uimanager = self.create_ui_manager()
    uimanager.insert_action_group(action_group)

    menubar = uimanager.get_widget("/MenuBar")

    self.attach(menubar, 0, 0, 1, 1)

def AddActionMenu(self, action_group):
    action_group.add_actions([
        ("ActionMenu", None, "Edition"),
        ("AddGame", None, "Add Game", None, None, self.AddGame)
    ])

def AddGame(self, widget):
    self.label.set_label('Test OK')

def create_ui_manager(self):
    uimanager = Gtk.UIManager()
    uimanager.add_ui_from_file(self.menuUi)
    return uimanager
</code>```

here is the menu file:

```<code><ui>
    <menubar name='MenuBar'>
        <menu action='ActionMenu'>
            <menuitem action='AddGame' />
        </menu>
    </menubar>
</ui>
</code>```

in this example I would have changed the contents of the label in the file 1 belong to the file 2 menu

Thank you very much for your help

答:
There are many ways to achieve your goals but following the common Gtk way, would be to create signals to your own custom composite widgets.

Let's create a signal, called add-game-clicked, so when a user clicks that menu option a signal in the Menu class will be triggered / emitted.

To do that on your code, we add:

```<code>self.menu.connect ("add-game-clicked", self.onAddGameClicked)
</code>```

And then, rename the method onClick to something more meaningful like onAddGameClicked

So, your main python file, let's call it main.py, will be:

```<code>#!/usr/bin/env python3
# coding: utf-8

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from TestMenu import Menu

class MainWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self)

        self.grid = Gtk.Grid()
        self.add(self.grid)

        self.label = Gtk.Label("An example of a Label widget.")

        self.menuBar = Menu()
        self.menuBar.connect ("add-game-clicked", self.onAddGameClicked)

        self.grid.attach(self.menuBar, 0, 0, 1, 1)
        self.grid.attach(self.label, 1, 0, 1, 1)

    def onAddGameClicked(self, widget):
        self.label.set_label('Test OK')

win = MainWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
</code>```

Then we need to create a signal on your custom composite widget. To do that we add:

```<code>__gsignals__ = {
    'add-game-clicked': (GObject.SIGNAL_RUN_FIRST, None, ())
}
</code>```

below the class definition and then emit the signal when the right event happens:

```<code>def AddGame(self, widget):
    self.emit("add-game-clicked")
</code>```

Its important to say that python is: indentation, indentation, indentation, and your TestMenu.py file it's not correctly indented.

So your TestMenu.py file should be like this:

```<code>import gi
gi.require_version('Gtk', '3.0')
from gi.repository import GObject, Gtk

class Menu(Gtk.Grid):

    __gsignals__ = {
        'add-game-clicked': (GObject.SIGNAL_RUN_FIRST, None, ())
    }

    menuUi= "Menu.ui"

    def __init__(self):
        Gtk.Grid.__init__(self)

        action_group = Gtk.ActionGroup("my_actions")

        self.AddActionMenu(action_group)

        uimanager = self.create_ui_manager()
        uimanager.insert_action_group(action_group)

        menubar = uimanager.get_widget("/MenuBar")

        self.attach(menubar, 0, 0, 1, 1)

    def AddActionMenu(self, action_group):
        action_group.add_actions([
            ("ActionMenu", None, "Edition"),
            ("AddGame", None, "Add Game", None, None, self.AddGame)
        ])

    def AddGame(self, widget):
        self.emit("add-game-clicked")

    def create_ui_manager(self):
        uimanager = Gtk.UIManager()
        uimanager.add_ui_from_file(self.menuUi)
        return uimanager
</code>```

Also notice that setting full path to files in this context ain't good. Use relative paths in your project otherwise things become too rigid and less portable.

Using the supplied Menu.ui file we should get something like this:

After clicking the Add Game menu option, the label will change.

Title: python GTK+ action in many files

Body:
I spread my code in several files but I do not know how to make the child file interact with the main file.

example fichier1:

#!/usr/bin/env python3
# coding: utf-8

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from TestMenu import Menu

class MainWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self)

        self.grid = Gtk.Grid()
        self.add(self.grid)

        self.label = Gtk.Label("An example of a Label widget.")

        self.menuBar = Menu()

        self.grid.attach(self.menuBar, 0, 0, 1, 1)
        self.grid.attach(self.label, 1, 0, 1, 1)

    def onClick(self, button):
        self.label.set_label('Test OK')

win = MainWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

Fichier2:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class Menu(Gtk.Grid):

menuUi= "/home/vianney/programmes/Menu.ui"

def __init__(self):
    Gtk.Grid.__init__(self)

    action_group = Gtk.ActionGroup("my_actions")

    self.AddActionMenu(action_group)

    uimanager = self.create_ui_manager()
    uimanager.insert_action_group(action_group)

    menubar = uimanager.get_widget("/MenuBar")

    self.attach(menubar, 0, 0, 1, 1)

def AddActionMenu(self, action_group):
    action_group.add_actions([
        ("ActionMenu", None, "Edition"),
        ("AddGame", None, "Add Game", None, None, self.AddGame)
    ])

def AddGame(self, widget):
    self.label.set_label('Test OK')

def create_ui_manager(self):
    uimanager = Gtk.UIManager()
    uimanager.add_ui_from_file(self.menuUi)
    return uimanager

here is the menu file:

<ui>
    <menubar name='MenuBar'>
        <menu action='ActionMenu'>
            <menuitem action='AddGame' />
        </menu>
    </menubar>
</ui>

in this example I would have changed the contents of the label in the file 1 belong to the file 2 menu

Thank you very much for your help

Body:
There are many ways to achieve your goals but following the common Gtk way, would be to create signals to your own custom composite widgets.

Let's create a signal, called add-game-clicked, so when a user clicks that menu option a signal in the Menu class will be triggered / emitted.

To do that on your code, we add:

self.menu.connect ("add-game-clicked", self.onAddGameClicked)

And then, rename the method onClick to something more meaningful like onAddGameClicked

So, your main python file, let's call it main.py, will be:

#!/usr/bin/env python3
# coding: utf-8

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from TestMenu import Menu

class MainWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self)

        self.grid = Gtk.Grid()
        self.add(self.grid)

        self.label = Gtk.Label("An example of a Label widget.")

        self.menuBar = Menu()
        self.menuBar.connect ("add-game-clicked", self.onAddGameClicked)

        self.grid.attach(self.menuBar, 0, 0, 1, 1)
        self.grid.attach(self.label, 1, 0, 1, 1)

    def onAddGameClicked(self, widget):
        self.label.set_label('Test OK')

win = MainWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

Then we need to create a signal on your custom composite widget. To do that we add:

__gsignals__ = {
    'add-game-clicked': (GObject.SIGNAL_RUN_FIRST, None, ())
}

below the class definition and then emit the signal when the right event happens:

def AddGame(self, widget):
    self.emit("add-game-clicked")

Its important to say that python is: indentation, indentation, indentation, and your TestMenu.py file it's not correctly indented.

So your TestMenu.py file should be like this:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import GObject, Gtk

class Menu(Gtk.Grid):

    __gsignals__ = {
        'add-game-clicked': (GObject.SIGNAL_RUN_FIRST, None, ())
    }

    menuUi= "Menu.ui"

    def __init__(self):
        Gtk.Grid.__init__(self)

        action_group = Gtk.ActionGroup("my_actions")

        self.AddActionMenu(action_group)

        uimanager = self.create_ui_manager()
        uimanager.insert_action_group(action_group)

        menubar = uimanager.get_widget("/MenuBar")

        self.attach(menubar, 0, 0, 1, 1)

    def AddActionMenu(self, action_group):
        action_group.add_actions([
            ("ActionMenu", None, "Edition"),
            ("AddGame", None, "Add Game", None, None, self.AddGame)
        ])

    def AddGame(self, widget):
        self.emit("add-game-clicked")

    def create_ui_manager(self):
        uimanager = Gtk.UIManager()
        uimanager.add_ui_from_file(self.menuUi)
        return uimanager

Also notice that setting full path to files in this context ain't good. Use relative paths in your project otherwise things become too rigid and less portable.

Using the supplied Menu.ui file we should get something like this:

After clicking the Add Game menu option, the label will change.


问:
VBA Match function using today's date to search for last year's entry
So say I got Today's date =TODAY() and two matrixes with sales arranged by date.

```<code>Date      Store1  Store2
1/11/2017  800    2000
2/11/2017  500    3000
</code>```

and

```<code>Date       Store1  Store2
1/11/2016   400     5000
2/11/2016   2000    6000
</code>```

I'm trying to calculate how much sales increased on a date compared to last year's but I cant find any way that works.

```<code>Date       IncreaseStore1 IncreaseStore2
1/11
2/11
</code>```

I found this Function to get last year's date but it gives me the date as text and I cant find a way to fix it with VBA.

```<code>Function PrevYear(XYear As Date) As String

    PrevYear = Format(Format(XYear, "dd/mm") & "/" & Format(XYear, "yyyy") - 1, "dd/mm/yyyy")

End Function
</code>```

Any help would be appreciated since I'm all out of ideas

答:
Your question is a bit unclear. Here is a function that returns a date rather than a string.</p>

```<code>Function PrevYear(XYear As Date) As Date
    PrevYear = DateAdd("YYYY", -1, XYear)
End Function
</code>```

Body:
So say I got Today's date =TODAY() and two matrixes with sales arranged by date.

Date      Store1  Store2
1/11/2017  800    2000
2/11/2017  500    3000

and

Date       Store1  Store2
1/11/2016   400     5000
2/11/2016   2000    6000

I'm trying to calculate how much sales increased on a date compared to last year's but I cant find any way that works.

Date       IncreaseStore1 IncreaseStore2
1/11
2/11

I found this Function to get last year's date but it gives me the date as text and I cant find a way to fix it with VBA.

Function PrevYear(XYear As Date) As String

    PrevYear = Format(Format(XYear, "dd/mm") & "/" & Format(XYear, "yyyy") - 1, "dd/mm/yyyy")

End Function

Any help would be appreciated since I'm all out of ideas

Body:
Your question is a bit unclear. Here is a function that returns a date rather than a string.

Function PrevYear(XYear As Date) As Date
    PrevYear = DateAdd("YYYY", -1, XYear)
End Function