问:
How to delete a specific dataset from Chart.js?
I want to add & delete datasets from chart.js using checkboxes.

Right now I am adding using this:

```<code>var ds1 = {
    label: ..
    data: .. etc
};
data.datasets.push(ds1);
</code>```

When I uncheck any of the checkboxes, it's always deleting the last dataset added, which is not necessary the one of the checkbox.

I'm using data.datasets.pop(ds1); to remove the when a checkbox is clicked.

答:
If you look at ChartJS' internal object chart.data.datasets, the datasets are distinguishable by the label you gave when initially adding the datasets (it's weird that there's no ID):

So it's really just a matter of filtering out an object from the array by that Label, and calling chart.update();.

```<code>// Filter out and set back into chart.data.datasets
chart.data.datasets = chart.data.datasets.filter(function(obj) {
    return (obj.label != targetLabel);
});
// Repaint
chart.update();
</code>```

Body:
I want to add & delete datasets from chart.js using checkboxes.

Right now I am adding using this:

var ds1 = {
    label: ..
    data: .. etc
};
data.datasets.push(ds1);

When I uncheck any of the checkboxes, it's always deleting the last dataset added, which is not necessary the one of the checkbox.

I'm using data.datasets.pop(ds1); to remove the when a checkbox is clicked.

Body:
If you look at ChartJS' internal object chart.data.datasets, the datasets are distinguishable by the label you gave when initially adding the datasets (it's weird that there's no ID):

So it's really just a matter of filtering out an object from the array by that Label, and calling chart.update();.

// Filter out and set back into chart.data.datasets
chart.data.datasets = chart.data.datasets.filter(function(obj) {
    return (obj.label != targetLabel);
});
// Repaint
chart.update();


来源: stackexchange

问:
Is it possible to include a C# variable in a string variable without using a concatenator?
Does .NET 3.5 C# allow us to include a variable within a string variable without having to use the + concatenator (or string.Format(), for that matter).

For example (In the pseudo, I'm using a $ symbol to specify the variable):

```<code>DateTime d = DateTime.Now;
string s = "The date is $d";
Console.WriteLine(s);
</code>```

Output:

The date is 4/12/2011 11:56:39 AM

Edit

Due to the handful of responses that suggested string.Format(), I can only assume that my original post wasn't clear when I mentioned "...(or string.Format(), for that matter)". To be clear, I'm well aware of the string.Format() method. However, in my specific project that I'm working on, string.Format() doesn't help me (it's actually worse than the + concatenator).

Also, I'm inferring that most/all of you are wondering what the motive behind my question is (I suppose I'd feel the same way if I read my question as is).

If you are one of the curious, here's the short of it:

I'm creating a web app running on a Windows CE device. Due to how the web server works, I create the entire web page content (css, js, html, etc) within a string variable. For example, my .cs managed code might have something like this:

```<code>string GetPageData()
    {
    string title = "Hello";
    DateTime date = DateTime.Now;

    string html = @"
    <!DOCTYPE html PUBLIC ...>
    <html>
    <head>
        <title>$title</title>
    </head>
    <body>
    <div>Hello StackO</div>
    <div>The date is $date</div>
    </body>
    </html>
    ";

}
</code>```

As you can see, having the ability to specify a variable without the need to concatenate, makes things a bit easier - especially when the content increases in size.

答:
string.Format (and similar formatting functions such as StringBuilder.AppendFormat) are the best way to do this in terms of flexibility, coding practice, and (usually) performance:

```<code>string s = string.Format("The date is {0}", d);
</code>```

You can also specify the display format of your DateTime, as well as inserting more than one object into the string. Check out MSDN's page on the string.Format method.

Certain types also have overloads to their ToString methods which allow you to specify a format string. You could also create an extension method for string that allows you to specify a format and/or parse syntax like this.

ContentLicense: CC BY-SA 3.0

Body:
Does .NET 3.5 C# allow us to include a variable within a string variable without having to use the + concatenator (or string.Format(), for that matter).

For example (In the pseudo, I'm using a $ symbol to specify the variable):

DateTime d = DateTime.Now;
string s = "The date is $d";
Console.WriteLine(s);

Output:

The date is 4/12/2011 11:56:39 AM

Edit

Due to the handful of responses that suggested string.Format(), I can only assume that my original post wasn't clear when I mentioned "...(or string.Format(), for that matter)". To be clear, I'm well aware of the string.Format() method. However, in my specific project that I'm working on, string.Format() doesn't help me (it's actually worse than the + concatenator).

Also, I'm inferring that most/all of you are wondering what the motive behind my question is (I suppose I'd feel the same way if I read my question as is).

If you are one of the curious, here's the short of it:

I'm creating a web app running on a Windows CE device. Due to how the web server works, I create the entire web page content (css, js, html, etc) within a string variable. For example, my .cs managed code might have something like this:

string GetPageData()
    {
    string title = "Hello";
    DateTime date = DateTime.Now;

    string html = @"
    <!DOCTYPE html PUBLIC ...>

        <title>$title</title>

Hello StackO

The date is $date

    ";

}

As you can see, having the ability to specify a variable without the need to concatenate, makes things a bit easier - especially when the content increases in size.

Body:
string.Format (and similar formatting functions such as StringBuilder.AppendFormat) are the best way to do this in terms of flexibility, coding practice, and (usually) performance:

string s = string.Format("The date is {0}", d);

You can also specify the display format of your DateTime, as well as inserting more than one object into the string. Check out MSDN's page on the string.Format method.

Certain types also have overloads to their ToString methods which allow you to specify a format string. You could also create an extension method for string that allows you to specify a format and/or parse syntax like this.


问:
Floating Text Next to An Image HTML CSS
I'm trying to float text around an image, but for some reason, the text won't go in the right place.

Here is what I want it to look like. I was able to create this in an editor by itself, but when I add it to my page, it breaks it and doesn't work.

I'm having trouble getting it to look like my other example. They have the same code for that part. Need help figuring out how to get it close to the first example.

Mine Now:

section{
 display:flex;
    border-style:solid;
    background-color:azure;
}

img {
  padding-top: 5em;
  padding-right:2em;
}

p{
float:right;
}

h1{
 text-align:center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
  <img src="images/GM05.png" alt="headshot">
  <article>
     <h1>Name Goes Here.</h1>
     <p>Cras tristique gravida tellus, id fringilla lorem pellentesque iaculis. Donec vitae risus mauris. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nunc consectetur purus sed diam iaculis congue. Morbi vitae nisl est. Sed sed justo vitae risus porta commodo vestibulum eget est. Cras eu augue enim. Etiam at commodo tellus, at posuere ligula. Vivamus at dolor eget sem faucibus aliquet sed et diam. Mauris vel leo eget nulla pulvinar suscipit vitae eu sem. Quisque nisi nibh, aliquet sit amet urna non, commodo fringilla tellus. Nullam tincidunt est nec tellus laoreet, id mollis urna pulvinar. Donec ligula ipsum, ultrices in venenatis quis, ultricies ut enim. Vivamus porttitor lobortis dui, id aliquam ipsum imperdiet non.</p>
  </article>
</section>
    </code>```

答:
There are no floats involved. Put your image in another wrapper. Then apply flex property to that wrapper. Adjust the last value (flex-basis) to the width you want that "column" to be.

```<code>aside {
  flex: 0 0 40%; /* flex-grow: 0; flex-shrink: 0; flex-basis: 40%; */
  padding-top: 64px;
}
</code>```

You can center the image in that space with margin.

```<code>aside img {
  display: block;
  max-width: 100%;
  height: auto;
  margin: 0 auto; /* auto on the sides centers the item */
}
</code>```

section {
  display: flex;
  border-style: solid;
  background-color: azure;
}

aside {
  flex: 0 0 40%;
  padding-top: 64px;
}

aside img {
  display: block;
  max-width: 100%;
  height: auto;
  margin: 0 auto;
}

h1 {
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
  <aside>
    <img src="https://picsum.photos/200/300" alt="headshot">
  </aside>
  <article>
    <h1>Name Goes Here.</h1>
    <p>Cras tristique gravida tellus, id fringilla lorem pellentesque iaculis. Donec vitae risus mauris. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nunc consectetur purus sed diam iaculis congue. Morbi vitae nisl est. Sed sed justo vitae
      risus porta commodo vestibulum eget est. Cras eu augue enim. Etiam at commodo tellus, at posuere ligula. Vivamus at dolor eget sem faucibus aliquet sed et diam. Mauris vel leo eget nulla pulvinar suscipit vitae eu sem. Quisque nisi nibh, aliquet
      sit amet urna non, commodo fringilla tellus. Nullam tincidunt est nec tellus laoreet, id mollis urna pulvinar. Donec ligula ipsum, ultrices in venenatis quis, ultricies ut enim. Vivamus porttitor lobortis dui, id aliquam ipsum imperdiet non.</p>
  </article>
</section></code>```

ContentLicense: CC BY-SA 4.0

Title: Floating Text Next to An Image HTML CSS

Body:
I'm trying to float text around an image, but for some reason, the text won't go in the right place.

Here is what I want it to look like. I was able to create this in an editor by itself, but when I add it to my page, it breaks it and doesn't work.

I'm having trouble getting it to look like my other example. They have the same code for that part. Need help figuring out how to get it close to the first example.

Mine Now:

section{
 display:flex;
    border-style:solid;
    background-color:azure;
}

img {
  padding-top: 5em;
  padding-right:2em;
}

p{
float:right;
}

h1{
 text-align:center;
}

Name Goes Here.

Cras tristique gravida tellus, id fringilla lorem pellentesque iaculis. Donec vitae risus mauris. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nunc consectetur purus sed diam iaculis congue. Morbi vitae nisl est. Sed sed justo vitae risus porta commodo vestibulum eget est. Cras eu augue enim. Etiam at commodo tellus, at posuere ligula. Vivamus at dolor eget sem faucibus aliquet sed et diam. Mauris vel leo eget nulla pulvinar suscipit vitae eu sem. Quisque nisi nibh, aliquet sit amet urna non, commodo fringilla tellus. Nullam tincidunt est nec tellus laoreet, id mollis urna pulvinar. Donec ligula ipsum, ultrices in venenatis quis, ultricies ut enim. Vivamus porttitor lobortis dui, id aliquam ipsum imperdiet non.

Body:
There are no floats involved. Put your image in another wrapper. Then apply flex property to that wrapper. Adjust the last value (flex-basis) to the width you want that "column" to be.

aside {
  flex: 0 0 40%; /* flex-grow: 0; flex-shrink: 0; flex-basis: 40%; */
  padding-top: 64px;
}

You can center the image in that space with margin.

aside img {
  display: block;
  max-width: 100%;
  height: auto;
  margin: 0 auto; /* auto on the sides centers the item */
}

section {
  display: flex;
  border-style: solid;
  background-color: azure;
}

aside {
  flex: 0 0 40%;
  padding-top: 64px;
}

aside img {
  display: block;
  max-width: 100%;
  height: auto;
  margin: 0 auto;
}

h1 {
  text-align: center;
}

<section>
  <aside>
    <img src="https://picsum.photos/200/300" alt="headshot">
  </aside>
  <article>
    <h1>Name Goes Here.</h1>
    <p>Cras tristique gravida tellus, id fringilla lorem pellentesque iaculis. Donec vitae risus mauris. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nunc consectetur purus sed diam iaculis congue. Morbi vitae nisl est. Sed sed justo vitae
      risus porta commodo vestibulum eget est. Cras eu augue enim. Etiam at commodo tellus, at posuere ligula. Vivamus at dolor eget sem faucibus aliquet sed et diam. Mauris vel leo eget nulla pulvinar suscipit vitae eu sem. Quisque nisi nibh, aliquet
      sit amet urna non, commodo fringilla tellus. Nullam tincidunt est nec tellus laoreet, id mollis urna pulvinar. Donec ligula ipsum, ultrices in venenatis quis, ultricies ut enim. Vivamus porttitor lobortis dui, id aliquam ipsum imperdiet non.</p>
  </article>
</section>


问:
read/write to the same file from multiple docker containers
I have 4 containers(java app) in 4 docker hosts. they need to read/write to the same file.

file lock cannot be used because of different OS.

So, I tried to create a .lock file, if one of the 4 containers created the .lock file, the other containers will have to wait.
But this still isn't working well. The other containers cannot see the .lock file created by other containers sometimes(not real-time).

Are there other solutions?

答:
I suggest you rethink your assumptions:

What if you have not 4 but 400 containers?

What if they are on servers not sharing a file system?

The clean way to do this is to write a very basic server (if the load allows it, this can be nginx+PHP and be done in 10 minutes) that does the file writing, run this in another container and connect to it from the other containers. This will give you:

file locking easy and reliable, as the file is seen only by one server

scalability

clusterability

abstraction


答:
If i understand correctly, you just wanna to display this image on the center.

So, change padding-top: 5em; to margin: auto;

Best regards,

Brhaka

Title: Floating Text Next to An Image HTML CSS


问:
cassandra 4.0.0 driver - PreparedStatement uses 100% of one CPU node?
With cassandra driver 4.0.0 (com.datastax.oss / java-driver-core / 4.0.0), a PreparedStatement (just by existing) uses 100% of one CPU node, even when the application is idle:

```<code>import com.datastax.oss.driver.api.core.CqlSession;

import java.net.InetSocketAddress;

public class Demo_4_0_0 {
    public static void main(String[] args) throws Exception {
        CqlSession session = CqlSession.builder().addContactPoint(new InetSocketAddress("localhost", 9042)).withLocalDatacenter("datacenter1").build();
        System.out.println("before preparing select");
        Thread.sleep(15000);
        session.prepare("SELECT value FROM demo.demo WHERE partition = 0;");
        System.out.println("after preparing select");
        Thread.sleep(15000);
        session.close();
    }
}
</code>```

The same PreparedStatement with cassandra driver 3.7.1 (com.datastax.cassandra / cassandra-driver-core / 3.7.1) behaves fine - no CPU load when the application is idle:

```<code>import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;

public class Demo_3_7_1 {
    public static void main(String[] args) throws Exception {
        Session session = Cluster.builder().addContactPoints("127.0.0.1").build().connect();
        System.out.println("before preparing select");
        Thread.sleep(15000);
        session.prepare("SELECT value FROM demo.demo WHERE partition = 0;");
        System.out.println("after preparing select");
        Thread.sleep(15000);
        session.close();
    }
}
</code>```

For the examples to work, in cassandra first execute:

```<code>CREATE KEYSPACE demo WITH REPLICATION = {'class':'SimpleStrategy', 'replication_factor':1};
CREATE TABLE demo.demo (partition INT PRIMARY KEY, value INT);
</code>```

My environment: Cassandra 3.11.2 (as docker container), jdk1.8.0_111 x64, Windows 10, 8 CPUs.

Any ideas?

Additional information: The thread dump before and after preparing the statement looks identical with one exception, that the "s0-timer-0" thread has appeared:

```<code>"s0-timer-0" #12 prio=5 os_prio=0 tid=0x0000000021392000 nid=0xcd0 runnable [0x0000000024f1e000]
   java.lang.Thread.State: RUNNABLE
        at java.lang.Thread.sleep(Native Method)
        at io.netty.util.HashedWheelTimer$Worker.waitForNextTick(HashedWheelTimer.java:579)
        at io.netty.util.HashedWheelTimer$Worker.run(HashedWheelTimer.java:478)
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
        at java.lang.Thread.run(Unknown Source)

   Locked ownable synchronizers:
        - None
</code>```

Here is the full thread dump after the statement has been prepared:

```<code>2019-04-06 10:50:54
Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.202-b08 mixed mode):

"s0-timer-0" #12 prio=5 os_prio=0 tid=0x0000000021392000 nid=0xcd0 runnable [0x0000000024f1e000]
   java.lang.Thread.State: RUNNABLE
        at java.lang.Thread.sleep(Native Method)
        at io.netty.util.HashedWheelTimer$Worker.waitForNextTick(HashedWheelTimer.java:579)
        at io.netty.util.HashedWheelTimer$Worker.run(HashedWheelTimer.java:478)
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
        at java.lang.Thread.run(Unknown Source)

   Locked ownable synchronizers:
        - None

"JMX server connection timeout 20" #20 daemon prio=5 os_prio=0 tid=0x000000001ff32000 nid=0xb90 in Object.wait() [0x0000000024a1f000]
   java.lang.Thread.State: TIMED_WAITING (on object monitor)
        at java.lang.Object.wait(Native Method)
        - waiting on <0x000000076b779218> (a [I)
        at com.sun.jmx.remote.internal.ServerCommunicatorAdmin$Timeout.run(Unknown Source)
        - locked <0x000000076b779218> (a [I)
        at java.lang.Thread.run(Unknown Source)

   Locked ownable synchronizers:
        - None

"RMI Scheduler(0)" #19 daemon prio=5 os_prio=0 tid=0x000000001ff31000 nid=0x13ac waiting on condition [0x000000002491f000]
   java.lang.Thread.State: TIMED_WAITING (parking)
        at sun.misc.Unsafe.park(Native Method)
        - parking to wait for  <0x000000076f8c4ca0> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
        at java.util.concurrent.locks.LockSupport.parkNanos(Unknown Source)
        at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(Unknown Source)
        at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(Unknown Source)
        at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor.getTask(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
        at java.lang.Thread.run(Unknown Source)

   Locked ownable synchronizers:
        - None

"RMI TCP Connection(1)-10.0.75.1" #18 daemon prio=5 os_prio=0 tid=0x0000000020be7800 nid=0x27b0 runnable [0x000000002481d000]
   java.lang.Thread.State: RUNNABLE
        at java.net.SocketInputStream.socketRead0(Native Method)
        at java.net.SocketInputStream.socketRead(Unknown Source)
        at java.net.SocketInputStream.read(Unknown Source)
        at java.net.SocketInputStream.read(Unknown Source)
        at java.io.BufferedInputStream.fill(Unknown Source)
        at java.io.BufferedInputStream.read(Unknown Source)
        - locked <0x000000076b73dae0> (a java.io.BufferedInputStream)
        at java.io.FilterInputStream.read(Unknown Source)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(Unknown Source)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(Unknown Source)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(Unknown Source)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$$Lambda$180/1667804988.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
        at java.lang.Thread.run(Unknown Source)

   Locked ownable synchronizers:
        - <0x000000076b553ee8> (a java.util.concurrent.ThreadPoolExecutor$Worker)

"RMI TCP Accept-0" #17 daemon prio=5 os_prio=0 tid=0x0000000020b3c000 nid=0x448c runnable [0x000000002461f000]
   java.lang.Thread.State: RUNNABLE
        at java.net.DualStackPlainSocketImpl.accept0(Native Method)
        at java.net.DualStackPlainSocketImpl.socketAccept(Unknown Source)
        at java.net.AbstractPlainSocketImpl.accept(Unknown Source)
        at java.net.PlainSocketImpl.accept(Unknown Source)
        - locked <0x000000076f400858> (a java.net.SocksSocketImpl)
        at java.net.ServerSocket.implAccept(Unknown Source)
        at java.net.ServerSocket.accept(Unknown Source)
        at sun.management.jmxremote.LocalRMIServerSocketFactory$1.accept(Unknown Source)
        at sun.rmi.transport.tcp.TCPTransport$AcceptLoop.executeAcceptLoop(Unknown Source)
        at sun.rmi.transport.tcp.TCPTransport$AcceptLoop.run(Unknown Source)
        at java.lang.Thread.run(Unknown Source)

   Locked ownable synchronizers:
        - None

"s0-io-1" #16 prio=5 os_prio=0 tid=0x0000000020b34000 nid=0x33f8 runnable [0x000000002310f000]
   java.lang.Thread.State: RUNNABLE
        at sun.nio.ch.WindowsSelectorImpl$SubSelector.poll0(Native Method)
        at sun.nio.ch.WindowsSelectorImpl$SubSelector.poll(Unknown Source)
        at sun.nio.ch.WindowsSelectorImpl$SubSelector.access$400(Unknown Source)
        at sun.nio.ch.WindowsSelectorImpl.doSelect(Unknown Source)
        at sun.nio.ch.SelectorImpl.lockAndDoSelect(Unknown Source)
        - locked <0x000000076f413268> (a io.netty.channel.nio.SelectedSelectionKeySet)
        - locked <0x000000076f413280> (a java.util.Collections$UnmodifiableSet)
        - locked <0x000000076f4131e8> (a sun.nio.ch.WindowsSelectorImpl)
        at sun.nio.ch.SelectorImpl.select(Unknown Source)
        at io.netty.channel.nio.SelectedSelectionKeySetSelector.select(SelectedSelectionKeySetSelector.java:62)
        at io.netty.channel.nio.NioEventLoop.select(NioEventLoop.java:786)
        at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:434)
        at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:905)
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
        at java.lang.Thread.run(Unknown Source)

   Locked ownable synchronizers:
        - None

"s0-io-0" #15 prio=5 os_prio=0 tid=0x00000000203cd800 nid=0x368c runnable [0x0000000021aff000]
   java.lang.Thread.State: RUNNABLE
        at sun.nio.ch.WindowsSelectorImpl$SubSelector.poll0(Native Method)
        at sun.nio.ch.WindowsSelectorImpl$SubSelector.poll(Unknown Source)
        at sun.nio.ch.WindowsSelectorImpl$SubSelector.access$400(Unknown Source)
        at sun.nio.ch.WindowsSelectorImpl.doSelect(Unknown Source)
        at sun.nio.ch.SelectorImpl.lockAndDoSelect(Unknown Source)
        - locked <0x000000076f40b900> (a io.netty.channel.nio.SelectedSelectionKeySet)
        - locked <0x000000076f40b918> (a java.util.Collections$UnmodifiableSet)
        - locked <0x000000076f40b880> (a sun.nio.ch.WindowsSelectorImpl)
        at sun.nio.ch.SelectorImpl.select(Unknown Source)
        at io.netty.channel.nio.SelectedSelectionKeySetSelector.select(SelectedSelectionKeySetSelector.java:62)
        at io.netty.channel.nio.NioEventLoop.select(NioEventLoop.java:786)
        at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:434)
        at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:905)
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
        at java.lang.Thread.run(Unknown Source)

   Locked ownable synchronizers:
        - None

"s0-admin-1" #14 prio=5 os_prio=0 tid=0x00000000202c7000 nid=0x4aac waiting on condition [0x0000000020a2f000]
   java.lang.Thread.State: TIMED_WAITING (parking)
        at sun.misc.Unsafe.park(Native Method)
        - parking to wait for  <0x000000076f418190> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
        at java.util.concurrent.locks.LockSupport.parkNanos(Unknown Source)
        at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(Unknown Source)
        at java.util.concurrent.LinkedBlockingQueue.poll(Unknown Source)
        at io.netty.util.concurrent.SingleThreadEventExecutor.takeTask(SingleThreadEventExecutor.java:251)
        at io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:52)
        at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:905)
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
        at java.lang.Thread.run(Unknown Source)

   Locked ownable synchronizers:
        - None

"s0-admin-0" #13 prio=5 os_prio=0 tid=0x00000000202b5800 nid=0x4158 waiting on condition [0x000000002072e000]
   java.lang.Thread.State: WAITING (parking)
        at sun.misc.Unsafe.park(Native Method)
        - parking to wait for  <0x000000076f420180> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
        at java.util.concurrent.locks.LockSupport.park(Unknown Source)
        at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(Unknown Source)
        at java.util.concurrent.LinkedBlockingQueue.take(Unknown Source)
        at io.netty.util.concurrent.SingleThreadEventExecutor.takeTask(SingleThreadEventExecutor.java:238)
        at io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:52)
        at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:905)
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
        at java.lang.Thread.run(Unknown Source)

   Locked ownable synchronizers:
        - None

"Service Thread" #10 daemon prio=9 os_prio=0 tid=0x000000001eb95000 nid=0x2b30 runnable [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
        - None

"C1 CompilerThread3" #9 daemon prio=9 os_prio=2 tid=0x000000001eb11800 nid=0x1948 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
        - None

"C2 CompilerThread2" #8 daemon prio=9 os_prio=2 tid=0x000000001eb05800 nid=0x56c waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
        - None

"C2 CompilerThread1" #7 daemon prio=9 os_prio=2 tid=0x000000001eafd800 nid=0x4a04 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
        - None

"C2 CompilerThread0" #6 daemon prio=9 os_prio=2 tid=0x000000001eafa800 nid=0x1e0c waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
        - None

"Attach Listener" #5 daemon prio=5 os_prio=2 tid=0x000000001eaf8800 nid=0x34c4 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
        - None

"Signal Dispatcher" #4 daemon prio=9 os_prio=2 tid=0x000000001cc1e000 nid=0x36f0 runnable [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
        - None

"Finalizer" #3 daemon prio=8 os_prio=1 tid=0x000000000319e800 nid=0x4acc in Object.wait() [0x000000001efce000]
   java.lang.Thread.State: WAITING (on object monitor)
        at java.lang.Object.wait(Native Method)
        - waiting on <0x000000076f438180> (a java.lang.ref.ReferenceQueue$Lock)
        at java.lang.ref.ReferenceQueue.remove(Unknown Source)
        - locked <0x000000076f438180> (a java.lang.ref.ReferenceQueue$Lock)
        at java.lang.ref.ReferenceQueue.remove(Unknown Source)
        at java.lang.ref.Finalizer$FinalizerThread.run(Unknown Source)

   Locked ownable synchronizers:
        - None

"Reference Handler" #2 daemon prio=10 os_prio=2 tid=0x0000000003195000 nid=0x4118 in Object.wait() [0x000000001eace000]
   java.lang.Thread.State: WAITING (on object monitor)
        at java.lang.Object.wait(Native Method)
        - waiting on <0x000000076f430468> (a java.lang.ref.Reference$Lock)
        at java.lang.Object.wait(Unknown Source)
        at java.lang.ref.Reference.tryHandlePending(Unknown Source)
        - locked <0x000000076f430468> (a java.lang.ref.Reference$Lock)
        at java.lang.ref.Reference$ReferenceHandler.run(Unknown Source)

   Locked ownable synchronizers:
        - None

"main" #1 prio=5 os_prio=0 tid=0x00000000011be000 nid=0x3c90 waiting on condition [0x000000000301f000]
   java.lang.Thread.State: TIMED_WAITING (sleeping)
        at java.lang.Thread.sleep(Native Method)
        at bug.Demo_4_0_0.main(Demo_4_0_0.java:14)

   Locked ownable synchronizers:
        - None

"VM Thread" os_prio=2 tid=0x000000001cc0a000 nid=0x17c8 runnable

"GC task thread#0 (ParallelGC)" os_prio=0 tid=0x00000000030b7800 nid=0x4b9c runnable

"GC task thread#1 (ParallelGC)" os_prio=0 tid=0x00000000030b9800 nid=0x9c8 runnable

"GC task thread#2 (ParallelGC)" os_prio=0 tid=0x00000000030bb000 nid=0x46e8 runnable

"GC task thread#3 (ParallelGC)" os_prio=0 tid=0x00000000030bd000 nid=0x3234 runnable

"GC task thread#4 (ParallelGC)" os_prio=0 tid=0x00000000030be800 nid=0x3160 runnable

"GC task thread#5 (ParallelGC)" os_prio=0 tid=0x00000000030bf800 nid=0xc20 runnable

"GC task thread#6 (ParallelGC)" os_prio=0 tid=0x00000000030c3800 nid=0x4298 runnable

"GC task thread#7 (ParallelGC)" os_prio=0 tid=0x00000000030c5000 nid=0x429c runnable

"VM Periodic Task Thread" os_prio=2 tid=0x000000001ebaf000 nid=0x4a20 waiting on condition

JNI global references: 664
</code>```

答:
I looked into this a little bit today as we've had several reports of this happening now (JAVA-2264).

It appears this is caused by the fact that there is some special logic in netty's HashedWheelTimer timer code to round sleep duration to a factor of 10:

// Check if we run on windows, as if thats the case we will need
// to round the sleepTime as workaround for a bug that only affect
// the JVM if it runs on windows.
//
// See https://github.com/netty/netty/issues/356
if (PlatformDependent.isWindows()) {
    sleepTimeMs = sleepTimeMs / 10 * 10;
}
```

Typically, this would be ok, however the java driver by default configures HashedWheelTimers tick duration to 1ms.  As sleepTimeMs is a long, my guess is we're sleeping in a tight loop as 1/10*10 = 0.

We will find a solution for this in the driver, whether it be adjusting the default tick duration overall (maybe 1ms is too aggressive), or just for windows.

Until then you can work around this in one of two ways:

Pass in the system property -Ddatastax-java-driver.advanced.netty.timer.tick-duration="100 millseconds" to your application

Set datastax-java-driver.advanced.netty.timer.tick-duration=100 millseconds in application.conf

Body:
With cassandra driver 4.0.0 (com.datastax.oss / java-driver-core / 4.0.0), a PreparedStatement (just by existing) uses 100% of one CPU node, even when the application is idle:

import com.datastax.oss.driver.api.core.CqlSession;

import java.net.InetSocketAddress;

public class Demo_4_0_0 {
    public static void main(String[] args) throws Exception {
        CqlSession session = CqlSession.builder().addContactPoint(new InetSocketAddress("localhost", 9042)).withLocalDatacenter("datacenter1").build();
        System.out.println("before preparing select");
        Thread.sleep(15000);
        session.prepare("SELECT value FROM demo.demo WHERE partition = 0;");
        System.out.println("after preparing select");
        Thread.sleep(15000);
        session.close();
    }
}

The same PreparedStatement with cassandra driver 3.7.1 (com.datastax.cassandra / cassandra-driver-core / 3.7.1) behaves fine - no CPU load when the application is idle:

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;

public class Demo_3_7_1 {
    public static void main(String[] args) throws Exception {
        Session session = Cluster.builder().addContactPoints("127.0.0.1").build().connect();
        System.out.println("before preparing select");
        Thread.sleep(15000);
        session.prepare("SELECT value FROM demo.demo WHERE partition = 0;");
        System.out.println("after preparing select");
        Thread.sleep(15000);
        session.close();
    }
}

For the examples to work, in cassandra first execute:

CREATE KEYSPACE demo WITH REPLICATION = {'class':'SimpleStrategy', 'replication_factor':1};
CREATE TABLE demo.demo (partition INT PRIMARY KEY, value INT);

My environment: Cassandra 3.11.2 (as docker container), jdk1.8.0_111 x64, Windows 10, 8 CPUs.

Any ideas?

Additional information: The thread dump before and after preparing the statement looks identical with one exception, that the "s0-timer-0" thread has appeared:

"s0-timer-0" #12 prio=5 os_prio=0 tid=0x0000000021392000 nid=0xcd0 runnable [0x0000000024f1e000]
   java.lang.Thread.State: RUNNABLE
        at java.lang.Thread.sleep(Native Method)
        at io.netty.util.HashedWheelTimer$Worker.waitForNextTick(HashedWheelTimer.java:579)
        at io.netty.util.HashedWheelTimer$Worker.run(HashedWheelTimer.java:478)
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
        at java.lang.Thread.run(Unknown Source)

   Locked ownable synchronizers:
        - None

Here is the full thread dump after the statement has been prepared:

2019-04-06 10:50:54
Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.202-b08 mixed mode):

"s0-timer-0" #12 prio=5 os_prio=0 tid=0x0000000021392000 nid=0xcd0 runnable [0x0000000024f1e000]
   java.lang.Thread.State: RUNNABLE
        at java.lang.Thread.sleep(Native Method)
        at io.netty.util.HashedWheelTimer$Worker.waitForNextTick(HashedWheelTimer.java:579)
        at io.netty.util.HashedWheelTimer$Worker.run(HashedWheelTimer.java:478)
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
        at java.lang.Thread.run(Unknown Source)

   Locked ownable synchronizers:
        - None

"JMX server connection timeout 20" #20 daemon prio=5 os_prio=0 tid=0x000000001ff32000 nid=0xb90 in Object.wait() [0x0000000024a1f000]
   java.lang.Thread.State: TIMED_WAITING (on object monitor)
        at java.lang.Object.wait(Native Method)
        - waiting on <0x000000076b779218> (a [I)
        at com.sun.jmx.remote.internal.ServerCommunicatorAdmin$Timeout.run(Unknown Source)
        - locked <0x000000076b779218> (a [I)
        at java.lang.Thread.run(Unknown Source)

   Locked ownable synchronizers:
        - None

"RMI Scheduler(0)" #19 daemon prio=5 os_prio=0 tid=0x000000001ff31000 nid=0x13ac waiting on condition [0x000000002491f000]
   java.lang.Thread.State: TIMED_WAITING (parking)
        at sun.misc.Unsafe.park(Native Method)
        - parking to wait for  <0x000000076f8c4ca0> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
        at java.util.concurrent.locks.LockSupport.parkNanos(Unknown Source)
        at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(Unknown Source)
        at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(Unknown Source)
        at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor.getTask(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
        at java.lang.Thread.run(Unknown Source)

   Locked ownable synchronizers:
        - None

"RMI TCP Connection(1)-10.0.75.1" #18 daemon prio=5 os_prio=0 tid=0x0000000020be7800 nid=0x27b0 runnable [0x000000002481d000]
   java.lang.Thread.State: RUNNABLE
        at java.net.SocketInputStream.socketRead0(Native Method)
        at java.net.SocketInputStream.socketRead(Unknown Source)
        at java.net.SocketInputStream.read(Unknown Source)
        at java.net.SocketInputStream.read(Unknown Source)
        at java.io.BufferedInputStream.fill(Unknown Source)
        at java.io.BufferedInputStream.read(Unknown Source)
        - locked <0x000000076b73dae0> (a java.io.BufferedInputStream)
        at java.io.FilterInputStream.read(Unknown Source)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(Unknown Source)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(Unknown Source)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(Unknown Source)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$$Lambda$180/1667804988.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
        at java.lang.Thread.run(Unknown Source)

   Locked ownable synchronizers:
        - <0x000000076b553ee8> (a java.util.concurrent.ThreadPoolExecutor$Worker)

"RMI TCP Accept-0" #17 daemon prio=5 os_prio=0 tid=0x0000000020b3c000 nid=0x448c runnable [0x000000002461f000]
   java.lang.Thread.State: RUNNABLE
        at java.net.DualStackPlainSocketImpl.accept0(Native Method)
        at java.net.DualStackPlainSocketImpl.socketAccept(Unknown Source)
        at java.net.AbstractPlainSocketImpl.accept(Unknown Source)
        at java.net.PlainSocketImpl.accept(Unknown Source)
        - locked <0x000000076f400858> (a java.net.SocksSocketImpl)
        at java.net.ServerSocket.implAccept(Unknown Source)
        at java.net.ServerSocket.accept(Unknown Source)
        at sun.management.jmxremote.LocalRMIServerSocketFactory$1.accept(Unknown Source)
        at sun.rmi.transport.tcp.TCPTransport$AcceptLoop.executeAcceptLoop(Unknown Source)
        at sun.rmi.transport.tcp.TCPTransport$AcceptLoop.run(Unknown Source)
        at java.lang.Thread.run(Unknown Source)

   Locked ownable synchronizers:
        - None

"s0-io-1" #16 prio=5 os_prio=0 tid=0x0000000020b34000 nid=0x33f8 runnable [0x000000002310f000]
   java.lang.Thread.State: RUNNABLE
        at sun.nio.ch.WindowsSelectorImpl$SubSelector.poll0(Native Method)
        at sun.nio.ch.WindowsSelectorImpl$SubSelector.poll(Unknown Source)
        at sun.nio.ch.WindowsSelectorImpl$SubSelector.access$400(Unknown Source)
        at sun.nio.ch.WindowsSelectorImpl.doSelect(Unknown Source)
        at sun.nio.ch.SelectorImpl.lockAndDoSelect(Unknown Source)
        - locked <0x000000076f413268> (a io.netty.channel.nio.SelectedSelectionKeySet)
        - locked <0x000000076f413280> (a java.util.Collections$UnmodifiableSet)
        - locked <0x000000076f4131e8> (a sun.nio.ch.WindowsSelectorImpl)
        at sun.nio.ch.SelectorImpl.select(Unknown Source)
        at io.netty.channel.nio.SelectedSelectionKeySetSelector.select(SelectedSelectionKeySetSelector.java:62)
        at io.netty.channel.nio.NioEventLoop.select(NioEventLoop.java:786)
        at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:434)
        at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:905)
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
        at java.lang.Thread.run(Unknown Source)

   Locked ownable synchronizers:
        - None

"s0-io-0" #15 prio=5 os_prio=0 tid=0x00000000203cd800 nid=0x368c runnable [0x0000000021aff000]
   java.lang.Thread.State: RUNNABLE
        at sun.nio.ch.WindowsSelectorImpl$SubSelector.poll0(Native Method)
        at sun.nio.ch.WindowsSelectorImpl$SubSelector.poll(Unknown Source)
        at sun.nio.ch.WindowsSelectorImpl$SubSelector.access$400(Unknown Source)
        at sun.nio.ch.WindowsSelectorImpl.doSelect(Unknown Source)
        at sun.nio.ch.SelectorImpl.lockAndDoSelect(Unknown Source)
        - locked <0x000000076f40b900> (a io.netty.channel.nio.SelectedSelectionKeySet)
        - locked <0x000000076f40b918> (a java.util.Collections$UnmodifiableSet)
        - locked <0x000000076f40b880> (a sun.nio.ch.WindowsSelectorImpl)
        at sun.nio.ch.SelectorImpl.select(Unknown Source)
        at io.netty.channel.nio.SelectedSelectionKeySetSelector.select(SelectedSelectionKeySetSelector.java:62)
        at io.netty.channel.nio.NioEventLoop.select(NioEventLoop.java:786)
        at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:434)
        at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:905)
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
        at java.lang.Thread.run(Unknown Source)

   Locked ownable synchronizers:
        - None

"s0-admin-1" #14 prio=5 os_prio=0 tid=0x00000000202c7000 nid=0x4aac waiting on condition [0x0000000020a2f000]
   java.lang.Thread.State: TIMED_WAITING (parking)
        at sun.misc.Unsafe.park(Native Method)
        - parking to wait for  <0x000000076f418190> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
        at java.util.concurrent.locks.LockSupport.parkNanos(Unknown Source)
        at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(Unknown Source)
        at java.util.concurrent.LinkedBlockingQueue.poll(Unknown Source)
        at io.netty.util.concurrent.SingleThreadEventExecutor.takeTask(SingleThreadEventExecutor.java:251)
        at io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:52)
        at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:905)
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
        at java.lang.Thread.run(Unknown Source)

   Locked ownable synchronizers:
        - None

"s0-admin-0" #13 prio=5 os_prio=0 tid=0x00000000202b5800 nid=0x4158 waiting on condition [0x000000002072e000]
   java.lang.Thread.State: WAITING (parking)
        at sun.misc.Unsafe.park(Native Method)
        - parking to wait for  <0x000000076f420180> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
        at java.util.concurrent.locks.LockSupport.park(Unknown Source)
        at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(Unknown Source)
        at java.util.concurrent.LinkedBlockingQueue.take(Unknown Source)
        at io.netty.util.concurrent.SingleThreadEventExecutor.takeTask(SingleThreadEventExecutor.java:238)
        at io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:52)
        at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:905)
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
        at java.lang.Thread.run(Unknown Source)

   Locked ownable synchronizers:
        - None

"Service Thread" #10 daemon prio=9 os_prio=0 tid=0x000000001eb95000 nid=0x2b30 runnable [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
        - None

"C1 CompilerThread3" #9 daemon prio=9 os_prio=2 tid=0x000000001eb11800 nid=0x1948 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
        - None

"C2 CompilerThread2" #8 daemon prio=9 os_prio=2 tid=0x000000001eb05800 nid=0x56c waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
        - None

"C2 CompilerThread1" #7 daemon prio=9 os_prio=2 tid=0x000000001eafd800 nid=0x4a04 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
        - None

"C2 CompilerThread0" #6 daemon prio=9 os_prio=2 tid=0x000000001eafa800 nid=0x1e0c waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
        - None

"Attach Listener" #5 daemon prio=5 os_prio=2 tid=0x000000001eaf8800 nid=0x34c4 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
        - None

"Signal Dispatcher" #4 daemon prio=9 os_prio=2 tid=0x000000001cc1e000 nid=0x36f0 runnable [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
        - None

"Finalizer" #3 daemon prio=8 os_prio=1 tid=0x000000000319e800 nid=0x4acc in Object.wait() [0x000000001efce000]
   java.lang.Thread.State: WAITING (on object monitor)
        at java.lang.Object.wait(Native Method)
        - waiting on <0x000000076f438180> (a java.lang.ref.ReferenceQueue$Lock)
        at java.lang.ref.ReferenceQueue.remove(Unknown Source)
        - locked <0x000000076f438180> (a java.lang.ref.ReferenceQueue$Lock)
        at java.lang.ref.ReferenceQueue.remove(Unknown Source)
        at java.lang.ref.Finalizer$FinalizerThread.run(Unknown Source)

   Locked ownable synchronizers:
        - None

"Reference Handler" #2 daemon prio=10 os_prio=2 tid=0x0000000003195000 nid=0x4118 in Object.wait() [0x000000001eace000]
   java.lang.Thread.State: WAITING (on object monitor)
        at java.lang.Object.wait(Native Method)
        - waiting on <0x000000076f430468> (a java.lang.ref.Reference$Lock)
        at java.lang.Object.wait(Unknown Source)
        at java.lang.ref.Reference.tryHandlePending(Unknown Source)
        - locked <0x000000076f430468> (a java.lang.ref.Reference$Lock)
        at java.lang.ref.Reference$ReferenceHandler.run(Unknown Source)

   Locked ownable synchronizers:
        - None

"main" #1 prio=5 os_prio=0 tid=0x00000000011be000 nid=0x3c90 waiting on condition [0x000000000301f000]
   java.lang.Thread.State: TIMED_WAITING (sleeping)
        at java.lang.Thread.sleep(Native Method)
        at bug.Demo_4_0_0.main(Demo_4_0_0.java:14)

   Locked ownable synchronizers:
        - None

"VM Thread" os_prio=2 tid=0x000000001cc0a000 nid=0x17c8 runnable

"GC task thread#0 (ParallelGC)" os_prio=0 tid=0x00000000030b7800 nid=0x4b9c runnable

"GC task thread#1 (ParallelGC)" os_prio=0 tid=0x00000000030b9800 nid=0x9c8 runnable

"GC task thread#2 (ParallelGC)" os_prio=0 tid=0x00000000030bb000 nid=0x46e8 runnable

"GC task thread#3 (ParallelGC)" os_prio=0 tid=0x00000000030bd000 nid=0x3234 runnable

"GC task thread#4 (ParallelGC)" os_prio=0 tid=0x00000000030be800 nid=0x3160 runnable

"GC task thread#5 (ParallelGC)" os_prio=0 tid=0x00000000030bf800 nid=0xc20 runnable

"GC task thread#6 (ParallelGC)" os_prio=0 tid=0x00000000030c3800 nid=0x4298 runnable

"GC task thread#7 (ParallelGC)" os_prio=0 tid=0x00000000030c5000 nid=0x429c runnable

"VM Periodic Task Thread" os_prio=2 tid=0x000000001ebaf000 nid=0x4a20 waiting on condition

JNI global references: 664

Body:
I looked into this a little bit today as we've had several reports of this happening now (JAVA-2264).

It appears this is caused by the fact that there is some special logic in netty's HashedWheelTimer timer code to round sleep duration to a factor of 10:

// Check if we run on windows, as if thats the case we will need
// to round the sleepTime as workaround for a bug that only affect
// the JVM if it runs on windows.
//
// See https://github.com/netty/netty/issues/356
if (PlatformDependent.isWindows()) {
    sleepTimeMs = sleepTimeMs / 10 * 10;
}

Typically, this would be ok, however the java driver by default configures HashedWheelTimers tick duration to 1ms.  As sleepTimeMs is a long, my guess is we're sleeping in a tight loop as 1/10*10 = 0.

We will find a solution for this in the driver, whether it be adjusting the default tick duration overall (maybe 1ms is too aggressive), or just for windows.

Until then you can work around this in one of two ways:

Pass in the system property -Ddatastax-java-driver.advanced.netty.timer.tick-duration="100 millseconds" to your application

Set datastax-java-driver.advanced.netty.timer.tick-duration=100 millseconds in application.conf


问:
NodeJS environment variables on Google App Engine and Travis CI
I have nodejs app and using Travis CI for Continuous Integration (run tests and code linting by eslint). In my project, I'm using some environments variables in .env file (jwt key, mongodb credentials etc.)

Now I want to setup Continuous Deployment after merging development branch into master. For this, I've already investigated Travis docs and other guides which found on google and made some setup. My .travis.yml file:

```<code>language: node_js
node_js: lts/*

cache:
  directories:
  - node_modules

script:
- yarn install
- yarn test
- yarn lint

notifications:
  email: false

deploy:
  provider: gae
  project: gae-project-name
  skip_cleanup: true
  keyfile: gae.json
  on: master

env:
  global:
  - secure: FlwzKDN8HXl1cuGBhtQwbm/GjbOVMcLfEhcJkKky+2aGIhe4BOSxjMynrCts7eM53a87GMnyJXsmFxKOeO+w8RYqHVixD77duejV2o+XkoZL1QWORqiSMyK8dvLNc+lqoJ1Lf+qFqOOQCq1TxJ4W5ycFs82/hJMlMuu8jf2fxGhENoDwcARivZ0Fsrq/4/JA+YS3JjG6dqr78M7VwhrKv4mk4M5wMHiacHpKPhHib56v//wwUtsgYnyVLV0n+CPBlm6yh2aWbESt+YLU4uar39gumpG5bzp4+F01qDrWQwi3ctArOYZ5sKHgSfHZDP4jOEcKF4pYWoUlMqkT1vInmK27jnoiiCjZzQ6sfLw2O8eTb104Rlbgae4ttY38KWNE5N5w37DvSV5VzkAZ5xJuXb4j+GF/YmDep5tKNFKgjyUkFeNb7gXY/9INaJlCMiw6guQ6dYRoQlHCbv43jLnxy75E5PHPKMKHkZEi1nfvCKBYgJhIZxZ1PEjWyrupvnt+eyV0IxC7e9vCr/Ih8GkUEPa/uFVHAhDzr5x11OxQogOlSbh+G1kytUS2LhUyxqnQeFwo0DZACML/GPW41r2iXmIwI+SZzSVuT/01ZTRJNiS56UfnncI/+q5rbHR/1muTArnEqbeCISOP0YN2cBF4MefelXuNmjy2IJop56vea/U=
  ...other variables
</code>```

Such config works well: if no errors occurred during test and lint commands, project deploys to Google App Engine.

But I faced with a problem: I can not safely export my env. variables to GAE build during CI process, as for build it takes files from master repo where .env is absent (files with sensitive data is in .gitignore). So although the app is deployed, it doesn't work as env. variables are absent.

I didn't find a way how I can safely export my environment variables to GAE with Travis CI and hope for your assistance.

P.S. as you may notice I've already encrypted my env. variables in .travis.yml. I made it for running tests which used environment details. But I don't know how to export them to GAE build process.

答:
there are few ways of dealing with this issue. I prefer ENV vars in the ci, cating them into the directory and removing afterward.

```<code> echo "$ENV_DEVELOP" > ./.env
 echo $APP_ENGINE_TEST_KEY > /tmp/$CI_PIPELINE_ID.json
</code>```

execute something like this during pipe, and then remove this after deploying process from the system

```<code> rm /tmp/$CI_PIPELINE_ID.json
 rm ./.env
</code>```

also, if you don't want to store creds anywhere in envs of the pipes, you can create base https server that will retrieve env exemplar for you on request with auth for commit hash.

You can create a hook for push event, and on push send commit hash to your server and store it in some file, afterwards, when the time of getting env came, curl from your pipeline directly to the server with deployment_commit_hash as authorization, and check saved values:) have a nice day ^_^

Body:
I have nodejs app and using Travis CI for Continuous Integration (run tests and code linting by eslint). In my project, I'm using some environments variables in .env file (jwt key, mongodb credentials etc.)

Now I want to setup Continuous Deployment after merging development branch into master. For this, I've already investigated Travis docs and other guides which found on google and made some setup. My .travis.yml file:

language: node_js
node_js: lts/*

cache:
  directories:
  - node_modules

script:
- yarn install
- yarn test
- yarn lint

notifications:
  email: false

deploy:
  provider: gae
  project: gae-project-name
  skip_cleanup: true
  keyfile: gae.json
  on: master

env:
  global:
  - secure: FlwzKDN8HXl1cuGBhtQwbm/GjbOVMcLfEhcJkKky+2aGIhe4BOSxjMynrCts7eM53a87GMnyJXsmFxKOeO+w8RYqHVixD77duejV2o+XkoZL1QWORqiSMyK8dvLNc+lqoJ1Lf+qFqOOQCq1TxJ4W5ycFs82/hJMlMuu8jf2fxGhENoDwcARivZ0Fsrq/4/JA+YS3JjG6dqr78M7VwhrKv4mk4M5wMHiacHpKPhHib56v//wwUtsgYnyVLV0n+CPBlm6yh2aWbESt+YLU4uar39gumpG5bzp4+F01qDrWQwi3ctArOYZ5sKHgSfHZDP4jOEcKF4pYWoUlMqkT1vInmK27jnoiiCjZzQ6sfLw2O8eTb104Rlbgae4ttY38KWNE5N5w37DvSV5VzkAZ5xJuXb4j+GF/YmDep5tKNFKgjyUkFeNb7gXY/9INaJlCMiw6guQ6dYRoQlHCbv43jLnxy75E5PHPKMKHkZEi1nfvCKBYgJhIZxZ1PEjWyrupvnt+eyV0IxC7e9vCr/Ih8GkUEPa/uFVHAhDzr5x11OxQogOlSbh+G1kytUS2LhUyxqnQeFwo0DZACML/GPW41r2iXmIwI+SZzSVuT/01ZTRJNiS56UfnncI/+q5rbHR/1muTArnEqbeCISOP0YN2cBF4MefelXuNmjy2IJop56vea/U=
  ...other variables

Such config works well: if no errors occurred during test and lint commands, project deploys to Google App Engine.

But I faced with a problem: I can not safely export my env. variables to GAE build during CI process, as for build it takes files from master repo where .env is absent (files with sensitive data is in .gitignore). So although the app is deployed, it doesn't work as env. variables are absent.

I didn't find a way how I can safely export my environment variables to GAE with Travis CI and hope for your assistance.

P.S. as you may notice I've already encrypted my env. variables in .travis.yml. I made it for running tests which used environment details. But I don't know how to export them to GAE build process.

Body:
there are few ways of dealing with this issue. I prefer ENV vars in the ci, cating them into the directory and removing afterward.

 echo "$ENV_DEVELOP" > ./.env
 echo $APP_ENGINE_TEST_KEY > /tmp/$CI_PIPELINE_ID.json

execute something like this during pipe, and then remove this after deploying process from the system

 rm /tmp/$CI_PIPELINE_ID.json
 rm ./.env

also, if you don't want to store creds anywhere in envs of the pipes, you can create base https server that will retrieve env exemplar for you on request with auth for commit hash.

You can create a hook for push event, and on push send commit hash to your server and store it in some file, afterwards, when the time of getting env came, curl from your pipeline directly to the server with deployment_commit_hash as authorization, and check saved values:) have a nice day ^_^


问:
How to send variable with the guzzle post method
I have an API and I need to send some data to it and I am using guzzle for handling it so here is my code:

```<code>$amount = $request->get('amount');
    $client = new \GuzzleHttp\Client();
    $requestapi = $client->post('http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber', [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => '{
        "Amount":"i want to send $amount here",
        "something":"1",
        "Description":"desc",
        }'
    ]);
</code>```

so every thing is fine and static data is being send but I want to know how can I send a variable.

答:
You can try to use Guzzle json option:

```<code>$amount = $request->get('amount');

$client = new \GuzzleHttp\Client();

$response = $client->post(
    'http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber',
    [
        GuzzleHttp\RequestOptions::JSON => [
            'Amount' => $amount,
            'something' => '1',
            'Description' => 'desc',
        ]
    ]
);
</code>```

Check Guzzle manual - http://docs.guzzlephp.org/en/stable/request-options.html#json

Body:
I have an API and I need to send some data to it and I am using guzzle for handling it so here is my code:

$amount = $request->get('amount');
    $client = new \GuzzleHttp\Client();
    $requestapi = $client->post('http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber', [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => '{
        "Amount":"i want to send $amount here",
        "something":"1",
        "Description":"desc",
        }'
    ]);

so every thing is fine and static data is being send but I want to know how can I send a variable.

Body:
You can try to use Guzzle json option:

$amount = $request->get('amount');

$client = new \GuzzleHttp\Client();

$response = $client->post(
    'http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber',
    [
        GuzzleHttp\RequestOptions::JSON => [
            'Amount' => $amount,
            'something' => '1',
            'Description' => 'desc',
        ]
    ]
);

Check Guzzle manual - http://docs.guzzlephp.org/en/stable/request-options.html#json


问:
Debounce functionality for multiple checkboxes in Angular
I am trying to apply debounce time for multiple check boxes in Angular 7. The idea is to delay the api calls for x seconds in order to have better performing application (checking/unchecking the checkboxes invokes a call to the API).

Each checkbox corresponds to a filter which is sent to the backend when checked/unchecked and that determines the result returned from the server. I have tried using a custom debounce directive suggested in the article mentioned here,
https://coryrylan.com/blog/creating-a-custom-debounce-click-directive-in-angular

The problem addresses debounce for a single input field, in my case if I check and uncheck a single checkbox multiple times within the debounce time, only of call to the backend is made no matter how many times I click it. But my problem is with checking/unchecking multiple checkboxes and have only one request made to the API with in the debounce time.
Right now a call to the api is made every time I click on the checkbox which does not address my issue.

Following is the directive I am using which is similar to the example in the article:

```<code>import { Output, EventEmitter, OnInit, OnDestroy, Directive, ElementRef  } from '@angular/core';
import { debounceTime } from 'rxjs/operators';
import { HostListener } from '@angular/core';
import { Subscription, Subject } from 'rxjs';

@Directive({
  selector: '[appDebounceClick]'
})
export class DebounceDirective implements OnInit, OnDestroy{

  @Output() debounceClick = new EventEmitter();
  private clicks = new Subject();
  private subscription: Subscription;

  constructor(private elementRef: ElementRef) { }

  ngOnInit() {
    this.subscription = this.clicks.pipe(
      debounceTime(2000)
    ).subscribe(e => this.debounceClick.emit(e));
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

  @HostListener('change', ['$event'])
    clickEvent(event) {
    this.clicks.next(event);
  }
}
</code>```

Following is the code in my template:

```<code><ng-container *ngFor="let checkbox of checkboxList">
  <mat-checkbox *ngIf="checkbox.name == 'test'"  [(ngModel)]="checkbox.selected" appDebounceClick (debounceClick)="onChange($event,checkbox)" >
    {{checkbox.name}}
  </mat-checkbox>
</ng-container>
</code>```

I feel the issue here is the Directive is applied to every checkbox which in turn creates a new Observable/Subject which only associated with an individual checkbox . I think there should be just one Subject to which the click events on the checkboxes be subscribes to, but I am not entirely sure how to implement that. Would appreciate any thoughts on this issue or any better ideas on solving this problem.

答:
You can use a Service to centralize the Subject, obviously the Service has to be Singleton so that all the checkboxes emits to one Subject and the debounceTime operator acts for all elements.

On the other hand, you can implement the same behavior but in the parent component, I mean, the Subject has to be placed in the parent component.

The decision depends on reusability matters.

Body:
I am trying to apply debounce time for multiple check boxes in Angular 7. The idea is to delay the api calls for x seconds in order to have better performing application (checking/unchecking the checkboxes invokes a call to the API).

Each checkbox corresponds to a filter which is sent to the backend when checked/unchecked and that determines the result returned from the server. I have tried using a custom debounce directive suggested in the article mentioned here,
https://coryrylan.com/blog/creating-a-custom-debounce-click-directive-in-angular

The problem addresses debounce for a single input field, in my case if I check and uncheck a single checkbox multiple times within the debounce time, only of call to the backend is made no matter how many times I click it. But my problem is with checking/unchecking multiple checkboxes and have only one request made to the API with in the debounce time.
Right now a call to the api is made every time I click on the checkbox which does not address my issue.

Following is the directive I am using which is similar to the example in the article:

import { Output, EventEmitter, OnInit, OnDestroy, Directive, ElementRef  } from '@angular/core';
import { debounceTime } from 'rxjs/operators';
import { HostListener } from '@angular/core';
import { Subscription, Subject } from 'rxjs';

@Directive({
  selector: '[appDebounceClick]'
})
export class DebounceDirective implements OnInit, OnDestroy{

  @Output() debounceClick = new EventEmitter();
  private clicks = new Subject();
  private subscription: Subscription;

  constructor(private elementRef: ElementRef) { }

  ngOnInit() {
    this.subscription = this.clicks.pipe(
      debounceTime(2000)
    ).subscribe(e => this.debounceClick.emit(e));
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

  @HostListener('change', ['$event'])
    clickEvent(event) {
    this.clicks.next(event);
  }
}

Following is the code in my template:

<ng-container *ngFor="let checkbox of checkboxList">
  <mat-checkbox *ngIf="checkbox.name == 'test'"  [(ngModel)]="checkbox.selected" appDebounceClick (debounceClick)="onChange($event,checkbox)" >
    {{checkbox.name}}
  </mat-checkbox>
</ng-container>

I feel the issue here is the Directive is applied to every checkbox which in turn creates a new Observable/Subject which only associated with an individual checkbox . I think there should be just one Subject to which the click events on the checkboxes be subscribes to, but I am not entirely sure how to implement that. Would appreciate any thoughts on this issue or any better ideas on solving this problem.


问:
How to create an empty folder on Google Storage with Google API?
How to create an empty folder on Google Storage with Google API? (Assume that / is path separator.)

答:
Thank you for the Question and the chosen  Best answer.
Here is a code snippet that I wrote:
Python Method:

```<code>def create_folder(bucket_name, destination_folder_name):
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(destination_folder_name)

    blob.upload_from_string('')

    print('Created {} .'.format(
        destination_folder_name))
</code>```

main code that calls the method:

```<code>folder = create_folder(bucket_name, 'test-folder/')
</code>```

Body:
Thank you for the Question and the chosen  Best answer.
Here is a code snippet that I wrote:
Python Method:

def create_folder(bucket_name, destination_folder_name):
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(destination_folder_name)

    blob.upload_from_string('')

    print('Created {} .'.format(
        destination_folder_name))

main code that calls the method:

folder = create_folder(bucket_name, 'test-folder/')


问:
How to specify a generic type in a namespace by parameter value
I have a function that pulls a row from a database.

```<code>function row<T>(table:string, id:number):Promise<T|null>
{
   //For simplicity's sake
   return await Db(`SELECT * FROM ${table} WHERE id = ${id}`)
}
</code>```

And also type definitions for tables in a namespace

```<code>export namespace Table
{
   export type office = {
      id:number
      location:string
   }

   export type person = {
      id:number
      name:string
      office:number
   }
}
</code>```

Currently I run it with a generic type passed,

```<code>const person = row<Table.person>('person', 1)
</code>```

which would give person with the type of Table.person but how can I make it a generic using the parameter's string value?

I was hoping something like this could be achieved, so that it will pull the type definition from the 'Table' namespace by the 'table' string parameter.

```<code>function row(table:string, id:number):Promise<Table[table]|null>
</code>```

答:
TypeScript namespaces have limitations on the type operations we can perform. If we try type operations on a namespace, the compiler will tell us that we cannot use a namespace as a type nor a value.

Here is a workaround that manually converts the Table namespace into a TableMap type so that we can do type operations with it.

Someone with more TypeScript experience than I have might be able to improve this workaround by generating the Tables type instead of creating it manually.

```<code>namespace Table {
  export type office = {
    id: number
    location: string
  }
  export type person = {
    id: number
    name: string
    office: number
  }
}

type TableMap = {
  'office': Table.office,
  'person': Table.person,
};

type TableKey = keyof TableMap;

function row<Key extends TableKey>(table: Key, id: number): Promise<TableMap[Key] | null> {
  return null;
}

const result = row('person', 1)
</code>```

Here it is in the playground, which demonstrates that the result if of type Promise
.

Body:
I have a function that pulls a row from a database.

function row<T>(table:string, id:number):Promise<T|null>
{
   //For simplicity's sake
   return await Db(`SELECT * FROM ${table} WHERE id = ${id}`)
}

And also type definitions for tables in a namespace

export namespace Table
{
   export type office = {
      id:number
      location:string
   }

   export type person = {
      id:number
      name:string
      office:number
   }
}

Currently I run it with a generic type passed,

const person = row
('person', 1)

which would give person with the type of Table.person but how can I make it a generic using the parameter's string value?

I was hoping something like this could be achieved, so that it will pull the type definition from the 'Table' namespace by the 'table' string parameter.

function row(table:string, id:number):Promise

Body:
TypeScript namespaces have limitations on the type operations we can perform. If we try type operations on a namespace, the compiler will tell us that we cannot use a namespace as a type nor a value.

Here is a workaround that manually converts the Table namespace into a TableMap type so that we can do type operations with it.

Someone with more TypeScript experience than I have might be able to improve this workaround by generating the Tables type instead of creating it manually.

namespace Table {
  export type office = {
    id: number
    location: string
  }
  export type person = {
    id: number
    name: string
    office: number
  }
}

type TableMap = {
  'office': Table.office,
  'person': Table.person,
};

type TableKey = keyof TableMap;

function row<Key extends TableKey>(table: Key, id: number): Promise<TableMap[Key] | null> {
  return null;
}

const result = row('person', 1)

Here it is <a href="https://www.typescriptlang.org/play/#src=namespace%20Table%20%7B%0D%0A%20%20export%20type%20office%20%3D%20%7B%0D%0A%20%20%20%20id%3A%20number%0D%0A%20%20%20%20location%3A%20string%0D%0A%20%20%7D%0D%0A%20%20export%20type%20person%20%3D%20%7B%0D%0A%20%20%20%20id%3A%20number%0D%0A%20%20%20%20name%3A%20string%0D%0A%20%20%20%20office%3A%20number%0D%0A%20%20%7D%0D%0A%7D%0D%0A%0D%0Atype%20TableMap%20%3D%20%7B%0D%0A%20%20'office'%3A%20Table.office%2C%0D%0A%20%20'person'%3A%20Table.person%2C%0D%0A%7D%3B%0D%0A%0D%0Atype%20TableKey%20%3D%20keyof%20TableMap%3B%0D%0A%0D%0Afunction%20row%3CKey%20extends%20TableKey%3E(table%3A%20Key%2C%20id%3A%20number)%3A%20Promise%3CTableMap%5BKey%5D%20%7C%20null%3E%20%7B%0D%0A%20%20return%20null%3B%0D%0A%7D%0D%0A%0D%0Aconst%20result%20%3D%20row('person'%2C%201)" rel="nofollow noreferrer">in the playground, which demonstrates that the result if of type Promise<Table.person>.


问:
How to run TTask multiple times in parallel?
I've a simple method that use TTask method to perform a long time operation calling a datasnap server.

The method below does the job:

```<code>procedure AssignPhoto(PhotoName, Folder: string; Image: TImage);
var
   Server: TSMClient;
   Size: Int64;
begin
  Server := TSMClient.Create(dmDados.DSRestConnection1);
  Size := 0;
  TTask.Run(
  procedure
  var
    PhotoStream: TStream;
  begin
    { 1. Long time operation calls datasnap to get a stream }
    PhotoStream := Server.DownloadFile(PhotoName, Folder, Size);

    { 2. Get the result in the UI Thread and display the picture }
    TThread.Synchronize(nil,
    procedure
    begin
      Image.Picture.LoadFromStream(PhotoStream);
      FreeAndNil(Server);
    end);

  end);
end;
</code>```

As you can see, this just call a datasnap server to get a TStream picture and load it into a TImage that was passed as a parameter.

The method works well, however, the problem is: if I call this method twice it doesn't work.

I call this method twice to load user's profile photo and user's id photo as the code below suggest.

```<code>  if FUrlProfile <> '' then
    AssignPhoto(FUrlProfile, PROFILE_PHOTO, imgProfile);
  if FUrlDoc <> '' then
    AssignPhoto(FUrlDoc, DOC_PHOTO, imgDoc);
</code>```

This opens a form and load the pictures in two TImage components.

The first time I open the form it works pretty well;

When I try to open the form again. The second time I try to open the form I get the error:

ENetHTTPRequestException with message 'Error adding header: (87) Incorrect Parameter'

I know that,

If I load only one picture it works pretty well all the time.

If I open the form, close and open again really fast it causes the error.

If I open the form, close, wait for a while and open it again it doesn't cause the error. It seams it needs to get something done before starting the procedure again.

So the problem is that it seams I can't call the TTask method multiple times. Maybe, am I missing something?

答:
@J... was correct in his comment. The problem was because I was using the same TDSRestConnection in multiple threads.

So, creating a TDSRestConnection each time the method was created is the solution.

```<code>procedure AssignPhoto(PhotoName, Folder: string; Image: TImage);
var
  Server: TSMClient;
  Size: Int64;
  DSRestConnection: TDSRestConnection;
begin
  DSRestConnection := GetConnection; // Creates a new TDSRestConnection
  Server := TSMClient.Create(DSRestConnection);
  Size := 0;
  TTask.Run(
  procedure
  var
    PhotoStream: TStream;
  begin
    { 1. Long time operation calls datasnap to get a stream }
    PhotoStream := Server.DownloadFile(PhotoName, Folder, Size);

    { 2. Get the result in the UI Thread and display the picture }
    TThread.Synchronize(nil,
    procedure
    begin
      Image.Picture.LoadFromStream(PhotoStream);
      FreeAndNil(Server);
    end);

  end);
end;

function GetConnection: TDSRestConnection;
begin
  Result := TDSRestConnection.Create(nil);
  Result.Host := SERVER_HOST;
  Result.Port := SERVER_PORT;
end;
</code>```

Body:
I've a simple method that use TTask method to perform a long time operation calling a datasnap server.

The method below does the job:

procedure AssignPhoto(PhotoName, Folder: string; Image: TImage);
var
   Server: TSMClient;
   Size: Int64;
begin
  Server := TSMClient.Create(dmDados.DSRestConnection1);
  Size := 0;
  TTask.Run(
  procedure
  var
    PhotoStream: TStream;
  begin
    { 1. Long time operation calls datasnap to get a stream }
    PhotoStream := Server.DownloadFile(PhotoName, Folder, Size);

    { 2. Get the result in the UI Thread and display the picture }
    TThread.Synchronize(nil,
    procedure
    begin
      Image.Picture.LoadFromStream(PhotoStream);
      FreeAndNil(Server);
    end);

  end);
end;

As you can see, this just call a datasnap server to get a TStream picture and load it into a TImage that was passed as a parameter.

The method works well, however, the problem is: if I call this method twice it doesn't work.

I call this method twice to load user's profile photo and user's id photo as the code below suggest.

  if FUrlProfile <> '' then
    AssignPhoto(FUrlProfile, PROFILE_PHOTO, imgProfile);
  if FUrlDoc <> '' then
    AssignPhoto(FUrlDoc, DOC_PHOTO, imgDoc);

This opens a form and load the pictures in two TImage components.

The first time I open the form it works pretty well;

When I try to open the form again. The second time I try to open the form I get the error:

ENetHTTPRequestException with message 'Error adding header: (87) Incorrect Parameter'

I know that,

If I load only one picture it works pretty well all the time.

If I open the form, close and open again really fast it causes the error.

If I open the form, close, wait for a while and open it again it doesn't cause the error. It seams it needs to get something done before starting the procedure again.

So the problem is that it seams I can't call the TTask method multiple times. Maybe, am I missing something?

Body:
@J... was correct in his comment. The problem was because I was using the same TDSRestConnection in multiple threads.

So, creating a TDSRestConnection each time the method was created is the solution.

procedure AssignPhoto(PhotoName, Folder: string; Image: TImage);
var
  Server: TSMClient;
  Size: Int64;
  DSRestConnection: TDSRestConnection;
begin
  DSRestConnection := GetConnection; // Creates a new TDSRestConnection
  Server := TSMClient.Create(DSRestConnection);
  Size := 0;
  TTask.Run(
  procedure
  var
    PhotoStream: TStream;
  begin
    { 1. Long time operation calls datasnap to get a stream }
    PhotoStream := Server.DownloadFile(PhotoName, Folder, Size);

    { 2. Get the result in the UI Thread and display the picture }
    TThread.Synchronize(nil,
    procedure
    begin
      Image.Picture.LoadFromStream(PhotoStream);
      FreeAndNil(Server);
    end);

  end);
end;

function GetConnection: TDSRestConnection;
begin
  Result := TDSRestConnection.Create(nil);
  Result.Host := SERVER_HOST;
  Result.Port := SERVER_PORT;
end;


问:
Colour the x-values and show in legend instead of as ticks, in matplotlib (or seaborn)
I have a large df which I've grouped to plot in a bar chart.
I made this mock df to show what I mean. (And I had way too much fun creating it...)

```<code>my = pd.DataFrame(
{'names': ['Andrea', 'Donna', 'Kelly', 'Brenda', 'Allison', 'Jo', 'Amanda', 'Jane', 'Kerry', 'Abby', 'Elizabeth', 'Haleh'],
'episodes': [ 147, 292, 292, 111, 160, 111, 199, 172, 250, 189, 160,184 ],
'tv-show' : ['Beverly Hills, 90210', 'Beverly Hills, 90210', 'Beverly Hills, 90210', 'Beverly Hills, 90210',
'Melrose place', 'Melrose place', 'Melrose place', 'Melrose place',
'ER', 'ER', 'ER', 'ER']})
my
</code>```

And then I grouped and plotted it: my.groupby('tv-show').sum().plot(kind='bar', stacked = True)

What I would like is a plot where the names of the tv-shows are in a legend instead of under the x-axis and where the shows have different colours (of course).

答:
Directly using pandas:

```<code>ax = my.groupby('tv-show').sum().transpose().plot.bar()
ax.set_xticks([])
</code>```

Body:
I have a large df which I've grouped to plot in a bar chart.
I made this mock df to show what I mean. (And I had way too much fun creating it...)

my = pd.DataFrame(
{'names': ['Andrea', 'Donna', 'Kelly', 'Brenda', 'Allison', 'Jo', 'Amanda', 'Jane', 'Kerry', 'Abby', 'Elizabeth', 'Haleh'],
'episodes': [ 147, 292, 292, 111, 160, 111, 199, 172, 250, 189, 160,184 ],
'tv-show' : ['Beverly Hills, 90210', 'Beverly Hills, 90210', 'Beverly Hills, 90210', 'Beverly Hills, 90210',
'Melrose place', 'Melrose place', 'Melrose place', 'Melrose place',
'ER', 'ER', 'ER', 'ER']})
my

And then I grouped and plotted it: my.groupby('tv-show').sum().plot(kind='bar', stacked = True)

What I would like is a plot where the names of the tv-shows are in a legend instead of under the x-axis and where the shows have different colours (of course).

Body:
Directly using pandas:

ax = my.groupby('tv-show').sum().transpose().plot.bar()
ax.set_xticks([])


问:
BACnet Virtual Devices - never respond to a direct command
Some background:
I'm attempting to create a virtual BACnet router with virtual devices behind it (see related post).  My test environment consists of a VM ( 10.2.0.15 ) running on my server with a BACnet explorer and Wireshark running on it.  I'm writing the code in VS2013 and also running wireshark on my local machine ( 192.168.56.1 ).

When I start the virtual router and send a who-is broadcast from the VM, I see the command and responses on the wireshark running on the vm.  On my local machine, I only see the command in wireshark, but not the responses going out.

All of this works fine.  However, the source address of the i-am responses ( according to wireshark on the VM as well as in the BACnet explorer details ) is that of the gateway (10.2.0.2) between the VM and my machine.

The Problem
Subsequent who-is commands targeting a specific virtual device never get to my local machine.  I can see the command being created using wireshark on the vm, but my code never sees the request nor does wireshark on my local machine see a new packet.

The Question
Should the source address of the initial i-am responses be the IP of my local machine or the IP address that I've assigned to the virtual device?  As stated above, the source address is currently that of the gateway between the VM and my machine.

Here is the code I'm using to construct the NPDU portion of the response to a who-is command - Hopefully someone can point out what I'm doing incorrectly.

```<code>        bytes[pos++] = BACnetEnums.BACNET_PROTOCOL_VERSION;

        //Control byte determines what fields exist in the rest of the NPDU record
        bytes[pos++] = this.AssembleControl();  //in the case, the response is 0x28

        //Destination Network Info
        //65535 - Broadcast
        bytes[pos++] = 0xff;  //DNET
        bytes[pos++] = 0xff;  //DNET

        //Destination
        bytes[pos++] = 0x00;  //DLEN
                              //DADDR
        //none since len = 0 and this is being broadcasted back

        bytes[pos++] = 0x00;  //SNET
        bytes[pos++] = 0x00;  //SNET

        bytes[pos++] = 0x06;  //SLEN

        //address should be 10.1.0.xxx, where x is the deviceid
        bytes[pos++] = this.SADR[0];  //10
        bytes[pos++] = this.SADR[1];  //1
        bytes[pos++] = this.SADR[2];  //0
        bytes[pos++] = this.SADR[3];  //varies based on the ID of the device - pulled from database
        bytes[pos++] = 0xBA;
        bytes[pos++] = 0xC0;

        //HopCount
        bytes[pos++] = 0xff;
</code>```

答: One related comment worth making - for virtual devices; you might need to specify a DNET # & DADR - destination network number & destination (V-MAC) address.  And some devices can be fussy about having/receiving the DADR/MAC address as the right/specific length (of bytes, e.g. fussy about the number of left-hand/leading padding-zero bytes).</p>

Body:
Some background:
I'm attempting to create a virtual BACnet router with virtual devices behind it (see related post).  My test environment consists of a VM ( 10.2.0.15 ) running on my server with a BACnet explorer and Wireshark running on it.  I'm writing the code in VS2013 and also running wireshark on my local machine ( 192.168.56.1 ).

When I start the virtual router and send a who-is broadcast from the VM, I see the command and responses on the wireshark running on the vm.  On my local machine, I only see the command in wireshark, but not the responses going out.

All of this works fine.  However, the source address of the i-am responses ( according to wireshark on the VM as well as in the BACnet explorer details ) is that of the gateway (10.2.0.2) between the VM and my machine.

The Problem
Subsequent who-is commands targeting a specific virtual device never get to my local machine.  I can see the command being created using wireshark on the vm, but my code never sees the request nor does wireshark on my local machine see a new packet.

The Question
Should the source address of the initial i-am responses be the IP of my local machine or the IP address that I've assigned to the virtual device?  As stated above, the source address is currently that of the gateway between the VM and my machine.

Here is the code I'm using to construct the NPDU portion of the response to a who-is command - Hopefully someone can point out what I'm doing incorrectly.

        bytes[pos++] = BACnetEnums.BACNET_PROTOCOL_VERSION;

        //Control byte determines what fields exist in the rest of the NPDU record
        bytes[pos++] = this.AssembleControl();  //in the case, the response is 0x28

        //Destination Network Info
        //65535 - Broadcast
        bytes[pos++] = 0xff;  //DNET
        bytes[pos++] = 0xff;  //DNET

        //Destination
        bytes[pos++] = 0x00;  //DLEN
                              //DADDR
        //none since len = 0 and this is being broadcasted back

        bytes[pos++] = 0x00;  //SNET
        bytes[pos++] = 0x00;  //SNET

        bytes[pos++] = 0x06;  //SLEN

        //address should be 10.1.0.xxx, where x is the deviceid
        bytes[pos++] = this.SADR[0];  //10
        bytes[pos++] = this.SADR[1];  //1
        bytes[pos++] = this.SADR[2];  //0
        bytes[pos++] = this.SADR[3];  //varies based on the ID of the device - pulled from database
        bytes[pos++] = 0xBA;
        bytes[pos++] = 0xC0;

        //HopCount
        bytes[pos++] = 0xff;


问:
Can't get Resource from POST/PUT request (.NET FHIR client, web api 2)
When I try to send a POST / PUT request using .NET FHIR API to asp.net Web API 2 server, I get the error message:

Hl7.Fhir.Rest.FhirOperationException: the operation failed due to a

  client error (UnsupportedMediaType). The body has no content.

1) Do I need to create some kind of MediaType Handler / Formatter?

2) Is there an open source server in which code implements the best practices of the .NET FHIR API?

I looked at Fiddler, seems fhir client sends correct JSON in the body

```<code>fhirClient = new FhirClient(serverUrl);
fhirClient.PreferredFormat = ResourceFormat.Json;

Patient patient = new Patient();
//fill patient

    var response = fhirClient.Update(patient);
</code>```

...

// web api 2 server:
WebApiConfig.cs:

```<code>config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/fhir+json"));
</code>```

I tried:

```<code>[HttpPut]
public void Update([FromBody] Resource resource, string id = null)
{
// updating logic
}

//or
[HttpPut]
public void Update(Resource resource, string id = null)
{
// updating logic
}
</code>```

but, when I tried

```<code>[HttpPut]
public void Update([FromBody] object resource, string id = null)
{
</code>```

I can see inside "object" a deserialized Patient and use jsonParser to get it back

答:
There are a few options in this, including the open source fhir-net-web-api project on github.

There is a aspnetcore version, and an full framework owin version.
Check the sample project in there for how to use them. </p>

Body:
When I try to send a POST / PUT request using .NET FHIR API to asp.net Web API 2 server, I get the error message:

Hl7.Fhir.Rest.FhirOperationException: the operation failed due to a

  client error (UnsupportedMediaType). The body has no content.

1) Do I need to create some kind of MediaType Handler / Formatter?

2) Is there an open source server in which code implements the best practices of the .NET FHIR API?

I looked at Fiddler, seems fhir client sends correct JSON in the body

fhirClient = new FhirClient(serverUrl);
fhirClient.PreferredFormat = ResourceFormat.Json;

Patient patient = new Patient();
//fill patient

    var response = fhirClient.Update(patient);

...

// web api 2 server:
WebApiConfig.cs:

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/fhir+json"));

I tried:

[HttpPut]
public void Update([FromBody] Resource resource, string id = null)
{
// updating logic
}

//or
[HttpPut]
public void Update(Resource resource, string id = null)
{
// updating logic
}

but, when I tried

[HttpPut]
public void Update([FromBody] object resource, string id = null)
{

I can see inside "object" a deserialized Patient and use jsonParser to get it back


问:
Overlay Text on a Centered Image Which Is Smaller Than Its Containing Element
I have the following case:

Image which its width is less than the page width.

Image needs to be centered within its parent div (Which is wider).

Overlay text should be displayed on the image on one of its corners.

Image can not be stretched. Image will appear in its native size.

The image size can not be set in CSS as this template will be used for many images in different size.

So the code I came up with is given in https://jsfiddle.net/RoyiA/gdezys7j Or (Must be viewed in Full Screen so the image will be centered):

@font-face {font-family: "MammaGamma";
src: url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.eot");
src: url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.eot?#iefix") format("embedded-opentype"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.woff2") format("woff2"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.woff") format("woff"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.ttf") format("truetype"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.svg#MammaGamma") format("svg");
}

.image-container {
   position: relative;
   font-family: Arial;
}

.image-center{
position: relative;
display: block;
margin-left: auto;
margin-right: auto;
}

.image-text-block {
   position: absolute;
display: block;
   top: 100px;
   left: 10px;
   background-color: rgba(100, 100, 100, 0.5);
   color: white;
   padding-left: 10px;
   padding-right: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Image Text Blocks</h2>
<p>How to place text blocks over an image:</p>

<div class="image-container">
 <img class="image-center" src="https://i.imgur.com/0s8kLb7.png" alt="Nature">
   <div class="image-text-block">
     <h3>Created with <span style="font-family:MammaGamma; color:rgb(239, 74, 74)">Photoshop</span></h3>
     <p>Image: Jane by Mireille Lannoo</p>
   </div>
</div></code>```

The problem I'm having is that the text div is relative to the position of its parent div while the image is centered. How can address that?

答:
.image-container {
   position: relative;
   font-family: Arial;
    width:650px;
    margin: auto;
    }

.image-center{
 margin:auto;
  width: 100%;
}

.image-text-block {
   position: absolute;
   top: 10px;
   left: 10px;
   background-color: rgba(100, 100, 100, 0.5);
   color: white;
   padding:0 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Image Text Blocks</h2>
<p>How to place text blocks over an image:</p>

<div class="image-container">
 <img class="image-center" src="https://i.imgur.com/0s8kLb7.png" alt="Nature">
   <div class="image-text-block">
     <h3>Created with <span style="font-family:MammaGamma; color:rgb(239, 74, 74)">Photoshop</span></h3>
     <p>Image: Jane by Mireille Lannoo</p>
   </div>
</div>.</code>```

Your image container does not have a set width, and therefore will be the width of the screen unless you set a width. You are positioning the text to the top left corner of the container, not the image.

Body:
I have the following case:

Image which its width is less than the page width.

Image needs to be centered within its parent div (Which is wider).

Overlay text should be displayed on the image on one of its corners.

Image can not be stretched. Image will appear in its native size.

The image size can not be set in CSS as this template will be used for many images in different size.

So the code I came up with is given in https://jsfiddle.net/RoyiA/gdezys7j Or (Must be viewed in Full Screen so the image will be centered):

@font-face {font-family: "MammaGamma";
src: url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.eot");
src: url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.eot?#iefix") format("embedded-opentype"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.woff2") format("woff2"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.woff") format("woff"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.ttf") format("truetype"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.svg#MammaGamma") format("svg");
}

.image-container {
   position: relative;
   font-family: Arial;
}

.image-center{
position: relative;
display: block;
margin-left: auto;
margin-right: auto;
}

.image-text-block {
   position: absolute;
display: block;
   top: 100px;
   left: 10px;
   background-color: rgba(100, 100, 100, 0.5);
   color: white;
   padding-left: 10px;
   padding-right: 10px;
}

Image Text Blocks

How to place text blocks over an image:

Created with Photoshop

Image: Jane by Mireille Lannoo

The problem I'm having is that the text div is relative to the position of its parent div while the image is centered. How can address that?

Body:
.image-container {
   position: relative;
   font-family: Arial;
    width:650px;
    margin: auto;
    }

.image-center{
 margin:auto;
  width: 100%;
}

.image-text-block {
   position: absolute;
   top: 10px;
   left: 10px;
   background-color: rgba(100, 100, 100, 0.5);
   color: white;
   padding:0 10px;
}

<h2>Image Text Blocks</h2>
<p>How to place text blocks over an image:</p>

<div class="image-container">
 <img class="image-center" src="https://i.imgur.com/0s8kLb7.png" alt="Nature">
   <div class="image-text-block">
     <h3>Created with <span style="font-family:MammaGamma; color:rgb(239, 74, 74)">Photoshop</span></h3>
     <p>Image: <a href="https://www.flickr.com/photos/151740882@N05/47029584231">Jane</a> by Mireille Lannoo</p>
   </div>
</div>.

Your image container does not have a set width, and therefore will be the width of the screen unless you set a width. You are positioning the text to the top left corner of the container, not the image.


问:
on delphi/android how to draw a TbitmapSurface on a Canvas?
Under delphi (and under firemonkey/android), What is the most fastest way to draw on a Tcanvas a TbitmapSurface ?

I try to use TTexture like MyTexture.Assign(aBitmapSurface) and later do TCustomCanvasGpu(Canvas).DrawTexture but MyTexture.Assign(aBitmapSurface) have 2 main drawbacks :

it's must be done inside the main thread (i don't know why else we have black screen)

it's relatively slow operation

答:
TBitmapSurface is in system memory so you need to assign your TBitmapSurface to a TBitmap first, to be converted to native OS bitmap (or texture) format that FMX uses for drawing:

```<code>bmp.Assign(surf);
</code>```

Then draw the Bitmap to the canvas:

```<code>canvas.BeginScene();
canvas.DrawBitmap(bmp, SrcRect, DstRect, AOpacity);
canvas.EndScene();
</code>```

I have tested it on Windows and Android. On android you need to call the Repaint too see the change.

Body:
TBitmapSurface is in system memory so you need to assign your TBitmapSurface to a TBitmap first, to be converted to native OS bitmap (or texture) format that FMX uses for drawing:

bmp.Assign(surf);

Then draw the Bitmap to the canvas:

canvas.BeginScene();
canvas.DrawBitmap(bmp, SrcRect, DstRect, AOpacity);
canvas.EndScene();

I have tested it on Windows and Android. On android you need to call the Repaint too see the change.


问:
Reverse order of days auto-populated by macro that creates new sheet named 06/01, 06/02 and so on
I am trying to set up a macro that when run will auto-create new sheets with names of dates in chronological order. EX: 06/01, 06/02 and fill the cells with data from a "Template" sheet. The macro currently will create these sheets in reverse order such as 06/30, 06/29..etc. How do I make it start from 06/01...06/30 instead of 06/30...06/01 with the new named sheets created?

I have tried the code listed below. Along with changing the

Sheets("Temp").Range("d5").Value = Sheets("Temp").Range("a5") - X

to

Sheets("Temp").Range("d5").Value = Sheets("Temp").Range("a5") + X

Setting up the code in VB for Temp Sheet:

--Start--

```<code>Sub Dtpopulate()

Dim S As Integer
Dim X As Integer
S = Sheets("Temp").Range("c5").Value

For X = 1 To S

newname = Sheets("Temp").Range("a6").Value

Worksheets("Template").Activate
       Sheets("Template").Cells.Select
    Selection.Copy

Sheets.Add.Name = newname
        Sheets(newname).Cells.Select
    Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats,
Operation:= _
        xlNone, SkipBlanks:=False, Transpose:=False

    Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
        SkipBlanks:=False, Transpose:=False

Sheets("Temp").Range("d5").Value = Sheets("Temp").Range("a5") - X

Next X

End Sub
</code>```

--Finish--

I expected the sheets to be created and auto-filled with the data from "Templates" and each sheet to be named 06/01...06/30, but the output are sheets named 06/30 to 06/01.

答:
If you step through your code you will notice that the sheets are created in the proper order: they are just not organized in order.

You will want each new sheet to be situated behind the most recently created one. You can read the deets about creating a new sheet here. The bit of code form this link that answers your question is:

Sheets.Add(After:=Worksheets(Worksheets.Count))

Body:
I am trying to set up a macro that when run will auto-create new sheets with names of dates in chronological order. EX: 06/01, 06/02 and fill the cells with data from a "Template" sheet. The macro currently will create these sheets in reverse order such as 06/30, 06/29..etc. How do I make it start from 06/01...06/30 instead of 06/30...06/01 with the new named sheets created?

I have tried the code listed below. Along with changing the

Sheets("Temp").Range("d5").Value = Sheets("Temp").Range("a5") - X

to

Sheets("Temp").Range("d5").Value = Sheets("Temp").Range("a5") + X

Setting up the code in VB for Temp Sheet:

--Start--

Sub Dtpopulate()

Dim S As Integer
Dim X As Integer
S = Sheets("Temp").Range("c5").Value

For X = 1 To S

newname = Sheets("Temp").Range("a6").Value

Worksheets("Template").Activate
       Sheets("Template").Cells.Select
    Selection.Copy

Sheets.Add.Name = newname
        Sheets(newname).Cells.Select
    Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats,
Operation:= _
        xlNone, SkipBlanks:=False, Transpose:=False

    Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
        SkipBlanks:=False, Transpose:=False

Sheets("Temp").Range("d5").Value = Sheets("Temp").Range("a5") - X

Next X

End Sub

--Finish--

I expected the sheets to be created and auto-filled with the data from "Templates" and each sheet to be named 06/01...06/30, but the output are sheets named 06/30 to 06/01.


问:
jQuery/javascript text selector similar to iphone
im looking for a javascript/jquery plugin that will allow a user to select a word on a web page which once selected allows the user to drag a handle left/right if they want to expand the number of words they have selected. The iphone has exactly this when you double click on a word - does anyone know of such a tool?

Thanks in advance

Al

答: This is not possible because you need HTML rendering engine to handle text/element flow. That's why there is (miserable) selection API in HTML specs. I suggest rethinking your problem in a way that doesn't  need such UI component.</p>


问:
Backtracking and Meta Characters
I was reading a book about regex. There was a basic example which I failed to understand.

let's say I search /cat/

and the word camel comes up.

The book says first it matches c (c matches),then it goes to a (a matches ) then when m comes up it fails. Then, it will backtrack to a to try matching the pattern again. I fail to understand why does it backtrack to a and what pattern is it looking for.

The second question is about matching a number

/var[[(][0-9][\])] /

I failed to understand what this line of regex means. (What it's trying to search)

Which character sets are being escaped?

答:
Let's try going on your match step by step.

First, it will match ca perfectly, since it is present on both the pattern and the string. Note that this match starts at c.

Then, it will try to continue matching with cam. This does not match the pattern, so it fails. Since it failed, the engine has to try matching again, from a new starting position. It already tried starting at c, so, for the next try, it will move the cursor one character to the right, which is a. Note that this is the a on camel, not the a on /cat/.

BTW, the pattern it is looking for is cat. That is, after all, what you want it to find, isn't it?

Your second pattern has several parts:

var will match the string "var" literally.

[[(] will match either a [ or a (. Note that both of these don't need to be escaped, because they're inside a list match.

[0-9] will match any digits (more pedantically, any character between 0 and 9)

[\])] will match either a ] or a ). Note that the character ] needs to be escaped, because otherwise it would mean the end of the list, which we don't want.

Knowing this, the answer is simple: It will search for var followed by a single digit between brackets or parenthesis. Any of these would match:

var(0)
var[5]
var(3]
var[9)
```

Note that the last two are probably not what the author intended. Try to think how could we guarantee that a match of [ must always be followed by ], and the same for ( and ).

Title: Backtracking and Meta Characters

Body:
Let's try going on your match step by step.

First, it will match ca perfectly, since it is present on both the pattern and the string. Note that this match starts at c.

Then, it will try to continue matching with cam. This does not match the pattern, so it fails. Since it failed, the engine has to try matching again, from a new starting position. It already tried starting at c, so, for the next try, it will move the cursor one character to the right, which is a. Note that this is the a on camel, not the a on /cat/.

BTW, the pattern it is looking for is cat. That is, after all, what you want it to find, isn't it?

Your second pattern has several parts:

var will match the string "var" literally.

[[(] will match either a [ or a (. Note that both of these don't need to be escaped, because they're inside a list match.

[0-9] will match any digits (more pedantically, any character between 0 and 9)

[\])] will match either a ] or a ). Note that the character ] needs to be escaped, because otherwise it would mean the end of the list, which we don't want.

Knowing this, the answer is simple: It will search for var followed by a single digit between brackets or parenthesis. Any of these would match:

var(0)
var[5]
var(3]
var[9)

Note that the last two are probably not what the author intended. Try to think how could we guarantee that a match of [ must always be followed by ], and the same for ( and ).