问:
Microformats Specifically hreview-aggregate
I had a question about microfomats and more specifically hreview-aggregate. A client implemented them a while ago but they are not showing in the SERPs however Google's rich snippet testing tool shows them working perfectly. I took a look at the code and it is currently

```<code><div class="hreview-aggregate">
            <div class="rating-45 clearfix">
                <span class="rating" title="4.383 of 5 stars">4.383 of 5 stars</span>
                <a tabindex="0" href="https://www.example.com/category/" title="View all xxxx Reviews">
                <span class="count">View all xxxx Reviews</span>
                </a>
            </div>
        </div>
</code>```

I changed it up to include class="average" class="best" and a few other spans that they were missing.

```<code><div class="hreview-aggregate">
            <div class="rating-45 clearfix">
                <span class="rating" title="4.383 of 5 stars"><span class="average">4.383</span> of <span class="best">5</span> stars</span>
                <a tabindex="0" href="https://www.example.com/category/" title="View all xxxx Reviews">
                View all <span class="count">xxxx</span> Reviews
                </a>
            </div>
        </div>
</code>```

Will the updated code finally show in the SERPs? Also, the page only has the rating but no reviews, should I use COUNT or VOTES?

答:
This is an old question but to those still using hreview-aggregate.

The structure more or less is as follows:

```<code><div class="hreview-aggregate">
<div class="item">
    <span class="fn">Item Name</span>
</div>
<div class="rating">
    <span class="average">3.5</span>
    <span class="best">5</span>
    <span class="count">15</span>
</div>
</code>```

In your code you should have something like this:

```<code><div class="hreview-aggregate">
<div class="item">
    <span class="fn">Item Name</span>
</div>
        <div class="rating-45 rating clearfix">
            <span title="4.383 of 5 stars"><span class="average">4.383</span> of <span class="best">5</span> stars</span>
            <a tabindex="0" href="https://www.example.com/category/" title="View all xxxx Reviews">
            View all <span class="count">10</span> Reviews
            </a>
        </div>
    </div>
</code>```

So that it fully validates with: https://search.google.com/structured-data/testing-tool

Should I use COUNT or VOTES?

From the microformat doc itself: http://microformats.org/wiki/hreview-aggregate

count:: This property is used to specify the total number of reviews for the product or service.

votes:: This property is used to specify the total number of users who have rated the product or service, contributing to the average rating. For some sites, the number of votes is equal to the number of reviews, so count may be used and this property omitted.

in your case, see my example with count as I believe this is most applicable to you.

As mentioned before there are several factors that can cause google not to show it.

Google itself says:

When Google finds valid reviews or ratings markup, we may show a rich snippet that includes stars and other summary info from reviews or ratings.

Keyword: MAY

https://developers.google.com/search/docs/data-types/reviews#review-snippets

from my experience they usually do, just make sure its properly formatted and validated.

Body:
I had a question about microfomats and more specifically hreview-aggregate. A client implemented them a while ago but they are not showing in the SERPs however Google's rich snippet testing tool shows them working perfectly. I took a look at the code and it is currently

                4.383 of 5 stars

                View all xxxx Reviews

I changed it up to include class="average" class="best" and a few other spans that they were missing.

                4.383 of 5 stars

                View all xxxx Reviews

Will the updated code finally show in the SERPs? Also, the page only has the rating but no reviews, should I use COUNT or VOTES?

Body:
This is an old question but to those still using hreview-aggregate.

The structure more or less is as follows:

<div class="hreview-aggregate">
<div class="item">
    <span class="fn">Item Name</span>
</div>
<div class="rating">
    <span class="average">3.5</span>
    <span class="best">5</span>
    <span class="count">15</span>
</div>

In your code you should have something like this:

<div class="hreview-aggregate">
<div class="item">
    <span class="fn">Item Name</span>
</div>
        <div class="rating-45 rating clearfix">
            <span title="4.383 of 5 stars"><span class="average">4.383</span> of <span class="best">5</span> stars</span>
            <a tabindex="0" href="https://www.example.com/category/" title="View all xxxx Reviews">
            View all <span class="count">10</span> Reviews
            </a>
        </div>
    </div>

So that it fully validates with: https://search.google.com/structured-data/testing-tool

Should I use COUNT or VOTES?

From the microformat doc itself: http://microformats.org/wiki/hreview-aggregate

count:: This property is used to specify the total number of reviews for the product or service.

votes:: This property is used to specify the total number of users who have rated the product or service, contributing to the average rating. For some sites, the number of votes is equal to the number of reviews, so count may be used and this property omitted.

in your case, see my example with count as I believe this is most applicable to you.

As mentioned before there are several factors that can cause google not to show it.

Google itself says:

When Google finds valid reviews or ratings markup, we may show a rich snippet that includes stars and other summary info from reviews or ratings.

Keyword: MAY

https://developers.google.com/search/docs/data-types/reviews#review-snippets

from my experience they usually do, just make sure its properly formatted and validated.


来源: stackexchange

问:
wrong data type in packet layer (scapy)
I want to reconstruct a packet with scapy. If I compare the original packet with my constructed packet, I see that a few entries in a layer of my packet have the wrong values. I think it comes from unsuitable datatypes of some values like the following one:

If I print stream_id in one string like this

```<code>stream_id = "\x00\x22\x97\x04\x06\xba\x00\x00"
</code>```

the output is unreadable (like wingding symbols).

But if I put stream_id together myself like this

```<code>alias = "CB"
stream_id = '\\x' + alias + '\\x' + alias + '\\x' + alias + '\\x' + alias
</code>```

the printing output is \x9B\x9B\x9B\x9B.

What's the difference between those two notations?

Please help

答:
\x<hex_byte> is a special escape sequence for Python strings denoting a literal byte as a hex digit.

The first one is essentially writing bytes to your stream_id, e.g.:

```<code>stream_id_1 = "\x00\x22\x97\x04\x06\xba\x00\x00"
stream_id_2 = chr(0x00) + chr(0x22) + chr(0x97) + chr(0x04) \
              + chr(0x06) + chr(0xba) + chr(0x00) + chr(0x00)

assert stream_id_1 == stream_id_2  # passes
</code>```

and if you print out the bytes you get: 0022970406ba0000

While the second one is writing a string, as if you wrote (using the same data as above):

```<code>stream_id_1 = "\\x00\\x22\\x97\\x04\\x06\\xba\\x00\\x00"
</code>```

escaping the escape sequence so that the numbers don't get interpreted as bytes, resulting in the following printout: 5c7830305c7832325c7839375c7830345c7830365c7862615c7830305c783030 which is, as you can see, a vastly different structure.

UPDATE - To build a stream of bytes you can construct them as in the 'manually' built string - by converting your alias to an integer and then using chr() to turn it into a byte char:

```<code>alias = chr(int("CB", 16))
stream_id = alias + alias + alias + alias  # etc.
</code>```

But judging by your comment, you just want to get a random byte so don't waste cycles by generating a hex string, then turning it into an integer to finally turn it into a byte char - get a random integer immediately and turn it into a byte char:

```<code>alias = chr(random.randint(0, 255))
stream_id = alias + alias + alias + alias  # etc.
</code>```

Or even better, forgo the random module and use os.urandom() instead:

```<code>import os

alias = os.urandom(1)
stream_id = alias + alias + alias + alias  # etc.
</code>```

Of course, you can use the same technique to get as many different random bytes as you like.

ContentLicense: CC BY-SA 3.0

Title: wrong data type in packet layer (scapy)

Body:
I want to reconstruct a packet with scapy. If I compare the original packet with my constructed packet, I see that a few entries in a layer of my packet have the wrong values. I think it comes from unsuitable datatypes of some values like the following one:

If I print stream_id in one string like this

stream_id = "\x00\x22\x97\x04\x06\xba\x00\x00"

the output is unreadable (like wingding symbols).

But if I put stream_id together myself like this

alias = "CB"
stream_id = '\\x' + alias + '\\x' + alias + '\\x' + alias + '\\x' + alias

the printing output is \x9B\x9B\x9B\x9B.

What's the difference between those two notations?

Please help

Body:
\x<hex_byte> is a special escape sequence for Python strings denoting a literal byte as a hex digit.

The first one is essentially writing bytes to your stream_id, e.g.:

stream_id_1 = "\x00\x22\x97\x04\x06\xba\x00\x00"
stream_id_2 = chr(0x00) + chr(0x22) + chr(0x97) + chr(0x04) \
              + chr(0x06) + chr(0xba) + chr(0x00) + chr(0x00)

assert stream_id_1 == stream_id_2  # passes

and if you print out the bytes you get: 0022970406ba0000

While the second one is writing a string, as if you wrote (using the same data as above):

stream_id_1 = "\\x00\\x22\\x97\\x04\\x06\\xba\\x00\\x00"

escaping the escape sequence so that the numbers don't get interpreted as bytes, resulting in the following printout: 5c7830305c7832325c7839375c7830345c7830365c7862615c7830305c783030 which is, as you can see, a vastly different structure.

UPDATE - To build a stream of bytes you can construct them as in the 'manually' built string - by converting your alias to an integer and then using chr() to turn it into a byte char:

alias = chr(int("CB", 16))
stream_id = alias + alias + alias + alias  # etc.

But judging by your comment, you just want to get a random byte so don't waste cycles by generating a hex string, then turning it into an integer to finally turn it into a byte char - get a random integer immediately and turn it into a byte char:

alias = chr(random.randint(0, 255))
stream_id = alias + alias + alias + alias  # etc.

Or even better, forgo the random module and use os.urandom() instead:

import os

alias = os.urandom(1)
stream_id = alias + alias + alias + alias  # etc.

Of course, you can use the same technique to get as many different random bytes as you like.


问:
Reading multiple txt files and saving them into one numpy array: how to concatenate numpy arrays
a) Here's my try. It works but I'm wondering if I can do it without if else conditions and indexing - more pythonic way.   </p>

```<code>sensor_files = ['file1.csv', 'file2.csv']

for idx,sensor_file in enumerate(sensor_files):
    with open(file, 'rb') as f:
        clean_lines = (line.replace(b';',b',')
        sensors = np.genfromtxt(clean_lines, dtype=int, delimiter=',')
        if idx == 0:
            acc_measurements = sensors
        else:
            acc_measurements = np.concatenate((acc_measurements, sensors))
</code>```

答:
A neat solution using pandas would be</p>

```<code>import pandas as pd
df1 = pd.read_csv("file1.csv")
df2 = pd.read_csv("file2.csv")
df_concatenated = df1.append(df2)
</code>```

Body:
a) Here's my try. It works but I'm wondering if I can do it without if else conditions and indexing - more pythonic way.

sensor_files = ['file1.csv', 'file2.csv']

for idx,sensor_file in enumerate(sensor_files):
    with open(file, 'rb') as f:
        clean_lines = (line.replace(b';',b',')
        sensors = np.genfromtxt(clean_lines, dtype=int, delimiter=',')
        if idx == 0:
            acc_measurements = sensors
        else:
            acc_measurements = np.concatenate((acc_measurements, sensors))

Body:
A neat solution using pandas would be

import pandas as pd
df1 = pd.read_csv("file1.csv")
df2 = pd.read_csv("file2.csv")
df_concatenated = df1.append(df2)


问:
Pentaho-carte rest api?
I just started with Pentaho data-integration and was able to create transformations/jobs from UI and run them from UI as well as Pentaho DI java SDK. Also, I successfully setup carte server, submitted transformation, and monitored it's status on carte webUI.

My question is:

Does carte server also exposes any JSON/XML rest API over which I can submit jobs/transformation and monitor their progress? Right now it seems to be developed only for usage through browser.

Thanks
- Nitin,

答:
Yes, the REST API exists.

Carte is based on a Jetty server which is meant to be used on a web browser, but there is no reason to prevent sending/receiving request like http://your-server:9090/kettle/status?xml=true.

However, I see two main obstacles: First you will receive html from which you have to extract the relevant information. It is not difficult to do but it has to be done by you.

Second, is the documentation. The community documentation is rather short, and the EE edition documentation does not address the question. There is an underground documentation but is may be outdated (or it may exist a more recent I do not know about).

So you are bound to crawl in the forum and in the sources [source][5]. in the org.pentaho.di.www package you find a lot of *Servlet.java, each one corresponding to an action whose url is defined at the beginning of the class in the variable CONTEXT_PATH.

For example, the class org.pentaho.di.www.RunTransServlet.java contains on line 58: public static final String CONTEXT_PATH = "/kettle/runTrans"; indicating the url to run a transformation is http://your-server:9090/kettle/runTrans?.... Then you now you have 2 parameters the transformation name and the log level either by looking in the html doc on lines 68-145, either by reading the code of the doGet method.

It is much easier than it sounds (thanks to Matt Casters and Jens Bleuel gift in software engineering).

I did myself a small ajax interface with less information. It was before they invented this CORS stuff, so you have to check that the Access-Control-Allow-Origin: * is written to the response header.

So, if you are brave enough and plan to do something in that direction, keep me up to date and do not hesitate to request help.

Title: Pentaho-carte rest api?


问:
Debian 9 wifi doesn't work
I've a problem. I've installed Debian 9 Stretch on my old Samsung laptop, everything is working fine except the wifi module. It says missing firmware when I hover over wifi at right upper corner.

I really don't know what to do.

```<code>lspci -knn | grep Net -A2

- 06:00.0 Network controller [0280]: Broadcom Limited BCM4313 802.11bgn Wireless Network Adapter [14e4:4727] (rev 01) Subsystem: Askey Computer Corp. BCM4313 802.11bgn Wireless Network Adapter [144f:7179]

Kernel driver in use: bcma-pci-bridge Kernel Modules: bcma
</code>```

```<code>uname -a

 Linux ClearSkySoftware 4.9.0-3-amd64 #1 SMP Debian 4.9.30-2+dev9u2 (2017-06-26) x86_64 GNU/Linux
</code>```

答:
According to the official website to get the wifi working on BCM4313 you should install the broadcom-sta-dkms and the linux-headers package then load the wl module

Edit your /etc/sources by adding the non-free component :

```<code>deb http://deb.debian.org/debian stretch main contrib non-free
deb http://deb.debian.org/debian stretch-updates main contrib non-free
deb http://security.debian.org/ stretch/updates main contrib non-free
</code>```

Update your package:

```<code>apt update && apt upgrade
</code>```

Install the linux-headers:

To get the available linux-headers , run:

```<code>apt-cache search linux-headers
</code>```

Install the appropriate linux-headers to your linux-image , there is an example:

```<code>apt install linux-headers-4.9.0-3-amd64
</code>```

Install the broadcom-sta-dkms:

```<code>apt install broadcom-sta-dkms
</code>```

Unload the conflicting modules:

```<code>modprobe -r b44 b43 b43legacy ssb brcmsmac bcma
</code>```

Load the wl module:

```<code>modprobe wl
</code>```

Title: Debian 9 wifi doesn't work

Body:
I've a problem. I've installed Debian 9 Stretch on my old Samsung laptop, everything is working fine except the wifi module. It says missing firmware when I hover over wifi at right upper corner.

I really don't know what to do.

lspci -knn | grep Net -A2

- 06:00.0 Network controller [0280]: Broadcom Limited BCM4313 802.11bgn Wireless Network Adapter [14e4:4727] (rev 01) Subsystem: Askey Computer Corp. BCM4313 802.11bgn Wireless Network Adapter [144f:7179]

Kernel driver in use: bcma-pci-bridge Kernel Modules: bcma

uname -a

 Linux ClearSkySoftware 4.9.0-3-amd64 #1 SMP Debian 4.9.30-2+dev9u2 (2017-06-26) x86_64 GNU/Linux

Body:
According to the official website to get the wifi working on BCM4313 you should install the broadcom-sta-dkms and the linux-headers package then load the wl module

Edit your /etc/sources by adding the non-free component :

deb http://deb.debian.org/debian stretch main contrib non-free
deb http://deb.debian.org/debian stretch-updates main contrib non-free
deb http://security.debian.org/ stretch/updates main contrib non-free

Update your package:

apt update && apt upgrade

Install the linux-headers:

To get the available linux-headers , run:

apt-cache search linux-headers

Install the appropriate linux-headers to your linux-image , there is an example:

apt install linux-headers-4.9.0-3-amd64

Install the broadcom-sta-dkms:

apt install broadcom-sta-dkms

Unload the conflicting modules:

modprobe -r b44 b43 b43legacy ssb brcmsmac bcma

Load the wl module:

modprobe wl


问:
Convert Array of JSON to Array of JSON based on key in hierarchical structure
Hi I have array of JSON and I want to convert it into hierarchical structure...

i.e,

FROM

```<code>data =
[
    { Level:"0", Name:"A1" },
    { Level:"1", Name:"A2" },
    { Level:"1", Name:"A3" },
    { Level:"0", Name:"A4" },
    { Level:"1", Name:"A4" },
    { Level:"1", Name:"A5" }
]
</code>```

TO

```<code>0 =
[
    { 1: [ { Level:1, Name:A2 }, { Level:1, Name:A3 } ] },
    { 1: [ { Level:1, Name:A4 }, { Level:1, Name:A5 } }
]
</code>```

I want to group based on level, starting from 0 but higher level can be more than 2.

答: with underscore: _.groupBy(data, 'Level')</p>

Body:
Hi I have array of JSON and I want to convert it into hierarchical structure...

i.e,

FROM

data =
[
    { Level:"0", Name:"A1" },
    { Level:"1", Name:"A2" },
    { Level:"1", Name:"A3" },
    { Level:"0", Name:"A4" },
    { Level:"1", Name:"A4" },
    { Level:"1", Name:"A5" }
]

TO

0 =
[
    { 1: [ { Level:1, Name:A2 }, { Level:1, Name:A3 } ] },
    { 1: [ { Level:1, Name:A4 }, { Level:1, Name:A5 } }
]

I want to group based on level, starting from 0 but higher level can be more than 2.


问:
Test method is inconclusive: Test wasn't run. Error?
I have a test class and below I have posted a sample test from the test class

```<code>namespace AdminPortal.Tests.Controller_Test.Customer
{
    [TestClass]
    public class BusinessUnitControllerTests
    {
        private IBusinessUnitRepository _mockBusinessUnitRepository;
        private BusinessUnitController _controller;

        [TestInitialize]
        public void TestInitialize()
        {
            _mockBusinessUnitRepository = MockRepository.GenerateMock<IBusinessUnitRepository>();
            _controller = new BusinessUnitController(_mockBusinessUnitRepository);
        }

        [TestCleanup]
        public void TestCleanup()
        {
            _mockBusinessUnitRepository = null;

            _controller.Dispose();
            _controller = null;

        }

        #region Index Action Tests
        [TestMethod]
        public void Index_Action_Calls_GetAllBusinessUnit()
        {
            _mockBusinessUnitRepository.Stub(x => x.GetAllBusinessUnit());

            _controller.Index();

            _mockBusinessUnitRepository.AssertWasCalled(x=>x.GetAllBusinessUnit());
        }
    }
}
</code>```

When I run the project I get following screen

I checked the references and the test project has the reference to main project.
Any idea why the test are not running or saying that they were inconclusive?

Edit 1:

I saw a post here and changed my test's setting's default processor architecture to X64 but it still doesn't work.

答:
In my case (Visual Studio Community 2017 version 15.2) the source of issue was new way of loading projects introduced in VS 2017, i.e. 'Lightweight Solution Load'.

In "Unit Test Sessions" window I noticed that solution has way less tests then it should. I had to open each unit test project manually in "Solution Explorer" and only then all tests were loaded and passed.

One way to solve this is to disable "Lightweight Solution Load" by right clicking on solution in "Solution Explorer" and set "Disable Lightweight Solution Load".

Body:
I have a test class and below I have posted a sample test from the test class

namespace AdminPortal.Tests.Controller_Test.Customer
{
    [TestClass]
    public class BusinessUnitControllerTests
    {
        private IBusinessUnitRepository _mockBusinessUnitRepository;
        private BusinessUnitController _controller;

        [TestInitialize]
        public void TestInitialize()
        {
            _mockBusinessUnitRepository = MockRepository.GenerateMock<IBusinessUnitRepository>();
            _controller = new BusinessUnitController(_mockBusinessUnitRepository);
        }

        [TestCleanup]
        public void TestCleanup()
        {
            _mockBusinessUnitRepository = null;

            _controller.Dispose();
            _controller = null;

        }

        #region Index Action Tests
        [TestMethod]
        public void Index_Action_Calls_GetAllBusinessUnit()
        {
            _mockBusinessUnitRepository.Stub(x => x.GetAllBusinessUnit());

            _controller.Index();

            _mockBusinessUnitRepository.AssertWasCalled(x=>x.GetAllBusinessUnit());
        }
    }
}

When I run the project I get following screen

I checked the references and the test project has the reference to main project.
Any idea why the test are not running or saying that they were inconclusive?

Edit 1:

I saw a post here and changed my test's setting's default processor architecture to X64 but it still doesn't work.


问:
How to calculate moving average for different starting date?
I would like to calculate moving averages for each participant in the dataset.

Participant may have more than one visit date, and I would like to calculate the average value in the past 3 days and in the past 2 days before each visit (not including the day of visit).

For example, let id=1, date=6/6/2017.

Average value in the past 2 days should be an average of value on 6/5/2017 and 6/4/2017.

Sample datasets are generated as below.
I am working on a much larger dataset, with more participants, more visits, and more days of value. I want to find an efficient way to calculate these averages.

```<code>timeseries <- data.frame(id=c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3),                         date=c("6/1/2017","6/2/2017","6/3/2017","6/4/2017","6/5/2017","6/6/2017",
                            "6/1/2017","6/2/2017","6/3/2017","6/4/2017","6/5/2017","6/6/2017",
                            "6/1/2017","6/2/2017","6/3/2017","6/4/2017","6/5/2017","6/6/2017"),
                     value=c(2,3,4,NA,6,7,
                             NA,9,5,NA,3,2,
                             5,7,3,8,3,5))
> timeseries
   id     date value
1   1 6/1/2017     2
2   1 6/2/2017     3
3   1 6/3/2017     4
4   1 6/4/2017    NA
5   1 6/5/2017     6
6   1 6/6/2017     7
7   2 6/1/2017    NA
8   2 6/2/2017     9
9   2 6/3/2017     5
10  2 6/4/2017    NA
...

visit <- data.frame(id=c(1,1,2,3,3,3),
                date=c("6/6/2017","6/5/2017",
                       "6/6/2017",
                       "6/6/2017","6/5/2017","6/4/2017"))

> visit
  id     date
1  1 6/6/2017
2  1 6/5/2017
3  2 6/6/2017
4  3 6/6/2017
5  3 6/5/2017
6  3 6/4/2017
</code>```

The result table should be something like this, where mean3 is the average value in the past 3 days, and mean2 is the average value in the past 2 days

```<code>> result
  id     date mean3 mean2
1  1 6/6/2017
2  1 6/5/2017
3  2 6/6/2017
4  3 6/6/2017
5  3 6/5/2017
6  3 6/4/2017
</code>```

答:
For each id of visit, I subset corresponding data from timeseries and then calculated mean of the value within n_days.

```<code>library(lubridate)
n_days = 2
sapply(1:NROW(visit), function(i)
    with(subset(x = timeseries,
                subset = timeseries$id == visit$id[i]),
         mean(x = value[difftime(time1 = mdy(visit$date[i]),
                                 time2 = mdy(date),
                                 units = "days") <= n_days &
                            difftime(time1 = mdy(visit$date[i]),
                                time2 = mdy(date),
                                units = "days") > 0],
              na.rm = TRUE)))
#[1] 6.0 4.0 3.0 5.5 5.5 5.0
</code>```

Body:
I would like to calculate moving averages for each participant in the dataset.

Participant may have more than one visit date, and I would like to calculate the average value in the past 3 days and in the past 2 days before each visit (not including the day of visit).

For example, let id=1, date=6/6/2017.

Average value in the past 2 days should be an average of value on 6/5/2017 and 6/4/2017.

Sample datasets are generated as below.
I am working on a much larger dataset, with more participants, more visits, and more days of value. I want to find an efficient way to calculate these averages.

timeseries <- data.frame(id=c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3),                         date=c("6/1/2017","6/2/2017","6/3/2017","6/4/2017","6/5/2017","6/6/2017",
                            "6/1/2017","6/2/2017","6/3/2017","6/4/2017","6/5/2017","6/6/2017",
                            "6/1/2017","6/2/2017","6/3/2017","6/4/2017","6/5/2017","6/6/2017"),
                     value=c(2,3,4,NA,6,7,
                             NA,9,5,NA,3,2,
                             5,7,3,8,3,5))
> timeseries
   id     date value
1   1 6/1/2017     2
2   1 6/2/2017     3
3   1 6/3/2017     4
4   1 6/4/2017    NA
5   1 6/5/2017     6
6   1 6/6/2017     7
7   2 6/1/2017    NA
8   2 6/2/2017     9
9   2 6/3/2017     5
10  2 6/4/2017    NA
...

visit <- data.frame(id=c(1,1,2,3,3,3),
                date=c("6/6/2017","6/5/2017",
                       "6/6/2017",
                       "6/6/2017","6/5/2017","6/4/2017"))

> visit
  id     date
1  1 6/6/2017
2  1 6/5/2017
3  2 6/6/2017
4  3 6/6/2017
5  3 6/5/2017
6  3 6/4/2017

The result table should be something like this, where mean3 is the average value in the past 3 days, and mean2 is the average value in the past 2 days

> result
  id     date mean3 mean2
1  1 6/6/2017
2  1 6/5/2017
3  2 6/6/2017
4  3 6/6/2017
5  3 6/5/2017
6  3 6/4/2017

Body:
For each id of visit, I subset corresponding data from timeseries and then calculated mean of the value within n_days.

library(lubridate)
n_days = 2
sapply(1:NROW(visit), function(i)
    with(subset(x = timeseries,
                subset = timeseries$id == visit$id[i]),
         mean(x = value[difftime(time1 = mdy(visit$date[i]),
                                 time2 = mdy(date),
                                 units = "days") <= n_days &
                            difftime(time1 = mdy(visit$date[i]),
                                time2 = mdy(date),
                                units = "days") > 0],
              na.rm = TRUE)))
#[1] 6.0 4.0 3.0 5.5 5.5 5.0


问:
Case insensitive string matching in awk
Assume a multi-line text file file in which some lines start with whitespaces.

```<code>$ cat file
foo Baz
  baz QUX
    QUx Quux
BaZ Qux
BazaaR
</code>```

Further assume that I wish to convert all those lines that start with a keyword (e.g. "baz") to lowercase letters, irrespective if (a) that keyword is written in lower- or uppercase letters (or any combination thereof) itself, and (b) that keyword is preceeded by whitespaces.

```<code>$ cat file | sought_command
foo Baz        # not to lowercase (line does not start with keyword)
  baz qux      # to lowercase
    QUx Quux
baz qux        # to lowercase
BazaaR         # not to lowercase (line does not start with keyword, but merely with a word containing the keyword)
</code>```

I believe that awk is the tool to do it, but I am uncertain how to implement the case-insensitivity for the keyword matching.

```<code>$ cat file | awk '{ if($1 ~ /^ *baz/) print tolower($0); else print $0}'
foo Baz
  baz qux
    QUx Quux
BaZ Qux       # ERROR HERE: was not replaced, b/c keyword not recognized.
BazaaR
</code>```

EDIT 1:
Adding IGNORECASE=1 appears to resolve the case-insensitivity, but now incorrectly converts the last line to lowercase.

```<code>$ cat file | awk '{IGNORECASE=1; if($1~/^ *baz/) print tolower($0); else print $0}'
foo Baz
  baz qux
    QUx Quux
baz qux
bazaar       # ERROR HERE: should not be converted to lowercase, as keyword not present (emphasis on word!).
</code>```

答:
You already know about tolower() so just use it again in the comparison and test for an exact string match instead of partial regexp:

```<code>awk 'tolower($1)=="baz"{$0=tolower($0)}1'
</code>```

ContentLicense: CC BY-SA 4.0

Title: Case insensitive string matching in awk

Body:
Assume a multi-line text file file in which some lines start with whitespaces.

$ cat file
foo Baz
  baz QUX
    QUx Quux
BaZ Qux
BazaaR

Further assume that I wish to convert all those lines that start with a keyword (e.g. "baz") to lowercase letters, irrespective if (a) that keyword is written in lower- or uppercase letters (or any combination thereof) itself, and (b) that keyword is preceeded by whitespaces.

$ cat file | sought_command
foo Baz        # not to lowercase (line does not start with keyword)
  baz qux      # to lowercase
    QUx Quux
baz qux        # to lowercase
BazaaR         # not to lowercase (line does not start with keyword, but merely with a word containing the keyword)

I believe that awk is the tool to do it, but I am uncertain how to implement the case-insensitivity for the keyword matching.

$ cat file | awk '{ if($1 ~ /^ *baz/) print tolower($0); else print $0}'
foo Baz
  baz qux
    QUx Quux
BaZ Qux       # ERROR HERE: was not replaced, b/c keyword not recognized.
BazaaR

EDIT 1:
Adding IGNORECASE=1 appears to resolve the case-insensitivity, but now incorrectly converts the last line to lowercase.

$ cat file | awk '{IGNORECASE=1; if($1~/^ *baz/) print tolower($0); else print $0}'
foo Baz
  baz qux
    QUx Quux
baz qux
bazaar       # ERROR HERE: should not be converted to lowercase, as keyword not present (emphasis on word!).

Body:
You already know about tolower() so just use it again in the comparison and test for an exact string match instead of partial regexp:

awk 'tolower($1)=="baz"{$0=tolower($0)}1'


问:
Text is being clipped off inside Constraint Layout android
I use the below layout to achieve a view with image on the right end of a constraint layout, and a text to the left of the image:

```<code><LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:app="http://schemas.android.com/apk/res-auto"
         xmlns:tools="http://schemas.android.com/tools"
         android:orientation="vertical"
         android:layout_width="match_parent"
         android:layout_height="match_parent">

  <android.support.constraint.ConstraintLayout
    android:id="@+id/parentPanel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/image"
                 android:layout_width="64dp"
                 android:layout_height="64dp"
                 app:layout_constraintRight_toRightOf="parent"
                 android:background="#ff0000"/>

            <TextView
                android:id="@+id/txt"
                android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:text="Lorem Ipsum is simply dummy text of the printing
 and typesetting industry. Lorem Ipsum has been the industry's
 standard dummy text ever since the 1500s, when an unknown printer took
 a galley of type and scrambled it to make a type specimen book"
                 app:layout_constraintTop_toTopOf="parent"
                 app:layout_constraintBottom_toBottomOf="parent"
                 app:layout_constraintRight_toLeftOf="@+id/image"
                 android:textColor="#000000"
                 android:textSize="20sp"/>
         </android.support.

constraint.ConstraintLayout>
     </LinearLayout>
</code>```

I have attached the screenshot of the UI that has been obtained from above XML. The text is being clipped off on the left, when text is too long.

Screenshot_1

Screenshot_2

The dependency that is being used in build.gradle is:

compile 'com.android.support.constraint:constraint-layout:1.0.1'

答:
You have to change LinearLayout to ConstraintLayout.
Your Layout should like below.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.constraint.ConstraintLayout
        android:id="@+id/parentPanel"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" >

        <ImageView
            android:id="@+id/image"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:background="#ff0000"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"  />

        <TextView
            android:id="@+id/txt"
            android:layout_width="0dp"
            android:layout_height="120dp"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:text="Lorem Ipsum is simply dummy text of the printing
 and typesetting industry. Lorem Ipsum has been the industry's
 standard dummy text ever since the 1500s, when an unknown printer took
 a galley of type and scrambled it to make a type specimen book"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            android:textColor="#000000"
            android:textSize="20sp"
            app:layout_constraintVertical_bias="0.0"
            app:layout_constraintRight_toLeftOf="@+id/image"
            android:layout_marginLeft="0dp"
            android:layout_marginRight="8dp" />
    </android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>
</code>```

Body:
I use the below layout to achieve a view with image on the right end of a constraint layout, and a text to the left of the image:

<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:app="http://schemas.android.com/apk/res-auto"
         xmlns:tools="http://schemas.android.com/tools"
         android:orientation="vertical"
         android:layout_width="match_parent"
         android:layout_height="match_parent">

  <android.support.constraint.ConstraintLayout
    android:id="@+id/parentPanel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/image"
                 android:layout_width="64dp"
                 android:layout_height="64dp"
                 app:layout_constraintRight_toRightOf="parent"
                 android:background="#ff0000"/>

            <TextView
                android:id="@+id/txt"
                android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:text="Lorem Ipsum is simply dummy text of the printing
 and typesetting industry. Lorem Ipsum has been the industry's
 standard dummy text ever since the 1500s, when an unknown printer took
 a galley of type and scrambled it to make a type specimen book"
                 app:layout_constraintTop_toTopOf="parent"
                 app:layout_constraintBottom_toBottomOf="parent"
                 app:layout_constraintRight_toLeftOf="@+id/image"
                 android:textColor="#000000"
                 android:textSize="20sp"/>
         </android.support.

constraint.ConstraintLayout>
     </LinearLayout>

I have attached the screenshot of the UI that has been obtained from above XML. The text is being clipped off on the left, when text is too long.

Screenshot_1

Screenshot_2

The dependency that is being used in build.gradle is:

compile 'com.android.support.constraint:constraint-layout:1.0.1'

Body:
You have to change LinearLayout to ConstraintLayout.
Your Layout should like below.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.constraint.ConstraintLayout
        android:id="@+id/parentPanel"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" >

        <ImageView
            android:id="@+id/image"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:background="#ff0000"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"  />

        <TextView
            android:id="@+id/txt"
            android:layout_width="0dp"
            android:layout_height="120dp"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:text="Lorem Ipsum is simply dummy text of the printing
 and typesetting industry. Lorem Ipsum has been the industry's
 standard dummy text ever since the 1500s, when an unknown printer took
 a galley of type and scrambled it to make a type specimen book"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            android:textColor="#000000"
            android:textSize="20sp"
            app:layout_constraintVertical_bias="0.0"
            app:layout_constraintRight_toLeftOf="@+id/image"
            android:layout_marginLeft="0dp"
            android:layout_marginRight="8dp" />
    </android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>


问:
Quit jQuery $.each loop

Possible Duplicate:

  How do I break out of an $.each in jquery?

How to quit the jquery $.each loop?

答:
continue and break do not work the same since you are passing a callback and jQuery does the loop, but you can emulate them:

To continue, return true inside the .each callback.

To break, return false.

ContentLicense: CC BY-SA 2.5

Title: Quit jQuery $.each loop


问:
Instant run doesn't work due to "multiple process"
After having configured instant run, the run button has a small yellow thunderbolt.But while I run the app, Android Studio still performed a full build & install, full message is listed in the picture.

I've searched the official documents in http://tools.android.com/tech-docs/instant-run , but there wasn't anything about "multiple process".I wonder "multiple processes" means compiling or my android app.

What should I configure to turn off multiple processes and experience instant run ?

答:
I ran into this problem when running ProcessPhoenix. Instead of disabling it completely, I just disabled it for my debug build.

Instead of compile I use

releaseCompile 'com.jakewharton:process-phoenix:2.0.0'

And to not break the build I use reflection to trigger the application process restart:

```<code>try {
    Class clazz = Class.forName("com.jakewharton.processphoenix.ProcessPhoenix");
    Method triggerRebirthMethod = clazz.getMethod("triggerRebirth", Context.class);
    triggerRebirthMethod.invoke(this, new Object[]{getActivity()});
} catch (Exception e) {
    // Exception handling
}
</code>```

So now I can still use Instant Run and keep the lib included. :)

(Of course, reflection is never ideal, but the app process restart is only used in one rare particular case in the app.)

Body:
I ran into this problem when running ProcessPhoenix. Instead of disabling it completely, I just disabled it for my debug build.

Instead of compile I use

releaseCompile 'com.jakewharton:process-phoenix:2.0.0'

And to not break the build I use reflection to trigger the application process restart:

try {
    Class clazz = Class.forName("com.jakewharton.processphoenix.ProcessPhoenix");
    Method triggerRebirthMethod = clazz.getMethod("triggerRebirth", Context.class);
    triggerRebirthMethod.invoke(this, new Object[]{getActivity()});
} catch (Exception e) {
    // Exception handling
}

So now I can still use Instant Run and keep the lib included. :)

(Of course, reflection is never ideal, but the app process restart is only used in one rare particular case in the app.)


问:
How to reset Postgres' primary key sequence when it falls out of sync?
I ran into the problem that my primary key sequence is not in sync with my table rows.

That is, when I insert a new row I get a duplicate key error because the sequence implied in the serial datatype returns a number that already exists.

It seems to be caused by import/restores not maintaining the sequence properly.

答:
I spent an hour trying to get djsnowsill's answer to work with a database using Mixed Case tables and columns, then finally stumbled upon the solution thanks to a comment from Manuel Darveau, but I thought I could make it a bit clearer for everyone:

```<code>CREATE OR REPLACE FUNCTION "reset_sequence" (tablename text, columnname text)
RETURNS "pg_catalog"."void" AS
$body$
DECLARE
BEGIN
EXECUTE format('SELECT setval(pg_get_serial_sequence(''%1$I'', %2$L),
        (SELECT COALESCE(MAX(%2$I)+1,1) FROM %1$I), false)',tablename,columnname);
END;
$body$  LANGUAGE 'plpgsql';

SELECT format('%s_%s_seq',table_name,column_name), reset_sequence(table_name,column_name)
FROM information_schema.columns WHERE column_default like 'nextval%';
</code>```

This has the benefit of:

not assuming ID column is spelled a particular way.

not assuming all tables have a sequence.

working for Mixed Case table/column names.

using format to be more concise.

To explain, the problem was that pg_get_serial_sequence takes strings to work out what you're referring to, so if you do:

```<code>"TableName" --it thinks it's a table or column
'TableName' --it thinks it's a string, but makes it lower case
'"TableName"' --it works!
</code>```

This is achieved using ''%1$I'' in the format string, '' makes an apostrophe 1$ means first arg, and I means in quotes

OwnerDisplayName: wdm

LastEditorDisplayName: Vinko Vrsalovic

Body:
I spent an hour trying to get djsnowsill's answer to work with a database using Mixed Case tables and columns, then finally stumbled upon the solution thanks to a comment from Manuel Darveau, but I thought I could make it a bit clearer for everyone:

CREATE OR REPLACE FUNCTION "reset_sequence" (tablename text, columnname text)
RETURNS "pg_catalog"."void" AS
$body$
DECLARE
BEGIN
EXECUTE format('SELECT setval(pg_get_serial_sequence(''%1$I'', %2$L),
        (SELECT COALESCE(MAX(%2$I)+1,1) FROM %1$I), false)',tablename,columnname);
END;
$body$  LANGUAGE 'plpgsql';

SELECT format('%s_%s_seq',table_name,column_name), reset_sequence(table_name,column_name)
FROM information_schema.columns WHERE column_default like 'nextval%';

This has the benefit of:

not assuming ID column is spelled a particular way.

not assuming all tables have a sequence.

working for Mixed Case table/column names.

using format to be more concise.

To explain, the problem was that pg_get_serial_sequence takes strings to work out what you're referring to, so if you do:

"TableName" --it thinks it's a table or column
'TableName' --it thinks it's a string, but makes it lower case
'"TableName"' --it works!

This is achieved using ''%1$I'' in the format string, '' makes an apostrophe 1$ means first arg, and I means in quotes


问:
Dockerfile doesn't run the CMD if the ENTRYPOINT isn't finished
I am trying to run a Dockerfile that run PostgreSQL and then add some tables to it.

This is my Dockerfile:

```<code>FROM postgres:9.6

MAINTAINER agomez@ikerlan.es

USER postgres
ADD ./backup.sql /backup.sql
ADD ./deploy/import_database.sh /import_database.sh

USER root
RUN chmod +x /import_database.sh

USER postgres

ENTRYPOINT ./docker-entrypoint.sh postgres
CMD ./import_database.sh
</code>```

The entrypoint doesn't finish becouse it runs the postgres server.
How can I run the CMD for example, after 20 seconds of running the ENTRYPOINT, but without finishing the ENTRYPOINT?

Is it possible?

答:
This is not how the CMD and ENTRYPOINT work. I'd recommend reading https://docs.docker.com/engine/reference/builder/#understand-how-cmd-and-entrypoint-interact and checking the chart for a better understanding of how the ENTRYPOINT and CMD interact with each other.

That said, if all you want to do is import a SQL file or run a script at runtime, the official PostgreSQL image already has you covered. See https://github.com/docker-library/docs/tree/master/postgres#how-to-extend-this-image for information on how to do this.

An example in the case of your Dockerfile (if you just wanted to import the SQL file) would be to do something like:

```<code>FROM postgres:9.6
ADD ./backup.sql /docker-entrypoint-initdb.d/backup.sql
</code>```

When starting a container from the image build on this Dockerfile, the default ENTRYPOINT script will start a temporary PostgreSQL instance, wait for it to be ready, import your data, and then restart to serve connections.

Body:
I am trying to run a Dockerfile that run PostgreSQL and then add some tables to it.

This is my Dockerfile:

FROM postgres:9.6

MAINTAINER agomez@ikerlan.es

USER postgres
ADD ./backup.sql /backup.sql
ADD ./deploy/import_database.sh /import_database.sh

USER root
RUN chmod +x /import_database.sh

USER postgres

ENTRYPOINT ./docker-entrypoint.sh postgres
CMD ./import_database.sh

The entrypoint doesn't finish becouse it runs the postgres server.
How can I run the CMD for example, after 20 seconds of running the ENTRYPOINT, but without finishing the ENTRYPOINT?

Is it possible?

Body:
This is not how the CMD and ENTRYPOINT work. I'd recommend reading https://docs.docker.com/engine/reference/builder/#understand-how-cmd-and-entrypoint-interact and checking the chart for a better understanding of how the ENTRYPOINT and CMD interact with each other.

That said, if all you want to do is import a SQL file or run a script at runtime, the official PostgreSQL image already has you covered. See https://github.com/docker-library/docs/tree/master/postgres#how-to-extend-this-image for information on how to do this.

An example in the case of your Dockerfile (if you just wanted to import the SQL file) would be to do something like:

FROM postgres:9.6
ADD ./backup.sql /docker-entrypoint-initdb.d/backup.sql

When starting a container from the image build on this Dockerfile, the default ENTRYPOINT script will start a temporary PostgreSQL instance, wait for it to be ready, import your data, and then restart to serve connections.


问:
VBA Looping through range and deleting rows based on value
I'm not sure why but i'm having a lot of difficulty running this code to loop through the range and delete the rows based on the value.  This code is part of a bigger macro i'm writing but it all runs well up to this point. </p>

```<code>Dim Lastrowresults as integer
Dim Counter as integer
Dim Resultsheet as worksheet
Dim rowcounter as integer

Set resultsheet=sheets("Search Results")
LastRowResults = ResultSheet.Range("A1").End(xlDown).Row
    For Counter = 3 To LastRowResults
      If ResultSheet.Range("I" & Counter).Value = "No" Then
         RowCounter = ResultSheet.Range("I" & Counter).Row
         Rows(RowCounter).EntireRow.Delete
     End If
    Next Counter
</code>```

答:
Does your bigger macro have screen updating off before the row deletion?

Maybe you can try this line before you delete the rows: Application.ScreenUpdating = False

And turn it on at the end: Application.ScreenUpdating = true

Body:
I'm not sure why but i'm having a lot of difficulty running this code to loop through the range and delete the rows based on the value.  This code is part of a bigger macro i'm writing but it all runs well up to this point.

Dim Lastrowresults as integer
Dim Counter as integer
Dim Resultsheet as worksheet
Dim rowcounter as integer

Set resultsheet=sheets("Search Results")
LastRowResults = ResultSheet.Range("A1").End(xlDown).Row
    For Counter = 3 To LastRowResults
      If ResultSheet.Range("I" & Counter).Value = "No" Then
         RowCounter = ResultSheet.Range("I" & Counter).Row
         Rows(RowCounter).EntireRow.Delete
     End If
    Next Counter


问:
Arduino temperature sensor counting back
I am trying to get my new velleman vma320 to work with my arduino.
It doensn't work at all, the temperature goes down its heated up. I've tried everything. Can somebody help me? Here is my code...

```<code>int SensorPin = A0;

void setup() {

  Serial.begin(9600);

}

void loop() {

  //reading
  int sensorvalue = analogRead(SensorPin);
  Serial.print("value: ");
  Serial.print(sensorvalue);

  //voltage
  float voltage = sensorvalue * 5.0;
  voltage /= 1024.0;
  Serial.print(", volts: ");
  Serial.print(voltage);

  //temperature
  float temperature = (voltage - 0.5) * 100 ;
  Serial.print(" degrees C");
  Serial.println(temperature);

}
</code>```

Is it something I have done wrong? Or is it just the sensor? I tried it with two sensors.

If you can help me that would be awesome.

Thanks in advance,
Jens Van den Eede.

答:
So, this is the working code for a thermister velleman vma320. According to the way it's wired, voltage will go down as the temperature goes up, and it's not linear. </p>

```<code>#include <math.h>

double Thermistor(int RawADC) {
 double Temp;
 Temp =log(10000.0/(1024.0/RawADC-1)); // for pull-up configuration
 Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
 Temp = Temp - 273.15;            // Convert Kelvin to Celcius
 return Temp;
}

void setup() {
 Serial.begin(9600);
}

void loop() {
 Serial.println(int(Thermistor(analogRead(A0))));
 delay(1000);
}
</code>```

Body:
I am trying to get my new velleman vma320 to work with my arduino.
It doensn't work at all, the temperature goes down its heated up. I've tried everything. Can somebody help me? Here is my code...

int SensorPin = A0;

void setup() {

  Serial.begin(9600);

}

void loop() {

  //reading
  int sensorvalue = analogRead(SensorPin);
  Serial.print("value: ");
  Serial.print(sensorvalue);

  //voltage
  float voltage = sensorvalue * 5.0;
  voltage /= 1024.0;
  Serial.print(", volts: ");
  Serial.print(voltage);

  //temperature
  float temperature = (voltage - 0.5) * 100 ;
  Serial.print(" degrees C");
  Serial.println(temperature);

}

Is it something I have done wrong? Or is it just the sensor? I tried it with two sensors.

If you can help me that would be awesome.

Thanks in advance,
Jens Van den Eede.

Body:
So, this is the working code for a thermister velleman vma320. According to the way it's wired, voltage will go down as the temperature goes up, and it's not linear.

#include <math.h>

double Thermistor(int RawADC) {
 double Temp;
 Temp =log(10000.0/(1024.0/RawADC-1)); // for pull-up configuration
 Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
 Temp = Temp - 273.15;            // Convert Kelvin to Celcius
 return Temp;
}

void setup() {
 Serial.begin(9600);
}

void loop() {
 Serial.println(int(Thermistor(analogRead(A0))));
 delay(1000);
}


问:
Rewriting in simple theorem proof
I wrote a definition of group in Idris:

```<code>data Group: Type -> Type where
    Unit: (x: t) -> Group t
    (*): Group t -> Group t -> Group t
    Inv: Group t -> Group t
postulate
    assoc: (a : Group t) -> (b : Group t) -> (c : Group t) -> ((a*b)*c = a*(b*c))
postulate
    neutralL: (x: t) -> (a : Group t) -> a * Unit x = a
postulate
    neutralR: (x: t) -> (a : Group t) -> Unit x * a = a
postulate
    invUnitL: (x: t) -> (a : Group t) -> a * (Inv a) = Unit x
postulate
    invUnitR: (x: t) -> (a : Group t) -> (Inv a) * a = Unit x
</code>```

Then I proved a couple of simple propositions:

```<code>cong : (a : Group t) -> (b : Group t) -> (c: Group t) -> a = b -> a*c = b*c
cong a b c post = rewrite post in Refl

neutralL1: (x: t) -> (a : Group t) -> a = a * Unit x
neutralL1 x a = rewrite neutralL x a in Refl

neutralR1: (x: t) -> (a : Group t) -> a = Unit x * a
neutralR1 x a = rewrite neutralR x a in Refl
</code>```

However, I have a problem with proving that there is only one unit element:

```<code>singleUnit : (x: t) -> (y: t) -> (Unit x = Unit y)
</code>```

I tried various expressions using a general idea, that Unit x = (by neutralL1 y (Unit x)) = Unit x * Unit y = (by neutralR x (Unit y)) = Unit y, but with no success:

```<code>singleUnit x y = rewrite neutralL1 y (Unit x) in neutralR x (Unit y)
singleUnit x y = rewrite neutralL1 y (Unit x) in rewrite neutralR x (Unit y) in Refl
singleUnit x y = rewrite neutralR x (Unit y) in neutralL1 y (Unit x)
singleUnit x y = rewrite neutralR x (Unit y) in rewrite neutralL1 y (Unit x) in Refl
</code>```

How can I prove this?
I have a feeling, that the problem here is related to substitution of complex expressions, like Unit x * Unit y.

答:
Unfortunately, this definition of a group won't work. In general, you have to be very careful introducing new axioms (postulates).

E.g. it's easy to see that neutralL violates the principle of disjointness of (different) data constructors, i.e. Constr1 <data> != Constr2 <data>.

```<code>starAndUnitAreDisjoint : (*) a (Unit x) = a -> Void
starAndUnitAreDisjoint Refl impossible
</code>```

Now we can prove false:

```<code>contradiction : Void
contradiction = starAndUnitAreDisjoint $ neutralL Z (Unit Z)
</code>```

Finita la commedia!

What you actually want is a record or a typeclass, see e.g. contrib/Control/Algebra.idr and contrib/Interfaces/Verified.idr. In addition, Agda versions are syntactically pretty close to Idris (agda-stdlib/src/Algebra.agda and probably the Abstract Algebra in Agda tutorial) -- you might want to have a look at them.

Title: Rewriting in simple theorem proof

Body:
I wrote a definition of group in Idris:

data Group: Type -> Type where
    Unit: (x: t) -> Group t
    (*): Group t -> Group t -> Group t
    Inv: Group t -> Group t
postulate
    assoc: (a : Group t) -> (b : Group t) -> (c : Group t) -> ((a*b)*c = a*(b*c))
postulate
    neutralL: (x: t) -> (a : Group t) -> a * Unit x = a
postulate
    neutralR: (x: t) -> (a : Group t) -> Unit x * a = a
postulate
    invUnitL: (x: t) -> (a : Group t) -> a * (Inv a) = Unit x
postulate
    invUnitR: (x: t) -> (a : Group t) -> (Inv a) * a = Unit x

Then I proved a couple of simple propositions:

cong : (a : Group t) -> (b : Group t) -> (c: Group t) -> a = b -> a*c = b*c
cong a b c post = rewrite post in Refl

neutralL1: (x: t) -> (a : Group t) -> a = a * Unit x
neutralL1 x a = rewrite neutralL x a in Refl

neutralR1: (x: t) -> (a : Group t) -> a = Unit x * a
neutralR1 x a = rewrite neutralR x a in Refl

However, I have a problem with proving that there is only one unit element:

singleUnit : (x: t) -> (y: t) -> (Unit x = Unit y)

I tried various expressions using a general idea, that Unit x = (by neutralL1 y (Unit x)) = Unit x * Unit y = (by neutralR x (Unit y)) = Unit y, but with no success:

singleUnit x y = rewrite neutralL1 y (Unit x) in neutralR x (Unit y)
singleUnit x y = rewrite neutralL1 y (Unit x) in rewrite neutralR x (Unit y) in Refl
singleUnit x y = rewrite neutralR x (Unit y) in neutralL1 y (Unit x)
singleUnit x y = rewrite neutralR x (Unit y) in rewrite neutralL1 y (Unit x) in Refl

How can I prove this?
I have a feeling, that the problem here is related to substitution of complex expressions, like Unit x * Unit y.

Body:
Unfortunately, this definition of a group won't work. In general, you have to be very careful introducing new axioms (postulates).

E.g. it's easy to see that neutralL violates the principle of disjointness of (different) data constructors, i.e. Constr1 <data> != Constr2 <data>.

starAndUnitAreDisjoint : (*) a (Unit x) = a -> Void
starAndUnitAreDisjoint Refl impossible

Now we can prove false:

contradiction : Void
contradiction = starAndUnitAreDisjoint $ neutralL Z (Unit Z)

Finita la commedia!

What you actually want is a record or a typeclass, see e.g. contrib/Control/Algebra.idr and contrib/Interfaces/Verified.idr. In addition, Agda versions are syntactically pretty close to Idris (agda-stdlib/src/Algebra.agda and probably the Abstract Algebra in Agda tutorial) -- you might want to have a look at them.


问:
Insert a symbol ">" between the characters in a list of strings
I have a column in Excel like this:

```<code>ABC
BCD
BA
</code>```

How can I put the symbols ">" between every letters in the strings? The expected output should be like this:

```<code>A>B>C
B>C>D
B>A
</code>```

Or could we do this in Matlab ?

答:
You'll want to create a custom function that takes in the value, loops through and places the characters, from the looks of it you want to skip when the character is a space... I also added the ability to change the character you are inserting on the fly, rather than hard coding. Something like:</p>

```<code>Public Function AddGTSigns(strIn As String, strCharToAdd As String) As String
    Dim strOut As String
    Dim lngCount As Integer
    Dim lngLength As Integer
    Dim strNextChar As String
    lngLength = Len(strIn)

    For lngCount = 1 To lngLength
        strOut = strOut & Mid(strIn, lngCount, 1)
        If lngCount < lngLength Then
            'Check next character'
            If Mid(strIn, lngCount, 1) <> " " Then
                strOut = strOut & strCharToAdd
            End If
        End If
    Next lngCount

    AddGTSigns = strOut

End Function

Private Sub RunIt()
    Dim strTest As String

    strTest = AddGTSigns("ABC CDE GHE", ">")

    MsgBox strTest
End Sub
</code>```

Body:
I have a column in Excel like this:

ABC
BCD
BA

How can I put the symbols ">" between every letters in the strings? The expected output should be like this:

A>B>C
B>C>D
B>A

Or could we do this in Matlab ?

Body:
You'll want to create a custom function that takes in the value, loops through and places the characters, from the looks of it you want to skip when the character is a space... I also added the ability to change the character you are inserting on the fly, rather than hard coding. Something like:

Public Function AddGTSigns(strIn As String, strCharToAdd As String) As String
    Dim strOut As String
    Dim lngCount As Integer
    Dim lngLength As Integer
    Dim strNextChar As String
    lngLength = Len(strIn)

    For lngCount = 1 To lngLength
        strOut = strOut & Mid(strIn, lngCount, 1)
        If lngCount < lngLength Then
            'Check next character'
            If Mid(strIn, lngCount, 1) <> " " Then
                strOut = strOut & strCharToAdd
            End If
        End If
    Next lngCount

    AddGTSigns = strOut

End Function

Private Sub RunIt()
    Dim strTest As String

    strTest = AddGTSigns("ABC CDE GHE", ">")

    MsgBox strTest
End Sub


问:
node.js pg-promise and pagination from API
Looking at https://github.com/vitaly-t/pg-promise/wiki/Data-Imports there's a very detailed doc on how to use it for importing.

However while that works for the demoed scenario I don't know how to apply it on my case.

When I do my web call, I get the actual JSON data and a paramter in the header which gives me a value for the next page (could be a date or String or a number value).

In the example, it says:

```<code>db.tx('massive-insert', t => {
    return t.sequence(index => {
        return getNextData(index)
            .then(data => {
                if (data) {
                    const insert = pgp.helpers.insert(data, cs);
                    return t.none(insert);
                }
            });
    });
})
    .then(data => {
        console.log('Total batches:', data.total, ', Duration:', data.duration);
    })
    .catch(error => {
        console.log(error);
    });
</code>```

In this case, sequence(index will use index which seems to increment +1.
But in my case,

```<code>function getNextData(nextPage) {
    //get the data for nextPage
    .....
   //get the nextPage if exists for future use
   nextPage = response.next;

   resolve(data);
}
</code>```

My question is, how can I replace index with nextPage in  this example, as each new Promise needs to use the nextPage from previous one.

LATER EDIT: And if I want to fetch info from a certain value of nextPageInfo?

For instance:

```<code>db.any('Select value from table')
      .then(function(value) {

var data = value; //not working

db.tx('massive-insert', t => {
    return t.sequence((index, data) => {
        return getNextData(index, data)
            .then(a => {
                if (a) {
                    const insert = pgp.helpers.insert(a.data, cs);
                    return t.none(insert).then(() => a.nextPageInfo);
                }
            })
    });
})
    .then(data => {
        // COMMIT has been executed
        console.log('Total batches:', data.total, ', Duration:', data.duration);
    })
    .catch(error => {
        // ROLLBACK has been executed
        console.log(error);
    })

}
</code>```

答:
Following this question, I have extended article Data Imports with the new extras section, which gives you exactly the example that you need. The example copied from the article:

```<code>function getNextData(t, index, nextPageInfo) {
    // t = database transaction protocol

    // NOTE: nextPageInfo = undefined when index = 0

    return new Promise((resolve, reject) {

        /* pull the next data, according to nextPageInfo */

        /* do reject(error) on an error, to ROLLBACK changes */

        if(/* there is still data left*/) {
            // if whateverNextDetails = undefined, the data will be inserted,
            // but the sequence will end there (as success).
            resolve({data, nextPageInfo: whateverNextDetails});
        } else {
            resolve(null);
        }
    });
}

db.tx('massive-insert', t => {
    return t.sequence((index, data) => {
        return getNextData(t, index, data)
            .then(a => {
                if (a) {
                    const insert = pgp.helpers.insert(a.data, cs);
                    return t.none(insert).then(() => a.nextPageInfo);
                }
            })
    });
})
    .then(data => {
        // COMMIT has been executed
        console.log('Total batches:', data.total, ', Duration:', data.duration);
    })
    .catch(error => {
        // ROLLBACK has been executed
        console.log(error);
    });
</code>```

Please note that since we are chaining the result from getNextData to the value of nextPageInfo, then if its value is undefined, it will do the next insert, but then will end the sequence (as success).

Body:
Looking at https://github.com/vitaly-t/pg-promise/wiki/Data-Imports there's a very detailed doc on how to use it for importing.

However while that works for the demoed scenario I don't know how to apply it on my case.

When I do my web call, I get the actual JSON data and a paramter in the header which gives me a value for the next page (could be a date or String or a number value).

In the example, it says:

db.tx('massive-insert', t => {
    return t.sequence(index => {
        return getNextData(index)
            .then(data => {
                if (data) {
                    const insert = pgp.helpers.insert(data, cs);
                    return t.none(insert);
                }
            });
    });
})
    .then(data => {
        console.log('Total batches:', data.total, ', Duration:', data.duration);
    })
    .catch(error => {
        console.log(error);
    });

In this case, sequence(index will use index which seems to increment +1.
But in my case,

function getNextData(nextPage) {
    //get the data for nextPage
    .....
   //get the nextPage if exists for future use
   nextPage = response.next;

   resolve(data);
}

My question is, how can I replace index with nextPage in  this example, as each new Promise needs to use the nextPage from previous one.

LATER EDIT: And if I want to fetch info from a certain value of nextPageInfo?

For instance:

db.any('Select value from table')
      .then(function(value) {

var data = value; //not working

db.tx('massive-insert', t => {
    return t.sequence((index, data) => {
        return getNextData(index, data)
            .then(a => {
                if (a) {
                    const insert = pgp.helpers.insert(a.data, cs);
                    return t.none(insert).then(() => a.nextPageInfo);
                }
            })
    });
})
    .then(data => {
        // COMMIT has been executed
        console.log('Total batches:', data.total, ', Duration:', data.duration);
    })
    .catch(error => {
        // ROLLBACK has been executed
        console.log(error);
    })

}

Body:
Following this question, I have extended article Data Imports with the new extras section, which gives you exactly the example that you need. The example copied from the article:

function getNextData(t, index, nextPageInfo) {
    // t = database transaction protocol

    // NOTE: nextPageInfo = undefined when index = 0

    return new Promise((resolve, reject) {

        /* pull the next data, according to nextPageInfo */

        /* do reject(error) on an error, to ROLLBACK changes */

        if(/* there is still data left*/) {
            // if whateverNextDetails = undefined, the data will be inserted,
            // but the sequence will end there (as success).
            resolve({data, nextPageInfo: whateverNextDetails});
        } else {
            resolve(null);
        }
    });
}

db.tx('massive-insert', t => {
    return t.sequence((index, data) => {
        return getNextData(t, index, data)
            .then(a => {
                if (a) {
                    const insert = pgp.helpers.insert(a.data, cs);
                    return t.none(insert).then(() => a.nextPageInfo);
                }
            })
    });
})
    .then(data => {
        // COMMIT has been executed
        console.log('Total batches:', data.total, ', Duration:', data.duration);
    })
    .catch(error => {
        // ROLLBACK has been executed
        console.log(error);
    });

Please note that since we are chaining the result from getNextData to the value of nextPageInfo, then if its value is undefined, it will do the next insert, but then will end the sequence (as success).


问:
jQuery resizable() and multiple alsoResizes?
Is there a way to set multiple alsoResizes in jQuery UI?

```<code>$('.selector').resizable({ alsoResize: '.other' });
</code>```

I would like to set a couple of other elements to also resize, not just one. The official documentation tells nothing.

答:
You can pass in an array of strings like so:

```<code>$('.selector').resizable({ alsoResize: [
    '.other',
    '.and-another',
    '#and-one-more'
]});
</code>```

These strings should represent selectors.  You can also resize by class or id.

Body:
Is there a way to set multiple alsoResizes in jQuery UI?

$('.selector').resizable({ alsoResize: '.other' });

I would like to set a couple of other elements to also resize, not just one. The official documentation tells nothing.

Body:
You can pass in an array of strings like so:

$('.selector').resizable({ alsoResize: [
    '.other',
    '.and-another',
    '#and-one-more'
]});

These strings should represent selectors.  You can also resize by class or id.


问:
Property 'files' does not exist on type 'EventTarget' error in typescript
I am trying to access the value of the input file from my ionic 2 application but still I'm facing the issue of property files does not exist on type 'EventTarget'.
As it is properly working in js but not in typescript.
The code is given below:

```<code>  document.getElementById("customimage").onchange= function(e?) {
            var files: any = e.target.files[0];
              EXIF.getData(e.target.files[0], function() {
                  alert(EXIF.getTag(this,"GPSLatitude"));
              });
          }
</code>```

Please help me solve this issue as it is not building my ionic 2 application.

答:
You can cast it as a HTMLInputElement:

```<code>document.getElementById("customimage").onchange = function(e: Event) {
    let file = (<HTMLInputElement>e.target).files[0];
    // rest of your code...
}
</code>```

Update:

You can also use this:

```<code>let file = (e.target as HTMLInputElement).files[0];
</code>```

Body:
I am trying to access the value of the input file from my ionic 2 application but still I'm facing the issue of property files does not exist on type 'EventTarget'.
As it is properly working in js but not in typescript.
The code is given below:

  document.getElementById("customimage").onchange= function(e?) {
            var files: any = e.target.files[0];
              EXIF.getData(e.target.files[0], function() {
                  alert(EXIF.getTag(this,"GPSLatitude"));
              });
          }

Please help me solve this issue as it is not building my ionic 2 application.

Body:
You can cast it as a HTMLInputElement:

document.getElementById("customimage").onchange = function(e: Event) {
    let file = (<HTMLInputElement>e.target).files[0];
    // rest of your code...
}

Update:

You can also use this:

let file = (e.target as HTMLInputElement).files[0];


问:
Resolving issue: ActionFilterAttribute in Unity
I have found this blogpost: http://blog.bitdiff.com/2012/05/sharing-common-view-model-data-in.html?showComment=1499113088147#c5286707438454380796 about sharing strongly-typed common view model data in asp.net mvc, and it look to me like it would solve of the problems I have with keeping track of some user related data across views.

I’m a complete novice when it comes to DI and Unity as I have never used it before, but I have an understanding of the benefits of using it. The post is from May 2012 but should as far as I can see still be valid, perhaps with some small changes.

I’m using C#, MVC 5, EF, Code First, Migrations, Unity V4.01 and Unity.MVC V4.01 with VS2015 Community Edition.

I have followed the blogpost from start to near finish (lacking the test) and all compiles. I have one problem though, this line causes problems:

```<code>GlobalFilters.Filters.Add(container.Resolve<LayoutModelAttribute>(), 1);
</code>```

As far as I can tell the right place to call place the line is in the FilterConfig.cs file in the App_start folder where I’ve done this:

```<code>    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        var container = UnityConfig.GetConfiguredContainer();
        filters.Add(container.Resolve<LayoutModelAttribute>());
    }
</code>```

The container.Resolve gets a squiggly line beneath it and the project won’t compile. The error description is this:

“The non-generic method 'IUnityContainer.Resolve(Type, string, params
  ResolverOverride[])' cannot be used with type arguments”

I’ve tried some other places also, but the result is the same, I now lean towards the notion that Unity itself has changed since 2012, and now must be resolved in a different way.

I’m pretty sure I’m doing something wrong and that it properly is because the blogpost is from 2012 and Unity now works in a different way. Due to my lack of experience with Unity, I’m unable to figure out how to change the line of code that won’t compile or to what extend and how to refactor the blogpost if necessary.

I’m hoping someone out there can point me in the right direction.

答:
It seems you are using container without it having a capability of injecting. Have a look at the following answer
Simple Injector property injection on action filter</p>

Body:
I have found this blogpost: http://blog.bitdiff.com/2012/05/sharing-common-view-model-data-in.html?showComment=1499113088147#c5286707438454380796 about sharing strongly-typed common view model data in asp.net mvc, and it look to me like it would solve of the problems I have with keeping track of some user related data across views.

I’m a complete novice when it comes to DI and Unity as I have never used it before, but I have an understanding of the benefits of using it. The post is from May 2012 but should as far as I can see still be valid, perhaps with some small changes.

I’m using C#, MVC 5, EF, Code First, Migrations, Unity V4.01 and Unity.MVC V4.01 with VS2015 Community Edition.

I have followed the blogpost from start to near finish (lacking the test) and all compiles. I have one problem though, this line causes problems:

GlobalFilters.Filters.Add(container.Resolve<LayoutModelAttribute>(), 1);

As far as I can tell the right place to call place the line is in the FilterConfig.cs file in the App_start folder where I’ve done this:

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        var container = UnityConfig.GetConfiguredContainer();
        filters.Add(container.Resolve<LayoutModelAttribute>());
    }

The container.Resolve gets a squiggly line beneath it and the project won’t compile. The error description is this:

“The non-generic method 'IUnityContainer.Resolve(Type, string, params
  ResolverOverride[])' cannot be used with type arguments”

I’ve tried some other places also, but the result is the same, I now lean towards the notion that Unity itself has changed since 2012, and now must be resolved in a different way.

I’m pretty sure I’m doing something wrong and that it properly is because the blogpost is from 2012 and Unity now works in a different way. Due to my lack of experience with Unity, I’m unable to figure out how to change the line of code that won’t compile or to what extend and how to refactor the blogpost if necessary.

I’m hoping someone out there can point me in the right direction.


问:
State monad: How to `print` intermediate value in Haskell
I'm new in haskell and I have following code

```<code>module StateTest where

import Control.Monad.State.Lazy

tick :: State Int Int
tick = do n <- get
          put (n+1)
          return n

plusOne :: Int -> Int
plusOne = execState tick

main = print $ plusOne 1
</code>```

And I want to print state value after put (n+1) and continue computation like this

```<code>tick = do n <- get
          put (n+1)
          print
          return n
</code>```

How whole code will look following to this?

答:
If you want to run IO actions within a state computation you can change the type of tick to return a StateT Int IO Int and use liftIO. Then you can run it using execStateT:

```<code>import Control.Monad.State.Lazy
import Control.Monad.IO.Class (liftIO)

tick :: StateT Int IO Int
tick = do n <- get
          put (n+1)
          liftIO $ print (n+1)
          return n

plusOne :: Int -> IO Int
plusOne = execStateT tick

main = plusOne 1 >> pure ()
</code>```

Body:
I'm new in haskell and I have following code

module StateTest where

import Control.Monad.State.Lazy

tick :: State Int Int
tick = do n <- get
          put (n+1)
          return n

plusOne :: Int -> Int
plusOne = execState tick

main = print $ plusOne 1

And I want to print state value after put (n+1) and continue computation like this

tick = do n <- get
          put (n+1)
          print
          return n

How whole code will look following to this?

Body:
If you want to run IO actions within a state computation you can change the type of tick to return a StateT Int IO Int and use liftIO. Then you can run it using execStateT:

import Control.Monad.State.Lazy
import Control.Monad.IO.Class (liftIO)

tick :: StateT Int IO Int
tick = do n <- get
          put (n+1)
          liftIO $ print (n+1)
          return n

plusOne :: Int -> IO Int
plusOne = execStateT tick

main = plusOne 1 >> pure ()


问:
Filter d3 SVG by JSON Attribute Based on Dropdown
I have node and link data for a force directed graph. Nodes may have one, two, or three links between them:

```<code>{"nodes": [{"id": "Michael Scott", "numOfLinks": 1}
          ,{"id": "Jim Halpert", "numOfLinks": 1}
          ,{"id": "Pam Beasley", "numOfLinks": 2}
          ,{"id": "Kevin Malone", "numOfLinks": 2}
          ,{"id": "Angela", "numOfLinks": 3}
          ,{"id": "Dwight Schrute", "numOfLinks": 3}]
,"links": [{"source": "Michael Scott", "target": "Jim Halpert", "type": "red"}
          ,{"source": "Pam Beasley", "target": "Kevin Malone", "type": "red"}
          ,{"source": "Pam Beasley", "target": "Kevin Malone", "type": "white"}
          ,{"source": "Angela", "target": "Dwight Schrute", "type": "red"}
          ,{"source": "Angela", "target": "Dwight Schrute", "type": "white"}
          ,{"source": "Angela", "target": "Dwight Schrute", "type": "blue"}]
}
</code>```

I have an HTML drop down for users to filter out nodes (and corresponding links) that don't have a certain number of links:

```<code><select id="selectLinkNumber" name="selectLinkNumber">
     <option value="1">All</option>
     <option value="2">Two or More Links</option>
     <option value="3">Three or More Links</option>
</select>
</code>```

I have incorporated this drop down into my d3 code:

```<code>var dropdown = d3.select("#selectLinkNumber")
var change = function() {
d3.selectAll("svg > *").remove()
var val = dropdown.node().options[dropdown.node().selectedIndex].value;

d3.json("test.json", function(error, graph) {
    //do stuff
    })
}
dropdown.on("change", change)
change();
</code>```

This results in a graph that is removed and reappears when a new selection is made from the drop down. The goal is to have only the nodes with values greater than or equal to the selection appear. For example, if "Three" is chosen, only Angela, Dwight, and their three links appear. If "Two" is chosen, Pam, Kevin, Angela, Dwight, and their corresponding links are chosen.

Logically, I think there needs to be something that filters the test.json data directly after the d3.json("test.json", function(error, graph) { line, based on val. I'm not sure how to efficiently accomplish this however. This example (https://jsfiddle.net/tgv6s5cd/14/) essentially does what I'm looking for, but I couldn't figure my way past the manual data creation and numerous functions. I think it would be simpler to just filter once after bringing in test.json

How should I filter data once the user makes a dropdown selection?

答:
That is basic array manipulation in Javascript. graph after all is just an object with two array properties.

```<code>d3.json("test.json", function(error, graph) {
    var filteredNodes = graph.nodes.filter(d => d.numOfLinks >= val);
    var names = filteredNodes.map(d => d.id);
    var filteredLinks = graph.links.filter((d) => {
        return (names.indexOf(d.source) >= 0) ||
               (names.indexOf(d.target) >= 0)
    });

    var filteredGraph = {
        nodes: filteredNodes,
        links: filteredLinks
    };
    // render
})
</code>```

Body:
I have node and link data for a force directed graph. Nodes may have one, two, or three links between them:

{"nodes": [{"id": "Michael Scott", "numOfLinks": 1}
          ,{"id": "Jim Halpert", "numOfLinks": 1}
          ,{"id": "Pam Beasley", "numOfLinks": 2}
          ,{"id": "Kevin Malone", "numOfLinks": 2}
          ,{"id": "Angela", "numOfLinks": 3}
          ,{"id": "Dwight Schrute", "numOfLinks": 3}]
,"links": [{"source": "Michael Scott", "target": "Jim Halpert", "type": "red"}
          ,{"source": "Pam Beasley", "target": "Kevin Malone", "type": "red"}
          ,{"source": "Pam Beasley", "target": "Kevin Malone", "type": "white"}
          ,{"source": "Angela", "target": "Dwight Schrute", "type": "red"}
          ,{"source": "Angela", "target": "Dwight Schrute", "type": "white"}
          ,{"source": "Angela", "target": "Dwight Schrute", "type": "blue"}]
}

I have an HTML drop down for users to filter out nodes (and corresponding links) that don't have a certain number of links:

<select id="selectLinkNumber" name="selectLinkNumber">
     <option value="1">All</option>
     <option value="2">Two or More Links</option>
     <option value="3">Three or More Links</option>
</select>

I have incorporated this drop down into my d3 code:

var dropdown = d3.select("#selectLinkNumber")
var change = function() {
d3.selectAll("svg > *").remove()
var val = dropdown.node().options[dropdown.node().selectedIndex].value;

d3.json("test.json", function(error, graph) {
    //do stuff
    })
}
dropdown.on("change", change)
change();

This results in a graph that is removed and reappears when a new selection is made from the drop down. The goal is to have only the nodes with values greater than or equal to the selection appear. For example, if "Three" is chosen, only Angela, Dwight, and their three links appear. If "Two" is chosen, Pam, Kevin, Angela, Dwight, and their corresponding links are chosen.

Logically, I think there needs to be something that filters the test.json data directly after the d3.json("test.json", function(error, graph) { line, based on val. I'm not sure how to efficiently accomplish this however. This example (https://jsfiddle.net/tgv6s5cd/14/) essentially does what I'm looking for, but I couldn't figure my way past the manual data creation and numerous functions. I think it would be simpler to just filter once after bringing in test.json

How should I filter data once the user makes a dropdown selection?

Body:
That is basic array manipulation in Javascript. graph after all is just an object with two array properties.

d3.json("test.json", function(error, graph) {
    var filteredNodes = graph.nodes.filter(d => d.numOfLinks >= val);
    var names = filteredNodes.map(d => d.id);
    var filteredLinks = graph.links.filter((d) => {
        return (names.indexOf(d.source) >= 0) ||
               (names.indexOf(d.target) >= 0)
    });

    var filteredGraph = {
        nodes: filteredNodes,
        links: filteredLinks
    };
    // render
})


问:
Performance Comparison of Shell Scripts vs high level interpreted langs (C#/Java/etc.)
First - This is not meant to be a 'which is better, ignorant nonionic war thread'... But rather, I generally need help in making an architecture decision / argument to put forward to my boss.

Skipping the details - I simply just would love to know and find the results of anyone who has done some performance comparisons of Shell vs [Insert General Purpose Programming Language (interpreted) here), such as C# or Java...

Surprisingly, I have spent some time on Google on searching here to not find any of this data. Has anyone ever done these comparisons, in different use-cases; hitting a database like in a XYX # of loops doing different types of SQL (Oracle pref, but MSSQL would do) queries such as any of the CRUD ops - and also not hitting database and just regular 50k loop type comparison doing different types of calculations, and things of that nature?

In particular - for right now, I need to a comparison of hitting an Oracle DB from a shell script vs, lets say C# (again, any GPPL thats interpreted would be fine, even the higher level ones like Python). But I also need to know about standard programming calculations / instructions/etc...

Before you ask 'why not just write a quick test yourself? The answer is: I've been a Windows developer my whole life/career and have very limited knowledge of Shell scripting - not to mention *nix as a whole.... So asking the question on here from the more experienced guys would be grealty beneficial, not to mention time saving as we are in near perputual deadline crunch as it is ;).

答:
It is highly dependent on what the script is doing. I've seen poorly written shell scripts sped up by one, two even three orders of magnitude by making simple changes.

Typically, a shell script is simply some glue logic that runs utilities that are usually compiled C or C++. If that's the case, there may not be much that can be done to speed things up. If the grunt work is being done by a poorly written utility that's compiled, it's just doing a lot of wasted effort really fast.

That said, Python or Perl are going to be much faster than a shell script, but a VM or native code will be faster yet.

Since you can't tell us any details, we can't really provide specific help.

If you want to see a simple demonstration for comparison, try my pure-Bash implementation of hexdump and compare it to the real thing:

```<code>$ time ./bash-hexdump /bin/bash > /dev/null
real    7m17.577s
user    7m2.570s
sys     0m14.745s
$ time hexdump -C /bin/bash > /dev/null
real    0m2.459s
user    0m2.260s
sys     0m0.176s
</code>```

One of the main reasons the Bash version is slow is that it reads the file character by character which is necessary to handle null bytes (shells aren't very good at handling binary data), but the primary reason is the speed of execution. Here is an example of a Python script I found:

```<code>$ time ./hexdump.py /bin/bash > /dev/null
real    0m11.694s
user    0m11.605s
sys     0m0.040s
</code>```

Body:
It is highly dependent on what the script is doing. I've seen poorly written shell scripts sped up by one, two even three orders of magnitude by making simple changes.

Typically, a shell script is simply some glue logic that runs utilities that are usually compiled C or C++. If that's the case, there may not be much that can be done to speed things up. If the grunt work is being done by a poorly written utility that's compiled, it's just doing a lot of wasted effort really fast.

That said, Python or Perl are going to be much faster than a shell script, but a VM or native code will be faster yet.

Since you can't tell us any details, we can't really provide specific help.

If you want to see a simple demonstration for comparison, try my pure-Bash implementation of hexdump and compare it to the real thing:

$ time ./bash-hexdump /bin/bash > /dev/null
real    7m17.577s
user    7m2.570s
sys     0m14.745s
$ time hexdump -C /bin/bash > /dev/null
real    0m2.459s
user    0m2.260s
sys     0m0.176s

One of the main reasons the Bash version is slow is that it reads the file character by character which is necessary to handle null bytes (shells aren't very good at handling binary data), but the primary reason is the speed of execution. Here is an example of a Python script I found:

$ time ./hexdump.py /bin/bash > /dev/null
real    0m11.694s
user    0m11.605s
sys     0m0.040s


问:
Select current line in intellij
Is there any way to select the whole line at caret in IntelliJ 15? I know you can select the current word (ctl + w), go to beginning/end of line but I can't find a current line selection feature.</p>

答: If none of the above are working, I suggest using end and home keys in combination with shift allowing you to select lines quickly.

Title: Select current line in intellij


问:
Why does it take such a long time for UI to be updated from background thread?
I understand that all UI updates must be done from Main thread.

But purely for the sake of deeper understanding how GCD and dispatch main work:

I have a button that runs a network call and in its completionHandler I eventually do:

```<code>self.layer.borderColor = UIColor(red: 255/255.0, green: 59/255.0, blue: 48/255.0, alpha: 1.0).cgColor
self.layer.borderWidth = 3.0
</code>```

For the color change to happen it takes 6-7 seconds. Obviously if run the above code from main thread it would change the border color immediately.

Question1 even though I don't have ANY other code to run, why doesn't the UI changes happen immediately from the background thread? What is waiting for?

Interesting though is that if I click the button to make the network call and then tap on the textField itself (before the 6-7 seconds), the border color would change immediately.

Is that happening because of:

From the background thread I've updated the model ie change the textField color which queues the UI/view to be updated...but since we're on a background queue, that UI updated could take a few seconds to happen

But then I tapped on the textField right away and forced a super quick read of the textField and all its properties which includes the border—from main thread (actual user touches are always handled through main thread)...which even though are not yet red on the screen, but since it's red on the model it will read from it and change color to red immediately.

Question2: Is that observation correct?

If I don't tap and just wait:

If I tap:

My full code is as below:

```<code>import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!

    @IBAction func isValid(_ sender: Any) {

        let userEmail = textField.text

        let requestURL = NSURL(string: "https://jsonplaceholder.typicode.com")

        var request = URLRequest(url: requestURL as! URL)

        request.httpMethod = "POST"

        let postString = "Anything"

        request.httpBody = postString.data(using: .utf8)

        let task = URLSession.shared.dataTask(with: request) { data, response, error in

            guard let data = data, error == nil else {
                print("error=\(error)")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            }

            do {

                let json = try? JSONSerialization.jsonObject(with: data, options: [])

                if let _ = json as? [String: Any] {

                    self.textField.layer.borderColor = UIColor(red: 255/255.0, green: 59/255.0, blue: 48/255.0, alpha: 1.0).cgColor
                    self.textField.layer.borderWidth = 3.0

                }

            } catch let error as NSError {
                print(error)
            }

        }
        task.resume()

    }
    override func viewDidLoad() {
        super.viewDidLoad()
    }

}
</code>```

答:
If you attempt to do UI updates from a background thread, "the results are undefined." The most common effect I've seen is what you describe - very long delays before the update shows up. The second-most common effect I've seen is a crash. The third-most common effect is some sort of drawing artifact.

The results of doing UI updates from a background thread are truly nondeterministic. You've got multiple processor cores accessing the same hardware resources at the same time, and with the exact timing between those accesses being unknowable and infinitely variable. It would be like having a computer with no display but 2 keyboards and 2 mice, and 2 operators editing the same document at the same time. Each person's actions with the keyboard would change the state of the document, and screw up the changes the other person was trying to apply. The cursor would be in the wrong place. The amount of text in the document would be different than expected. The scroll position would be off. etc, etc.

Similarly, if 2 cores are each trying to access hardware resources to do screen refreshes, those accesses will cross and conflict with each other.

As Martin says in his comment, the UIKit code is proprietary, so we can't know the details of what goes wrong. All we know is that bad things happen, so DON'T DO THAT.

Body:
I understand that all UI updates must be done from Main thread.

But purely for the sake of deeper understanding how GCD and dispatch main work:

I have a button that runs a network call and in its completionHandler I eventually do:

self.layer.borderColor = UIColor(red: 255/255.0, green: 59/255.0, blue: 48/255.0, alpha: 1.0).cgColor
self.layer.borderWidth = 3.0

For the color change to happen it takes 6-7 seconds. Obviously if run the above code from main thread it would change the border color immediately.

Question1 even though I don't have ANY other code to run, why doesn't the UI changes happen immediately from the background thread? What is waiting for?

Interesting though is that if I click the button to make the network call and then tap on the textField itself (before the 6-7 seconds), the border color would change immediately.

Is that happening because of:

From the background thread I've updated the model ie change the textField color which queues the UI/view to be updated...but since we're on a background queue, that UI updated could take a few seconds to happen

But then I tapped on the textField right away and forced a super quick read of the textField and all its properties which includes the border—from main thread (actual user touches are always handled through main thread)...which even though are not yet red on the screen, but since it's red on the model it will read from it and change color to red immediately.

Question2: Is that observation correct?

If I don't tap and just wait:

If I tap:

My full code is as below:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!

    @IBAction func isValid(_ sender: Any) {

        let userEmail = textField.text

        let requestURL = NSURL(string: "https://jsonplaceholder.typicode.com")

        var request = URLRequest(url: requestURL as! URL)

        request.httpMethod = "POST"

        let postString = "Anything"

        request.httpBody = postString.data(using: .utf8)

        let task = URLSession.shared.dataTask(with: request) { data, response, error in

            guard let data = data, error == nil else {
                print("error=\(error)")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            }

            do {

                let json = try? JSONSerialization.jsonObject(with: data, options: [])

                if let _ = json as? [String: Any] {

                    self.textField.layer.borderColor = UIColor(red: 255/255.0, green: 59/255.0, blue: 48/255.0, alpha: 1.0).cgColor
                    self.textField.layer.borderWidth = 3.0

                }

            } catch let error as NSError {
                print(error)
            }

        }
        task.resume()

    }
    override func viewDidLoad() {
        super.viewDidLoad()
    }

}