问:
JavaScript working in Firefox but not other browsers
I am fiddling with this piece of code to try to understand how parts of it work.  Everything seems to be working as expected in Firefox, however the Login button does not work in any other browser.  When I inspect it in Chrome it is saying:

Uncaught SyntaxError: Unexpected token u in JSON at position 0

at JSON.parse ()

at CheckUsername (alt.html:24)

at HTMLInputElement.onclick (alt.html:72)

And before that it was complaining about the CookieVars variable being undefined (I think, I cannot get it to replicate that error again).

I have tried Googling the issue but some of the explanations are way over my head or seem to not be relevant to my situation.

Can someone tell me how come this works in Firefox and not any other browser?  What the issue is and how it can be fixed?

Your assistance is appreciated.

```<code><!DOCTYPE html>
<html>
<head>
  <title></title>
  <meta charset="UTF-8">
</head>
<script>
function NewMember() {
    var CookieVars = {};

    CookieVars.username = document.getElementById("UsersName").value;
    CookieVars.password = document.getElementById("PassWord").value;

    var jsonString = JSON.stringify(CookieVars);

    document.cookie = "MembersDetails=" + jsonString;
    alert("Thank you, you are now registered.");
    ClearTextBoxes();
}

function CheckUsername() {
    var nameValueArray = document.cookie.split("=");
    var CookieVars = JSON.parse(nameValueArray[1]);
    var UsersNameVar = document.getElementById("UsersName").value;

    if (CookieVars.username == UsersNameVar) {
       CheckPassword();
            } else {
                alert("Username not recognised, please register.");
    }
}

function CheckPassword() {
   var nameValueArray = document.cookie.split("=");
   var CookieVars = JSON.parse(nameValueArray[1]);
   var PassWordVar = document.getElementById("PassWord").value;
   if (CookieVars.password == PassWordVar) {
      document.getElementById("message").innerHTML = "You are now logged in, welcome.";
   } else {
      alert("Incorrect Password.");
   }
}

function ClearTextBoxes() {
    document.getElementById("UsersName").value = "";
    document.getElementById("PassWord").value = "";
}

</script>
<body>
  <table border="3">
    <tr>
      <td>
        Username:
      </td>
      <td>
        <input type="text" id="UsersName">
      </td>
    </tr>
    <tr>
      <td>
        Password:
      </td>
      <td>
        <input type="text" id="PassWord">
      </td>
    </tr>
    <tr>
      <td colspan="2">
        <input type="button" value="Register" onclick="NewMember()">
        <input type="button" value="Login" onclick="CheckUsername()">
        <input type="button" value="Clear Boxes" onclick="ClearTextBoxes()">
      </td>
    </tr>
  </table>
    <p id="message"></p>
<img src="" alt="">
</body>
</html>
</code>```

答:
validate your JSON:

```<code>function isJSON(str) {
    try {
        return (JSON.parse(str) && !!str);
    } catch (e) {
        return false;
    }
}

function CheckUsername() {
  var nameValueArray = document.cookie.split("=");
  var CookieVars = (nameValueArray && isJSON(nameValueArray[1])) ? JSON.parse(nameValueArray[1]) : false;
  var UsersNameVar = document.getElementById("UsersName").value;

  if (CookieVars && CookieVars.username == UsersNameVar) {
   CheckPassword();
        } else {
            alert("Username not recognised, please register.");
  }
}

function CheckPassword() {
  var nameValueArray = document.cookie.split("=");
  var CookieVars = (nameValueArray && isJSON(nameValueArray[1])) ? JSON.parse(nameValueArray[1]) : false;
  var PassWordVar = document.getElementById("PassWord").value;
  if (CookieVars && CookieVars.password == PassWordVar) {
     document.getElementById("message").innerHTML = "You are now logged in,
   welcome.";
 } else {
  alert("Incorrect Password.");
 }
}
</code>```

this will prevent that error. But maybe there is still an error in your code which causes the wrong data to be written into nameValueArray. For example because of Chrome's Cookie behaviour.

greetings

Body:
I am fiddling with this piece of code to try to understand how parts of it work.  Everything seems to be working as expected in Firefox, however the Login button does not work in any other browser.  When I inspect it in Chrome it is saying:

Uncaught SyntaxError: Unexpected token u in JSON at position 0

at JSON.parse ()

at CheckUsername (alt.html:24)

at HTMLInputElement.onclick (alt.html:72)

And before that it was complaining about the CookieVars variable being undefined (I think, I cannot get it to replicate that error again).

I have tried Googling the issue but some of the explanations are way over my head or seem to not be relevant to my situation.

Can someone tell me how come this works in Firefox and not any other browser?  What the issue is and how it can be fixed?

Your assistance is appreciated.

<!DOCTYPE html>

  <title></title>
  <meta charset="UTF-8">

        Username:

        <input type="text" id="UsersName">

        Password:

        <input type="text" id="PassWord">

        <input type="button" value="Register" onclick="NewMember()">
        <input type="button" value="Login" onclick="CheckUsername()">
        <input type="button" value="Clear Boxes" onclick="ClearTextBoxes()">

Body:
validate your JSON:

function isJSON(str) {
    try {
        return (JSON.parse(str) && !!str);
    } catch (e) {
        return false;
    }
}

function CheckUsername() {
  var nameValueArray = document.cookie.split("=");
  var CookieVars = (nameValueArray && isJSON(nameValueArray[1])) ? JSON.parse(nameValueArray[1]) : false;
  var UsersNameVar = document.getElementById("UsersName").value;

  if (CookieVars && CookieVars.username == UsersNameVar) {
   CheckPassword();
        } else {
            alert("Username not recognised, please register.");
  }
}

function CheckPassword() {
  var nameValueArray = document.cookie.split("=");
  var CookieVars = (nameValueArray && isJSON(nameValueArray[1])) ? JSON.parse(nameValueArray[1]) : false;
  var PassWordVar = document.getElementById("PassWord").value;
  if (CookieVars && CookieVars.password == PassWordVar) {
     document.getElementById("message").innerHTML = "You are now logged in,
   welcome.";
 } else {
  alert("Incorrect Password.");
 }
}

this will prevent that error. But maybe there is still an error in your code which causes the wrong data to be written into nameValueArray. For example because of Chrome's Cookie behaviour.

greetings


来源: stackexchange

问:
Virtualhost Apache and Tomcat
I have Tomcat and Apache web server. by MOD_JK I configure Apache to send request for http://127.0.0.1/cas to Tomcat.

http://127.0.0.1/cas works correctly and Tomcat response to it.

now I want this https://127.0.0.1/cas to work, (SSL).

I search it and found that I need Virtualhost on Apache that send requests to Tomcat, my question is how can I create a SSL Virtualhost?

and should I remove all configuration that I create before this for http://127.0.0.1/cas?

答:
There's a lot of online examples for httpd SSL virtual host configuration.  Just specify something similar to the following, and put your mod_jk JKMount references inside of it.</p>

```<code>NameVirtualHost 192.168.100.10:443

<VirtualHost 192.168.100.100:443>
  ServerName  domain.com:443
  UseCanonicalName Off

  CustomLog    /var/log/httpd/domain.log combined
  ErrorLog     /var/log/httpd/domain-error.log

  SSLEngine on
  SSLVerifyClient none
  SSLCertificateFile /etc/httpd/conf/ssl.crt/domain.com.crt
  SSLCertificateKeyFile /etc/httpd/conf/ssl.key/domain.com.key

  SSLProxyEngine on

  SetEnvIf User-Agent ".*MSIE.*" \
   nokeepalive ssl-unclean-shutdown \
   downgrade-1.0 force-response-1.0

</VirtualHost>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Virtualhost Apache and Tomcat

Body:
There's a lot of online examples for httpd SSL virtual host configuration.  Just specify something similar to the following, and put your mod_jk JKMount references inside of it.

NameVirtualHost 192.168.100.10:443

<VirtualHost 192.168.100.100:443>
  ServerName  domain.com:443
  UseCanonicalName Off

  CustomLog    /var/log/httpd/domain.log combined
  ErrorLog     /var/log/httpd/domain-error.log

  SSLEngine on
  SSLVerifyClient none
  SSLCertificateFile /etc/httpd/conf/ssl.crt/domain.com.crt
  SSLCertificateKeyFile /etc/httpd/conf/ssl.key/domain.com.key

  SSLProxyEngine on

  SetEnvIf User-Agent ".*MSIE.*" \
   nokeepalive ssl-unclean-shutdown \
   downgrade-1.0 force-response-1.0

</VirtualHost>


问:
Dropdown Menu is not overlapping Slick Gallery
I have jQuery Slick Gallery and inside it I have a Dropdown Menu. A button shows the currently selected entry and the menu entries are an unordered list which appear when the button is clicked.

The unordered list is hidden at the bottom edge but should appear above the dots. You can see the problem also on the image below:

An example what I try to do you can find here: http://jsfiddle.net/45cst6nq/

HTML

```<code><section class="slider">
  <div>
    <ul class="list">
      <li>Please select</li>
      <li>Point 1</li>
      <li>Point 2</li>
      <li>Point 3</li>
      <li>Point 4</li>
      <li>Point 5</li>
      <li>Point 6</li>
      <li>Point 7</li>
      <li>Point 8</li>
      <li>Point 9</li>
      <li>Point 10</li>
    </ul>
  </div>
  <div>slide2</div>
  <div>slide3</div>
  <div>slide4</div>
  <div>slide5</div>
  <div>slide6</div>
</section>
</code>```

CSS

```<code>$c1: #3a8999;
$c2: #e84a69;

.slider {
    width: auto;
    margin: 30px 50px 50px;
}

.slick-slide {
    background: $c1;
    color: white;
    padding: 40px 0;
    font-size: 30px;
    font-family: "Arial", "Helvetica";
    text-align: center;
}

.slick-prev:before,
.slick-next:before {
    color: black;
}

.slick-dots {
    bottom: -30px;
}

.slick-slide:nth-child(odd) {
     background: $c2;
}

.list {
  position: absolute;
  top: 0;
}
</code>```

JS

```<code>$(".slider").slick({
    autoplay: false,
    dots: true,
    responsive: [{
        breakpoint: 500,
        settings: {
            dots: false,
            arrows: false,
            infinite: false,
            slidesToShow: 2,
            slidesToScroll: 2
        }
    }]
});
</code>```

This is a simplyfied example to demonstrate the issue. The components I am showing on my customor project are a little bit more complex.

I already tried to fix this with changing z-index and overflows. It looks like it's working when I set overflow-x to visible but than the cloned slides also get visible. Using overflow-y: visible; doesn't work.
Why does only overflow-x: visible shows the list correctly overlapping, but overflow-y: visible; does not? For me this doesn't make sense.

Is there a possibility to solve the issue? I like the slick gallery in general and don't want to write my own for this case.

答:
your question is not very clear as to what you want to achieve, but if you are trying to fit in the list element into the slider i will suggest you add this code to you css.

```<code>.slider div .list{
  position: relative;
}
</code>```

This allows the list to show in the slide. This doesn't affect other slide.

ContentLicense: CC BY-SA 3.0

Body:
I have jQuery Slick Gallery and inside it I have a Dropdown Menu. A button shows the currently selected entry and the menu entries are an unordered list which appear when the button is clicked.

The unordered list is hidden at the bottom edge but should appear above the dots. You can see the problem also on the image below:

An example what I try to do you can find here: http://jsfiddle.net/45cst6nq/

HTML

Please select

Point 1

Point 2

Point 3

Point 4

Point 5

Point 6

Point 7

Point 8

Point 9

Point 10

slide2

slide3

slide4

slide5

slide6

CSS

$c1: #3a8999;
$c2: #e84a69;

.slider {
    width: auto;
    margin: 30px 50px 50px;
}

.slick-slide {
    background: $c1;
    color: white;
    padding: 40px 0;
    font-size: 30px;
    font-family: "Arial", "Helvetica";
    text-align: center;
}

.slick-prev:before,
.slick-next:before {
    color: black;
}

.slick-dots {
    bottom: -30px;
}

.slick-slide:nth-child(odd) {
     background: $c2;
}

.list {
  position: absolute;
  top: 0;
}

JS

$(".slider").slick({
    autoplay: false,
    dots: true,
    responsive: [{
        breakpoint: 500,
        settings: {
            dots: false,
            arrows: false,
            infinite: false,
            slidesToShow: 2,
            slidesToScroll: 2
        }
    }]
});

This is a simplyfied example to demonstrate the issue. The components I am showing on my customor project are a little bit more complex.

I already tried to fix this with changing z-index and overflows. It looks like it's working when I set overflow-x to visible but than the cloned slides also get visible. Using overflow-y: visible; doesn't work.
Why does only overflow-x: visible shows the list correctly overlapping, but overflow-y: visible; does not? For me this doesn't make sense.

Is there a possibility to solve the issue? I like the slick gallery in general and don't want to write my own for this case.

Body:
your question is not very clear as to what you want to achieve, but if you are trying to fit in the list element into the slider i will suggest you add this code to you css.

.slider div .list{
  position: relative;
}

This allows the list to show in the slide. This doesn't affect other slide.


问:
Deaccumulate values in sas
I have a SAS dataset that looks like the following:

```<code>  Year  Qtr Variable
2009    1   10
2009    2   15
2009    3   20
2009    4   25
2010    1   5
2010    2   7
2010    3   9
2010    4   12
2011    1   14
2011    2   17
2011    3   21
2011    4   26
</code>```

The variable gets accumulated over quarters. I want to replace that variable with the actual increase during the quarter i.e., I want the table to look like:

```<code>Year    Qtr Variable
2009    1   10
2009    2   5
2009    3   5
2009    4   5
2010    1   5
2010    2   2
2010    3   2
2010    4   3
2011    1   14
2011    2   3
2011    3   4
2011    4   5
</code>```

If it is the first quarter leave the value unchanged, otherwise subtract the previous value.
Is there any command to do this in SAS?

Also, not sure if it helps, but this is what I am trying to do:

```<code>data ppe;
set ppeqrt;
by gvkey;
where (sppey>=0 or sppey=.) and sppey not in (1,2,3,7,.c,.i,.a,.s);
year=year(datadate);
qtr=qtr(datadate);
keep ppentq sppey year qtr;

**** Here I am missing the differences of sppey by year and quarter whithin each gvkey (I did not include this variable above not to burden this) ******

proc means data=ppe noprint;
var ppentq sppey;
class year qtr;
types year*qtr;
output out=ppesums mean= sum=/autoname;
</code>```

答:
Just a note about the DIF function:
As shown, using the IFN function, it works as intended. But only because the IFN function always calculates both output values before choosing one.
In other words, this works:

```<code>variable = ifn(first.year,variable,dif(variable));
</code>```

but this does not:

```<code>if not first.year then variable=dif(variable);
</code>```

because the DIF function should be called every time to work as intended here, as the DIF and LAG functions work by storing value(s) from previous calls in an internal stack.

Title: Deaccumulate values in sas

Body:
I have a SAS dataset that looks like the following:

  Year  Qtr Variable
2009    1   10
2009    2   15
2009    3   20
2009    4   25
2010    1   5
2010    2   7
2010    3   9
2010    4   12
2011    1   14
2011    2   17
2011    3   21
2011    4   26

The variable gets accumulated over quarters. I want to replace that variable with the actual increase during the quarter i.e., I want the table to look like:

Year    Qtr Variable
2009    1   10
2009    2   5
2009    3   5
2009    4   5
2010    1   5
2010    2   2
2010    3   2
2010    4   3
2011    1   14
2011    2   3
2011    3   4
2011    4   5

If it is the first quarter leave the value unchanged, otherwise subtract the previous value.
Is there any command to do this in SAS?

Also, not sure if it helps, but this is what I am trying to do:

data ppe;
set ppeqrt;
by gvkey;
where (sppey>=0 or sppey=.) and sppey not in (1,2,3,7,.c,.i,.a,.s);
year=year(datadate);
qtr=qtr(datadate);
keep ppentq sppey year qtr;

**** Here I am missing the differences of sppey by year and quarter whithin each gvkey (I did not include this variable above not to burden this) ******

proc means data=ppe noprint;
var ppentq sppey;
class year qtr;
types year*qtr;
output out=ppesums mean= sum=/autoname;

Body:
Just a note about the DIF function:
As shown, using the IFN function, it works as intended. But only because the IFN function always calculates both output values before choosing one.
In other words, this works:

variable = ifn(first.year,variable,dif(variable));

but this does not:

if not first.year then variable=dif(variable);

because the DIF function should be called every time to work as intended here, as the DIF and LAG functions work by storing value(s) from previous calls in an internal stack.


问:
Does tidytext::unnest_tokens works with spanish characters?
I am trying to use unnest_tokens with spanish text. It works fine with unigrams, but breaks the special characters with bigrams.

The code works fine on Linux. I added some info on the locale.

```<code>library(tidytext)
library(dplyr)

df <- data_frame(
  text = "César Moreira Nuñez"
)

# works ok:
df %>%
  unnest_tokens(word, text)

# # A tibble: 3 x 1
# word
# <chr>
# 1 césar
# 2 moreira
# 3 nuñez

# breaks é and ñ
df %>%
  unnest_tokens(bigram, text, token = "ngrams", n = 2 )

# # A tibble: 2 x 1
# bigram
# <chr>
# 1 cã©sar moreira
# 2 moreira nuã±ez

> Sys.getlocale()
[1] "LC_COLLATE=English_United States.1252;LC_CTYPE=English_United
States.1252;LC_MONETARY=English_United
States.1252;LC_NUMERIC=C;LC_TIME=English_United States.1252"
</code>```

答:
It seems that it happens when you change the token argument to ngrams. I m not sure why it does that, but here is a work around using package qlcMatrix

```<code>library(qlcMatrix)

splitStrings(df$text, sep = ' ', bigrams = TRUE, boundary = FALSE, bigram.binder = ' ')$bigrams
#[1] "César Moreira" "Moreira Nuñez"
</code>```

Body:
I am trying to use unnest_tokens with spanish text. It works fine with unigrams, but breaks the special characters with bigrams.

The code works fine on Linux. I added some info on the locale.

library(tidytext)
library(dplyr)

df <- data_frame(
  text = "César Moreira Nuñez"
)

# works ok:
df %>%
  unnest_tokens(word, text)

# # A tibble: 3 x 1
# word
# <chr>
# 1 césar
# 2 moreira
# 3 nuñez

# breaks é and ñ
df %>%
  unnest_tokens(bigram, text, token = "ngrams", n = 2 )

# # A tibble: 2 x 1
# bigram
# <chr>
# 1 cã©sar moreira
# 2 moreira nuã±ez

> Sys.getlocale()
[1] "LC_COLLATE=English_United States.1252;LC_CTYPE=English_United
States.1252;LC_MONETARY=English_United
States.1252;LC_NUMERIC=C;LC_TIME=English_United States.1252"

Body:
It seems that it happens when you change the token argument to ngrams. I m not sure why it does that, but here is a work around using package qlcMatrix

library(qlcMatrix)

splitStrings(df$text, sep = ' ', bigrams = TRUE, boundary = FALSE, bigram.binder = ' ')$bigrams
#[1] "César Moreira" "Moreira Nuñez"


问:
JavaScript: Compare dates in an array and sum the "price" for each month/year
I have a json file with multiple transactions with a date and a price attribute. Now I want to compare the dates and if they are in the same month and year I want to sum up the prices.

JSON:

```<code>transactions: [
{
  date: "2017-11-17",
  price: "28",
},
{
  ...
}
</code>```

JavaScript:

```<code>request.onload = function() {
  for(const transaction of request.response.transactions) {
    let year = new Date(transaction.date).getFullYear();
    let month = new Date(transaction.date).getMonth();

    console.log(year + ' ' + month);  // output: 2017-11 ...
  }
};
</code>```

I tried to loop over the json object but I struggle to find a solution to compare the dates.

答:
```<code>var array = [];
for (var i = 0; i < transactions.length; i++) {
    var date = new Date(transactions[i].date);
    var ym = date.getFullYear() + "-" + date.getMonth();
    if (array[ym] == null) {
        array[ym] = 0;
    }
    array[ym] += parseInt(transactions[i].price);
}
</code>```

With this data

```<code>var transactions = [{
                date: "2017-11-17",
                price: "28",
            },
            {
                date: "2017-12-17",
                price: "5",
            },
            {
                date: "2016-02-17",
                price: "28",
            },
            {
                date: "2015-11-17",
                price: "25",
            },
            {
                date: "2016-02-17",
                price: "12",
            },
            {
                date: "2017-11-17",
                price: "50",
            }
        ];
</code>```

This will give you the sum of all of the year-months duplicates like this :

```<code>[
    2017-10: 78,
    2017-11: 5,
    2016-1: 40,
    2015-10: 25
]
</code>```

Body:
I have a json file with multiple transactions with a date and a price attribute. Now I want to compare the dates and if they are in the same month and year I want to sum up the prices.

JSON:

transactions: [
{
  date: "2017-11-17",
  price: "28",
},
{
  ...
}

JavaScript:

request.onload = function() {
  for(const transaction of request.response.transactions) {
    let year = new Date(transaction.date).getFullYear();
    let month = new Date(transaction.date).getMonth();

    console.log(year + ' ' + month);  // output: 2017-11 ...
  }
};

I tried to loop over the json object but I struggle to find a solution to compare the dates.

Body:
var array = [];
for (var i = 0; i < transactions.length; i++) {
    var date = new Date(transactions[i].date);
    var ym = date.getFullYear() + "-" + date.getMonth();
    if (array[ym] == null) {
        array[ym] = 0;
    }
    array[ym] += parseInt(transactions[i].price);
}

With this data

var transactions = [{
                date: "2017-11-17",
                price: "28",
            },
            {
                date: "2017-12-17",
                price: "5",
            },
            {
                date: "2016-02-17",
                price: "28",
            },
            {
                date: "2015-11-17",
                price: "25",
            },
            {
                date: "2016-02-17",
                price: "12",
            },
            {
                date: "2017-11-17",
                price: "50",
            }
        ];

This will give you the sum of all of the year-months duplicates like this :

[
    2017-10: 78,
    2017-11: 5,
    2016-1: 40,
    2015-10: 25
]


问:
pytorch data loader multiple iterations
i use iris-dataset to train a simple network with pytorch.

```<code>trainset = iris.Iris(train=True)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=150,
                                          shuffle=True, num_workers=2)

dataiter = iter(trainloader)
</code>```

the dataset itself has only 150 data points, and pytorch dataloader iterates jus t once over the whole dataset, because of the batch size of 150.

My question is now, is there generally any way to tell dataloader of pytorch to repeat over the dataset if it's once done with iteration?

thnaks

update

got it runnning :)
just created a sub class of dataloader and implemented my own __next__()

答:
The simplest option is to just use a nested loop:

```<code>for i in range(10):
    for batch in trainloader:
        do_something(batch)
</code>```

Another option would be to use itertools.cycle, perhaps in combination with itertools.take.

Of course, using a DataLoader with batch size equal to the whole dataset is a bit unusual. You don't need to call iter() on the trainloader either.

Title: pytorch data loader multiple iterations

Body:
i use iris-dataset to train a simple network with pytorch.

trainset = iris.Iris(train=True)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=150,
                                          shuffle=True, num_workers=2)

dataiter = iter(trainloader)

the dataset itself has only 150 data points, and pytorch dataloader iterates jus t once over the whole dataset, because of the batch size of 150.

My question is now, is there generally any way to tell dataloader of pytorch to repeat over the dataset if it's once done with iteration?

thnaks

update

got it runnning :)
just created a sub class of dataloader and implemented my own __next__()

Body:
The simplest option is to just use a nested loop:

for i in range(10):
    for batch in trainloader:
        do_something(batch)

Another option would be to use itertools.cycle, perhaps in combination with itertools.take.

Of course, using a DataLoader with batch size equal to the whole dataset is a bit unusual. You don't need to call iter() on the trainloader either.


问:
node-fetch responding with 503 where request responding with 200 behind proxy
Below I have two http requests, one made with request and the other being made with isomorphic-fetch (node-fetch). For some reason the request with request works, however node-fetch is responding back with an error code 503. Is there anything I am missing from the fetch version?

```<code>const URL = require('url')
const fetch = require('isomorphic-fetch')
const HttpsProxyAgent = require('https-proxy-agent')
const request = require('request');

const url = process.env.URL
const proxy = process.env.PROXY

const requestPromise = function (url, options) {
    if (/^\/\//.test(url)) {
    url = 'https:' + url;
    }

    return new Promise(function(resolve, reject) {
        return request.call(this, url, options, function (err, res, body) {
            if (err) {
            throw new Error(err);
            }

            res.ok = true;
            res.json = function () {
            return JSON.parse(res.body);
            }
            return resolve(res);
        });
    });
};

function getProxy (url) {
    const parsedProxyURL = URL.parse(url);
    parsedProxyURL.secureProxy = parsedProxyURL.protocol === 'https:';
    return parsedProxyURL
}

requestPromise(url, {
    agent:new HttpsProxyAgent(getProxy(proxy))
})
    .then(console.log)
    .catch(console.log)

fetch(url, {
    agent:new HttpsProxyAgent(getProxy(proxy))
})
    .then(console.log)
    .catch(console.log)
</code>```

答:
The request module seems to be setting one header automatically, the host that fetch module is not. by making this change it works.

```<code>const URL = require('url')
const fetch = require('isomorphic-fetch')
const HttpsProxyAgent = require('https-proxy-agent')
const request = require('request')

function getProxy (url) {
    const parsedProxyURL = URL.parse(url)
    parsedProxyURL.secureProxy = parsedProxyURL.protocol === 'https:'
    return parsedProxyURL
}

const url = process.env.URL
const proxy = process.env.PROXY

fetch(url, {
    headers: {host: URL.parse(url).host},
    agent: new HttpsProxyAgent(getProxy(proxy))
})
    .then(res => res.json()).then(res => {
        console.log(res)
    })
    .catch(console.log)
</code>```

Body:
Below I have two http requests, one made with request and the other being made with isomorphic-fetch (node-fetch). For some reason the request with request works, however node-fetch is responding back with an error code 503. Is there anything I am missing from the fetch version?

const URL = require('url')
const fetch = require('isomorphic-fetch')
const HttpsProxyAgent = require('https-proxy-agent')
const request = require('request');

const url = process.env.URL
const proxy = process.env.PROXY

const requestPromise = function (url, options) {
    if (/^\/\//.test(url)) {
    url = 'https:' + url;
    }

    return new Promise(function(resolve, reject) {
        return request.call(this, url, options, function (err, res, body) {
            if (err) {
            throw new Error(err);
            }

            res.ok = true;
            res.json = function () {
            return JSON.parse(res.body);
            }
            return resolve(res);
        });
    });
};

function getProxy (url) {
    const parsedProxyURL = URL.parse(url);
    parsedProxyURL.secureProxy = parsedProxyURL.protocol === 'https:';
    return parsedProxyURL
}

requestPromise(url, {
    agent:new HttpsProxyAgent(getProxy(proxy))
})
    .then(console.log)
    .catch(console.log)

fetch(url, {
    agent:new HttpsProxyAgent(getProxy(proxy))
})
    .then(console.log)
    .catch(console.log)

Body:
The request module seems to be setting one header automatically, the host that fetch module is not. by making this change it works.

const URL = require('url')
const fetch = require('isomorphic-fetch')
const HttpsProxyAgent = require('https-proxy-agent')
const request = require('request')

function getProxy (url) {
    const parsedProxyURL = URL.parse(url)
    parsedProxyURL.secureProxy = parsedProxyURL.protocol === 'https:'
    return parsedProxyURL
}

const url = process.env.URL
const proxy = process.env.PROXY

fetch(url, {
    headers: {host: URL.parse(url).host},
    agent: new HttpsProxyAgent(getProxy(proxy))
})
    .then(res => res.json()).then(res => {
        console.log(res)
    })
    .catch(console.log)

ContentLicense: CC BY-SA 4.0


问:
Replace and Rearrange string in javascript
I have an input string

```<code>this.name in ['Sachin','Rahul','Anil']
</code>```

If I find " in " in the above string, I need to replace this as below

```<code>['Sachin','Rahul','Anil'].indexOf(this.name) > -1
</code>```

Similarly, If I have an input string containing not in

```<code>this.name not in ['Sachin','Rahul','Anil']
</code>```

If " not in " is found, I need to replace it as

```<code>['Sachin','Rahul','Anil'].indexOf(this.name)  < 0
</code>```

Is it possible to achieve this in javascript?

答:
To test for existence and replace

```<code>var theArray = ['Sachin', 'Rahul', 'Anil'];
var searchForName = 'Rahul';
var indexOfName = theArray.indexOf(searchForName);
if (indexOfName > -1) {
   theArray[indexOfName] = 'Sahil'; // gives ['Sachin', 'Sahil', 'Anil']
}
</code>```

To remove

```<code>var theArray = ['Sachin', 'Rahul', 'Anil'];
var searchForName = 'Rahul';
var indexOfName = theArray.indexOf(searchForName);
if (indexOfName > -1) {
   theArray.splice(indexOfName, 1); // gives ['Sachin', 'Anil']
}
</code>```

Although as the others have alluded to, its difficult to understand your intent based off the question

Body:
I have an input string

this.name in ['Sachin','Rahul','Anil']

If I find " in " in the above string, I need to replace this as below

['Sachin','Rahul','Anil'].indexOf(this.name) > -1

Similarly, If I have an input string containing not in

this.name not in ['Sachin','Rahul','Anil']

If " not in " is found, I need to replace it as

['Sachin','Rahul','Anil'].indexOf(this.name)  < 0

Is it possible to achieve this in javascript?

Body:
To test for existence and replace

var theArray = ['Sachin', 'Rahul', 'Anil'];
var searchForName = 'Rahul';
var indexOfName = theArray.indexOf(searchForName);
if (indexOfName > -1) {
   theArray[indexOfName] = 'Sahil'; // gives ['Sachin', 'Sahil', 'Anil']
}

To remove

var theArray = ['Sachin', 'Rahul', 'Anil'];
var searchForName = 'Rahul';
var indexOfName = theArray.indexOf(searchForName);
if (indexOfName > -1) {
   theArray.splice(indexOfName, 1); // gives ['Sachin', 'Anil']
}

Although as the others have alluded to, its difficult to understand your intent based off the question


问:
How do I parallelise a for loop, using `omp parallel` or otherwise?
Assuming I have three integer vectors:

mainVect of size 8 million element

vect1 of size 1.5 million element

vect2 of size 1.5 million element

I want to run the following code:

```<code>int i,j;
for ( i = 0; i < vect1.size(); i++)
{
    for ( j = 0; j < mainVect.size(); j++)
    {
        if (vect1[i] == mainVect[j])
        {
            vect2[i]++;
        }
    }
}
</code>```

It took a very long time without finishing yet...How I can speed up the run, I have multiprocessors. As a try, I've added the following sentence before the previous code (I read that it run in parallel)

```<code>#pragma omp parallel for private(i, j) shared( mainVect, vect1, vect2)
</code>```

But still slow ...

If I divide the for loop into 4 sections; for example, how I can make these for loops run simultaneously such as

```<code>for ( i = 0; i < vect1.size()/4; i++)
{

}

for ( i = vect1.size()/4; i < vect1.size()/2; i++)
{

}
.... and so on
</code>```

Or any other methods ...

P.S.:
Windows google cloud machine, n1-standard-4 (4 vCPUs, 15 GB memory) .. CPU utilization only 27% when run the above code.

答:
Using threads is one possible solution.

But the main question is: what problem are you trying to solve?

If I understand it correctly, you're counting the number of occurrences in mainVect of an element in vect1. Since you don't need to know where, you can rearrange (a copy of) mainVect.

My approach would be:

Sort mainVect

convert mainVect to a table consisting of "key" and number of occurrences

Sort vect1 and create an indirection vector. Iterating over this indirection vector gives the "key"s in ascending sequence

now you can "merge"

The complexity of this approach is O(n log n)

Body:
Assuming I have three integer vectors:

mainVect of size 8 million element

vect1 of size 1.5 million element

vect2 of size 1.5 million element

I want to run the following code:

int i,j;
for ( i = 0; i < vect1.size(); i++)
{
    for ( j = 0; j < mainVect.size(); j++)
    {
        if (vect1[i] == mainVect[j])
        {
            vect2[i]++;
        }
    }
}

It took a very long time without finishing yet...How I can speed up the run, I have multiprocessors. As a try, I've added the following sentence before the previous code (I read that it run in parallel)

#pragma omp parallel for private(i, j) shared( mainVect, vect1, vect2)

But still slow ...

If I divide the for loop into 4 sections; for example, how I can make these for loops run simultaneously such as

for ( i = 0; i < vect1.size()/4; i++)
{

}

for ( i = vect1.size()/4; i < vect1.size()/2; i++)
{

}
.... and so on

Or any other methods ...

P.S.:
Windows google cloud machine, n1-standard-4 (4 vCPUs, 15 GB memory) .. CPU utilization only 27% when run the above code.


问:
How can I verify a plaintext password with a hash algorithm?
I have a question about salts. For example, there is a record in our
database that looks like this:

```<code>Password: YUphoRF70vJEPAOjMmc/9n47hyQ=
Password Format: 1
Password Salt: Vx37L8ItQo3rJzx5gRCxTw==
</code>```

I am trying to verify this password, but the method I am using isn't working.

This is the method:

```<code>public static string EncodePassword(string pass, string salt)
{
    byte[] bytes = Encoding.Unicode.GetBytes(pass);
    byte[] src = Encoding.Unicode.GetBytes(salt);
    byte[] dst = new byte[src.Length + bytes.Length];
    Buffer.BlockCopy(src, 0, dst, 0, src.Length);
    Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
    HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
    byte[] inArray = algorithm.ComputeHash(dst);
    return Convert.ToBase64String(inArray);
}
</code>```

And I pass it like this:

```<code>string encodedPasswd = Cryptography.EncodePassword(ClearTxtPassword, DbPasswordSalt);
</code>```

What comes back does not look like the password in the database.

I am wondering if there is something else I should be doing to the salt? Is
what is stored in the DB what I should be passing to the EncodePassword method or is
there a step in between in which I should be decoding it prior to passing it as a
parameter?

I am just not sure why I am getting a password mismatch. According to the web.config of the site I am working on, it is passwordFormat="Hashed" and the PasswordFormat column in the DB says "1" so I know it is SHA1.

Do you have any ideas why I am not getting the right match or how to get further along in figuring it out?(And yes, I have the right password.)

EDIT:

I have tried the following updated method:

```<code>public static string EncodePassword(string pass, string salt)
{
    byte[] bytes = Encoding.Unicode.GetBytes(pass);
    byte[] src = Convert.FromBase64String(salt);
    byte[] dst = new byte[src.Length + bytes.Length];
    Buffer.BlockCopy(src, 0, dst, 0, src.Length);
    Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
    HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
    byte[] inArray = algorithm.ComputeHash(dst);
    return Convert.ToBase64String(inArray);
}
</code>```

Against my current DB data and it still isn't matching up. For example, I am getting
the following results:

```<code>passwordText = "administrator"
passwordformat: 1 / SHA1
passwordSaltInDb: "zVhahfmXj9MrOQySyPQ1Qw=="
passwordInDb = "YZ5xRJkNG9erGStAkWJA3hID9vE="

encodedPasswordResults = "DWZ6XRtVMy4l+XSUOKoX8usUOJI="
</code>```

Is there any way that somebody could test on in their own environment to see why I am getting such different results?

答:
If you're passing in the salt exactly as it's stored in the database then you're dealing with a Base-64 encoded string. To convert it to a byte[] array you should use Convert.FromBase64String rather than Unicode.GetBytes. Something along these lines:

```<code>public static string EncodePassword(string pass, string salt)
{
    byte[] bytes = Encoding.Unicode.GetBytes(pass);
    byte[] src = Convert.FromBase64String(salt);
    byte[] dst = new byte[src.Length + bytes.Length];
    Buffer.BlockCopy(src, 0, dst, 0, src.Length);
    Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
    HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
    byte[] inArray = algorithm.ComputeHash(dst);
    return Convert.ToBase64String(inArray);
}
</code>```

By the way, although your question repeatedly mentions decrypting the password, it looks to me as if you're simply trying to validate a plaintext password against the stored hash. If that's the case then the above code should be fine.

If you really are trying to decrypt the stored hash then don't bother! The hash is not an encrypted version of the password, so decrypting it is impossible.

Body:
I have a question about salts. For example, there is a record in our
database that looks like this:

Password: YUphoRF70vJEPAOjMmc/9n47hyQ=
Password Format: 1
Password Salt: Vx37L8ItQo3rJzx5gRCxTw==

I am trying to verify this password, but the method I am using isn't working.

This is the method:

public static string EncodePassword(string pass, string salt)
{
    byte[] bytes = Encoding.Unicode.GetBytes(pass);
    byte[] src = Encoding.Unicode.GetBytes(salt);
    byte[] dst = new byte[src.Length + bytes.Length];
    Buffer.BlockCopy(src, 0, dst, 0, src.Length);
    Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
    HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
    byte[] inArray = algorithm.ComputeHash(dst);
    return Convert.ToBase64String(inArray);
}

And I pass it like this:

string encodedPasswd = Cryptography.EncodePassword(ClearTxtPassword, DbPasswordSalt);

What comes back does not look like the password in the database.

I am wondering if there is something else I should be doing to the salt? Is
what is stored in the DB what I should be passing to the EncodePassword method or is
there a step in between in which I should be decoding it prior to passing it as a
parameter?

I am just not sure why I am getting a password mismatch. According to the web.config of the site I am working on, it is passwordFormat="Hashed" and the PasswordFormat column in the DB says "1" so I know it is SHA1.

Do you have any ideas why I am not getting the right match or how to get further along in figuring it out?(And yes, I have the right password.)

EDIT:

I have tried the following updated method:

public static string EncodePassword(string pass, string salt)
{
    byte[] bytes = Encoding.Unicode.GetBytes(pass);
    byte[] src = Convert.FromBase64String(salt);
    byte[] dst = new byte[src.Length + bytes.Length];
    Buffer.BlockCopy(src, 0, dst, 0, src.Length);
    Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
    HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
    byte[] inArray = algorithm.ComputeHash(dst);
    return Convert.ToBase64String(inArray);
}

Against my current DB data and it still isn't matching up. For example, I am getting
the following results:

passwordText = "administrator"
passwordformat: 1 / SHA1
passwordSaltInDb: "zVhahfmXj9MrOQySyPQ1Qw=="
passwordInDb = "YZ5xRJkNG9erGStAkWJA3hID9vE="

encodedPasswordResults = "DWZ6XRtVMy4l+XSUOKoX8usUOJI="

Is there any way that somebody could test on in their own environment to see why I am getting such different results?

Body:
If you're passing in the salt exactly as it's stored in the database then you're dealing with a Base-64 encoded string. To convert it to a byte[] array you should use Convert.FromBase64String rather than Unicode.GetBytes. Something along these lines:

public static string EncodePassword(string pass, string salt)
{
    byte[] bytes = Encoding.Unicode.GetBytes(pass);
    byte[] src = Convert.FromBase64String(salt);
    byte[] dst = new byte[src.Length + bytes.Length];
    Buffer.BlockCopy(src, 0, dst, 0, src.Length);
    Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
    HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
    byte[] inArray = algorithm.ComputeHash(dst);
    return Convert.ToBase64String(inArray);
}

By the way, although your question repeatedly mentions decrypting the password, it looks to me as if you're simply trying to validate a plaintext password against the stored hash. If that's the case then the above code should be fine.

If you really are trying to decrypt the stored hash then don't bother! The hash is not an encrypted version of the password, so decrypting it is impossible.


问:
How do I iterate through an ansible registered value?
So, I had to run a command in ansible which will have multiple answers,
 for example : Run a command to list the names and other details of all the users. Result will have say,

```<code>Carry   2/10

Barry   19/7

Harry   7/7

Jerry   11/4

Terry   7/12

Marie   13/10
</code>```

I've saved this result to variable called names in the tasks of the playbook

```<code> register: names
</code>```

How do I iterate through each of these names one at a time and run specific commands when I'm iterating through them?

Will I have to convert this string to a json file as ansible accepts json?

答:
You can iterate throgh those lines with: with_lines: "{{ names }}"

That way each time the {{ item }} var gets a line, on which you can run anything you like (for start i would check if the line isn't empty).
I would also recommand to look at ansible regex filters so you could manipulate those strings.

You could also use with_items: "{{ names.stdout_lines }}" as the ansible-documantation says

Body:
So, I had to run a command in ansible which will have multiple answers,
 for example : Run a command to list the names and other details of all the users. Result will have say,

Carry   2/10

Barry   19/7

Harry   7/7

Jerry   11/4

Terry   7/12

Marie   13/10

I've saved this result to variable called names in the tasks of the playbook

 register: names

How do I iterate through each of these names one at a time and run specific commands when I'm iterating through them?

Will I have to convert this string to a json file as ansible accepts json?


问:
Apply a function that has arguments from two different dataframes, with group by. (pandas)
I have the following task that troubles me.
I have a function that I want to apply to a pandas dataframe, by group. This function, takes as input 1 series from another dataframe, and 1 from the current one. I tried many different ways but and eventually I found a solution, however I wonder if there is a better way.

Bellow I provide a reproducible example.

```<code>#load the data
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
iris = load_iris()
data1 = pd.DataFrame(data= np.c_[ iris['target'], iris['data']],  columns=  ['target'] + iris['feature_names'] )
data2 = pd.DataFrame({'x' : data1[data1.target == 0].iloc[:,1], 'y' :data1[data1.target == 0].iloc[:,2]})

# define one random function
def some_function(x, p):
    err = (x - p )
    return sum(err)
</code>```

So my first try was:

```<code>data1.groupby('target').apply(lambda x: some_function(data2.iloc[:,0], data1.iloc[:,4])) # this does not work
</code>```

after trying many different ways,

```<code> data1.groupby('target').apply(lambda x: some_function(data1.iloc[:,1], data1.iloc[:,4])) # this works
data1.groupby('target').apply(lambda x: some_function(data2.iloc[:,1],data1[data1.target==0].iloc[:,4])) # this works
    data1.groupby('target').apply(lambda x: some_function(data2.iloc[:,1], data1[data1.target==1].iloc[:,4])) # this does not work
</code>```

I found out (after long time) that it was a problem with the indexing. So the following works.

```<code>data1.groupby('target').apply(lambda x: some_function(data2.iloc[:,0],  x.iloc[:,4].reset_index().iloc[:,1]))
</code>```

Is there any other way? Why if I use axis = 1 at the end it does not work?

Finally, how can I add this in the new row in the data1? something like that it does not merge the results to all rows.

```<code>   data1.groupby('target')['new_column'] = data1.groupby('target').apply(lambda x: some_function(data2.iloc[:,0],  x.iloc[:,4].reset_index().iloc[:,1]))
</code>```

or without using the groupby

答:
I think you can use reset_index() with parameter drop=True for remove original index values but generally is necessary length of each group is same as length of another DataFrame data2:

Test lengths:

```<code>s1 = data1.groupby('target').size()
print (s1)
target
0.0    50
1.0    50
2.0    50
dtype: int64

print (len(data2))
50
</code>```

```<code>s = (data1.groupby('target')
          .apply(lambda x: some_function(data2.iloc[:,0],
                                         x.iloc[:,4].reset_index(drop=True))))
</code>```

Alternative is convert Series to numpy array:

```<code>s=data1.groupby('target').apply(lambda x: some_function(data2.iloc[:,0],x.iloc[:,4].values))

print (s)
target
0.0    238.1
1.0    184.0
2.0    149.0
dtype: float64
</code>```

And for new column use map:

```<code>data1['new'] = data1['target'].map(s)
print (data1.head())
   target  sepal length (cm)  sepal width (cm)  petal length (cm)  \
0     0.0                5.1               3.5                1.4
1     0.0                4.9               3.0                1.4
2     0.0                4.7               3.2                1.3
3     0.0                4.6               3.1                1.5
4     0.0                5.0               3.6                1.4

   petal width (cm)    new
0               0.2  238.1
1               0.2  238.1
2               0.2  238.1
3               0.2  238.1
4               0.2  238.1

print (data1.tail())
     target  sepal length (cm)  sepal width (cm)  petal length (cm)  \
145     2.0                6.7               3.0                5.2
146     2.0                6.3               2.5                5.0
147     2.0                6.5               3.0                5.2
148     2.0                6.2               3.4                5.4
149     2.0                5.9               3.0                5.1

     petal width (cm)    new
145               2.3  149.0
146               1.9  149.0
147               2.0  149.0
148               2.3  149.0
149               1.8  149.0
</code>```

Body:
I have the following task that troubles me.
I have a function that I want to apply to a pandas dataframe, by group. This function, takes as input 1 series from another dataframe, and 1 from the current one. I tried many different ways but and eventually I found a solution, however I wonder if there is a better way.

Bellow I provide a reproducible example.

#load the data
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
iris = load_iris()
data1 = pd.DataFrame(data= np.c_[ iris['target'], iris['data']],  columns=  ['target'] + iris['feature_names'] )
data2 = pd.DataFrame({'x' : data1[data1.target == 0].iloc[:,1], 'y' :data1[data1.target == 0].iloc[:,2]})

# define one random function
def some_function(x, p):
    err = (x - p )
    return sum(err)

So my first try was:

data1.groupby('target').apply(lambda x: some_function(data2.iloc[:,0], data1.iloc[:,4])) # this does not work

after trying many different ways,

 data1.groupby('target').apply(lambda x: some_function(data1.iloc[:,1], data1.iloc[:,4])) # this works
data1.groupby('target').apply(lambda x: some_function(data2.iloc[:,1],data1[data1.target==0].iloc[:,4])) # this works
    data1.groupby('target').apply(lambda x: some_function(data2.iloc[:,1], data1[data1.target==1].iloc[:,4])) # this does not work

I found out (after long time) that it was a problem with the indexing. So the following works.

data1.groupby('target').apply(lambda x: some_function(data2.iloc[:,0],  x.iloc[:,4].reset_index().iloc[:,1]))

Is there any other way? Why if I use axis = 1 at the end it does not work?

Finally, how can I add this in the new row in the data1? something like that it does not merge the results to all rows.

   data1.groupby('target')['new_column'] = data1.groupby('target').apply(lambda x: some_function(data2.iloc[:,0],  x.iloc[:,4].reset_index().iloc[:,1]))

or without using the groupby

Body:
I think you can use reset_index() with parameter drop=True for remove original index values but generally is necessary length of each group is same as length of another DataFrame data2:

Test lengths:

s1 = data1.groupby('target').size()
print (s1)
target
0.0    50
1.0    50
2.0    50
dtype: int64

print (len(data2))
50

s = (data1.groupby('target')
          .apply(lambda x: some_function(data2.iloc[:,0],
                                         x.iloc[:,4].reset_index(drop=True))))

Alternative is convert Series to numpy array:

s=data1.groupby('target').apply(lambda x: some_function(data2.iloc[:,0],x.iloc[:,4].values))

print (s)
target
0.0    238.1
1.0    184.0
2.0    149.0
dtype: float64

And for new column use map:

data1['new'] = data1['target'].map(s)
print (data1.head())
   target  sepal length (cm)  sepal width (cm)  petal length (cm)  \
0     0.0                5.1               3.5                1.4
1     0.0                4.9               3.0                1.4
2     0.0                4.7               3.2                1.3
3     0.0                4.6               3.1                1.5
4     0.0                5.0               3.6                1.4

   petal width (cm)    new
0               0.2  238.1
1               0.2  238.1
2               0.2  238.1
3               0.2  238.1
4               0.2  238.1

print (data1.tail())
     target  sepal length (cm)  sepal width (cm)  petal length (cm)  \
145     2.0                6.7               3.0                5.2
146     2.0                6.3               2.5                5.0
147     2.0                6.5               3.0                5.2
148     2.0                6.2               3.4                5.4
149     2.0                5.9               3.0                5.1

     petal width (cm)    new
145               2.3  149.0
146               1.9  149.0
147               2.0  149.0
148               2.3  149.0
149               1.8  149.0


问:
is this a valid class variable ? $this->$variablename
I am referencing to a variable like this

```<code>$this->variablename
</code>```

but I have seen accessing variable like this:

```<code>$this->$variablename
</code>```

for example in a google script

```<code>public function __get($key)
{
    $keyTypeName = $this->keyType($key);
    $keyDataType = $this->dataType($key);
    if (isset($this->$keyTypeName) && !isset($this->processed[$key])) {
      if (isset($this->modelData[$key])) {
        $val = $this->modelData[$key];
      } else if (isset($this->$keyDataType) &&
          ($this->$keyDataType == 'array' || $this->$keyDataType == 'map')) {
        $val = array();
      } else {
        $val = null;
      }
   }
}
</code>```

in this example it is $this->$keyTypeName, is this an error or valid code?. In php 7 it is giving error.

答: Yes, they're called variable variables. It accesses $this->whateverKeyTypeNameIsSetTo.

Body:
I am referencing to a variable like this

$this->variablename

but I have seen accessing variable like this:

$this->$variablename

for example in a google script

public function __get($key)
{
    $keyTypeName = $this->keyType($key);
    $keyDataType = $this->dataType($key);
    if (isset($this->$keyTypeName) && !isset($this->processed[$key])) {
      if (isset($this->modelData[$key])) {
        $val = $this->modelData[$key];
      } else if (isset($this->$keyDataType) &&
          ($this->$keyDataType == 'array' || $this->$keyDataType == 'map')) {
        $val = array();
      } else {
        $val = null;
      }
   }
}

in this example it is $this->$keyTypeName, is this an error or valid code?. In php 7 it is giving error.


问:
Spring - same mapping to display different list
I'm trying to use the same view to display different lists based on the param I'm passing from the button in JSP.

what I need is: when user click on button, will call the same view but data should be display from the second list .(getPreviousYearReports())

here's my code:

```<code>@RequestMapping(value = "/viewReports.do", method = {RequestMethod.GET , RequestMethod.POST})
public ModelAndView viewReports( @RequestParam final Integer storeNumber,
        final HttpServletRequest request) {
    ModelAndView view = getModelAndView("viewReports");

    List<StoreReport> reportsList;
    if(request.getParameter("previous") != null ) {
        reportsList = storeReportService.getPreviousYearReports(storeNumber);

    } else {
        reportsList = storeReportService.getReportsByStore(storeNumber);
    }
....
}
</code>```

in my JSP.
I have added submit button to call the same view mapping

```<code><button id="previous" name="previous" type="submit" class="btnFwd gradient smButtonStyling"
    onClick="window.location.href='/viewReports.do?storeNumber=${storeNumber}'">
View Previous Year Reports
</code>```

答:
I was missing to pass the "&previous" param </p>

```<code><button id="previous" name="previous" type="submit" class="btnFwd gradient smButtonStyling"
        onClick="window.location.href='/StoreReports/viewReports.do?storeNumber=${storeNumber}&previous'">
      View Previous Year Reports
</button>
</code>```

Body:
I'm trying to use the same view to display different lists based on the param I'm passing from the button in JSP.

what I need is: when user click on button, will call the same view but data should be display from the second list .(getPreviousYearReports())

here's my code:

@RequestMapping(value = "/viewReports.do", method = {RequestMethod.GET , RequestMethod.POST})
public ModelAndView viewReports( @RequestParam final Integer storeNumber,
        final HttpServletRequest request) {
    ModelAndView view = getModelAndView("viewReports");

    List<StoreReport> reportsList;
    if(request.getParameter("previous") != null ) {
        reportsList = storeReportService.getPreviousYearReports(storeNumber);

    } else {
        reportsList = storeReportService.getReportsByStore(storeNumber);
    }
....
}

in my JSP.
I have added submit button to call the same view mapping

<button id="previous" name="previous" type="submit" class="btnFwd gradient smButtonStyling"
    onClick="window.location.href='/viewReports.do?storeNumber=${storeNumber}'">
View Previous Year Reports

Body:
I was missing to pass the "&previous" param

<button id="previous" name="previous" type="submit" class="btnFwd gradient smButtonStyling"
        onClick="window.location.href='/StoreReports/viewReports.do?storeNumber=${storeNumber}&previous'">
      View Previous Year Reports
</button>


问:
When you program in as3, do you usually use classes?
I want other programmers' opinions on this.  When you program in as3, do you usually use classes?  Why?</p>

答: Yes, even if it just a Main class that represents the main timeline.  To be honest, though, every time opt for a minimal one class project and don't use my PureMVC baseline, the project grows and I kick myself.  Going full PureMVC on an initially simple project really saved me recently because it took a few left turns and ended up with some rather complex logic.  Instead of rewriting everything, most of the new logic involved new notifications (ie, PureMVC events), and reworking who responded to what notifications and when.</p>


问:
Can't change series edgeColor in highCharts after chart is drawn
I'm attempting to change edgeColor property for a series in a 3d column chart after the chart is drawn, based on some user input (like selecting a certain series).  I was able to do this was a 2d column chart using the borderColor property.  My data loading snippet looks like this:

```<code>$.each(seriesDataArray,function(i,val){
   console.log (val);
   chartDetails.series.push({ "size" : val.datasetSizeVerified , "data" : val.data});
};
</code>```

And I'm trying to modify the edgeColor in a function later on in code:

```<code>function highlightChartSeries(currentTableDisplayIndex){
        if (myChart){
            $.each(myChart.series,function(i,val){
                val.edgeColor = "green" ;
                val.redraw();
            });

            myChart.series[currentTableDisplayIndex].edgeColor = "red";
            myChart.series[currentTableDisplayIndex].redraw();

        }
}
</code>```

Again, this works great in 2D with a column chart using the borderColor property.  I can set the edgeColor in the original series object during chart construction, and that edgeColor is reflected in my original graph.  However, I can't change it later.  Any help is appreciated!

答:
To add (or change) some value to existing series, you should use Chart.Series function called update(), and pass to it new configuration options object, because it is a function specially created to executing actions like that. Please take a look at code below:

```<code>chart.series.forEach(series => {
  series.update({
    edgeColor: 'black'
  })
})
</code>```

I prepared for you live example how to use that function.

Best regards!

Body:
I'm attempting to change edgeColor property for a series in a 3d column chart after the chart is drawn, based on some user input (like selecting a certain series).  I was able to do this was a 2d column chart using the borderColor property.  My data loading snippet looks like this:

$.each(seriesDataArray,function(i,val){
   console.log (val);
   chartDetails.series.push({ "size" : val.datasetSizeVerified , "data" : val.data});
};

And I'm trying to modify the edgeColor in a function later on in code:

function highlightChartSeries(currentTableDisplayIndex){
        if (myChart){
            $.each(myChart.series,function(i,val){
                val.edgeColor = "green" ;
                val.redraw();
            });

            myChart.series[currentTableDisplayIndex].edgeColor = "red";
            myChart.series[currentTableDisplayIndex].redraw();

        }
}

Again, this works great in 2D with a column chart using the borderColor property.  I can set the edgeColor in the original series object during chart construction, and that edgeColor is reflected in my original graph.  However, I can't change it later.  Any help is appreciated!

Body:
To add (or change) some value to existing series, you should use Chart.Series function called update(), and pass to it new configuration options object, because it is a function specially created to executing actions like that. Please take a look at code below:

chart.series.forEach(series => {
  series.update({
    edgeColor: 'black'
  })
})

I prepared for you live example how to use that function.

Best regards!


问:
EF Core - Set Timestamp before save still uses the old value
I have a Model with a Timestamp (Concurrency Token) column. I'm trying to write an integration test where I check that it works as I expect but with no success. My test looks like following

Get the entity with that should be updated from the web api with a HttpClient call.

Make a request directly to the Context and get the same entity

Change a property on the entity from step 2.

Save the entity updated in step 3.

Change a property on the entity from step 1.

Send a put request with the new entity with HttpClient to the Web Api.

In my web API I first get the entity from the database, sets the property and timestamp value from the one I got from the client. Now my entity object in the api controller has a different Timestamp value than the one in the database. Now I expect that savechanges would fail, but it doesn't. Instead it saves the entity to the database and generates a new Timestamp value. I checked with Sql Server Profiler to see the generated query and it turns out that is still use the old Timestamp value and not the one I assigned to the entity in my api controller.

What is the reason to this? Does it have anything to do with Timestamp being a database generated value that makes EF ignore changes made to it from the business layer?

The full test application can be found here: https://github.com/Abrissirba/EfTimestampBug

```<code>    public class BaseModel
    {
        [Timestamp]
        public byte[] Timestamp { get; set; }
    }

    public class Person : BaseModel
    {
        public int Id { get; set; }

        public String Title { get; set; }
    }

    public class Context : DbContext
    {
        public Context()
        {}

        public Context(DbContextOptions options) : base(options)
        {}

        public DbSet<Person> Persons{ get; set; }
    }

    protected override void BuildModel(ModelBuilder modelBuilder)
    {
        modelBuilder
            .HasAnnotation("ProductVersion", "7.0.0-rc1-16348")
            .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

        modelBuilder.Entity("EFTimestampBug.Models.Person", b =>
            {
                b.Property<int>("Id")
                    .ValueGeneratedOnAdd();

                b.Property<byte[]>("Timestamp")
                    .IsConcurrencyToken()
                    .ValueGeneratedOnAddOrUpdate();

                b.Property<string>("Title");

                b.HasKey("Id");
            });
    }

    // PUT api/values/5
    [HttpPut("{id}")]
    public Person Put(int id, [FromBody]Person personDTO)
    {
        // 7
        var person = db.Persons.SingleOrDefault(x => x.Id == id);
        person.Title = personDTO.Title;
        person.Timestamp = personDTO.Timestamp;
        db.SaveChanges();
        return person;
    }

    [Fact]
    public async Task Fail_When_Timestamp_Differs()
    {
        using (var client = server.CreateClient().AcceptJson())
        {
            await client.PostAsJsonAsync(ApiEndpoint, Persons[0]);
            // 1
            var getResponse = await client.GetAsync(ApiEndpoint);
            var fetched = await getResponse.Content.ReadAsJsonAsync<List<Person>>();

            Assert.True(getResponse.IsSuccessStatusCode);
            Assert.NotEmpty(fetched);

            var person = fetched.First();
            // 2
            var fromDb = await db.Persons.SingleOrDefaultAsync(x => x.Id == person.Id);
            // 3
            fromDb.Title = "In between";
            // 4
            await db.SaveChangesAsync();

            // 5
            person.Title = "After - should fail";
            // 6
            var postResponse = await client.PutAsJsonAsync(ApiEndpoint + person.Id, person);
            var created = await postResponse.Content.ReadAsJsonAsync<Person>();

            Assert.False(postResponse.IsSuccessStatusCode);
        }
    }

    // generated sql - @p1 has the original timestamp from the entity and not the assigned and therefore the save succeed which was not intended
    exec sp_executesql N'SET NOCOUNT OFF;
    UPDATE[Person] SET[Title] = @p2
    OUTPUT INSERTED.[Timestamp]
    WHERE [Id] = @p0 AND[Timestamp] = @p1;
    ',N'@p0 int,@p1 varbinary(8),@p2 nvarchar(4000)',@p0=21,@p1=0x00000000000007F4,@p2=N'After - should fail'
</code>```

答:
Microsoft have updated their tutorial for this in Handling concurrency conflicts - EF Core with ASP.NET Core MVC tutorial. It specifically states the following regarding updates:

Before you call SaveChanges, you have to put that original
  RowVersion property value in the OriginalValues collection for the
  entity.

```<code>_context.Entry(entityToUpdate).Property("RowVersion").OriginalValue = rowVersion;
</code>```

Then when the Entity Framework creates a SQL UPDATE command, that
  command will include a WHERE clause that looks for a row that has the
  original RowVersion value. If no rows are affected by the UPDATE
  command (no rows have the original RowVersion value), the Entity
  Framework throws a DbUpdateConcurrencyException exception.

Body:
I have a Model with a Timestamp (Concurrency Token) column. I'm trying to write an integration test where I check that it works as I expect but with no success. My test looks like following

Get the entity with that should be updated from the web api with a HttpClient call.

Make a request directly to the Context and get the same entity

Change a property on the entity from step 2.

Save the entity updated in step 3.

Change a property on the entity from step 1.

Send a put request with the new entity with HttpClient to the Web Api.

In my web API I first get the entity from the database, sets the property and timestamp value from the one I got from the client. Now my entity object in the api controller has a different Timestamp value than the one in the database. Now I expect that savechanges would fail, but it doesn't. Instead it saves the entity to the database and generates a new Timestamp value. I checked with Sql Server Profiler to see the generated query and it turns out that is still use the old Timestamp value and not the one I assigned to the entity in my api controller.

What is the reason to this? Does it have anything to do with Timestamp being a database generated value that makes EF ignore changes made to it from the business layer?

The full test application can be found here: https://github.com/Abrissirba/EfTimestampBug

    public class BaseModel
    {
        [Timestamp]
        public byte[] Timestamp { get; set; }
    }

    public class Person : BaseModel
    {
        public int Id { get; set; }

        public String Title { get; set; }
    }

    public class Context : DbContext
    {
        public Context()
        {}

        public Context(DbContextOptions options) : base(options)
        {}

        public DbSet<Person> Persons{ get; set; }
    }

    protected override void BuildModel(ModelBuilder modelBuilder)
    {
        modelBuilder
            .HasAnnotation("ProductVersion", "7.0.0-rc1-16348")
            .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

        modelBuilder.Entity("EFTimestampBug.Models.Person", b =>
            {
                b.Property<int>("Id")
                    .ValueGeneratedOnAdd();

                b.Property<byte[]>("Timestamp")
                    .IsConcurrencyToken()
                    .ValueGeneratedOnAddOrUpdate();

                b.Property<string>("Title");

                b.HasKey("Id");
            });
    }

    // PUT api/values/5
    [HttpPut("{id}")]
    public Person Put(int id, [FromBody]Person personDTO)
    {
        // 7
        var person = db.Persons.SingleOrDefault(x => x.Id == id);
        person.Title = personDTO.Title;
        person.Timestamp = personDTO.Timestamp;
        db.SaveChanges();
        return person;
    }

    [Fact]
    public async Task Fail_When_Timestamp_Differs()
    {
        using (var client = server.CreateClient().AcceptJson())
        {
            await client.PostAsJsonAsync(ApiEndpoint, Persons[0]);
            // 1
            var getResponse = await client.GetAsync(ApiEndpoint);
            var fetched = await getResponse.Content.ReadAsJsonAsync<List<Person>>();

            Assert.True(getResponse.IsSuccessStatusCode);
            Assert.NotEmpty(fetched);

            var person = fetched.First();
            // 2
            var fromDb = await db.Persons.SingleOrDefaultAsync(x => x.Id == person.Id);
            // 3
            fromDb.Title = "In between";
            // 4
            await db.SaveChangesAsync();

            // 5
            person.Title = "After - should fail";
            // 6
            var postResponse = await client.PutAsJsonAsync(ApiEndpoint + person.Id, person);
            var created = await postResponse.Content.ReadAsJsonAsync<Person>();

            Assert.False(postResponse.IsSuccessStatusCode);
        }
    }

    // generated sql - @p1 has the original timestamp from the entity and not the assigned and therefore the save succeed which was not intended
    exec sp_executesql N'SET NOCOUNT OFF;
    UPDATE[Person] SET[Title] = @p2
    OUTPUT INSERTED.[Timestamp]
    WHERE [Id] = @p0 AND[Timestamp] = @p1;
    ',N'@p0 int,@p1 varbinary(8),@p2 nvarchar(4000)',@p0=21,@p1=0x00000000000007F4,@p2=N'After - should fail'

Body:
Microsoft have updated their tutorial for this in Handling concurrency conflicts - EF Core with ASP.NET Core MVC tutorial. It specifically states the following regarding updates:

Before you call SaveChanges, you have to put that original
  RowVersion property value in the OriginalValues collection for the
  entity.

_context.Entry(entityToUpdate).Property("RowVersion").OriginalValue = rowVersion;

Then when the Entity Framework creates a SQL UPDATE command, that
  command will include a WHERE clause that looks for a row that has the
  original RowVersion value. If no rows are affected by the UPDATE
  command (no rows have the original RowVersion value), the Entity
  Framework throws a DbUpdateConcurrencyException exception.


问:
Are there any limitations for angular pipes?
In my application I am using pipe a couple of times.
my html code

And this is how my pipe looks like

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'highlightSearch',
  pure: false
})
export class HighlightSearchPipe implements PipeTransform {

  transform(value: any, args: any): any {
    // console.log('args', args);
    if (value && args && args.trim()) {
      console.log('args', args);
      return value.replace(new RegExp( '(' + args + ')', 'gi'), '<b>$1</b>');
    }
    return value;
  }

}
</code>```

And when I run my application, I could see several log statements in my console.
console log
This seems like I am not using the pipe in right approach. Could someone please shed light on this.

答:
Impure pipes are executed on each change detection, which could be bad for performance, depending on your page. If you can, always aim for pure pipes.

Pure pipes only execute when their input values change.

Body:
In my application I am using pipe a couple of times.
my html code

And this is how my pipe looks like

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'highlightSearch',
  pure: false
})
export class HighlightSearchPipe implements PipeTransform {

  transform(value: any, args: any): any {
    // console.log('args', args);
    if (value && args && args.trim()) {
      console.log('args', args);
      return value.replace(new RegExp( '(' + args + ')', 'gi'), '$1');
    }
    return value;
  }

}

And when I run my application, I could see several log statements in my console.
console log
This seems like I am not using the pipe in right approach. Could someone please shed light on this.


问:
Angular 2 equivalent of ng-bind-html, $sce.trustAsHTML(), and $compile?
In Angular 1.x, we could insert HTML in real-time by using the HTML tag ng-bind-html, combined with the JavaScript call $sce.trustAsHTML(). This got us 80% of th way there, but wouldn't work when Angular tags were used, such as if you inserted HTML that used ng-repeat or custom directives.

To get that to work, we could use a custom directive that called $compile.

What is the equivalent for all of this in Angular 2? We can bind using [inner-html] but this only works for very simple HTML tags such as . It doesn't transform custom angular 2 directives into functioning HTML elements. (Much like Angular 1.x without the $compile step.) What is the equivalent of $compile for Angular 2?

答:
Have a look at this module https://www.npmjs.com/package/ngx-dynamic-template

After a long research, only this thing helped me. The rest of the solutions seems to be outdated.


问:
Karma test paste event
I have a simple component that handle paste event into a form input.

The form:

```<code>this.searchForm = this.formBuilder.group({
  query: [ null, [Validators.required] ]
});

onPaste(event) {
    event.preventDefault();
    const formattedQuery = event.clipboardData.getData('text/plain')
      .split(/,?[\r\n\t]+\s?/)
      .join(', ')
      .replace(/,\s?$/g, '');

    this.searchForm.get('query').setValue(formattedQuery);
  }
</code>```

Now I am trying to test that and it looks like this:

```<code>it('should reformat pasted data', () => {
    const queryField = fixture.debugElement.query(By.css('input[type="search"]'));
    queryField.nativeElement.dispatchEvent(new ClipboardEvent('paste', {
      dataType: 'text/plain',
      data: '123\r123'
    }));
    fixture.detectChanges();
    expect(queryField.nativeElement.value).toBe('123, 123');
    // also tried expect(component.searchForm.get('query').value).toBe('123, 123');
  });
</code>```

But as a result i've got

```<code>Expected '' to be '123, 123'
</code>```

If i do console.log(queryField.nativeElement) it shows the input, but why it doesn't handle new ClipboardEvent('paste') event?

```<code><input class="ng-untouched ng-pristine ng-invalid" formcontrolname="query" type="search" ng-reflect-name="query">
</code>```

Full component you can find here https://stackblitz.com/edit/angular-cp9yhx?file=app%2Fhello.component.ts

What's wrong with my unit test?

答:
Try this:

```<code>it('should reformat pasted data', () => {
  component.onPaste(new ClipboardEvent('paste', {
    dataType: 'text/plain',
    data: '123\r123'
  }));
  expect(queryField.nativeElement.value).toBe('123, 123');
});
</code>```

Or even

```<code>it('should reformat pasted data', () => {
  component.onPaste(new ClipboardEvent('paste', {
    dataType: 'text/plain',
    data: '123\r123'
  }));
  expect(component.searchForm.get('query').value).toBe('123, 123');
});
</code>```

Title: Karma test paste event

Body:
I have a simple component that handle paste event into a form input.

The form:

this.searchForm = this.formBuilder.group({
  query: [ null, [Validators.required] ]
});

onPaste(event) {
    event.preventDefault();
    const formattedQuery = event.clipboardData.getData('text/plain')
      .split(/,?[\r\n\t]+\s?/)
      .join(', ')
      .replace(/,\s?$/g, '');

    this.searchForm.get('query').setValue(formattedQuery);
  }

Now I am trying to test that and it looks like this:

it('should reformat pasted data', () => {
    const queryField = fixture.debugElement.query(By.css('input[type="search"]'));
    queryField.nativeElement.dispatchEvent(new ClipboardEvent('paste', {
      dataType: 'text/plain',
      data: '123\r123'
    }));
    fixture.detectChanges();
    expect(queryField.nativeElement.value).toBe('123, 123');
    // also tried expect(component.searchForm.get('query').value).toBe('123, 123');
  });

But as a result i've got

Expected '' to be '123, 123'

If i do console.log(queryField.nativeElement) it shows the input, but why it doesn't handle new ClipboardEvent('paste') event?

<input class="ng-untouched ng-pristine ng-invalid" formcontrolname="query" type="search" ng-reflect-name="query">

Full component you can find here https://stackblitz.com/edit/angular-cp9yhx?file=app%2Fhello.component.ts

What's wrong with my unit test?

Body:
Try this:

it('should reformat pasted data', () => {
  component.onPaste(new ClipboardEvent('paste', {
    dataType: 'text/plain',
    data: '123\r123'
  }));
  expect(queryField.nativeElement.value).toBe('123, 123');
});

Or even

it('should reformat pasted data', () => {
  component.onPaste(new ClipboardEvent('paste', {
    dataType: 'text/plain',
    data: '123\r123'
  }));
  expect(component.searchForm.get('query').value).toBe('123, 123');
});


问:
Why is my image so high on the page?
I have two buttons on a webpage, I am trying to make the Clear button be a little lower, to align with the Search button.  Why is the Clear button so high?

Here is a live example: http://www.davidjpotter.com/temp/test.php

```<code><table border=1>
<tr>
<td>
  <button type="submit">Search</button>
  <img src="../images/button-clear.png">
</td>
</tr>
</table>
</code>```

答:
It's high because the default value of the vertical-align CSS property is baseline.  This applies to all elements with display: inline, which includes  elements.

Try instead setting it to middle:

```<code><img src="../images/button-clear.png" style="vertical-align:middle" />
</code>```

Title: Why is my image so high on the page?

Body:
I have two buttons on a webpage, I am trying to make the Clear button be a little lower, to align with the Search button.  Why is the Clear button so high?

Here is a live example: http://www.davidjpotter.com/temp/test.php

  <button type="submit">Search</button>

Body:
It's high because the default value of the vertical-align CSS property is baseline.  This applies to all elements with display: inline, which includes <img> elements.

Try instead setting it to middle:

<img src="../images/button-clear.png" style="vertical-align:middle" />