text:
Q: How are instances of class objects used to build applications? I'm currently working on an assignment about OOP and I'm a bit stuck on figuring out some examples of how class objects are used to build applications. I'm assuming it means things such as buttons, labels and that type of thing?
Thank you for reading!


text:
Q: Tomcat - MySQL - Hibernate - c3p0 timeout/broken pipe I've been struggling to make my web application(s) stop throwing broken pipe/timeout exceptions. I've read many threads (here, here, here, here and others) and blogs, but to no avail.
I have c3p0-0.9.1.2.jar, hibernate-c3p0-4.1.1.Final.jar, hibernate-core-4.1.1.Final.jar and all required jar files in my WEB-INF/lib folder. I don't think the version is the problem but I figured, I should list the details. Apache Tomcat/6.0.24, MySQL Ver 14.14 Distrib 5.1.70. All this running on Ubuntu 10.04.4 LTS, lucid.
I get the following exceptions in my catalina log after 8 hours of (db) inactivity:
10:18:45,657 WARN SqlExceptionHelper:143 - SQL Error: 0, SQLState: 08S01
10:18:45,660 ERROR SqlExceptionHelper:144 - The last packet successfully received from the server was 69,956,254 milliseconds ago. The last packet sent successfully to the server was 69,956,255 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.
org.hibernate.exception.JDBCConnectionException: The last packet successfully received from the server was 69,956,254 milliseconds ago. The last packet sent successfully to the server was 69,956,255 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:131)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at sun.proxy.$Proxy24.executeQuery(Unknown Source)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1962)
at org.hibernate.loader.Loader.doQuery(Loader.java:829)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:289)
at org.hibernate.loader.Loader.doList(Loader.java:2447)
at org.hibernate.loader.Loader.doList(Loader.java:2433)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2263)
at org.hibernate.loader.Loader.list(Loader.java:2258)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:470)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:355)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:196)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1161)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
at gr.adds.myapp.server.db.DB.getBFromUser(DB.java:49)
at gr.adds.myapp.server.BSImpl.getBusesInfo(BSImpl.java:57)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:569)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.jk.server.JkCoyoteHandler.invoke(JkCoyoteHandler.java:190)
at org.apache.jk.common.HandlerRequest.invoke(HandlerRequest.java:291)
at org.apache.jk.common.ChannelSocket.invoke(ChannelSocket.java:769)
at org.apache.jk.common.ChannelSocket.processConnection(ChannelSocket.java:698)
at org.apache.jk.common.ChannelSocket$SocketConnection.runIt(ChannelSocket.java:891)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:690)
at java.lang.Thread.run(Thread.java:679)
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 69,956,254 milliseconds ago. The last packet sent successfully to the server was 69,956,255 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:532)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1116)
at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3364)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1983)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2624)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2127)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2293)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:76)
at sun.reflect.GeneratedMethodAccessor37.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
... 41 more
Caused by: java.net.SocketException: Broken pipe
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109)
at java.net.SocketOutputStream.write(SocketOutputStream.java:153)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3345)
... 51 more

Here is my hibernate.cfg.xml:
<session-factory>
    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/mydb?autoReconnect=true</property>
    <property name="connection.username">dbuser</property>
    <property name="connection.password">dbpass</property>
    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">thread</property>
    <!-- Disable the second-level cache -->
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">false</property>
    <!-- Drop and re-create the database schema on startup -->
    <property name="hibernate.hbm2ddl.auto">update</property>
    <property name="hibernate.connection.useUnicode">true</property>
    <property name="hibernate.connection.characterEncoding">UTF-8</property>
    <!-- hibernate.cfg.xml -->

    <property name="connection.autoReconnect">true</property>
    <property name="connection.autoReconnectForPools">true</property>
    <property name="connection.is-connection-validation-required">true</property>
    <property name="current_session_context_class">thread</property>
    <!-- <property name="max_fetch_depth">1</property> -->

    <property name="hibernate.connection.provider_class">org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider</property>
<!--        <property name="hibernate.c3p0.initial_size">5</property>  -->
<!--        <property name="hibernate.c3p0.min_size">5</property> -->
<!--        <property name="hibernate.c3p0.max_size">50</property> -->
<!--        <property name="hibernate.c3p0.timeout">1800</property> -->
<!--        <property name="hibernate.c3p0.max_statements">250</property> -->

<!--        <property name="hibernate.c3p0.idle_test_period">60</property> -->
<!--        <property name="hibernate.c3p0.acquire_increment">5</property> -->
    <property name="hibernate.c3p0.numHelperThreads">3</property>
    <!-- no "connection.pool_size" entry! -->
    <!-- JDBC connection pool (use the built-in) -->
    <!-- <property name="connection.pool_size">1</property> -->
<!--        <property name="hibernate.transaction.auto_close_session">false</property> -->
    <property name="hibernate.c3p0.acquire_increment">3</property>
    <property name="hibernate.c3p0.idle_test_period">25200</property>
    <property name="hibernate.c3p0.timeout">1800</property>
    <property name="hibernate.c3p0.max_size">15</property>
    <property name="hibernate.c3p0.min_size">3</property>
    <property name="hibernate.c3p0.max_statements">250</property>

    <property name="hibernate.c3p0.preferredTestQuery">SELECT 1;</property>
    <property name="hibernate.c3p0.testConnectionOnCheckout">true</property>

    <!-- Mapping files -->
            ...
</session-factory>

Also, I have a c3p0.properties file in the same folder as hibernate.cfg.xml:
c3p0.testConnectionOnCheckout=true
c3p0.preferredTestQuery=SELECT 1;
com.mchange.v2.c3p0.management.ManagementCoordinator=com.mchange.v2.c3p0.management.NullManagementCoordinator

My tomcat tomcat6/conf/server.xml file has:
<Connector port="8080" protocol="AJP/1.3" connectionTimeout="20000" URIEncoding="UTF-8" redirectPort="8443" />

My /etc/mysql/my.conf file is default.
I should tell you I tried many many combinations.
To start, adding the wait_timeout in /etc/mysql/my.conf doesn't seem to have any effect (UPDATED->READ UPDATE BELOW). I changed it to 60 (for 60 seconds), waited a few minutes and did not get the exception I was expecting. I haven't waited 8 hours since putting that value there but I believe the results would be the same. Without the wait_timeout property, after 8 hours I get similar exceptions as above every time (with only time difference).
I've read that the hibernate.c3p0.idle_test_period should be less than the mysql wait_timeout, which it is why I have 7 hours (25200 seconds) for the first while the latter by default is 8 hours. I've played around with the other values as well but they don't seem to matter. You see several commented out values in my hibernate.cfg.xml file above because I've tried many many combinations. I've read that the testConnectionOnCheckout is expensive but I added it to see if I can make this work.
Of course, restarting tomcat (sudo service tomcat6 restart) works, but this is not the solution.
Does anyone have an idea what I can try/change to make this stop giving me this exception? Any "magic" values that will make it work?
UPDATE:
Ok, I wasn't putting the wait_timout inside [mysqld].
So I put in my.conf
wait_timeout=120

and in hibernate.cfg.xml:
<property name="hibernate.c3p0.idle_test_period">80</property>
<property name="hibernate.c3p0.timeout">60</property>

Now the error I get is:
14:15:41,746 WARN NewPooledConnection:486 - [c3p0] A PooledConnection that has already signalled a Connection error is still in use!
14:15:41,747 WARN NewPooledConnection:487 - [c3p0] Another error has occurred [ com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed. ] which will not be reported to listeners!
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:532)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1013)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ConnectionImpl.throwConnectionClosedException(ConnectionImpl.java:1205)
at com.mysql.jdbc.ConnectionImpl.checkClosed(ConnectionImpl.java:1197)
at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4186)
at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4152)
at sun.reflect.GeneratedMethodAccessor31.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at com.mchange.v2.c3p0.stmt.GooGooStatementCache$1StmtAcquireTask.run(GooGooStatementCache.java:525)
at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547)
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet successfully received from the server was 300,078 milliseconds ago. The last packet sent successfully to the server was 18 milliseconds ago.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:532)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1116)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3102)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2991)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3532)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2624)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2127)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2293)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:76)
at sun.reflect.GeneratedMethodAccessor37.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at sun.proxy.$Proxy24.executeQuery(Unknown Source)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1962)
at org.hibernate.loader.Loader.doQuery(Loader.java:829)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:289)
at org.hibernate.loader.Loader.doList(Loader.java:2447)
at org.hibernate.loader.Loader.doList(Loader.java:2433)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2263)
at org.hibernate.loader.Loader.list(Loader.java:2258)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:470)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:355)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:196)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1161)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
at gr.adds.myapp.server.db.DB.getBFromUser(DB.java:49)
at gr.adds.myapp.server.BSImpl.getBusesInfo(BSImpl.java:57)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:569)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.jk.server.JkCoyoteHandler.invoke(JkCoyoteHandler.java:190)
at org.apache.jk.common.HandlerRequest.invoke(HandlerRequest.java:291)
at org.apache.jk.common.ChannelSocket.invoke(ChannelSocket.java:769)
at org.apache.jk.common.ChannelSocket.processConnection(ChannelSocket.java:698)
at org.apache.jk.common.ChannelSocket$SocketConnection.runIt(ChannelSocket.java:891)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:690)
at java.lang.Thread.run(Thread.java:679)
Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2552)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3002)
... 53 more
14:15:41,751 WARN SqlExceptionHelper:143 - SQL Error: 0, SQLState: 08003
14:15:41,752 ERROR SqlExceptionHelper:144 - No operations allowed after connection closed.
org.hibernate.exception.JDBCConnectionException: No operations allowed after connection closed.
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:68)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.proxy.ConnectionProxyHandler.continueInvocation(ConnectionProxyHandler.java:146)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at sun.proxy.$Proxy23.prepareStatement(Unknown Source)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:147)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:166)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:145)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1720)
at org.hibernate.loader.Loader.doQuery(Loader.java:828)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:289)
at org.hibernate.loader.Loader.doList(Loader.java:2447)
at org.hibernate.loader.Loader.doList(Loader.java:2433)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2263)
at org.hibernate.loader.Loader.list(Loader.java:2258)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:470)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:355)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:196)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1161)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
at gr.adds.myapp.server.db.DB.getBFromUser(DB.java:49)
at gr.adds.myapp.server.BSImpl.getBusesInfo(BSImpl.java:57)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:569)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.jk.server.JkCoyoteHandler.invoke(JkCoyoteHandler.java:190)
at org.apache.jk.common.HandlerRequest.invoke(HandlerRequest.java:291)
at org.apache.jk.common.ChannelSocket.invoke(ChannelSocket.java:769)
at org.apache.jk.common.ChannelSocket.processConnection(ChannelSocket.java:698)
at org.apache.jk.common.ChannelSocket$SocketConnection.runIt(ChannelSocket.java:891)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:690)
at java.lang.Thread.run(Thread.java:679)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:532)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1013)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ConnectionImpl.throwConnectionClosedException(ConnectionImpl.java:1205)
at com.mysql.jdbc.ConnectionImpl.checkClosed(ConnectionImpl.java:1197)
at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4186)
at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4152)
at sun.reflect.GeneratedMethodAccessor31.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at com.mchange.v2.c3p0.stmt.GooGooStatementCache$1StmtAcquireTask.run(GooGooStatementCache.java:525)
at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547)
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

Any ideas? Shouldn't the wait_timeout > c3p0.idle_test_period > c3p0.timeout?
UPDATE 7th Oct:
Still same timeout, but I added logging info in my log4j.properties file to make sure c3p0 is running with the desired values in my hibernate.cfg.xml file and sure enough I got:
11:13:09,393 INFO MLog:92 - MLog clients using log4j logging.
11:13:09,477 INFO C3P0Registry:216 - Initializing c3p0-0.9.2.1 [built 20-March-2013 11:16:28 +0000; debug? true; trace: 10]
11:13:09,627 INFO AbstractPoolBackedDataSource:522 - Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@3d0991ef [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@b336cd6b [ acquireIncrement -> 1, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, debugUnreturnedConnectionStackTraces -> false, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> z8kflt8x14i4fy2kk9fga|7eac4d3b, idleConnectionTestPeriod -> 60, initialPoolSize -> 3, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 120, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 25, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 1, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@ebdc296f [ description -> null, driverClass -> null, factoryClassLocation -> null, identityToken -> z8kflt8x14i4fy2kk9fga|1fbbc779, jdbcUrl -> jdbc:mysql://localhost:3306/mydb?autoReconnect=true, properties -> {autoReconnect=true, is-connection-validation-required=true, useUnicode=true, user=******, password=******, characterEncoding=UTF-8, autoReconnectForPools=true} ], preferredTestQuery -> select 1;, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false; userOverrides: {} ], dataSourceName -> null, factoryClassLocation -> null, identityToken -> z8kflt8x14i4fy2kk9fga|27b104d7, numHelperThreads -> 3 ]

Also updated to the latest libraries just in case, but still the same: c3p0-0.9.2.1.jar, hibernate-c3p0-4.2.6.Final.jar, hibernate-commons-annotations-4.0.2.Final.jar, hibernate-core-4.2.6.Final.jar, mysql-connector-java-5.1.26-bin.jar.

A: This kind of thing is almost always caused by a firewall or some other networking component shutting-down an idle connection. The solution is to use a connection-test statement, which is looks like you're doing. I don't know anything about C3P0 (other than that it hasn't release 1.0 yet) so I can't tell if your configuration is correct for preventing idle-timeouts.
I'm wondering why you aren't using Tomcat's built-in connection pool. It seems to work perfectly fine and configurations Just Work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: about the key "defer"and "select" in Go func TestContext(t *testing.T){
    message:=make(chan int,10)
    //producer
    for i:=0;i<10;i++{
        message<-i
    }

    //consumer
    ctx,cancel:=context.WithTimeout(context.Background(),time.Second*5)

    go func(ctx context.Context) {
            ticker := time.NewTicker(1 * time.Second)
            for _ = range ticker.C {
                select {
                case <-ctx.Done():
                    fmt.Println("child process interrupt...")
                    return
                default:
                    fmt.Printf("send message: %d\n", <-message)
                }
            }
        }(ctx)

    defer close(message)
    defer cancel()
    select{
        case <-ctx.Done():
            //time.Sleep(1*time.Second)
            fmt.Println("main process exit!")
    }

}

Q1: when is the "defer cancel" executed? after select ?
Q2: In Q1,if "defer cancel" is executed after select , will the ctx.Done() return nil? and will the select be blocked?

A: All deferred function calls will run after the function body runs, but before the function returns, so yes, defer cancel will execute after select.
Select will block until the context times out. When the context times out, the <-ctx.Done() case will be enabled, so select can continue after the context timeout.


text:
Q: Search Radius for Line Density I have been working with GIS for many years but I am fairly new to the spatial analyst side of things. I am working with many satellite tracks for many different individual animals and would like to determine a migratory corridor for these animals. We have decided to use line density for the analysis of these data. Our question is: how to determine the search radius, which I have learned is very important?
I found out that one way to do this would be to use the tools on movebank.org like ArcMET and Home Range Tools. However to use these tools, a time/date stamp is required for every point on the satellite track and we do not have this information for all of the points. This is also the reason why we decided to use line density instead of kernel density. So we decided to use line density in ArcGIS.
I found that one way that many people determine a search radius for point density or kernel density is by using the Incremental Spatial Autocorrelation. However to perform this type of spatial statistics, one needs count data/incidence data. Since these are satellite tracks, the data inherently is only one animal per track (line).
So based on these issues, does anyone have any ideas on how to determine the search radius? Any other spatial statistics that we could use?


text:
Q: CSS Fluid Width inside div with fixed width I have two divs inside a wrapper div of width 880px.
The first div contains an image which can be any width, I'd like the second width to scale with it i.e:
Div 1 = 300px
Div 2 = 580px << this div scales to fit the parent div.
Setting a width of 100% on the second div ignores the fixed width on the parent div.
Is this possible using only css or would I have to use javascript/jquery (jquery is already loaded so it's not too big a hassle)?
Thanks!

A: With CSS, you can only set dimensions that are directly relative to an element's content, one if its parents, the font size, or to the screen resolution, but not to the dimensions of its siblings.* This means that, in order for the second block to be the same width as the image, it should "inherit" the width from a parent, or have it set dynamically. For example:
#wrapper {
    float: left;
}

…

The float property on the #wrapper block makes its width fit its contents. The width of the #fits_img block is auto or 100% by default (since it's a div element), so its width will fit #wrapper and therefore be indirectly relative to the width of the image.
If you can't make the #wrapper element float, you could also mirror the width with jQuery like so:
$(document).ready(function()
{
    $('#fits_img').width($('#image').width());
});

* Note that there are also absolute units like 'cm', but they're relatively useless and rarely used.

A: copy/paste the code below and try changing the image's width and see what happens.

a sadasd wqe sad asdqwe qweqwedasdasdqwe qwe qwe


text:
Q: How to delete contacts from iPhone? I just set up my brand new iPhone 5 running iOS 6. I set it up as a new device.
I have been using Exchange to sync my contacts with Google (Gmail) Contacts for the past few days. Today I stopped doing that and started syncing via CardDAV.
However I have some contacts that I can't delete. In fact, if I turn off all contact syncing (including iCloud) I am still left with 50 contacts that I can't delete. I try to delete them, but they just stay there.
Any thoughts on how to solve this?
Update: Note that I have tried a restore (and restored from backup) on the iPhone and this did not fix it.

A: Just go to your contact via contacts app icon. Select desired contact then click edit in top right corner and then scroll down to very bottom and click delete contact, voilá!


text:
Q: Android: Googe Map is null although initialized I have a Maps Fragment with a MapView inside.
I initialise a Google Map Object in the onMapReady Method and the marker I set in this method at the beginning works fine. But as soon as I want to modify the marker or set a new one in another custom Method, I get a NullPointerException saying that my googleMap object is null. Which it should not be due to the fact that it has been already initialised.
Your help would be very much appreciated. Thank you very much in advance.
Here's my code:
This is what the beginning ofmy fragment activity looks like:
public class MapsFragment extends Fragment implements OnMapReadyCallback {

MapView mMapView;
private GoogleMap googleMap;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_maps, container, false);

    mMapView = (MapView) rootView.findViewById(R.id.mapView);
    mMapView.onCreate(savedInstanceState);

    mMapView.onResume(); // needed to get the map to display immediately

    try {
        MapsInitializer.initialize(getActivity().getApplicationContext());
    } catch (Exception e) {
        e.printStackTrace();
    }

    mMapView.getMapAsync(this);

    return rootView;
}

This is the onMapReady Method:
@Override
public void onMapReady(GoogleMap gMap) {
    // The global variable googleMap gets initialised
    googleMap = gMap;
    LatLng sydney = new LatLng(-33.852, 151.211);
    googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}

This is my custom user called method:
 public void updateCamera(String search_string) {

   LatLng search_string_place = new LatLng(-37.9712371, 144.4927088);

   // THIS is where the NullPointer exception happens for the first time
   googleMap.addMarker(new
   MarkerOptions().position(search_string_place).title(Melbourne));

   googleMap.moveCamera(CameraUpdateFactory.newLatLng(search_string_place));
 }

All methods are in the same class: MapsFragment
Edit:
Error Log:
FATAL EXCEPTION: main
Process: <packagename>, PID: 26556
java.lang.IllegalStateException: Could not execute method of the activity
  at android.view.View$1.onClick(View.java:3830)
  at android.view.View.performClick(View.java:4445)
  at android.view.View$PerformClick.run(View.java:18446)
  at android.os.Handler.handleCallback(Handler.java:733)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:136)
  at android.app.ActivityThread.main(ActivityThread.java:5146)
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:515)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
  at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:515)
  at android.view.View$1.onClick(View.java:3825)
  ... 11 more
Caused by: java.lang.NullPointerException
  at <packagename>.MapsFragment.updateCamera(MapsFragment.java:134)
  at <packagename>.MainActivity.callUpdateCamera(MainActivity.java:46)
  ... 14 more

My manifest file:
<?xml version="1.0" encoding="utf-8"?>

<!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    android:name="android.support.multidex.MultiDexApplication">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <!--
         The API key for Google Maps-based APIs is defined as a string resource.
         (See the file "res/values/google_maps_api.xml").
         Note that the API key is linked to the encryption key used to sign the APK.
         You need a different API key for each encryption key, including the release key that is used to
         sign the APK for publishing.
         You can define the keys for the debug and release targets in src/debug/ and src/release/.
    -->
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

</application>

EDIT:
I solved the problem by just putting everything in one class/activity. Then all the calls worked fine. I think the problem was that I created a new instance of the MapsFragment and in this new instance the global var googleMap was undefined.
Thank you very much for all the answers.

A: Had the same problem, it worked when I changed GoogleMap object to static

A: I don't know where you call your custom method, but you could try to pass the initialized map to your method to be sure you can access it.
Try this:
public void updateCamera(String search_string, GoogleMap googleMap) {

   LatLng search_string_place = new LatLng(-37.9712371, 144.4927088);

   // THIS is where the NullPointer exception happens for the first time
   googleMap.addMarker(new
   MarkerOptions().position(search_string_place).title(Melbourne));

   googleMap.moveCamera(CameraUpdateFactory.newLatLng(search_string_place));
 }


text:
Q: Optimization Tips int *s;
allocate memory for s[100];
void func (int *a, int *b)
{
    int i;

    for (i = 0; i < 100; i++)
    {
        s[i] = a[i] ^ b[i];
    }
}

Assume that this particular code snippet is being called 1000 times, and this is the most time consuming operation in my code. Also assume that addresses of a and b is changed every time. 's' is a global variable which is updated with different sets of values of a & b.
As far as I assume, the main performance bottleneck would be memory access, because the only other operation is XOR, which is very trivial.
Would you please suggest how can I optimize my code in the best possible way?
the question I really wanted to ask, but I think it didn't get properly conveyed is, let for example this for loop contains 10 such XOR operations, the loop count is 100 and the function is called 1000 times, the point is high memory access..If the code is to be executed on a single core machine, what are scopes for improvement?

A: I've tested proposed solutions, and other two. I was not able to test onemasse' proposal as the result saved to s[] was not correct. I was not able to fix it too. I had to do some changes on moonshadow code. The measurement unit is clock cycles, so lower is better.
Original code:
#define MAX 100
void inline STACKO ( struct timespec *ts, struct timespec *te ){

    int i, *s, *a, *b;

    for (i = 0; i < MAX; ++i){
        s = (int *) malloc (sizeof (int)); ++s;
        a = (int *) malloc (sizeof (int)); ++a;
        b = (int *) malloc (sizeof (int)); ++b;
    }

    srand ( 1024 );
    for (i = 0; i < MAX; ++i){
        a[i] = ( rand() % 2 );
        b[i] = ( rand() % 2 );
    }

    rdtscb_getticks ( ts ); /* start measurement */

    for (i = 0; i < MAX; i++)
        s[i] = a[i] ^ b[i];

    rdtscb_getticks ( te ); /* end measurement */

/*
    printf("\n");
    for (i = 0; i < MAX; ++i)
        printf("%d", s[i]);
    printf("\n");
*/
}

New proposal 1: register int
From:
int i, *s, *a, *b;

To:
register int i, *s, *a, *b;

New proposal 2: No array notation
s_end = &s[MAX];
for (s_ptr = &s[0], a_ptr = &a[0], b_ptr = &b[0]; \
   s_ptr < s_end; \
   ++s_ptr, ++a_ptr, ++b_ptr){
    *s_ptr = *a_ptr ^ *b_ptr;
}

moonshadow proposed optimization:
s_ptr = &s[0];
a_ptr = &a[0];
b_ptr = &b[0];

for (i = 0; i < (MAX/4); i++){

    s_ptr[0] = a_ptr[0] ^ b_ptr[0];
    s_ptr[1] = a_ptr[1] ^ b_ptr[1];
    s_ptr[2] = a_ptr[2] ^ b_ptr[2];
    s_ptr[3] = a_ptr[3] ^ b_ptr[3];
    s_ptr+=4; a_ptr+=4; b_ptr+=4;
}

moonshadow proposed optimization + register int:
From:
int i, *s, ...

To:
register int i, *s, ...

Christoffer proposed optimization:
#pragma omp for
for (i = 0; i < MAX; i++)
{
    s[i] = a[i] ^ b[i];
}

Results:

Original Code   1036.727264
New Proposal 1  611.147928
New proposal 2  450.788845
moonshadow      713.3845
moonshadow2     452.481192
Christoffer     1054.321943

There is other simple way of optimizing the resulting binary. Passing -O2 to gcc tells that you want optimization. To know exactly what -O2 does, refer to gcc man page.
After enabling -O2:

Original Code   464.233031
New Proposal 1  452.620255
New proposal 2  454.519383
moonshadow      428.651083
moonshadow2     419.317444
Christoffer     452.079057

Source codes available at: http://goo.gl/ud52m

A: Don't use the loop variable to index.
Unroll the loop.
for (i = 0; i < (100/4); i++)
{
  s[0] = a[0] ^ b[0];
  s[1] = a[1] ^ b[1];
  s[2] = a[2] ^ b[2];
  s[3] = a[3] ^ b[3];
  s+=4; a+=4; b+=4;
}

Work out how to perform SIMD XOR on your platform.
Performing these XORs as an explicit step is potentially more expensive than doing them as part of another calculation: you're having to read from a and b and store the result in s - if s is read again for more calculation, you'd save a read and a write per iteration, and all the function call and loop overhead, by doing the XOR there instead; likewise, if a and b are outputs of some other functions, you do better by performing the XOR at the end of one of those functions.

A: int *s;
allocate memory for s[100];
void func (int *a, int *b)
{
    int i;

    #pragma omp for
    for (i = 0; i < 100; i++)
    {
        s[i] = a[i] ^ b[i];
    }
}

Of course, for only a hundred elements you might not see any particular improvement :-)

A: Just a guess here. If this is a cache issue you could try this:
int *s;
allocate memory for s[100];
void func (int *a, int *b)
{
    int i;

    memcpy( s, a, 100 );

    for (i = 0; i < 100; i++)
    {
        s[i] = s[i] ^ b[i];
    }
}

The memcpy, although it's a function call will often be inlined by the compiler if the size argument is a constant. Loop unrolling will probably not help here as it can be done automatically by the compiler. But you shouldn't take my word for it, verify on your platform.


text:
Q: Make bibliography not part of previous chapter I'm writing my thesis and I have a problem with references:
The references span across two pages. On the top of the second page there is a header (that appears on every page where a new chapter does not begin). The header informs a reader about the current chapter he/she is reading. But in the references it says "Conclusion", which is my last chapter. I would like this not to appear in the references (or say "References"). There are some other chapters after References, that I would like to keep their headers (\appendix).
This is the code to create references (bibtex):
\bibliographystyle{plain}
\bibliography{thesisrefs}

This makes the headers:
\def\ps@thesisheadings{%
\def\chaptermark##1{%
\markright{%
\ifnum\c@secnumdepth >\m@ne
\thechapter.\ %
\fi ##1}}
\let\@oddfoot\@empty
\let\@oddhead\@empty
\def\@oddhead{\vbox{\hbox to \textwidth{%
\hfil{\sc\rightmark}}\vskip 4pt\hrule}}
\if@twoside
 \def\@evenhead{\vbox{\hbox to \textwidth{%
 {\sc\rightmark}\hfil}\vskip 4pt\hrule}}
\else
 \let\@evenhead\@oddhead
\fi
\def\@oddfoot{\hfil\PageFont\thepage}
\if@twoside
 \def\@evenfoot{\PageFont\thepage\hfil}%
\else
 \let\@evenfoot\@oddfoot
\fi
}

A: Evidently your bibliography command doesn't update the running heads. Judging from your code, you just need to call \chaptermark{References} (manually or automatically) when the bibliography starts.
Presumably this doesn't happen because your bibliography is a section, not a chapter. If you don't like the idea of calling \chaptermark for a section, just call \markright directly.


text:
Q: Hidden junk characters in XML files
Possible Duplicate:
How to remove invisible junk characters from a XML file

I am getting these() type of hidden junk characters in my xml files.How can I remove these using C# code.
I have so many xml files like this.
Please help me.
Thanks in advance.


text:
Q: Running integration tests in Github actions: issues with connecting with postgres I have some integration tests that, in order to succesfully run, require a running postgres database, setup via docker-compose, and my go app running from main.go. Here is my docker-compose:
version: "3.9"
services:

  postgres:
    image: postgres:12.5
    user: postgres
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: password
      POSTGRES_DB: my-db
    ports:
      - "5432:5432"
    volumes:
      - data:/var/lib/postgresql/data
      - ./initdb:/docker-entrypoint-initdb.d
networks:
  default:
    driver: bridge

volumes:
  data:
    driver: local

and my Github Actions are as follows:
jobs:
  unit:
    name: Test
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:12.5
        env:
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: password
          POSTGRES_DB: my-db
        ports:
          - 5432:5432
    env:
      GOMODCACHE: "${{ github.workspace }}/.go/mod/cache"
      TEST_RACE: true
   steps:
     - name: Initiate Database
       run: psql -f initdb/init.sql postgresql://postgres:password@localhost:5432/my-db

     - name: Set up Cloud SDK
       uses: google-github-actions/setup-gcloud@v0

     - name: Authenticate with GCP
       id: auth
       uses: "google-github-actions/auth@v0"
       with: credentials_json: ${{ secrets.GCP_ACTIONS_SECRET }}

     - name: Configure Docker
       run: |
         gcloud auth configure-docker "europe- docker.pkg.dev,gcr.io,eu.gcr.io"

     - name: Set up Docker BuildX
       uses: docker/setup-buildx-action@v1

     - name: Start App
       run: |
         VERSION=latest make images
         docker run -d -p 3000:3000 -e      POSTGRES_DB_URL='//postgres:password@localhost:5432/my-db?sslmode=disable' --name='app' image/app

     - name: Tests
       env:
        POSTGRES_DB_URL: //postgres:password@localhost:5432/my-db?sslmode=disable
      GOMODCACHE: ${{ github.workspace }}/.go/pkg/mod
       run: |
         make test-integration
         docker stop app

My tests run just fine locally firing off the docker-compose with docker-compose up and running the app from main.go. However, in Github actions I am getting the following error:
failed to connect to `host=/tmp user=nonroot database=`: dial error (dial unix /tmp/.s.PGSQL.5432: connect: no such file or directory

What am I missing? Thanks

A: I think this code has more than one problem.
Problem one:
In your code I don't see you run docker-compose up, therefore I would assume that Postgres is not running.
Problem two:
is in this line: docker run -d -p 3000:3000 -e POSTGRES_DB_URL='//postgres:password@localhost:5432/my-app?sslmode=disable' --name='app' image/app
You point the host of Postgres to localhost, which on your local machine works. As there localhost is your local comuter. Though, as you use docker run you are not running this on your local machine, but in a docker container. There localhost is pointing to inside the conmtainer.
Posible solution for both
As you are already using docker-compose I suggest you to also add your test web server there.
Change your docker-compose file to:
version: "3.9"
services:

  webapp:
    build: image/app
    environment:
      POSTGRES_DB_URL='//postgres:password@postgres:5432/my-app?sslmode=disable'
    ports:
      - "3000:3000"
    depends_on:
      - "postgres"

  postgres:
    image: postgres:12.5
    user: postgres
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: password
      POSTGRES_DB: my-app
    ports:
      - "5432:5432"
    volumes:
      - data:/var/lib/postgresql/data
      - ./initdb:/docker-entrypoint-initdb.d
networks:
  default:
    driver: bridge

volumes:
  data:
    driver: local

If you now run docker-compose up, both services will be available. And it should work. Though I am not a github-actions expert, so I might have missed something. At least like this, you can run your tests locally the same way as in CI, something that I always see as a big plus.

A: What you are missing is setting up the actual Postgres Client inside the Github Actions server (that is why there is no psql tool to be found).
Set it up as a step.
     - name: Install PostgreSQL client
        run: |
          apt-get update
          apt-get install --yes postgresql-client

Apart from that, if you run everything through docker-compose you will need to wait for postgres to be up and running (healthy & accepting connections).
Consider the following docker-compose:
version: '3.1'

services:
  api:
    build: .
    depends_on:
      - db
    ports:
      - 8080:8080
    environment:
      - RUN_UP_MIGRATION=true
      - PSQL_CONN_STRING=postgres://gotstock_user:123@host.docker.internal:5432/gotstockapi?sslmode=disable
    command: ./entry

  db:
    image: postgres:9.5-alpine
    restart: always
    environment:
      - POSTGRES_USER=root
      - POSTGRES_PASSWORD=password
    ports:
      - "5432:5432"
    volumes:
      - ./db:/docker-entrypoint-initdb.d/

There are a couple of things you need to notice. First of all, in the environment section of the api we have PSQL_CONN_STRING=postgres://gotstock_user:123@host.docker.internal:5432/gotstockapi?sslmode=disable which is the connection string to the db being passed as an env variable. Notice the host is host.docker.internal.
Besides that we have command: ./entry in the api section. The entry file contains the following #!/bin/ash script:
#!/bin/ash
NOT_READY=1
while [ $NOT_READY -gt 0 ] # <- loop that waits till postgres is ready to accept connections
do
    pg_isready --dbname=gotstockapi --host=host.docker.internal --port=5432 --username=gotstock_user
    NOT_READY=$?
    sleep 1
done;
./gotstock-api # <- actually executes the build of the api
sleep 10
go test -v ./it # <- executes the integration-tests

And finally, in order for the psql client to work in the above script, the docker file of the api is looking like this:

# syntax=docker/dockerfile:1

FROM golang:1.19-alpine3.15

RUN apk add build-base

WORKDIR /app

COPY go.mod go.sum ./
RUN go mod download && go mod verify

COPY . .

RUN apk add postgresql-client

RUN go build -o gotstock-api

EXPOSE 8080

Notice RUN apk add postgresql-client which installs the client.
Happy hacking! =)


text:
Q: IIS Web configuration issue I have an issue with my web.config file issue, can you please assist on this, present using the IIS 10 and windows server 2016
What type of changes need to done to this config file?
I have validated this files with the other environment files and verified the all Feature delegation settings all looks fine, still the issue is not resolved.

A: Solution 1:
I had the same problem. Don't remember where I found it on the web, but here is what I did:

*

*Click "Start button"

*in the search box, enter "Turn windows features on or off"

*in the features window, Click: "Internet Information Services"

*Click: "World Wide Web Services"

*Click: "Application Development Features"

*Check (enable) the features. I checked all but CGI.

btw, I'm using Windows 7. Many comments over the years have certified this works all the way up to Windows 10 and Server 2019, as well.
Solution 2:
Follow the below steps to unlock the handlers at the parent level:

*

*In the connections tree(in IIS), go to your server node and then to your website.

*For the website, in the right window you will see configuration editor under Management.

*Double click on the configuration editor.

*In the window that opens, on top you will find a drop down for sections. Choose "system.webServer/handlers" from the drop down.

*On the right side, there is another drop down. Choose "ApplicationHost.Config "

*On the right most pane, you will find "Unlock Section" under "Section" heading. Click on that.

*Once the handlers at the applicationHost is unlocked, your website should run fine.


text:
Q: Extract elements from sequences, tuples Say I have this:
let coor = seq { ... }
// val coor : seq<int * int> = seq[(12,34); (56, 78); (90, 12); ...]

I'm trying to get the value of the first number of the second element in the sequence, in this case 56. Looking at the MSDN Collection API reference, Seq.nth 1 coor returns (56, 78), of type seq <int * int>. How do I get 56 out of it?

A: It's a tuple, so you could use the function fst;
> let value = fst(Seq.nth 1 coor);;
val value : int = 56

...or access it via pattern matching;
> let value,_ = Seq.nth 1 coor;;
val value : int = 56

A: I suggest you go through Tuple article:
http://msdn.microsoft.com/en-us/library/dd233200.aspx
A couple of exceptions that might shed some light on the problem:
Function fst is used to access the first element of the tuple:
(1, 2) |> fst // returns 1

Function snd is used to access the second element
(1, 2) |> snd // returns 2

In order to extract element from wider tuples you can use following syntax:
let _,_,a,_ = (1, 2, 3, 4) // a = 3

To use it in various collections (well lambdas that are passed to collection's functions), let's start with following sequence:
let s = seq {
        for i in 1..3 do yield i,-i
    }

We end up with
seq<int * int> = seq [(1, -1); (2, -2); (3, -3)]

Let's say we want to extract only the first element (note the arguments of the lambda):
s |> Seq.map (fun (a, b) -> a)

Or even shorter:
s |> Seq.map fst

And lets finally go back to your question.
s |> Seq.nth 1 |> fst


text:
Q: SQl Query get data very slow from different tables I am writing a sql query to get data from different tables but it is getting data from different tables very slowly.
Approximately above 2 minutes to complete.
What i am doing is here :
1. I am getting data differences and on behalf of date difference i am getting account numbers
2. I am comparing tables to get exact data i need.
here is my query
select T.accountno,
       MAX(T.datetxn) as MxDt,
       datediff(MM,MAX(T.datetxn), '2011-6-30') as Diffs,
       max(P.Name) as POName
from   Account_skd A,
       AccountTxn_skd T,
       POName P
where  A.AccountNo = T.AccountNo and
       GPOCode = A.OfficeCode and
       Code = A.POCode and
       A.servicecode = T.ServiceCode
group by T.AccountNo
order by len(T.AccountNo) DESC

please help that how i can use joins or any other way to get data within very less time say 5-10 seconds.

A: Since it appears you are getting EVERY ACCOUNT, and performance is slow, I would try by creating a prequery by just account, then do a single join to the other join tables something like..
select
      T.Accountno,
      T.MxDt,
      datediff(MM, T.MxDt, '2011-6-30') as Diffs,
      P.Name as POName
   from
         ( select T1.AccountNo,
                  Max( T1.DateTxn ) MxDt
              from AccontTxn_skd T1
              group by T1.AccountNo ) T
         JOIN Account_skd A
            on T.AccountNo = A.AccountNo
            JOIN POName P
               on A.POCode = P.Code         <-- GUESSING as you didn't qualify alias.field
              AND A.OfficeCode = P.GPOCode  <-- in your query for these two fields
   order by
      len(T.AccountNo) DESC

You had other elements based on the T.ServiceCode matching, but since you are only grouping on the account number anyhow, did it matter which service code was used?  Otherwise, you would need to group by both the account AND service code (which I would have added the service code into the prequery and added as join condition to the account table too).


text:
Q: SQL XML generating multiple containers depending on row count This is a bit of a difficult one to explain......but I'll do my best.....
I have a SQL XML export that works perfectly well however I need to add an additional field to record a wav file location. This wouldn't be a problem if there was only one wav location, however there could be either one or several wav locations that need recording.
Within my extract SQL I want to do something akin to a If statement or a Case When so when there is only one file location I only have the one XML container file location in the XML file, if there are two - I have two etc. I basically don't want empty containers. Does anybody know if this would be possible?
I have attached an example of code that hopefully give you an idea of what I'm asking.
(SELECT --Agreement--
'Some Text' as AdditionalInformation,
If @RecordingCount = 2
    (SELECT
            (Select
                REC1.Recording_Location as MainRecordingRef
                FOR XML PATH('MainRecordingRef'), TYPE),
            (Select
                REC1.Recording_Location as MainRecordingRef
                FOR XML PATH('MainRecordingRef'), TYPE)
        FOR XML PATH('MainRecordingRefs'), TYPE),
End

If @RecordingCount = 3
    (SELECT
            (Select
                REC1.Recording_Location as MainRecordingRef
                FOR XML PATH('MainRecordingRef'), TYPE),
            (Select
                REC1.Recording_Location as MainRecordingRef
                FOR XML PATH('MainRecordingRef'), TYPE),
                (Select
                REC1.Recording_Location as MainRecordingRef
                FOR XML PATH('MainRecordingRef'), TYPE)
        FOR XML PATH('MainRecordingRefs'), TYPE),
End

FOR XML PATH('Agreement'), TYPE)
The above code doesn't work but was wondering if there was a different approach that I might need to take. Any advice would be appreciated.
EDIT
This is what I currently output...
Agreement
AgreementReference PP20170510-122300 AgreementReference
  MainRecordingRefs
   MainRecordingRef
    RecRef LOGOS-PP20170510-122300-9174.wav /RecRef
   /MainRecordingRef
   MainRecordingRef
    RecRef LOGOS-PP20170510-122400-9175.wav /RecRef
   /MainRecordingRef
  MainRecordingRef
  MainRecordingRef
  MainRecordingRef
  MainRecordingRefs
Agreement

In the above I'm exporting five Recording Refs two have something in and the other three are empty but really only want to export the recording refs that are not empty so it looks something like...
Agreement
AgreementReference PP20170510-122300 AgreementReference
  MainRecordingRefs
   MainRecordingRef
    RecRef LOGOS-PP20170510-122300-9174.wav /RecRef
   /MainRecordingRef
   MainRecordingRef
    RecRef LOGOS-PP20170510-122400-9175.wav /RecRef
   /MainRecordingRef
  MainRecordingRefs
Agreement

Is there anything I can do within the XML to only show recording references that are not null?

A: Your question is not quite clear (sample data + expected output would help most). But my magic crystall ball tells me, that you want to place one Wav into your XML and more Wavs - if there are any - into a further node collection...
Something like this?
DECLARE @mockup1 TABLE(ID INT,SomeData VARCHAR(100));
INSERT INTO @mockup1 VALUES (1,'Some 1 has 1 WAV')
                           ,(2,'Some 2 has 2 WAVs')
                           ,(3,'Some 3 has 3 WAVs');
DECLARE @mockup2 TABLE(ID INT,ID1 INT,WavUrl VARCHAR(100));
INSERT INTO @mockup2 VALUES(1,1,'URL 1')
                          ,(2,2,'URL 2-1')
                          ,(3,2,'URL 2-2')
                          ,(4,3,'URL 3-1')
                          ,(5,3,'URL 3-2')
                          ,(6,3,'URL 3-3');

SELECT m1.ID
      ,m1.SomeData
      --The first Wav goes in one extra node
      ,(SELECT w.ID
              ,w.WavUrl
        FROM @mockup2 AS w
        WHERE w.ID1=m1.ID AND w.ID=(SELECT MIN(x.ID) FROM @mockup2 AS x WHERE x.ID1=m1.ID)
        FOR XML PATH('MainRecord'),TYPE
       )
      --All later Wavs go into a collection
      ,(SELECT w2.ID
              ,w2.WavUrl
        FROM @mockup2 AS w2
        WHERE w2.ID1=m1.ID AND w2.ID<>(SELECT MIN(x.ID) FROM @mockup2 AS x WHERE x.ID1=m1.ID)
        FOR XML PATH('Record'),ROOT('MoreRecords'),TYPE
        )
FROM @mockup1 AS m1
FOR XML PATH('Test'),ROOT('root');

The result
<root>
  <Test>
    <ID>1</ID>
    <SomeData>Some 1 has 1 WAV</SomeData>
    <MainRecord>
      <ID>1</ID>
      <WavUrl>URL 1</WavUrl>
    </MainRecord>
  </Test>
  <Test>
    <ID>2</ID>
    <SomeData>Some 2 has 2 WAVs</SomeData>
    <MainRecord>
      <ID>2</ID>
      <WavUrl>URL 2-1</WavUrl>
    </MainRecord>
    <MoreRecords>
      <Record>
        <ID>3</ID>
        <WavUrl>URL 2-2</WavUrl>
      </Record>
    </MoreRecords>
  </Test>
  <Test>
    <ID>3</ID>
    <SomeData>Some 3 has 3 WAVs</SomeData>
    <MainRecord>
      <ID>4</ID>
      <WavUrl>URL 3-1</WavUrl>
    </MainRecord>
    <MoreRecords>
      <Record>
        <ID>5</ID>
        <WavUrl>URL 3-2</WavUrl>
      </Record>
      <Record>
        <ID>6</ID>
        <WavUrl>URL 3-3</WavUrl>
      </Record>
    </MoreRecords>
  </Test>
</root>


text:
Q: Why is my ExceptionMapper getting thrown away in Jersey/Grizzly? Currently I'm working in Grizzly 2.3.16 and Jersey 2.14. I'm trying to get a custom exception handled by the server and returned to the client. Instead it seems I'm getting generic Grizzly errors, even though the correct code seems to be called.
This is the filter method (part of a class that has the '@Provider' decoration).
@Override
public void filter(ContainerRequestContext context) throws IOException
{
    throw new MappableException(
        new CustomAuthenticationException(
            "Custom Error message"));
}

Here is the entire ExceptionMapper implementation:
@Provider
public class CustomAuthenticationExceptionMapper
    implements ExceptionMapper<CustomAuthenticationException>
{
    public Response toResponse(CustomAuthenticationException e)
    {
        return Response.status(Status.UNAUTHORIZED.getStatusCode()).
                header("WWW-Authenticate", "Basic realm=\"Custom\"").
                type("text/plain").entity(e.getMessage()).build();
    }
}

Here is how I get the response and read it:
response = invocationBuilder.method(requestMethod.toString(), Response.class);
System.out.println(response.readEntity(String.class));

When I get the entity, it's HTML from Grizzly as opposed to my custom message as it should be.
Here is the stack trace from just before toResponse is called - I can verify the code is being called but it looks like somehow Jersey or Grizzly is just discarding it and ultimately being replaced with the default grizzly message.
at org.glassfish.jersey.server.ServerRuntime$Responder.mapException(ServerRuntime.java:528)
    at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:409)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:277)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:297)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:254)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1030)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:377)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
    at org.glassfish.grizzly.servlet.FilterChainImpl.doFilter(FilterChainImpl.java:147)
    at org.glassfish.grizzly.servlet.FilterChainImpl.invokeFilterChain(FilterChainImpl.java:106)
    at org.glassfish.grizzly.servlet.ServletHandler.doServletService(ServletHandler.java:221)
    at org.glassfish.grizzly.servlet.ServletHandler.service(ServletHandler.java:169)
    at org.glassfish.grizzly.http.server.HttpHandler$1.run(HttpHandler.java:219)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
    at java.lang.Thread.run(Unknown Source)

I'm not sure what other parts would be relevant but they can be provided as necessary.

A: I needed to add the jersey-grizzly-connector.jar from maven.


text:
Q: Stationary paths Let $Q$ be a finite quiver and denote the stationary parts of $Q$ by $e_{i}$. Suppose we have two arrows $f,g$ such that their composition $f \circ g$ is equal to $e_{i}$. Does this always implies that $f=g=e_{i}$?

A: When you say arrow, I assume $f,g\in Q_1$.  Then the answer is no.  Note that the trivial path (which I assume here is the stationary path you wrote) is defined to have path length zero, and we usually do not think of $e_i$ as elements in $Q_1$, they really are elements of $Q_0$.
Be careful if you are asking a question about representations of path algebra of quiver, then $fg=e_i$ is not in any admissible ideal since path length of $e_i$ is zero.  The path algebra of a quiver arise from $kQ/I$ where $I$ needs to be admissible, i.e. contains elements of path length $\geq 2$.  Representation-theoretically, $fg=e_i$ means you go two radical layer down the projective (indecomposable) module corresponding to $i$ and you ended up in the simple top, this does not make any sense (this is also the reason why path algebra are defined using admissible ideals).


text:
Q: probability of selecting candidates from a pool of applicants
I'm trying to solve this problem, but am stuck finding the probability in part a.
First, I believe there is a total of $n!$ possible outcomes for each of the n colleges (hence $n * n!$ total possibilities).
Since there are n colleges and n students, each college must pick a distinct student. Hence I thought that

College 1 has student 1 ( n C 1 ) chosen, and has (n-1)! permutations for arranging the rest of students.

College 2 has student 2 ( n-1 C 1) chosen, and has (n-1)! permutations.

...

College n has student n ( n - (n-1) C 1 = 1 C 1) chosen, and has (n-1)! permutations.

Hence overall, the colleges have n*(n-1)*...*1 * (n-1)! = n! (n-1)! possible choices of selecting distinct n students.
But this is clearly larger than the total possible outcome I had calculated earlier, and I was wondering where I went wrong. Any help would be really appreciated!

A: You are close, but have a few small mathematical errors.
In your computation of total possible outcomes, it should be $(n!)^n$, rather than $n \cdot n!$.
In your computation of the desired outcomes, it should be $n! ((n-1)!)^n$, rather than $n! (n-1)!$.

Note that you can simplify the problem by supposing each college selects a single student at random to admit. You can ignore their rankings of the remaining students; in your approach, this simplification corresponds to the cancellation of $((n-1)!)^n$ in your numerator and denominator.


text:
Q: How to order posts in Wordpress by date? How can I change re-order posts so that the most recent articles appear at the top of the list?
I found that this is possible by using something like this:
WP_Query('orderby=date&order=DESC')

But how and in which file should I use it?
I tried to add it at the end of in wp-includes/post.php, but it's breaking the site.


text:
Q: Dump limit in PostgreSQL I am trying to dump a database which has a size of just over 100 GiB. I am using the following command (with pv to give a progress bar to observe where this problem occurs):
pg_dump -h <host> -U <user> <db> | pv -c -s $(psql -h <host> -U <user> <db> -tc "SELECT pg_database_size('<db>')") -N dump | gzip > <db>.sql.gz

The dump chugs along happily until it reaches 56.8GiB raw passing through the pipeline (~25GiB of the compressed file), and then just dies. I am at a loss as to why this is happening. The filesystem is ext4, so it's not a size limitation there.
I'm currently running it again, but splitting files into 10GiB chunks. Let's see how this goes.
Any ideas why, no matter what, the dump stops at 56.8GiB?
EDIT: The server I'm trying to get the dump from is a pod running on Google Kubernetes Engine. I have tried dumping both on the pod itself, and from another pod connecting through a service, and the problem persists.


text:
Q: `preg_match` the Whole String in PHP This thing really confuses me, pardon my ignorance.
I have a var $name in here that I want to be free from number, I don't want any digit to be included in it. My preg_match() is this:
var_dump(preg_match('/[^\d]/',$name));

Test cases:
$name = "213131"; // int(0)
$name = "asdda"; // int(1)
$name = "as232dda"; // int(1)

What I want is to have the third case to be int(0) too.
I'm really a hard time understanding this preg_match(), docs say it return 1 if a pattern match a subject. Here in my case, I use a negated class.

A: #3 matches because you have both letters and numbers.  Your regex in English basically says

it matches if there is a non-digit character

If you want to match only non-digit characters, you have to have the regex match against the entire string and allow for an arbitrary number of characters:
^[^\d]+$

A: Your regex only checks that there is at least one non-digit.  Instead, you need to check that it is only non-digits:
var_dump(preg_match('/^\D+$/',$name));

(^ and $ are the beginning and end of the string. \D means anything not a digit--the opposite of \d.  So this only matches non-digits from beginning to end.  It doesn't match an empty string.  Replace + with * if you want to match an empty string as well).

A: Try this:
<?php
    $string = "as232dda";
    $new_string = trim(str_replace(range(0,9),'',$string));
    echo $new_string;// gives 'asdda'
?>

Or function form:
<?php
  function remove_numbers($string){
    return(trim(str_replace(range(0,9),'',$string)));
  }

  $string = "as232dda";
  echo remove_numbers($string); // gives 'asdda'
?>


text:
Q: How do I clean the data when iqr is equal to 0? I want to clean my data but one variable has more than 86 percent zero and consequently iqr=0. When I want to clean outliers, that feature is eliminated because all the non-zeros were defined as outliers or extremes, and the value of that feature is equal to 0 for all of the records.
I think that is not reasonable, but how do I manage  this situation?

A: I'll start with referring to your comment:

i am in preprocessing phase . and outlier should be removed in this phase

It is not true that during data preprocessing you need to remove the outliers. By any means, this is not a default approach. Yes, you should remove invalid data, but by invalid we mean the data that is corrupted, or incorrect (e.g. human age of 1000 years old). You do not remove the rare samples.
The problem described in your question is a great example of why we don't do this. In your case, removing the samples that occur in the data less frequently would mean that you dropped all the non-zero entries, leaving you with a column that is constant, hence useless, so in fact you would need to remove the whole column from your data. What a waste!
Moreover, the infrequent samples may be very valuable in terms of the unique information they bring to the data. Say that you are studying successes and failures of companies across the time. If you removed the companies that lasted the shortest amount of time, and the ones that lasted the longest among of time, you are losing a lot of valuable information. If you did a medical study and dropped the subjects that had some rare symptoms, it might be the case that you removed from your data the samples that could shed most light on the studied phenomenon.
I highly recommend that you check also other questions tagged as outliers to learn more. One of the things that you would learn from those threads is that even if you have good reason to remove the outliers, using some simple criteria like points outside of few standard deviations from the mean, or outside IQR range, in many cases are pretty bad ideas.


text:
Q: using python in maya do for-loop through selected nodes I would like to know a few things here. I'm collecting all the selected nodes using this code snippet below. What I'm now wondering is...

*

*How do I write a for-loop going through each node in the collection?

*How do i get the total number of nodes in the collection?

*How do I get the first node's position in the collection?

*How do I get the last node's position in the collection?
nodes = cmds.ls(long = True, selection = True, type = 'dagNode')

A: 1.
for n in nodes:
    print n

2.
print len(nodes)

3.
print nodes[0]

4.
print nodes[-1]

Hope it will help you.


text:
Q: Android studio перестала предлагать вариант для import класса Андроид студио перестала предлагать импортировать в класс некоторые библиотеки, например при написании ConstraintLayout, он не понимает, что это пока вручную не прописать импорт, тоже самое с RecyclerView в gradle зависимости есть, Clean Rebuild проекта делал.

A: Измените язык - переключите с русского на английский.
UPD
Для решения проблемы необходимо было удалить "android.support" из секции "Exclude from Import and Completetion" (из вкладки "File | Settings | Editor | General | Auto Import"). В настройках этот пакет был исключен для импорта и автодополнения, а ConstraintLayout и RecyclerView находятся как раз в этом пакете.

A: Сходите на File -> Settings -> Editor -> Auto Import -> Java и поиграйте с флажками.
Альтернативно, можно выбирать курсором нераспознанный класс и нажимать alt-enter и Студия предложит набор вариантов для импорта. Вообще alt-enter обладает многими чудесными свойствами, например с его помощью текстовые строки можно пихать сразу в ресурсы и проч.


text:
Q: Custom Validation using ValidationAttribute does not fire Client side validation I have created a custom validator deriving from ValidationAttribute. My undertsandng is that it will generate enough meta data for the client side script to automatically validate (using jquery.validate). The custom validator is working fine in server side. But it does not fire error message in the client side. (Other default validators like "StringLength" are working fine in the client side too.) How do we correct it?
public class Person
{
    [Required(ErrorMessage = "First name required")]
    public string FirstName { get; set; }

    [CustomStartLetterMatch("FirstName")]
    [StringLength(5,ErrorMessage = "Must be under 5 characters")]
    public string LastName { get; set; }

    [Range(18,50,ErrorMessage="Must be between 18 and 50")]
    public int Age { get; set; }

}

public sealed class CustomStartLetterMatch : ValidationAttribute
{

    private const string _defaultErrorMessage = " First letter of '{0}' must be same as first letetr of '{1}'";
    private string _basePropertyName;

    public CustomStartLetterMatch(string basePropertyName)
        : base(_defaultErrorMessage)
    {
        _basePropertyName = basePropertyName;
    }

    //Override FormatErrorMessage Method
    public override string FormatErrorMessage(string name)
    {
        return string.Format(_defaultErrorMessage, name, _basePropertyName);
    }

    //Override IsValid
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        //Get PropertyInfo Object
        var basePropertyInfo = validationContext.ObjectType.GetProperty(_basePropertyName);
        var baseValue = (string)basePropertyInfo.GetValue(validationContext.ObjectInstance, null);
        var currentValue = (string)value;

        string firstLetterBaseValue = baseValue.Substring(0, 1);
        string firstLetterCurrentValue = currentValue.Substring(0, 1);

        //Comparision
        if (!string.Equals(firstLetterBaseValue, firstLetterCurrentValue))
        {
            var message = FormatErrorMessage(validationContext.DisplayName);
            return new ValidationResult(message);
        }

        //Default return - This means there were no validation error
        return null;
    }

}

VIEW
@model MyValidationTEST.Person

@*UnObtrusive*@

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>Person</legend>

        @Html.LabelFor(model => model.FirstName)

        @Html.EditorFor(model => model.FirstName)
        @Html.ValidationMessageFor(model => model.FirstName)

        @Html.LabelFor(model => model.LastName)

        @Html.EditorFor(model => model.LastName)
        @Html.ValidationMessageFor(model => model.LastName)

        @Html.LabelFor(model => model.Age)

        @Html.EditorFor(model => model.Age)
        @Html.ValidationMessageFor(model => model.Age)

        <input type="submit" value="Create" />

</fieldset>
}

@Html.ActionLink("Back to List", "Index")

READING:

*

*IValidatableObject in MVC3 - client side validation

*In ASP.NET MVC3 how do you stay DRY with very similar but slightly different viewmodels?

*http://odetocode.com/Blogs/scott/archive/2011/02/22/custom-data-annotation-validator-part-ii-client-code.aspx

*http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html

*ASP.NET MVC 3 client-side validation with parameters

*How can I have a custom ValidationAttribute rendered as a 'data-val-xx' attribute on the client-side?

*Clientside Validation in "Self Validate Model" in ASP.NET-MVC3

A:
My undertsandng is that it will generate enough meta data for the
  client side script to automatically validate (using jquery.validate).

Your understanding is wrong. You cannot possibly expect that there's enough metadata in order to generate client validation. In this IsValid method you could do absolutely anything. You could even call an unmanaged C++ library to perform validation. You cannot possibly expect that ASP.NET MVC 3 will reflect this on the client.
You need to implement IClientValidatable and add a custom adapter if you want to enable client validation for such custom validation logic. In this adapter you have to reimplement the same logic you did on the server but using javascript this time.
Here's one example. And here's another one.
As you can see client side validation works fine with some simple rules such as Required and stuff, bit once you start doing some real validation you will have to implement it yourself.


text:
Q: How can I open my documentDirectory (from my UITableView) files in a UIWebView? I would like my files from my iOS document directory (the files are listed in my UITableView) to be accessible, so when tapped, a UIWebView would load that file (offline).
How can I do this?

A: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *pathForYourFile = [documentsDirectory stringByAppendingPathComponent:[filePathsArray objectAtIndex:indexPath.row]];

[yourWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:pathForYourFile ofType:@"html"]isDirectory:NO]]];

}

Refer this document to find out the file formats supported by UIWebView
http://developer.apple.com/library/ios/#qa/qa1630/_index.html


text:
Q: How to share data between Virtual machine and host machine? I have install Windows7 32 bit virtual machine, and Win7 64bit as a host machine . I want to share data between virtual machine and host machine. How I can share the data between both machines?
I am using VMWare to run virtual machine.
Thanks.

A: https://www.vmware.com/support/ws4/doc/running_sharefold_ws.html
You may install VMWare Tools to share folders to share file between guest OS and host OS.
In above article, Windows 7 is not included, you can share file across windows 7.


text:
Q: Correct Apache var/www permissions I'm new to writing permissions in Apache. This is a shared sever of which I have one account on it.
I was having an issue with FileZilla not being able to write to my var/www directory and in an attempt to change its permissions I think I have made it worse.
Here are my current settings
$ ls -l
total 40
drwxr-xr-x  2 root root  4096 Feb  5  2013 backups
drwxr-xr-x  7 root root  4096 Jul 30  2013 cache
drwxr-xr-x 26 root root  4096 Jul 30  2013 lib
drwxrwsr-x  2 root staff 4096 Apr 15  2008 local
lrwxrwxrwx  1 root root     9 Feb  5  2013 lock -> /run/lock
drwxr-xr-x  7 root root  4096 Jul 30  2013 log
drwxrwsr-x  2 root mail  4096 Feb  5  2013 mail
drwxr-xr-x  2 root root  4096 Feb  5  2013 opt
lrwxrwxrwx  1 root root     4 Feb  5  2013 run -> /run
drwxr-xr-x  4 root root  4096 Feb  5  2013 spool
drwxrwxrwt  2 root root  4096 Feb  5  2013 tmp
drwxrwx---  2 root root  4096 Jul 30  2013 www

Can anyone tell me what are the correct permissions to have on the www folder, and even better how to obtain them?
I think it should be
drwxrwxr-x  2 root root  4096 Jul 30  2013 www

Thanks

A: There is no such thing as "correct permissions".
There's the permissions setup which was used as default in your installation.
There's the right permissions to use for YOUR security model
You appear to be using a security model which requires non-standard permissions, And you've not once mentioned 'users' or 'groups' let alone what your security model is.
As root, you should chown /var/www to whoever should 'own' the directory (hint: it's neither root nor the apache uid) then set the group ownership appropriately (we can't tell from the information you've provided what that is - but again it's neither root nor the apache uid) then chmod o_rx the directory.
Then please go learn a bit about Linux/Unix admin - try googling for "the rute"


text:
Q: NSPageController resizing and snapshots I have an NSPageController in book mode with two pages and each contains an NSTableView. If I start my application and resize it vertically and then swipe to the other page the snapshot used in the swipe animation is of the NSTableView before the resize. This view swiping in only covers part of the previous view and this looks terrible. Is it possible to get the NSPageController to invalidate the snapshots when the view is resized?

A: The PictureSwiper example does exactly this by setting the frame of the view whenever the window is resized. However, you need to have your layout/resize constraints set. Whenever the view size changes, the constraints will cause NSPageController's view objects to be resized as well. If you're doing something unique with your view layout/size, you will need to manually resize as in the example linked.
Also, snaphots are generated on-the-fly. From the arrangedObjects method documentation of NSPageController:

The delegate will be asked for snapshots as they are needed.

And this is useful to keep in mind:

When using the book mode, if pageController.view is layer backed, live layers are used during transition instead of snapshots.


text:
Q: Why can I not import data-tier application without access to all other databses? I am attempting to backup and restore a database located in Azure SQL database via Azure blob storage. To do this I have ran Export Data-Tier Application... on the selected database and successfully stored it in a blob container as a BACPAC file. Now I am trying to do the reverse and Import Data-Tier Application... to check the backup process functions correctly, however I receive the following error:

'The server principal "username" is not able to access database
  "Database A" under the current security context'

The database it is referencing is the first listed database in the server I am trying to create a new database in which I don't have permissions for, and each time I give myself permission to access the first it just moves down the list to the next one and blocks me again. I don't understand why I need permissions for database A, B, C... to create a new database which is a copy of D, especially when I have the db_manager role so shouldn't have an issue with database creation.
Does this error indicate I am doing something wrong with the backup import, or is this a known issue and I need to have permissions for all databases in a server where I wish to import a backup to?

A: Please update SQL Server Management Studio (SSMS) to the latest version and try to export/import with the latest SSMS.
You can achieve the same using Azure portal. Open the appropriate database server page and then, on the toolbar, select Import database.

Select the storage account and the container for the BACPAC file and then select the BACPAC file from which to import. In addition, specify the new database size (usually the same as origin) and provide the destination SQL Server credentials.

You can also try with PowerShell.
$importRequest = New-AzSqlDatabaseImport
   -ResourceGroupName "<your_resource_group>" `
   -ServerName "<your_server>" `
   -DatabaseName "<your_database>" `
   -DatabaseMaxSizeBytes "<database_size_in_bytes>" `
   -StorageKeyType "StorageAccessKey" `
   -StorageKey $(Get-AzStorageAccountKey -ResourceGroupName "<your_resource_group>" -StorageAccountName "<your_storage_account").Value[0] `
   -StorageUri "https://myStorageAccount.blob.core.windows.net/importsample/sample.bacpac" `
   -Edition "Standard" `
   -ServiceObjectiveName "P6" `
   -AdministratorLogin "<your_server_admin_account_user_id>" `
   -AdministratorLoginPassword $(ConvertTo-SecureString -String "<your_server_admin_account_password>" -AsPlainText -Force)


text:
Q: How do I strip pass phrase from a private key with 3072 bits - Got Error need fix I created  a CSR SSL Certificate request and successfully generated the cert files from the CA , however when I went to strip the passphrase which I have on file I got an error most likely because I created the private key with 3072 bits and not the default amount of bits.  Now I have a problem it seems trying to strip the passphrase.
Here is what I did:
openssl genrsa -des3 -out mykey.key 3072
I will skip the steps that follow because all I need do is strip the key above mykey.key of the pass code.
openssl rsa -in mykey.key -out nopc_mykey.key
I should be able to do this and all should work fine but the 3072 bits seem to cause a problem namely:

unable to load Private Key
  140538251888456:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:evp_enc.c:535:
  140538251888456:error:0906A065:PEM routines:PEM_do_header:bad decrypt:pem_lib.c:476:

Any ideas how I can fix this and strip the passcode for SSL? Perhaps some way to provide the number of bits used to create the key in the first place?

A: Please be informed that key size must be 2048 bit. All SSL Certificates in use must be 2048 bit in accordance with CA/B Forum guidelines.
See: https://www.globalsign.com/ssl-information-center/1024-bit-public-and-private-keys.html
You may refer to this link on how to Generate a CSR in OpenSSL:
https://support.globalsign.com/customer/portal/articles/1221018-generate-csr---apache-openssl


text:
Q: How to create a folder in SharePoint 2010 document library using REST or HTTP methods I am using Java to make calls to the SharePoint REST Interface to get list items of a document library and HTTP methods to upload documents to SharePoint. But, I am having a difficult time trying to figure out how to create a folder programmatically using either REST or HTTP methods. Whenever I try to make a POST with an item data I get the following error
Invalid slug header for BLOBs. Slug headers must be server- or web-relative URL of the file. Server-relative URLs begins with a forward slash (\"/\").
Can anyone please help.
Many thanks in advance.
Dinesh

A: Get items
To get all items you can either call this url:
http://yourhost/_vti_bin/ListData.svc/YourLib

Or you can call this url:
http://yourhost/_vti_bin/Lists.asmx

with this payload:
<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
    xmlns:xsd='http://www.w3.org/2001/XMLSchema'
    xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>
  <soap:Body>
    <GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>
      <listName>YourLib</listName>
    </GetListItems>
  </soap:Body>
</soap:Envelope>

Create folder
I can't say if this is the correct approach, but it should work.
It uses Batch  which I find a bit scary, but I have used this myself with success.
To create a folder you can call this url:
http://yourhost/sites/wf/_vti_bin/Lists.asmx

with this payload:
<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
    xmlns:xsd='http://www.w3.org/2001/XMLSchema'
    xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>
  <soap:Body>
    <UpdateListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>
      <listName>YourLib</listName>
      <updates>
        <Batch OnError='Continue' PreCalc='TRUE' ListVersion='0' >
          <Method ID='1' Cmd='New'>
            <Field Name='FSObjType'>1</Field>
            <Field Name='BaseName'>YourFolder</Field>
          </Method>
        </Batch>
      </updates>
    </UpdateListItems>
  </soap:Body>
</soap:Envelope>

A: As Tommy pointed out and according to 3.1.4.3 Document:

Inserting new documents to a document library involve sending a POST
  request containing the contents of the document to the EntitySet
  representing the document library. The protocol client MUST include
  the SLUG header (as specified in RFC5023 section 9.7) whose value
  is the name of the file that is being created in their POST requests.

How to create Folder via REST in SharePoint 2010
function createFolder(webUrl,listName,folderName,folderPath, success, failure) {

    var folderPayload = {
      'ContentType': 'Folder',
      'Title' : folderName,
      'Path' : folderPath
    };

    $.ajax({
        url: webUrl + "/_vti_bin/listdata.svc/" + listName,
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(folderPayload),
        headers: {
            "Accept": "application/json;odata=verbose",
            "Slug": folderPath + "/" + folderName + "|0x0120"
        },
        success: function (data) {
            success(data.d);
        },
        error: function (data) {
            failure(data.responseJSON.error);
        }
    });
}

Examples:
1 Create root folder named Orders in the Documents library
createFolder('https://intranet.contoso.com','Documents','Orders', '/Shared Documents',function(folder){
    console.log('Folder ' + folder.Name + ' has been created succesfully');
  },
  function(error){
    console.log(JSON.stringify(error));
  }
);

2 Create sub folder named 2014 under the folder Orders in the Documents library
createFolder('https://intranet.contoso.com','Documents','2014', '/Shared Documents/Orders',function(folder){
    console.log('Folder ' + folder.Name + ' has been created succesfully');
  },
  function(error){
    console.log(JSON.stringify(error));
  }
);

A: I don't have high enough reputation to comment, but I already gave the answer to this over here: Folder creation in Document library using listdata.svc
On creating folders in lists, its the same way, but without the "slug" header and you just add "/Lists" to beginning of the "Path" property.


text:
Q: Display image on strstr match Trying to display an image only for Android users, but I don't want to use any redirection for it.
So far I have this, but it uses header() which redirects.
if (strstr($_SERVER['HTTP_USER_AGENT'],"Android")) {
        header("Location: app.png");
}

A: You can just output the image in your page, using readfile. Make sure to send the correct headers as well.
For example:
if(strstr($_SERVER['HTTP_USER_AGENT',"Android"))
{
 header('content-type: application/png'); //Let the client know its a png.
 readfile('app.png');
}

This way any request made to your page using Android will result in the raw image being returned. If you want to 'force' the client to download the image send the content-disposition header as well.

A: It depends on what you want to do.
If you want to display the image inside an HTML document, why not use this kind of code?
if (strstr($_SERVER['HTTP_USER_AGENT'],"Android")) {
    echo '<img src="app.png"/>';
}


text:
Q: What does this old PHP code mean - variable name on a single line? I'm re-factoring this ugly pile of legacy code and I came across this:
// $log is a PEAR logging object
$log->debug( 'some error message' );

with this immediately after:
$foo;
$bar;
...
...

I.e. Just a load of variable names within a function.. what does this do ?  Nothing ?
Thanks :).

A: They are variable declarations without values being assigned to them.

A: They're completely pointless and they don't declare the variables at all, as PHP has no concept of variable declaration, only assignment, and these statements don't assign anything to the variables. See an example using $variable; as compared to this example without $variable;; they have the same result.
Perhaps it's a coding style.


text:
Q: What determines the speed at which a laptop battery charges? What factors affect the charge time of laptop batteries?  Is it the laptop's use while charging? The age of the battery? The charger's wattage?

A: yes All of the above.
IF it is a Li-Ion battery or Li-Poly:
Normally the battery is faster charged to about 80% (capacity not display numbers), then it slowly finishes up at a slower rate till it reached the peak voltages that are set .  On some laptops the peak voltage for li-ion charge can be set down a bit , to insure longer life.
These alogrythms for charging are CC (constant current) a specific amperage of charge, and CV (constant voltage) where the voltage is held at Say ~4.1 or ~4.2 Per cell.
In CV (the second stage) Because the voltage Difference or voltage differential between the battery and the charge gets smaller , the charge rate (or amps) dwindles down until the voltages are very similar. At some low rate the charge is then terminated.
(much more simple than it sounds, yet gets complicated many ways)
Basically though, to 80% capacity the Rate, or ammount of power that can go to charge the battery should not change much. so that is one clue to your puzzel.
This all gets very muddy, as various versions of the alogrythms are applied. Some alogrythms which simulate or attempt CC CV methods, and do act similar to the "proper" CC CV method, but are not using actual proper CC CV.  :-)  are you having fun yet?
IF the power supply AND the internal power capabilities (in the laptop) can handle it, you could charge at a full rate and use the laptop to its maximum potential also, and it could do both without effecting either.
 A bunch of Ifs, where you should remember that stuffing a larger power supply of the proper type would not insure that the laptop itself would charge any different.
 There are cooling conciderations for the charge curcuit itself, and the rest of the laptop that smartly might not allow so much heat going on, or any increased rate, while being used or not.
How they cheapened it or designed it to cope with , heat, power, and specs.
PLUS the batteries dont really like to be heated by processors, which gets ignored too often.
A User can usually treat ALL li-ion batteries better , in any li-ion powered products, by being more kind with the heat.  Another clue to your puzzel. Keeping the heat down by not using the laptop when charging can get a battery to last much longer. Keeping the heat at "normal room temps" for these "normal room temperature" batteries treats them better in all situations, even storage.
An aged li-ion battery loses capacity over time and charge cycles. with proper li-ion curcuitry, this aged battery should actually take less time to charge. With the increased resitance, and lowered holding capacity. Generally there is less power that it can Hold.
That is where things get really muddy again, when it comes to explaining the reality, and the different methods that can be used.
With Increased resistance the voltage can reach the second stage sooner CV and take longer to charge , even though less will ever be put in.
Confused yet?
At some point the age of the battery (depending totally on the quality of it) will be so Bad that the voltage will never be reached. Again how the curcuitry deals with this situation varies. That could again Increase the time it charged for, even though less charge will exist. Waste because the cells no longer "accept" the charge as well.
Here it should be noted that the battery could be so bad, that you see things like the displayed charge rate drops quickly when taken off the charge, it could be a battery that is end of life.
now days they even have implemented a maximum age and number of charges into the curcuit , and the battery is deemed to be at end of life.  varies , and some done very poorly again.
Refers only to Li-ion type chemisty, and varies because of many factors due to different implementations of charge alogrythms, and safety and info curcuits.