答:
It doesn't need to be hoisted.

The functions don't try to access the variable until they are called.

You don't call them until after the constant is defined and has a value assigned to it.

Title: Javascript Temporal Dead Zone

Body:
I don't really understand what's happening with the snippet below.

I would expect an error because of the Temporal Dead Zone, but it looks like const baz = '123123'; gets hoisted.

What's the reason why everything works?

class Foo {
  constructor() {
    console.log('Foo baz is:', baz)
  }
}

function log() {
  console.log('log baz is:', baz);
}

const baz = '123123';

log();
new Foo();


来源: stackexchange

问:
How to use the identity as a column value during an insert
I have a stored proc containing an SQL statement which is something like:

```<code>CREATE PROCEDURE SaveUser
@UserName nvarchar(10),
@FirstName nvarchar(150),
@LastName nvarchar(150)

AS
BEGIN

    INSERT INTO Users (UserName, FirstName, LastName)
    VALUES (@UserName, @FirstName, @LastName)

    SELECT SCOPE_IDENTITY()

END
</code>```

Some users cannot log into the system and do not have a username; however, the UserName field has a unique index on it so I would like to be able to insert the users ID #, which is an auto increment field, as the UserName.

Does anyone know of an MS SQL Server method or variable which would allow me to do something like?

```<code>INSERT INTO Users (UserName, FirstName, LastName)
VALUES (ISNULL(@UserName, SCOPE_IDENTITY()),@FirstName,@LastName)
</code>```

Edit My intention right now is to use something like the following

```<code>DECLARE @NextID int
SET @NextID = IDENT_CURRENT(Users) + IDENT_INCR(Users)

INSERT INTO Users (UserName, FirstName, LastName)
VALUES (ISNULL(@UserName, @NextID), @FirstName, @LastName)
</code>```

I would just like to know if there is a built in method which could guarantee that this would be consistent.

答:
For anyone using SQL Server 2008 or beyond, there is a new feature that solves this problem quite easily and with no need to make any app or Proc changes: Filtered Indexes.  Filtered Indexes let you put a WHERE condition on the Index so that the Index will ignore those values.  In this case, you can ignore null UserName values, even in a Unique Index.

The syntax is as follows:

```<code>CREATE UNIQUE INDEX IX_Users_UserName ON Users (UserName)
                         WHERE UserName is not null
</code>```

Using a Filtered Index to solve this particular problem also means that you do not need to put junk-data into the UserName field.

ContentLicense: CC BY-SA 2.5

Body:
I have a stored proc containing an SQL statement which is something like:

CREATE PROCEDURE SaveUser
@UserName nvarchar(10),
@FirstName nvarchar(150),
@LastName nvarchar(150)

AS
BEGIN

    INSERT INTO Users (UserName, FirstName, LastName)
    VALUES (@UserName, @FirstName, @LastName)

    SELECT SCOPE_IDENTITY()

END

Some users cannot log into the system and do not have a username; however, the UserName field has a unique index on it so I would like to be able to insert the users ID #, which is an auto increment field, as the UserName.

Does anyone know of an MS SQL Server method or variable which would allow me to do something like?

INSERT INTO Users (UserName, FirstName, LastName)
VALUES (ISNULL(@UserName, SCOPE_IDENTITY()),@FirstName,@LastName)

Edit My intention right now is to use something like the following

DECLARE @NextID int
SET @NextID = IDENT_CURRENT(Users) + IDENT_INCR(Users)

INSERT INTO Users (UserName, FirstName, LastName)
VALUES (ISNULL(@UserName, @NextID), @FirstName, @LastName)

I would just like to know if there is a built in method which could guarantee that this would be consistent.

Body:
For anyone using SQL Server 2008 or beyond, there is a new feature that solves this problem quite easily and with no need to make any app or Proc changes: Filtered Indexes.  Filtered Indexes let you put a WHERE condition on the Index so that the Index will ignore those values.  In this case, you can ignore null UserName values, even in a Unique Index.

The syntax is as follows:

CREATE UNIQUE INDEX IX_Users_UserName ON Users (UserName)
                         WHERE UserName is not null

Using a Filtered Index to solve this particular problem also means that you do not need to put junk-data into the UserName field.

ContentLicense: CC BY-SA 3.0


问:
how to align javascript's equals sign in webstorm
all

when i config my Webstorm9 settings like this ,it turns out that the sample code in the right aligns the equals sign properly

but when i formatting my javascript code in the editor it doesn't work,it still shows

and what i want is align the equals sign

anyone who can take a look?

-------EDIT------

maybe i misunderstand the checked option,but i copy the sample code to my editor then reformat it, oh,bad result..

答:
Update for WebStorm 2017.3

Apparently, since version 2017.3, the Other tab has been removed from Code Style > JavaScript.

Now you have a couple of alignment options under the Wrapping and Braces tab (scroll down to the bottom):

It took me a while to figure this out, hope this helps


问:
Change year/quarter date format to previous period in python
I have a dataset containing monthly observations of a time-series.
What I want to do is transform the datetime to year/quarter format and then extract the first value DATE[0] as the previous quarter. For example 2006-10-31 belongs to 4Q of 2006. But I want to change it to 2006Q3.
For the extraction of the subsequent values I will just use the last value from each quarter.
So, for 2006Q4 I will keep BBGN, SSD, and QQ4567 values only from DATE[2]. Similarly, for 2007Q1 I will keep only DATE[5] values, and so forth.

Original dataset:

```<code>               DATE                BBGN    SSD             QQ4567
    0  2006-10-31 00:00:00        1.210  22.022          9726.550
    1  2006-11-30 00:00:00        1.270  22.060          9891.008
    2  2006-12-31 00:00:00        1.300  22.080         10055.466
    3  2007-01-31 00:00:00        1.330  22.099         10219.924
    4  2007-02-28 00:00:00        1.393  22.110         10350.406
    5  2007-03-31 00:00:00        1.440  22.125         10480.888
</code>```

After processing the DATE

```<code>       DATE          BBGN    SSD             QQ4567
    0  2006Q3        1.210  22.022          9726.550
    2  2006Q4        1.300  22.080         10055.466
    5  2007Q1        1.440  22.125         10480.888
</code>```

The steps I have taken so far are:

Turn the values from the yyyy-mm-dd hh format to yyyyQQ format

```<code>DF['DATE'] = pd.to_datetime(DF['DATE']).dt.to_period('Q')
</code>```

and I get this

```<code>    DATE          BBGN    SSD             QQ4567
0  2006Q4        1.210  22.022          9726.550
1  2006Q4        1.270  22.060          9891.008
2  2006Q4        1.300  22.080         10055.466
3  2007Q1        1.330  22.099         10219.924
4  2007Q1        1.393  22.110         10350.406
5  2007Q1        1.440  22.125         10480.888
</code>```

The next step is to extract the last values from each quarter. But because I always want to keep the first row I will exclude DATE[0] from the function.

```<code>quarterDF = DF.iloc[1:,].drop_duplicates(subset='DATE', keep='last')
</code>```

Now, my question is how can I change the value in DATE[0] to always be the previous quarter. So, from 2006Q4 to be 2006Q3. Also, how this will work if DATE[0] is 2007Q1, can I change it to 2006Q4?

答:
Here is a pivot_table approach

```<code># Subtract the quarter from date save it in a column
df['Q'] = df['DATE'] - pd.tseries.offsets.QuarterEnd()

#0   2006-09-30
#1   2006-09-30
#2   2006-09-30
#3   2006-12-31
#4   2006-12-31
#5   2006-12-31
#Name: Q, dtype: datetime64[ns]

# Drop and pivot for not including the columns
ndf = df.drop(['DATE','Q'],1).pivot_table(index=pd.to_datetime(df['Q']).dt.to_period('Q'),aggfunc='last')

      BBGN     QQ4567     SSD
Qdate
2006Q3  1.30  10055.466  22.080
2006Q4  1.44  10480.888  22.125
</code>```

Body:
I have a dataset containing monthly observations of a time-series.
What I want to do is transform the datetime to year/quarter format and then extract the first value DATE[0] as the previous quarter. For example 2006-10-31 belongs to 4Q of 2006. But I want to change it to 2006Q3.
For the extraction of the subsequent values I will just use the last value from each quarter.
So, for 2006Q4 I will keep BBGN, SSD, and QQ4567 values only from DATE[2]. Similarly, for 2007Q1 I will keep only DATE[5] values, and so forth.

Original dataset:

               DATE                BBGN    SSD             QQ4567
    0  2006-10-31 00:00:00        1.210  22.022          9726.550
    1  2006-11-30 00:00:00        1.270  22.060          9891.008
    2  2006-12-31 00:00:00        1.300  22.080         10055.466
    3  2007-01-31 00:00:00        1.330  22.099         10219.924
    4  2007-02-28 00:00:00        1.393  22.110         10350.406
    5  2007-03-31 00:00:00        1.440  22.125         10480.888

After processing the DATE

       DATE          BBGN    SSD             QQ4567
    0  2006Q3        1.210  22.022          9726.550
    2  2006Q4        1.300  22.080         10055.466
    5  2007Q1        1.440  22.125         10480.888

The steps I have taken so far are:

Turn the values from the yyyy-mm-dd hh format to yyyyQQ format

DF['DATE'] = pd.to_datetime(DF['DATE']).dt.to_period('Q')

and I get this

    DATE          BBGN    SSD             QQ4567
0  2006Q4        1.210  22.022          9726.550
1  2006Q4        1.270  22.060          9891.008
2  2006Q4        1.300  22.080         10055.466
3  2007Q1        1.330  22.099         10219.924
4  2007Q1        1.393  22.110         10350.406
5  2007Q1        1.440  22.125         10480.888

The next step is to extract the last values from each quarter. But because I always want to keep the first row I will exclude DATE[0] from the function.

quarterDF = DF.iloc[1:,].drop_duplicates(subset='DATE', keep='last')

Now, my question is how can I change the value in DATE[0] to always be the previous quarter. So, from 2006Q4 to be 2006Q3. Also, how this will work if DATE[0] is 2007Q1, can I change it to 2006Q4?

Body:
Here is a pivot_table approach

# Subtract the quarter from date save it in a column
df['Q'] = df['DATE'] - pd.tseries.offsets.QuarterEnd()

#0   2006-09-30
#1   2006-09-30
#2   2006-09-30
#3   2006-12-31
#4   2006-12-31
#5   2006-12-31
#Name: Q, dtype: datetime64[ns]

# Drop and pivot for not including the columns
ndf = df.drop(['DATE','Q'],1).pivot_table(index=pd.to_datetime(df['Q']).dt.to_period('Q'),aggfunc='last')

      BBGN     QQ4567     SSD
Qdate
2006Q3  1.30  10055.466  22.080
2006Q4  1.44  10480.888  22.125


问:
Searching for a string of text in a specific worksheet
Im trying to make excel search for a text string in a specific column in a specific worksheet that is not the active worksheet. VBA gives me an error that says i cannot use this method of selection. so my question is, do you have a suggestion to do it in another way?</p>

```<code>Worksheets("Parts for renovation").Columns("Q:Q").Select
Set cell = Selection.Find(What:="Total transfer price", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

If cell Is Nothing Then

    Exit Sub

Else

    Worksheets("Internal").Cells(29, 4) = Worksheets("Parts for Renovation").ActiveCell.Offset(0, 4)

End If
</code>```

答:
Your error comes, because you select a range on a non-active worksheet. This is one of the reasons, why you should be avoiding select in general.

However, if you want to make your code working (which is strongly not advisable), you may consider selecting the worksheet before selecting the range:

```<code>Worksheets("Parts for renovation").Select
Columns("Q:Q").Select
</code>```

For the advisable part, try to avoid the usage of "Select" -
 How to avoid using Select in Excel VBA

Body:
Im trying to make excel search for a text string in a specific column in a specific worksheet that is not the active worksheet. VBA gives me an error that says i cannot use this method of selection. so my question is, do you have a suggestion to do it in another way?

Worksheets("Parts for renovation").Columns("Q:Q").Select
Set cell = Selection.Find(What:="Total transfer price", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

If cell Is Nothing Then

    Exit Sub

Else

    Worksheets("Internal").Cells(29, 4) = Worksheets("Parts for Renovation").ActiveCell.Offset(0, 4)

End If

Body:
Your error comes, because you select a range on a non-active worksheet. This is one of the reasons, why you should be avoiding select in general.

However, if you want to make your code working (which is strongly not advisable), you may consider selecting the worksheet before selecting the range:

Worksheets("Parts for renovation").Select
Columns("Q:Q").Select

For the advisable part, try to avoid the usage of "Select" -
 How to avoid using Select in Excel VBA


问:
How to run test on specific browser by selenium grid
I have register two platform with chrome browser on windows 7 and windows 10 into selenium grid server.

I want to run a test at Chrome browser on Windows 10 but when i run the test, the test randomly run on Windows 7 and randomly run on Windows 10 on chrome.

Do you have an idea how to do the configuration to run the test on specific browser and platform when we have registered multiple platform?

hub:

```<code>java -jar selenium-server-standalone-3.7.1.jar -role hub
</code>```

register node on windows 7:

```<code>java -Dwebdriver.chrome.driver=chromedriver_2.33.exe -jar selenium-server-standalone-3.7.1.jar -role node -hub http://localhost:4444
</code>```

register node on windows 10:

```<code>java -Dwebdriver.chrome.driver=chromedriver_2.33.exe -jar selenium-server-standalone-3.7.1.jar -role node -hub http://localhost:4444
</code>```

protractor.conf.js

```<code>exports.config = {

    specs: [
        '**/*.mytest.e2e-spec.ts'
    ],
    multiCapabilities: [
        {
            browserName: 'chrome',
            platform: 'WIN10',
        }
    ],
    seleniumAddress: 'http://localhost:4444/wd/hub',
    baseUrl: 'http://localhost:4200/',
    framework: 'jasmine',
    jasmineNodeOpts: {
        print: function () {
        }
    },
    onPrepare: function () {
        require('ts-node').register({
            project: 'e2e/tsconfig.e2e.json'
        });
    }
};
</code>```

答:
As per your question and DebanjanB answer, You have two nodes and two hubs. You need to register the nodes with same hub. Please try with following configuration, it may works.

Start your hub on windows 7 Machine with following command,

java -jar selenium-server-standalone-3.7.1.jar -role hub

Start/register your first node on windows 7 with following command,

java -Dwebdriver.chrome.driver=chromedriver_2.33.exe -jar selenium-server-standalone-3.7.1.jar -role node

start/register your second node on windows 10 with following command,

java -Dwebdriver.chrome.driver=chromedriver_2.33.exe -jar selenium-server-standalone-3.7.1.jar -role node -hub http://"IP Address OF Windows 7 machine":4444/grid/register

To verify the nodes are listed on hub, just open the url http://localhost:4444/grid/console on windows 7 machine.  Then, verify your nodes are listed on the page.

You have to run your script from the windows 7 machine because your selenium address is using localhost address( seleniumAddress: 'http://localhost:4444/wd/hub'). if you want to run from windows 10 machine or any other machine. change the selenium address as 'http://"windows7ipaddress":4444/wd/hub' in config file.

I have tested it on my machine it is working fine. It will start the chrome on windows 10 machine as your multiCapabilities  platform value is WIN10.

note: replace the value of ip address value in place where ever required.

Body:
I have register two platform with chrome browser on windows 7 and windows 10 into selenium grid server.

I want to run a test at Chrome browser on Windows 10 but when i run the test, the test randomly run on Windows 7 and randomly run on Windows 10 on chrome.

Do you have an idea how to do the configuration to run the test on specific browser and platform when we have registered multiple platform?

hub:

java -jar selenium-server-standalone-3.7.1.jar -role hub

register node on windows 7:

java -Dwebdriver.chrome.driver=chromedriver_2.33.exe -jar selenium-server-standalone-3.7.1.jar -role node -hub http://localhost:4444

register node on windows 10:

java -Dwebdriver.chrome.driver=chromedriver_2.33.exe -jar selenium-server-standalone-3.7.1.jar -role node -hub http://localhost:4444

protractor.conf.js

exports.config = {

    specs: [
        '**/*.mytest.e2e-spec.ts'
    ],
    multiCapabilities: [
        {
            browserName: 'chrome',
            platform: 'WIN10',
        }
    ],
    seleniumAddress: 'http://localhost:4444/wd/hub',
    baseUrl: 'http://localhost:4200/',
    framework: 'jasmine',
    jasmineNodeOpts: {
        print: function () {
        }
    },
    onPrepare: function () {
        require('ts-node').register({
            project: 'e2e/tsconfig.e2e.json'
        });
    }
};


问:
Data type size impact on performance
I'm running intensive numerical simulations. I often use long integers, but I realized it would be safe to use integers instead. Would this improve the speed of my simulations significantly?</p>

答:
Depends. If you have lots and lots of numbers consecutively in memory, they're more likely to fit in the L2 cache, so you have fewer cache misses. L2 cache misses - depending on your platform - can be a significant performance impact, so it's definitely a good idea to make things fit in cache as much as possible (and prefetch if you can). But don't expect your code to fly all of a sudden because your types are smaller.

EDIT: One more thing - if you choose an awkward type (like a 16-bit integer on a 32-bit or 64-bit platform), you may end up with worse performance because the CPU will have to surgically extract the 16-bit value and turn it into something it can work with. But typically, ints are a good choice.

Title: Data type size impact on performance


问:
Limit bash while loop to 10 retries
How can this while loop be limited to maximum 10 retries?</p>

```<code>#!/bin/sh
while ! test -d /somemount/share/folder
do
    echo "Waiting for mount /somemount/share/folder..."
    sleep 1
done
</code>```

答:
I would comment but I do not have enough points for that. I want to contribute anyway.
So this makes it work even if the while loop is nested in another loop. before the break the c variable is being reset to zero.
credits to @anubhava who came up with the original solution.</p>

```<code>#!/bin/sh

while ! test -d /somemount/share/folder
do
    echo "Waiting for mount /somemount/share/folder..."
    ((c++)) && ((c==10)) && c=0 && break
    sleep 1
done
</code>```

Title: Limit bash while loop to 10 retries

Body:
How can this while loop be limited to maximum 10 retries?

#!/bin/sh
while ! test -d /somemount/share/folder
do
    echo "Waiting for mount /somemount/share/folder..."
    sleep 1
done

Body:
I would comment but I do not have enough points for that. I want to contribute anyway.
So this makes it work even if the while loop is nested in another loop. before the break the c variable is being reset to zero.
credits to @anubhava who came up with the original solution.

#!/bin/sh

while ! test -d /somemount/share/folder
do
    echo "Waiting for mount /somemount/share/folder..."
    ((c++)) && ((c==10)) && c=0 && break
    sleep 1
done


问:
Firefox extension missing Referer url in ajax header when making ajax calls
I am trying to make an ajax call to a server and the server needs referer url to identify my request

```<code>    $.ajax({
            url: abc + '/123/xyz/',
                cache: false,
                type: 'GET',
                crossDomain: true,
                headers: {
                    "key": "xxxxxxxxxxx"
                }
            }).done(function(result) {
                executeOnSuccess();
    });
</code>```

The expected result on the server should be that if i execute this line  request.getHeader("referer");

I should get the referer url but i get a null, but if i make the same ajax request using chrome extension it works and i get the referer url.

I have been stuck on this for a while now. The other option is to add referer url manually to the ajax header but i was expecting it to work like chrome?

Does any one has any idea about it ?

Thanks in advance.

答:
The browser will always overwrite the referrer. Meaning you can't change the referrer of an ajax call.  But you can try!

```<code>$.ajax({
    url: abc + '/123/xyz/',
    type: "GET",
    headers: {
        "Referer": "Change here reference"
    },
    success: function (data) {
        alert("Success");
    },
    error: function (data) {
        console.log(data);
    }
});
</code>```

Also, note that if you are planning to submit your extension in AMO, you should always use https in your calls to any server.

Body:
I am trying to make an ajax call to a server and the server needs referer url to identify my request

    $.ajax({
            url: abc + '/123/xyz/',
                cache: false,
                type: 'GET',
                crossDomain: true,
                headers: {
                    "key": "xxxxxxxxxxx"
                }
            }).done(function(result) {
                executeOnSuccess();
    });

The expected result on the server should be that if i execute this line  request.getHeader("referer");

I should get the referer url but i get a null, but if i make the same ajax request using chrome extension it works and i get the referer url.

I have been stuck on this for a while now. The other option is to add referer url manually to the ajax header but i was expecting it to work like chrome?

Does any one has any idea about it ?

Thanks in advance.

Body:
The browser will always overwrite the referrer. Meaning you can't change the referrer of an ajax call.  But you can try!

$.ajax({
    url: abc + '/123/xyz/',
    type: "GET",
    headers: {
        "Referer": "Change here reference"
    },
    success: function (data) {
        alert("Success");
    },
    error: function (data) {
        console.log(data);
    }
});

Also, note that if you are planning to submit your extension in AMO, you should always use https in your calls to any server.


问:
Python. Replace elements using slice
I need to implement Sieve of Eratosthenes algorithm.
I have list:

bar = [2, 3, 4, 5, 6, 7, 8, 9, 10]

I need to replace each odd element with "0".
Now I have code:

```<code>while viewIndex < maxNumber:
    bar[viewIndex] = 0
    viewIndex += 2
</code>```

But I remember about slices. And for me it will be nice to write something like this:

```<code>bar[currentIndex::2] = 0
</code>```

But I have error:

```<code>TypeError: must assign iterable to extended slice
</code>```

Maybe you know a beautiful solution to this task.

答:
You should assign the slice to an iterable of the same length as the number of odds:

```<code>bar[1::2] = [0]*(len(bar)//2)
print(bar)
# [2, 0, 4, 0, 6, 0, 8, 0, 10]
</code>```

To extend this for even indices, you need to take into consideration lists with odd-lengths (not relevant for the above case) by adding the modulo 2 value of the list length:

```<code>bar[::2] = [0]*(len(bar)//2 + len(bar)%2)
</code>```

Which is same as:

```<code>bar[::2] = [0]*sum(divmod(len(bar), 2))
</code>```

Title: Python. Replace elements using slice

Body:
I need to implement Sieve of Eratosthenes algorithm.
I have list:

bar = [2, 3, 4, 5, 6, 7, 8, 9, 10]

I need to replace each odd element with "0".
Now I have code:

while viewIndex < maxNumber:
    bar[viewIndex] = 0
    viewIndex += 2

But I remember about slices. And for me it will be nice to write something like this:

bar[currentIndex::2] = 0

But I have error:

TypeError: must assign iterable to extended slice

Maybe you know a beautiful solution to this task.

Body:
You should assign the slice to an iterable of the same length as the number of odds:

bar[1::2] = [0]*(len(bar)//2)
print(bar)
# [2, 0, 4, 0, 6, 0, 8, 0, 10]

To extend this for even indices, you need to take into consideration lists with odd-lengths (not relevant for the above case) by adding the modulo 2 value of the list length:

bar[::2] = [0]*(len(bar)//2 + len(bar)%2)

Which is same as:

bar[::2] = [0]*sum(divmod(len(bar), 2))


问:
Javascript mouseout if got id show, if not write "no id"
I've got 2 divs with two different id ;

mainid

infoid

I need that when I mouseout #mainid div innerHTML text on #infoid with first divs would show up.

Full code

function myFunction() {

    var x = document.getElementById("dom").id;

     document.getElementById("info").innerHTML = x;

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {height:100%;
margin:0;
padding:0;}

h2, h3 {
 margin:0px;
 text-align:center;
 padding-top:25px;
}

.cc:nth-child(odd) .first-line {background-color: #CCC;
color:red;}
p {text-align:center;
margin:0;
padding:5px;
color:#fff;}

.box5 {text-align:center;
}
.box5 .first-line {
 padding:0px;
 margin:0px;
}
.box5 .second-line {
 padding:0px;
 margin:0px;
}
.box5 img {
 padding-top:3px;
 padding-bottom:3px;
 padding-right:10px;
 padding-left:10px;
 margin:5px;
 border: 3px solid #0B0B3B;
 outline:3px solid #F4FA58;
 display:inline-block;

}

.imgs {width:50px;height:50px;}

@media screen and (min-width: 769px){
 .box1 {height:50%;
 width:30%;
 float:left;
 background-color:#81DAF5;}
  .box2 {height:10%;
 width:70%;
 float:right;
 background-color:#81F781;}
   .box3 {height:20%;
 width:15%;
 float:left;
 background-color:#5858FA;}
 .box4 {height:20%;
 width:55%;
 float:right;
 background-color:#F4FA58;}
 .box5 {height:20%;
 width:70%;
 float:right;
 background-color:#FAAC58;}
 .box6 {height:40%;
 width:15%;
 float:left;
 background-color:#A0522D;}
 .box7 {height:40%;
 width:35%;
 float:left;
 background-color:#FA5858;}
 .box8 {height:40%;
 width:50%;
 float:right;
 background-color:#fff;}
 .box9 {height:10%;
 width:100%;
 float:left;
 background-color:#000;}
}

@media screen and (max-width: 768px) {
 .box2:hover  {
  animation-name:scale;
  -webkit-animation-name: scale;
  -webkit-animation: scale 0.5s linear infinite;
    -webkit-animation-duration: 0.5s;
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in;
    -o-transition: all 0.5s ease-in;
    -ms-transition: all 0.5s ease-in;
    transition: all 0.5s ease-in;
}
 @-webkit-keyframes scale {
    from {

       webkit-transform:scale(1)
    }
    to {
    webkit-transform:scale(0);
 webkit-background-color:red;
    }
}

@keyframes scale {

    from {

    transform:scale(1)
    }
    to {

  transform:scale(0);
  background-color:red;
    }
}

.box5:hover  {
  animation-name:rotate;
  -webkit-animation-name: rotate;
  -webkit-animation: rotate 0.5s linear infinite;
    -webkit-animation-duration: 0.5s;
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in;
    -o-transition: all 0.5s ease-in;
    -ms-transition: all 0.5s ease-in;
    transition: all 0.5s ease-in;
}
 @-webkit-keyframes rotate{
    from {

       webkit-transform:rotatex(0deg);
    }
    to {
    webkit-transform:rotatex(360deg);

    }
}

@keyframes rotate {

    from {

    transform:rotatex(0deg);
    }
    to {

  transform:rotatex(360deg);
    }
}

.box3 h3  {
  animation-name:scaletext;
  -webkit-animation-name: scaletext;
  -webkit-animation: scaletext 0.5s linear infinite;
    -webkit-animation-duration: 0.5s;
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in;
    -o-transition: all 0.5s ease-in;
    -ms-transition: all 0.5s ease-in;
    transition: all 0.5s ease-in;
   -webkit-animation-delay: 3s;
    animation-delay: 3s;
}
 @-webkit-keyframes scaletext{
    from {
      0%   {webkit-font-size:12px;}
    25%  {webkit-font-size:8px;}
    50%  {webkit-font-size:16px;}
    100% {webkit-font-size:11px;}
    }

}

@keyframes scaletext {

    0%   {font-size:12px;}
    25%  {font-size:8px;}
    50%  {font-size:16px;}
    100% {font-size:11px;}
}

 .box1 {height:50%;
 width:50%;
 float:left;
 background-color:#81DAF5;}
 .box2 {height:10%;
 width:50%;
 float:right;
 background-color:#81F781;}
 .box3 {height:20%;
 width:50%;
 float:left;
 background-color:#5858FA;}
 .box4 {
 display:none;
 height:0px;
 width:0px;}
 .box5 {height:20%;
 width:50%;
 float:right;
 background-color:#FAAC58;}
 .box6 {display:none;}
 .box7 {height:40%;
 width:20%;
 float:left;
 background-color:#FA5858;}
 .box8 {height:40%;
 width:80%;
 float:right;
 background-color:#fff;}
 .box9 {height:10%;
 width:100%;
 float:left;
 background-color:#000;}
}</code>```

Pirma eilutė

Antra eilutė

Pirma eilutė

Pirma eilutė

Antra eilutė

Pirma eilutė

Antra eilutė

Pirma eilutė

Antra eilutė

Pirma eilutė

Antra eilutė

Pirma eilutė

Antra eilutė

Pirma eilutė

Antra eilutė

Pirma eilutė
```

The problem is that I can't make something that would write if there is no id.

Maby someone can help me making if else statement in this javascript ?

If got div {code}
Else {write : no id}

答:
function mouseOutFunc(element) {
  document.getElementById('info').innerHTML = element.id || "No Id";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="info"></div>
<div id="div1" onmouseout="mouseOutFunc(this)">ONE</div>
<div id="div2" onmouseout="mouseOutFunc(this)">TWO</div>
<div onmouseout="mouseOutFunc(this)">NO ID</div></code>```

Try this

Body:
I've got 2 divs with two different id ;

mainid

infoid

I need that when I mouseout #mainid div innerHTML text on #infoid with first divs would show up.

Full code

function myFunction() {

    var x = document.getElementById("dom").id;

     document.getElementById("info").innerHTML = x;

}

html, body {height:100%;
margin:0;
padding:0;}

h2, h3 {
 margin:0px;
 text-align:center;
 padding-top:25px;
}

.cc:nth-child(odd) .first-line {background-color: #CCC;
color:red;}
p {text-align:center;
margin:0;
padding:5px;
color:#fff;}

.box5 {text-align:center;
}
.box5 .first-line {
 padding:0px;
 margin:0px;
}
.box5 .second-line {
 padding:0px;
 margin:0px;
}
.box5 img {
 padding-top:3px;
 padding-bottom:3px;
 padding-right:10px;
 padding-left:10px;
 margin:5px;
 border: 3px solid #0B0B3B;
 outline:3px solid #F4FA58;
 display:inline-block;

}

.imgs {width:50px;height:50px;}

@media screen and (min-width: 769px){
 .box1 {height:50%;
 width:30%;
 float:left;
 background-color:#81DAF5;}
  .box2 {height:10%;
 width:70%;
 float:right;
 background-color:#81F781;}
   .box3 {height:20%;
 width:15%;
 float:left;
 background-color:#5858FA;}
 .box4 {height:20%;
 width:55%;
 float:right;
 background-color:#F4FA58;}
 .box5 {height:20%;
 width:70%;
 float:right;
 background-color:#FAAC58;}
 .box6 {height:40%;
 width:15%;
 float:left;
 background-color:#A0522D;}
 .box7 {height:40%;
 width:35%;
 float:left;
 background-color:#FA5858;}
 .box8 {height:40%;
 width:50%;
 float:right;
 background-color:#fff;}
 .box9 {height:10%;
 width:100%;
 float:left;
 background-color:#000;}
}

@media screen and (max-width: 768px) {
 .box2:hover  {
  animation-name:scale;
  -webkit-animation-name: scale;
  -webkit-animation: scale 0.5s linear infinite;
    -webkit-animation-duration: 0.5s;
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in;
    -o-transition: all 0.5s ease-in;
    -ms-transition: all 0.5s ease-in;
    transition: all 0.5s ease-in;
}
 @-webkit-keyframes scale {
    from {

       webkit-transform:scale(1)
    }
    to {
    webkit-transform:scale(0);
 webkit-background-color:red;
    }
}

@keyframes scale {

    from {

    transform:scale(1)
    }
    to {

  transform:scale(0);
  background-color:red;
    }
}

.box5:hover  {
  animation-name:rotate;
  -webkit-animation-name: rotate;
  -webkit-animation: rotate 0.5s linear infinite;
    -webkit-animation-duration: 0.5s;
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in;
    -o-transition: all 0.5s ease-in;
    -ms-transition: all 0.5s ease-in;
    transition: all 0.5s ease-in;
}
 @-webkit-keyframes rotate{
    from {

       webkit-transform:rotatex(0deg);
    }
    to {
    webkit-transform:rotatex(360deg);

    }
}

@keyframes rotate {

    from {

    transform:rotatex(0deg);
    }
    to {

  transform:rotatex(360deg);
    }
}

.box3 h3  {
  animation-name:scaletext;
  -webkit-animation-name: scaletext;
  -webkit-animation: scaletext 0.5s linear infinite;
    -webkit-animation-duration: 0.5s;
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in;
    -o-transition: all 0.5s ease-in;
    -ms-transition: all 0.5s ease-in;
    transition: all 0.5s ease-in;
   -webkit-animation-delay: 3s;
    animation-delay: 3s;
}
 @-webkit-keyframes scaletext{
    from {
      0%   {webkit-font-size:12px;}
    25%  {webkit-font-size:8px;}
    50%  {webkit-font-size:16px;}
    100% {webkit-font-size:11px;}
    }

}

@keyframes scaletext {

    0%   {font-size:12px;}
    25%  {font-size:8px;}
    50%  {font-size:16px;}
    100% {font-size:11px;}
}

 .box1 {height:50%;
 width:50%;
 float:left;
 background-color:#81DAF5;}
 .box2 {height:10%;
 width:50%;
 float:right;
 background-color:#81F781;}
 .box3 {height:20%;
 width:50%;
 float:left;
 background-color:#5858FA;}
 .box4 {
 display:none;
 height:0px;
 width:0px;}
 .box5 {height:20%;
 width:50%;
 float:right;
 background-color:#FAAC58;}
 .box6 {display:none;}
 .box7 {height:40%;
 width:20%;
 float:left;
 background-color:#FA5858;}
 .box8 {height:40%;
 width:80%;
 float:right;
 background-color:#fff;}
 .box9 {height:10%;
 width:100%;
 float:left;
 background-color:#000;}
}

Pirma eilutė

Antra eilutė

Pirma eilutė

Pirma eilutė

Antra eilutė

Pirma eilutė

Antra eilutė

Pirma eilutė

Antra eilutė

Pirma eilutė

Antra eilutė

Pirma eilutė

Antra eilutė

Pirma eilutė

Antra eilutė

Pirma eilutė

The problem is that I can't make something that would write if there is no id.

Maby someone can help me making if else statement in this javascript ?

If got div {code}
Else {write : no id}

Body:
function mouseOutFunc(element) {
  document.getElementById('info').innerHTML = element.id || "No Id";
}

<div id="info"></div>
<div id="div1" onmouseout="mouseOutFunc(this)">ONE</div>
<div id="div2" onmouseout="mouseOutFunc(this)">TWO</div>
<div onmouseout="mouseOutFunc(this)">NO ID</div>

Try this


问:
Difference between character sets in Python and re2c regular expressions
Character sets in regular expressions are specified using []. Character sets match any one of the enclosed characters. For example, [abc] will match one of 'a', 'b', or 'c'.

I realize there are potentially differences between character sets in Python and re2c regular expressions. I know what is the same in both:

Both accept ranges, for example [a-z] matches all lowercase letters

Both accept inverse sets using [^...] notation

Both accept common alphanumeric and some other characters (spaces, etc.)

But I'm concerned about these possibly being different:

Characters that need to be escaped inside of the character set

Where to place a literal '-' or '^' inside the character set if I want to match that character and not specify an inverse set or a range

Can you explain the difference between Python and re2c character sets?

答:
I would escape anything that causes confusion -

/[][]/ matches ']' or '['

/[[]]/ matches '[]'

/[]]]/ matches ']]'

/[[[]/ matches '['

/[]/ is an umatched '[' error


问:
sort whole array on the basic of a specific index in value
i am fetching some data from multiple tables on the basis of particular id, instead of using joins i used nested queries, now the data needs to be to sorted as i am using nested queries it is difficult to use orderby now below is the array i am generating!

```<code>Array
(
    [0] => Array
        (
            [id] => 54
            [name] => Array
                (
                    [0] => Array
                        (
                            [name] => Jumbo Green Raisins Chinese
                        )

                )

            [path] => Array
                (
                    [0] => Array
                        (
                            [path] => Jumbo_Green_Raisins_Chinese2.jpg
                        )

                )

            [sort] => Array
                (
                    [0] => Array
                        (
                            [sort] => 2
                        )

                )

        )

    [1] => Array
        (
            [id] => 55
            [name] => Array
                (
                    [0] => Array
                        (
                            [name] => Regular Green Raisins Chinese
                        )

                )

            [path] => Array
                (
                    [0] => Array
                        (
                            [path] => Regular_Green_Raisins_Chinese.jpg
                        )

                )

            [sort] => Array
                (
                    [0] => Array
                        (
                            [sort] => 4
                        )

                )

        )

    [2] => Array
        (
            [id] => 56
            [name] => Array
                (
                    [0] => Array
                        (
                            [name] => Green Sunderkhani Raisins
                        )

                )

            [path] => Array
                (
                    [0] => Array
                        (
                            [path] => Green_Sunderkhani_Raisins.jpg
                        )

                )

            [sort] => Array
                (
                    [0] => Array
                        (
                            [sort] => 3
                        )

                )

        )

    [3] => Array
        (
            [id] => 57
            [name] => Array
                (
                    [0] => Array
                        (
                            [name] => Jumbo Black Raisins
                        )

                )

            [path] => Array
                (
                    [0] => Array
                        (
                            [path] => Jumbo_Black_Raisins.jpg
                        )

                )

            [sort] => Array
                (
                    [0] => Array
                        (
                            [sort] => 1
                        )

                )

        )
)
</code>```

basically i am using a loop to display the information retrieved in the above data, what i want to do is inside the loop display the sorted data the index sort is what i need to see while sorting, i could do it with db too but i have to mess up code in a lot of places it would be alot better if i do i this way! any help?

答:
Basic php usort</p>

```<code>function sorted_nested($a, $b) {
    if($a['sort'][0]['sort'] == $b['sort'][0]['sort']) {
        return 0;
    }

    if($a['sort'][0]['sort'] < $b['sort'][0]['sort']) {
        return -1;
    } else {
        return 1;
    }
}

usort($array, 'sorted_nested');
</code>```

Body:
i am fetching some data from multiple tables on the basis of particular id, instead of using joins i used nested queries, now the data needs to be to sorted as i am using nested queries it is difficult to use orderby now below is the array i am generating!

Array
(
    [0] => Array
        (
            [id] => 54
            [name] => Array
                (
                    [0] => Array
                        (
                            [name] => Jumbo Green Raisins Chinese
                        )

                )

            [path] => Array
                (
                    [0] => Array
                        (
                            [path] => Jumbo_Green_Raisins_Chinese2.jpg
                        )

                )

            [sort] => Array
                (
                    [0] => Array
                        (
                            [sort] => 2
                        )

                )

        )

    [1] => Array
        (
            [id] => 55
            [name] => Array
                (
                    [0] => Array
                        (
                            [name] => Regular Green Raisins Chinese
                        )

                )

            [path] => Array
                (
                    [0] => Array
                        (
                            [path] => Regular_Green_Raisins_Chinese.jpg
                        )

                )

            [sort] => Array
                (
                    [0] => Array
                        (
                            [sort] => 4
                        )

                )

        )

    [2] => Array
        (
            [id] => 56
            [name] => Array
                (
                    [0] => Array
                        (
                            [name] => Green Sunderkhani Raisins
                        )

                )

            [path] => Array
                (
                    [0] => Array
                        (
                            [path] => Green_Sunderkhani_Raisins.jpg
                        )

                )

            [sort] => Array
                (
                    [0] => Array
                        (
                            [sort] => 3
                        )

                )

        )

    [3] => Array
        (
            [id] => 57
            [name] => Array
                (
                    [0] => Array
                        (
                            [name] => Jumbo Black Raisins
                        )

                )

            [path] => Array
                (
                    [0] => Array
                        (
                            [path] => Jumbo_Black_Raisins.jpg
                        )

                )

            [sort] => Array
                (
                    [0] => Array
                        (
                            [sort] => 1
                        )

                )

        )
)

basically i am using a loop to display the information retrieved in the above data, what i want to do is inside the loop display the sorted data the index sort is what i need to see while sorting, i could do it with db too but i have to mess up code in a lot of places it would be alot better if i do i this way! any help?

Body:
Basic php usort

function sorted_nested($a, $b) {
    if($a['sort'][0]['sort'] == $b['sort'][0]['sort']) {
        return 0;
    }

    if($a['sort'][0]['sort'] < $b['sort'][0]['sort']) {
        return -1;
    } else {
        return 1;
    }
}

usort($array, 'sorted_nested');


Title: Python. Replace elements using slice

Body:
Use simple for loop

bar = [2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in  range(len(bar)):
   if bar[i] % 2 != 0:
       bar[i] = 0
print(bar)

Output

[2, 0, 4, 0, 6, 0, 8, 0, 10]


问:
How could I create a custom dozer initializer
Is it possible to create a custom dozer initializer so it accepts a parameter with the constructor and not just an empty constructor?

For example, next converter failed because of dozer can't initialize it, and throws java.lang.InstantiationException

```<code>public class MyCustomDozerConverter extends DozerConverter<MyObject, String> {

    private static String myParameter;

    // How could dozer accepts this constructor?
    public MyCustomDozerConverter(String myParameter) {
        super(MyObject.class, String.class);
        this.myParameter = myParameter;
    }

    @Override
    public String convertTo(MyObject source, String destination) {
        // Using value of myParamter which passed in constructor
        // business logic
        return destination;
    }

    @Override
    public MyObject convertFrom(String source, MyObject destination) {
        // business logic
        return null;
    }
}
</code>```

Also if it possible, so how can i send this parameter to constructor so it will be dynamic not static?

Note: i am using dozer inside spring-boot project

答:
In your configuration class you need to add this section:

```<code>@Bean
public DozerBeanMapper mapper() throws IOException {
    List<String> mappingFiles = new ArrayList<String>();
    List<CustomConverter> customConverters = new ArrayList<CustomConverter>();
    customConverters.add(new MyCustomDozerConverter(""));

    DozerBeanMapper mapper = new DozerBeanMapper();
    mapper.setMappingFiles(mappingFiles);
    mapper.setCustomConverters(customConverters);

    return mapper;
}
</code>```

In this way dozer will use instance of MyCustomConverter you set in mapper.setCustomConverters(customConverters) method.

Body:
Is it possible to create a custom dozer initializer so it accepts a parameter with the constructor and not just an empty constructor?

For example, next converter failed because of dozer can't initialize it, and throws java.lang.InstantiationException

public class MyCustomDozerConverter extends DozerConverter<MyObject, String> {

    private static String myParameter;

    // How could dozer accepts this constructor?
    public MyCustomDozerConverter(String myParameter) {
        super(MyObject.class, String.class);
        this.myParameter = myParameter;
    }

    @Override
    public String convertTo(MyObject source, String destination) {
        // Using value of myParamter which passed in constructor
        // business logic
        return destination;
    }

    @Override
    public MyObject convertFrom(String source, MyObject destination) {
        // business logic
        return null;
    }
}

Also if it possible, so how can i send this parameter to constructor so it will be dynamic not static?

Note: i am using dozer inside spring-boot project

Body:
In your configuration class you need to add this section:

@Bean
public DozerBeanMapper mapper() throws IOException {
    List<String> mappingFiles = new ArrayList<String>();
    List<CustomConverter> customConverters = new ArrayList<CustomConverter>();
    customConverters.add(new MyCustomDozerConverter(""));

    DozerBeanMapper mapper = new DozerBeanMapper();
    mapper.setMappingFiles(mappingFiles);
    mapper.setCustomConverters(customConverters);

    return mapper;
}

In this way dozer will use instance of MyCustomConverter you set in mapper.setCustomConverters(customConverters) method.


答:
You can use map to set elements on odd index to zero,

```<code>bar = [2, 3, 4, 5, 6, 7, 8, 9, 10]
print map(lambda i: 0 if bar.index(i)%2!=0 else i, bar)

[2, 0, 4, 0, 6, 0, 8, 0, 10]
</code>```

or if you want to set odd element value to zero, you can do this,

```<code>map(lambda i: 0 if i%2!=0 else i, bar)
</code>```

Title: Python. Replace elements using slice

Body:
You can use map to set elements on odd index to zero,

bar = [2, 3, 4, 5, 6, 7, 8, 9, 10]
print map(lambda i: 0 if bar.index(i)%2!=0 else i, bar)

[2, 0, 4, 0, 6, 0, 8, 0, 10]

or if you want to set odd element value to zero, you can do this,

map(lambda i: 0 if i%2!=0 else i, bar)


问:
TCP - How to play a java game between two players on localhost server
I have made a game named Two Dice Pig in java. The game has a simple GUI interface showing two dice faces as well as both players scores and names. The game starts with the simple dialog message asking for both players' name and the game starts. Both players interact with only one GUI interface and play as their turn come.  The game is completely coded. Now, what I want is to make a server (For now I want to try it on my local server) and both players should get their own GUI. And when a player A is playing, player B should not be able to do anything with the interface. I hope it clears. It's my networking project, but I don't have any idea how to do that. Any help would be greatly appreciated.

Note: I want to apply the same idea as this man applied. Just watch only for 15 seconds. Thanks!,

答:
Making a multiplayer game is not a trivial task. Be prepared to rewrite most of you code as it seems you didn't think of writing multiplayer code from the beginning. Here are two different strategies:

Method 1: Dumb client

Most of game logic should be done in server. Clients just display what server told them. They also send commands to server to change game state.

Example:

Player X clicks on roll the dice button.

Client X sends to server roll command

Server checks if it's player X turn or not and returns an error if not.

Server rolls the dice. Assume its 3.

Server changes the turn to Y.

Server sends a message to all clients saying the dice is 3 and it's Y's turn.

Basically server waits for a command from players and do them in sequence. Update the world and broadcast the new world to all clients. Clients just wait to get updates from the server and display them to user.

Method 2: Lockstep simulation

Most of game logic is done in client and server just mediate between them to convey commands. Only commands are transferred and state is simulated in each client. You should be pretty careful to not get synchronization bugs (command may deliver late or other things could happen). You should make sure that applying a command in each client in the same state. For example random seeds should be same so random functions will return same value in both clients.

Example:

Player X clicks on roll the dice.

Client X will roll the dice for itself and let say it results in 4

Client X will send roll command to server.

Server broadcast roll command to client Y.

Client Y receive roll command.

Client Y will roll the dice and should result in 4 (Your code should provide same result in all clients in consistent manner)


问:
Scrambling/Unscrambling a string in Classic ASP
I'm wanting to send a string that has some meaning through the URL.

I know that I could probably do other things to send a string, but this is the only way in this situation.

I'm wanting send it and an unreadable format and be able to get the original string back later. I'm trying to avoid the words encrypt/decrypt because I've done research and It seems a bit more envolved than what I'm wanting in classic ASP( unless I'm missing something ). So I'm not really wanting to IMPLEMENT a encrypt/decrypt algorithm. I'm hoping there is something built into ASP that will allow me to do this.

I'm looking for both the way to scramble the message and a way to get it back.

Any suggestions?

答:
If you're looking to scramble the string (as opposed to encrypting it) then write your own rot13 encoder/decoder.

The same algorithm can easily be applied to translate all ASCII characters.

You'd probably be better off storing the same data in the session though.


问:
CommonOpenFileDialog cause Windows Form to shrink
I've been working on a Windows Forms application, and have recently added a simple settings page that allows the user to select a folder for where the output goes. The OpenFileDialog is ugly and not nice to use, so I've added in the WindowsAPICodePack to get access to the CommonOpenFileDialog - all good there.

When I open the CommonOpenFileDialog, the Windows form application shrinks to a smaller size, as shown in the image attached.

On the left is the program normally, on the right is with the dialog open:

I've tried checking the size of the Form before and after, that's not changing, so I'm hitting a bit of a brick wall. Any information would be useful, I can provide more details if needed.

Code to open the dialog is:

```<code>CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.DefaultDirectory = selectedFolderTextBox.Text;
dialog.IsFolderPicker = true;

if (dialog.ShowDialog() != CommonFileDialogResult.Ok) return;

selectedFolderTextBox.Text = dialog.FileName;
</code>```

答:
Enable dpi-aware by adding app.manifest file, and uncomment this blocks.

```<code><application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings>
    <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
    </windowsSettings>
</application>
</code>```

This works for me on my Surface Pro 4(dpi scale 200%).

ContentLicense: CC BY-SA 4.0

Body:
I've been working on a Windows Forms application, and have recently added a simple settings page that allows the user to select a folder for where the output goes. The OpenFileDialog is ugly and not nice to use, so I've added in the WindowsAPICodePack to get access to the CommonOpenFileDialog - all good there.

When I open the CommonOpenFileDialog, the Windows form application shrinks to a smaller size, as shown in the image attached.

On the left is the program normally, on the right is with the dialog open:

I've tried checking the size of the Form before and after, that's not changing, so I'm hitting a bit of a brick wall. Any information would be useful, I can provide more details if needed.

Code to open the dialog is:

CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.DefaultDirectory = selectedFolderTextBox.Text;
dialog.IsFolderPicker = true;

if (dialog.ShowDialog() != CommonFileDialogResult.Ok) return;

selectedFolderTextBox.Text = dialog.FileName;

Body:
Enable dpi-aware by adding app.manifest file, and uncomment this blocks.

<application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings>
    <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
    </windowsSettings>
</application>

This works for me on my Surface Pro 4(dpi scale 200%).


问:
Making the Android emulator run faster
The Android emulator is a bit sluggish. For some devices, like the Motorola Droid and the Nexus One, the app runs faster in the actual device than the emulator. This is a problem when testing games and visual effects.

How do you make the emulator run as fast as possible? I've been toying with its parameters but haven't found a configuration that shows a noticeable improvement yet.

答: choose a low resolution emulator (eg: Nexus S) if you don't have a good graphic card (like me)</p>

Title: Making the Android emulator run faster


问:
Can Laravel using join table to get data?
Just some random thought, can laravel using join table rather than using eloquent relationship. Because most of answers that i read in here suggest to using relationship like belongstoMany, belongsto and other eloquent relationship. If can, it should be nice if u guys giving me some sample code about how to do that. Sorry for the silly question. Thank you</p>

答:
A basic example using something I created a while ago using joins which were a forum thread table and a forum replies table. See below:

```<code>$forum = Forum::where('forumType', '=', $topic->forumType)
    ->leftJoin('forum_replies','forum_topics.forumid','=','forum_replies.topic_id')
    ->groupBy('forum_topics.forumid')
    ->orderBy('forum_replies.updated_at', 'DESC')
    ->get();
</code>```

The above examples joins the forumid from forum_topics table to the forum_replies table's topic_id

Not a very tidy way of doing it though, you should definitely approach this by using relationships instead.

The code above was converted some time ago to relationships instead of using joins.

Body:
A basic example using something I created a while ago using joins which were a forum thread table and a forum replies table. See below:

$forum = Forum::where('forumType', '=', $topic->forumType)
    ->leftJoin('forum_replies','forum_topics.forumid','=','forum_replies.topic_id')
    ->groupBy('forum_topics.forumid')
    ->orderBy('forum_replies.updated_at', 'DESC')
    ->get();

The above examples joins the forumid from forum_topics table to the forum_replies table's topic_id

Not a very tidy way of doing it though, you should definitely approach this by using relationships instead.

The code above was converted some time ago to relationships instead of using joins.


问:
How can I line up radio buttons horizontally rather than vertically?
I have been looking at the Cookbook - 7.3.3 Automagic Form Elements trying to find a way for radio buttons to line up horizontally rather than vertically.  I have been looking at the 'div' => 'class_name' $options also the $options[‘between’], $options[‘separator’] and $options[‘after’] but have been unsuccessful.  Is there a "cake" way of doing this?

```<code><?=$form->input('Product Type', array(
     'type' => 'radio',
     'id' => $tire['ProductType']['id'],
     'name' => $tire['ProductType']['id'],
     'options' => array(2=>'Tire Manufacturer', 7=>'Rim Manufacturer '),
));?>
</code>```

The of equivalent this

```<code><label>Product Type</label>
<div style="padding-top:5px;">
    <input type="radio" name="data[Manufacturer][product_type_id]" value="<?=$tire['ProductType']['id']?>"> Tire Manufacturer
    <input type="radio" name="data[Manufacturer][product_type_id]" value="<?=$wheel['ProductType']['id']?>"> Rim Manufacturer
</div>
</code>```

答:
This works for me:
Inside your view file (viewfile.ctp):

```<code><div>
<?php
echo $this->Form->create('changeRegion');
$options=array('US'=>'U.S.','CA'=>'Canada', 'FN'=>'International');
$attributes=array('legend'=>false, 'label'=>false, 'value'=>'US', 'class'=>'locRad');
echo $form->radio('subLocation',$options,$attributes);
echo $this->Form->end();
?>
<div class="clear"></div>
</div>
</code>```

Make sure 'label'=>false and 'legend'=>false are set in your attributes.

In your stylesheet:

```<code>input[type=radio] {
float:left;
margin:0px;
width:20px;
}

form#changeRegionStdForm input[type=radio].locRad {
margin:3px 0px 0px 3px;
float:none;
}
</code>```

I fought this forever because of the default CakePHP style rule for input[type=radio] (inside the app/webroot/css/cake.generic.css file) was always taking precedence. I generated another rule to specifically pick out the radio group in question by referencing the form along with the radio input rule appended with the class name (form#changeRegionStdForm input[type=radio].locRad).  I initially did this with the form# rule listed before the input[type=.  Only when I moved it after the input[type= did the radio buttons line up horizontally.

I hope this makes sense and actually helps someone else.

Body:
I have been looking at the Cookbook - 7.3.3 Automagic Form Elements trying to find a way for radio buttons to line up horizontally rather than vertically.  I have been looking at the 'div' => 'class_name' $options also the $options[‘between’], $options[‘separator’] and $options[‘after’] but have been unsuccessful.  Is there a "cake" way of doing this?

<?=$form->input('Product Type', array(
     'type' => 'radio',
     'id' => $tire['ProductType']['id'],
     'name' => $tire['ProductType']['id'],
     'options' => array(2=>'Tire Manufacturer', 7=>'Rim Manufacturer '),
));?>

The of equivalent this

Product Type

    <input type="radio" name="data[Manufacturer][product_type_id]" value="<?=$tire['ProductType']['id']?>"> Tire Manufacturer
    <input type="radio" name="data[Manufacturer][product_type_id]" value="<?=$wheel['ProductType']['id']?>"> Rim Manufacturer

Body:
This works for me:
Inside your view file (viewfile.ctp):

<div>
<?php
echo $this->Form->create('changeRegion');
$options=array('US'=>'U.S.','CA'=>'Canada', 'FN'=>'International');
$attributes=array('legend'=>false, 'label'=>false, 'value'=>'US', 'class'=>'locRad');
echo $form->radio('subLocation',$options,$attributes);
echo $this->Form->end();
?>
<div class="clear"></div>
</div>

Make sure 'label'=>false and 'legend'=>false are set in your attributes.

In your stylesheet:

input[type=radio] {
float:left;
margin:0px;
width:20px;
}

form#changeRegionStdForm input[type=radio].locRad {
margin:3px 0px 0px 3px;
float:none;
}

I fought this forever because of the default CakePHP style rule for input[type=radio] (inside the app/webroot/css/cake.generic.css file) was always taking precedence. I generated another rule to specifically pick out the radio group in question by referencing the form along with the radio input rule appended with the class name (form#changeRegionStdForm input[type=radio].locRad).  I initially did this with the form# rule listed before the input[type=.  Only when I moved it after the input[type= did the radio buttons line up horizontally.

I hope this makes sense and actually helps someone else.


问:
The reason 'subprocess.run' is better than 'os.system' for beginner
I read many answers on this topic.

It seems that they try to explain it with much more difficult illustrations or just saying it's deprecated consulting official documentation.

os.system is handy for beginner.

Could the reason be explained in an easy example o a metaphor?

答:
One example of many is that subprocess.run() can capture the output, while os.system() only captures the return code.

subprocess.run() is simply way more flexible. It can do everything that os.system() can but also way more. If you KNOW that you never will use any of the benefits in subprocess.run(), then by all means, use os.system(), but most people would say that it's a bit of a waste of time to learn two different tools for the same thing.

os.system() is pretty much a copy of system() in C.


问:
Use JSoup to get all textual links
I'm using JSoup to grab content from web pages.

I want to get all the links on a page that have some contained text (it doesn't matter what the text is) just needs to be non-empty/image etc.

Example of links I want:

```<code><a href="somepage.html">Link to Some Page</a>
</code>```

Since it contains the text "Link to Some Page"

Links I don't want:

```<code><a href="somepage.html"><img src="someimage.jpg"/></a>
<a href="somepage.html"></a>
</code>```

My code looks like this. How can I modify it to only get the first type of link?

```<code>Document document = // I get my document object
Elements linksOnPage = document.select("a[href]")
for (Element page : linksOnPage) {
    String link = page.attr("abs:href");
    // I do stuff with the link
}
</code>```

答:
You could do something like this.
It does it's job though it's probably not the fanciest solution out there.

Note: the function text() gets you a clean text so if there are any HTML code fragements inside it, it won't return them.

```<code>Document doc = // get the doc
Elements linksOnPage = document.select("a");

for (Element pageElem : linksOnPage){
    String link = "";
    if(pageElem.text().trim().equals(""))
       continue;
    // do smth with it
}
</code>```

Title: Use JSoup to get all textual links

Body:
I'm using JSoup to grab content from web pages.

I want to get all the links on a page that have some contained text (it doesn't matter what the text is) just needs to be non-empty/image etc.

Example of links I want:

Link to Some Page

Since it contains the text "Link to Some Page"

Links I don't want:

My code looks like this. How can I modify it to only get the first type of link?

Document document = // I get my document object
Elements linksOnPage = document.select("a[href]")
for (Element page : linksOnPage) {
    String link = page.attr("abs:href");
    // I do stuff with the link
}

Body:
You could do something like this.
It does it's job though it's probably not the fanciest solution out there.

Note: the function text() gets you a clean text so if there are any HTML code fragements inside it, it won't return them.

Document doc = // get the doc
Elements linksOnPage = document.select("a");

for (Element pageElem : linksOnPage){
    String link = "";
    if(pageElem.text().trim().equals(""))
       continue;
    // do smth with it
}


问:
Jest: fake setInterval not working as expected
I'm trying to create a Timer component, that allows children to start a timer, and then provides them with how much time is left in 1 second intervals.

I have the following test:

 Full Code

/* Test */
jest.useFakeTimers()
it.only('should update the reamining time every second', () => {
  const time = 1/12
  const wrapper = shallow(<Timer time={time} />)

  wrapper.find('.start').simulate('click')

  jest.runAllTimers()

  expect(setInterval.mock.calls.length).toBe(4)
})```
</div>
</div>
</p>

<p> Full Code
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/*    Code     */

updateTimeLeft() {
  const now: number = +new Date()
  const timeLeft = this.state.endTime - now

  if (timeLeft < 0) {
    clearInterval(this.state.timeInterval)
  }

  this.setState({ timeLeft })
}

intializeTimer(minutes: number) {
  const startTime: number = new Date().getTime()
  const endTime: number = new Date(startTime + minutes * 60 * 1000).getTime()

  this.setState({
    startTime,
    endTime
  })

  const timeInterval: NodeJS.Timer = global.setInterval(
    () => this.updateTimeLeft(),
    1000
  )
  this.setState({ timeInterval })
}</code>```

The code works. The problem is, in the test, setInteval.mock.calls.length = 1, not matter what.

Is there anything I misunderstood about Jest fake timers?

Thank you ❤

答:
There is nothing with fake timers.
You have called setInterval inside initializeTimer only once, that's why setInterval.mock.calls.length shows you 1. But it's callback function will be called as much as you need.
Think of it as for loop, you have only one for loop declaration (our setInterval in this case), and as much body calls as you need (our callback function here)

Hope, it helps.

Body:
I'm trying to create a Timer component, that allows children to start a timer, and then provides them with how much time is left in 1 second intervals.

I have the following test:

 Full Code

/* Test */
jest.useFakeTimers()
it.only('should update the reamining time every second', () => {
  const time = 1/12
  const wrapper = shallow(<Timer time={time} />)

  wrapper.find('.start').simulate('click')

  jest.runAllTimers()

  expect(setInterval.mock.calls.length).toBe(4)
})

 Full Code

/*    Code     */

updateTimeLeft() {
  const now: number = +new Date()
  const timeLeft = this.state.endTime - now

  if (timeLeft < 0) {
    clearInterval(this.state.timeInterval)
  }

  this.setState({ timeLeft })
}

intializeTimer(minutes: number) {
  const startTime: number = new Date().getTime()
  const endTime: number = new Date(startTime + minutes * 60 * 1000).getTime()

  this.setState({
    startTime,
    endTime
  })

  const timeInterval: NodeJS.Timer = global.setInterval(
    () => this.updateTimeLeft(),
    1000
  )
  this.setState({ timeInterval })
}

The code works. The problem is, in the test, setInteval.mock.calls.length = 1, not matter what.

Is there anything I misunderstood about Jest fake timers?

Thank you ❤


问:
Test Google CDN for a certain location
We have video (mp4) files on the Google Storage with the CDN enabled. The videos are pseudo-streamed (HTTP byte-range) well from all but one of our users. All videos have same format, were encoded by ffmpeg with the same parameters. All videos are streamed well from different locations (especially tested from USA and Europe).

Just one user from South Korea reports he cannot stream some videos, but can stream the others well. He has tried 3 different devices (Windows, iPhone, Android tabled) with same result. He has tried to switch to mobile network (LTE) and still had the problem. We do not know if other users in South Korea have same problem or not, we have not many users there.

Is it possible the PoP or GCC nodes in the South Korea serve little different data than elsewhere? Is it possible to test HTTP requests to the same PoP, GCC nodes as the Korean users from Europe?

Update: After a few more test with the user we have found that the video downloaded (by curl) is correct. He has problem with some fresh videos, too, so the problem is not in caching. The problem arises, when the video has index at the end, so the player has to seek to the end of file first (HTTP byte-range). (But not always, he can play some videos with the index at the end).

答:
Test your service from different locations

Data is not served differently depending on location. To make an HTTP request from a remote location, I would suggest spinning up a VM instance with a container, with a ready VPN server (1) in a region close to the remote location you are looking for (2). In this case, it's either Taiwan or Singapore (3) closest to test your service from.

Google CDN and large files

As you can see, cached responses must have a body of under 10 MB, otherwise they won't be cached (5). Still, the documentation offers a tip for large files caching, towards optimising outgoing traffic with Cloud CDN Interconnect (4).
It would seem that Cloud CDN is not a proper service for video streaming. Can you tell me how do you handle in your back-end the video streaming through HTTP? Do you partition somehow the files before sending data in the responses?
You can also check your logs, to see if data is being sent from the cache to the users, or from the back-end. (6)

Google CDN and partial content responses

According to (5), the only stored responses are the ones having the status code 200/203/300, etc., along with other conditions to be respected. Usually, according to RFC 7233 (7), successful partial content responses are coded with the 206 HTTP status code. This means that Cloud CDN does not implicitly support caching partial content. Still, please bear in mind that Cloud CDN does respect the RFC 7234 specifications (8), in the sense that byte range requests are optional when using caching ("A cache MAY complete a stored incomplete response by making a subsequent range request"). My opinion is that only full content responses are being cached, while requests for "chunks" are proxied to the origin server and the responses are not getting inserted into the cache.

Title: Test Google CDN for a certain location


问:
Redirect non-www domain to www, preserving staging
I have two domains, www.example.com and staging.example.com (both hosted on the same box).

I'd like to always redirect example.com to www.example.com, but when I use solutions from other SO threads it breaks the staging domain.

Can someone point me in the right direction?

Thanks!

UPDATE: Does this cover https as well? If not, what do I have to do to get that working?

答:
```<code>RewriteEngine On

# not HTTPS
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

# HTTPS
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteCond %{HTTPS} =on
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
</code>```

There should not be any conflict with staging.example.com

Body:
RewriteEngine On

# not HTTPS
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

# HTTPS
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteCond %{HTTPS} =on
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

There should not be any conflict with staging.example.com


问:
why my scrapy response body returns a favicon.ico
I am searching for a long time on net. But no use.  I have tried some webs but there is one can't pass, it returns favicon.ico

For example, I try and crawl the following URL from the scrapy shell:

```<code>$ scrapy shell "https://baijia.baidu.com"
2017-12-04 20:37:51 [scrapy.utils.log] INFO: Scrapy 1.4.0 started (bot: tutorial)
2017-12-04 20:37:51 [scrapy.utils.log] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'tutorial.spiders', 'DUPEFILTER_CLASS': 'scrapy.dupefilters.BaseDupeFilter', 'SPIDER_MODULES': ['tutorial.spiders'], 'HTTPCACHE_ENABLED': True, 'BOT_NAME': 'tutorial', 'LOGSTATS_INTERVAL': 0, 'FEED_EXPORT_ENCODING': 'utf-8'}
2017-12-04 20:37:51 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.memusage.MemoryUsage',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.corestats.CoreStats']
2017-12-04 20:37:51 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats',
 'scrapy.downloadermiddlewares.httpcache.HttpCacheMiddleware']
2017-12-04 20:37:51 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2017-12-04 20:37:51 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2017-12-04 20:37:51 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2017-12-04 20:37:51 [scrapy.core.engine] INFO: Spider opened
2017-12-04 20:37:51 [scrapy.extensions.httpcache] DEBUG: Using filesystem cache storage in /home/suocheng/My_Scrapy/tutorial/.scrapy/httpcache
2017-12-04 20:37:51 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://baijia.baidu.com> (referer: None) ['cached']
[s] Available Scrapy objects:
[s]   scrapy     scrapy module (contains scrapy.Request, scrapy.Selector, etc)
[s]   crawler    <scrapy.crawler.Crawler object at 0x2ebbc10>
[s]   item       {}
[s]   request    <GET https://baijia.baidu.com>
[s]   response   <200 https://baijia.baidu.com>
[s]   settings   <scrapy.settings.Settings object at 0x2ebbb90>
[s]   spider     <DefaultSpider 'default' at 0x33634d0>
[s] Useful shortcuts:
[s]   fetch(url[, redirect=True]) Fetch URL and update local objects (by default, redirects are followed)
[s]   fetch(req)                  Fetch a scrapy.Request and update local objects
[s]   shelp()           Shell help (print this help)
[s]   view(response)    View response in a browser
>>> response.body
'favicon.ico'
>>>
</code>```

it returns favicon.ico.
and if i set the Xpath like this:

```<code>>>> response.xpath('/html/head/title')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/lib64/python2.7/site-packages/scrapy/http/response/__init__.py", line 105, in xpath
    raise NotSupported("Response content isn't text")
NotSupported: Response content isn't text
</code>```

so how to solve this problem?
Thanks in advance.

答:
It seems this sever sends file with string favicon.ico if you have incorrect USER-AGENT

Try with extra option which looks like correct USER-AGENT and you get HTML file.

```<code>scrapy shell -s USER_AGENT="Mozilla/5.0" https://baijia.baidu.com
</code>```

And then response.xpath will work.

```<code>In [1]: response.xpath('/html/head/title/text()').extract_first()
Out[1]: '首页-百家号'
</code>```

You can get better USER-AGENT from your browser using page httpbin.org

Body:
I am searching for a long time on net. But no use.  I have tried some webs but there is one can't pass, it returns favicon.ico

For example, I try and crawl the following URL from the scrapy shell:

$ scrapy shell "https://baijia.baidu.com"
2017-12-04 20:37:51 [scrapy.utils.log] INFO: Scrapy 1.4.0 started (bot: tutorial)
2017-12-04 20:37:51 [scrapy.utils.log] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'tutorial.spiders', 'DUPEFILTER_CLASS': 'scrapy.dupefilters.BaseDupeFilter', 'SPIDER_MODULES': ['tutorial.spiders'], 'HTTPCACHE_ENABLED': True, 'BOT_NAME': 'tutorial', 'LOGSTATS_INTERVAL': 0, 'FEED_EXPORT_ENCODING': 'utf-8'}
2017-12-04 20:37:51 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.memusage.MemoryUsage',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.corestats.CoreStats']
2017-12-04 20:37:51 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats',
 'scrapy.downloadermiddlewares.httpcache.HttpCacheMiddleware']
2017-12-04 20:37:51 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2017-12-04 20:37:51 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2017-12-04 20:37:51 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2017-12-04 20:37:51 [scrapy.core.engine] INFO: Spider opened
2017-12-04 20:37:51 [scrapy.extensions.httpcache] DEBUG: Using filesystem cache storage in /home/suocheng/My_Scrapy/tutorial/.scrapy/httpcache
2017-12-04 20:37:51 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://baijia.baidu.com> (referer: None) ['cached']
[s] Available Scrapy objects:
[s]   scrapy     scrapy module (contains scrapy.Request, scrapy.Selector, etc)
[s]   crawler    <scrapy.crawler.Crawler object at 0x2ebbc10>
[s]   item       {}
[s]   request    <GET https://baijia.baidu.com>
[s]   response   <200 https://baijia.baidu.com>
[s]   settings   <scrapy.settings.Settings object at 0x2ebbb90>
[s]   spider     <DefaultSpider 'default' at 0x33634d0>
[s] Useful shortcuts:
[s]   fetch(url[, redirect=True]) Fetch URL and update local objects (by default, redirects are followed)
[s]   fetch(req)                  Fetch a scrapy.Request and update local objects
[s]   shelp()           Shell help (print this help)
[s]   view(response)    View response in a browser
>>> response.body
'favicon.ico'
>>>

it returns favicon.ico.
and if i set the Xpath like this:

>>> response.xpath('/html/head/title')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/lib64/python2.7/site-packages/scrapy/http/response/__init__.py", line 105, in xpath
    raise NotSupported("Response content isn't text")
NotSupported: Response content isn't text

so how to solve this problem?
Thanks in advance.

Body:
It seems this sever sends file with string favicon.ico if you have incorrect USER-AGENT

Try with extra option which looks like correct USER-AGENT and you get HTML file.

scrapy shell -s USER_AGENT="Mozilla/5.0" https://baijia.baidu.com

And then response.xpath will work.

In [1]: response.xpath('/html/head/title/text()').extract_first()
Out[1]: '首页-百家号'

You can get better USER-AGENT from your browser using page httpbin.org


问:
OpenCv cv2.arcLength(cnt,True) and cv2.contourArea(cnt) error
When I am trying run following code:

```<code>img = cv2.imread('index4.jpg',0)
ret,thresh = cv2.threshold(img,127,255,0)
ret,thresh = cv2.threshold(img,127,255,0)
contours,hierarchy, _ = cv2.findContours(thresh, 1, 2)
cnt = contours[0]
perimeter = cv2.arcLength(cnt,True)
</code>```

I am getting following error:

```<code>---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
<ipython-input-65-f8db5433a171> in <module>()
----> 1 perimeter = cv2.arcLength(cnt,True)

error: /io/opencv/modules/imgproc/src/shapedescr.cpp:285: error: (-215) count >= 0 && (depth == CV_32F || depth == CV_32S) in function arcLength
</code>```

and Then:

```<code>area = cv2.contourArea(cnt)
</code>```

and Error:

```<code>---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
<ipython-input-63-c660947e12c8> in <module>()
----> 1 area = cv2.contourArea(cnt)

error: /io/opencv/modules/imgproc/src/shapedescr.cpp:320: error: (-215) npoints >= 0 && (depth == CV_32F || depth == CV_32S) in function contourArea
</code>```

N.B:

python3, opencv version: '3.3.0'

How can I solve these issues ?

答:
The contours are the second element in the returned tuple from findContours(), not the first. Previously in older versions of OpenCV, findContours() only returned two results---but now it returns three--and the additional value became the first element of the returned tuple.

From the docs for cv2.findContours():

```<code>cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]]) → image, contours, hierarchy
</code>```

Thus

```<code>image, contours, hierarchy = cv2.findContours(thresh, 1, 2)
</code>```

will fix you up. Or if you only want the contours, you don't need to use throwaway variables like _, just index the tuple that is returned:

```<code>contours = cv2.findContours(thresh, 1, 2)[1]
</code>```

Body:
When I am trying run following code:

img = cv2.imread('index4.jpg',0)
ret,thresh = cv2.threshold(img,127,255,0)
ret,thresh = cv2.threshold(img,127,255,0)
contours,hierarchy, _ = cv2.findContours(thresh, 1, 2)
cnt = contours[0]
perimeter = cv2.arcLength(cnt,True)

I am getting following error:

---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
<ipython-input-65-f8db5433a171> in <module>()
----> 1 perimeter = cv2.arcLength(cnt,True)

error: /io/opencv/modules/imgproc/src/shapedescr.cpp:285: error: (-215) count >= 0 && (depth == CV_32F || depth == CV_32S) in function arcLength

and Then:

area = cv2.contourArea(cnt)

and Error:

---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
<ipython-input-63-c660947e12c8> in <module>()
----> 1 area = cv2.contourArea(cnt)

error: /io/opencv/modules/imgproc/src/shapedescr.cpp:320: error: (-215) npoints >= 0 && (depth == CV_32F || depth == CV_32S) in function contourArea

N.B:

python3, opencv version: '3.3.0'

How can I solve these issues ?

Body:
The contours are the second element in the returned tuple from findContours(), not the first. Previously in older versions of OpenCV, findContours() only returned two results---but now it returns three--and the additional value became the first element of the returned tuple.

From the docs for cv2.findContours():

cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]]) → image, contours, hierarchy

Thus

image, contours, hierarchy = cv2.findContours(thresh, 1, 2)

will fix you up. Or if you only want the contours, you don't need to use throwaway variables like _, just index the tuple that is returned:

contours = cv2.findContours(thresh, 1, 2)[1]


问:
identity server - get updated claims with refresh token
I put some claims in the access token that comes from DB while login (e.g. entity_id and role). Now at some stage the entity_id claim gets changed and I need to get a new access token with the updated claims. I am doing this using the refresh token to get a new access token but it comes with the same old claims inside; may be because the class implementing IResourceOwnerPasswordValidator is not being called in case of refresh token. So how can I get the updated claims in access token? Because user has to logout and re-login otherwise to get the entity_id and role claims updated.

I know the other option is to make use of the /userinfo endpoint for claims but my question here is in this case how the [Authorize(Roles = "Manager")] attribute of ASP.NET Core will work and get to know about roles if they don't exist in the access token?

答:
Or put differently - data that changes often is not a good candidate for claims in tokens.

That said - you can make identityserver run through the profile service pipeline again when getting a refreshed token - see here:

https://identityserver4.readthedocs.io/en/release/reference/client.html?highlight=UpdateAccessTokenClaimsOnRefresh


问:
How to set up a mature building process for my C program that uses a third-party library (APR - Apache Portability Runtime)
I have written a C program that consists of a number of files, and uses APR (http://apr.apache.org) - it includes its headers and I would prefer dynamic linking of its libraries.

My problem is that currently I hard-code both the paths to APR headers as set up at my development site and the paths of the static APR library I have found.

This is what my Makefile looks like (i renamed some bits):

```<code>my_program: file1.c file2.c file3.c file4.c file5.c file6.c file7.c
    @rm -f $@
    $(CC) -std=c99 -pedantic -D_POSIX_C_SOURCE -I/usr/local/include/apache -L/usr/local/lib -lapr-1 $(CFLAGS) $^ -o $@
</code>```

Obviously the name of the APR static library file is libapr-1.a, but I also have libapr-1.so and libapr-1.so.0 and even libapr-1.la which I am not even sure what is. So, in effect, I suspect that right now I am linking to APR statically. Aside from my goal of a respectable build system, I would like to link to APR dynamically.

Is there a common practice for me to set up an automated build that will work not only for me now, but also is flexible enough for others to build my program? I smell the proximity of the autotools, but I have absolutely zero experience with them, and would like for now to settle for the next best thing. What options do I have?

答:
By default linker will pickup shared library (.so) and if it not found static library (.a).
So when you pass to linker -lapr-1 it will exectly what you want.

To ensure that your binrary indeed will use shared library run:

```<code>ldd your_binary
</code>```

You should see apr library in output list.

Body:
I have written a C program that consists of a number of files, and uses APR (http://apr.apache.org) - it includes its headers and I would prefer dynamic linking of its libraries.

My problem is that currently I hard-code both the paths to APR headers as set up at my development site and the paths of the static APR library I have found.

This is what my Makefile looks like (i renamed some bits):

my_program: file1.c file2.c file3.c file4.c file5.c file6.c file7.c
    @rm -f $@
    $(CC) -std=c99 -pedantic -D_POSIX_C_SOURCE -I/usr/local/include/apache -L/usr/local/lib -lapr-1 $(CFLAGS) $^ -o $@

Obviously the name of the APR static library file is libapr-1.a, but I also have libapr-1.so and libapr-1.so.0 and even libapr-1.la which I am not even sure what is. So, in effect, I suspect that right now I am linking to APR statically. Aside from my goal of a respectable build system, I would like to link to APR dynamically.

Is there a common practice for me to set up an automated build that will work not only for me now, but also is flexible enough for others to build my program? I smell the proximity of the autotools, but I have absolutely zero experience with them, and would like for now to settle for the next best thing. What options do I have?

Body:
By default linker will pickup shared library (.so) and if it not found static library (.a).
So when you pass to linker -lapr-1 it will exectly what you want.

To ensure that your binrary indeed will use shared library run:

ldd your_binary

You should see apr library in output list.


问:
Remove part of string but getting the deleted part as result
So, quick question (searched a lot in Google, but only found the answer which produces same response as below):

code:

```<code>var teste = '10/12/2017';
console.log(teste); //returns 10/12/2017
var teste_cut = teste.substr(6,2);
console.log(teste_cut); //returns only 20
</code>```

What I want is 10/12/17. I can't change how the string is created, so I need to change it after getting said string. Does a method for doing this exist, or should I work around with other functions? I'm feeling stupid right now, since it seens to be a fairly obvious answer, but I guess we all get our stupid moments :P

答:
You can simply rebuild a new string without the parts you don't want using multiple substr :

var test = '10/12/2017';
console.log(test);
var test_cut = test.substr(0,6)+test.substr(8,test.length);
console.log(test_cut)```

Body:
So, quick question (searched a lot in Google, but only found the answer which produces same response as below):

code:

var teste = '10/12/2017';
console.log(teste); //returns 10/12/2017
var teste_cut = teste.substr(6,2);
console.log(teste_cut); //returns only 20

What I want is 10/12/17. I can't change how the string is created, so I need to change it after getting said string. Does a method for doing this exist, or should I work around with other functions? I'm feeling stupid right now, since it seens to be a fairly obvious answer, but I guess we all get our stupid moments :P


问:
Save a lot of file excel as rda using R
I have 1000 file excel with the name "1.xlsx" "2.xlsx" ... "1000.xlsx". Then how can i write a loop to save them as "1.rda" "2.rda" ... "1000.rda" without using this code 1000 times

j1 <- read.xlsx("1.xlsx",1)

save(j1, file = "j1.rda")

Thanks a lot

答:
Does this work?

```<code>library(tidyverse)
xlsx_to_rda <- function(inputname, outputname){
  save(read.xlsx(inputname,1), file = outputname)
}
walk2(paste0(1:1000, ".xlsx"),
      paste0(1:1000, ".rda"),
      xlsx_to_rda)
</code>```

By the way rds would be a better file format, because it stores just one r object.

Title: Save a lot of file excel as rda using R

Body:
Does this work?

library(tidyverse)
xlsx_to_rda <- function(inputname, outputname){
  save(read.xlsx(inputname,1), file = outputname)
}
walk2(paste0(1:1000, ".xlsx"),
      paste0(1:1000, ".rda"),
      xlsx_to_rda)

By the way rds would be a better file format, because it stores just one r object.


问:
Highlight words in R list of strings based on term document matrix
The following is a dataframe of campaign data

```<code> Subject                  Response Rate(%)     Campaign Type    Channel
  Buy Stunning Phone A        81.00                   A         e-mail
 Special Emi OFFER             81.00                   B            e-mail
 Buy Stunning Phone at EMI     73.00                   C            SMS
The game changer is here.      85.00                   A            SMS
 Buy Stunnig Phone A           80.00                   A            SMS
 Special Emi OFFER             88.00                   B         e-mail
 Buy Stunning Phone at EMI     48.00                   C        e-mail
The game changer is here.      48.00                   A         e-mail
Buy Stunning Phone             89.00                   A         e-mail
 Special Emi OFFER             89.00                   B         SMS
 Buy Stunning Phone at EMI     69.00                   C         SMS
</code>```

I have created a term document matrix as follows

```<code>    Word    Frequency
     big    10
   upgrade  10
    worth   10
     latest 9
     much   9
    phone   8
 exciting   8
    back    7
  colours   7
    case    6
  stylish   6
   clear    6
experience  5
     time   5
</code>```

I have subsetted the databy dplyr based channel type in order of  decreasing response rates.
I wish to highlight / list the words of the term document matrix against each subject. If the Word is present in the subject, listed as a separate list near the subject. I am unable to find a way to do this.

答:
do you mean something like this</p>

```<code>library(dplyr)

df <- read.table(header = TRUE, sep = "," ,text = "Subject,Response Rate(%),Campaign Type,Channel
Buy Stunning Phone A,81.00,A,e-mail
Special Emi OFFER,81.00,B,e-mail
Buy Stunning Phone at EMI,73.00,C,SMS
The game changer is here.,85.00,A,SMS
Buy Stunnig Phone A,80.00,A,SMS
Special Emi OFFER,88.00,B,e-mail
Buy Stunning Phone at EMI,48.00,C,e-mail
The game changer is here.,48.00,A,e-mail
Buy Stunning Phone,89.00,A,e-mail
Special Emi OFFER,89.00,B,SMS
Buy Stunning Phone at EMI,69.00,C,SMS",)

df2 <- read.table(header = TRUE, sep = "," ,text = "Word,Frequency
big,10
upgrade,10
worth,10
latest,9
much,9
phone,8
exciting,8
back,7
colours,7
case,6
stylish,6
clear,6
experience,5
time,5",)

m = sapply(df2$Word %>% as.character() %>% trimws(),regexpr,text = df$Subject %>% as.character(),ignore.case = TRUE)

df$keyWord <- sapply(1:nrow(m),function(idx){
t = m[idx,] > 0 %>% unlist()
paste0(names(t)[t],collapse = ",")
})
df
</code>```

Body:
The following is a dataframe of campaign data

 Subject                  Response Rate(%)     Campaign Type    Channel
  Buy Stunning Phone A        81.00                   A         e-mail
 Special Emi OFFER             81.00                   B            e-mail
 Buy Stunning Phone at EMI     73.00                   C            SMS
The game changer is here.      85.00                   A            SMS
 Buy Stunnig Phone A           80.00                   A            SMS
 Special Emi OFFER             88.00                   B         e-mail
 Buy Stunning Phone at EMI     48.00                   C        e-mail
The game changer is here.      48.00                   A         e-mail
Buy Stunning Phone             89.00                   A         e-mail
 Special Emi OFFER             89.00                   B         SMS
 Buy Stunning Phone at EMI     69.00                   C         SMS

I have created a term document matrix as follows

    Word    Frequency
     big    10
   upgrade  10
    worth   10
     latest 9
     much   9
    phone   8
 exciting   8
    back    7
  colours   7
    case    6
  stylish   6
   clear    6
experience  5
     time   5

I have subsetted the databy dplyr based channel type in order of  decreasing response rates.
I wish to highlight / list the words of the term document matrix against each subject. If the Word is present in the subject, listed as a separate list near the subject. I am unable to find a way to do this.

Body:
do you mean something like this

library(dplyr)

df <- read.table(header = TRUE, sep = "," ,text = "Subject,Response Rate(%),Campaign Type,Channel
Buy Stunning Phone A,81.00,A,e-mail
Special Emi OFFER,81.00,B,e-mail
Buy Stunning Phone at EMI,73.00,C,SMS
The game changer is here.,85.00,A,SMS
Buy Stunnig Phone A,80.00,A,SMS
Special Emi OFFER,88.00,B,e-mail
Buy Stunning Phone at EMI,48.00,C,e-mail
The game changer is here.,48.00,A,e-mail
Buy Stunning Phone,89.00,A,e-mail
Special Emi OFFER,89.00,B,SMS
Buy Stunning Phone at EMI,69.00,C,SMS",)

df2 <- read.table(header = TRUE, sep = "," ,text = "Word,Frequency
big,10
upgrade,10
worth,10
latest,9
much,9
phone,8
exciting,8
back,7
colours,7
case,6
stylish,6
clear,6
experience,5
time,5",)

m = sapply(df2$Word %>% as.character() %>% trimws(),regexpr,text = df$Subject %>% as.character(),ignore.case = TRUE)

df$keyWord <- sapply(1:nrow(m),function(idx){
t = m[idx,] > 0 %>% unlist()
paste0(names(t)[t],collapse = ",")
})
df


问:
Regarding non-equal allocators in STL
I am reading Item 10 in Effective STL by Scott Meyers on allocators in C++.

Standard says that an implementation of the STL is permitted to assume
  that all allocator objects of the same type are equivalent and always
  compare equal.

That's all well and good, but the more you think about it. the more
  you'll realize just how draconian a restriction it is that STL
  implementations may assume that allocators of the same type are
  equivalent. It means that portable allocator objects — allocators that
  will function correctly under different STL implementations — may not
  have state. Let's be explicit about this: it means that portable
  allocators may not have any nonstatic data members, at least not any
  that affect their behavior. None. Nada. That means, for example, you
  can't have one SpecialAllocator that allocates from one heap and
  a different SpecialAllocator that allocates from a different
  heap. Such allocators wouldn't be equivalent, and STL implementations
  exist where attempts to use both allocators could lead to corrupt
  runtime data structures.

In fairness to the Standardization Committee, I should point out that
  it included the following statement immediately after the text that
  permits STL implementers to assume that allocators of the same type
  are equivalent:

Implementors are encouraged to supply libraries that ... support
  non-equal instances. In such implementations. ... the semantics of
  containers and algorithms when allocator instances compare non-equal
  are implementation-defined.

This is a lovely sentiment, but as a user of the STL who is
  considering the development of a custom allocator with state, it
  offers you next to nothing.  You can take advantage of this statement
  only if (1) you know that the STL implementations you are using
  support inequivalent allocators, (2) you are willing to delve into
  their documentation to determine whether the implementation-defined
  behavior of "non-equal" allocators is acceptable to you, and

(3) you're not concerned about porting your code to STL
  implementations that may take advantage of the latitude expressly
  extended to them by the Standard. In short, this paragraph — paragraph
  5 of section 20.1.5. for those who insist on knowing — is the
  Standard's "1 have a dream" speech for allocators. Until that dream
  becomes common reality, programmers concerned about portability will
  limit themselves to custom allocators with no state.

My question on above paragraph are

What does author mean by inequivalent or  non-equal allocators?

What does last paragraph in above text i.e, point 3 mean in simple terms?

答:
That information is out of date.  C++11 and later versions support stateful allocators.

The quotes you have posted from Effective C++ are only of concern if you are writing a C++ library which requires custom allocators, does not require C++11, and which supports building against unknown/unspecified standard libraries.  To a first approximation, nobody is doing this anymore.  The people who were doing it before often had their own "enhanced" standard library implementations to support stateful allocators, such as EASTL or BDESTL.

Title: Regarding non-equal allocators in STL