问:
How to access object from array of objects in Python
I have made a object called Protocol that takes in a port and protocol name. This object is then stored in an array. My question is how do i access my object in the array? Im coming from mostly doing Java and I can't quite figure it out. I keep getting error 'int' object has no attribute getPort.

Protocol.py Object/Model

```<code>class Protocol:
    def __init__(self, protocolName, port):
         self.protocolName = protocolName
         self.port = port

    def setPort(self, port):
        self.port = port

    def setProtocol(self,protocolName):
        self.protocolName = protocolName

    def getPort(self):
        return self.port

    def getProtocol(self):
        return self.protocolName
</code>```

JSONSlicer.py Where function is

```<code>from Model.Protocol import Protocol
from Model.Service import Service

class JSONSlicers:
    def protocolSeperator(self,protocols,num):
        protocolsFound = []   # Protocol port # odds, Protocol name # evens

        i=0
        for p in protocols:
            for sub in range(0,len(p.split('/')) - 1):
                #  protocol = Protocol(p.split('/')[sub])
                fPort = p.split('/')[sub]

                sub+=1
                fProto = p.split('/')[sub]
                #protocol = Protocol(p.split('/')[sub])
                protocol = Protocol(fPort,fProto)
                protocolsFound.append(protocol)

        print(protocolsFound[0].getPort()) # Trying to print attribute of object here

        return protocolsFound
</code>```

答:
It errors because you set the first index of protocolsFound to an in num

Take a look at this line an fix it,

```<code>protocolsFound = [num]
</code>```

why do you need the num in there?

Body:
I have made a object called Protocol that takes in a port and protocol name. This object is then stored in an array. My question is how do i access my object in the array? Im coming from mostly doing Java and I can't quite figure it out. I keep getting error 'int' object has no attribute getPort.

Protocol.py Object/Model

class Protocol:
    def __init__(self, protocolName, port):
         self.protocolName = protocolName
         self.port = port

    def setPort(self, port):
        self.port = port

    def setProtocol(self,protocolName):
        self.protocolName = protocolName

    def getPort(self):
        return self.port

    def getProtocol(self):
        return self.protocolName

JSONSlicer.py Where function is

from Model.Protocol import Protocol
from Model.Service import Service

class JSONSlicers:
    def protocolSeperator(self,protocols,num):
        protocolsFound = []   # Protocol port # odds, Protocol name # evens

        i=0
        for p in protocols:
            for sub in range(0,len(p.split('/')) - 1):
                #  protocol = Protocol(p.split('/')[sub])
                fPort = p.split('/')[sub]

                sub+=1
                fProto = p.split('/')[sub]
                #protocol = Protocol(p.split('/')[sub])
                protocol = Protocol(fPort,fProto)
                protocolsFound.append(protocol)

        print(protocolsFound[0].getPort()) # Trying to print attribute of object here

        return protocolsFound

Body:
It errors because you set the first index of protocolsFound to an in num

Take a look at this line an fix it,

protocolsFound = [num]

why do you need the num in there?


来源: stackexchange

问:
Fix JQuery Countdown Timer in Rails 3 Application
I need a countdown timer for a rails application I'm working on so I decided to use this.

http://keith-wood.name/countdown.html

In the public/javascripts folder I've added jquery.countdown.js
In the public/styleheets folder I've added jquery.countdown.css

In app/views/layouts/application.html.erb I add the javascript and css files to the stylesheet and javascript tags.

In my view I've added

```<code><script>
    var element = '#countDownTimer';
    var year = <%= @deal.end.year %>;
    var month = <%= @deal.end.month %>;
    var day = <%= @deal.end.day %>;
   setCountdownTimer(element, year, month, day);
</script>
<div id="countDownTimer"></div>
</code>```

which is going to be used to select with jQuery to add the timer.

Here is my application.js file

```<code>// The following function is called once the rest of the document is fully loaded
 $(document).ready(function()
 {

function setCountdownTimer(element, year, month, day) {
  var date = new Date(year, month, day);
  $(element).countdown({until: date});
}

// DEALS TABS ON DEALS PAGES
$("#tabs > ul").tabs(); // Make the tabs.

// FANCYBOX FOR GALLERY IMAGES POPUP
$("a.galleryitem").fancybox();

// MEDIA ENCODER FOR PODCASTS
$.mb_audioEmbedder.playerPath="/media/player.swf" //the path to audio player
    $.mb_videoEmbedder.defaults.width=500;
$.mb_audioEmbedder.defaults.width=214;
    $("#media").mb_embedMovies();
    $("#media").mb_embedAudio();

});
</code>```

Can anyone tell me why this doesn't work?

答:
Try wrapping

```<code>   var element = '#countDownTimer';
   var year = <%= @deal.end.year %>;
   var month = <%= @deal.end.month %>;
   var day = <%= @deal.end.day %>;
   setCountdownTimer(element, year, month, day);
</code>```

inside a $(document).ready()

also I don't think this needs to be in the $(document).ready()

```<code>function setCountdownTimer(element, year, month, day) {
  var date = new Date(year, month, day);
  $(element).countdown({until: date});
}
</code>```

The issue is probably that your calling setCountdownTimer before its defined

ContentLicense: CC BY-SA 3.0

Body:
I need a countdown timer for a rails application I'm working on so I decided to use this.

http://keith-wood.name/countdown.html

In the public/javascripts folder I've added jquery.countdown.js
In the public/styleheets folder I've added jquery.countdown.css

In app/views/layouts/application.html.erb I add the javascript and css files to the stylesheet and javascript tags.

In my view I've added

which is going to be used to select with jQuery to add the timer.

Here is my application.js file

// The following function is called once the rest of the document is fully loaded
 $(document).ready(function()
 {

function setCountdownTimer(element, year, month, day) {
  var date = new Date(year, month, day);
  $(element).countdown({until: date});
}

// DEALS TABS ON DEALS PAGES
$("#tabs > ul").tabs(); // Make the tabs.

// FANCYBOX FOR GALLERY IMAGES POPUP
$("a.galleryitem").fancybox();

// MEDIA ENCODER FOR PODCASTS
$.mb_audioEmbedder.playerPath="/media/player.swf" //the path to audio player
    $.mb_videoEmbedder.defaults.width=500;
$.mb_audioEmbedder.defaults.width=214;
    $("#media").mb_embedMovies();
    $("#media").mb_embedAudio();

});

Can anyone tell me why this doesn't work?

Body:
Try wrapping

   var element = '#countDownTimer';
   var year = <%= @deal.end.year %>;
   var month = <%= @deal.end.month %>;
   var day = <%= @deal.end.day %>;
   setCountdownTimer(element, year, month, day);

inside a $(document).ready()

also I don't think this needs to be in the $(document).ready()

function setCountdownTimer(element, year, month, day) {
  var date = new Date(year, month, day);
  $(element).countdown({until: date});
}

The issue is probably that your calling setCountdownTimer before its defined


问:
Are the await / async keywords needed under Task.Run?
I have an async lambda expression wrapped under Task.Run.
However, it looks like I can drop the async and await keywords and they will produce the same result.

```<code>t1 = Task.Run(() => DoSomethingExpensiveAsync());
t2 = Task.Run(() => DoSomethingExpensiveAsync());
await Task.WhenAll(t1, t2);
</code>```

vs

```<code>var t1 = Task.Run(async () => await DoSomethingExpensiveAsync());
var t2 = Task.Run(async () => await DoSomethingExpensiveAsync());
await Task.WhenAll(t1, t2);
</code>```

How come the compiler let me do this and what is happening behind
the scene?

Is there a situation where adding them will make a
difference?

答:
How come the compiler let me do this and what is happening behind the scene?

The overload of Task.Run that you're invoking takes a Func<Task> - that is, a Task-returning function. It doesn't matter where the Task comes from; the function just needs to return it from somewhere.

If you pass a delegate without async and await, then the delegate is just calling a Task-returning function and returns that same Task. If you pass a delegate with async and await, then the delegate calls the Task-returning function and awaits it; the actual Task returned from the delegate is created by the async keyword.

In this case, the two are semantically equivalent. Using the async/await keywords are a bit less efficient, since the compiler creates a state machine for the async delegate.

Is there a situation where adding them will make a difference?

Yes. In the general case, you should keep async and await. Only remove them in extremely simple "passthrough" situations like the one here.

ContentLicense: CC BY-SA 4.0

Body:
I have an async lambda expression wrapped under Task.Run.
However, it looks like I can drop the async and await keywords and they will produce the same result.

t1 = Task.Run(() => DoSomethingExpensiveAsync());
t2 = Task.Run(() => DoSomethingExpensiveAsync());
await Task.WhenAll(t1, t2);

vs

var t1 = Task.Run(async () => await DoSomethingExpensiveAsync());
var t2 = Task.Run(async () => await DoSomethingExpensiveAsync());
await Task.WhenAll(t1, t2);

How come the compiler let me do this and what is happening behind
the scene?

Is there a situation where adding them will make a
difference?


问:
Visual studio code - how to copy search results?
Does Visual Studio Code have any way to copy the results of a search into a new window?

As a bonus, I'd really like to be able to drop the file name and just copy the lines containing the text of my search results to a new window.

For example, I'd like to to be able to copy the results of the search below to a new editor window. I don't mind if I need to install an extension to do it.

答:
This will work for a single file, assuming each line you care about begins with the search text:
 1. Highlight your search string
 2. CTRL + SHIFT + L to select all occurrences found
 3. SHIFT + ↓ to select all of those lines
 4. CTRL + C
 5. Open a new file
 6. CTRL + V</p>


答:
In Python, you don't have to declare a variable before using it.

The line:

```<code>protocolsFound = [num]
</code>```

Is probably intended to create a list of size num, but you can either just create it as an empty list protocolsFound = [] and start filling it with .append(), or if you need to be able to access specific positions in the list, you can create a list with num empty positions like protocolsFound = [None for _ in range(num)]. This is rarely needed in well-written Python code, though.

Title: How to access object from array of objects in Python

Body:
In Python, you don't have to declare a variable before using it.

The line:

protocolsFound = [num]

Is probably intended to create a list of size num, but you can either just create it as an empty list protocolsFound = [] and start filling it with .append(), or if you need to be able to access specific positions in the list, you can create a list with num empty positions like protocolsFound = [None for _ in range(num)]. This is rarely needed in well-written Python code, though.


问:
Why do some CPUs have different instructions to do signed and unsigned operations?
Let's assume we have the following binary numbers with their representation:

```<code>| bin | unsigned | signed   |
|:---:|----------|----------|
| 110 | 6        | -2       |
| 111 | 7        | -1       |
</code>```

Now regardless if signed or unsigned, 111 + 110 = 1101,
Now I can interpret the result 1101 as signed or unsigned which is:

```<code>| bin  | unsigned | signed   |
|:----:|----------|----------|
| 1101 | 13       | -3       |
</code>```

Which matches the decimal operation:

```<code>6+7 = 13
-1-2 = -3
</code>```

There was no difference between doing a signed addition or unsigned addition. So why would CPUs have different circuits/instructions for such operation?

答:
Because 2's complement add/sub is the same binary operation as unsigned add/sub.  But for comparison (and division and widening multiply), interpretation of the MSB as a sign bit or not matters.

Some CPUs just have a cmp instruction that sets all flags, and then you get your branch instruction checks a specific flag condition (predicate).  Other CPUs without flags / condition codes (like MIPS and RISC-V) need predicates in their compare-into-register instructions.

SIMD compare instructions on x86 / ARM are also compare-into-register, not setting multiple different flags, so they also have the predicate as part of the compare instruction (like cmpps takes an immediate byte with the predicate, or for integer there's pcmpgtd / pcmpeqd.)

Body:
Let's assume we have the following binary numbers with their representation:

| bin | unsigned | signed   |
|:---:|----------|----------|
| 110 | 6        | -2       |
| 111 | 7        | -1       |

Now regardless if signed or unsigned, 111 + 110 = 1101,
Now I can interpret the result 1101 as signed or unsigned which is:

| bin  | unsigned | signed   |
|:----:|----------|----------|
| 1101 | 13       | -3       |

Which matches the decimal operation:

6+7 = 13
-1-2 = -3

There was no difference between doing a signed addition or unsigned addition. So why would CPUs have different circuits/instructions for such operation?


问:
Force overwrite file
I'm using this in my generator

```<code>this.fs.copy(this.templatePath('index.html'),this.destinationPath('index.html') );
</code>```

I want it to skip the overwrite confirmation everytime it finds a confilict (like force overwrite option)

答:
If this is a must to do, you can still force overwriting files by using fs.copyFile(), fs.writeFile() or fs.writeFileSync() function from fs. both functions write data to a file, replacing the file if it already exists.

```<code>const yosay = require("yosay");

....

fs.writeFile(filePath, fileContent, 'utf8', err => yosay(err));
</code>```

If you get error File already exists, you may need to set explicit write flag in the the third param to make it work:

```<code>fs.writeFile(filePath,fileContent,{encoding:'utf8',flag:'w'}, err => yosay(err));
</code>```

OR

```<code>const fs = require('fs');

// destination.txt will be created or overwritten by default.
fs.copyFile('source.txt', 'destination.txt', (err) => {
  if (err) throw err;
  console.log('source.txt was copied to destination.txt');
});
</code>```

Title: Force overwrite file

Body:
I'm using this in my generator

this.fs.copy(this.templatePath('index.html'),this.destinationPath('index.html') );

I want it to skip the overwrite confirmation everytime it finds a confilict (like force overwrite option)

Body:
If this is a must to do, you can still force overwriting files by using fs.copyFile(), fs.writeFile() or fs.writeFileSync() function from fs. both functions write data to a file, replacing the file if it already exists.

const yosay = require("yosay");

....

fs.writeFile(filePath, fileContent, 'utf8', err => yosay(err));

If you get error File already exists, you may need to set explicit write flag in the the third param to make it work:

fs.writeFile(filePath,fileContent,{encoding:'utf8',flag:'w'}, err => yosay(err));

OR

const fs = require('fs');

// destination.txt will be created or overwritten by default.
fs.copyFile('source.txt', 'destination.txt', (err) => {
  if (err) throw err;
  console.log('source.txt was copied to destination.txt');
});


问:
Convert an existing Replica Set In Mongodb to a Sharded Cluster
I have a replica set with 3 nodes. Is there a way to convert this existing Replica Set to a Sharded Cluster. Please find below the config file of the replica set:

All of my 3 nodes in replica set have sharding enabled:-

```<code>sharding:
  clusterRole: shardsvr
</code>```

答: sharding is enabled at the database level ....and then implemented at the collection level.   any operating replica set can work in a sharding environment but there wouldn't be a compelling reason to do sharding until you have multiple replica clusters working in parallel...  it's a big decision - no going back...and you need to be very clear on your sharding key....  so definitely invest time in learning the technology at the MongoDB University.</p>

Body:
I have a replica set with 3 nodes. Is there a way to convert this existing Replica Set to a Sharded Cluster. Please find below the config file of the replica set:

All of my 3 nodes in replica set have sharding enabled:-

sharding:
  clusterRole: shardsvr


问:
How to safely generate external links?
I would like to create an HTML link in my view, which leads to an offsite site and has a dynamic URL component.

I tried this:

```<code><a href="https://stackoverflow.com/users/@item.Title">
    @Html.DisplayFor(modelItem => item.Title)
</a>
</code>```

where item.Title is a dynamic string. If I use @item.Title it is safely HTML encoded, but it is not url encoded. So if the string contains / for example my URL will be broken. How can I URL encode it? Is there a tag helper that can generate the link for me?

答:
Try to use  System.Net.WebUtility.UrlEncode in razor like:</p>

```<code>@{
    var title = System.Net.WebUtility.UrlEncode(item.Title);
}
<a href="https://stackoverflow.com/users/@title">
    @Html.DisplayFor(modelItem => item.Title)

</a>
</code>```

Title: How to safely generate external links?

Body:
I would like to create an HTML link in my view, which leads to an offsite site and has a dynamic URL component.

I tried this:

    @Html.DisplayFor(modelItem => item.Title)

where item.Title is a dynamic string. If I use @item.Title it is safely HTML encoded, but it is not url encoded. So if the string contains / for example my URL will be broken. How can I URL encode it? Is there a tag helper that can generate the link for me?

Body:
Try to use  System.Net.WebUtility.UrlEncode in razor like:

@{
    var title = System.Net.WebUtility.UrlEncode(item.Title);
}
<a href="https://stackoverflow.com/users/@title">
    @Html.DisplayFor(modelItem => item.Title)

</a>


问:
Typo3 Session lost in MS-Edge when opening a new window
I'm experiencing a strange problem with the Edge-Browser.

I'm using an ajax-call to login a user. As long as the user is in the same window, the session vars seem to be persistent.
But as soon as I open a new window (target="_blank") the session vars seem to be lost and the user isn't logged in anymore. The session vars are gone in the opening window as well.

I'm using this to set and get the session vars:

```<code>$sessionData = $GLOBALS['TSFE']->fe_user->getKey('ses', self::$prefixKey . $key);

$GLOBALS['TSFE']->fe_user->setKey('ses', self::$prefixKey . $key, $sessionData);
$GLOBALS['TSFE']->fe_user->storeSessionData();
</code>```

It's happening in all versions of Edge - interestingly, for once it doesn't happen in IE.

Any ideas?

[Edit for clarification]: The new window is on the same domain as the opening one. No subdomains, no nothing.

答:
Which version of Edge browser are you using? Please refer to the following steps to make sure you are not disabled cookies in Edge browser:

Open Edge browser, click on the More actions button in the top right
corner and select Settings.

Click View Advanced Settings. You’ll need to scroll down to the
bottom of the page.

Press the dropdown arrow under the Cookies field.

Select Don't block cookies.

If still not working, try to reset the Edge browser setting.

Body:
I'm experiencing a strange problem with the Edge-Browser.

I'm using an ajax-call to login a user. As long as the user is in the same window, the session vars seem to be persistent.
But as soon as I open a new window (target="_blank") the session vars seem to be lost and the user isn't logged in anymore. The session vars are gone in the opening window as well.

I'm using this to set and get the session vars:

$sessionData = $GLOBALS['TSFE']->fe_user->getKey('ses', self::$prefixKey . $key);

$GLOBALS['TSFE']->fe_user->setKey('ses', self::$prefixKey . $key, $sessionData);
$GLOBALS['TSFE']->fe_user->storeSessionData();

It's happening in all versions of Edge - interestingly, for once it doesn't happen in IE.

Any ideas?

[Edit for clarification]: The new window is on the same domain as the opening one. No subdomains, no nothing.


问:
How to consolidate columns based on dates with SQL
If I have the following SQL my_table:

```<code> ╔══════╦═════════════════════╦═══════════╦═══════════════╗
 ║  id  ║    date_recorded    ║ new_entry ║ price_updated ║
 ╠══════╬═════════════════════╬═══════════╬═══════════════╣
 ║ ...  ║ ...                 ║    ...    ║      ...      ║
 ║ 120  ║ 2020-02-13 18:53:49 ║    15     ║      13       ║
 ║ 121  ║ 2020-02-14 00:52:58 ║     5     ║       2       ║
 ║ 122  ║ 2020-02-14 06:53:38 ║     1     ║       4       ║
 ║ 123  ║ 2020-02-14 12:54:21 ║     5     ║       1       ║
 ║ 124  ║ 2020-02-14 18:54:50 ║     9     ║       9       ║
 ║ 125  ║ 2020-02-15 00:54:45 ║     7     ║      11       ║
 ║ ...  ║ ...                 ║    ...    ║      ...      ║
 ╚══════╩═════════════════════╩═══════════╩═══════════════╝
</code>```

Question:

How would I write an SQL Query to query all the dates in my_table so the output is just the date and the new_entry & price_updated columns are consolidated into one row for all dates in the date_recorded column:

```<code> ╔═════════════════╦═══════════╦═══════════════╗
 ║  date_recorded  ║ new_entry ║ price_updated ║
 ╠═════════════════╬═══════════╬═══════════════╣
 ║ ...             ║    ...    ║      ...      ║
 ║ 2020-02-13      ║    15     ║      13       ║
 ║ 2020-02-14      ║    20  #  ║      16 *     ║  #20 = 5 + 1 + 5 + 9  |  *16 = 2 + 4 + 9 + 1
 ║ 2020-02-15      ║     7     ║      11       ║
 ║ ...             ║    ...    ║      ...      ║
 ╚═════════════════╩═══════════╩═══════════════╝
</code>```

答:
You can just use a GROUP BY expression, grouping on the DATE part of date_recorded and SUMming the new_entry and price_updated values:

```<code>SELECT DATE(date_recorded) AS date_recorded,
       SUM(new_entry) AS new_entry,
       SUM(price_updated) AS price_updated
FROM my_table
GROUP BY DATE(date_recorded)
</code>```

Demo on SQLFiddle

Body:
If I have the following SQL my_table:

 ╔══════╦═════════════════════╦═══════════╦═══════════════╗
 ║  id  ║    date_recorded    ║ new_entry ║ price_updated ║
 ╠══════╬═════════════════════╬═══════════╬═══════════════╣
 ║ ...  ║ ...                 ║    ...    ║      ...      ║
 ║ 120  ║ 2020-02-13 18:53:49 ║    15     ║      13       ║
 ║ 121  ║ 2020-02-14 00:52:58 ║     5     ║       2       ║
 ║ 122  ║ 2020-02-14 06:53:38 ║     1     ║       4       ║
 ║ 123  ║ 2020-02-14 12:54:21 ║     5     ║       1       ║
 ║ 124  ║ 2020-02-14 18:54:50 ║     9     ║       9       ║
 ║ 125  ║ 2020-02-15 00:54:45 ║     7     ║      11       ║
 ║ ...  ║ ...                 ║    ...    ║      ...      ║
 ╚══════╩═════════════════════╩═══════════╩═══════════════╝

Question:

How would I write an SQL Query to query all the dates in my_table so the output is just the date and the new_entry & price_updated columns are consolidated into one row for all dates in the date_recorded column:

 ╔═════════════════╦═══════════╦═══════════════╗
 ║  date_recorded  ║ new_entry ║ price_updated ║
 ╠═════════════════╬═══════════╬═══════════════╣
 ║ ...             ║    ...    ║      ...      ║
 ║ 2020-02-13      ║    15     ║      13       ║
 ║ 2020-02-14      ║    20  #  ║      16 *     ║  #20 = 5 + 1 + 5 + 9  |  *16 = 2 + 4 + 9 + 1
 ║ 2020-02-15      ║     7     ║      11       ║
 ║ ...             ║    ...    ║      ...      ║
 ╚═════════════════╩═══════════╩═══════════════╝

Body:
You can just use a GROUP BY expression, grouping on the DATE part of date_recorded and SUMming the new_entry and price_updated values:

SELECT DATE(date_recorded) AS date_recorded,
       SUM(new_entry) AS new_entry,
       SUM(price_updated) AS price_updated
FROM my_table
GROUP BY DATE(date_recorded)

Demo on SQLFiddle


问:
remove div without an id tag
I need a solution to remove a div without an ID tag in JavaScript only. The div looks like this
.

Here is the full structure.

```<code><tr id="-1">
  <td class="stxt">
    <div align="center">
    </div>
  </td>
</tr>
</code>```

答:
You need to work out how to get a reference to it, once you've done that, you can remove it using:

```<code>div.parentNode.removeChild(div);
</code>```

Of course the align attribute has been deprecated, but anyway, you can find the divs with align="center" using:

```<code>var divs = document.getElementsByTagName('div');
var div;
var i = divs.length;

while (i--) {
  div = divs[i];

  if (div.getAttribute('align') == 'center') {
    div.parentNode.removeChild(div);
  }
}
</code>```

Which will remove every div in the document that has align="center".

Note that the object returned by getElementsByTagName is a NodeList. If you iterate over it from 0 and remove nodes, they are removed from the live list so you will skip the node following the one you remove and you will attempt to access no existant nodes at the end. Going over the list backwards avoids these pitfalls. An alternative is to turn the NodeList into an array, but that's somewhat inefficient.

Edit

Since you edited the question, here's an update answer.

You can get a reference to the TR using getElementById:

```<code>var root = document.getElementById('-1');
</code>```

Now you can go down the DOM:

```<code>var cell = root.cells[0]; // First cell in the row
var div = cell.getElementsByTagName('div')[0]; // first div
cell.removeChild(div);
</code>```

Which is specific to the structure you've posted.

Title: remove div without an id tag

Body:
You need to work out how to get a reference to it, once you've done that, you can remove it using:

div.parentNode.removeChild(div);

Of course the align attribute has been deprecated, but anyway, you can find the divs with align="center" using:

var divs = document.getElementsByTagName('div');
var div;
var i = divs.length;

while (i--) {
  div = divs[i];

  if (div.getAttribute('align') == 'center') {
    div.parentNode.removeChild(div);
  }
}

Which will remove every div in the document that has align="center".

Note that the object returned by getElementsByTagName is a NodeList. If you iterate over it from 0 and remove nodes, they are removed from the live list so you will skip the node following the one you remove and you will attempt to access no existant nodes at the end. Going over the list backwards avoids these pitfalls. An alternative is to turn the NodeList into an array, but that's somewhat inefficient.

Edit

Since you edited the question, here's an update answer.

You can get a reference to the TR using getElementById:

var root = document.getElementById('-1');

Now you can go down the DOM:

var cell = root.cells[0]; // First cell in the row
var div = cell.getElementsByTagName('div')[0]; // first div
cell.removeChild(div);

Which is specific to the structure you've posted.


问:
Gulp minify and move files with same folder structure
I have a folder structure like this:

```<code>.
├── dist/
└── src/
    ├── index.php
    └── projects/
        ├── some-project/
        │   ├── main.css
        │   ├── main.js
        │   └── index.html
        └── N'th project/ ...
</code>```

I need to minify and move every project inside src/ to dist/ without breaking folder structure. Should look like this:

```<code>.
├── dist/
│   ├── index.php
│   └── projects/
│       ├── some-project/
│       │   ├── main.css(minified)
│       │   ├── main.js(minified)
│       │   └── index.html
│       └── N'th project/ (also minified) ...
└── src/
    ├── index.php
    └── projects/
        ├── some-project/
        │   ├── main.css
        │   ├── main.js
        │   └── index.html
        └── N'th project/ ...
</code>```

Thanks for your time.

答:
```<code>gulp.task("projectTest", () => {

  return gulp.src("./src/projects/**/*.css")
    // minify pipe, etc.
    .pipe(gulp.dest('dist/projects'))
});
</code>```

From https://gulpjs.com/docs/en/api/concepts#glob-base:

A glob base - sometimes called glob parent - is the path segment
  before any special characters in a glob string. As such, the glob base
  of /src/js/**.js is /src/js/. All paths that match the glob are
  guaranteed to share the glob base - that path segment can't be
  variable.

Vinyl instances generated by src() are constructed with the glob base
  set as their base property. When written to the file system with
  dest(), the base will be removed from the output path to preserve
  directory structures.

That is a little confusing as written.  In my code the part before the globstar ** is the base.  So ./src/projects/ is the base.  And the directory structure under the base is always preserved - but that wouldn't include projects (because that is part of the base and will be removed automatically in gulp.dest).

In the dest pipe, the directory structures (project1, project2, etc.) are still there but would be sent to your dest folder without the base path at the beginning.  So you will need to add whatever part of that base path back into your dest folder if you want it.

So gulp.dest('dist/projects') to get the preserved folder structure put back under projects as you want.

So if what I said is true, this alternative should work as well:

```<code>gulp.task("projectTest", () => {

  // return gulp.src("./src/projects/**/*.css")

  return gulp.src("./src/**/*.css")

    // .pipe(gulp.dest('dist/projects'))

    .pipe(gulp.dest('dist'))
});
</code>```

Now the directory structure under src is preserved (becasue src is the base).  So you get the same result just sending all that to dist.

You can decide which form you prefer, I think the first version is a little clearer.  And if there are files under src that you do not want captured by the gulp.src glob.

Body:
I have a folder structure like this:

.
├── dist/
└── src/
    ├── index.php
    └── projects/
        ├── some-project/
        │   ├── main.css
        │   ├── main.js
        │   └── index.html
        └── N'th project/ ...

I need to minify and move every project inside src/ to dist/ without breaking folder structure. Should look like this:

.
├── dist/
│   ├── index.php
│   └── projects/
│       ├── some-project/
│       │   ├── main.css(minified)
│       │   ├── main.js(minified)
│       │   └── index.html
│       └── N'th project/ (also minified) ...
└── src/
    ├── index.php
    └── projects/
        ├── some-project/
        │   ├── main.css
        │   ├── main.js
        │   └── index.html
        └── N'th project/ ...

Thanks for your time.

Body:
gulp.task("projectTest", () => {

  return gulp.src("./src/projects/**/*.css")
    // minify pipe, etc.
    .pipe(gulp.dest('dist/projects'))
});

From https://gulpjs.com/docs/en/api/concepts#glob-base:

A glob base - sometimes called glob parent - is the path segment
  before any special characters in a glob string. As such, the glob base
  of /src/js/**.js is /src/js/. All paths that match the glob are
  guaranteed to share the glob base - that path segment can't be
  variable.

Vinyl instances generated by src() are constructed with the glob base
  set as their base property. When written to the file system with
  dest(), the base will be removed from the output path to preserve
  directory structures.

That is a little confusing as written.  In my code the part before the globstar ** is the base.  So ./src/projects/ is the base.  And the directory structure under the base is always preserved - but that wouldn't include projects (because that is part of the base and will be removed automatically in gulp.dest).

In the dest pipe, the directory structures (project1, project2, etc.) are still there but would be sent to your dest folder without the base path at the beginning.  So you will need to add whatever part of that base path back into your dest folder if you want it.

So gulp.dest('dist/projects') to get the preserved folder structure put back under projects as you want.

So if what I said is true, this alternative should work as well:

gulp.task("projectTest", () => {

  // return gulp.src("./src/projects/**/*.css")

  return gulp.src("./src/**/*.css")

    // .pipe(gulp.dest('dist/projects'))

    .pipe(gulp.dest('dist'))
});

Now the directory structure under src is preserved (becasue src is the base).  So you get the same result just sending all that to dist.

You can decide which form you prefer, I think the first version is a little clearer.  And if there are files under src that you do not want captured by the gulp.src glob.


问:
Fill in cells in specific columns if cells are blank
Hi I am looking to edit this function I saw in a older post to something that is more dynamic and can actually fill in the blanks on the right column since right now it is filling in Column B instead of the blanks in D. Here is the function I have

```<code>function Absent() {
  var tss = SpreadsheetApp.getActiveSpreadsheet();
  var values = tss.getRange("Attendance!D1:D20").getValues();

  for(i=0; i<values.length; i++) {
    var value = values[i][0];

    if (value == "") {
      var rangeB = tss.getSheetByName("Attendance").getRange(i+1,2);

      if(!rangeB.isBlank()) {
        rangeB.setValue("A");
      }
    }
  }
}
</code>```

The current situation I have is that there are names in Column A that are marked with a P (because they are present) in columns "D","H","J","L","N","P","R","T","V","X","Z","AB","AF","AH","AJ","AL","AN" The people who are not there are left blank but I would like to fill them in with A when I run the scrip through a button. Here you can see the sheet.
The script below is what I run first to add Ps to everyone that is present but I am not sure how to edit to where after it adds P's it goes back in and if name is not found put an A so that is why I am doing the second script. But if there is a way to just add it to this one that would be great!

```<code>
  var sprsheet = SpreadsheetApp.getActiveSpreadsheet();
  var transpose = sprsheet.getSheetByName("Transpose");
  var attendance = sprsheet.getSheetByName("Attendance");

  //Ranges of Transpose
  var colDates = transpose.getRange("D1:BU1").getValues();
  var attendees = transpose.getRange("D2:BU2").getValues();

  //Ranges of Attendance
  var eventsCol = ["D","H","J","L","N","P","T","V","X","Z","AB","AF","AH","AJ","AL","AN","AR","AT","AV","AX","AZ","BD","BF","BH","BJ","BL","BP","BR","BT","BV","BX","BZ"]; //Add Column letters is need more dates added
  var kids = attendance.getRange("A2:A205").getValues(); //Increase this if you add more names

  loop1:
  for (var i = 0; i < eventsCol.length; i++){ //For each column

    var list = getIndividuals(attendees[0][i]); //Get the list of each Transpose row 2

    loop2:
    for (var x = 0; x < kids.length; x++){ //For each name in Attendance

      loop3:
      for (var y = 0; y < list.length; y++){ //Compare it with each name of the list

        if (list[y] == kids[x][0] || list[y] == " " + kids[x][0]){ //Second "or" is in case there is an space in the first position.

        attendance.getRange(eventsCol[i]+(x+2)).setValue("P");

          break loop3; //Once it finds a name it makes no sense to keep searching. Go back to the next name.

         }
        }

      }

    }
  }

//Split the list into each name, removing the first space
function getIndividuals(attendees){

  var individuals = attendees.split(",");

  for (var i = 0; i < individuals.length; i++){

    if (individuals[i][0] == " "){

      individuals[i][0].replace(" ", "");

    }

  }

  return individuals;
}
</code>```

答:
your current script does the following:
1) Retrieve D1:10
2) check through the values of D1:D10 to see which is empty
3) if the range is empty, set a value of A on the 2nd column.

the following script would:
1) check through the given range
2) check for empty value
3) set a value of A on the same range

```<code>  var app = SpreadsheetApp;
  var ss = app.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();

  var checkrange = sheet.getRange(2,1,9,1).getValues(); //range to check getRange(starting row, starting column,number of rows to check, number of column to check)

  for( i=0; i<checkrange.length; i++){
    var content = checkrange[i];

    if (content ==""){
      sheet.getRange(i+2,1).setValue("A"); //plus 1 because first item in array is a 0, but it would be in row 1, plus another 1 because of header. to change the column, change the 1 to whichever column you need
    }
  }
}
</code>```

Body:
Hi I am looking to edit this function I saw in a older post to something that is more dynamic and can actually fill in the blanks on the right column since right now it is filling in Column B instead of the blanks in D. Here is the function I have

function Absent() {
  var tss = SpreadsheetApp.getActiveSpreadsheet();
  var values = tss.getRange("Attendance!D1:D20").getValues();

  for(i=0; i<values.length; i++) {
    var value = values[i][0];

    if (value == "") {
      var rangeB = tss.getSheetByName("Attendance").getRange(i+1,2);

      if(!rangeB.isBlank()) {
        rangeB.setValue("A");
      }
    }
  }
}

The current situation I have is that there are names in Column A that are marked with a P (because they are present) in columns "D","H","J","L","N","P","R","T","V","X","Z","AB","AF","AH","AJ","AL","AN" The people who are not there are left blank but I would like to fill them in with A when I run the scrip through a button. Here you can see the sheet.
The script below is what I run first to add Ps to everyone that is present but I am not sure how to edit to where after it adds P's it goes back in and if name is not found put an A so that is why I am doing the second script. But if there is a way to just add it to this one that would be great!

  var sprsheet = SpreadsheetApp.getActiveSpreadsheet();
  var transpose = sprsheet.getSheetByName("Transpose");
  var attendance = sprsheet.getSheetByName("Attendance");

  //Ranges of Transpose
  var colDates = transpose.getRange("D1:BU1").getValues();
  var attendees = transpose.getRange("D2:BU2").getValues();

  //Ranges of Attendance
  var eventsCol = ["D","H","J","L","N","P","T","V","X","Z","AB","AF","AH","AJ","AL","AN","AR","AT","AV","AX","AZ","BD","BF","BH","BJ","BL","BP","BR","BT","BV","BX","BZ"]; //Add Column letters is need more dates added
  var kids = attendance.getRange("A2:A205").getValues(); //Increase this if you add more names

  loop1:
  for (var i = 0; i < eventsCol.length; i++){ //For each column

    var list = getIndividuals(attendees[0][i]); //Get the list of each Transpose row 2

    loop2:
    for (var x = 0; x < kids.length; x++){ //For each name in Attendance

      loop3:
      for (var y = 0; y < list.length; y++){ //Compare it with each name of the list

        if (list[y] == kids[x][0] || list[y] == " " + kids[x][0]){ //Second "or" is in case there is an space in the first position.

        attendance.getRange(eventsCol[i]+(x+2)).setValue("P");

          break loop3; //Once it finds a name it makes no sense to keep searching. Go back to the next name.

         }
        }

      }

    }
  }

//Split the list into each name, removing the first space
function getIndividuals(attendees){

  var individuals = attendees.split(",");

  for (var i = 0; i < individuals.length; i++){

    if (individuals[i][0] == " "){

      individuals[i][0].replace(" ", "");

    }

  }

  return individuals;
}

Body:
your current script does the following:
1) Retrieve D1:10
2) check through the values of D1:D10 to see which is empty
3) if the range is empty, set a value of A on the 2nd column.

the following script would:
1) check through the given range
2) check for empty value
3) set a value of A on the same range

  var app = SpreadsheetApp;
  var ss = app.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();

  var checkrange = sheet.getRange(2,1,9,1).getValues(); //range to check getRange(starting row, starting column,number of rows to check, number of column to check)

  for( i=0; i<checkrange.length; i++){
    var content = checkrange[i];

    if (content ==""){
      sheet.getRange(i+2,1).setValue("A"); //plus 1 because first item in array is a 0, but it would be in row 1, plus another 1 because of header. to change the column, change the 1 to whichever column you need
    }
  }
}


问:
Istream function to read with istream parameter
I'm trying to understand this code

```<code>istream &read(istream &is, Sales_data &item)
{
    double price = 0;
    is >> item.bookNo >> item.units_sold >> price;
    item.revenue = price * item.units_sold;
    return is;
}

ostream &print(ostream &os, const Sales_data &item)
{
    os << item.isbn() << " " << item.units_sold << " "
        << item.revenue << " " << item.avg_price();
    return os;
}
</code>```

I don't understand what are these function ,  also I can't understand why we use istream for reading and ostream for printing instead of using cin and cout.

答:
std::cin and std::cout are specific instances of a std::istream and a std::ostream. Therefore, you could call these functions and pass std::cin or std::cout as the streams you want to use. This allows the functions to be more general-purpose, because we can use streams for more than just command line input and output.

In particular, std::ifstream and std::ofstream for file I/O and std::istringstream and std::ostringstream for string I/O.

Body:
I'm trying to understand this code

istream &read(istream &is, Sales_data &item)
{
    double price = 0;
    is >> item.bookNo >> item.units_sold >> price;
    item.revenue = price * item.units_sold;
    return is;
}

ostream &print(ostream &os, const Sales_data &item)
{
    os << item.isbn() << " " << item.units_sold << " "
        << item.revenue << " " << item.avg_price();
    return os;
}

I don't understand what are these function ,  also I can't understand why we use istream for reading and ostream for printing instead of using cin and cout.


问:
Modal fullscreen is aligned to the left
My fullscreen modal is aligned to the left. Centered property does not solve it. I have a row of the grid that dynamically displays a series of Cards. Each Card has the modal associated, so when you click the Card the modal opens with information from the Card.

This is the grid where i render it

```<code><Grid.Column key={this.props.sensorid} width={4}>
        <Card
          onClick={() => {
            this.setState({ modalOpen: true });
          }}
          color={color}
          header={String(porce) + " %"}
          description={this.props.sensorname}
          meta={nivelUno + " mm"}
        />

          <ModalSensor
            sensorWell={this.props.sensorWell}
            sensorName={this.props.sensorConPrefijo}
            sensorId = {this.props.sensorid}
            modalOpen={this.state.modalOpen}
            handleClose={() => {
              this.setState({ modalOpen: false });
            }}
          />

      </Grid.Column>
</code>```

This is the modal

```<code>export default class ModalSensor extends Component {
  render() {
    return (
      <div>
      <Modal
        centered={true}
        open={this.props.modalOpen}
        onClose={this.props.handleClose}
        closeOnEscape={true}
        size={"Fullscreen"}
      >
        <Modal.Header>Nivel del sensor {this.props.sensorName}</Modal.Header>
        <Modal.Content>

            <Sensor sensorwell={this.props.sensorWell} sensorcodigo={this.props.sensorName}/>

        </Modal.Content>
        <Modal.Actions>
          <Button
            inverted
            color="orange"
            type="button"
            icon="checkmark"
            labelPosition="right"
            onClick={this.props.handleClose}
            content="Cerrar"
          />
        </Modal.Actions>
      </Modal>
      </div>
    );
  }
}
</code>```

答:
I've also encountered this type of layout bug, but I fixed it by adding a custom class to

```<code>.customClass {
  left: 50%;
  transform: translateX(-50%);
}
</code>```

Title: Modal fullscreen is aligned to the left

Body:
My fullscreen modal is aligned to the left. Centered property does not solve it. I have a row of the grid that dynamically displays a series of Cards. Each Card has the modal associated, so when you click the Card the modal opens with information from the Card.

This is the grid where i render it

<Grid.Column key={this.props.sensorid} width={4}>
        <Card
          onClick={() => {
            this.setState({ modalOpen: true });
          }}
          color={color}
          header={String(porce) + " %"}
          description={this.props.sensorname}
          meta={nivelUno + " mm"}
        />

          <ModalSensor
            sensorWell={this.props.sensorWell}
            sensorName={this.props.sensorConPrefijo}
            sensorId = {this.props.sensorid}
            modalOpen={this.state.modalOpen}
            handleClose={() => {
              this.setState({ modalOpen: false });
            }}
          />

      </Grid.Column>

This is the modal

export default class ModalSensor extends Component {
  render() {
    return (

      <Modal
        centered={true}
        open={this.props.modalOpen}
        onClose={this.props.handleClose}
        closeOnEscape={true}
        size={"Fullscreen"}
      >
        <Modal.Header>Nivel del sensor {this.props.sensorName}</Modal.Header>
        <Modal.Content>

            <Sensor sensorwell={this.props.sensorWell} sensorcodigo={this.props.sensorName}/>

        </Modal.Content>
        <Modal.Actions>
          <Button
            inverted
            color="orange"
            type="button"
            icon="checkmark"
            labelPosition="right"
            onClick={this.props.handleClose}
            content="Cerrar"
          />
        </Modal.Actions>
      </Modal>

    );
  }
}

Body:
I've also encountered this type of layout bug, but I fixed it by adding a custom class to <div class="ui fullscreen modal transition visible active" />

.customClass {
  left: 50%;
  transform: translateX(-50%);
}


问:
How to get words from output of XLNet using Transformers library
I am using Hugging Face's Transformer library to work with different NLP models. Following code does masking with XLNet. It outputs a tensor with numbers. How do I convert the output to words again?

```<code>import torch
from transformers import XLNetModel,  XLNetTokenizer, XLNetLMHeadModel

tokenizer = XLNetTokenizer.from_pretrained('xlnet-base-cased')
model = XLNetLMHeadModel.from_pretrained('xlnet-base-cased')

# We show how to setup inputs to predict a next token using a bi-directional context.
input_ids = torch.tensor(tokenizer.encode("I went to <mask> York and saw the <mask> <mask> building.")).unsqueeze(0)  # We will predict the masked token
print(input_ids)

perm_mask = torch.zeros((1, input_ids.shape[1], input_ids.shape[1]), dtype=torch.float)
perm_mask[:, :, -1] = 1.0  # Previous tokens don't see last token

target_mapping = torch.zeros((1, 1, input_ids.shape[1]), dtype=torch.float)  # Shape [1, 1, seq_length] => let's predict one token
target_mapping[0, 0, -1] = 1.0  # Our first (and only) prediction will be the last token of the sequence (the masked token)

outputs = model(input_ids, perm_mask=perm_mask, target_mapping=target_mapping)
next_token_logits = outputs[0]  # Output has shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size]
</code>```

The current output I get is:

tensor([[[ -5.1466, -17.3758, -17.3392,  ..., -12.2839, -12.6421, -12.4505]]],
       grad_fn=AddBackward0)

答:
The output you have is a tensor of size 1 by 1 by vocabulary size.  The meaning of the nth number in this tensor is the estimated log-odds of the nth vocabulary item.  So, if you want to get out the word that the model predicts to be most likely to come in the final position (the position you specified with target_mapping), all you need to do is find the word in the vocabulary with the maximum predicted log-odds.

Just add the following to the code you have:

```<code>predicted_index = torch.argmax(next_token_logits[0][0]).item()
predicted_token = tokenizer.convert_ids_to_tokens(predicted_index)
</code>```

So predicted_token is the token the model predicts as most likely in that position.

Note, by default behaviour of XLNetTokenizer.encoder() adds special tokens  and  to the end of a string of tokens when it encodes it.  The code you have given masks and predicts the final word, which, after running though tokenizer.encoder() is the special character '<cls>', which is probably not what you want.

That is, when you run

tokenizer.encode("I went to <mask> York and saw the <mask> <mask> building.")

the result is a list of token ids,

[35, 388, 22, 6, 313, 21, 685, 18, 6, 6, 540, 9, 4, 3]

which, if you convert back to tokens (by calling tokenizer.convert_ids_to_tokens() on the above id list), you will see has two extra tokens added at the end,

['▁I', '▁went', '▁to', '<mask>', '▁York', '▁and', '▁saw', '▁the', '<mask>', '<mask>', '▁building', '.', '<sep>', '<cls>']

So, if the word you are meaning to predict is 'building', you should use perm_mask[:, :, -4] = 1.0 and target_mapping[0, 0, -4] = 1.0.

Body:
I am using Hugging Face's Transformer library to work with different NLP models. Following code does masking with XLNet. It outputs a tensor with numbers. How do I convert the output to words again?

import torch
from transformers import XLNetModel,  XLNetTokenizer, XLNetLMHeadModel

tokenizer = XLNetTokenizer.from_pretrained('xlnet-base-cased')
model = XLNetLMHeadModel.from_pretrained('xlnet-base-cased')

# We show how to setup inputs to predict a next token using a bi-directional context.
input_ids = torch.tensor(tokenizer.encode("I went to <mask> York and saw the <mask> <mask> building.")).unsqueeze(0)  # We will predict the masked token
print(input_ids)

perm_mask = torch.zeros((1, input_ids.shape[1], input_ids.shape[1]), dtype=torch.float)
perm_mask[:, :, -1] = 1.0  # Previous tokens don't see last token

target_mapping = torch.zeros((1, 1, input_ids.shape[1]), dtype=torch.float)  # Shape [1, 1, seq_length] => let's predict one token
target_mapping[0, 0, -1] = 1.0  # Our first (and only) prediction will be the last token of the sequence (the masked token)

outputs = model(input_ids, perm_mask=perm_mask, target_mapping=target_mapping)
next_token_logits = outputs[0]  # Output has shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size]

The current output I get is:

tensor([[[ -5.1466, -17.3758, -17.3392,  ..., -12.2839, -12.6421, -12.4505]]],
       grad_fn=AddBackward0)

Body:
The output you have is a tensor of size 1 by 1 by vocabulary size.  The meaning of the nth number in this tensor is the estimated log-odds of the nth vocabulary item.  So, if you want to get out the word that the model predicts to be most likely to come in the final position (the position you specified with target_mapping), all you need to do is find the word in the vocabulary with the maximum predicted log-odds.

Just add the following to the code you have:

predicted_index = torch.argmax(next_token_logits[0][0]).item()
predicted_token = tokenizer.convert_ids_to_tokens(predicted_index)

So predicted_token is the token the model predicts as most likely in that position.

Note, by default behaviour of XLNetTokenizer.encoder() adds special tokens  and  to the end of a string of tokens when it encodes it.  The code you have given masks and predicts the final word, which, after running though tokenizer.encoder() is the special character '<cls>', which is probably not what you want.

That is, when you run

tokenizer.encode("I went to <mask> York and saw the <mask> <mask> building.")

the result is a list of token ids,

[35, 388, 22, 6, 313, 21, 685, 18, 6, 6, 540, 9, 4, 3]

which, if you convert back to tokens (by calling tokenizer.convert_ids_to_tokens() on the above id list), you will see has two extra tokens added at the end,

['▁I', '▁went', '▁to', '<mask>', '▁York', '▁and', '▁saw', '▁the', '<mask>', '<mask>', '▁building', '.', '<sep>', '<cls>']

So, if the word you are meaning to predict is 'building', you should use perm_mask[:, :, -4] = 1.0 and target_mapping[0, 0, -4] = 1.0.


问:
Regex for find multiline form data (php)
I try (without success) to make a regex for find a  submit button even if button code is in one two or more lines.

I use now this patter

/<(button|input)(.*type=['\"](submit|button)['\"].*)?>/i

and works fine if the button code is in one line

<input type="submit" name="mybutton" class="button_class" value="Submit" title="Click Me" />

I want to make it work if my button code look like

<input type="submit" name="mybutton"

class="button_class" value="Submit"

title="Click Me" />

Thanks

答:
Add s (not m) as a modifier:

```<code>/<(button|input)(.*type=['\"](submit|button)['\"].*)?>/is
</code>```

s (PCRE_DOTALL)

If this modifier is set, a dot
  metacharacter in the pattern matches
  all characters, including newlines.
  Without it, newlines are excluded.
  This modifier is equivalent to Perl's
  /s modifier. A negative class such as
  [^a] always matches a newline
  character, independent of the setting
  of this modifier.

m (PCRE_MULTILINE)

By default, PCRE treats the subject
  string as consisting of a single
  "line" of characters (even if it
  actually contains several newlines).
  The "start of line" metacharacter (^)
  matches only at the start of the
  string, while the "end of line"
  metacharacter ($) matches only at the
  end of the string, or before a
  terminating newline (unless D modifier
  is set). This is the same as Perl.
  When this modifier is set, the "start
  of line" and "end of line" constructs
  match immediately following or
  immediately before any newline in the
  subject string, respectively, as well
  as at the very start and end. This is
  equivalent to Perl's /m modifier. If
  there are no "\n" characters in a
  subject string, or no occurrences of ^
  or $ in a pattern, setting this
  modifier has no effect.

Body:
Add s (not m) as a modifier:

/<(button|input)(.*type=['\"](submit|button)['\"].*)?>/is

s (PCRE_DOTALL)

If this modifier is set, a dot
  metacharacter in the pattern matches
  all characters, including newlines.
  Without it, newlines are excluded.
  This modifier is equivalent to Perl's
  /s modifier. A negative class such as
  [^a] always matches a newline
  character, independent of the setting
  of this modifier.

m (PCRE_MULTILINE)

By default, PCRE treats the subject
  string as consisting of a single
  "line" of characters (even if it
  actually contains several newlines).
  The "start of line" metacharacter (^)
  matches only at the start of the
  string, while the "end of line"
  metacharacter ($) matches only at the
  end of the string, or before a
  terminating newline (unless D modifier
  is set). This is the same as Perl.
  When this modifier is set, the "start
  of line" and "end of line" constructs
  match immediately following or
  immediately before any newline in the
  subject string, respectively, as well
  as at the very start and end. This is
  equivalent to Perl's /m modifier. If
  there are no "\n" characters in a
  subject string, or no occurrences of ^
  or $ in a pattern, setting this
  modifier has no effect.


问:
d3.js heatmap not showing data correctly
I have the following HTML document with JavaScript embedded where I try to plot a list of JavaScript objects in a d3.js heatmap. But it seems to only show the data of the first row repeatedly on every row. Any help will be greatly appreciated. This is my code and output:

```<code><!-- Code from d3-graph-gallery.com -->
<!DOCTYPE html>
<meta charset="utf-8">

<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>

<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>

<script>

  // Heatmap data loading
  //document.getElementById("data_display").innerHTML = csvDataString;  //DEBUG

  //var data = {{ heatmap_data|tojson }};

  data = [{group: 'CHEMBL325', variable: 'CHEMBL98', value: 7.2}, {group: 'CHEMBL325', variable: 'CHEMBL99', value: 7.43}, {group: 'CHEMBL325', variable: 'CHEMBL27759', value: 7.31}, {group: 'CHEMBL325', variable: 'CHEMBL2018302', value: 7.19}, {group: 'CHEMBL325', variable: 'CHEMBL483254', value: 7.24}, {group: 'CHEMBL325', variable: 'CHEMBL1213490', value: 7.26}, {group: 'CHEMBL325', variable: 'CHEMBL356769', value: 7.23}, {group: 'CHEMBL325', variable: 'CHEMBL272980', value: 7.21}, {group: 'CHEMBL325', variable: 'CHEMBL430060', value: 7.23}, {group: 'CHEMBL325', variable: 'CHEMBL1173445', value: 7.23}, {group: 'CHEMBL325', variable: 'CHEMBL356066', value: 7.26}, {group: 'CHEMBL325', variable: 'CHEMBL1914702', value: 7.26}, {group: 'CHEMBL1937', variable: 'CHEMBL98', value: 6.94}, {group: 'CHEMBL1937', variable: 'CHEMBL99', value: 7.17}, {group: 'CHEMBL1937', variable: 'CHEMBL27759', value: 7.09}, {group: 'CHEMBL1937', variable: 'CHEMBL2018302', value: 7.06}, {group: 'CHEMBL1937', variable: 'CHEMBL483254', value: 7.14}, {group: 'CHEMBL1937', variable: 'CHEMBL1213490', value: 7.19}, {group: 'CHEMBL1937', variable: 'CHEMBL356769', value: 7.14}, {group: 'CHEMBL1937', variable: 'CHEMBL272980', value: 7.13}, {group: 'CHEMBL1937', variable: 'CHEMBL430060', value: 7.16}, {group: 'CHEMBL1937', variable: 'CHEMBL1173445', value: 7.14}, {group: 'CHEMBL1937', variable: 'CHEMBL356066', value: 7.18}, {group: 'CHEMBL1937', variable: 'CHEMBL1914702', value: 7.17}, {group: 'CHEMBL1829', variable: 'CHEMBL98', value: 7.18}, {group: 'CHEMBL1829', variable: 'CHEMBL99', value: 7.37}, {group: 'CHEMBL1829', variable: 'CHEMBL27759', value: 7.24}, {group: 'CHEMBL1829', variable: 'CHEMBL2018302', value: 7.22}, {group: 'CHEMBL1829', variable: 'CHEMBL483254', value: 7.31}, {group: 'CHEMBL1829', variable: 'CHEMBL1213490', value: 7.35}, {group: 'CHEMBL1829', variable: 'CHEMBL356769', value: 7.31}, {group: 'CHEMBL1829', variable: 'CHEMBL272980', value: 7.24}, {group: 'CHEMBL1829', variable: 'CHEMBL430060', value: 7.29}, {group: 'CHEMBL1829', variable: 'CHEMBL1173445', value: 7.25}, {group: 'CHEMBL1829', variable: 'CHEMBL356066', value: 7.3}, {group: 'CHEMBL1829', variable: 'CHEMBL1914702', value: 7.3}, {group: 'CHEMBL3524', variable: 'CHEMBL98', value: 5.88}, {group: 'CHEMBL3524', variable: 'CHEMBL99', value: 6.39}, {group: 'CHEMBL3524', variable: 'CHEMBL27759', value: 6.3}, {group: 'CHEMBL3524', variable: 'CHEMBL2018302', value: 6.27}, {group: 'CHEMBL3524', variable: 'CHEMBL483254', value: 6.33}, {group: 'CHEMBL3524', variable: 'CHEMBL1213490', value: 6.35}, {group: 'CHEMBL3524', variable: 'CHEMBL356769', value: 6.25}, {group: 'CHEMBL3524', variable: 'CHEMBL272980', value: 6.25}, {group: 'CHEMBL3524', variable: 'CHEMBL430060', value: 6.33}, {group: 'CHEMBL3524', variable: 'CHEMBL1173445', value: 6.32}, {group: 'CHEMBL3524', variable: 'CHEMBL356066', value: 6.46}, {group: 'CHEMBL3524', variable: 'CHEMBL1914702', value: 6.46}, {group: 'CHEMBL2563', variable: 'CHEMBL98', value: 5.74}, {group: 'CHEMBL2563', variable: 'CHEMBL99', value: 6.12}, {group: 'CHEMBL2563', variable: 'CHEMBL27759', value: 6.11}, {group: 'CHEMBL2563', variable: 'CHEMBL2018302', value: 6.09}, {group: 'CHEMBL2563', variable: 'CHEMBL483254', value: 6.24}, {group: 'CHEMBL2563', variable: 'CHEMBL1213490', value: 6.25}, {group: 'CHEMBL2563', variable: 'CHEMBL356769', value: 6.18}, {group: 'CHEMBL2563', variable: 'CHEMBL272980', value: 6.18}, {group: 'CHEMBL2563', variable: 'CHEMBL430060', value: 6.18}, {group: 'CHEMBL2563', variable: 'CHEMBL1173445', value: 6.18}, {group: 'CHEMBL2563', variable: 'CHEMBL356066', value: 6.24}, {group: 'CHEMBL2563', variable: 'CHEMBL1914702', value: 6.23}, {group: 'CHEMBL1865', variable: 'CHEMBL98', value: 7.36}, {group: 'CHEMBL1865', variable: 'CHEMBL99', value: 7.58}, {group: 'CHEMBL1865', variable: 'CHEMBL27759', value: 7.57}, {group: 'CHEMBL1865', variable: 'CHEMBL2018302', value: 7.59}, {group: 'CHEMBL1865', variable: 'CHEMBL483254', value: 7.62}, {group: 'CHEMBL1865', variable: 'CHEMBL1213490', value: 7.56}, {group: 'CHEMBL1865', variable: 'CHEMBL356769', value: 7.54}, {group: 'CHEMBL1865', variable: 'CHEMBL272980', value: 7.54}, {group: 'CHEMBL1865', variable: 'CHEMBL430060', value: 7.51}, {group: 'CHEMBL1865', variable: 'CHEMBL1173445', value: 7.48}, {group: 'CHEMBL1865', variable: 'CHEMBL356066', value: 7.49}, {group: 'CHEMBL1865', variable: 'CHEMBL1914702', value: 7.49}, {group: 'CHEMBL2716', variable: 'CHEMBL98', value: 5.76}, {group: 'CHEMBL2716', variable: 'CHEMBL99', value: 6.19}, {group: 'CHEMBL2716', variable: 'CHEMBL27759', value: 6.19}, {group: 'CHEMBL2716', variable: 'CHEMBL2018302', value: 6.16}, {group: 'CHEMBL2716', variable: 'CHEMBL483254', value: 6.12}, {group: 'CHEMBL2716', variable: 'CHEMBL1213490', value: 6.11}, {group: 'CHEMBL2716', variable: 'CHEMBL356769', value: 5.98}, {group: 'CHEMBL2716', variable: 'CHEMBL272980', value: 5.98}, {group: 'CHEMBL2716', variable: 'CHEMBL430060', value: 5.98}, {group: 'CHEMBL2716', variable: 'CHEMBL1173445', value: 5.98}, {group: 'CHEMBL2716', variable: 'CHEMBL356066', value: 5.98}, {group: 'CHEMBL2716', variable: 'CHEMBL1914702', value: 5.97}, {group: 'CHEMBL3192', variable: 'CHEMBL98', value: 6.19}, {group: 'CHEMBL3192', variable: 'CHEMBL99', value: 6.28}, {group: 'CHEMBL3192', variable: 'CHEMBL27759', value: 6.24}, {group: 'CHEMBL3192', variable: 'CHEMBL2018302', value: 6.22}, {group: 'CHEMBL3192', variable: 'CHEMBL483254', value: 6.27}, {group: 'CHEMBL3192', variable: 'CHEMBL1213490', value: 6.33}, {group: 'CHEMBL3192', variable: 'CHEMBL356769', value: 6.32}, {group: 'CHEMBL3192', variable: 'CHEMBL272980', value: 6.29}, {group: 'CHEMBL3192', variable: 'CHEMBL430060', value: 6.3}, {group: 'CHEMBL3192', variable: 'CHEMBL1173445', value: 6.29}, {group: 'CHEMBL3192', variable: 'CHEMBL356066', value: 6.31}, {group: 'CHEMBL3192', variable: 'CHEMBL1914702', value: 6.31}, {group: 'CHEMBL4145', variable: 'CHEMBL98', value: 6.14}, {group: 'CHEMBL4145', variable: 'CHEMBL99', value: 6.42}, {group: 'CHEMBL4145', variable: 'CHEMBL27759', value: 6.42}, {group: 'CHEMBL4145', variable: 'CHEMBL2018302', value: 6.38}, {group: 'CHEMBL4145', variable: 'CHEMBL483254', value: 6.36}, {group: 'CHEMBL4145', variable: 'CHEMBL1213490', value: 6.33}, {group: 'CHEMBL4145', variable: 'CHEMBL356769', value: 6.28}, {group: 'CHEMBL4145', variable: 'CHEMBL272980', value: 6.28}, {group: 'CHEMBL4145', variable: 'CHEMBL430060', value: 6.28}, {group: 'CHEMBL4145', variable: 'CHEMBL1173445', value: 6.25}, {group: 'CHEMBL4145', variable: 'CHEMBL356066', value: 6.23}, {group: 'CHEMBL4145', variable: 'CHEMBL1914702', value: 6.26}, {group: 'CHEMBL5103', variable: 'CHEMBL98', value: 6.71}, {group: 'CHEMBL5103', variable: 'CHEMBL99', value: 7.12}, {group: 'CHEMBL5103', variable: 'CHEMBL27759', value: 7.01}, {group: 'CHEMBL5103', variable: 'CHEMBL2018302', value: 6.98}, {group: 'CHEMBL5103', variable: 'CHEMBL483254', value: 7.04}, {group: 'CHEMBL5103', variable: 'CHEMBL1213490', value: 7.1}, {group: 'CHEMBL5103', variable: 'CHEMBL356769', value: 7.0}, {group: 'CHEMBL5103', variable: 'CHEMBL272980', value: 7.0}, {group: 'CHEMBL5103', variable: 'CHEMBL430060', value: 7.0}, {group: 'CHEMBL5103', variable: 'CHEMBL1173445', value: 6.97}, {group: 'CHEMBL5103', variable: 'CHEMBL356066', value: 6.99}, {group: 'CHEMBL5103', variable: 'CHEMBL1914702', value: 6.98}, {group: 'CHEMBL3310', variable: 'CHEMBL98', value: 6.7}, {group: 'CHEMBL3310', variable: 'CHEMBL99', value: 6.91}, {group: 'CHEMBL3310', variable: 'CHEMBL27759', value: 6.86}, {group: 'CHEMBL3310', variable: 'CHEMBL2018302', value: 6.82}, {group: 'CHEMBL3310', variable: 'CHEMBL483254', value: 6.79}, {group: 'CHEMBL3310', variable: 'CHEMBL1213490', value: 6.85}, {group: 'CHEMBL3310', variable: 'CHEMBL356769', value: 6.74}, {group: 'CHEMBL3310', variable: 'CHEMBL272980', value: 6.72}, {group: 'CHEMBL3310', variable: 'CHEMBL430060', value: 6.72}, {group: 'CHEMBL3310', variable: 'CHEMBL1173445', value: 6.72}, {group: 'CHEMBL3310', variable: 'CHEMBL356066', value: 6.75}, {group: 'CHEMBL3310', variable: 'CHEMBL1914702', value: 6.76}];

  // set the dimensions and margins of the graph
  var margin = {top: 30, right: 100, bottom: 30, left: 100},
    width = 600 - margin.left - margin.right,
    height = 450 - margin.top - margin.bottom;

  // append the svg object to the body of the page
  var svg = d3.select("#my_dataviz")
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

  // Labels of row and columns
  var myGroups = ["CHEMBL325", "CHEMBL1937", "CHEMBL1829", "CHEMBL3524", "CHEMBL2563", "CHEMBL1865", "CHEMBL2716", "CHEMBL3192", "CHEMBL4145", "CHEMBL5103", "CHEMBL3310"]
  var myVars = ["CHEMBL98", "CHEMBL99", "CHEMBL27759", "CHEMBL2018302", "CHEMBL483254", "CHEMBL1213490", "CHEMBL356769", "CHEMBL272980", "CHEMBL430060", "CHEMBL1173445", "CHEMBL356066", "CHEMBL1914702"]

  // Build X scales and axis:
  var x = d3.scaleBand()
    .range([ 0, width ])
    .domain(myGroups)
    .padding(0.01);
  svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x))
    .selectAll("text")
    .attr("y", 0)
    .attr("x", 9)
    .attr("dy", ".35em")
    .attr("transform", "rotate(60)")
    .style("text-anchor", "start");

  // Build Y scales and axis:
  var y = d3.scaleBand()
    .range([ height, 0 ])
    .domain(myVars)
    .padding(0.01);
  svg.append("g")
    .call(d3.axisLeft(y));

  // Build color scale
  var myColor = d3.scaleLinear()
    .range(["#ffffff", "#c60606"])
    .domain([5,9])

  //Read the data and add squares
  svg.selectAll()
    .data(data, function(d) {return d.group+':'+d.variable;})
    .enter()
    .append("rect")
    .attr("x", function(d) { return x(d.group) })
    .attr("y", function(d) { return y(d.variable) })
    .attr("width", x.bandwidth() )
    .attr("height", y.bandwidth() )
    .style("fill", function(d) { return myColor(d.value)} )

</script>
</code>```

There is the output that I am getting.

答:
I have checked your code and there is no mistake. The values are so close that you cannot see the difference.

But you can definitely improve this by improving your color scale. Instead of fixing minimum and maximum value. You can find it from data like below:

// Build color scale
  var myColor = d3.scaleLinear()
    .range(["#ffffff", "#c60606"])
    .domain([d3.min(data, function(d) { return d.value}), d3.max(data, function(d) { return d.value})])

You will be able to see that their is slight difference in colors. I hope it resolves your issue.

<!DOCTYPE html>
<meta charset="utf-8">

```

Body:
I have the following HTML document with JavaScript embedded where I try to plot a list of JavaScript objects in a d3.js heatmap. But it seems to only show the data of the first row repeatedly on every row. Any help will be greatly appreciated. This is my code and output:

<!DOCTYPE html>
<meta charset="utf-8">

There is the output that I am getting.

Body:
I have checked your code and there is no mistake. The values are so close that you cannot see the difference.

But you can definitely improve this by improving your color scale. Instead of fixing minimum and maximum value. You can find it from data like below:

// Build color scale
  var myColor = d3.scaleLinear()
    .range(["#ffffff", "#c60606"])
    .domain([d3.min(data, function(d) { return d.value}), d3.max(data, function(d) { return d.value})])

You will be able to see that their is slight difference in colors. I hope it resolves your issue.

<!-- Code from d3-graph-gallery.com -->
<!DOCTYPE html>
<meta charset="utf-8">

<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>

<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>

<script>
  // Heatmap data loading
  //document.getElementById("data_display").innerHTML = csvDataString;  //DEBUG

  //var data = {{ heatmap_data|tojson }};

  data = [{
    group: 'CHEMBL325',
    variable: 'CHEMBL98',
    value: 7.2
  }, {
    group: 'CHEMBL325',
    variable: 'CHEMBL99',
    value: 7.43
  }, {
    group: 'CHEMBL325',
    variable: 'CHEMBL27759',
    value: 7.31
  }, {
    group: 'CHEMBL325',
    variable: 'CHEMBL2018302',
    value: 7.19
  }, {
    group: 'CHEMBL325',
    variable: 'CHEMBL483254',
    value: 7.24
  }, {
    group: 'CHEMBL325',
    variable: 'CHEMBL1213490',
    value: 7.26
  }, {
    group: 'CHEMBL325',
    variable: 'CHEMBL356769',
    value: 7.23
  }, {
    group: 'CHEMBL325',
    variable: 'CHEMBL272980',
    value: 7.21
  }, {
    group: 'CHEMBL325',
    variable: 'CHEMBL430060',
    value: 7.23
  }, {
    group: 'CHEMBL325',
    variable: 'CHEMBL1173445',
    value: 7.23
  }, {
    group: 'CHEMBL325',
    variable: 'CHEMBL356066',
    value: 7.26
  }, {
    group: 'CHEMBL325',
    variable: 'CHEMBL1914702',
    value: 7.26
  }, {
    group: 'CHEMBL1937',
    variable: 'CHEMBL98',
    value: 6.94
  }, {
    group: 'CHEMBL1937',
    variable: 'CHEMBL99',
    value: 7.17
  }, {
    group: 'CHEMBL1937',
    variable: 'CHEMBL27759',
    value: 7.09
  }, {
    group: 'CHEMBL1937',
    variable: 'CHEMBL2018302',
    value: 7.06
  }, {
    group: 'CHEMBL1937',
    variable: 'CHEMBL483254',
    value: 7.14
  }, {
    group: 'CHEMBL1937',
    variable: 'CHEMBL1213490',
    value: 7.19
  }, {
    group: 'CHEMBL1937',
    variable: 'CHEMBL356769',
    value: 7.14
  }, {
    group: 'CHEMBL1937',
    variable: 'CHEMBL272980',
    value: 7.13
  }, {
    group: 'CHEMBL1937',
    variable: 'CHEMBL430060',
    value: 7.16
  }, {
    group: 'CHEMBL1937',
    variable: 'CHEMBL1173445',
    value: 7.14
  }, {
    group: 'CHEMBL1937',
    variable: 'CHEMBL356066',
    value: 7.18
  }, {
    group: 'CHEMBL1937',
    variable: 'CHEMBL1914702',
    value: 7.17
  }, {
    group: 'CHEMBL1829',
    variable: 'CHEMBL98',
    value: 7.18
  }, {
    group: 'CHEMBL1829',
    variable: 'CHEMBL99',
    value: 7.37
  }, {
    group: 'CHEMBL1829',
    variable: 'CHEMBL27759',
    value: 7.24
  }, {
    group: 'CHEMBL1829',
    variable: 'CHEMBL2018302',
    value: 7.22
  }, {
    group: 'CHEMBL1829',
    variable: 'CHEMBL483254',
    value: 7.31
  }, {
    group: 'CHEMBL1829',
    variable: 'CHEMBL1213490',
    value: 7.35
  }, {
    group: 'CHEMBL1829',
    variable: 'CHEMBL356769',
    value: 7.31
  }, {
    group: 'CHEMBL1829',
    variable: 'CHEMBL272980',
    value: 7.24
  }, {
    group: 'CHEMBL1829',
    variable: 'CHEMBL430060',
    value: 7.29
  }, {
    group: 'CHEMBL1829',
    variable: 'CHEMBL1173445',
    value: 7.25
  }, {
    group: 'CHEMBL1829',
    variable: 'CHEMBL356066',
    value: 7.3
  }, {
    group: 'CHEMBL1829',
    variable: 'CHEMBL1914702',
    value: 7.3
  }, {
    group: 'CHEMBL3524',
    variable: 'CHEMBL98',
    value: 5.88
  }, {
    group: 'CHEMBL3524',
    variable: 'CHEMBL99',
    value: 6.39
  }, {
    group: 'CHEMBL3524',
    variable: 'CHEMBL27759',
    value: 6.3
  }, {
    group: 'CHEMBL3524',
    variable: 'CHEMBL2018302',
    value: 6.27
  }, {
    group: 'CHEMBL3524',
    variable: 'CHEMBL483254',
    value: 6.33
  }, {
    group: 'CHEMBL3524',
    variable: 'CHEMBL1213490',
    value: 6.35
  }, {
    group: 'CHEMBL3524',
    variable: 'CHEMBL356769',
    value: 6.25
  }, {
    group: 'CHEMBL3524',
    variable: 'CHEMBL272980',
    value: 6.25
  }, {
    group: 'CHEMBL3524',
    variable: 'CHEMBL430060',
    value: 6.33
  }, {
    group: 'CHEMBL3524',
    variable: 'CHEMBL1173445',
    value: 6.32
  }, {
    group: 'CHEMBL3524',
    variable: 'CHEMBL356066',
    value: 6.46
  }, {
    group: 'CHEMBL3524',
    variable: 'CHEMBL1914702',
    value: 6.46
  }, {
    group: 'CHEMBL2563',
    variable: 'CHEMBL98',
    value: 5.74
  }, {
    group: 'CHEMBL2563',
    variable: 'CHEMBL99',
    value: 6.12
  }, {
    group: 'CHEMBL2563',
    variable: 'CHEMBL27759',
    value: 6.11
  }, {
    group: 'CHEMBL2563',
    variable: 'CHEMBL2018302',
    value: 6.09
  }, {
    group: 'CHEMBL2563',
    variable: 'CHEMBL483254',
    value: 6.24
  }, {
    group: 'CHEMBL2563',
    variable: 'CHEMBL1213490',
    value: 6.25
  }, {
    group: 'CHEMBL2563',
    variable: 'CHEMBL356769',
    value: 6.18
  }, {
    group: 'CHEMBL2563',
    variable: 'CHEMBL272980',
    value: 6.18
  }, {
    group: 'CHEMBL2563',
    variable: 'CHEMBL430060',
    value: 6.18
  }, {
    group: 'CHEMBL2563',
    variable: 'CHEMBL1173445',
    value: 6.18
  }, {
    group: 'CHEMBL2563',
    variable: 'CHEMBL356066',
    value: 6.24
  }, {
    group: 'CHEMBL2563',
    variable: 'CHEMBL1914702',
    value: 6.23
  }, {
    group: 'CHEMBL1865',
    variable: 'CHEMBL98',
    value: 7.36
  }, {
    group: 'CHEMBL1865',
    variable: 'CHEMBL99',
    value: 7.58
  }, {
    group: 'CHEMBL1865',
    variable: 'CHEMBL27759',
    value: 7.57
  }, {
    group: 'CHEMBL1865',
    variable: 'CHEMBL2018302',
    value: 7.59
  }, {
    group: 'CHEMBL1865',
    variable: 'CHEMBL483254',
    value: 7.62
  }, {
    group: 'CHEMBL1865',
    variable: 'CHEMBL1213490',
    value: 7.56
  }, {
    group: 'CHEMBL1865',
    variable: 'CHEMBL356769',
    value: 7.54
  }, {
    group: 'CHEMBL1865',
    variable: 'CHEMBL272980',
    value: 7.54
  }, {
    group: 'CHEMBL1865',
    variable: 'CHEMBL430060',
    value: 7.51
  }, {
    group: 'CHEMBL1865',
    variable: 'CHEMBL1173445',
    value: 7.48
  }, {
    group: 'CHEMBL1865',
    variable: 'CHEMBL356066',
    value: 7.49
  }, {
    group: 'CHEMBL1865',
    variable: 'CHEMBL1914702',
    value: 7.49
  }, {
    group: 'CHEMBL2716',
    variable: 'CHEMBL98',
    value: 5.76
  }, {
    group: 'CHEMBL2716',
    variable: 'CHEMBL99',
    value: 6.19
  }, {
    group: 'CHEMBL2716',
    variable: 'CHEMBL27759',
    value: 6.19
  }, {
    group: 'CHEMBL2716',
    variable: 'CHEMBL2018302',
    value: 6.16
  }, {
    group: 'CHEMBL2716',
    variable: 'CHEMBL483254',
    value: 6.12
  }, {
    group: 'CHEMBL2716',
    variable: 'CHEMBL1213490',
    value: 6.11
  }, {
    group: 'CHEMBL2716',
    variable: 'CHEMBL356769',
    value: 5.98
  }, {
    group: 'CHEMBL2716',
    variable: 'CHEMBL272980',
    value: 5.98
  }, {
    group: 'CHEMBL2716',
    variable: 'CHEMBL430060',
    value: 5.98
  }, {
    group: 'CHEMBL2716',
    variable: 'CHEMBL1173445',
    value: 5.98
  }, {
    group: 'CHEMBL2716',
    variable: 'CHEMBL356066',
    value: 5.98
  }, {
    group: 'CHEMBL2716',
    variable: 'CHEMBL1914702',
    value: 5.97
  }, {
    group: 'CHEMBL3192',
    variable: 'CHEMBL98',
    value: 6.19
  }, {
    group: 'CHEMBL3192',
    variable: 'CHEMBL99',
    value: 6.28
  }, {
    group: 'CHEMBL3192',
    variable: 'CHEMBL27759',
    value: 6.24
  }, {
    group: 'CHEMBL3192',
    variable: 'CHEMBL2018302',
    value: 6.22
  }, {
    group: 'CHEMBL3192',
    variable: 'CHEMBL483254',
    value: 6.27
  }, {
    group: 'CHEMBL3192',
    variable: 'CHEMBL1213490',
    value: 6.33
  }, {
    group: 'CHEMBL3192',
    variable: 'CHEMBL356769',
    value: 6.32
  }, {
    group: 'CHEMBL3192',
    variable: 'CHEMBL272980',
    value: 6.29
  }, {
    group: 'CHEMBL3192',
    variable: 'CHEMBL430060',
    value: 6.3
  }, {
    group: 'CHEMBL3192',
    variable: 'CHEMBL1173445',
    value: 6.29
  }, {
    group: 'CHEMBL3192',
    variable: 'CHEMBL356066',
    value: 6.31
  }, {
    group: 'CHEMBL3192',
    variable: 'CHEMBL1914702',
    value: 6.31
  }, {
    group: 'CHEMBL4145',
    variable: 'CHEMBL98',
    value: 6.14
  }, {
    group: 'CHEMBL4145',
    variable: 'CHEMBL99',
    value: 6.42
  }, {
    group: 'CHEMBL4145',
    variable: 'CHEMBL27759',
    value: 6.42
  }, {
    group: 'CHEMBL4145',
    variable: 'CHEMBL2018302',
    value: 6.38
  }, {
    group: 'CHEMBL4145',
    variable: 'CHEMBL483254',
    value: 6.36
  }, {
    group: 'CHEMBL4145',
    variable: 'CHEMBL1213490',
    value: 6.33
  }, {
    group: 'CHEMBL4145',
    variable: 'CHEMBL356769',
    value: 6.28
  }, {
    group: 'CHEMBL4145',
    variable: 'CHEMBL272980',
    value: 6.28
  }, {
    group: 'CHEMBL4145',
    variable: 'CHEMBL430060',
    value: 6.28
  }, {
    group: 'CHEMBL4145',
    variable: 'CHEMBL1173445',
    value: 6.25
  }, {
    group: 'CHEMBL4145',
    variable: 'CHEMBL356066',
    value: 6.23
  }, {
    group: 'CHEMBL4145',
    variable: 'CHEMBL1914702',
    value: 6.26
  }, {
    group: 'CHEMBL5103',
    variable: 'CHEMBL98',
    value: 6.71
  }, {
    group: 'CHEMBL5103',
    variable: 'CHEMBL99',
    value: 7.12
  }, {
    group: 'CHEMBL5103',
    variable: 'CHEMBL27759',
    value: 7.01
  }, {
    group: 'CHEMBL5103',
    variable: 'CHEMBL2018302',
    value: 6.98
  }, {
    group: 'CHEMBL5103',
    variable: 'CHEMBL483254',
    value: 7.04
  }, {
    group: 'CHEMBL5103',
    variable: 'CHEMBL1213490',
    value: 7.1
  }, {
    group: 'CHEMBL5103',
    variable: 'CHEMBL356769',
    value: 7.0
  }, {
    group: 'CHEMBL5103',
    variable: 'CHEMBL272980',
    value: 7.0
  }, {
    group: 'CHEMBL5103',
    variable: 'CHEMBL430060',
    value: 7.0
  }, {
    group: 'CHEMBL5103',
    variable: 'CHEMBL1173445',
    value: 6.97
  }, {
    group: 'CHEMBL5103',
    variable: 'CHEMBL356066',
    value: 6.99
  }, {
    group: 'CHEMBL5103',
    variable: 'CHEMBL1914702',
    value: 6.98
  }, {
    group: 'CHEMBL3310',
    variable: 'CHEMBL98',
    value: 6.7
  }, {
    group: 'CHEMBL3310',
    variable: 'CHEMBL99',
    value: 6.91
  }, {
    group: 'CHEMBL3310',
    variable: 'CHEMBL27759',
    value: 6.86
  }, {
    group: 'CHEMBL3310',
    variable: 'CHEMBL2018302',
    value: 6.82
  }, {
    group: 'CHEMBL3310',
    variable: 'CHEMBL483254',
    value: 6.79
  }, {
    group: 'CHEMBL3310',
    variable: 'CHEMBL1213490',
    value: 6.85
  }, {
    group: 'CHEMBL3310',
    variable: 'CHEMBL356769',
    value: 6.74
  }, {
    group: 'CHEMBL3310',
    variable: 'CHEMBL272980',
    value: 6.72
  }, {
    group: 'CHEMBL3310',
    variable: 'CHEMBL430060',
    value: 6.72
  }, {
    group: 'CHEMBL3310',
    variable: 'CHEMBL1173445',
    value: 6.72
  }, {
    group: 'CHEMBL3310',
    variable: 'CHEMBL356066',
    value: 6.75
  }, {
    group: 'CHEMBL3310',
    variable: 'CHEMBL1914702',
    value: 6.76
  }];

  // set the dimensions and margins of the graph
  var margin = {
      top: 30,
      right: 100,
      bottom: 100,
      left: 100
    },
    width = 600 - margin.left - margin.right,
    height = 450 - margin.top - margin.bottom;

  // append the svg object to the body of the page
  var svg = d3.select("#my_dataviz")
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform",
      "translate(" + margin.left + "," + margin.top + ")");

  // Labels of row and columns
  var myGroups = ["CHEMBL325", "CHEMBL1937", "CHEMBL1829", "CHEMBL3524", "CHEMBL2563", "CHEMBL1865", "CHEMBL2716", "CHEMBL3192", "CHEMBL4145", "CHEMBL5103", "CHEMBL3310"]
  var myVars = ["CHEMBL98", "CHEMBL99", "CHEMBL27759", "CHEMBL2018302", "CHEMBL483254", "CHEMBL1213490", "CHEMBL356769", "CHEMBL272980", "CHEMBL430060", "CHEMBL1173445", "CHEMBL356066", "CHEMBL1914702"]

  // Build X scales and axis:
  var x = d3.scaleBand()
    .range([0, width])
    .domain(myGroups)
    .padding(0.01);
  svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x))
    .selectAll("text")
    .attr("y", 0)
    .attr("x", 9)
    .attr("dy", ".35em")
    .attr("transform", "rotate(60)")
    .style("text-anchor", "start");

  // Build Y scales and axis:
  var y = d3.scaleBand()
    .range([height, 0])
    .domain(myVars)
    .padding(0.01);
  svg.append("g")
    .call(d3.axisLeft(y));

  // Build color scale
  var myColor = d3.scaleLinear()
    .range(["#ffffff", "#c60606"])
    .domain([d3.min(data, function(d) { return d.value}), d3.max(data, function(d) { return d.value})])

  //Read the data and add squares
  svg.selectAll()
    .data(data, function(d) {
      return d.group + ':' + d.variable;
    })
    .enter()
    .append("rect")
    .attr("x", function(d) {
      return x(d.group)
    })
    .attr("y", function(d) {
      return y(d.variable)
    })
    .attr("width", x.bandwidth())
    .attr("height", y.bandwidth())
    .style("fill", function(d) {
      return myColor(d.value)
    })

</script>


问:
Countdown var to loop and display array
I'm very new to javascript and I'm trying to do something I thought would be very basic.

I've created a countdown timer and used "i" as my variable to hold a number from 0-5. And I have an array of "d" from d[0] to d[5] containing strings.

I'm trying to make the timer countdown pass the "i" value into an innerHTML method array value so I want it to display d[5]... d[4]...d[3]... etc.

What am I doing wrong!? Please Help!

```<code><html><head><script language="javascript" type="text/javascript">

var d=new Array():
    d[1]="One";
    d[2]="Two";
    d[3]="Three";
    d[4]="Four";
    d[5]="Five";

    var i=5;

    var i=setInterval("timer()",2000); //1000 will  run it every 1 second

    function timer() {
        i--;
        if (i <= 0)

 clearInterval(countD);
 return;
      }
 }

 document.getElementById(timer).innerHTML = d[i];

 </script>

 </head>
 <body>

 <h1>
 <p id="timer"></p>
 </h1>

 </body>
 </html>
</code>```

答:
Also, document.getElementById(timer).innerHTML = d[i];

should be document.getElementById("timer").innerHTML = d[i];

id names need to have quotes around them because they are not names of variables. The variable 'timer' is undefined.

Also, you are missing a curly brace on the line if (i <= 0). I am assuming that you meant to exit the function if this if statement is true.

Also, you have a colon instead of a semicolon on the line var d=new Array():

Also, you can't have a paragraph tag inside of an h1

Also, you should encapsulate all of this javascript into a function called something like init. I believe that the javascript code in the head runs before the html is loaded. The javascript can't therefore find the
 tag. Then, use  as your body tag.

EDIT: As the commenters have stated, you are using the variable i for multiple unrelated things.

Title: Countdown var to loop and display array

Body:
Also, document.getElementById(timer).innerHTML = d[i];

should be document.getElementById("timer").innerHTML = d[i];

id names need to have quotes around them because they are not names of variables. The variable 'timer' is undefined.

Also, you are missing a curly brace on the line if (i <= 0). I am assuming that you meant to exit the function if this if statement is true.

Also, you have a colon instead of a semicolon on the line var d=new Array():

Also, you can't have a paragraph tag inside of an h1

Also, you should encapsulate all of this javascript into a function called something like init. I believe that the javascript code in the head runs before the html is loaded. The javascript can't therefore find the
 tag. Then, use <body onload="init()"> as your body tag.

EDIT: As the commenters have stated, you are using the variable i for multiple unrelated things.


问:
Why is Python OpenCV camera read in Ubuntu slower than Windows?
I have a really simple code to view video from web-cam (Microsoft HD LifeCam Studio) as follow:

```<code>import cv2
from imutils.video import FPS

cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
fps = FPS().start()

while cap.isOpened():
    _,frame = cap.read()
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    fps.update()
fps.stop()
print("{}".format(fps.fps()))

cap.release()
cv2.destroyAllWindows()
</code>```

The code will print out the FPS when the program ends.

When running this code on Windows, I receive 30 FPS. However, when running on Ubuntu, I only receive 10 FPS.

I have tried cap.set(cv2.cv.CV_CAP_PROP_FPS, 30) but it does not work.

Does anyone experience the same situation? Is there any solution for this problem?

I'm running Windows 10 and Ubuntu 16.04
Python 3.5.2
OpenCV 3.4.0

答: The problem lies on how I install the OpenCV framework. In Ubuntu, I use pip to install the OpenCV which causes the weak performance. Instead of using pip, I built OpenCV from the source code which enhance the performance to the same as in Windows.

Body:
I have a really simple code to view video from web-cam (Microsoft HD LifeCam Studio) as follow:

import cv2
from imutils.video import FPS

cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
fps = FPS().start()

while cap.isOpened():
    _,frame = cap.read()
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    fps.update()
fps.stop()
print("{}".format(fps.fps()))

cap.release()
cv2.destroyAllWindows()

The code will print out the FPS when the program ends.

When running this code on Windows, I receive 30 FPS. However, when running on Ubuntu, I only receive 10 FPS.

I have tried cap.set(cv2.cv.CV_CAP_PROP_FPS, 30) but it does not work.

Does anyone experience the same situation? Is there any solution for this problem?

I'm running Windows 10 and Ubuntu 16.04
Python 3.5.2
OpenCV 3.4.0


问:
Removing spaces from a input form string with JavaScript and PHP?

Considering this input form, how do you remove the spaces on copy and paste into the form?

How do you remove spaces from the request when passing this value to the database?

答:
var activities = document.getElementById("fieldname");

activities.addEventListener("change", function() {
  value = activities.value;
  value = value.replace(/\s/g, "");
  activities.value = value;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
   <input type="text" id="fieldname">
</body>
</html></code>```

Body:
var activities = document.getElementById("fieldname");

activities.addEventListener("change", function() {
  value = activities.value;
  value = value.replace(/\s/g, "");
  activities.value = value;
});

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
   <input type="text" id="fieldname">
</body>
</html>


问:
Securing static html files cross domain
I have multiple .NET projects that allow authenticated users to browse html files on another domain via iframe.

I'm struggling with securing these files so that no user can take the link from the iframe and share that link.

The projects are hosted on iis, and users are authenticated with a JWT token.

Any help is appreciated.

答:
I'm afraid it is unavailable to prevent user from getting link from your iframe because they are always able to view the link via developer tool.

But you could create a URL rewrite rule to strict the src link can only be accessed from your website by checking HTTP_REFERR header.

If the referrer domain incorrect or null, then your rule will block it.

Title: Securing static html files cross domain


答:
If you can just remove the content, you can use:

```<code>var all = document.getElementsByTagName("div");
for(i=0; i < all.length; i++) {
    all[i].innerHTML = ""
}
</code>```

See http://jsfiddle.net/7KVkC/

Title: remove div without an id tag

Body:
I need a solution to remove a div without an ID tag in JavaScript only. The div looks like this
.

Here is the full structure.

Body:
If you can just remove the content, you can use:

var all = document.getElementsByTagName("div");
for(i=0; i < all.length; i++) {
    all[i].innerHTML = ""
}

See http://jsfiddle.net/7KVkC/


问:
PHP Excel can't save on folder
I want to save my excel file to my server.

Folder location is public_html/PHPExcel/generated/

Please see code below:

```<code>header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="filename.xls"');
        header('Cache-Control: max-age=0');

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save(str_replace(__FILE__,'public_html/PHPExcel/generated/filename.xls',__FILE__));
</code>```

Thank you

答:
Hope this help you.</p>

```<code>header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");;
header("Content-Disposition: attachment;filename=$filename");
header("Content-Transfer-Encoding: binary ");
$filename= 'xyz.xlsx';
$objWriter->save($filename);
</code>```

Title: PHP Excel can't save on folder

Body:
I want to save my excel file to my server.

Folder location is public_html/PHPExcel/generated/

Please see code below:

header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="filename.xls"');
        header('Cache-Control: max-age=0');

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save(str_replace(__FILE__,'public_html/PHPExcel/generated/filename.xls',__FILE__));

Thank you

Body:
Hope this help you.

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");;
header("Content-Disposition: attachment;filename=$filename");
header("Content-Transfer-Encoding: binary ");
$filename= 'xyz.xlsx';
$objWriter->save($filename);


问:
Download in documents directory or move file async - iOS
I am building an iOS app in which the user can download different files.

I am using an URLSessionDownloadTask and an URLSession to download a file asynchronously.
When the download is finished, the destination folder is by default, the tmp/ directory.

So, when the download ends, I need to move the temporary file to another directory.
For a picture or a song, this takes only 1 second maybe even less.
 But when the file is a video for example, it can take up to 15 seconds.

The issue

To allow the user to still interact with the app, I would like to make this move asynchronous.
Each time I try to do that, the file manager throws an exception.

“CFNetworkDownload_xxxxxx.tmp” couldn’t be moved to “Downloads” because either the former doesn't exist, or the folder containing the latter doesn't exist.

What have I tried

I tried to put the call to the file manager in a background thread, it throws.

I tried to remove the destination file before calling the move method, to make sure that the file doesn't already exists.

I tried to make a call to the copy function, before removing the file from the tmp/ directory.

My code

The call to the file manager looks like that.

```<code>func simpleMove(from location: URL, to dest: URL) -> Bool {
    let fileManager = FileManager.default
    do {
        try fileManager.moveItem(at: location, to: dest)
        return true
    } catch {
        print("\(error.localizedDescription)")
        return false
    }
}
</code>```

When I put that in a background thread, I do it like that.

```<code>DispatchQueue.global().async {
    if !simpleMove(from: location, to: dest) {
        //Failure
    }
}
</code>```

Questions

How can I possibly move a really large file without affecting the UI?

It would be an even better solution to download the file directly in a permanent directory. How can I do that?

When I make the call to my simpleMove(from:to:) synchronously, it works perfectly.
So, why the error says that the destination directory doesn't exists? (or something like that, I'm not sure of the meaning of that error)

Thanks.

Note

The code above is written in Swift 3, but if you have an Objective-C or a Swift 2 answer,
feel free to share it as well!

答:
Amusingly, the correct answer to this was posted in another question, where it was not the correct answer.

The solution is covered in Apple's Documentation where they state:

location

A file URL for the temporary file. Because the file is temporary, you must either open the file for reading or move it to a permanent location in your app’s sandbox container directory before returning from this delegate method.

If you choose to open the file for reading, you should do the actual reading in another thread to avoid blocking the delegate queue.

You are probably calling simpleMove from the success handler for the DownloadTask.  When you call simpleMove on a background thread, the success handler returns and your temp file is cleaned up before simpleMove is even called.

The solution is to do as Apple says and open the file for reading:

public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    do {
        let file: FileHandle = try FileHandle(forReadingFrom: location)

        DispatchQueue.global().async {
            let data = file.readDataToEndOfFile()
            FileManager().createFile(atPath: destination, contents: data, attributes: nil)
        }
    } catch {
        // Handle error
    }
}
```

Body:
I am building an iOS app in which the user can download different files.

I am using an URLSessionDownloadTask and an URLSession to download a file asynchronously.
When the download is finished, the destination folder is by default, the tmp/ directory.

So, when the download ends, I need to move the temporary file to another directory.
For a picture or a song, this takes only 1 second maybe even less.
 But when the file is a video for example, it can take up to 15 seconds.

The issue

To allow the user to still interact with the app, I would like to make this move asynchronous.
Each time I try to do that, the file manager throws an exception.

“CFNetworkDownload_xxxxxx.tmp” couldn’t be moved to “Downloads” because either the former doesn't exist, or the folder containing the latter doesn't exist.

What have I tried

I tried to put the call to the file manager in a background thread, it throws.

I tried to remove the destination file before calling the move method, to make sure that the file doesn't already exists.

I tried to make a call to the copy function, before removing the file from the tmp/ directory.

My code

The call to the file manager looks like that.

func simpleMove(from location: URL, to dest: URL) -> Bool {
    let fileManager = FileManager.default
    do {
        try fileManager.moveItem(at: location, to: dest)
        return true
    } catch {
        print("\(error.localizedDescription)")
        return false
    }
}

When I put that in a background thread, I do it like that.

DispatchQueue.global().async {
    if !simpleMove(from: location, to: dest) {
        //Failure
    }
}

Questions

How can I possibly move a really large file without affecting the UI?

It would be an even better solution to download the file directly in a permanent directory. How can I do that?

When I make the call to my simpleMove(from:to:) synchronously, it works perfectly.
So, why the error says that the destination directory doesn't exists? (or something like that, I'm not sure of the meaning of that error)

Thanks.

Note

The code above is written in Swift 3, but if you have an Objective-C or a Swift 2 answer,
feel free to share it as well!


问:
How to enable word level Confidence for MS Azure Speech to Text Service
How to get word-level confidence for each word using MS  Azure speech to text service? Currently, I am getting confidence value for sentence-level and I need word-level confidence for further processing.</p>

答:
You can retrieve the wordLevelConfidence by adding the  ‘format=detailed’ & ‘wordLevelConfidence=true’ to the URI

For example, the language set to US English using the West US endpoint is: https://westus.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US&format=detailed&wordLevelConfidence=true.

If you use the SDK:

```<code>var config = SpeechConfig.FromSubscription(sub, "westeurope");
config.SetServiceProperty("wordLevelConfidence", "true", ServicePropertyChannel.UriQueryParameter);
//config.RequestWordLevelTimestamps(); in case you also want wordleveltimestamps
config.OutputFormat = OutputFormat.Detailed;
</code>```

the word confidence values are not part of the result directly, Take a look at the below for complete result in JSON form.
recognizer.Recognized += (s, e) =>
                    {
                     var j = e.Result.Properties.GetProperty(PropertyId.SpeechServiceResponse_JsonResult);

Body:
You can retrieve the wordLevelConfidence by adding the  ‘format=detailed’ & ‘wordLevelConfidence=true’ to the URI

For example, the language set to US English using the West US endpoint is: https://westus.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US&format=detailed&wordLevelConfidence=true.

If you use the SDK:

var config = SpeechConfig.FromSubscription(sub, "westeurope");
config.SetServiceProperty("wordLevelConfidence", "true", ServicePropertyChannel.UriQueryParameter);
//config.RequestWordLevelTimestamps(); in case you also want wordleveltimestamps
config.OutputFormat = OutputFormat.Detailed;

the word confidence values are not part of the result directly, Take a look at the below for complete result in JSON form.
recognizer.Recognized += (s, e) =>
                    {
                     var j = e.Result.Properties.GetProperty(PropertyId.SpeechServiceResponse_JsonResult);