问:
Glassfish Admin Console throws java.lang.IllegalStateException when creating JDBC Pool
A week ago I downloaded Glassfish 4.1.  Did a zip install.  Attempted to use Admin Console to create a JDBC Connection Pool.  Received this error message:

```<code>java.lang.IllegalStateException: getOutputStream() has already been called for this response
</code>```

Lots of references to that error.  Lots of people declared it "Asked & Answered".  But I can't find a single reference anywhere to that problem, let alone a solution.

But if anyone believes it's been answered, please be sure to add a link to the solution to this problem:  New installation.  Did nothing but open the console and try to create a new JDBC Connection Pool.

```<code>Resource Type: javax.sql.DataSource.
Vendor: MySql.
</code>```

I've stored mysql-connector-java-5.1.35.jar in \glassfish4\glassfish\lib

Here's the closest thing to a solution I found.  But it was for GF v3.

I finally have tracked down the actual problem in my domain.xml:
  -Dorg.glassfish.web.rfc2109_cookie_names_enforced=false
  was missing in the domain.xml created by asupgrade. I just added it to the domain.xml jvm-options and GF v3 now works as expected.
  Added:

  <jvm-options>-Dorg.glassfish.web.rfc2109_cookie_names_enforced=false</jvm-options>

Tried that.  Didn't work.  (I pasted the GF log entry to show the recommended line is added to the domain.xml GF used on startup.)

I tried digging out domain.xml from my old v3 server and using it in the new v4.  That didn't work.

Other questions involving my Exception message all related to getting it with a deployed app -- mostly servlets.  But this is a clean server.  No apps have been installed.

I found a lot of links to people working on this Exception as a GF bug. Most are awhile ago.  None gave a workaround or even said they'd ever solved it.

Can anyone offer a solution?

Or let me know if this is just a bug Oracle decided not to fix?

Or know of where I can find help?  This is killing me.

In case it helps here is the GF log for a clean start up (with the jvm insert in the domain.xml.)  It also shows the stack trace for the failed attempt to create a JDBC Connection Pool.

NOTE: I pulled out all [INFO] log entries.  And the [WARNING] entries that  are left all seem related to Grizzly.

```<code>[2015-10-09T12:21:24.598-1000] [] [INFO] [NCLS-GFLAUNCHER-00005] [javax.enterprise.launcher] [tid: _ThreadID=1 _ThreadName=main] [timeMillis: 1444429284598] [levelValue: 800] [[
  JVM invocation command line:
C:\Program Files\Java\jdk1.8.0_05\bin\java.exe
-cp
C:/glassfish4/glassfish/modules/glassfish.jar
-XX:+UnlockDiagnosticVMOptions
-XX:NewRatio=2
-XX:MaxPermSize=192m
-Xmx512m
-javaagent:C:/glassfish4/glassfish/lib/monitor/flashlight-agent.jar
-client
-Djavax.xml.accessExternalSchema=all
-Djavax.net.ssl.trustStore=C:\glassfish4\glassfish\domains\domain1/config/cacerts.jks
-Djdk.corba.allowOutputStreamSubclass=true
-Dfelix.fileinstall.dir=C:\glassfish4\glassfish/modules/autostart/
-Dorg.glassfish.additionalOSGiBundlesToStart=org.apache.felix.shell,org.apache.felix.gogo.runtime,org.apache.felix.gogo.shell,org.apache.felix.gogo.command,org.apache.felix.shell.remote,org.apache.felix.fileinstall
-Dcom.sun.aas.installRoot=C:\glassfish4\glassfish
-Dfelix.fileinstall.poll=5000
-Djava.endorsed.dirs=C:\glassfish4\glassfish/modules/endorsed;C:\glassfish4\glassfish/lib/endorsed
-Djava.security.policy=C:\glassfish4\glassfish\domains\domain1/config/server.policy
-Dosgi.shell.telnet.maxconn=1
-Dfelix.fileinstall.bundles.startTransient=true
-Dcom.sun.enterprise.config.config_environment_factory_class=com.sun.enterprise.config.serverbeans.AppserverConfigEnvironmentFactory
-Dfelix.fileinstall.log.level=2
-Dorg.glassfish.web.rfc2109_cookie_names_enforced=false
-Djavax.net.ssl.keyStore=C:\glassfish4\glassfish\domains\domain1/config/keystore.jks
-Djava.security.auth.login.config=C:\glassfish4\glassfish\domains\domain1/config/login.conf
-Dfelix.fileinstall.disableConfigSave=false
-Dfelix.fileinstall.bundles.new.start=true
-Dcom.sun.aas.instanceRoot=C:\glassfish4\glassfish\domains\domain1
-Dosgi.shell.telnet.port=6666
-Dgosh.args=--nointeractive
-Dcom.sun.enterprise.security.httpsOutboundKeyAlias=s1as
-Dosgi.shell.telnet.ip=127.0.0.1
-DANTLR_USE_DIRECT_CLASS_LOADING=true
-Djava.awt.headless=true
-Dcom.ctc.wstx.returnNullForDefaultNamespace=true
-Djava.ext.dirs=C:\Program Files\Java\jdk1.8.0_05/lib/ext;C:\Program Files\Java\jdk1.8.0_05/jre/lib/ext;C:\glassfish4\glassfish\domains\domain1/lib/ext
-Djdbc.drivers=org.apache.derby.jdbc.ClientDriver
-Djava.library.path=C:/glassfish4/glassfish/lib;C:/ProgramData/Oracle/Java/javapath;C:/Windows/Sun/Java/bin;C:/Windows/System32;C:/Windows;C:/glassfish4/glassfish/ C:/Program Files/Dell/Dell Data Protection/Drivers/TSS/bin;C:/Program Files (x86)/Common Files/Intuit/QBPOSSDKRuntime;C:/Program Files (x86)/QuickTime/QTSystem;D:/Bulletproof/bpMySql/bin;C:/glassfish4/glassfish
com.sun.enterprise.glassfish.bootstrap.ASMain
-upgrade
false
-domaindir
C:/glassfish4/glassfish/domains/domain1
-read-stdin
true
-asadmin-args
--host,,,localhost,,,--port,,,4848,,,--secure=false,,,--terse=false,,,--echo=false,,,--interactive=true,,,start-domain,,,--verbose=false,,,--watchdog=false,,,--debug=false,,,--domaindir,,,C:\glassfish4\glassfish\domains,,,domain1
-domainname
domain1
-instancename
server
-type
DAS
-verbose
false
-asadmin-classpath
C:/glassfish4/glassfish/lib/client/appserver-cli.jar
-debug
false
-asadmin-classname
com.sun.enterprise.admin.cli.AdminMain]]

 [2015-10-09T12:21:27.864-1000] [glassfish 4.1] [WARNING] [] [org.glassfish.grizzly.config.Utils] [tid: _ThreadID=17 _ThreadName=RunLevelControllerThread-1444429287050] [timeMillis: 1444429287864] [levelValue: 900] [[
  Instance could not be initialized. Class=interface org.glassfish.grizzly.http.server.AddOn, name=http-listener-1, realClassName=org.glassfish.grizzly.http2.Http2AddOn]]

[2015-10-09T12:21:27.962-1000] [glassfish 4.1] [WARNING] [] [org.glassfish.grizzly.config.Utils] [tid: _ThreadID=17 _ThreadName=RunLevelControllerThread-1444429287050] [timeMillis: 1444429287962] [levelValue: 900] [[
  Instance could not be initialized. Class=interface org.glassfish.grizzly.http.server.AddOn, name=http-listener-2, realClassName=org.glassfish.grizzly.http2.Http2AddOn]]

[2015-10-09T12:21:27.970-1000] [glassfish 4.1] [WARNING] [] [org.glassfish.grizzly.config.Utils] [tid: _ThreadID=17 _ThreadName=RunLevelControllerThread-1444429287050] [timeMillis: 1444429287970] [levelValue: 900] [[
  Instance could not be initialized. Class=interface org.glassfish.grizzly.http.server.AddOn, name=admin-listener, realClassName=org.glassfish.grizzly.http2.Http2AddOn]]

[2015-10-09T12:21:31.120-1000] [glassfish 4.1] [WARNING] [] [org.glassfish.grizzly.config.Utils] [tid: _ThreadID=75 _ThreadName=pool-13-thread-1] [timeMillis: 1444429291120] [levelValue: 900] [[
  Instance could not be initialized. Class=interface org.glassfish.grizzly.http.server.AddOn, name=http-listener-1, realClassName=org.glassfish.grizzly.http2.Http2AddOn]]

[2015-10-09T12:21:31.135-1000] [glassfish 4.1] [WARNING] [] [org.glassfish.grizzly.config.Utils] [tid: _ThreadID=75 _ThreadName=pool-13-thread-1] [timeMillis: 1444429291135] [levelValue: 900] [[
  Instance could not be initialized. Class=interface org.glassfish.grizzly.http.server.AddOn, name=http-listener-2, realClassName=org.glassfish.grizzly.http2.Http2AddOn]]

[2015-10-09T12:21:37.895-1000] [glassfish 4.1] [WARNING] [] [javax.enterprise.system.container.web.com.sun.web.security] [tid: _ThreadID=48 _ThreadName=admin-listener(4)] [timeMillis: 1444429297895] [levelValue: 900] [[
  Context path from ServletContext:  differs from path from bundle: /]]

 [2015-10-09T12:22:46.963-1000] [glassfish 4.1] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=48 _ThreadName=admin-listener(4)] [timeMillis: 1444429366963] [levelValue: 900] [[
  StandardWrapperValve[FacesServlet]: Servlet.service() for servlet FacesServlet threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
    at org.apache.catalina.connector.Response.getWriter(Response.java:777)
    at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:224)
    at com.sun.faces.context.ExternalContextImpl.getResponseOutputWriter(ExternalContextImpl.java:851)
    at com.sun.faces.context.PartialViewContextImpl.createPartialResponseWriter(PartialViewContextImpl.java:504)
    at com.sun.faces.context.PartialViewContextImpl.access$300(PartialViewContextImpl.java:79)
    at com.sun.faces.context.PartialViewContextImpl$DelayedInitPartialResponseWriter.getWrapped(PartialViewContextImpl.java:642)
    at javax.faces.context.PartialResponseWriter.startDocument(PartialResponseWriter.java:120)
    at com.sun.faces.context.AjaxExceptionHandlerImpl.handlePartialResponseError(AjaxExceptionHandlerImpl.java:202)
    at com.sun.faces.context.AjaxExceptionHandlerImpl.handle(AjaxExceptionHandlerImpl.java:127)
    at javax.faces.context.ExceptionHandlerWrapper.handle(ExceptionHandlerWrapper.java:100)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:119)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at com.sun.webui.jsf.util.UploadFilter.doFilter(UploadFilter.java:233)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.doChainInvoke(StandardPipeline.java:678)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:745)
]]
</code>```

答: This was a bug in GlassFish 4.1.1 as brothers have been mentioned, but it has been resolved in GlassFish 4.1.2 so you can simply download to it here, and for more info go here

Body:
A week ago I downloaded Glassfish 4.1.  Did a zip install.  Attempted to use Admin Console to create a JDBC Connection Pool.  Received this error message:

java.lang.IllegalStateException: getOutputStream() has already been called for this response

Lots of references to that error.  Lots of people declared it "Asked & Answered".  But I can't find a single reference anywhere to that problem, let alone a solution.

But if anyone believes it's been answered, please be sure to add a link to the solution to this problem:  New installation.  Did nothing but open the console and try to create a new JDBC Connection Pool.

Resource Type: javax.sql.DataSource.
Vendor: MySql.

I've stored mysql-connector-java-5.1.35.jar in \glassfish4\glassfish\lib

Here's the closest thing to a solution I found.  But it was for GF v3.

I finally have tracked down the actual problem in my domain.xml:
  -Dorg.glassfish.web.rfc2109_cookie_names_enforced=false
  was missing in the domain.xml created by asupgrade. I just added it to the domain.xml jvm-options and GF v3 now works as expected.
  Added:

  <jvm-options>-Dorg.glassfish.web.rfc2109_cookie_names_enforced=false</jvm-options>

Tried that.  Didn't work.  (I pasted the GF log entry to show the recommended line is added to the domain.xml GF used on startup.)

I tried digging out domain.xml from my old v3 server and using it in the new v4.  That didn't work.

Other questions involving my Exception message all related to getting it with a deployed app -- mostly servlets.  But this is a clean server.  No apps have been installed.

I found a lot of links to people working on this Exception as a GF bug. Most are awhile ago.  None gave a workaround or even said they'd ever solved it.

Can anyone offer a solution?

Or let me know if this is just a bug Oracle decided not to fix?

Or know of where I can find help?  This is killing me.

In case it helps here is the GF log for a clean start up (with the jvm insert in the domain.xml.)  It also shows the stack trace for the failed attempt to create a JDBC Connection Pool.

NOTE: I pulled out all [INFO] log entries.  And the [WARNING] entries that  are left all seem related to Grizzly.

[2015-10-09T12:21:24.598-1000] [] [INFO] [NCLS-GFLAUNCHER-00005] [javax.enterprise.launcher] [tid: _ThreadID=1 _ThreadName=main] [timeMillis: 1444429284598] [levelValue: 800] [[
  JVM invocation command line:
C:\Program Files\Java\jdk1.8.0_05\bin\java.exe
-cp
C:/glassfish4/glassfish/modules/glassfish.jar
-XX:+UnlockDiagnosticVMOptions
-XX:NewRatio=2
-XX:MaxPermSize=192m
-Xmx512m
-javaagent:C:/glassfish4/glassfish/lib/monitor/flashlight-agent.jar
-client
-Djavax.xml.accessExternalSchema=all
-Djavax.net.ssl.trustStore=C:\glassfish4\glassfish\domains\domain1/config/cacerts.jks
-Djdk.corba.allowOutputStreamSubclass=true
-Dfelix.fileinstall.dir=C:\glassfish4\glassfish/modules/autostart/
-Dorg.glassfish.additionalOSGiBundlesToStart=org.apache.felix.shell,org.apache.felix.gogo.runtime,org.apache.felix.gogo.shell,org.apache.felix.gogo.command,org.apache.felix.shell.remote,org.apache.felix.fileinstall
-Dcom.sun.aas.installRoot=C:\glassfish4\glassfish
-Dfelix.fileinstall.poll=5000
-Djava.endorsed.dirs=C:\glassfish4\glassfish/modules/endorsed;C:\glassfish4\glassfish/lib/endorsed
-Djava.security.policy=C:\glassfish4\glassfish\domains\domain1/config/server.policy
-Dosgi.shell.telnet.maxconn=1
-Dfelix.fileinstall.bundles.startTransient=true
-Dcom.sun.enterprise.config.config_environment_factory_class=com.sun.enterprise.config.serverbeans.AppserverConfigEnvironmentFactory
-Dfelix.fileinstall.log.level=2
-Dorg.glassfish.web.rfc2109_cookie_names_enforced=false
-Djavax.net.ssl.keyStore=C:\glassfish4\glassfish\domains\domain1/config/keystore.jks
-Djava.security.auth.login.config=C:\glassfish4\glassfish\domains\domain1/config/login.conf
-Dfelix.fileinstall.disableConfigSave=false
-Dfelix.fileinstall.bundles.new.start=true
-Dcom.sun.aas.instanceRoot=C:\glassfish4\glassfish\domains\domain1
-Dosgi.shell.telnet.port=6666
-Dgosh.args=--nointeractive
-Dcom.sun.enterprise.security.httpsOutboundKeyAlias=s1as
-Dosgi.shell.telnet.ip=127.0.0.1
-DANTLR_USE_DIRECT_CLASS_LOADING=true
-Djava.awt.headless=true
-Dcom.ctc.wstx.returnNullForDefaultNamespace=true
-Djava.ext.dirs=C:\Program Files\Java\jdk1.8.0_05/lib/ext;C:\Program Files\Java\jdk1.8.0_05/jre/lib/ext;C:\glassfish4\glassfish\domains\domain1/lib/ext
-Djdbc.drivers=org.apache.derby.jdbc.ClientDriver
-Djava.library.path=C:/glassfish4/glassfish/lib;C:/ProgramData/Oracle/Java/javapath;C:/Windows/Sun/Java/bin;C:/Windows/System32;C:/Windows;C:/glassfish4/glassfish/ C:/Program Files/Dell/Dell Data Protection/Drivers/TSS/bin;C:/Program Files (x86)/Common Files/Intuit/QBPOSSDKRuntime;C:/Program Files (x86)/QuickTime/QTSystem;D:/Bulletproof/bpMySql/bin;C:/glassfish4/glassfish
com.sun.enterprise.glassfish.bootstrap.ASMain
-upgrade
false
-domaindir
C:/glassfish4/glassfish/domains/domain1
-read-stdin
true
-asadmin-args
--host,,,localhost,,,--port,,,4848,,,--secure=false,,,--terse=false,,,--echo=false,,,--interactive=true,,,start-domain,,,--verbose=false,,,--watchdog=false,,,--debug=false,,,--domaindir,,,C:\glassfish4\glassfish\domains,,,domain1
-domainname
domain1
-instancename
server
-type
DAS
-verbose
false
-asadmin-classpath
C:/glassfish4/glassfish/lib/client/appserver-cli.jar
-debug
false
-asadmin-classname
com.sun.enterprise.admin.cli.AdminMain]]

 [2015-10-09T12:21:27.864-1000] [glassfish 4.1] [WARNING] [] [org.glassfish.grizzly.config.Utils] [tid: _ThreadID=17 _ThreadName=RunLevelControllerThread-1444429287050] [timeMillis: 1444429287864] [levelValue: 900] [[
  Instance could not be initialized. Class=interface org.glassfish.grizzly.http.server.AddOn, name=http-listener-1, realClassName=org.glassfish.grizzly.http2.Http2AddOn]]

[2015-10-09T12:21:27.962-1000] [glassfish 4.1] [WARNING] [] [org.glassfish.grizzly.config.Utils] [tid: _ThreadID=17 _ThreadName=RunLevelControllerThread-1444429287050] [timeMillis: 1444429287962] [levelValue: 900] [[
  Instance could not be initialized. Class=interface org.glassfish.grizzly.http.server.AddOn, name=http-listener-2, realClassName=org.glassfish.grizzly.http2.Http2AddOn]]

[2015-10-09T12:21:27.970-1000] [glassfish 4.1] [WARNING] [] [org.glassfish.grizzly.config.Utils] [tid: _ThreadID=17 _ThreadName=RunLevelControllerThread-1444429287050] [timeMillis: 1444429287970] [levelValue: 900] [[
  Instance could not be initialized. Class=interface org.glassfish.grizzly.http.server.AddOn, name=admin-listener, realClassName=org.glassfish.grizzly.http2.Http2AddOn]]

[2015-10-09T12:21:31.120-1000] [glassfish 4.1] [WARNING] [] [org.glassfish.grizzly.config.Utils] [tid: _ThreadID=75 _ThreadName=pool-13-thread-1] [timeMillis: 1444429291120] [levelValue: 900] [[
  Instance could not be initialized. Class=interface org.glassfish.grizzly.http.server.AddOn, name=http-listener-1, realClassName=org.glassfish.grizzly.http2.Http2AddOn]]

[2015-10-09T12:21:31.135-1000] [glassfish 4.1] [WARNING] [] [org.glassfish.grizzly.config.Utils] [tid: _ThreadID=75 _ThreadName=pool-13-thread-1] [timeMillis: 1444429291135] [levelValue: 900] [[
  Instance could not be initialized. Class=interface org.glassfish.grizzly.http.server.AddOn, name=http-listener-2, realClassName=org.glassfish.grizzly.http2.Http2AddOn]]

[2015-10-09T12:21:37.895-1000] [glassfish 4.1] [WARNING] [] [javax.enterprise.system.container.web.com.sun.web.security] [tid: _ThreadID=48 _ThreadName=admin-listener(4)] [timeMillis: 1444429297895] [levelValue: 900] [[
  Context path from ServletContext:  differs from path from bundle: /]]

 [2015-10-09T12:22:46.963-1000] [glassfish 4.1] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=48 _ThreadName=admin-listener(4)] [timeMillis: 1444429366963] [levelValue: 900] [[
  StandardWrapperValve[FacesServlet]: Servlet.service() for servlet FacesServlet threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
    at org.apache.catalina.connector.Response.getWriter(Response.java:777)
    at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:224)
    at com.sun.faces.context.ExternalContextImpl.getResponseOutputWriter(ExternalContextImpl.java:851)
    at com.sun.faces.context.PartialViewContextImpl.createPartialResponseWriter(PartialViewContextImpl.java:504)
    at com.sun.faces.context.PartialViewContextImpl.access$300(PartialViewContextImpl.java:79)
    at com.sun.faces.context.PartialViewContextImpl$DelayedInitPartialResponseWriter.getWrapped(PartialViewContextImpl.java:642)
    at javax.faces.context.PartialResponseWriter.startDocument(PartialResponseWriter.java:120)
    at com.sun.faces.context.AjaxExceptionHandlerImpl.handlePartialResponseError(AjaxExceptionHandlerImpl.java:202)
    at com.sun.faces.context.AjaxExceptionHandlerImpl.handle(AjaxExceptionHandlerImpl.java:127)
    at javax.faces.context.ExceptionHandlerWrapper.handle(ExceptionHandlerWrapper.java:100)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:119)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at com.sun.webui.jsf.util.UploadFilter.doFilter(UploadFilter.java:233)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.doChainInvoke(StandardPipeline.java:678)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:745)
]]


来源: stackexchange

问:
How to output a reverse expanded sum
I want to output a reverse expanded sum, which should give me an output like this:

Reverse expanded sum:
  Output the expanded sum in reverse.
  For example, if the user entered 7, then your program should output:

```<code>7+6+5+4+3+2+1=28
</code>```

The code below is giving me an non-stop output instead with +-12+-13 format:

```<code> public static int printSum(int n, boolean reverse) {
    int sum = 0;
    String s = "";
    for(int i = 1; i < n+1; i--) {
        sum += i;//was =
        //System.out.print(i + "+");
    }
    for(int i = 1; i <n; i--) {
        s =String.valueOf(i);
        System.out.print(s + "+");
    }
    //System.out.print(i);

    System.out.print( n + "=" + sum);
    return sum;
}
</code>```

I used case statements in the main method to call the printSum method:

```<code>//reverse expanded sum
case 2:
    System.out.print("Enter a positive integer.\n");
    number = console.nextInt();
    printSum(number, false);
    break;
</code>```

答:
I suppose your logic is correct to some extent. Try this.</p>

```<code>public static int printSum(int n, boolean reverse){

  int sum = 0;
  for( int i = n ; i>0 ; i--){
     sum += i;
     if(i > 1){
       System.out.print(i + "+");
     }else{
      System.out.print(i);
     }
  }
  System.out.print( n + "=" + sum);
  return sum;
 }
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to output a reverse expanded sum

Body:
I want to output a reverse expanded sum, which should give me an output like this:

Reverse expanded sum:
  Output the expanded sum in reverse.
  For example, if the user entered 7, then your program should output:

7+6+5+4+3+2+1=28

The code below is giving me an non-stop output instead with +-12+-13 format:

 public static int printSum(int n, boolean reverse) {
    int sum = 0;
    String s = "";
    for(int i = 1; i < n+1; i--) {
        sum += i;//was =
        //System.out.print(i + "+");
    }
    for(int i = 1; i <n; i--) {
        s =String.valueOf(i);
        System.out.print(s + "+");
    }
    //System.out.print(i);

    System.out.print( n + "=" + sum);
    return sum;
}

I used case statements in the main method to call the printSum method:

//reverse expanded sum
case 2:
    System.out.print("Enter a positive integer.\n");
    number = console.nextInt();
    printSum(number, false);
    break;

Body:
I suppose your logic is correct to some extent. Try this.

public static int printSum(int n, boolean reverse){

  int sum = 0;
  for( int i = n ; i>0 ; i--){
     sum += i;
     if(i > 1){
       System.out.print(i + "+");
     }else{
      System.out.print(i);
     }
  }
  System.out.print( n + "=" + sum);
  return sum;
 }


问:
Which encoding opens CSV files correctly with Excel on both Mac and Windows?
We have a web app that exports CSV files containing foreign characters with UTF-8, no BOM. Both Windows and Mac users get garbage characters in Excel. I tried converting to UTF-8 with BOM; Excel/Win is fine with it, Excel/Mac shows gibberish. I'm using Excel 2003/Win, Excel 2011/Mac.
Here's all the encodings I tried:

```<code>Encoding  BOM      Win                            Mac
--------  ---      ----------------------------   ------------
utf-8     --       scrambled                      scrambled
utf-8     BOM      WORKS                          scrambled
utf-16    --       file not recognized            file not recognized
utf-16    BOM      file not recognized            Chinese gibberish
utf-16LE  --       file not recognized            file not recognized
utf-16LE  BOM      characters OK,                 same as Win
                   row data all in first field
</code>```

The best one is UTF-16LE with BOM, but the CSV is not recognized as such. The field separator is comma, but semicolon doesn't change things.

Is there any encoding that works in both worlds?

答:
Solve this using java ( UTF-16LE with BOM ):

```<code>String csvReportStr = getCsvReport();
byte[] data = Charset.forName("UTF-16LE").encode(csvReportStr)
    .put(0, (byte) 0xFF)
    .put(1, (byte) 0xFE)
    .array();
</code>```

Note that CSV file should use TAB as separator. You can read the CSV file both on windows and MAC OS X.

Refer to: How do I encode/decode UTF-16LE byte arrays with a BOM?

Body:
We have a web app that exports CSV files containing foreign characters with UTF-8, no BOM. Both Windows and Mac users get garbage characters in Excel. I tried converting to UTF-8 with BOM; Excel/Win is fine with it, Excel/Mac shows gibberish. I'm using Excel 2003/Win, Excel 2011/Mac.
Here's all the encodings I tried:

Encoding  BOM      Win                            Mac
--------  ---      ----------------------------   ------------
utf-8     --       scrambled                      scrambled
utf-8     BOM      WORKS                          scrambled
utf-16    --       file not recognized            file not recognized
utf-16    BOM      file not recognized            Chinese gibberish
utf-16LE  --       file not recognized            file not recognized
utf-16LE  BOM      characters OK,                 same as Win
                   row data all in first field

The best one is UTF-16LE with BOM, but the CSV is not recognized as such. The field separator is comma, but semicolon doesn't change things.

Is there any encoding that works in both worlds?

Body:
Solve this using java ( UTF-16LE with BOM ):

String csvReportStr = getCsvReport();
byte[] data = Charset.forName("UTF-16LE").encode(csvReportStr)
    .put(0, (byte) 0xFF)
    .put(1, (byte) 0xFE)
    .array();

Note that CSV file should use TAB as separator. You can read the CSV file both on windows and MAC OS X.

Refer to: How do I encode/decode UTF-16LE byte arrays with a BOM?


问:
How to remove unwanted space below scrollview in android?
When I run this code on my device, additional space appears below the imageView. In the end, I would like my images to fulfill the greatest amount of space on the screen without distorting their dimensions. Any help would be greatly appreciated. I have attached the code for my elements and their attributes. Thanks!
    </p>

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_ch0_example_problems"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:clipToPadding="false"
android:fillViewport="false"
android:scrollbarStyle="insideOverlay"
tools:context="com.example.android.chsalgebra.Ch0ExampleProblems">

<Button
    android:id="@+id/prevBut1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_marginBottom="6dp"
    android:layout_marginLeft="6dp"
    android:onClick="displayProblemMinus"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:text="Previous"
    android:textAllCaps="false"
    android:textColor="#769ecd" />

<Button
    android:id="@+id/nextBut1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_marginBottom="6dp"
    android:layout_marginRight="6dp"
    android:onClick="displayProblemPlus"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:text="Next"
    android:textAllCaps="false"
    android:textColor="#769ecd" />

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/prevBut1"
    android:layout_alignLeft="@+id/prevBut1"
    android:layout_alignParentTop="true"
    android:layout_alignStart="@+id/prevBut1">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/ex1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:paddingTop="12dp"
            android:scaleType="fitStart"
            app:srcCompat="@drawable/ch0ex1" />
    </LinearLayout>
</ScrollView>
</RelativeLayout>
</code>```

答:
Replace the imageview with text view with height wrap content. </p>

<p>If the space is still there, then the problem is with the scroll view, else imageview has problem. </p>

Body:
When I run this code on my device, additional space appears below the imageView. In the end, I would like my images to fulfill the greatest amount of space on the screen without distorting their dimensions. Any help would be greatly appreciated. I have attached the code for my elements and their attributes. Thanks!

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_ch0_example_problems"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:clipToPadding="false"
android:fillViewport="false"
android:scrollbarStyle="insideOverlay"
tools:context="com.example.android.chsalgebra.Ch0ExampleProblems">

<Button
    android:id="@+id/prevBut1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_marginBottom="6dp"
    android:layout_marginLeft="6dp"
    android:onClick="displayProblemMinus"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:text="Previous"
    android:textAllCaps="false"
    android:textColor="#769ecd" />

<Button
    android:id="@+id/nextBut1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_marginBottom="6dp"
    android:layout_marginRight="6dp"
    android:onClick="displayProblemPlus"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:text="Next"
    android:textAllCaps="false"
    android:textColor="#769ecd" />

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/prevBut1"
    android:layout_alignLeft="@+id/prevBut1"
    android:layout_alignParentTop="true"
    android:layout_alignStart="@+id/prevBut1">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/ex1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:paddingTop="12dp"
            android:scaleType="fitStart"
            app:srcCompat="@drawable/ch0ex1" />
    </LinearLayout>
</ScrollView>
</RelativeLayout>

Body:
Replace the imageview with text view with height wrap content.

If the space is still there, then the problem is with the scroll view, else imageview has problem.


问:
What does "cd -P" / "pwd -P" code do that "$(basename -- "$BASH_SOURCE")" does not?
I am reading a environment variable setup shell program for spark. I don't quite understand this part.

Codes are shown below:

```<code># resolve links - $0 may be a softlink
this="${BASH_SOURCE:-$0}"
common_bin="$(cd -P -- "$(dirname -- "$this")" && pwd -P)"
script="$(basename -- "$this")"
this="$common_bin/$script"

# convert relative path to absolute path
config_bin="`dirname "$this"`"
script="`basename "$this"`"
config_bin="`cd "$config_bin"; pwd`"
this="$config_bin/$script"

export SPARK_PREFIX="`dirname "$this"`"/..
export SPARK_HOME="${SPARK_PREFIX}"
export SPARK_CONF_DIR="${SPARK_CONF_DIR:-"$SPARK_HOME/conf"}"
# Add the PySpark classes to the PYTHONPATH:
export PYTHONPATH="$SPARK_HOME/python:$PYTHONPATH"
export PYTHONPATH="$SPARK_HOME/python/lib/py4j-0.9-src.zip:$PYTHONPATH"
</code>```

In the first part it is said by comment that the part is to resolve the links, and in the second part, it is said to convert relative path to absolute path.

But I don't see any difference between these 2 "this": this="$common_bin/$script" and this="$config_bin/$script". I think first 4 lines already resolve link and give variable "this" an absolute path, why the shell does the same thing again in the second part(commands after the second comment)?

Thanks in advance.

答:
Though the script's intention seems to be exactly what Charles has mentioned, the code has an issue that would make both common_bin and config_bin set to the same value.

The issue is on line 5:

```<code> this="$common_bin/$script"
</code>```

That would make this point to the physical path of the script, obtained from pwd -P earlier.

Then, on line 8, config_bin is being set to the dirname of this, which would be the physical path, not the one with symlink unresolved:

```<code> config_bin="`dirname "$this"`"
</code>```

So, both config_bin and common_bin will end up getting the same value.  I don't see either of the variables used anywhere else in the script and hence not sure what the author's real intent was.  It does appear that the following section of code isn't required at all:

```<code># convert relative path to absolute path
config_bin="`dirname "$this"`"
script="`basename "$this"`"
config_bin="`cd "$config_bin"; pwd`"
this="$config_bin/$script"
</code>```

Body:
I am reading a environment variable setup shell program for spark. I don't quite understand this part.

Codes are shown below:

# resolve links - $0 may be a softlink
this="${BASH_SOURCE:-$0}"
common_bin="$(cd -P -- "$(dirname -- "$this")" && pwd -P)"
script="$(basename -- "$this")"
this="$common_bin/$script"

# convert relative path to absolute path
config_bin="`dirname "$this"`"
script="`basename "$this"`"
config_bin="`cd "$config_bin"; pwd`"
this="$config_bin/$script"

export SPARK_PREFIX="`dirname "$this"`"/..
export SPARK_HOME="${SPARK_PREFIX}"
export SPARK_CONF_DIR="${SPARK_CONF_DIR:-"$SPARK_HOME/conf"}"
# Add the PySpark classes to the PYTHONPATH:
export PYTHONPATH="$SPARK_HOME/python:$PYTHONPATH"
export PYTHONPATH="$SPARK_HOME/python/lib/py4j-0.9-src.zip:$PYTHONPATH"

In the first part it is said by comment that the part is to resolve the links, and in the second part, it is said to convert relative path to absolute path.

But I don't see any difference between these 2 "this": this="$common_bin/$script" and this="$config_bin/$script". I think first 4 lines already resolve link and give variable "this" an absolute path, why the shell does the same thing again in the second part(commands after the second comment)?

Thanks in advance.

Body:
Though the script's intention seems to be exactly what Charles has mentioned, the code has an issue that would make both common_bin and config_bin set to the same value.

The issue is on line 5:

 this="$common_bin/$script"

That would make this point to the physical path of the script, obtained from pwd -P earlier.

Then, on line 8, config_bin is being set to the dirname of this, which would be the physical path, not the one with symlink unresolved:

 config_bin="`dirname "$this"`"

So, both config_bin and common_bin will end up getting the same value.  I don't see either of the variables used anywhere else in the script and hence not sure what the author's real intent was.  It does appear that the following section of code isn't required at all:

# convert relative path to absolute path
config_bin="`dirname "$this"`"
script="`basename "$this"`"
config_bin="`cd "$config_bin"; pwd`"
this="$config_bin/$script"


问:
How to block access to the .svn/entries on my webserver?
I setup an NGINX webserver and use svn to manage project folder. Nessus found the weakness:

Configure permissions for the affected

  web server to deny access to the

  '.svn' directory.

How do I block access to the .svn directory? It seems that svn export is the more preferable way to checkout on the webserver, but it easier to me to use svn up.

答:
If you're under IIS, you can use the method outlined here:

https://serverfault.com/questions/23340/ignoring-svn-directories-under-iis

ContentLicense: CC BY-SA 2.5


问:
Database is not updating after running stored procedure in asp app
I have an asp app that should be able to let a user update an entry in a sql server database. When I run my stored procedure though in my method, nothing happens to the database.

```<code>public void updateFeature(Feature updatedFeature)
{
    using (SqlConnection sqlConnection = new SqlConnection(GetConnectionString(updatedFeature.Environment)))
    using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
    {
        sqlCommand.CommandType = CommandType.StoredProcedure;
        sqlCommand.CommandText = "usp_UpdateFeature";
        sqlCommand.Parameters.AddWithValue("@FeatureName", updatedFeature.FeatureName);
        sqlCommand.Parameters.AddWithValue("@FeatureID", updatedFeature.FeatureID);
        sqlCommand.Parameters.AddWithValue("@FeatureDescription", updatedFeature.Description);
        sqlCommand.Parameters.AddWithValue("@FieldName", updatedFeature.FieldName);
        sqlCommand.Parameters.AddWithValue("@OnOffSwitch", updatedFeature.IsOn);
        sqlCommand.Parameters.AddWithValue("@ChannelID", updatedFeature.ChannelID);
        sqlCommand.Parameters.AddWithValue("@ProductID", updatedFeature.ProductID);

        sqlConnection.Open();
        int numberOfRowsChanged =  sqlCommand.ExecuteNonQuery();
    }
}
</code>```

and my stored procedure looks like this

```<code>ALTER PROCEDURE [dbo].[usp_UpdateFeature]
(
 @FeatureID int,
 @FeatureName varchar(30),
 @FeatureDescription varchar(200) = null,
 @FieldName varchar(40),
 @OnOffSwitch bit,
 @ChannelID varchar(3),
 @ProductID varchar(2)
)
AS

SET NOCOUNT ON

UPDATE FM_Feature
SET FeatureName = @FeatureName,
 FeatureDescription = @FeatureDescription,
 FieldName = @FieldName,
 OnOffSwitch = @OnOffSwitch,
 ProductID = @ProductID,
 ChannelID = @ChannelID
WHERE FeatureID = @FeatureID
</code>```

The numberOfRowsChanged parameter returns -1 but I do not get any exceptions or errors. Is there something that I am missing or not understanding?

答:
I think that you need to open your connection before you create your command, i hope that will be helpful for you .

```<code>using (SqlConnection sqlConnection = new SqlConnection(GetConnectionString(updatedFeature.Environment))

sqlConnection.Open();

using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
{
    sqlCommand.CommandType = CommandType.StoredProcedure;
    sqlCommand.CommandText = "usp_UpdateFeature";
    sqlCommand.Parameters.AddWithValue("@FeatureName", updatedFeature.FeatureName);
    sqlCommand.Parameters.AddWithValue("@FeatureID", updatedFeature.FeatureID);
    sqlCommand.Parameters.AddWithValue("@FeatureDescription", updatedFeature.Description);
    sqlCommand.Parameters.AddWithValue("@FieldName", updatedFeature.FieldName);
    sqlCommand.Parameters.AddWithValue("@OnOffSwitch", updatedFeature.IsOn);
    sqlCommand.Parameters.AddWithValue("@ChannelID", updatedFeature.ChannelID);
    sqlCommand.Parameters.AddWithValue("@ProductID", updatedFeature.ProductID);

    int numberOfRowsChanged =  sqlCommand.ExecuteNonQuery();
}
</code>```

enjoy it .

Body:
I have an asp app that should be able to let a user update an entry in a sql server database. When I run my stored procedure though in my method, nothing happens to the database.

public void updateFeature(Feature updatedFeature)
{
    using (SqlConnection sqlConnection = new SqlConnection(GetConnectionString(updatedFeature.Environment)))
    using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
    {
        sqlCommand.CommandType = CommandType.StoredProcedure;
        sqlCommand.CommandText = "usp_UpdateFeature";
        sqlCommand.Parameters.AddWithValue("@FeatureName", updatedFeature.FeatureName);
        sqlCommand.Parameters.AddWithValue("@FeatureID", updatedFeature.FeatureID);
        sqlCommand.Parameters.AddWithValue("@FeatureDescription", updatedFeature.Description);
        sqlCommand.Parameters.AddWithValue("@FieldName", updatedFeature.FieldName);
        sqlCommand.Parameters.AddWithValue("@OnOffSwitch", updatedFeature.IsOn);
        sqlCommand.Parameters.AddWithValue("@ChannelID", updatedFeature.ChannelID);
        sqlCommand.Parameters.AddWithValue("@ProductID", updatedFeature.ProductID);

        sqlConnection.Open();
        int numberOfRowsChanged =  sqlCommand.ExecuteNonQuery();
    }
}

and my stored procedure looks like this

ALTER PROCEDURE [dbo].[usp_UpdateFeature]
(
 @FeatureID int,
 @FeatureName varchar(30),
 @FeatureDescription varchar(200) = null,
 @FieldName varchar(40),
 @OnOffSwitch bit,
 @ChannelID varchar(3),
 @ProductID varchar(2)
)
AS

SET NOCOUNT ON

UPDATE FM_Feature
SET FeatureName = @FeatureName,
 FeatureDescription = @FeatureDescription,
 FieldName = @FieldName,
 OnOffSwitch = @OnOffSwitch,
 ProductID = @ProductID,
 ChannelID = @ChannelID
WHERE FeatureID = @FeatureID

The numberOfRowsChanged parameter returns -1 but I do not get any exceptions or errors. Is there something that I am missing or not understanding?

Body:
I think that you need to open your connection before you create your command, i hope that will be helpful for you .

using (SqlConnection sqlConnection = new SqlConnection(GetConnectionString(updatedFeature.Environment))

sqlConnection.Open();

using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
{
    sqlCommand.CommandType = CommandType.StoredProcedure;
    sqlCommand.CommandText = "usp_UpdateFeature";
    sqlCommand.Parameters.AddWithValue("@FeatureName", updatedFeature.FeatureName);
    sqlCommand.Parameters.AddWithValue("@FeatureID", updatedFeature.FeatureID);
    sqlCommand.Parameters.AddWithValue("@FeatureDescription", updatedFeature.Description);
    sqlCommand.Parameters.AddWithValue("@FieldName", updatedFeature.FieldName);
    sqlCommand.Parameters.AddWithValue("@OnOffSwitch", updatedFeature.IsOn);
    sqlCommand.Parameters.AddWithValue("@ChannelID", updatedFeature.ChannelID);
    sqlCommand.Parameters.AddWithValue("@ProductID", updatedFeature.ProductID);

    int numberOfRowsChanged =  sqlCommand.ExecuteNonQuery();
}

enjoy it .


问:
Why does an AJAX call to a different website providing an API not violate the Same-Origin Policy?
I was writing a React JS app, running off from localhost:8080, and then my own website, making AJAX calls to the API that openweathermap.org provides.

Then it made me wonder, for both localhost:8080 and my website, say www.mysite.com, doesn't the AJAX call to fetch data from http://api.openweathermap.org/data/2.5/forecast violate the Same-Origin Policy?

If the sample is actually hosted on GitHub page, then the AJAX call actually could not go through because GitHub page right now use https, while the AJAX call to the API use http and cannot be https, and it won't get the data.

P.S. it is quite sure that the AJAX wasn't done through JSONP, as I actually saw in the console that the request was made, and the response was just pure JSON data. (so no script tag method was used).

答:
http://api.openweathermap.org/data/2.5/forecast sends Access-Control-Allow-* headers:

```<code>$ curl -I http://api.openweathermap.org/data/2.5/forecast
HTTP/1.1 401 Unauthorized
Server: openresty
Date: Sat, 01 Apr 2017 02:11:30 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 107
Connection: keep-alive
X-Cache-Key: /data/2.5/forecast?
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST
</code>```

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS explains what effect those response headers have on browsers—but the gist of it is, if your client-side JavaScript code running in a browser sends a cross-origin request, and the response that comes back includes the Access-Control-Allow-Origin response header, then the browser will expose that response to your code. But if the response doesn’t include the Access-Control-Allow-Origin response header, then the browser won’t allow your code to access the response.

Body:
http://api.openweathermap.org/data/2.5/forecast sends Access-Control-Allow-* headers:

$ curl -I http://api.openweathermap.org/data/2.5/forecast
HTTP/1.1 401 Unauthorized
Server: openresty
Date: Sat, 01 Apr 2017 02:11:30 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 107
Connection: keep-alive
X-Cache-Key: /data/2.5/forecast?
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS explains what effect those response headers have on browsers—but the gist of it is, if your client-side JavaScript code running in a browser sends a cross-origin request, and the response that comes back includes the Access-Control-Allow-Origin response header, then the browser will expose that response to your code. But if the response doesn’t include the Access-Control-Allow-Origin response header, then the browser won’t allow your code to access the response.


问:
Can I change the order of argument evaluation in clang?
Clang evaluates its arguments from left to right, gcc from right to left. (Both is ok according to the C and C++ language specs, see also g++ vs intel/clang argument passing order?) Is there a way to change the order of argument evaluation in clang? If not via a pragma or compiler switch, maybe someone can point me to the right place in the clang codebase?

Some background information: I'm having a huge (3rd party, not so well documented) codebase that I'm trying to port from gcc to clang and I'm seeing strange problems. From previous experiences I think that at least part of the problem is the argument order evaluation. Being able to switch back and forth between the two modes without mixing two entirely different compilers (and thus maybe introducing many other sources of problems) would be very helpful in bisecting the problem.

答:
i think clang still eval the arguments from right to left.

Consider this code:

int add(int a, int b)
{
   return a+b;
}

When compiled after clang:

080483c0 <add>:
 80483c0:   55                      push   %ebp
 80483c1:   89 e5                   mov    %esp,%ebp
 80483c3:   83 ec 08                sub    $0x8,%esp
 80483c6:   8b 45 0c                mov    0xc(%ebp),%eax
 80483c9:   8b 4d 08                mov    0x8(%ebp),%ecx
 80483cc:   89 4d fc                mov    %ecx,-0x4(%ebp)
 80483cf:   89 45 f8                mov    %eax,-0x8(%ebp)
 80483d2:   8b 45 fc                mov    -0x4(%ebp),%eax
 80483d5:   03 45 f8                add    -0x8(%ebp),%eax
 80483d8:   83 c4 08                add    $0x8,%esp
 80483db:   5d                      pop    %ebp
 80483dc:   c3                      ret

 80483dd:   0f 1f 00                nopl   (%eax)

let think about this decompiled code:

the mov copy the args to the stack

`

```<code>+---------+
|high     |
+---------+
|101      |<-arg2
+---------+
|99       |<-arg1
+---------+
|ret      |
+---------+
|ebp      |
+---------+
|99       |<-a
+---------+
|101      |<-b
+---------+
|low      |
+---------+
</code>```

`

when print &a or &b in gdb, it seems like the arg1 has a higher address than arg2.

acctully, the a and b are now in the stack which below the ebp.

Body:
i think clang still eval the arguments from right to left.

Consider this code:

int add(int a, int b)
{
   return a+b;
}

When compiled after clang:

080483c0 <add>:
 80483c0:   55                      push   %ebp
 80483c1:   89 e5                   mov    %esp,%ebp
 80483c3:   83 ec 08                sub    $0x8,%esp
 80483c6:   8b 45 0c                mov    0xc(%ebp),%eax
 80483c9:   8b 4d 08                mov    0x8(%ebp),%ecx
 80483cc:   89 4d fc                mov    %ecx,-0x4(%ebp)
 80483cf:   89 45 f8                mov    %eax,-0x8(%ebp)
 80483d2:   8b 45 fc                mov    -0x4(%ebp),%eax
 80483d5:   03 45 f8                add    -0x8(%ebp),%eax
 80483d8:   83 c4 08                add    $0x8,%esp
 80483db:   5d                      pop    %ebp
 80483dc:   c3                      ret

 80483dd:   0f 1f 00                nopl   (%eax)

let think about this decompiled code:

the mov copy the args to the stack

`

+---------+
|high     |
+---------+
|101      |<-arg2
+---------+
|99       |<-arg1
+---------+
|ret      |
+---------+
|ebp      |
+---------+
|99       |<-a
+---------+
|101      |<-b
+---------+
|low      |
+---------+

`

when print &a or &b in gdb, it seems like the arg1 has a higher address than arg2.

acctully, the a and b are now in the stack which below the ebp.


问:
Error : cause android.compileSdkVersion is missing
I am recently started to work on the Android Studio. When I am doing sync with gradle then it is giving me a error .

Error : Cause: android.compileSdkVersion is missing!

Guys what could be reason for this, I already have same compileSDKVersion and build tool installed. I see many threads that saying to confirm that you have same sdk version installed in your system but in my case it is already installed.

build.gradle

```<code>android {
    compileSdkVersion 19
    buildToolsVersion "19.0.1"

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }

    sourceSets {
        instrumentTest.setRoot('src/test')
    }
}
</code>```

答:
try this :

```<code>apply plugin: 'android'
apply from: "${rootDir}/android_common.gradle"
</code>```

move your apply from: "${rootDir}/android_common.gradle"
to last lines

Body:
I am recently started to work on the Android Studio. When I am doing sync with gradle then it is giving me a error .

Error : Cause: android.compileSdkVersion is missing!

Guys what could be reason for this, I already have same compileSDKVersion and build tool installed. I see many threads that saying to confirm that you have same sdk version installed in your system but in my case it is already installed.

build.gradle

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.1"

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }

    sourceSets {
        instrumentTest.setRoot('src/test')
    }
}

Body:
try this :

apply plugin: 'android'
apply from: "${rootDir}/android_common.gradle"

move your apply from: "${rootDir}/android_common.gradle"
to last lines


问:
How to check if an input is a valid name in python
I tried this code:

```<code>name = str(input("What is your name? "))
if not name.isalpha():
        print("Please enter a valid name.")
        continue
</code>```

but when I enter a name with a space or full name, I get the "Please enter a valid name." statement even if I only entered a name without any other types of data i.e. int, float.

Does the space count as a string?
If not, how should I change my code so that it will accept a full name with spaces but not accept numbers?

Thanks.

答:
It looks like you just want to check if each character is either a space or a letter. You can do that manually by going through each letter.</p>

```<code>name = str(input("What is your name? "))
if not all(x.isalpha or x == "" for x in  name):
    print("Please enter a valid name.")
else:
    print(name)
</code>```

Body:
I tried this code:

name = str(input("What is your name? "))
if not name.isalpha():
        print("Please enter a valid name.")
        continue

but when I enter a name with a space or full name, I get the "Please enter a valid name." statement even if I only entered a name without any other types of data i.e. int, float.

Does the space count as a string?
If not, how should I change my code so that it will accept a full name with spaces but not accept numbers?

Thanks.

Body:
It looks like you just want to check if each character is either a space or a letter. You can do that manually by going through each letter.

name = str(input("What is your name? "))
if not all(x.isalpha or x == "" for x in  name):
    print("Please enter a valid name.")
else:
    print(name)


问:
Converting Time in UTC to Pacific time
I get a string from a external method with a time and date like so "07/09/10 14:50" is there any way I can convert that time in ruby to 'Pacific US' time knowing its 'UTC' time? with changes accounted for in the date? I.e if the time difference results in the day being different.

答:
require 'time'

If you want pacific time just subtract 25200 seconds from Time.new There is a 7 hour difference between pacific time and GMT.

t = Time.parse((Time.new-25200).to_s)

Then use strftime to format however you want it to look.

puts t.strftime("%A %D at %I:%M%p")

Title: Converting Time in UTC to Pacific time


问:
how get hash info from a torrent file using php?
Is any way to find hash info from a torrent file?
I want to put a form that upload a torrent file, then when it upload, get just hash info from that torrent file,

is it possible using PHP ?

答: It's certainly possible. You will need a library to deserialize the data from the bencode format torrent files are using, and then access info.pieces


问:
How to replace lite-server with my express server.js for Angular 2?
Well, the question maybe has nothing to do with Angular 2, but...After watching Deborah's PluralSight Getting Started video, I tried to migrate my existing angular 1.x project to angular 2. For the client part, I want to switch to TypeScript and Angular 2, but for server part, I want to keep existing code as much as possible. The first issue I ran into is how to replace lite-server used in Deborah's project with my own server.js, while keeping her browsersync setup. Here is part of her package.json file which uses lite-server with -c parameter:

```<code>"scripts": {
    "build": "tsc -p src/",
    "build:watch": "tsc -p src/ -w",
    "serve": "lite-server -c=bs-config.json",
    "prestart": "npm run build",
    "start": "concurrently \"npm run build:watch\" \"npm run serve\"",
    "lint": "tslint ./src/**/*.ts -t verbose"
},
</code>```

bs-config.json looks like this:

```<code>{
  "server": {
    "baseDir": "src",
    "routes": {
      "/node_modules": "node_modules"
    }
  }
}
</code>```

My question is how to replace lite-server with my server.js which looks like this:

```<code>var express  = require('express');
var app      = express();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var http = require('http');
var path = require('path');

var session = require('express-session');
var route = require('./server/route');

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));

var port = 3000;
app.listen(port);
console.log('App listening on port ' + port);

route.init(app);

app.get('*', function(req, res) {
   res.sendfile(__dirname + '/public/index.html');
});
</code>```

systemjs.config.js

```<code>/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

      // other libraries
      'rxjs': 'npm:rxjs'
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);
</code>```

tsconfig.json

```<code>{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  }
}
</code>```

答:
you can use something like reload for express

```<code>reloadServer = reload(server, app);
watch.watchTree(__dirname + "/public", function (f, curr, prev) {
    // Fire server-side reload event
    reloadServer.reload();
});
</code>```

it works with nodemoon, forever and node-supervisor, which is the recommended way of using reload.

Body:
Well, the question maybe has nothing to do with Angular 2, but...After watching Deborah's PluralSight Getting Started video, I tried to migrate my existing angular 1.x project to angular 2. For the client part, I want to switch to TypeScript and Angular 2, but for server part, I want to keep existing code as much as possible. The first issue I ran into is how to replace lite-server used in Deborah's project with my own server.js, while keeping her browsersync setup. Here is part of her package.json file which uses lite-server with -c parameter:

"scripts": {
    "build": "tsc -p src/",
    "build:watch": "tsc -p src/ -w",
    "serve": "lite-server -c=bs-config.json",
    "prestart": "npm run build",
    "start": "concurrently \"npm run build:watch\" \"npm run serve\"",
    "lint": "tslint ./src/**/*.ts -t verbose"
},

bs-config.json looks like this:

{
  "server": {
    "baseDir": "src",
    "routes": {
      "/node_modules": "node_modules"
    }
  }
}

My question is how to replace lite-server with my server.js which looks like this:

var express  = require('express');
var app      = express();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var http = require('http');
var path = require('path');

var session = require('express-session');
var route = require('./server/route');

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));

var port = 3000;
app.listen(port);
console.log('App listening on port ' + port);

route.init(app);

app.get('*', function(req, res) {
   res.sendfile(__dirname + '/public/index.html');
});

systemjs.config.js

/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

      // other libraries
      'rxjs': 'npm:rxjs'
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  }
}

Body:
you can use something like reload for express

reloadServer = reload(server, app);
watch.watchTree(__dirname + "/public", function (f, curr, prev) {
    // Fire server-side reload event
    reloadServer.reload();
});

it works with nodemoon, forever and node-supervisor, which is the recommended way of using reload.


问:
Is the "C# Language Specifications" updated for C# 6.0 or 7.0 yet?
C# is already 7.0. But C# Language Specifications is still for 5.0.

I realize the specifications is outdated when I couldn't find GetValueOrDefault() for a nullable type  in the document.

I wonder if the specification has been updated yet, at least for 6.0?

答:
I have not found any official language specifications for C# 6 and 7 on Microsoft or ECMA site, but here are few links.

While Microsoft's documentation for C# 6 and 7 at these links is succinct, the StackOverflow pages have lots of examples, details and cover gotchas.

For C# 7

What's new in C# 7 on Microsoft website.

For C# 6

What's New in C# 6 on Microsoft website.

For C# 5 and older versions

If someone stumbles upon this question looking for C# version 5, 4 or 2 specifications, Jon Skeet at  C# in Depth
page has put together a nice collection of all the specifications.

P.S. I am intentionally pasting an image snapshot of his page (instead of contents in text format) so I don't take the traffic away from his page.


问:
Cassandra Materialized Views
I have few queries related to the materialized views(MV) in Cassandra 3.x version. Given below is  my understanding of how materialized views work. Can anyone please tell me if my understanding is correct

1.) MV is a replica of a base table. Say I have a base table with 100 GB of data and my replication factor is 3. MV on the base table is nothing but another table with a different partition occupying the same storage as that of the base table. If I am creating an MV for my above table, I will need an addition of 100GB * 3(replication factor)  for storing the new materialized view data?

2.) If the above case is valid, then as such there will be two write process happening for the same data. In case of INSERT, there will be a WRITE overhead, since data will be inserted both to the table and the MV? In case of updates, there will be a read before write on the MV?

3.) The changes to MV when a base table changes will happen asynchornously? What happens if the entire table data is deleted, will it be reflected in MV's immediately or is there some cleanup we need to take?

4.) Any scenarios which needs to be considered where use of MV's could be avoided?

Please help me in clarifying the above questions?

Thanks in advance.

答:
Materialized views handle automated server-side denormalization, removing the need for client side handling of this denormalization and ensuring eventual consistency between the base and view data. This denormalization allows for very fast lookups of data in each view using the normal Cassandra read path

Your Questions Answered below :

If you used select * when creating MV it will take addition of 100GB * 3 storage

The base replica performs a local read of the data in order to create the correct update for the view and use batchlog to provide an equivalent eventual consistency between base table and view. So Each MV will cost you about 10% performance at write time

It will reflected immediately and cassandra will take care of that cleanup.

When not to use MV :

Low cardinality data will create hotspots around the ring
If the partition key of all of the data is the same, those nodes would become overloaded

If there will be a large number of partition tombstones, the performance may suffer

Title: Cassandra Materialized Views


问:
How I can use one Rspec expect assertion to be run for every test, without repeating myself?
I have different functions to write a Rspec tests for. But the problem is, what I try to test here, has same syntax per each function, so I have to copy paste that "expect" line for each test case. Do you know how I can write that expect assertion once and apply to each test step?

look at "expect(Delayed::Job.count).to eq(1)" In the code below:

```<code>  it 'is able to send reminder email for submission deadline to signed-up users ' do
    mail = DelayedMailer.new(@assignment.id, "submission", @due_at)
    Delayed::Job.enqueue(payload_object: mail, priority: 1, run_at: 1.second.from_now)
    expect(Delayed::Job.count).to eq(1)
    expect(Delayed::Job.last.handler).to include("deadline_type:     submission")
    expect { mail.perform } .to change { Mailer.deliveries.count } .by(1)
  end

  it 'is able to send reminder email for review deadline to reviewers ' do
    mail = DelayedMailer.new(@assignment.id, "review", @due_at)
    Delayed::Job.enqueue(payload_object: mail, priority: 1, run_at: 1.second.from_now)
    expect(Delayed::Job.count).to eq(1)
    expect(Delayed::Job.last.handler).to include("deadline_type: review")
    expect { mail.perform } .to change { Mailer.deliveries.count } .by(1)
  end

  it 'is able to send reminder email for Metareview deadline to meta-reviewers and team members of the assignment' do
    mail = DelayedMailer.new(@assignment.id, "metareview", @due_at)
    Delayed::Job.enqueue(payload_object: mail, priority: 1, run_at: 1.second.from_now)
    expect(Delayed::Job.count).to eq(1)
    expect(Delayed::Job.last.handler).to include("deadline_type: metareview")
    expect { mail.perform } .to change { Mailer.deliveries.count } .by(2)
  end
</code>```

答:
You've got two options here:

1) Make a helper method that wraps that logic: https://relishapp.com/rspec/rspec-core/v/3-4/docs/helper-methods/define-helper-methods-in-a-module

The only downside to this one is that you'll have to call the method everywhere you want it.

or

2) Use an after each hook: https://relishapp.com/rspec/rspec-core/v/3-4/docs/helper-methods/define-helper-methods-in-a-module

I don't recommend this one because it will literally run after every spec.

Body:
I have different functions to write a Rspec tests for. But the problem is, what I try to test here, has same syntax per each function, so I have to copy paste that "expect" line for each test case. Do you know how I can write that expect assertion once and apply to each test step?

look at "expect(Delayed::Job.count).to eq(1)" In the code below:

  it 'is able to send reminder email for submission deadline to signed-up users ' do
    mail = DelayedMailer.new(@assignment.id, "submission", @due_at)
    Delayed::Job.enqueue(payload_object: mail, priority: 1, run_at: 1.second.from_now)
    expect(Delayed::Job.count).to eq(1)
    expect(Delayed::Job.last.handler).to include("deadline_type:     submission")
    expect { mail.perform } .to change { Mailer.deliveries.count } .by(1)
  end

  it 'is able to send reminder email for review deadline to reviewers ' do
    mail = DelayedMailer.new(@assignment.id, "review", @due_at)
    Delayed::Job.enqueue(payload_object: mail, priority: 1, run_at: 1.second.from_now)
    expect(Delayed::Job.count).to eq(1)
    expect(Delayed::Job.last.handler).to include("deadline_type: review")
    expect { mail.perform } .to change { Mailer.deliveries.count } .by(1)
  end

  it 'is able to send reminder email for Metareview deadline to meta-reviewers and team members of the assignment' do
    mail = DelayedMailer.new(@assignment.id, "metareview", @due_at)
    Delayed::Job.enqueue(payload_object: mail, priority: 1, run_at: 1.second.from_now)
    expect(Delayed::Job.count).to eq(1)
    expect(Delayed::Job.last.handler).to include("deadline_type: metareview")
    expect { mail.perform } .to change { Mailer.deliveries.count } .by(2)
  end


问:
c++ 12bit variable, how can I do this?
I'm building a voxel engine so I have concerns about memory usage, using 12bit instead of 16bit block ids could save a lot of memory. I have a 3D array of block ids, each id has a static configuration.

I'm not sure what a good way to achieve this would be. Is there a way to just get a block of raw memory and manage it myself and would this be a good idea; are there any problems I might run into? Is there a better way to do this?

I have some experience with c++, but most of my time was spent with Java and c#.

Thanks for reading!

答:
It is possible e.g. :-

reserve a 8-byte variable (store 5 variables, each 12 bits), or

reserve using char[k] that k~ceiling{(12*n)/8.0f}, then use union, etc....

Here is a link (I am the one who ask) that I learn about allocating memory in a chunk.

 How to use void* as a single variable holder? (Ex. void* raw=SomeClass() )

However, I moderately disagree of what you are trying to do.

As far I know, the disadvantage of your approach are :-

Some bug : It is harder to implement.

alignment issue : Performance can be worse.

See this : Memory alignment : how to use alignof / alignas?

Traditional recommendation : profile it before (prematurely) optimize it.

Title: c++ 12bit variable, how can I do this?


问:
Comparing enumerated types in java
```<code> public class seasons{

        public enum compare{

                 summer(0), spring(1), winter(3), fall(4);

               (assume the constructor is already coded)
       }
}
</code>```

How would I create a method that takes in 2 seasons as arguements and compares the values of the seasons?

答:
Compare with == operator</p>

```<code>public static void main(String[] args)
    {
        compareSeasons(Seasons.Summer, Seasons.Summer); //returns true;
        compareSeasons(Seasons.Summer, Seasons.Autumn); //returns false
    }

private enum Seasons{ Summer, Autumn, Winter, Spring; }

private static boolean compareSeasons(Seasons seasonOne, Seasons seasonTwo){
        return seasonOne == seasonTwo;
    }
</code>```

Title: Comparing enumerated types in java

Body:
 public class seasons{

        public enum compare{

                 summer(0), spring(1), winter(3), fall(4);

               (assume the constructor is already coded)
       }
}

How would I create a method that takes in 2 seasons as arguements and compares the values of the seasons?

Body:
Compare with == operator

public static void main(String[] args)
    {
        compareSeasons(Seasons.Summer, Seasons.Summer); //returns true;
        compareSeasons(Seasons.Summer, Seasons.Autumn); //returns false
    }

private enum Seasons{ Summer, Autumn, Winter, Spring; }

private static boolean compareSeasons(Seasons seasonOne, Seasons seasonTwo){
        return seasonOne == seasonTwo;
    }


问:
Implementing Javascript Video like Youtube Editor
I've been searching how to implement a web application which provide the functionality to edit videos. just like the youtube Editor. What are best and free libraries out there for building a web app like this?. A library which support react would be great!.</p>

答: This might be the one you are looking for html5-videoEditor. This is more of a proof of concept than a fully functional web-application. Right now it allows you to load videos into the browser, they get automatically uploaded via WebsSocket to a node.js application, where those assets get transcoded (H264/WebM/OGG). Then you can create a composition (=new video), copy videos to the stage, trim them, transform them, stack them and then finally encode them on the server-side using AviSynth and ffmpeg Currently each encoding job will produce a H264 encoded video.</p>


问:
Node.js encode ISO8859-1 to UTF-8
I have an application that allows users to persist strings to a database and those strings may contain emojis. The problem I have is an emoji such as  will get stored in MySQL as ðŸ˜Š

When I retrieve this string using a PHP MySQL client and render it in a web browser, it renders fine probably because the Content-Type is set to UTF-8. When I try to read the string in node.js, I get back what I think is the ISO8859-1 encoding a literal ðŸ˜Š. The charset on the table is set to latin1 and that's where I'm getting ISO8859-1 from.

What's the right way to encode the string in node.js so that I can see the emoji and not the encoding set by MySQL when I console.log the string?

答:
You do not need, and should not convert encoding. Just use the right protocols. If you send the HTML page in UTF-8, the browser will send the data back to your server in UTF-8.

Then you want to store the data to your database which is in latin1, that won't work at all. You must convert your database to UTF-8 as well. That includes the database, the tables, and eventually the columns themselves. Also make sure that your database client is configured to connect in UTF-8, because the client itself has to declare its encoding.

Once you have the whole data-flux in UTF-8, everything will work flawlessly.

Server -> GET HTML -> POST -> Server -> SQL Client -> Database -> Table -> Column

Title: Node.js encode ISO8859-1 to UTF-8


问:
Speeding up the performance of write.table
I have a data.frame and I want to write it out. The dimensions of my data.frame are 256 rows by 65536 columns. What are faster alternatives to write.csv?

答:
You can also try 'readr' package's read_rds (compare to data.table::fread) and write_rds (compare to data.table::fwrite).

Here is a simple example in my dataset　(1133 rows and 429499 columns):

write dataset

fwrite(rankp2,file="rankp2_429499.txt",col.names=T,row.names=F,quote = F,sep="\t")
write_rds(rankp2,"rankp2_429499.rds")

read dataset (1133 rows and 429499 columns)

system.time(fread("rankp2_429499.txt",sep="\t",header=T,fill = TRUE))
 　user  system elapsed
 42.391   0.526  42.949

system.time(read_rds("rankp2_429499.rds"))
   user  system elapsed
  2.157   0.388   2.547

Hope it helps.


问:
How to sort a column in datagridview by time
Can we sort datagridview column by time only hh:mm:sseven if this column cells contains time in String datatype, more information about my project, i filtered some rows from another datagridview to be shown in the current datagridview that am talking about in this question then in this cells of column contains TimeSpan (not 24-hour or 12-hour format) converted to String datatype, so i want the first row in this datagridview to contains the less time span of all the existing values in this column or in another way the nearest cell value from 00:00:00, if we can sort column in this way how to do it or if we can't sort it as i planned how it works in another way.

For Example: (unsorted column)

Column

00:20:30

00:12:50

00:16:00

(sorted column)

Column

00:12:50

00:16:00

00:20:30

Thanks

答:
From you comment:

”cause i need from the first row that will be sorted in this datagridview to be shown in a textbox, this values are changing each
  time interval”

I am guessing you want a text box to always display the lowest value from a particular column in a DataGridView. I am not sure if simply looking at a particular cell in the data grid view is the best approach. This appears to be the case and the sorting of the column you are asking for seems to imply that the top cell will always be the lowest time span.

I found that as strings the time strings sorted properly by simply clicking on the column header. As you commented, there might be other text in front of the string. If this is the case then you will have to clean up the string, otherwise the commented out code below achieves this sorting requirement you are asking by simply sorting the grid on that column when new rows are added or changes are made to an existing time span cell.

This text box should work regardless of the sorting used in the grid. The only thing this text box needs to look for is when one of the two events described above happens. If the grid has a row added or the user changes the value of a currently displayed time span, then we may need to update the text in this text box.

This is what the code below does. If new rows are added to the grid or the user makes changes to a timespan cell, then those events update the lowest time span text box. The code simply loops through the grid to determine which time span is shorter. If the data is large, it may be quicker to simply check the current lowest time span with the newly added or changed one. The code below takes the last eight characters from the string in what should be the form “hh:mm:ss” then makes time spans from those strings and compares them. Hope this helps.

Below A button click event to toggle the datagridview sorting based on column[0]

```<code>private void button1_Click(object sender, EventArgs e) {
  DataGridViewColumn sortCol = dataGridView1.Columns[0];
  if (dataGridView1.SortOrder == SortOrder.None) {
    dataGridView1.Sort(sortCol, ListSortDirection.Ascending);
  } else {
    if (dataGridView1.SortOrder == SortOrder.Ascending) {
      dataGridView1.Sort(sortCol, ListSortDirection.Descending);
    } else {
      dataGridView1.Sort(sortCol, ListSortDirection.Ascending);
    }
  }
}
</code>```

Two events “CellValueChanged” and “RowsAdded” are used to update the TextBox tbShortestTime.

```<code>private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
  if (e.ColumnIndex == 0) {
    tbShortestTime.Text = GetShortestTime();
    //DataGridViewColumn sortCol = dataGridView1.Columns[0];
    //dataGridView1.Sort(sortCol, ListSortDirection.Ascending);
  }
}
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) {
  tbShortestTime.Text = GetShortestTime();
  //DataGridViewColumn sortCol = dataGridView1.Columns[0];
  //dataGridView1.Sort(sortCol, ListSortDirection.Ascending);
}

private string GetShortestTime() {
  string lowestString = "999:23:59";
  for (int i = 0; i < dataGridView1.Rows.Count; i++) {
    DataGridViewRow curRow = dataGridView1.Rows[i];
    if (!curRow.IsNewRow && curRow.Cells[0].Value != null) {
      lowestString = GetLowerTimeString(lowestString, curRow.Cells[0].Value.ToString());
    }
  }
  return lowestString;
}

private string GetLowerTimeString(string inTime1String, string inTime2String) {
  if (inTime1String.Length >= 8 && inTime1String.Length >= 8) {
    string time1String = inTime1String.Substring(inTime1String.Length - 8, 8);
    string time2String = inTime2String.Substring(inTime2String.Length - 8, 8);
    TimeSpan t1 = new TimeSpan();
    TimeSpan t2 = new TimeSpan();
    TimeSpan.TryParse(time1String, out t1);
    TimeSpan.TryParse(time2String, out t2);
    if (t1 < t2)
      return time1String;
    if (t1 > t2)
      return time2String;
    return time1String;
  }
  else {
    if (inTime1String.Length > inTime2String.Length)
      return inTime2String;
    else
      return inTime1String;
  }
}
</code>```

Body:
From you comment:

”cause i need from the first row that will be sorted in this datagridview to be shown in a textbox, this values are changing each
  time interval”

I am guessing you want a text box to always display the lowest value from a particular column in a DataGridView. I am not sure if simply looking at a particular cell in the data grid view is the best approach. This appears to be the case and the sorting of the column you are asking for seems to imply that the top cell will always be the lowest time span.

I found that as strings the time strings sorted properly by simply clicking on the column header. As you commented, there might be other text in front of the string. If this is the case then you will have to clean up the string, otherwise the commented out code below achieves this sorting requirement you are asking by simply sorting the grid on that column when new rows are added or changes are made to an existing time span cell.

This text box should work regardless of the sorting used in the grid. The only thing this text box needs to look for is when one of the two events described above happens. If the grid has a row added or the user changes the value of a currently displayed time span, then we may need to update the text in this text box.

This is what the code below does. If new rows are added to the grid or the user makes changes to a timespan cell, then those events update the lowest time span text box. The code simply loops through the grid to determine which time span is shorter. If the data is large, it may be quicker to simply check the current lowest time span with the newly added or changed one. The code below takes the last eight characters from the string in what should be the form “hh:mm:ss” then makes time spans from those strings and compares them. Hope this helps.

Below A button click event to toggle the datagridview sorting based on column[0]

private void button1_Click(object sender, EventArgs e) {
  DataGridViewColumn sortCol = dataGridView1.Columns[0];
  if (dataGridView1.SortOrder == SortOrder.None) {
    dataGridView1.Sort(sortCol, ListSortDirection.Ascending);
  } else {
    if (dataGridView1.SortOrder == SortOrder.Ascending) {
      dataGridView1.Sort(sortCol, ListSortDirection.Descending);
    } else {
      dataGridView1.Sort(sortCol, ListSortDirection.Ascending);
    }
  }
}

Two events “CellValueChanged” and “RowsAdded” are used to update the TextBox tbShortestTime.

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
  if (e.ColumnIndex == 0) {
    tbShortestTime.Text = GetShortestTime();
    //DataGridViewColumn sortCol = dataGridView1.Columns[0];
    //dataGridView1.Sort(sortCol, ListSortDirection.Ascending);
  }
}
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) {
  tbShortestTime.Text = GetShortestTime();
  //DataGridViewColumn sortCol = dataGridView1.Columns[0];
  //dataGridView1.Sort(sortCol, ListSortDirection.Ascending);
}

private string GetShortestTime() {
  string lowestString = "999:23:59";
  for (int i = 0; i < dataGridView1.Rows.Count; i++) {
    DataGridViewRow curRow = dataGridView1.Rows[i];
    if (!curRow.IsNewRow && curRow.Cells[0].Value != null) {
      lowestString = GetLowerTimeString(lowestString, curRow.Cells[0].Value.ToString());
    }
  }
  return lowestString;
}

private string GetLowerTimeString(string inTime1String, string inTime2String) {
  if (inTime1String.Length >= 8 && inTime1String.Length >= 8) {
    string time1String = inTime1String.Substring(inTime1String.Length - 8, 8);
    string time2String = inTime2String.Substring(inTime2String.Length - 8, 8);
    TimeSpan t1 = new TimeSpan();
    TimeSpan t2 = new TimeSpan();
    TimeSpan.TryParse(time1String, out t1);
    TimeSpan.TryParse(time2String, out t2);
    if (t1 < t2)
      return time1String;
    if (t1 > t2)
      return time2String;
    return time1String;
  }
  else {
    if (inTime1String.Length > inTime2String.Length)
      return inTime2String;
    else
      return inTime1String;
  }
}


问:
setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

componentDidMount(prevProps, prevState, prevContext) {
    let [audioNode, songLen] = [this.refs.audio, List.length-1];

    audioNode.addEventListener('ended', () => {
        this._endedPlay(songLen, () => {
            this._currSong(this.state.songIndex);
            this._Play(audioNode);
        });
    });

    audioNode.addEventListener('timeupdate', () => {
        let [remainTime, remainTimeMin, remainTimeSec, remainTimeInfo] = [];

        if(!isNaN(audioNode.duration)) {
            remainTime = audioNode.duration - audioNode.currentTime;
            remainTimeMin = parseInt(remainTime/60);  // 剩余分
            remainTimeSec = parseInt(remainTime%60);  // 剩余秒

            if(remainTimeSec < 10) {
                remainTimeSec = '0'+remainTimeSec;
            }
            remainTimeInfo = remainTimeMin + ':' + remainTimeSec;
            this.setState({'time': remainTimeInfo});
        }
    });
}

componentWillUnmount () {
    let audio = this.refs.audio;
    audio.removeEventListener('timeupdate');
    audio.removeEventListener('ended');
}
```

Error:

Warning: setState(...): Can only update a mounted or mounting
  component. This usually means you called setState() on an unmounted
  component. This is a no-op. Please check the code for the undefined
  component.

I removeEventListener 'ended' in componentWillUnmount, but it is not working. because I add this.setState({'time': remainTimeInfo}); in componentDidMount.

答:
I had this problem before, and solved it according to React official page isMounted is an Antipattern.

Set a property isMounted flag to be true in componentDidMount , and toggle it false in componentWillUnmount. When you setState() in your callbacks, check isMounted first! It works for me.

```<code>state = {
    isMounted: false
  }
  componentDidMount() {
      this.setState({isMounted: true})
  }
  componentWillUnmount(){
      this.setState({isMounted: false})
  }
</code>```

callback:

```<code>if (this.state.isMounted) {
 this.setState({'time': remainTimeInfo});}
</code>```

Body:
componentDidMount(prevProps, prevState, prevContext) {
    let [audioNode, songLen] = [this.refs.audio, List.length-1];

    audioNode.addEventListener('ended', () => {
        this._endedPlay(songLen, () => {
            this._currSong(this.state.songIndex);
            this._Play(audioNode);
        });
    });

    audioNode.addEventListener('timeupdate', () => {
        let [remainTime, remainTimeMin, remainTimeSec, remainTimeInfo] = [];

        if(!isNaN(audioNode.duration)) {
            remainTime = audioNode.duration - audioNode.currentTime;
            remainTimeMin = parseInt(remainTime/60);  // 剩余分
            remainTimeSec = parseInt(remainTime%60);  // 剩余秒

            if(remainTimeSec < 10) {
                remainTimeSec = '0'+remainTimeSec;
            }
            remainTimeInfo = remainTimeMin + ':' + remainTimeSec;
            this.setState({'time': remainTimeInfo});
        }
    });
}

componentWillUnmount () {
    let audio = this.refs.audio;
    audio.removeEventListener('timeupdate');
    audio.removeEventListener('ended');
}

Error:

Warning: setState(...): Can only update a mounted or mounting
  component. This usually means you called setState() on an unmounted
  component. This is a no-op. Please check the code for the undefined
  component.

I removeEventListener 'ended' in componentWillUnmount, but it is not working. because I add this.setState({'time': remainTimeInfo}); in componentDidMount.

Body:
I had this problem before, and solved it according to React official page isMounted is an Antipattern.

Set a property isMounted flag to be true in componentDidMount , and toggle it false in componentWillUnmount. When you setState() in your callbacks, check isMounted first! It works for me.

state = {
    isMounted: false
  }
  componentDidMount() {
      this.setState({isMounted: true})
  }
  componentWillUnmount(){
      this.setState({isMounted: false})
  }

callback:

if (this.state.isMounted) {
 this.setState({'time': remainTimeInfo});}

ContentLicense: CC BY-SA 4.0


问:
Exposing appengine cloud endpoints api on custom domain url address
I have set of apis written on google appengine using google cloud endpoints. I want to publish these api's for other developers to consume by releasing the documentation generated through api-explorer. For this I would want my apis to be exposed on url such as https://api.example.com/v1/ but all my api endpoints generated through appengine have a url signature as https://module-dot-project-name.appspot.com/_ah/api/v1/. I have tried mapping my api.example.com to the module serving the api's using the dispatch file, but I could not get my apis to work on my own domain address.

1) How can I get my apis to work on my own domain name?

2) How can I publish my api documentation using api-explorer serving on my own domain address? On url such as https://apis-explorer.appspot.com/apis-explorer/?base=https://api.example.com#p/

答:
1) is now possible with the newer version of cloud endpoints, called Cloud Endpoints Framework. Here is the documentantion, but if you are using the App Engine Standard environment it just works.

2) I'm not sure is possible. I only wrote this answer to addres number 1. :)