问:
Preventing Text from Scrolling Over Anchored Button Using CSS
I have a button that I'm anchoring to the bottom left of my page, because I want it accessible at all times, without scrolling required if there is too much content above it. This is the css I have currently to accomplish this:

```<code>.add-button {
  font-size: 18px;
  background-color: #cfcfcf;
  padding: 10px 45px;
  position: absolute;
  left: 20px;
  bottom: 20px;
}
</code>```

Now I'd like to make it so, if there is scrollable content, that the content doesn't scroll "behind" the button, but disappears from view some place just above the button. By the way, the containing div is titled "side-panel". How could I do this with css?

答:
You should use a fixed position container in your footer that spans the full browser width (and has a background color the same as the body background your text is on) and put your button inside that. Then naturally your content will scroll behind it. The content 'disappearing some place above the button' can be accomplished by adjusting the padding (or padding-top) on the container.

#footer {
  position: fixed;
  bottom: 0;
  width: 100%;
  padding: 10px;
  background-color: #fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='wrapper'>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque finibus facilisis molestie. Cras vulputate velit in nulla gravida, malesuada ultrices quam tempor. Vestibulum dapibus sapien lectus, quis sollicitudin neque scelerisque et. Vivamus faucibus sem eget libero volutpat, et tincidunt purus lobortis. Duis volutpat diam risus, sed molestie tortor viverra id. Vestibulum nec eros et est hendrerit finibus. Aliquam erat volutpat. Cras massa erat, semper sed pharetra nec, tempus sed felis.</p>
<p>Pellentesque odio quam, tincidunt dictum metus sit amet, sollicitudin pretium ligula. Etiam mollis orci quis massa vestibulum, vitae elementum urna dapibus. Nulla facilisi. Cras quis enim sit amet leo condimentum porttitor id non tortor. Phasellus sapien lorem, rhoncus eu nisi feugiat, vestibulum imperdiet risus. In dictum ligula est, vel porttitor lectus ultrices eu. Etiam aliquet ante molestie, sodales mauris eget, finibus velit. Maecenas feugiat nisl libero, in lacinia elit ornare ac.</p>
<p>Maecenas id dignissim mauris, eget elementum massa. Morbi in dictum libero. Integer euismod tortor non arcu cursus laoreet. Aenean eleifend mi metus, eget semper nunc euismod luctus. Mauris venenatis volutpat mauris ut porta. Maecenas felis risus, consequat iaculis ipsum varius, tempus semper magna. Vestibulum vitae nisi nibh. Nam in tortor quis lacus tristique porta ac at risus. Praesent convallis, felis eget imperdiet porta, arcu sem facilisis elit, quis posuere lacus turpis quis ex. Etiam finibus lorem commodo nunc ultrices egestas. Etiam tempus volutpat bibendum. Vivamus ornare, odio vitae pharetra fringilla, turpis arcu luctus velit, a posuere lectus lacus id purus. Nam in malesuada tortor. Nunc pulvinar venenatis urna, in finibus nisi dapibus quis.</p>
<p>Donec cursus risus non augue rutrum, at venenatis augue tincidunt. Phasellus interdum elementum quam, quis laoreet enim blandit sed. Mauris ut est non lectus mollis egestas a vitae purus. Nunc porta dui massa, eget tempor quam venenatis vel. Donec dignissim sollicitudin massa, ac convallis nisl dictum sed. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Praesent non dui ullamcorper, rutrum lectus in, euismod mauris. Curabitur imperdiet ut magna nec pretium.</p>
<p>Nunc vitae congue nunc. Aenean eget justo ante. Suspendisse nec molestie orci. Suspendisse ac consequat orci, in consequat risus. Vestibulum volutpat, erat ut egestas scelerisque, sapien diam mattis mauris, malesuada facilisis elit dui in urna. Aliquam erat volutpat. Aliquam erat volutpat. Maecenas venenatis tincidunt massa at imperdiet. Praesent auctor euismod purus, id iaculis sem placerat vitae. Aliquam erat volutpat.</p>
  <div id='footer'>
    <button id='button' value='Foo'>Foo!</button>
  </div>
</div></code>```

Body:
I have a button that I'm anchoring to the bottom left of my page, because I want it accessible at all times, without scrolling required if there is too much content above it. This is the css I have currently to accomplish this:

.add-button {
  font-size: 18px;
  background-color: #cfcfcf;
  padding: 10px 45px;
  position: absolute;
  left: 20px;
  bottom: 20px;
}

Now I'd like to make it so, if there is scrollable content, that the content doesn't scroll "behind" the button, but disappears from view some place just above the button. By the way, the containing div is titled "side-panel". How could I do this with css?

Body:
You should use a fixed position container in your footer that spans the full browser width (and has a background color the same as the body background your text is on) and put your button inside that. Then naturally your content will scroll behind it. The content 'disappearing some place above the button' can be accomplished by adjusting the padding (or padding-top) on the container.

#footer {
  position: fixed;
  bottom: 0;
  width: 100%;
  padding: 10px;
  background-color: #fff;
}

<div id='wrapper'>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque finibus facilisis molestie. Cras vulputate velit in nulla gravida, malesuada ultrices quam tempor. Vestibulum dapibus sapien lectus, quis sollicitudin neque scelerisque et. Vivamus faucibus sem eget libero volutpat, et tincidunt purus lobortis. Duis volutpat diam risus, sed molestie tortor viverra id. Vestibulum nec eros et est hendrerit finibus. Aliquam erat volutpat. Cras massa erat, semper sed pharetra nec, tempus sed felis.</p>
<p>Pellentesque odio quam, tincidunt dictum metus sit amet, sollicitudin pretium ligula. Etiam mollis orci quis massa vestibulum, vitae elementum urna dapibus. Nulla facilisi. Cras quis enim sit amet leo condimentum porttitor id non tortor. Phasellus sapien lorem, rhoncus eu nisi feugiat, vestibulum imperdiet risus. In dictum ligula est, vel porttitor lectus ultrices eu. Etiam aliquet ante molestie, sodales mauris eget, finibus velit. Maecenas feugiat nisl libero, in lacinia elit ornare ac.</p>
<p>Maecenas id dignissim mauris, eget elementum massa. Morbi in dictum libero. Integer euismod tortor non arcu cursus laoreet. Aenean eleifend mi metus, eget semper nunc euismod luctus. Mauris venenatis volutpat mauris ut porta. Maecenas felis risus, consequat iaculis ipsum varius, tempus semper magna. Vestibulum vitae nisi nibh. Nam in tortor quis lacus tristique porta ac at risus. Praesent convallis, felis eget imperdiet porta, arcu sem facilisis elit, quis posuere lacus turpis quis ex. Etiam finibus lorem commodo nunc ultrices egestas. Etiam tempus volutpat bibendum. Vivamus ornare, odio vitae pharetra fringilla, turpis arcu luctus velit, a posuere lectus lacus id purus. Nam in malesuada tortor. Nunc pulvinar venenatis urna, in finibus nisi dapibus quis.</p>
<p>Donec cursus risus non augue rutrum, at venenatis augue tincidunt. Phasellus interdum elementum quam, quis laoreet enim blandit sed. Mauris ut est non lectus mollis egestas a vitae purus. Nunc porta dui massa, eget tempor quam venenatis vel. Donec dignissim sollicitudin massa, ac convallis nisl dictum sed. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Praesent non dui ullamcorper, rutrum lectus in, euismod mauris. Curabitur imperdiet ut magna nec pretium.</p>
<p>Nunc vitae congue nunc. Aenean eget justo ante. Suspendisse nec molestie orci. Suspendisse ac consequat orci, in consequat risus. Vestibulum volutpat, erat ut egestas scelerisque, sapien diam mattis mauris, malesuada facilisis elit dui in urna. Aliquam erat volutpat. Aliquam erat volutpat. Maecenas venenatis tincidunt massa at imperdiet. Praesent auctor euismod purus, id iaculis sem placerat vitae. Aliquam erat volutpat.</p>
  <div id='footer'>
    <button id='button' value='Foo'>Foo!</button>
  </div>
</div>


来源: stackexchange

问:
How to create a free standing patch without source control?
I need to patch libidn2 on Solaris. libidn2 was fetched from GNU's website with wget. Its not provided by Sun and its not in source control.

The library does not use glibc, and it does not have the function error (int status, int errnum, const char *format, ...). I made a copy of the original source file and I have a diff with a similar function:

```<code>solaris:libidn2-0.16$ diff -u src/idn2.c.bu src/idn2.c
--- src/idn2.c.bu       2017-03-29 00:20:08.621934160 -0400
+++ src/idn2.c  2017-03-29 01:25:12.488402745 -0400
@@ -31,7 +31,9 @@
 #include <unistr.h>

 /* Gnulib headers. */
+#ifndef __sun__
 #include "error.h"
+#endif
 #include "gettext.h"
 #define _(String) dgettext (PACKAGE, String)
 #include "progname.h"
@@ -48,6 +50,18 @@
      year.  */
   "Copyright %s %d Simon Josefsson.";

+#if defined(__sun__)
+static void
+error (int status, int errnum, const char *format, ...)
+{
+    va_list args;
+    va_start(args, format);
+    vfprintf(stderr, format, args);
+    va_end(args);
+    exit(status);
+}
+#endif
+
 static void
 usage (int status)
 {
</code>```

I've been reading through the diff(1) and patch(1) man pages, but I'm not quite getting what needs to be done. I don't believe I've found a discussion of the task (maybe I am not seeing the forest through the trees).

My question is, how can I turn this into a free standing patch? That is, how can I turn it into something to apply after a fresh download and unpack of libidn2?

答:
This sounds like an XY problem. Your core problem is "currently I am applying a patch to the libidn2 source which I want to redo later for future releases of libidn2", right? This is exactly what you want to use source code control for! Just because the upstream source is not fetched from a source code control repository, it does not mean that you cannot put into one yourself:

```<code>$ mkdir libidn2-source; cd libidn2-source
$ git init
$ git checkout -b upstream
$ wget https://alpha.gnu.org/gnu/libidn/libidn2-0.16.tar.gz
$ tar zxvf libidn2-0.16.tar.gz && rm libidn2-0.16.tar.gz
$ git add .
$ git commit -m "Upstream libidn2-0.16.tar.gz"
$ git checkout -b downstream
$ cp /the/file/in/the/question/src/idn2.c src/idn2.c
$ git add src/idn2.c
$ git commit -m "Added sun specific error fallback function"

# In the future...
$ git checkout upstream
$ wget https://alpha.gnu.org/gnu/libidn/libidn2-latestgreatest.tar.gz
$ tar zxvf libidn2-latestgreatest.tar.gz && rm libidn2-latestgreatest.tar.gz
$ git add .
$ git commit -m "Upstream libidn2-latestgreatest.tar.gz"

# Now for the "apply after a fresh download and unpack of libidn2" part:
$ git rebase upstream downstream
</code>```

Notice the lack of any keep track of and update free standing patch file here.

The source seems to be available in a git repo, so you might just clone that instead of downloading and checking in tar files, but the rebase part will be exactly the same.

ContentLicense: CC BY-SA 3.0

Body:
I need to patch libidn2 on Solaris. libidn2 was fetched from GNU's website with wget. Its not provided by Sun and its not in source control.

The library does not use glibc, and it does not have the function error (int status, int errnum, const char *format, ...). I made a copy of the original source file and I have a diff with a similar function:

solaris:libidn2-0.16$ diff -u src/idn2.c.bu src/idn2.c
--- src/idn2.c.bu       2017-03-29 00:20:08.621934160 -0400
+++ src/idn2.c  2017-03-29 01:25:12.488402745 -0400
@@ -31,7 +31,9 @@
 #include <unistr.h>

 /* Gnulib headers. */
+#ifndef __sun__
 #include "error.h"
+#endif
 #include "gettext.h"
 #define _(String) dgettext (PACKAGE, String)
 #include "progname.h"
@@ -48,6 +50,18 @@
      year.  */
   "Copyright %s %d Simon Josefsson.";

+#if defined(__sun__)
+static void
+error (int status, int errnum, const char *format, ...)
+{
+    va_list args;
+    va_start(args, format);
+    vfprintf(stderr, format, args);
+    va_end(args);
+    exit(status);
+}
+#endif
+
 static void
 usage (int status)
 {

I've been reading through the diff(1) and patch(1) man pages, but I'm not quite getting what needs to be done. I don't believe I've found a discussion of the task (maybe I am not seeing the forest through the trees).

My question is, how can I turn this into a free standing patch? That is, how can I turn it into something to apply after a fresh download and unpack of libidn2?

Body:
This sounds like an XY problem. Your core problem is "currently I am applying a patch to the libidn2 source which I want to redo later for future releases of libidn2", right? This is exactly what you want to use source code control for! Just because the upstream source is not fetched from a source code control repository, it does not mean that you cannot put into one yourself:

$ mkdir libidn2-source; cd libidn2-source
$ git init
$ git checkout -b upstream
$ wget https://alpha.gnu.org/gnu/libidn/libidn2-0.16.tar.gz
$ tar zxvf libidn2-0.16.tar.gz && rm libidn2-0.16.tar.gz
$ git add .
$ git commit -m "Upstream libidn2-0.16.tar.gz"
$ git checkout -b downstream
$ cp /the/file/in/the/question/src/idn2.c src/idn2.c
$ git add src/idn2.c
$ git commit -m "Added sun specific error fallback function"

# In the future...
$ git checkout upstream
$ wget https://alpha.gnu.org/gnu/libidn/libidn2-latestgreatest.tar.gz
$ tar zxvf libidn2-latestgreatest.tar.gz && rm libidn2-latestgreatest.tar.gz
$ git add .
$ git commit -m "Upstream libidn2-latestgreatest.tar.gz"

# Now for the "apply after a fresh download and unpack of libidn2" part:
$ git rebase upstream downstream

Notice the lack of any keep track of and update free standing patch file here.

The source seems to be available in a git repo, so you might just clone that instead of downloading and checking in tar files, but the rebase part will be exactly the same.


问:
$.Ajax POST, accessing return data
I'm currently working on a ASP.NET Webforms site and I've run in to a small problem. Been searching around for 2 hours now and I got a deadline, so hoping someone here can assist.

On my .cs file I have the following Webmethod

```<code>[WebMethod]
   public static string IsJobEditable(int jobid)
   {
       try
       {
           string isEditable = "false";

           JobsBLL jbl = new JobsBLL();

           int jobStatusId = jbl.GetJobStatusId(jobid);

           if(jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Waiting) || jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Edit))
           {
               isEditable = "true";
           }

           return isEditable;

       }
       catch (Exception ex)
       {

           throw ex;
       }
   }
</code>```

This function in this case will ALWAYS return TRUE as a string.

On Aspx page I have the following

```<code>$(function () {

           $.ajax({

               type: "POST",
               url: "Coordination.aspx/IsJobEditable",
               data: "{jobid:" + jobid + "}",
               contentType: "application/json; charset=utf-8",
               dataType: "text",
               success: function (result) {

                   alert(result);

                   // This is written out in the alert {"d":"true"}
                   // I want this in a variable as a string
                   // so I can do a check on it before I do some other actions
                   // The format is not a String so i cannot split on it to
                   // retrieve the "true" part.

               },
               error: function (err, result) { alert(err); }

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

As you can see in the comments the value I get back in the Callback method is in to me a weird format. The type is unknown and I need this value to be able to proceed with my entire method surrounding the small portion of the Javascript.

So can anyone point me into the direction where I can access the result variable / data as a var or anything else that will let me put it into a var (as a string).

答: try alert(result.d);</p>

Title: $.Ajax POST, accessing return data

Body:
I'm currently working on a ASP.NET Webforms site and I've run in to a small problem. Been searching around for 2 hours now and I got a deadline, so hoping someone here can assist.

On my .cs file I have the following Webmethod

[WebMethod]
   public static string IsJobEditable(int jobid)
   {
       try
       {
           string isEditable = "false";

           JobsBLL jbl = new JobsBLL();

           int jobStatusId = jbl.GetJobStatusId(jobid);

           if(jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Waiting) || jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Edit))
           {
               isEditable = "true";
           }

           return isEditable;

       }
       catch (Exception ex)
       {

           throw ex;
       }
   }

This function in this case will ALWAYS return TRUE as a string.

On Aspx page I have the following

$(function () {

           $.ajax({

               type: "POST",
               url: "Coordination.aspx/IsJobEditable",
               data: "{jobid:" + jobid + "}",
               contentType: "application/json; charset=utf-8",
               dataType: "text",
               success: function (result) {

                   alert(result);

                   // This is written out in the alert {"d":"true"}
                   // I want this in a variable as a string
                   // so I can do a check on it before I do some other actions
                   // The format is not a String so i cannot split on it to
                   // retrieve the "true" part.

               },
               error: function (err, result) { alert(err); }

           });
       });

As you can see in the comments the value I get back in the Callback method is in to me a weird format. The type is unknown and I need this value to be able to proceed with my entire method surrounding the small portion of the Javascript.

So can anyone point me into the direction where I can access the result variable / data as a var or anything else that will let me put it into a var (as a string).

Body: try alert(result.d);

ContentLicense: CC BY-SA 2.5


问:
Http Parser full exception in jetty 8 solr (v 4.5) server
I have a standalone solr(4.5) server which is running on top of jetty 8 .I have an application server on apache tomcat server which is a customer facing node.
Application server connects to standalone solr server to fetch the search result.I send POST request as the query to SOLR is huge but I get the below WARN message on jetty solr server:

```<code> WARN  org.eclipse.jetty.http.HttpParser  â HttpParser Full for server1:8983 <->server 2:99988
</code>```

On the tomcat application server I get the below error  message :

```<code>  SEVERE: Servlet.service() for servlet [DispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.apache.solr.common.SolrException: No live SolrServers available to handle this request] with root cause
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 | java.net.SocketException: Broken pipe
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at java.net.SocketOutputStream.socketWrite0(Native Method)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:113)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at java.net.SocketOutputStream.write(SocketOutputStream.java:159)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.io.AbstractSessionOutputBuffer.flushBuffer(AbstractSessionOutputBuffer.java:147)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.io.AbstractSessionOutputBuffer.writeLine(AbstractSessionOutputBuffer.java:246)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.io.HttpRequestWriter.writeHeadLine(HttpRequestWriter.java:56)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.io.HttpRequestWriter.writeHeadLine(HttpRequestWriter.java:44)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.io.AbstractMessageWriter.write(AbstractMessageWriter.java:90)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.AbstractHttpClientConnection.sendRequestHeader(AbstractHttpClientConnection.java:258)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.conn.DefaultClientConnection.sendRequestHeader(DefaultClientConnection.java:271)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.conn.ManagedClientConnectionImpl.sendRequestHeader(ManagedClientConnectionImpl.java:203)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.protocol.HttpRequestExecutor.doSendRequest(HttpRequestExecutor.java:221)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:715)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:520)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.solr.client.solrj.impl.HttpSolrServer.request(HttpSolrServer.java:395)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.solr.client.solrj.impl.HttpSolrServer.request(HttpSolrServer.java:199)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.403 |         at org.apache.solr.client.solrj.impl.LBHttpSolrServer.request(LBHttpSolrServer.java:467)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.403 |         at org.apache.solr.client.solrj.request.QueryRequest.process(QueryRequest.java:90)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.403 |         at org.apache.solr.client.solrj.SolrServer.query(SolrServer.java:301)
</code>```

I have tried increasing the "requestHeaderSize" , and "maxFormContentSize" in jetty.xml but no luck.

答:
First: Jetty 8 is EOL (End of Life), consider upgrading to something supported and stable.

The HttpParser Full is from excessively large request entities (which is the Request URI line and Request Headers).

If this error is from the server side, then its the Request headers.

See https://stackoverflow.com/a/16015332/775715 for advice on configuring it properly on the server side.  (Hint: its a Connector setting.  So if you have 2 connectors, you have 2 configurations to change)

maxFormContentSize is for the request body content on POST requests, and has no effect on request uri or request headers.  The HttpParser Full is not going to be triggered for excessive request body content, so ignore this aspect of the problem, focus on the request URI and request headers.

If this error is from the client side, then its the Response headers.

Pay attention to what's generating those request URI and request headers, as that's the culprit!  The default setting is specifically designed for maximum compatibility on the general internet, if you have to increase the default settings then you either have something seriously wrong with your request URI or request headers, or you are using the API improperly (such as sending documents via POST/GET uri strings, and not request body content)

Body:
I have a standalone solr(4.5) server which is running on top of jetty 8 .I have an application server on apache tomcat server which is a customer facing node.
Application server connects to standalone solr server to fetch the search result.I send POST request as the query to SOLR is huge but I get the below WARN message on jetty solr server:

 WARN  org.eclipse.jetty.http.HttpParser  â HttpParser Full for server1:8983 <->server 2:99988

On the tomcat application server I get the below error  message :

  SEVERE: Servlet.service() for servlet [DispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.apache.solr.common.SolrException: No live SolrServers available to handle this request] with root cause
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 | java.net.SocketException: Broken pipe
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at java.net.SocketOutputStream.socketWrite0(Native Method)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:113)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at java.net.SocketOutputStream.write(SocketOutputStream.java:159)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.io.AbstractSessionOutputBuffer.flushBuffer(AbstractSessionOutputBuffer.java:147)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.io.AbstractSessionOutputBuffer.writeLine(AbstractSessionOutputBuffer.java:246)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.io.HttpRequestWriter.writeHeadLine(HttpRequestWriter.java:56)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.io.HttpRequestWriter.writeHeadLine(HttpRequestWriter.java:44)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.io.AbstractMessageWriter.write(AbstractMessageWriter.java:90)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.AbstractHttpClientConnection.sendRequestHeader(AbstractHttpClientConnection.java:258)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.conn.DefaultClientConnection.sendRequestHeader(DefaultClientConnection.java:271)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.conn.ManagedClientConnectionImpl.sendRequestHeader(ManagedClientConnectionImpl.java:203)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.protocol.HttpRequestExecutor.doSendRequest(HttpRequestExecutor.java:221)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:715)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:520)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.solr.client.solrj.impl.HttpSolrServer.request(HttpSolrServer.java:395)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.402 |         at org.apache.solr.client.solrj.impl.HttpSolrServer.request(HttpSolrServer.java:199)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.403 |         at org.apache.solr.client.solrj.impl.LBHttpSolrServer.request(LBHttpSolrServer.java:467)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.403 |         at org.apache.solr.client.solrj.request.QueryRequest.process(QueryRequest.java:90)
INFO   | jvm 1    | main    | 2017/03/30 03:30:46.403 |         at org.apache.solr.client.solrj.SolrServer.query(SolrServer.java:301)

I have tried increasing the "requestHeaderSize" , and "maxFormContentSize" in jetty.xml but no luck.


问:
asp.net Table code behind
I started learning asp.net. I'm having problem to create a table in the code behind. I load data from my database and I want to display it in the table and also have a link to another page.

Here is my aspx code:

```<code><div class="container">
        <div class="row">
            <div class="col-lg-12">
                <h3>Search Books</h3>
            </div>
        </div>
        <div class="row">
            <div class="col-lg-4 col-lg-offset-4">
                <input type="search" id="search" value="" class="form-control" />
            </div>
        </div>
        <div class="row">
            <div class="col-lg-12">
                <table class="table" id="table">
                    <thead>
                        <tr>
                            <th>Author</th>
                            <th>Title</th>
                        </tr>
                    </thead>
                    <tbody>
                        <%=getWhileLoopData()%>
                    </tbody>
                </table>
                <hr />
            </div>
        </div>
    </div>
</code>```

My cs code:

```<code>public string getWhileLoopData()
{
    string htmlStr = "";
    var query = (from b in db.Books
                 where b.Available == true
                 orderby b.DataInserted descending
                 select b).Take(10);

    foreach (var row in query)
    {
        LinkButton btn = new LinkButton();
        btn.ID = "openBook" + row.Id;
        btn.CommandArgument = row.Id.ToString();
        btn.Command += Load_Book;
        btn.Text = "Open Book";
        htmlStr += "<tr><td>" + row.Author + "</td><td>" + row.Title + "</td><td>" + btn + "</td>";
    }

    return htmlStr;
}

private void Load_Book(object sender, CommandEventArgs e)
{
    Response.Redirect("Book.aspx?Id=" + e.CommandArgument);
}
</code>```

JavaScript to handle search option:

```<code>$(function () {
$('#table').searchable({
    striped: true,
    oddRow: { 'background-color': '#f5f5f5' },
    evenRow: { 'background-color': '#fff' },
    searchType: 'fuzzy'
});

$('#searchable-container').searchable({
    searchField: '#container-search',
    selector: '.row',
    childSelector: '.col-xs-4',
    show: function (elem) {
        elem.slideDown(100);
    },
    hide: function (elem) {
        elem.slideUp(100);
    }
})
</code>```

});

Almost everything works fine. But the Linkbutton only display a string "System.Web.UI.WebControls.LinkButton". Does anyone know what I am doing wrong? Is it the best way to implement?

Thanks

答:
We don't normally create html tags from code behind in ASP.Net Web Form; it could be very fragile and hard to maintain. Instead, we use data controls such as GridView, ListView.

For example,

```<code><asp:GridView runat="server" ID="BookGridView" AutoGenerateColumns="False"
    ItemType="DemoWebForm.Book">
    <Columns>
        <asp:BoundField DataField="Author" HeaderText="Author" />
        <asp:BoundField DataField="Title" HeaderText="Title" />

        <%-- Use HyperLinkField if you do not need to postback to server --%>
        <asp:HyperLinkField DataNavigateUrlFields="Id"
            DataNavigateUrlFormatString="Book.aspx?Id={0}"
            Text="Open Book" HeaderText="Redirect to New Page" />

        <asp:TemplateField HeaderText="Post Back and Redirect">
            <ItemTemplate>
                <asp:LinkButton runat="server" ID="OpenBookLinkButton" Text="Open Book"
                    OnCommand="Load_Book" CommandArgument="<%#: Item.Id %>">
                </asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
</code>```

Code Behind

```<code>namespace DemoWebForm
{
    public class Book
    {
        public int Id { get; set; }
        public string Author { get; set; }
        public string Title { get; set; }
    }

    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BookGridView.DataSource = new List<Book>
                {
                    new Book {Id = 1, Author = "One", Title = "One Hundred"},
                    new Book {Id = 2, Author = "Two", Title = "Two Hundreds"},
                    new Book {Id = 3, Author = "Three", Title = "Three Hundreds"},
                };
                BookGridView.DataBind();
            }
        }

        protected void Load_Book(object sender, CommandEventArgs e)
        {
            Response.Redirect("Book.aspx?Id=" + e.CommandArgument);
        }
    }
}
</code>```

Title: asp.net Table code behind

Body:
I started learning asp.net. I'm having problem to create a table in the code behind. I load data from my database and I want to display it in the table and also have a link to another page.

Here is my aspx code:

Search Books

                <input type="search" id="search" value="" class="form-control" />

                            Author
                            Title

                        <%=getWhileLoopData()%>

My cs code:

public string getWhileLoopData()
{
    string htmlStr = "";
    var query = (from b in db.Books
                 where b.Available == true
                 orderby b.DataInserted descending
                 select b).Take(10);

    foreach (var row in query)
    {
        LinkButton btn = new LinkButton();
        btn.ID = "openBook" + row.Id;
        btn.CommandArgument = row.Id.ToString();
        btn.Command += Load_Book;
        btn.Text = "Open Book";
        htmlStr += "
" + row.Author + "	" + row.Title + "	" + btn + "	";
    }

    return htmlStr;
}

private void Load_Book(object sender, CommandEventArgs e)
{
    Response.Redirect("Book.aspx?Id=" + e.CommandArgument);
}

JavaScript to handle search option:

$(function () {
$('#table').searchable({
    striped: true,
    oddRow: { 'background-color': '#f5f5f5' },
    evenRow: { 'background-color': '#fff' },
    searchType: 'fuzzy'
});

$('#searchable-container').searchable({
    searchField: '#container-search',
    selector: '.row',
    childSelector: '.col-xs-4',
    show: function (elem) {
        elem.slideDown(100);
    },
    hide: function (elem) {
        elem.slideUp(100);
    }
})

});

Almost everything works fine. But the Linkbutton only display a string "System.Web.UI.WebControls.LinkButton". Does anyone know what I am doing wrong? Is it the best way to implement?

Thanks

Body:
We don't normally create html tags from code behind in ASP.Net Web Form; it could be very fragile and hard to maintain. Instead, we use data controls such as GridView, ListView.

For example,

<asp:GridView runat="server" ID="BookGridView" AutoGenerateColumns="False"
    ItemType="DemoWebForm.Book">
    <Columns>
        <asp:BoundField DataField="Author" HeaderText="Author" />
        <asp:BoundField DataField="Title" HeaderText="Title" />

        <%-- Use HyperLinkField if you do not need to postback to server --%>
        <asp:HyperLinkField DataNavigateUrlFields="Id"
            DataNavigateUrlFormatString="Book.aspx?Id={0}"
            Text="Open Book" HeaderText="Redirect to New Page" />

        <asp:TemplateField HeaderText="Post Back and Redirect">
            <ItemTemplate>
                <asp:LinkButton runat="server" ID="OpenBookLinkButton" Text="Open Book"
                    OnCommand="Load_Book" CommandArgument="<%#: Item.Id %>">
                </asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Code Behind

namespace DemoWebForm
{
    public class Book
    {
        public int Id { get; set; }
        public string Author { get; set; }
        public string Title { get; set; }
    }

    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BookGridView.DataSource = new List<Book>
                {
                    new Book {Id = 1, Author = "One", Title = "One Hundred"},
                    new Book {Id = 2, Author = "Two", Title = "Two Hundreds"},
                    new Book {Id = 3, Author = "Three", Title = "Three Hundreds"},
                };
                BookGridView.DataBind();
            }
        }

        protected void Load_Book(object sender, CommandEventArgs e)
        {
            Response.Redirect("Book.aspx?Id=" + e.CommandArgument);
        }
    }
}


问:
Anova in Python using Scipy without manually typing in every group name
I have a df that looks like this

```<code>           Ens_prot_ID      Ens_gene_ID Sample     TPM      ppm   ppm/TPM
0      ENSP00000416240  ENSG00000109072  liver  2540.4    0.003  0.000001
21597  ENSP00000226218  ENSG00000109072  liver  2540.4  110.000  0.043300
...
</code>```

The code below isn't working and gives "KeyError: 0"

```<code>from scipy import stats
proteins=df['Ens_prot_ID'].unique()
stats.f_oneway([df[df['Ens_prot_ID'] == prot]['ppm/TPM'] for prot in proteins])
</code>```

I don't have any issue running

```<code>from scipy import stats
proteins=df['Ens_prot_ID'].unique()
for prot in proteins:
    df[df['Ens_prot_ID'] == prot]['ppm/TPM']
</code>```

So it's seems like the issue is f_oneway() not liking my form of input. Is there any way to get the function to accept group names that aren't typed in by hand?

答:
You can do it this way:

```<code>stats.f_oneway(*(df[df['Ens_prot_ID'] == prot]['ppm/TPM'] for prot in proteins))
</code>```

The * allows you to pass multiple arguments to a function: https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/

I also changed the list comprehension to a generator comprehension in case your DataFrame is very large.

Body:
I have a df that looks like this

           Ens_prot_ID      Ens_gene_ID Sample     TPM      ppm   ppm/TPM
0      ENSP00000416240  ENSG00000109072  liver  2540.4    0.003  0.000001
21597  ENSP00000226218  ENSG00000109072  liver  2540.4  110.000  0.043300
...

The code below isn't working and gives "KeyError: 0"

from scipy import stats
proteins=df['Ens_prot_ID'].unique()
stats.f_oneway([df[df['Ens_prot_ID'] == prot]['ppm/TPM'] for prot in proteins])

I don't have any issue running

from scipy import stats
proteins=df['Ens_prot_ID'].unique()
for prot in proteins:
    df[df['Ens_prot_ID'] == prot]['ppm/TPM']

So it's seems like the issue is f_oneway() not liking my form of input. Is there any way to get the function to accept group names that aren't typed in by hand?

Body:
You can do it this way:

stats.f_oneway(*(df[df['Ens_prot_ID'] == prot]['ppm/TPM'] for prot in proteins))

The * allows you to pass multiple arguments to a function: https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/

I also changed the list comprehension to a generator comprehension in case your DataFrame is very large.


答:
I recommend following all the comment sugestion but as for why your link button end up display: System.Web.UI.WebControls.LinkButton is because when concatening it with a string it's like invoking .ToString() on it and that return a string containing the object type. if you want to keep following your route you'll need to include actual html tag in your string to display your link button like

```<code><button></button>
</code>```

or

```<code><input type="button"></input>
</code>```

or event a simple link:

```<code><a href="#">click me</a>
</code>```

Title: asp.net Table code behind

Body:
I recommend following all the comment sugestion but as for why your link button end up display: System.Web.UI.WebControls.LinkButton is because when concatening it with a string it's like invoking .ToString() on it and that return a string containing the object type. if you want to keep following your route you'll need to include actual html tag in your string to display your link button like

<button></button>

or

<input type="button"></input>

or event a simple link:

<a href="#">click me</a>


问:
jQuery - Variable Scope Problem
I have the following javascript:

```<code>      $.getJSON('/calculate_quote/' + moulding_1_id, function(data) {
        moulding_1_cost = data.moulding.cost;
        moulding_1_width = data.moulding.width;
      });
      cost_of_moulding = ( ( 2 * ( width + ( 2 * moulding_1_width ) ) + 2 * ( height + ( 2 * moulding_1_width ) ) ) / 1000 ) * moulding_1_cost;
      $('#item_total').html( cost_of_moulding );
</code>```

The problem is that the two variables moulding_1_cost and moulding_1_width are undefined outside of the getJSON call.  How do I make these two variables available outside the getJSON call?

答:
add

```<code>var moulding_1_cost;
var moulding_1_width;
</code>```

outside of any javaScript function ;)

Title: jQuery - Variable Scope Problem

Body:
I have the following javascript:

      $.getJSON('/calculate_quote/' + moulding_1_id, function(data) {
        moulding_1_cost = data.moulding.cost;
        moulding_1_width = data.moulding.width;
      });
      cost_of_moulding = ( ( 2 * ( width + ( 2 * moulding_1_width ) ) + 2 * ( height + ( 2 * moulding_1_width ) ) ) / 1000 ) * moulding_1_cost;
      $('#item_total').html( cost_of_moulding );

The problem is that the two variables moulding_1_cost and moulding_1_width are undefined outside of the getJSON call.  How do I make these two variables available outside the getJSON call?

Body:
add

var moulding_1_cost;
var moulding_1_width;

outside of any javaScript function ;)


问:
How to convert a Windows CMD Forloop in PowerShell
I have the following code in command shell code.

```<code>SET MYdir=%NewPath%\%CUST%\SuppliesTypes
SET "MYsCount=1"
SET /p MYsCount="Number of MYs in project? (default: %MYSCount%): "
for /L %%a in (1,1,%MYsCount%) do (
    SET /p MYNums="Enter %%a MY Number: "
    call md "%MYdir%\MY_%%MYNums%%"
    )
SET "MYsCount="
</code>```

However, I am converting my code from CMD to PowerShell.  I do not fully understand the correct way to convert over.  Here might be how it should be done, but it's not working as it just jumps right through.

```<code>SET MYdir=%NewPath%\%CUST%\Product
SET "MYsCount=1"
SET /p MYsCount="Number of MYs in project? (default: %MYSCount%): "
For ($MYsCount = 1; $MYsCount -eq 10; $MYsCount++){
   SET /p MyNums="Enter %%a Product Numbers: "
   CALL MD "%MYdir%\%CUST%\Product_%%"
}
SET "$MYsCount="
</code>```

I've looked at the following sites and articles:

PowerShell Basics: Programming With Loops (Helped validate)

How to do a forloop in a Django template? (Didn't really help)

Windows PowerShell Cookbook, 3rd Edition  (Page 170)

I am running this code inside a While-Loop.

Thanks for your help!

答:
I believe the issue is coming from how you are declaring your variables. SET creates the variables as environment variables that powershell does not access natively. Below is how I would write up your section of code:

```<code>$MYDir = "$env:NewPath\$env:CUST\SuppliesTypes"
$MYsCount = 1
$MYsCount = read-host -prompt "Number of MYs in project? (default: $MYSCount): "
foreach ($a in 0..$MYsCount){
    $MYNums = Read-Host -Prompt "Enter $a Product Numbers: "
    New-Item -Path "$MYDir\MY_$MYNums" -ItemType Directory
}
$MYsCount = $null
</code>```

I used a foreach loop instead of a normal for loop because you were incrementing by one each time and I have noticed a small performance gain from using foreach when the step is not complicated. 0..$variable is a short hand for using each number from 0 to the declared variable.

If you did want to use a for loop as you mentioned then you could use:

```<code>For ($MYsCount = 1; $MYsCount -eq 10; $MYsCount++){
</code>```

as you had expected. This loop will only stop if the $MYsCount variable equals 10 though so if someone set the variable to something above 10 it would run indefinitely.

Body:
I have the following code in command shell code.

SET MYdir=%NewPath%\%CUST%\SuppliesTypes
SET "MYsCount=1"
SET /p MYsCount="Number of MYs in project? (default: %MYSCount%): "
for /L %%a in (1,1,%MYsCount%) do (
    SET /p MYNums="Enter %%a MY Number: "
    call md "%MYdir%\MY_%%MYNums%%"
    )
SET "MYsCount="

However, I am converting my code from CMD to PowerShell.  I do not fully understand the correct way to convert over.  Here might be how it should be done, but it's not working as it just jumps right through.

SET MYdir=%NewPath%\%CUST%\Product
SET "MYsCount=1"
SET /p MYsCount="Number of MYs in project? (default: %MYSCount%): "
For ($MYsCount = 1; $MYsCount -eq 10; $MYsCount++){
   SET /p MyNums="Enter %%a Product Numbers: "
   CALL MD "%MYdir%\%CUST%\Product_%%"
}
SET "$MYsCount="

I've looked at the following sites and articles:

PowerShell Basics: Programming With Loops (Helped validate)

How to do a forloop in a Django template? (Didn't really help)

Windows PowerShell Cookbook, 3rd Edition  (Page 170)

I am running this code inside a While-Loop.

Thanks for your help!

Body:
I believe the issue is coming from how you are declaring your variables. SET creates the variables as environment variables that powershell does not access natively. Below is how I would write up your section of code:

$MYDir = "$env:NewPath\$env:CUST\SuppliesTypes"
$MYsCount = 1
$MYsCount = read-host -prompt "Number of MYs in project? (default: $MYSCount): "
foreach ($a in 0..$MYsCount){
    $MYNums = Read-Host -Prompt "Enter $a Product Numbers: "
    New-Item -Path "$MYDir\MY_$MYNums" -ItemType Directory
}
$MYsCount = $null

I used a foreach loop instead of a normal for loop because you were incrementing by one each time and I have noticed a small performance gain from using foreach when the step is not complicated. 0..$variable is a short hand for using each number from 0 to the declared variable.

If you did want to use a for loop as you mentioned then you could use:

For ($MYsCount = 1; $MYsCount -eq 10; $MYsCount++){

as you had expected. This loop will only stop if the $MYsCount variable equals 10 though so if someone set the variable to something above 10 it would run indefinitely.


答:
You have an interesting amalgam of batch file and powershell there in your second code block. It is hard to read when some things are one language and some things are another. Let's see if we can't get it all into PowerShell here.</p>

```<code>$MYdir = "$NewPath\$CUST\Product"
$MYsCount = 1
$UserMYsCount = Read-Host "Number of MYs in project? (default: $MYSCount): "
If([string]::IsNullOrEmpty($UserMYsCount){
    $UserMYsCount = $MYsCount
}
For ($i = 1; $i -le $UserMYsCount; $I++){
   $MyNums = Read-Host "Enter $i Product Numbers: "
   New-Item -Path "$MYdir\MY_$MyNums" -ItemType Directory
}
</code>```

Title: How to convert a Windows CMD Forloop in PowerShell

Body:
You have an interesting amalgam of batch file and powershell there in your second code block. It is hard to read when some things are one language and some things are another. Let's see if we can't get it all into PowerShell here.

$MYdir = "$NewPath\$CUST\Product"
$MYsCount = 1
$UserMYsCount = Read-Host "Number of MYs in project? (default: $MYSCount): "
If([string]::IsNullOrEmpty($UserMYsCount){
    $UserMYsCount = $MYsCount
}
For ($i = 1; $i -le $UserMYsCount; $I++){
   $MyNums = Read-Host "Enter $i Product Numbers: "
   New-Item -Path "$MYdir\MY_$MyNums" -ItemType Directory
}


问:
saving ArrayList in the bundle savedInstanceState
the ArrayList is defined on class level.
these are my savedInstance methods:

```<code>@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putStringArrayList("savedList", list);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    list=savedInstanceState.getStringArrayList("savedList");
}
</code>```

but still, when i change orientation the ArrayList is blank

答:
try to use

```<code>list.addAll(savedInstanceState.getStringArrayList("savedList"));
</code>```

instead

```<code>list=savedInstanceState.getStringArrayList("savedList");
</code>```

Body:
the ArrayList is defined on class level.
these are my savedInstance methods:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putStringArrayList("savedList", list);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    list=savedInstanceState.getStringArrayList("savedList");
}

but still, when i change orientation the ArrayList is blank

Body:
try to use

list.addAll(savedInstanceState.getStringArrayList("savedList"));

instead

list=savedInstanceState.getStringArrayList("savedList");


问:
Can webpack report which file triggered a compilation in watch mode?
I would like for Webpack to log which file triggered my watch mode build.

I have configured a plugin that listens to the watch-run compiler event hook like this:

```<code>function() {
  this.plugin("watch-run", function(watching, callback) {
    // maybe something in `watching` will indicate the changed file?
    // when I find out what it is, `console.log` it here
    callback();
  });
}

// Example output: "/Users/aaron/git/test/index.js" was changed, new build triggered
</code>```

But I cannot figure out where the changed file information might be, if it is there at all.

The Webpack documentation is really lacking in this area. The Compiler Event Hook page doesn't have any examples (only a message to explain that examples are coming soon), and the old v1 documentation is not much better at elaborating the properties/methods available in the watching/compiler object.

Any help or guidance would be greatly appreciated.

答:
This kind of information is not covered by the webpack documentation and it would be difficult to include every possible option that is available on the compiler. But I would say that this is an area where you should explore the available options by either reading the source code or spinning up a debugger and investigate them. I did the latter and found that the changed files are available in:

```<code>watching.compiler.watchFileSystem.watcher.mtimes
</code>```

This is an object where each key is an absolute path to a file that has been changed and the value is the timestamp when it has been changed. It is possible to have more than one file change that triggers the recompilation, when multiple changes have been saved within the configured poll interval.

The following code prints the files that have been changed (the files might also be empty):

```<code>this.plugin("watch-run", (watching, done) => {
  const changedTimes = watching.compiler.watchFileSystem.watcher.mtimes;
  const changedFiles = Object.keys(changedTimes)
    .map(file => `\n  ${file}`)
    .join("");
  if (changedFiles.length) {
    console.log("New build triggered, files changed:", changedFiles);
  }
  done();
});
</code>```

An example output of this is:

```<code>New build triggered, files changed:
  /path/to/app/src/components/item/Item.js
  /path/to/app/src/App.js
</code>```

Note: This output will come before the final stats are printed.

Body:
I would like for Webpack to log which file triggered my watch mode build.

I have configured a plugin that listens to the watch-run compiler event hook like this:

function() {
  this.plugin("watch-run", function(watching, callback) {
    // maybe something in `watching` will indicate the changed file?
    // when I find out what it is, `console.log` it here
    callback();
  });
}

// Example output: "/Users/aaron/git/test/index.js" was changed, new build triggered

But I cannot figure out where the changed file information might be, if it is there at all.

The Webpack documentation is really lacking in this area. The Compiler Event Hook page doesn't have any examples (only a message to explain that examples are coming soon), and the old v1 documentation is not much better at elaborating the properties/methods available in the watching/compiler object.

Any help or guidance would be greatly appreciated.

Body:
This kind of information is not covered by the webpack documentation and it would be difficult to include every possible option that is available on the compiler. But I would say that this is an area where you should explore the available options by either reading the source code or spinning up a debugger and investigate them. I did the latter and found that the changed files are available in:

watching.compiler.watchFileSystem.watcher.mtimes

This is an object where each key is an absolute path to a file that has been changed and the value is the timestamp when it has been changed. It is possible to have more than one file change that triggers the recompilation, when multiple changes have been saved within the configured poll interval.

The following code prints the files that have been changed (the files might also be empty):

this.plugin("watch-run", (watching, done) => {
  const changedTimes = watching.compiler.watchFileSystem.watcher.mtimes;
  const changedFiles = Object.keys(changedTimes)
    .map(file => `\n  ${file}`)
    .join("");
  if (changedFiles.length) {
    console.log("New build triggered, files changed:", changedFiles);
  }
  done();
});

An example output of this is:

New build triggered, files changed:
  /path/to/app/src/components/item/Item.js
  /path/to/app/src/App.js

Note: This output will come before the final stats are printed.


问:
Akamai request from Server unless ddos attack detected
Im looking for some help and no Akamai expert. Basically Im wondering if it is possible to implement Akamai in the following scenario:
1. Normal running request passes through akamai and only static assets such as css and js are cached, everything else is served direct from the server.
2. DDOS attack detected: Not sure if this is possible but the idea would be if akamai has a feature or api call to check if there has been a large scale ddos attack started, if so instead of passing the request to the app servers it reverts to a fully cached version of the site until the attack finishes.
Icing on the cake would be if we could set the threshold to what levels of attack to revert to, maybe based on a percentage over expected traffic levels?

Appreciate any sort of guidance.

答:
Yes you can do this, either from Akamai config or by sending relevant headers from the origin (your site/API) telling Akamai not to cache certain files. Bear in mind that you'll still pay for traffic flowing through Akamai, even if they're not caching it, although if you have global users that want good performance you won't mind that cause the performance through their network is awesome.

They do indeed have a product that will protect you from ddos, how configurable it is I'm not sure but basically with Akamai everything is configurable if you've got the money to spend with them! Having said that, they wouldn't be serving anything to ddos requests of course, they'd be trying to determine where the attack is coming from and ignoring those requests so not sure what you're suggesting is what you'd actually want.


问:
Submitting html form using PHP to display "Thank You" message in same div
I am trying to create a simple forum using php to email the contents. Once the user clicks submit, I would like to have the div display a thank you message.

Currently going about this by trying to have the php write the html code using an if else statement. It seems the if statement is working, but the else statement is showing up as text.

Here is my code:

```<code><?php
if(isset($_POST['submit'])) {
        echo "<form method="post" action="">
        <div class="field half first">
        <label for="name">Name</label>
        <input type="text" name="name" id="name" />
        </div>
        <div class="field half">
        <label for="email">Email</label>
        <input type="text" name="email" id="email" />
        </div>
        <div class="field">
        <label for="message">Message</label>
        <textarea name="message" id="message" rows="5"></textarea>
        </div>
        <input class="button submit" type="submit" name="submit" value="Submit">
        </form>";

} else {
    $email_to = "field25farming@gmail.com";
    $email_subject = "Field 25 Contact Form";
    echo "Thanks! We'll get back to you soon.";
}
?>
</code>```

You can see the problem in the bottom of the page here if you'd like: http://field25.com/

I'm also open to other ways of achieving this, thanks for you help.

答:
Surprised that's rendering anything at all! There are a couple of problems. First, you have nested double quotes. Second, you're checking for the existence of the submit and if it exists, rendering the form. If it has to exist first, it'll never be rendered.

You can avoid the first problem entirely by simply dipping out of PHP. The second problem can be fixed by checking if submit does not exist via the ! operator (or flipping the if/else output).

```<code><?php
// if submit is not set, we want to render the form.
if( !isset($_POST['submit']) ) { ?>

<!-- leave PHPlandia -->

<form method="post" action="">
  <div class="field half first">
    <label for="name">Name</label>
    <input type="text" name="name" id="name" />
  </div>
  <div class="field half">
    <label for="email">Email</label>
    <input type="text" name="email" id="email" />
  </div>
  <div class="field">
    <label for="message">Message</label>
    <textarea name="message" id="message" rows="5"></textarea>
  </div>
  <input class="button submit" type="submit" name="submit" value="Submit">
  </form>
<?php
} else {
    $email_to = "field25farming@gmail.com";
    $email_subject = "Field 25 Contact Form";

    // ... rest of your email sending code here ...

    echo "Thanks! We'll get back to you soon.";
}

?>
</code>```

Body:
I am trying to create a simple forum using php to email the contents. Once the user clicks submit, I would like to have the div display a thank you message.

Currently going about this by trying to have the php write the html code using an if else statement. It seems the if statement is working, but the else statement is showing up as text.

Here is my code:

<?php
if(isset($_POST['submit'])) {
        echo "<form method="post" action="">

        Name
        <input type="text" name="name" id="name" />

        Email
        <input type="text" name="email" id="email" />

        Message
        <textarea name="message" id="message" rows="5"></textarea>

        <input class="button submit" type="submit" name="submit" value="Submit">
        </form>";

} else {
    $email_to = "field25farming@gmail.com";
    $email_subject = "Field 25 Contact Form";
    echo "Thanks! We'll get back to you soon.";
}
?>

You can see the problem in the bottom of the page here if you'd like: http://field25.com/

I'm also open to other ways of achieving this, thanks for you help.

Body:
Surprised that's rendering anything at all! There are a couple of problems. First, you have nested double quotes. Second, you're checking for the existence of the submit and if it exists, rendering the form. If it has to exist first, it'll never be rendered.

You can avoid the first problem entirely by simply dipping out of PHP. The second problem can be fixed by checking if submit does not exist via the ! operator (or flipping the if/else output).

<?php
// if submit is not set, we want to render the form.
if( !isset($_POST['submit']) ) { ?>

<!-- leave PHPlandia -->

<form method="post" action="">
  <div class="field half first">
    <label for="name">Name</label>
    <input type="text" name="name" id="name" />
  </div>
  <div class="field half">
    <label for="email">Email</label>
    <input type="text" name="email" id="email" />
  </div>
  <div class="field">
    <label for="message">Message</label>
    <textarea name="message" id="message" rows="5"></textarea>
  </div>
  <input class="button submit" type="submit" name="submit" value="Submit">
  </form>
<?php
} else {
    $email_to = "field25farming@gmail.com";
    $email_subject = "Field 25 Contact Form";

    // ... rest of your email sending code here ...

    echo "Thanks! We'll get back to you soon.";
}

?>


答:
Try this:

```<code>array = array[0..-3]
</code>```

This tells Ruby to take the slice of the array from index 0 (the first element) to index -3 (the third from last element), omitting the last two elements.

Alternately, you can also modify the array in place using Array#slice!:

```<code>array.slice!(-2, 2)
</code>```

Title: Removing the last 2 elements in an array - Ruby

Body: If I have this array - [49, 33, 8, 45, 20, 6, 34, 50, 31, 36, 28, 42, 35, 32, 7, 2, 9, 1, 18, 21] how can I get this return - [49, 33, 8, 45, 20, 6, 34, 50, 31, 36, 28, 42, 35, 32, 7, 2, 9, 1] I've tried this and it doesn't work. array.size - 2..

Body:
Try this:

array = array[0..-3]

This tells Ruby to take the slice of the array from index 0 (the first element) to index -3 (the third from last element), omitting the last two elements.

Alternately, you can also modify the array in place using Array#slice!:

array.slice!(-2, 2)


问:
wait() and Thread.sleep() Dont work
Im trying to make picture move across a canvas.

```<code>import java.awt.*; class GraphicsProgram extends Canvas{

static int up = 0;

    public GraphicsProgram(){
        setSize(700, 700);
        setBackground(Color.white);
    }

    public static void main(String[] argS){

         //GraphicsProgram class is now a type of canvas
          //since it extends the Canvas class
          //lets instantiate it
         GraphicsProgram GP = new GraphicsProgram();
        //create a new frame to which we will add a canvas
        Frame aFrame = new Frame();
        aFrame.setSize(700, 700);

        //add the canvas
        aFrame.add(GP);

        aFrame.setVisible(true);

    }

    public void paint(Graphics g){

        Image img1 = Toolkit.getDefaultToolkit().getImage("Code.jpg");
        g.drawImage(img1, up, up, this);         }

public void  Move() {   up = up + 1;    Move();

    Thread.sleep(2000);
      }

}
</code>```

The console then returns

GraphicsProgram.java:43: error: unreported exception
  InterruptedException; must be caught or declared to be thrown
      Thread.sleep(2000);
                  ^ 1 error

I really can not understand why my Thread.sleep() is not working as I have searched it up and this is exactly what they put.

答:
InterruptedException is a checked Exception and you have to catch it as shown below:

```<code>try {
    Thread.sleep(2000);
} catch (InterruptedException e) {
    e.printStackTrace();
}
</code>```

But, as @Hovercraft highlighted, calling sleep in the painting method is not a good practice.

Title: wait() and Thread.sleep() Dont work

Body:
Im trying to make picture move across a canvas.

import java.awt.*; class GraphicsProgram extends Canvas{

static int up = 0;

    public GraphicsProgram(){
        setSize(700, 700);
        setBackground(Color.white);
    }

    public static void main(String[] argS){

         //GraphicsProgram class is now a type of canvas
          //since it extends the Canvas class
          //lets instantiate it
         GraphicsProgram GP = new GraphicsProgram();
        //create a new frame to which we will add a canvas
        Frame aFrame = new Frame();
        aFrame.setSize(700, 700);

        //add the canvas
        aFrame.add(GP);

        aFrame.setVisible(true);

    }

    public void paint(Graphics g){

        Image img1 = Toolkit.getDefaultToolkit().getImage("Code.jpg");
        g.drawImage(img1, up, up, this);         }

public void  Move() {   up = up + 1;    Move();

    Thread.sleep(2000);
      }

}

The console then returns

GraphicsProgram.java:43: error: unreported exception
  InterruptedException; must be caught or declared to be thrown
      Thread.sleep(2000);
                  ^ 1 error

I really can not understand why my Thread.sleep() is not working as I have searched it up and this is exactly what they put.

Body:
InterruptedException is a checked Exception and you have to catch it as shown below:

try {
    Thread.sleep(2000);
} catch (InterruptedException e) {
    e.printStackTrace();
}

But, as @Hovercraft highlighted, calling sleep in the painting method is not a good practice.


问:
How best to programmatically tell whether a TLabel's Caption is clipped (i.e. drawn using ellipsis)?
I have a TLabel with EllipsisPosition set to epEndEllipsis and I need to be able to tell whether the text is currently clipped or not. Besides calculating the area required to display the text myself and comparing it with the actual dimensions of the label, has anyone come up with an easier/more elegant way of doing this?

Actually, calculating the required area in a fail-safe manner also doesn't appear to be as straight forward as it sounds... For instance TCanvas.GetTextHeight does not take into account linebreaks.

TCustomLabel.DoDrawText internally uses either DrawTextW or DrawThemeTextExwith the DT_CALCRECT flag to determine whether it should use the ellipsis or not. There's quite a lot of code involved there, all of which is declared private. Simply duplicating all that code would not exactly qualify as "elegant" in my book...

Any ideas?

(I'm using Delphi 2010 in case anyone comes up with a Delphi-version-specific solution)

Update 1: I now figured out that I can simply call TCustomLabel.DoDrawText(lRect, DT_CALCRECT) directly (which is merely declared protected) to let the label perform the required size calculation without having to duplicate its code. I just have to make sure to either temporarily set EllipsisPosition to epNone or use a temporary label instance altogether. This is actually not that bad and I might just go with it if noone can think of an even simpler solution.

Update 2: I have now added my solution as a separate answer. It turned out to be rather more straight-forward than I anticipated so there probably is no easier/better way to do it but I'll leave this question open for a little while longer anyway just in case.

答:
FWIW, here's what I came up with (this is a method of a custom TLabel-descendant):

```<code>function TMyLabel.IsTextClipped: Boolean;
const
  EllipsisStr = '...';
var
  lEllipBup: TEllipsisPosition;
  lRect: TRect;
begin
  lRect := ClientRect;
  Dec(lRect.Right, Canvas.TextWidth(EllipsisStr));

  lEllipBup := EllipsisPosition;
  EllipsisPosition := epNone;
  try
    DoDrawText(lRect, DT_CALCRECT or IfThen(WordWrap, DT_WORDBREAK));
  finally
    EllipsisPosition := lEllipBup;
  end;
  Result := ((lRect.Right - lRect.Left) > ClientWidth)
         or ((lRect.Bottom - lRect.Top) > ClientHeight);
end;
</code>```

As this now uses exactly the same logic as TCustomLabel.DoDrawText (especially the artificial padding and the correct WordWrap setting) it also deals correctly with multi-line and word-wrapped input texts. Note that "correctly" in this case means "it always returns True when the TLabel is drawn with a clipped caption and False otherwise".

While the above code does what I originally asked for I will probably not use it this way - but this is more due to shortcomings of TLabel itself: Especially with multi-line text it often does not behave the way I would have wanted it to, e.g. when there is not enough space for multiple lines, the last word of the first line will always be truncated even if that entire line plus the ellipsis would have fitted.

Body:
FWIW, here's what I came up with (this is a method of a custom TLabel-descendant):

function TMyLabel.IsTextClipped: Boolean;
const
  EllipsisStr = '...';
var
  lEllipBup: TEllipsisPosition;
  lRect: TRect;
begin
  lRect := ClientRect;
  Dec(lRect.Right, Canvas.TextWidth(EllipsisStr));

  lEllipBup := EllipsisPosition;
  EllipsisPosition := epNone;
  try
    DoDrawText(lRect, DT_CALCRECT or IfThen(WordWrap, DT_WORDBREAK));
  finally
    EllipsisPosition := lEllipBup;
  end;
  Result := ((lRect.Right - lRect.Left) > ClientWidth)
         or ((lRect.Bottom - lRect.Top) > ClientHeight);
end;

As this now uses exactly the same logic as TCustomLabel.DoDrawText (especially the artificial padding and the correct WordWrap setting) it also deals correctly with multi-line and word-wrapped input texts. Note that "correctly" in this case means "it always returns True when the TLabel is drawn with a clipped caption and False otherwise".

While the above code does what I originally asked for I will probably not use it this way - but this is more due to shortcomings of TLabel itself: Especially with multi-line text it often does not behave the way I would have wanted it to, e.g. when there is not enough space for multiple lines, the last word of the first line will always be truncated even if that entire line plus the ellipsis would have fitted.


问:
Get USB port of plugged in device in node
I'm using node-detection to be notify when a USB device was plugged in. However I can't seem to find out how to know to which port was it plugged in to, e.g. sdb1, sdc1, etc. Is there a simple way of doing it?

答:
I think it's not working with node-detection

Maybe not the best way, but this worked for me:

```<code>var shell = require('shelljs');
var watch = require('node-watch');
var tmpUsb;

Array.prototype.contains = function(needle){
  for (var i=0; i<this.length; i++)
    if (this[i] == needle) return true;

  return false;
}

Array.prototype.diff = function(compare) {
    return this.filter(function(elem) {return !compare.contains(elem);})
}

getUsb = function() {
      this.usbJson = JSON.parse(shell.exec('lsblk --json', {silent:true}).stdout);
      var dev = this.usbJson.blockdevices;
      var devices = [];
      dev.forEach(function(entry) {
          entry.children.forEach(function(e) {
              devices.push(e.mountpoint);
          });
      });
      return devices;
}

tmpUsb = getUsb();

watch('/dev/disk/by-id', { recursive: true }, function(evt, name) {
    var curr = getUsb();
    var add = curr.diff(tmpUsb);
    var rem = tmpUsb.diff(curr);
    if(add.length > 0) {
      console.log("ADD > " + add);
    }
    if(rem.length > 0) {
      console.log("REM > " + rem);
    }
    tmpUsb = curr;
});
</code>```

Please add in your question what your output is. What code did you try....

Body:
I think it's not working with node-detection

Maybe not the best way, but this worked for me:

var shell = require('shelljs');
var watch = require('node-watch');
var tmpUsb;

Array.prototype.contains = function(needle){
  for (var i=0; i<this.length; i++)
    if (this[i] == needle) return true;

  return false;
}

Array.prototype.diff = function(compare) {
    return this.filter(function(elem) {return !compare.contains(elem);})
}

getUsb = function() {
      this.usbJson = JSON.parse(shell.exec('lsblk --json', {silent:true}).stdout);
      var dev = this.usbJson.blockdevices;
      var devices = [];
      dev.forEach(function(entry) {
          entry.children.forEach(function(e) {
              devices.push(e.mountpoint);
          });
      });
      return devices;
}

tmpUsb = getUsb();

watch('/dev/disk/by-id', { recursive: true }, function(evt, name) {
    var curr = getUsb();
    var add = curr.diff(tmpUsb);
    var rem = tmpUsb.diff(curr);
    if(add.length > 0) {
      console.log("ADD > " + add);
    }
    if(rem.length > 0) {
      console.log("REM > " + rem);
    }
    tmpUsb = curr;
});

Please add in your question what your output is. What code did you try....


问:
Automatic Slideshow Not Working JavaScript
I am currently trying to understand how to create a slideshow in JavaScript from W3Schools. The Manual slideshow worked perfectly but the automatic slideshow is not working in any way.

HTML:

```<code><!DOCTYPE html>

<html>

<head>
    <link rel="stylesheet" href="styles.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="scripts.js"></script>
</head>

<body>

    <div id="main_adverts">
        <img class="slide" src="images/imgslider1.jpg"/>
        <img class="slide" src="images/imgslider2.jpg"/>
        <img class="slide" src="images/imgslider3.jpg"/>
    </div>
</body>
<html>
</code>```

JavaScript:

```<code>var myIndex = 0;
carousel();

function carousel() {
    var i;
    var x = document.getElementsByClassName("slide");
    for (i = 0; i < x.length; i++) {
       x[i].style.display = "none";
    }
    myIndex++;
    if (myIndex > x.length) {myIndex = 1}
    x[myIndex-1].style.display = "block";
    setTimeout(carousel, 2000); // Change image every 2 seconds
}
</code>```

CSS:

```<code>#main_adverts{
    width: 70%;
    height: 70%;
    position: absolute;
    top: 20%;
    left: 15%;
    border: 1px solid black;
}

#main_adverts img{
    width: 100%;
    height: 100%;
    position: absolute;
}
</code>```

答:
For anyone who may come across this in the future. The safest way to solve this issue is to wrap your code like the following:

```<code>window.onload = function(){
    //Your code here
}
</code>```

By doing so, regardless of where you place your JavaScript in the HTML file, it will wait to execute until the page has fully loaded.

Body:
I am currently trying to understand how to create a slideshow in JavaScript from W3Schools. The Manual slideshow worked perfectly but the automatic slideshow is not working in any way.

HTML:

<!DOCTYPE html>

    <link rel="stylesheet" href="styles.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

JavaScript:

var myIndex = 0;
carousel();

function carousel() {
    var i;
    var x = document.getElementsByClassName("slide");
    for (i = 0; i < x.length; i++) {
       x[i].style.display = "none";
    }
    myIndex++;
    if (myIndex > x.length) {myIndex = 1}
    x[myIndex-1].style.display = "block";
    setTimeout(carousel, 2000); // Change image every 2 seconds
}

CSS:

#main_adverts{
    width: 70%;
    height: 70%;
    position: absolute;
    top: 20%;
    left: 15%;
    border: 1px solid black;
}

#main_adverts img{
    width: 100%;
    height: 100%;
    position: absolute;
}

Body:
For anyone who may come across this in the future. The safest way to solve this issue is to wrap your code like the following:

window.onload = function(){
    //Your code here
}

By doing so, regardless of where you place your JavaScript in the HTML file, it will wait to execute until the page has fully loaded.


问:
Compile time configuration using if-statements
In the embedded C world, we frequently store configuration details in headers so that a library can be built for a specific task, minimizing overhead and compiled size.

One example would be:

```<code>//libnameConf.h
#define LIBNAME_WAVE LIBNAME_A

typedef enum {
  LIBNAME_A,
  LIBNAME_B,
  LIBNAME_C
} libname_wave_t;
</code>```

```<code>//libname.c
double coef_arr_a[100] = {...};
double coef_arr_b[100] = {...};
double coef_arr_c[100] = {...};

if (LIBNAME_WAVE == LIBNAME_A) {
  somestruct.waveCoefs = coef_arr_a;
  //do other coef_arr_a specific stuff
} else if (LIBNAME_WAVE == LIBNAME_B) {...}
</code>```

For this particular case we're using an if-statement that the compiler will obviously collapse which is a good thing because we only want a reference to coef_arr_a so that the others won't be compiled into the binary and take up space.

Unfortunately, this yields the warning

```<code>warning: comparison between 'enum <anonymous>' and 'enum <anonymous>' [-Wenum-compare]
</code>```

Is there a better way that avoids this warning?

答: Sounds like you need conditional compilaiton in C but the way you're doing it is not correct. Conditional compilation is a concept of the preprocessor which is run before the compiler. The point of preprocessor is to manipulate the source code before it is fed to the compiler. Since you haven't used any preprocessor conditionals, all the source code is fed to the compiler regardless of your compile-time conditionals. You should definitely use preprocessor conditionals to reduce your binary.</p>

Body:
In the embedded C world, we frequently store configuration details in headers so that a library can be built for a specific task, minimizing overhead and compiled size.

One example would be:

//libnameConf.h
#define LIBNAME_WAVE LIBNAME_A

typedef enum {
  LIBNAME_A,
  LIBNAME_B,
  LIBNAME_C
} libname_wave_t;

//libname.c
double coef_arr_a[100] = {...};
double coef_arr_b[100] = {...};
double coef_arr_c[100] = {...};

if (LIBNAME_WAVE == LIBNAME_A) {
  somestruct.waveCoefs = coef_arr_a;
  //do other coef_arr_a specific stuff
} else if (LIBNAME_WAVE == LIBNAME_B) {...}

For this particular case we're using an if-statement that the compiler will obviously collapse which is a good thing because we only want a reference to coef_arr_a so that the others won't be compiled into the binary and take up space.

Unfortunately, this yields the warning

warning: comparison between 'enum <anonymous>' and 'enum <anonymous>' [-Wenum-compare]

Is there a better way that avoids this warning?


问:
StaleObjectStateException ERROR
Anyone can point me to the error please?

Note: this is a simplified test case extracted from my real app.
Thus the weird usage of 3 entity managers and
em1.getTransaction().begin();
em1.clear();
em1.close();
at the end of each section.
In real app it happens in different times.
HibernateUtil is basically copied from the tutorial.

```<code>        HibernateUtil.open();

        EntityManager em1 = HibernateUtil.reserveEntityManager();
        em1.getTransaction().begin();
        StringType st1 = new StringType();
        st1.setName("a");
        em1.persist(st1);
        em1.getTransaction().commit();
        em1.getTransaction().begin();
        em1.clear();
        em1.close();

        EntityManager em2 = HibernateUtil.reserveEntityManager();
        em2.getTransaction().begin();
        StringType st2 = new StringType();
        st2.setName("a");
        st2.setId(st1.getId());
        em2.merge(st2);
        em2.getTransaction().commit();
        em2.getTransaction().begin();
        em2.clear();
        em2.close();

        EntityManager em3 = HibernateUtil.reserveEntityManager();
        em3.getTransaction().begin();
        StringType st3 = new StringType();
        st3.setName("a");
        st3.setId(st1.getId());
        [b]em3.merge(st3);[/b]
        em3.getTransaction().commit();
        em3.getTransaction().begin();
        em3.clear();
        em3.close();

public static EntityManager reserveEntityManager()
    {
        return emf.createEntityManager();
    }

public static void open()
    {
        try
        {
            emf = Persistence.createEntityManagerFactory("manager1");
        }
        catch (Throwable e)
        {
            throw new ExceptionInInitializerError(e);
        }
    }
</code>```

javax.persistence.OptimisticLockException: org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [WebOrganizer.classes.types.StringType#174]
   at org.hibernate.ejb.AbstractEntityManagerImpl.wrapStaleStateException(AbstractEntityManagerImpl.java:646)
   at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:600)
   at org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:237)
   at WebOrganizer.web.servlets.TypeServlet.test2(TypeServlet.java:356)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
   at java.lang.reflect.Method.invoke(Method.java:597)
   at org.testng.internal.MethodHelper.invokeMethod(MethodHelper.java:580)
   at org.testng.internal.Invoker.invokeMethod(Invoker.java:517)
   at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:669)
   at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:956)
   at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:126)
   at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:110)
   at org.testng.TestRunner.runWorkers(TestRunner.java:720)
   at org.testng.TestRunner.privateRun(TestRunner.java:590)
   at org.testng.TestRunner.run(TestRunner.java:484)
   at org.testng.SuiteRunner.runTest(SuiteRunner.java:332)
   at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:327)
   at org.testng.SuiteRunner.privateRun(SuiteRunner.java:299)
   at org.testng.SuiteRunner.run(SuiteRunner.java:204)
   at org.testng.TestNG.createAndRunSuiteRunners(TestNG.java:864)
   at org.testng.TestNG.runSuitesLocally(TestNG.java:830)
   at org.testng.TestNG.run(TestNG.java:748)
   at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:73)
   at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:124)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
   at java.lang.reflect.Method.invoke(Method.java:597)
   at com.intellij.rt.execution.application.AppMain.main(AppMain.java:90)

Caused by: org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [WebOrganizer.classes.types.StringType#174]
   at org.hibernate.event.def.DefaultMergeEventListener.entityIsDetached(DefaultMergeEventListener.java:261)
   at org.hibernate.event.def.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:120)
   at org.hibernate.event.def.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:53)
   at org.hibernate.impl.SessionImpl.fireMerge(SessionImpl.java:677)
   at org.hibernate.impl.SessionImpl.merge(SessionImpl.java:661)
   at org.hibernate.impl.SessionImpl.merge(SessionImpl.java:665)
   at org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:228)
   ... 28 more

答:
I'd give something like this a try:

```<code>EntityTransaction tx1 = em1.getTransaction();
// make your modifications
em1.merge(st1);
tx1.commit();
</code>```

Not sure why you have are beginning a transaction right before you clean up the EntityManager.  I don't work with JPA transactions programmatically so this is just an educated guess.  Also, why are you creating a new EntityManager every time if it's returning the same instance?

OwnerDisplayName: michael

Title: StaleObjectStateException ERROR

Body:
Anyone can point me to the error please?

Note: this is a simplified test case extracted from my real app.
Thus the weird usage of 3 entity managers and
em1.getTransaction().begin();
em1.clear();
em1.close();
at the end of each section.
In real app it happens in different times.
HibernateUtil is basically copied from the tutorial.

        HibernateUtil.open();

        EntityManager em1 = HibernateUtil.reserveEntityManager();
        em1.getTransaction().begin();
        StringType st1 = new StringType();
        st1.setName("a");
        em1.persist(st1);
        em1.getTransaction().commit();
        em1.getTransaction().begin();
        em1.clear();
        em1.close();

        EntityManager em2 = HibernateUtil.reserveEntityManager();
        em2.getTransaction().begin();
        StringType st2 = new StringType();
        st2.setName("a");
        st2.setId(st1.getId());
        em2.merge(st2);
        em2.getTransaction().commit();
        em2.getTransaction().begin();
        em2.clear();
        em2.close();

        EntityManager em3 = HibernateUtil.reserveEntityManager();
        em3.getTransaction().begin();
        StringType st3 = new StringType();
        st3.setName("a");
        st3.setId(st1.getId());
        [b]em3.merge(st3);[/b]
        em3.getTransaction().commit();
        em3.getTransaction().begin();
        em3.clear();
        em3.close();

public static EntityManager reserveEntityManager()
    {
        return emf.createEntityManager();
    }

public static void open()
    {
        try
        {
            emf = Persistence.createEntityManagerFactory("manager1");
        }
        catch (Throwable e)
        {
            throw new ExceptionInInitializerError(e);
        }
    }

javax.persistence.OptimisticLockException: org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [WebOrganizer.classes.types.StringType#174]
   at org.hibernate.ejb.AbstractEntityManagerImpl.wrapStaleStateException(AbstractEntityManagerImpl.java:646)
   at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:600)
   at org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:237)
   at WebOrganizer.web.servlets.TypeServlet.test2(TypeServlet.java:356)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
   at java.lang.reflect.Method.invoke(Method.java:597)
   at org.testng.internal.MethodHelper.invokeMethod(MethodHelper.java:580)
   at org.testng.internal.Invoker.invokeMethod(Invoker.java:517)
   at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:669)
   at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:956)
   at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:126)
   at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:110)
   at org.testng.TestRunner.runWorkers(TestRunner.java:720)
   at org.testng.TestRunner.privateRun(TestRunner.java:590)
   at org.testng.TestRunner.run(TestRunner.java:484)
   at org.testng.SuiteRunner.runTest(SuiteRunner.java:332)
   at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:327)
   at org.testng.SuiteRunner.privateRun(SuiteRunner.java:299)
   at org.testng.SuiteRunner.run(SuiteRunner.java:204)
   at org.testng.TestNG.createAndRunSuiteRunners(TestNG.java:864)
   at org.testng.TestNG.runSuitesLocally(TestNG.java:830)
   at org.testng.TestNG.run(TestNG.java:748)
   at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:73)
   at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:124)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
   at java.lang.reflect.Method.invoke(Method.java:597)
   at com.intellij.rt.execution.application.AppMain.main(AppMain.java:90)

Caused by: org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [WebOrganizer.classes.types.StringType#174]
   at org.hibernate.event.def.DefaultMergeEventListener.entityIsDetached(DefaultMergeEventListener.java:261)
   at org.hibernate.event.def.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:120)
   at org.hibernate.event.def.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:53)
   at org.hibernate.impl.SessionImpl.fireMerge(SessionImpl.java:677)
   at org.hibernate.impl.SessionImpl.merge(SessionImpl.java:661)
   at org.hibernate.impl.SessionImpl.merge(SessionImpl.java:665)
   at org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:228)
   ... 28 more

Body:
I'd give something like this a try:

EntityTransaction tx1 = em1.getTransaction();
// make your modifications
em1.merge(st1);
tx1.commit();

Not sure why you have are beginning a transaction right before you clean up the EntityManager.  I don't work with JPA transactions programmatically so this is just an educated guess.  Also, why are you creating a new EntityManager every time if it's returning the same instance?


问:
leanModal.js - Simplest jQuery Modal Script Troubleshooting
Man oh man. After slaving over leanModal, the simplest possible Modal Window script, for many hours, I still can't get it to trigger.

leanModal: http://leanmodal.finelysliced.com.au

My site: http://wlvrtn.com/sites/nms-leanmodal/

Help a jQuery noob out?

HEAD:

```<code><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="_/js/jquery.leanModal.min.js"></script>
<script type="text/javascript">
        $(function() {
            $('a[rel*=leanModal]').leanModal({ top : 200, closeButton: ".modal_close" });
        });
</script>
</code>```

CSS:

```<code>#lean_overlay {
position: fixed;
z-index: 10000;
top: 0px;
left: 0px;
height:100%;
width:100%;
background: #000;
display: none;
}

#test {
width: 600px;
display:none;
background: #FFF;
}
</code>```

HTML:

```<code><a class="request-consultation" rel="leanModal" name="test" href="#test">
    Request Complimentary Consultation
</a>

<div id="test">
    <p>Lorem ipsum dolor sit amet.</p>
</div>
</code>```

答:
try adding the third parameter.</p>

```<code>$('#foo').leanModal({top:100,overlay:0.5,closeButton:".modal_close"});
</code>```

Body:
Man oh man. After slaving over leanModal, the simplest possible Modal Window script, for many hours, I still can't get it to trigger.

leanModal: http://leanmodal.finelysliced.com.au

My site: http://wlvrtn.com/sites/nms-leanmodal/

Help a jQuery noob out?

HEAD:

CSS:

#lean_overlay {
position: fixed;
z-index: 10000;
top: 0px;
left: 0px;
height:100%;
width:100%;
background: #000;
display: none;
}

#test {
width: 600px;
display:none;
background: #FFF;
}

HTML:

    Request Complimentary Consultation

Lorem ipsum dolor sit amet.

Body:
try adding the third parameter.

$('#foo').leanModal({top:100,overlay:0.5,closeButton:".modal_close"});


问:
How to do map function on vector in R?
I have a vector like (1,100,2,30,20,...)

And what I'd like to do is mapping these value to another value. Actually I can do a loop on these values, but I wonder whether I can make the map function vectorized. For example, I'd like to map the value to its bucket such as following

```<code>1 ->  "< 10",
20 -> "10 to 50",
60 -> "50 to 100",
</code>```

Thanks

答:
Use Purrr's map (https://www.rdocumentation.org/packages/purrr/versions/0.1.0/topics/map )

e.g.

```<code>xx=c(1,4,0,3,1)

f = function(s) return(c((10*s):(10*s+9)))
xx %>% map(f)
</code>```

Title: How to do map function on vector in R?

Body:
I have a vector like (1,100,2,30,20,...)

And what I'd like to do is mapping these value to another value. Actually I can do a loop on these values, but I wonder whether I can make the map function vectorized. For example, I'd like to map the value to its bucket such as following

1 ->  "< 10",
20 -> "10 to 50",
60 -> "50 to 100",

Thanks

Body:
Use Purrr's map (https://www.rdocumentation.org/packages/purrr/versions/0.1.0/topics/map )

e.g.

xx=c(1,4,0,3,1)

f = function(s) return(c((10*s):(10*s+9)))
xx %>% map(f)


问:
Pushing codes in bitbucket delete server files
I am using Laravel Forge and connect it to Envoyer, when I push the codes to bitbucket master branch (that connected to live server) it delete all the users files (such as users profile picture and ...).

I tried .gitignore in two different format each time:

```<code>/public/images/profile/*
#and
/public/images/profile/
</code>```

but still the users images are deleted.

Any one know how can prevent deletion of the images inside a folder?

答:
With each deploy Envoyer is creating new directory with fresh code from your repository. Your files aren't really deleted, those are still at the server in previous deployment folder.

To solve this, place user files in storage directory. Afterwards go to Envoyer -> Deployment Hooks -> Manage Linked Folders and add the following:

More details here - https://envoyer.io/docs

Deployment Lifecycle

When a deployment is triggered for your project, Envoyer will execute your deployment plan. By default, this consists of downloading a tarball of your project, installing the Composer dependencies, pointing the current symbolic link at the latest release, and finally purging any old deployments from your server.

Managing Uploaded Files

When storing user uploaded files, you should store them in the storage directory of your application if you are using Laravel. Then, you may use the "Manage Linked Folders" feature of Envoyer to create a symbolic link from your public directory to the storage directory. The "Manage Linked Folders" button can be found on the "Deployment Hooks" tab of your project.

If you are not using Laravel, you will essentially follow the same process. However, you will need to manually create a storage directory in the deployment path of your application (the same directory level as the current symbolic link).

Body:
I am using Laravel Forge and connect it to Envoyer, when I push the codes to bitbucket master branch (that connected to live server) it delete all the users files (such as users profile picture and ...).

I tried .gitignore in two different format each time:

/public/images/profile/*
#and
/public/images/profile/

but still the users images are deleted.

Any one know how can prevent deletion of the images inside a folder?


问:
Mod Rewrite Regex Negative Lookahead
I am trying to match all URIs that begin with #/tool_[a-z\-]+# except if it's followed by /public.  Such as /tool_calculator or whatever.

For example, if the URI begins with /tool_store-front or /tool_store-front/anything-but-public then I want to redirect them to HTTPS.  So, /tool_store-front/public would not redirect.

Here's what I have and it's not working

```<code>RewriteCond %{HTTPS} =off
RewriteCond %{REQUEST_URI} ^/?tool_[a-z-]+(?!/public.+) [OR]
RewriteCond %{REQUEST_URI} ^/?secure
RewriteCond %{REQUEST_URI} !^/?secure/public/info
RewriteRule ^(.*)$ https://www.example.org%{REQUEST_URI} [NC,L]
</code>```

答:
You can also change your negative lookahead condition to this using a possessive quantifier:

```<code>RewriteCond %{HTTPS} =off
RewriteCond %{REQUEST_URI} ^/tool_[a-z-]++(?!/public) [NC,OR]
RewriteCond %{REQUEST_URI} ^/secure(?!/public/info) [NC]
RewriteRule ^ https://www.example.org%{REQUEST_URI} [NE,R=301,L]
</code>```

You can also use this negative lookahead:

```<code>RewriteCond %{REQUEST_URI} ^/tool_[a-z-]+(?!.*/public) [NC,OR]
</code>```

Problem in your condition ^/?tool_[a-z-]+(?!/public.+) is that regex engine is backtracking [a-z]+, one position before / to assert negative lookahead (?!/public.+) true.

Title: Mod Rewrite Regex Negative Lookahead

Body:
I am trying to match all URIs that begin with #/tool_[a-z\-]+# except if it's followed by /public.  Such as /tool_calculator or whatever.

For example, if the URI begins with /tool_store-front or /tool_store-front/anything-but-public then I want to redirect them to HTTPS.  So, /tool_store-front/public would not redirect.

Here's what I have and it's not working

RewriteCond %{HTTPS} =off
RewriteCond %{REQUEST_URI} ^/?tool_[a-z-]+(?!/public.+) [OR]
RewriteCond %{REQUEST_URI} ^/?secure
RewriteCond %{REQUEST_URI} !^/?secure/public/info
RewriteRule ^(.*)$ https://www.example.org%{REQUEST_URI} [NC,L]

Body:
You can also change your negative lookahead condition to this using a possessive quantifier:

RewriteCond %{HTTPS} =off
RewriteCond %{REQUEST_URI} ^/tool_[a-z-]++(?!/public) [NC,OR]
RewriteCond %{REQUEST_URI} ^/secure(?!/public/info) [NC]
RewriteRule ^ https://www.example.org%{REQUEST_URI} [NE,R=301,L]

You can also use this negative lookahead:

RewriteCond %{REQUEST_URI} ^/tool_[a-z-]+(?!.*/public) [NC,OR]

Problem in your condition ^/?tool_[a-z-]+(?!/public.+) is that regex engine is backtracking [a-z]+, one position before / to assert negative lookahead (?!/public.+) true.


问:
MS-SQL/ColdFusion: Mysterious database error: Object has been closed
I'm using ColdFusion with Microsoft SQL Server 2005 and on occasion I get this error:

"[Macromedia][SQLServer JDBC Driver]Object has been closed."

The traceback invariably leads to an SQL query as one would expect, even simple SELECT commands with no JOINs or input parameters or anything fancy at all.

The only solution I've heard about so far is to restart "the service", which I can only imagine refers to the SQL Server service. I've tried restarting both the SQL Server and the ColdFusion Service, but it still keeps happening at random times.

(Also a restart isn't a solution. One cannot have arbitrary pages giving arbitrary error messages at arbitrary times in a production environment.)

When it occurs, it occurs persistently for a few minutes, then goes away and might come back in a few seconds or minutes. It started happening when I was developing a JavaScript portion of my application which should have nothing to do with either the ColdFusion code or the SQL commands.

My searches online have been fruitless so far.

Any help appreciated.

答:
Turns out this simply happens when the server is overloaded. There seems to be no remedy other than restarting and/or removing load from the server.

Thanks all who answered, anyway!


答:
In general, it's bad practice to use Thread.sleep() inside the Move method.  But, if that's what you intend to do:

This is a compilation error complaining that there's an exception that might not get caught, try surrounding your Thread.sleep(2000) with a try-catch statement, example:

```<code>try {
    Thread.sleep(2000);
} catch (InterruptedException e) {
    e.printStackTrace();
}
</code>```

Title: wait() and Thread.sleep() Dont work

Body:
In general, it's bad practice to use Thread.sleep() inside the Move method.  But, if that's what you intend to do:

This is a compilation error complaining that there's an exception that might not get caught, try surrounding your Thread.sleep(2000) with a try-catch statement, example:

try {
    Thread.sleep(2000);
} catch (InterruptedException e) {
    e.printStackTrace();
}