问:
Nginx - how to access Client Certificate's Subject Alternative Name (SAN) field
I have an Nginx server which clients make requests to with a Client certificate containing a specific CN and SAN. I want to be able to extract the CN (Common Name) and SAN (Subject Alternative Names) fields of that client cert.

rough example config:

```<code>server {
listen 443 ssl;
ssl_client_certificate /etc/nginx/certs/client.crt;
ssl_verify_client on; #400 if request without valid cert

location / {
    root    /usr/share/nginx/html;

}
location /auth_test {
    # do something with the CN and SAN.
    # tried these embedded vars so far, to no avail
    return 200 "
    $ssl_client_s_dn
    $ssl_server_name
    $ssl_client_escaped_cert
    $ssl_client_cert
    $ssl_client_raw_cert";
}
}
</code>```

Using the embedded variables exposed as part of the ngx_http_ssl_module module I can access the DN (Distinguished Name) and therefore CN etc but I don't seem to be able to get access to the SAN.

Is there some embedded var / other module / general Nginx foo I'm missing? I can access the raw cert, so is it possible to decode that manually and extract it?

I'd really rather do this at the Nginx layer as opposed to passing the cert down to the application layer and doing it there.

Any help much appreciated.

答:
I'm not a lua expert, but here's what I got working:</p>

```<code>local openssl = require('openssl')

dnsNames = {}
for k,v in pairs(openssl.x509.read(ngx.var.ssl_client_raw_cert):extensions()) do
    for k1,v1 in pairs(v:info()) do
        if(type(v1)=='table') then
            for k2,v2 in pairs(v1) do
                if(type(v2)=='table') then
                    for k3,v3 in pairs(v2) do
                        if(k3=='dNSName') then
                            table.insert(dnsNames, v3:toprint())
                        end
                    end
                end
            end
        end
    end
end
ngx.say(table.concat(dnsNames, ':'))
</code>```

Body:
I have an Nginx server which clients make requests to with a Client certificate containing a specific CN and SAN. I want to be able to extract the CN (Common Name) and SAN (Subject Alternative Names) fields of that client cert.

rough example config:

server {
listen 443 ssl;
ssl_client_certificate /etc/nginx/certs/client.crt;
ssl_verify_client on; #400 if request without valid cert

location / {
    root    /usr/share/nginx/html;

}
location /auth_test {
    # do something with the CN and SAN.
    # tried these embedded vars so far, to no avail
    return 200 "
    $ssl_client_s_dn
    $ssl_server_name
    $ssl_client_escaped_cert
    $ssl_client_cert
    $ssl_client_raw_cert";
}
}

Using the embedded variables exposed as part of the ngx_http_ssl_module module I can access the DN (Distinguished Name) and therefore CN etc but I don't seem to be able to get access to the SAN.

Is there some embedded var / other module / general Nginx foo I'm missing? I can access the raw cert, so is it possible to decode that manually and extract it?

I'd really rather do this at the Nginx layer as opposed to passing the cert down to the application layer and doing it there.

Any help much appreciated.

Body:
I'm not a lua expert, but here's what I got working:

local openssl = require('openssl')

dnsNames = {}
for k,v in pairs(openssl.x509.read(ngx.var.ssl_client_raw_cert):extensions()) do
    for k1,v1 in pairs(v:info()) do
        if(type(v1)=='table') then
            for k2,v2 in pairs(v1) do
                if(type(v2)=='table') then
                    for k3,v3 in pairs(v2) do
                        if(k3=='dNSName') then
                            table.insert(dnsNames, v3:toprint())
                        end
                    end
                end
            end
        end
    end
end
ngx.say(table.concat(dnsNames, ':'))


来源: stackexchange

问:
How to calculate the difference between consecutive sets of two columns in a column range using dplyr
I would like to calculate the difference between consecutive columns in a range of columns using dplyr.

For example, using the iris data set I would want to be able to specify the range Sepal.Width:Petal.Width and have a dataframe that contained the original iris data and the differences between the consecutive columns from Sepal.Width:Petal.Width:

```<code>  Sepal.Length Sepal.Width Petal.Length Petal.Width Species diff1 diff2
1          5.1         3.5          1.4         0.2  setosa   2.1   1.2
2          4.9         3.0          1.4         0.2  setosa   1.6   1.2
3          4.7         3.2          1.3         0.2  setosa   1.9   1.1
4          4.6         3.1          1.5         0.2  setosa   1.6   1.3
5          5.0         3.6          1.4         0.2  setosa   2.2   1.2
6          5.4         3.9          1.7         0.4  setosa   2.2   1.3
</code>```

Someone posted a solution loops and lapply (Calculate the difference between consecutive, grouped columns in a data.table) but I'm specifically looking for a dplyr solution.

答:
You could also use grepl and which to get the column indices..

```<code>start <- which(grepl("Sepal.Width", colnames(iris)))
end <- which(grepl("Petal.Width", colnames(iris)))

for (i in start:(end-1)) {
eval(parse(text = paste0("iris$diff",i-1," <- iris[,",i,"]-iris[,",i,"+1]")))
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to calculate the difference between consecutive columns in a range of columns using dplyr.

For example, using the iris data set I would want to be able to specify the range Sepal.Width:Petal.Width and have a dataframe that contained the original iris data and the differences between the consecutive columns from Sepal.Width:Petal.Width:

  Sepal.Length Sepal.Width Petal.Length Petal.Width Species diff1 diff2
1          5.1         3.5          1.4         0.2  setosa   2.1   1.2
2          4.9         3.0          1.4         0.2  setosa   1.6   1.2
3          4.7         3.2          1.3         0.2  setosa   1.9   1.1
4          4.6         3.1          1.5         0.2  setosa   1.6   1.3
5          5.0         3.6          1.4         0.2  setosa   2.2   1.2
6          5.4         3.9          1.7         0.4  setosa   2.2   1.3

Someone posted a solution loops and lapply (Calculate the difference between consecutive, grouped columns in a data.table) but I'm specifically looking for a dplyr solution.

Body:
You could also use grepl and which to get the column indices..

start <- which(grepl("Sepal.Width", colnames(iris)))
end <- which(grepl("Petal.Width", colnames(iris)))

for (i in start:(end-1)) {
eval(parse(text = paste0("iris$diff",i-1," <- iris[,",i,"]-iris[,",i,"+1]")))
}


问:
How to do an Ansible condition test of user/group existence?
As new nodes (CentOS 7.6) are added, there are basic groups and users that need to be created. Some of the nodes have some of the groups and users.  I would like to only create the groups and users on the nodes where they don't exist via my Ansible (version 2.8.0) basic role file.

Currently, I'm testing for the group/user, but the there's always a "fatal" printed and my conditionals don't appear to work.

roles/basic/tasks/main.yml

```<code>- name: "Does k8s group exist?"
  shell: grep -q "^k8s" /etc/group
  register: gexist

- name: "Create k8s group"
  shell: groupadd -g 8000 k8s
  when: gexist.rc != 0

- name: "Does k8s user exist?"
  shell: id -u k8s > /dev/null 2>&1
  register: uexist

- name: "Create k8s user"
  shell: useradd -g 8000 -d /home/k8s -s /bin/bash -u 8000 -m k8s
  when: uexist.rc != 0
</code>```

which yields:

```<code>TASK [basic : Does k8s group exist?] *****************************************************************************************************************************
fatal: [master]: FAILED! => {"changed": true, "cmd": "grep -q \"^k8s:\" /etc/group", "delta": "0:00:00.009424", "end": "2019-05-29 14:42:17.947350", "msg": "non-zero return code", "rc": 1, "start": "2019-05-29 14:42:17.937926", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
fatal: [node3]: FAILED! => {"changed": true, "cmd": "grep -q \"^k8s:\" /etc/group", "delta": "0:00:00.012089", "end": "2019-05-29 06:41:36.661356", "msg": "non-zero return code", "rc": 1, "start": "2019-05-29 06:41:36.649267", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
fatal: [node1]: FAILED! => {"changed": true, "cmd": "grep -q \"^k8s:\" /etc/group", "delta": "0:00:00.010104", "end": "2019-05-29 14:42:17.990460", "msg": "non-zero return code", "rc": 1, "start": "2019-05-29 14:42:17.980356", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
changed: [node2]
</code>```

There has got to be a better to do conditionals (if-then-else) than the way I'm doing it.

答:
See user and group. The code below is probably what you're looking for.

```<code>- name: "Create k8s group"
  group:
    gid: 8000
    name: k8s

- name: "Create k8s user"
  user:
    group: k8s
    home: /home/k8s
    shell: /bin/bash
    uid: 8000
    name: k8s
</code>```

The only if-then-else in Ansible I'm aware of is the ternary filter (for other options see jinja).  The control flow is rather poor in Ansible compared to other procedural languages. It's because of the code rather defines a state of the system then a procedure.

To answer your question:

How to do an Ansible condition test of user/group existence?

Your code does it correctly, but the purpose of Ansible is to define the state of the system. It's not important a user or group existed before or not. After successfully having run the code they will exist (definition of a state) and running the code again makes sure they still exist (audit).

Body:
As new nodes (CentOS 7.6) are added, there are basic groups and users that need to be created. Some of the nodes have some of the groups and users.  I would like to only create the groups and users on the nodes where they don't exist via my Ansible (version 2.8.0) basic role file.

Currently, I'm testing for the group/user, but the there's always a "fatal" printed and my conditionals don't appear to work.

roles/basic/tasks/main.yml

- name: "Does k8s group exist?"
  shell: grep -q "^k8s" /etc/group
  register: gexist

- name: "Create k8s group"
  shell: groupadd -g 8000 k8s
  when: gexist.rc != 0

- name: "Does k8s user exist?"
  shell: id -u k8s > /dev/null 2>&1
  register: uexist

- name: "Create k8s user"
  shell: useradd -g 8000 -d /home/k8s -s /bin/bash -u 8000 -m k8s
  when: uexist.rc != 0

which yields:

TASK [basic : Does k8s group exist?] *****************************************************************************************************************************
fatal: [master]: FAILED! => {"changed": true, "cmd": "grep -q \"^k8s:\" /etc/group", "delta": "0:00:00.009424", "end": "2019-05-29 14:42:17.947350", "msg": "non-zero return code", "rc": 1, "start": "2019-05-29 14:42:17.937926", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
fatal: [node3]: FAILED! => {"changed": true, "cmd": "grep -q \"^k8s:\" /etc/group", "delta": "0:00:00.012089", "end": "2019-05-29 06:41:36.661356", "msg": "non-zero return code", "rc": 1, "start": "2019-05-29 06:41:36.649267", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
fatal: [node1]: FAILED! => {"changed": true, "cmd": "grep -q \"^k8s:\" /etc/group", "delta": "0:00:00.010104", "end": "2019-05-29 14:42:17.990460", "msg": "non-zero return code", "rc": 1, "start": "2019-05-29 14:42:17.980356", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
changed: [node2]

There has got to be a better to do conditionals (if-then-else) than the way I'm doing it.

Body:
See user and group. The code below is probably what you're looking for.

- name: "Create k8s group"
  group:
    gid: 8000
    name: k8s

- name: "Create k8s user"
  user:
    group: k8s
    home: /home/k8s
    shell: /bin/bash
    uid: 8000
    name: k8s

The only if-then-else in Ansible I'm aware of is the ternary filter (for other options see jinja).  The control flow is rather poor in Ansible compared to other procedural languages. It's because of the code rather defines a state of the system then a procedure.

To answer your question:

How to do an Ansible condition test of user/group existence?

Your code does it correctly, but the purpose of Ansible is to define the state of the system. It's not important a user or group existed before or not. After successfully having run the code they will exist (definition of a state) and running the code again makes sure they still exist (audit).


问:
Hyperlink cell in Winforms DataGridView
I have a datagridview with the following data.

```<code>ContactType        |        Contact
------------------------------------
Phone              |       894356458
Email              |     xyz@abc.com
</code>```

Here, I need to display the data "xyz@abc.com" as a hyperlink, with a tooltip "Click to send email". The number data "894356458" should not have a hyperlink.

Any ideas???

TIA!

答:
You can change style of whole column in DataGridView. This is also a way to make column link column.</p>

```<code>DataGridViewCellStyle cellStyle = new DataGridViewCellStyle();
        cellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
        cellStyle.ForeColor = Color.LightBlue;
        cellStyle.SelectionForeColor = Color.Black;
        cellStyle.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Underline);
        dataGridView.Columns[1].DefaultCellStyle = cellStyle;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Hyperlink cell in Winforms DataGridView

Body:
I have a datagridview with the following data.

ContactType        |        Contact
------------------------------------
Phone              |       894356458
Email              |     xyz@abc.com

Here, I need to display the data "xyz@abc.com" as a hyperlink, with a tooltip "Click to send email". The number data "894356458" should not have a hyperlink.

Any ideas???

TIA!

Body:
You can change style of whole column in DataGridView. This is also a way to make column link column.

DataGridViewCellStyle cellStyle = new DataGridViewCellStyle();
        cellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
        cellStyle.ForeColor = Color.LightBlue;
        cellStyle.SelectionForeColor = Color.Black;
        cellStyle.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Underline);
        dataGridView.Columns[1].DefaultCellStyle = cellStyle;


问:
Centre a Navigation Bar with HTML/CSS
I have no formal training in HTML and CSS, but web development is a hobby of mine, and I have a problem that I am really struggling to get for my personal website.  Here:

You can see that the elements of my unordered list are not centred on the black unordered list background; in the body tag:

```<code>        <ul>
            <li><a href="homepage.html">Home</a></li>
            <li><a href="resume.html">Bio</a></li>
            <li><a href="projects.html">Projects</a></li>
            <li><a href="blog.html">Blog</a></li>
            <li><a href="store.html">Store</a></li>
            <li><a href="contact.html">Contact</a></li>
        </ul>
</code>```

Previously, in the head tag, I declare the style for each of these elements in the document, and what to do if the cursor hovers over it:

```<code>    <style>
        ul {
            list-style-type: none;
            background-color: black;
            margin: 0;
            padding: 0;
            overflow: hidden;
        }
        li {
            float: left;
        }
        li a {
            display: block;
            color: white;
            text-align: center;
            border-width: thick;
            padding: 14px 16px;
            text-decoration: none;
        }
        li a:hover {
            background-color: darkgray;
        }
    </style>
</code>```

The concept I've tried more times than not is if you have a div tag around li and you centre that.  But, I am going in circles.  So how do you centre the white lettering while keeping an equal amount of black space on either side?  Thank you very much!

For reference, I have branched out from this tutorial.

答:
You can use flexbox with justify-content: center;

For example

```<code>ul {
    list-style-type: none;
    background-color: black;
    margin: 0;
    padding: 0;
    overflow: hidden;
    display: flex;
    justify-content: center;
}
</code>```

Title: Centre a Navigation Bar with HTML/CSS

Body:
I have no formal training in HTML and CSS, but web development is a hobby of mine, and I have a problem that I am really struggling to get for my personal website.  Here:

You can see that the elements of my unordered list are not centred on the black unordered list background; in the body tag:

Home

Bio

Projects

Blog

Store

Contact

Previously, in the head tag, I declare the style for each of these elements in the document, and what to do if the cursor hovers over it:

The concept I've tried more times than not is if you have a div tag around li and you centre that.  But, I am going in circles.  So how do you centre the white lettering while keeping an equal amount of black space on either side?  Thank you very much!

For reference, I have branched out from this tutorial.

Body:
You can use flexbox with justify-content: center;

For example

ul {
    list-style-type: none;
    background-color: black;
    margin: 0;
    padding: 0;
    overflow: hidden;
    display: flex;
    justify-content: center;
}


答:
By default, ul and li are display: block;. In order to achieve your result you need to wrap your list in a centered div and set the background color on the div.

Add a wrapper to your HTML

```<code><div class="wrapper">
    <ul>
        <li><a href="homepage.html">Home</a></li>
        <li><a href="resume.html">Bio</a></li>
        <li><a href="projects.html">Projects</a></li>
        <li><a href="blog.html">Blog</a></li>
        <li><a href="store.html">Store</a></li>
        <li><a href="contact.html">Contact</a></li>
    </ul>
</div>
</code>```

Then, in your CSS

```<code>.wrapper {
    background-color: black;
    text-align: center;
}

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    display: inline-block;
}
</code>```

Title: Centre a Navigation Bar with HTML/CSS

Body:
By default, ul and li are display: block;. In order to achieve your result you need to wrap your list in a centered div and set the background color on the div.

Add a wrapper to your HTML

<div class="wrapper">
    <ul>
        <li><a href="homepage.html">Home</a></li>
        <li><a href="resume.html">Bio</a></li>
        <li><a href="projects.html">Projects</a></li>
        <li><a href="blog.html">Blog</a></li>
        <li><a href="store.html">Store</a></li>
        <li><a href="contact.html">Contact</a></li>
    </ul>
</div>

Then, in your CSS

.wrapper {
    background-color: black;
    text-align: center;
}

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    display: inline-block;
}


问:
Karate DSL pulling out brackets when passed as json params
I'm trying to pass some json data as params in a feature. The request is failing because it looks like Karate is removing the brackets from the string I'm passing in. Once it make the request, I can see the brackets specifically after the "list" element is gone. If I take the encoded request that karate makes and manually add the brackets where they should be, it works fine.

We could try passing it in a couple other ways, but I'm trying to understand why it's changing what would work to something that won't.

This is what it looks like as the raw json being passed in.

```<code>"start": "1557943276102",
  "end": "1559152876102",
  "page": 1,
  "user": "0000000000000001",
  "list": [              <---- this bracket gets stripped
    {
      "field1": [
        "field2",
        "field3",
        "field4"
      ],
      "field5": "123456"
    }
  ],                     <---- this bracket gets stripped
  "authToken": "theauthtoken"
}
</code>```

Then setting it to params like
* params jsonData

My request fails, where if the brackets remained intact the request works.

答:
In the case of params an array means repeated values, which is common in real-life, see params.feature. If you really want a bracket, use a string value:

```<code>"list": '[{"field1":["field2","field3","field4"],"field5":"123456"}]'
</code>```

Body:
I'm trying to pass some json data as params in a feature. The request is failing because it looks like Karate is removing the brackets from the string I'm passing in. Once it make the request, I can see the brackets specifically after the "list" element is gone. If I take the encoded request that karate makes and manually add the brackets where they should be, it works fine.

We could try passing it in a couple other ways, but I'm trying to understand why it's changing what would work to something that won't.

This is what it looks like as the raw json being passed in.

"start": "1557943276102",
  "end": "1559152876102",
  "page": 1,
  "user": "0000000000000001",
  "list": [              <---- this bracket gets stripped
    {
      "field1": [
        "field2",
        "field3",
        "field4"
      ],
      "field5": "123456"
    }
  ],                     <---- this bracket gets stripped
  "authToken": "theauthtoken"
}

Then setting it to params like
* params jsonData

My request fails, where if the brackets remained intact the request works.

Body:
In the case of params an array means repeated values, which is common in real-life, see params.feature. If you really want a bracket, use a string value:

"list": '[{"field1":["field2","field3","field4"],"field5":"123456"}]'


问:
How does function.apply.bind work in the following code?
So I get that an array of [200,599] is returned from the promise and the callback function inside spread is being passed into Function.apply.bind, but now I'm lost. How is the array of [200,599] split into x and y? How exactly does the apply.bind work?</p>

```<code>function getY(x) {
        return new Promise( function(resolve,reject){
            setTimeout( function(){
                resolve( (3 * x) - 1 );
            }, 100 );
        } );
    }

function foo(bar,baz) {
    var x = bar * baz;

    // return both promises
    return [
        Promise.resolve( x ),
        getY( x )
    ];
}

function spread(fn) {
    return Function.apply.bind( fn, null );
}

Promise.all(
    foo( 10, 20 )
)
.then(
    spread( function(x,y){
        console.log( x, y );    // 200 599
    } )
)
</code>```

答:
The reason it works is the "destructuring" nature of apply (if given an array of values, they would be provided spreaded to the function you use apply on).

Now back to your code when calling bind on apply, the value returned is a function which returns the same function provided to bind, the only thing different is when executed it would be called using apply (with an array as thisArg in your case), but it isn't going to be executed until you call it.
In your case when the promise has resolved, the function provided tothen woule be executed with an array of arguments provided by Promise resolution.

function spread(fn){
   let boundedFn = fn.bind(fn)

   return function(arg){
      return boundedFn.apply(null,arg)
   }
}

spread((x, y, c) => console.log(x, y, c))([1,2,3])

// or

Promise.resolve([6, 5]).then(spread((a, b) => console.log(a, b)))```

The reason bind is provided (in your code) with null as second param is to prevent the array provided by the caller from being given to apply as its first param, which reserved for this.

Body:
So I get that an array of [200,599] is returned from the promise and the callback function inside spread is being passed into Function.apply.bind, but now I'm lost. How is the array of [200,599] split into x and y? How exactly does the apply.bind work?

function getY(x) {
        return new Promise( function(resolve,reject){
            setTimeout( function(){
                resolve( (3 * x) - 1 );
            }, 100 );
        } );
    }

function foo(bar,baz) {
    var x = bar * baz;

    // return both promises
    return [
        Promise.resolve( x ),
        getY( x )
    ];
}

function spread(fn) {
    return Function.apply.bind( fn, null );
}

Promise.all(
    foo( 10, 20 )
)
.then(
    spread( function(x,y){
        console.log( x, y );    // 200 599
    } )
)

Body:
The reason it works is the "destructuring" nature of apply (if given an array of values, they would be provided spreaded to the function you use apply on).

Now back to your code when calling bind on apply, the value returned is a function which returns the same function provided to bind, the only thing different is when executed it would be called using apply (with an array as thisArg in your case), but it isn't going to be executed until you call it.
In your case when the promise has resolved, the function provided tothen woule be executed with an array of arguments provided by Promise resolution.

function spread(fn){
   let boundedFn = fn.bind(fn)

   return function(arg){
      return boundedFn.apply(null,arg)
   }
}

spread((x, y, c) => console.log(x, y, c))([1,2,3])

// or

Promise.resolve([6, 5]).then(spread((a, b) => console.log(a, b)))

The reason bind is provided (in your code) with null as second param is to prevent the array provided by the caller from being given to apply as its first param, which reserved for this.


问:
EF 6.1 Fluent API: Ignore property of the base class
I have a base class for all entities:

```<code>public class BaseClass
{
    public int SomeProperty {get; set;}
}

public class SomeEntity : BaseClass
{
    ...
}
</code>```

I want to ignore this property in some cases. Could I do in the OnModelCreating method something like this:

```<code>public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Properties<int>()
                    .Where(p => p.Name == "SomeProperty")
                    .Ignore();
}
</code>```

?

答:
Could you override it?</p>

```<code>public class SomeEntity : BaseClass
{
    [NotMapped]
    public override int SomeProperty { get; set; }
    ...
}
</code>```

Body:
I have a base class for all entities:

public class BaseClass
{
    public int SomeProperty {get; set;}
}

public class SomeEntity : BaseClass
{
    ...
}

I want to ignore this property in some cases. Could I do in the OnModelCreating method something like this:

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Properties<int>()
                    .Where(p => p.Name == "SomeProperty")
                    .Ignore();
}

?

Body:
Could you override it?

public class SomeEntity : BaseClass
{
    [NotMapped]
    public override int SomeProperty { get; set; }
    ...
}


问:
R: weighted inverse document frequency (tfidf) similarity between strings
I want to be able to find similarity between two strings, weighting each token (word) with its inverse document frequency (those frequencies are not taken from those strings).

Using quanteda I can create a dfm_tfidf with inverted frequency weights, but do not know how to proceed after that.

Sample data :

ss = c(
        "ibm madrid limited research",
        "madrid limited research",
        "limited research",
        "research"
    )
counts = list(ibm = 1, madrid = 2, limited = 3, research = 4)
cor = corpus(long_list_of_strings)  ## the documents where we take words from
df = dfm(cor, tolower = T, verbose = T)
dfi = dfm_tfidf(df)
```

<p>The goal is to find a function <code>similarity</code> that will make:</p>

<pre class="lang-r prettyprint-override"><code>res = similarity(dfi, "ibm limited", similarity_scheme = "simple matching")
</code>```

with res in the form (random numbers for the example):

```<code>"ibm madrid limited research"  0.445
"madrid limited research" 0.2
"limited research" 0.76
"research" 0.45
</code>```

Ideally would be to apply to those frequencies a function like :

```<code>sim = sum(Wc) / sqrt(sum(Wi)*sum(Wj))
</code>```

where:
Wc are the weights of words common to the two strings.

Wi and Wj are the weights of words in string1 and string2.

答:
You want the textstat_simil() function from quanteda.  You should add the document to be targeted into the corpus, and then use the selection argument to focus on that.  "simple matching" is implemented as one of the similarity methods, but you should be aware that this looks for the presence or absence of terms, so tf-idf weighting will not affect this.

library("quanteda")
## Package version: 1.4.3
##
ss <- c(
  "ibm limited",
  "ibm madrid limited research",
  "madrid limited research",
  "limited research",
  "research"
)
ssdfm <- dfm(ss)
ssdfm
## Document-feature matrix of: 5 documents, 4 features (40.0% sparse).
## 5 x 4 sparse Matrix of class "dfm"
##        features
## docs    ibm limited madrid research
##   text1   1       1      0        0
##   text2   1       1      1        1
##   text3   0       1      1        1
##   text4   0       1      0        1
##   text5   0       0      0        1
dfm_tfidf(ssdfm)
## Document-feature matrix of: 5 documents, 4 features (40.0% sparse).
## 5 x 4 sparse Matrix of class "dfm"
##        features
## docs        ibm    limited  madrid   research
##   text1 0.39794 0.09691001 0       0
##   text2 0.39794 0.09691001 0.39794 0.09691001
##   text3 0       0.09691001 0.39794 0.09691001
##   text4 0       0.09691001 0       0.09691001
##   text5 0       0          0       0.09691001
```

<p>Here, you can see that the result is unaffected by the tf-idf weighting:</p>

<pre class="lang-r prettyprint-override"><code>dfm_tfidf(ssdfm) %>%
  textstat_simil(method = "simple matching", selection = "text1") %>%
  as.matrix()
##       text1
## text1  1.00
## text2  0.50
## text3  0.25
## text4  0.50
## text5  0.25

ssdfm %>%
  textstat_simil(method = "simple matching", selection = "text1") %>%
  as.matrix()
##       text1
## text1  1.00
## text2  0.50
## text3  0.25
## text4  0.50
## text5  0.25
</code>```

Body:
I want to be able to find similarity between two strings, weighting each token (word) with its inverse document frequency (those frequencies are not taken from those strings).

Using quanteda I can create a dfm_tfidf with inverted frequency weights, but do not know how to proceed after that.

Sample data :

ss = c(
        "ibm madrid limited research",
        "madrid limited research",
        "limited research",
        "research"
    )
counts = list(ibm = 1, madrid = 2, limited = 3, research = 4)
cor = corpus(long_list_of_strings)  ## the documents where we take words from
df = dfm(cor, tolower = T, verbose = T)
dfi = dfm_tfidf(df)

The goal is to find a function similarity that will make:

res = similarity(dfi, "ibm limited", similarity_scheme = "simple matching")

with res in the form (random numbers for the example):

"ibm madrid limited research"  0.445
"madrid limited research" 0.2
"limited research" 0.76
"research" 0.45

Ideally would be to apply to those frequencies a function like :

sim = sum(Wc) / sqrt(sum(Wi)*sum(Wj))

where:
Wc are the weights of words common to the two strings.

Wi and Wj are the weights of words in string1 and string2.

Body:
You want the textstat_simil() function from quanteda.  You should add the document to be targeted into the corpus, and then use the selection argument to focus on that.  "simple matching" is implemented as one of the similarity methods, but you should be aware that this looks for the presence or absence of terms, so tf-idf weighting will not affect this.

library("quanteda")
## Package version: 1.4.3
##
ss <- c(
  "ibm limited",
  "ibm madrid limited research",
  "madrid limited research",
  "limited research",
  "research"
)
ssdfm <- dfm(ss)
ssdfm
## Document-feature matrix of: 5 documents, 4 features (40.0% sparse).
## 5 x 4 sparse Matrix of class "dfm"
##        features
## docs    ibm limited madrid research
##   text1   1       1      0        0
##   text2   1       1      1        1
##   text3   0       1      1        1
##   text4   0       1      0        1
##   text5   0       0      0        1
dfm_tfidf(ssdfm)
## Document-feature matrix of: 5 documents, 4 features (40.0% sparse).
## 5 x 4 sparse Matrix of class "dfm"
##        features
## docs        ibm    limited  madrid   research
##   text1 0.39794 0.09691001 0       0
##   text2 0.39794 0.09691001 0.39794 0.09691001
##   text3 0       0.09691001 0.39794 0.09691001
##   text4 0       0.09691001 0       0.09691001
##   text5 0       0          0       0.09691001

Here, you can see that the result is unaffected by the tf-idf weighting:

dfm_tfidf(ssdfm) %>%
  textstat_simil(method = "simple matching", selection = "text1") %>%
  as.matrix()
##       text1
## text1  1.00
## text2  0.50
## text3  0.25
## text4  0.50
## text5  0.25

ssdfm %>%
  textstat_simil(method = "simple matching", selection = "text1") %>%
  as.matrix()
##       text1
## text1  1.00
## text2  0.50
## text3  0.25
## text4  0.50
## text5  0.25


问:
how to get a filename in HTML and use it in D3.js (javascript)?
I've written a d3 script that plots some data and in which the path to the input file is hard coded.

I'd like to be able to select the file by browsing on my computer and then passing it to the script.

```<code><body>

<!--locally browse to get the filename-->
<input type="file" id="input">

<script src="http://d3js.org/d3.v3.js"></script>
<script>

// Get the data
d3.tsv("#input", function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});

// then the code that plots etc....
</script>

</html>
</code>```

答:
You can use d3.csvParse to parse the result after reading file. Here's my working code:

```<code><input type="file" id="input" onchange="handleFiles">

<script>
const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);

function handleFiles() {
    const fileList = this.files; /* now you can work with the file list */
    var file = fileList[0];
    var reader = new FileReader();
    reader.onload = function(e) {
        // The file's text will be printed here
        console.log(e.target.result);
        console.log(d3.csvParse(e.target.result));
    };
    reader.readAsText(file);
}
</code>```

Body:
I've written a d3 script that plots some data and in which the path to the input file is hard coded.

I'd like to be able to select the file by browsing on my computer and then passing it to the script.

<input type="file" id="input">

Body:
You can use d3.csvParse to parse the result after reading file. Here's my working code:

<input type="file" id="input" onchange="handleFiles">

<script>
const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);

function handleFiles() {
    const fileList = this.files; /* now you can work with the file list */
    var file = fileList[0];
    var reader = new FileReader();
    reader.onload = function(e) {
        // The file's text will be printed here
        console.log(e.target.result);
        console.log(d3.csvParse(e.target.result));
    };
    reader.readAsText(file);
}


问:
NoSuchTableException being thrown from dbunit test cases
I'm trying to fix the test suite on an project which I've inherited from another programmer for some java database code.  The project itself is using hibernate and MySQL for the DB stuff, but for the purposes of the test cases dbunit is being used.  I can correctly load and initialize hibernate's session factory, but I keep getting exceptions when I try to run my tests in Eclipse, namely "org.dbunit.dataset.NoSuchTableException: mytablename".

I know that all the files are in the right place, and that the actual XML file I'm passing into dbunit is ok (I'm using the FlatXmlDataSet type).  My setUp() method in the database test case base class looks like this:

```<code>@Override
protected void setUp() throws Exception {
    super.setUp();
    IDataSet dataSet = new FlatXmlDataSet(new File(mDataFile));

    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();

    IDatabaseConnection connection = new DatabaseConnection(session.connection());

    DatabaseConfig config = connection.getConfig();
    config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new HsqldbDataTypeFactory());

    DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet);

    session.getTransaction().commit();
}
</code>```

Right after the CLEAN_INSERT database operation, the exception gets thrown complaining about the last table in my XML file, regardless of which table this is.  I have verified the DTD and XML schema by hand and with Eclipse, even going to the point of making sure the ordering of the tables in the two files matched.  I'd rather not paste those files in here (as it would involve a lot of search-replacing), but trust me that I've looked through dbunit examples and made sure that the syntax matches.

Any ideas on what could be wrong?  I've been googling for hours and can't come up with anything useful.

Edit: One thing I forgot to mention, is that when I place a breakpoint at the line which throws, I can look through dataSet's structure and see that all of my tables are actually in there, along with all of the test data.  So at least that part seems to be working correctly.

@Bogdan: Hrm... good idea.  I'll try loading the data with a regular INSERT.
@sleske: Also a good suggestion.  Thanks for the hints; hopefully this will set me on the right path to fixing this problem.

答:
The DatabaseOperation.CLEAN_INSERT is essentially a combination of DatabaseOperation.DELETE_ALL and DatabaseOperation.INSERT. Since the DatabaseOperation.DELETE_ALL clears the tables in reversed order, I suspect that it does not fail when clearing the last table, but when clearing the first one.

Are you sure that the tables from your data set actually exist in the database you are using while testing? The error you are getting would suggest that they don't.

OwnerDisplayName: sqook

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to fix the test suite on an project which I've inherited from another programmer for some java database code.  The project itself is using hibernate and MySQL for the DB stuff, but for the purposes of the test cases dbunit is being used.  I can correctly load and initialize hibernate's session factory, but I keep getting exceptions when I try to run my tests in Eclipse, namely "org.dbunit.dataset.NoSuchTableException: mytablename".

I know that all the files are in the right place, and that the actual XML file I'm passing into dbunit is ok (I'm using the FlatXmlDataSet type).  My setUp() method in the database test case base class looks like this:

@Override
protected void setUp() throws Exception {
    super.setUp();
    IDataSet dataSet = new FlatXmlDataSet(new File(mDataFile));

    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();

    IDatabaseConnection connection = new DatabaseConnection(session.connection());

    DatabaseConfig config = connection.getConfig();
    config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new HsqldbDataTypeFactory());

    DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet);

    session.getTransaction().commit();
}

Right after the CLEAN_INSERT database operation, the exception gets thrown complaining about the last table in my XML file, regardless of which table this is.  I have verified the DTD and XML schema by hand and with Eclipse, even going to the point of making sure the ordering of the tables in the two files matched.  I'd rather not paste those files in here (as it would involve a lot of search-replacing), but trust me that I've looked through dbunit examples and made sure that the syntax matches.

Any ideas on what could be wrong?  I've been googling for hours and can't come up with anything useful.

Edit: One thing I forgot to mention, is that when I place a breakpoint at the line which throws, I can look through dataSet's structure and see that all of my tables are actually in there, along with all of the test data.  So at least that part seems to be working correctly.

@Bogdan: Hrm... good idea.  I'll try loading the data with a regular INSERT.
@sleske: Also a good suggestion.  Thanks for the hints; hopefully this will set me on the right path to fixing this problem.

LastEditorDisplayName: sqook

OwnerDisplayName: Bogdan


问:
How to increment a MySQL timestamp in PHP?
So I have a MYSQL timestampl that is generating values that are 4hours ahead of what they should be. How would i subtract 4hrs from the MySQL time stamp and display that?

Here's my current code

```<code>$mdate = date('F j, Y, g:i a',strtotime( $bm->date_added));
//$bm->dated_added returns the times stamp//
echo $mdate;
</code>```

Thanks

答:
You should really figure out the root problem and fix it. Most likely you need to set MySQL's timezone to fit your own (or the server itself has the wrong date set).

That said, you can just subtract 14,400 seconds from the strtotime result.

```<code>$mdate = date('F j, Y, g:i a',strtotime($bm->date_added) - 14400);
</code>```

Body:
So I have a MYSQL timestampl that is generating values that are 4hours ahead of what they should be. How would i subtract 4hrs from the MySQL time stamp and display that?

Here's my current code

$mdate = date('F j, Y, g:i a',strtotime( $bm->date_added));
//$bm->dated_added returns the times stamp//
echo $mdate;

Thanks

Body:
You should really figure out the root problem and fix it. Most likely you need to set MySQL's timezone to fit your own (or the server itself has the wrong date set).

That said, you can just subtract 14,400 seconds from the strtotime result.

$mdate = date('F j, Y, g:i a',strtotime($bm->date_added) - 14400);


问:
In Azure, how can you configure an alert or notification when a SQL Server failover happened?
In Azure, how can you configure an alert or notification when a SQL Server failover happened if you setup a SQL server with Failover groups and failover policy is set to automatic? If it can't be setup in Monitor can it be scripted elsewhere?</p>

答:
Found a way to script this in Azure using Automation Accounts > Runbook > using Powershell. A simple script like this should do it. Just need to figure out the run as account and trigger it by schedule or alert.  </p>

```<code>function sendEmailAlert
{
    # Send email
}

function checkFailover
{
    $list = Get-AzSqlDatabaseFailoverGroup -ResourceGroupName "my-resourceGroup" -server "my-sql-server"

    if ( $list.ReplicationRole -ne 'Primary')
    {
        sendEmailAlert
    }
}

checkFailover
</code>```

Body:
Found a way to script this in Azure using Automation Accounts > Runbook > using Powershell. A simple script like this should do it. Just need to figure out the run as account and trigger it by schedule or alert.

function sendEmailAlert
{
    # Send email
}

function checkFailover
{
    $list = Get-AzSqlDatabaseFailoverGroup -ResourceGroupName "my-resourceGroup" -server "my-sql-server"

    if ( $list.ReplicationRole -ne 'Primary')
    {
        sendEmailAlert
    }
}

checkFailover


问:
Angular 6 pass data to component on router menu click
I have a navmenu component as under:

```<code>     <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown"><span class='glyphicon glyphicon-wrench'></span> Configuration<span class="caret"></span></a>
        <ul class="dropdown-menu" role="menu">
            <li class="dropdown-header">Options</li>
            <li [routerLinkActive]="['link-active']">
                <a [routerLink]="['config']" [queryParams]="{optionFilter: 'LOB' }">
                    <span class='glyphicon glyphicon-arrow-right'></span> Line of Business
                </a>
            </li>
            <li [routerLinkActive]="['link-active']">
                <a [routerLink]="['config']" [queryParams]="{optionFilter: 'RG' }">
                    <span class='glyphicon glyphicon-arrow-right'></span> Report Groups
                </a>
            </li>
        </ul>
    </li>
</code>```

There are dropdown menus under Configuration. All menus lead to the same component 'config'. However, based on the routerLink selected I need to write logic. How can I pass the param 'Line of Business', or 'Report Group' to the config component and retrieve in ngOnInit?

答:
Passed queryparams as suggested by mbojko, and retrieved in the component as under:</p>

```<code>//import router in component
import { ActivatedRoute} from '@angular/router';

//constructor:
    constructor(
        private _route: ActivatedRoute) { }
 ngOnInit() {
        this._route
            .queryParams
            .subscribe(params => {
                this.FilterOption = params['optionFilter'];
                console.log('menu click', params['optionFilter']);
            });
}
</code>```

Body:
I have a navmenu component as under:

         Configuration

Options

                     Line of Business

                     Report Groups

There are dropdown menus under Configuration. All menus lead to the same component 'config'. However, based on the routerLink selected I need to write logic. How can I pass the param 'Line of Business', or 'Report Group' to the config component and retrieve in ngOnInit?

Body:
Passed queryparams as suggested by mbojko, and retrieved in the component as under:

//import router in component
import { ActivatedRoute} from '@angular/router';

//constructor:
    constructor(
        private _route: ActivatedRoute) { }
 ngOnInit() {
        this._route
            .queryParams
            .subscribe(params => {
                this.FilterOption = params['optionFilter'];
                console.log('menu click', params['optionFilter']);
            });
}


问:
How do I use shell script to check if a bucket exists?
I have aws cli installed. I'm just not sure how to do this in shell script.

when I run command aws s3 ls s3://bucket it would give me something like this

A client error (NoSuchBucket) occurred when calling the ListObjects operation: The specified bucket does not exist

That means the bucket doesn't exist. So I want to run that from shell script and check if grep finds it. But my command doesn't work.

```<code>if [ $(aws s3 ls "s3://$S3_BUCKET" | grep 'NoSuchBucket' &> /dev/null) == 0 ]
then
    echo "$S3_BUCKET doesn\'t exist please check again"
    exit
fi
</code>```

It just gave me this

backup.sh: 20: [: 0: unexpected operator

Updated

I changed the script to be

```<code>echo "S3_BUCKET=$S3_BUCKET"
if aws s3 ls "s3://$S3_BUCKET" | grep -q 'AllAccessDisabled'
then
    echo "$S3_BUCKET doesn\'t exist please check again"
    exit
fi
</code>```

And this is the output I got

```<code>A client error (AllAccessDisabled) occurred when calling the ListObjects operation: All access to this object has been disabled
</code>```

So the text contains AllAccessDisabled but I still don't the echo the next line.

答:
```<code>#!/bin/bash

if [[ -z $(aws s3api head-bucket --bucket my-bucket 2>&1) ]]; then
        echo "bucket exists"
else
        echo "bucket does not exist or permission is not there to view it."
fi
</code>```

Body:
I have aws cli installed. I'm just not sure how to do this in shell script.

when I run command aws s3 ls s3://bucket it would give me something like this

A client error (NoSuchBucket) occurred when calling the ListObjects operation: The specified bucket does not exist

That means the bucket doesn't exist. So I want to run that from shell script and check if grep finds it. But my command doesn't work.

if [ $(aws s3 ls "s3://$S3_BUCKET" | grep 'NoSuchBucket' &> /dev/null) == 0 ]
then
    echo "$S3_BUCKET doesn\'t exist please check again"
    exit
fi

It just gave me this

backup.sh: 20: [: 0: unexpected operator

Updated

I changed the script to be

echo "S3_BUCKET=$S3_BUCKET"
if aws s3 ls "s3://$S3_BUCKET" | grep -q 'AllAccessDisabled'
then
    echo "$S3_BUCKET doesn\'t exist please check again"
    exit
fi

And this is the output I got

A client error (AllAccessDisabled) occurred when calling the ListObjects operation: All access to this object has been disabled

So the text contains AllAccessDisabled but I still don't the echo the next line.


问:
Real-time conditional rendering in react-native
I am trying to figure out how to render a component based on a bool. But the user will also have the option to change the bool and I need the app to update in real-time.

For simplicity at the moment I am trying to render some text only:

```<code>const deposit = <Text>deposit</Text>
const noDeposit = <Text>noDeposit</Text>
</code>```

And this is my view where I want to render it:

```<code><View>
  {this.props.depositRequired ? deposit : noDeposit}
</View>
</code>```

It works with displaying one of them when the app is first started. But it never updates and I'm kind of at a loss of how to do this. Any help is much appreciated!

答:
Try to use lifecycle method for receiving props called componentWillReceiveProps to make the component update. Implement it like this:

```<code>  componentWillReceiveProps(nextProps){
  if(nextProps.depositRequired !== this.props.depositRequired){
    // just call to update the component
    this.setState({})
  }
}
</code>```

Body:
I am trying to figure out how to render a component based on a bool. But the user will also have the option to change the bool and I need the app to update in real-time.

For simplicity at the moment I am trying to render some text only:

const deposit = <Text>deposit</Text>
const noDeposit = <Text>noDeposit</Text>

And this is my view where I want to render it:

<View>
  {this.props.depositRequired ? deposit : noDeposit}
</View>

It works with displaying one of them when the app is first started. But it never updates and I'm kind of at a loss of how to do this. Any help is much appreciated!

Body:
Try to use lifecycle method for receiving props called componentWillReceiveProps to make the component update. Implement it like this:

  componentWillReceiveProps(nextProps){
  if(nextProps.depositRequired !== this.props.depositRequired){
    // just call to update the component
    this.setState({})
  }
}


问:
Method to monitor requests that come towards Keycloak server
I'm trying to understand the functionalities of Keycloak and trying to find a way to monitor request flows (like in Wireshark) in a local environment (localhost). What tool could I use for this purpose in a Windows environment? I've got an Angular app that is integrated with Keycloak, and it works. When I request localhost:4200, the browser takes me to Keycloak login screen.

To view logs, I changed the log level in the Keycloak server at ..\keycloak-4.8.3.Final\standalone\configuration from INFO to ALL. It did expand the log entries that showed in the console but it didn't show any logs when my angular application redirects to Keycloak and when I enter user credentials in  Keycloak login screen.

I would like to see the request flow from browser to Keycloak and all the auth requests and so on. Is there a tool that I could use for this purpose?

答:
another way to get the event is from the </p>

```<code>Keycloak keycloak = KeycloakBuilder.builder()
            .serverUrl("localhost")
            .realm("myRealm")
            .grantType(OAuth2Constants.PASSWORD)
            .clientId("myclient")
            .clientSecret("xxxx-xxxxx-xxxx-xxx")
            .username("foo")//the admin user
            .password("password")
            .build();

List<EventRepresentation> events = keycloak.realm("myRealm").getEvents();
</code>```

<p>then you choose the type of event you want to target </p>

Body:
another way to get the event is from the

Keycloak keycloak = KeycloakBuilder.builder()
            .serverUrl("localhost")
            .realm("myRealm")
            .grantType(OAuth2Constants.PASSWORD)
            .clientId("myclient")
            .clientSecret("xxxx-xxxxx-xxxx-xxx")
            .username("foo")//the admin user
            .password("password")
            .build();

List<EventRepresentation> events = keycloak.realm("myRealm").getEvents();

then you choose the type of event you want to target


问:
page scraping to get prices from google finance
I am trying to get stock prices by scraping google finance pages, I am doing this in python, using urllib package and then using regex to get price data.

When I leave my python script running, it works initially for some time (few minutes) and then starts throwing exception [HTTP Error 503: Service Unavailable]

I guess this is happening because on web server side it detects frequent page updates as a robot and throws this exception after a while..

is there a way around this, i.e. deleting some cookie or creating some cookie etc..

or even better if google gives some api, I want to do this in python because the complete app in python, but if there is nothing available in python to do this, I can consider alternatives. This is my python method that I use in loop to get data ( with few seconds of sleep I call this method in loop)

```<code> def getPriceFromGOOGLE(self, symbol):
    """
    gets last traded price from google for given security
    """
    toReturn = 0.0
    try:
        base_url = 'http://google.com/finance?q='
        req = urllib2.Request(base_url + symbol)
        content = urllib2.urlopen(req).read()
        namestr = 'name:\"' + symbol + '\",cp:(.*),p:(.*),cid(.*)}'
        m = re.search(namestr, content)
        if m:
            data = str(m.group(2).strip().strip('"'))
            price = data.replace(',','')
            toReturn = float(price)
        else:
            print 'ERROR ' + str(symbol) + ' --- ' + str(content)
    except Exception, exc:
        print 'Exc: ' + str(exc)
    finally:
        return toReturn
</code>```

答:
There is a Google Finance API:

http://code.google.com/apis/finance/docs/2.0/developers_guide_protocol.html

And there is a Python client library for it:

http://code.google.com/p/gdata-python-client/

Body:
I am trying to get stock prices by scraping google finance pages, I am doing this in python, using urllib package and then using regex to get price data.

When I leave my python script running, it works initially for some time (few minutes) and then starts throwing exception [HTTP Error 503: Service Unavailable]

I guess this is happening because on web server side it detects frequent page updates as a robot and throws this exception after a while..

is there a way around this, i.e. deleting some cookie or creating some cookie etc..

or even better if google gives some api, I want to do this in python because the complete app in python, but if there is nothing available in python to do this, I can consider alternatives. This is my python method that I use in loop to get data ( with few seconds of sleep I call this method in loop)

 def getPriceFromGOOGLE(self, symbol):
    """
    gets last traded price from google for given security
    """
    toReturn = 0.0
    try:
        base_url = 'http://google.com/finance?q='
        req = urllib2.Request(base_url + symbol)
        content = urllib2.urlopen(req).read()
        namestr = 'name:\"' + symbol + '\",cp:(.*),p:(.*),cid(.*)}'
        m = re.search(namestr, content)
        if m:
            data = str(m.group(2).strip().strip('"'))
            price = data.replace(',','')
            toReturn = float(price)
        else:
            print 'ERROR ' + str(symbol) + ' --- ' + str(content)
    except Exception, exc:
        print 'Exc: ' + str(exc)
    finally:
        return toReturn


问:
How would I change the src of an iframe with a text input?
So, Mojang released a version of Minecraft for the browser and I've been trying to add it to my website. I successfully did that with an iframe but people wanted multiplayer. Since multiplayer works through links, the goal would be to input the link they receive from someone else and change the iframe from the standard one to the new multiplayer one.

What I've tried is to get the user input, assign it to a variable, and use document.write to rewrite the existing iframe with the new src.

Here's what I've got. Note: it's in a modal.

input[type=text], input[type=password] {
  width: 300px;
}
.cancelbtn {
  width: auto;
  padding: 10px 18px;
  background-color: #f44336;
}

/* Center the image and position the close button */
.imgcontainer {
  text-align: center;
  margin: 24px 0 12px 0;
  position: relative;
}

img.avatar {
  width: 40%;
  border-radius: 50%;
}

.container {
  padding: 16px;
}

span.psw {
  float: right;
  padding-top: 16px;
}

/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
  padding-top: 60px;
}

/* Modal Content/Box */
.modal-content {
  background-color: #fefefe;
  margin: 5% auto 15% auto; /* 5% from the top, 15% from the bottom and centered */
  border: 1px solid #888;
  width: 80%; /* Could be more or less, depending on screen size */
}

/* The Close Button (x) */
.close {
  position: absolute;
  right: 25px;
  top: 0;
  color: #000;
  font-size: 35px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: red;
  cursor: pointer;
}

/* Add Zoom Animation */
.animate {
  -webkit-animation: animatezoom 0.6s;
  animation: animatezoom 0.6s
}

@-webkit-keyframes animatezoom {
  from {-webkit-transform: scale(0)}
  to {-webkit-transform: scale(1)}
}

@keyframes animatezoom {
  from {transform: scale(0)}
  to {transform: scale(1)}
}

/* Change styles for span and cancel button on extra small screens */
@media screen and (max-width: 300px) {
  span.psw {
     display: block;
     float: none;
  }
  .cancelbtn {
     width: 100%;
  }
}
.button {
  color: white;
  background-color: #4CAF50;
  border-color: #ccc;
  font-size: 14px;
  font-weight: 400;
  border: 1px solid transparent;
  border-radius: 4px;
  cursor: pointer;
  line-height: 1.42857143;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  padding: 6px 12px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
<div align="center"><iframe id="change" name="change" width="800" height="500" src="//classic.minecraft.net"></iframe></div>
 <div>
 <button class="button" id="button"><b>Fullscreen</b> </button>
 <button class="button" id="modal" onclick="document.getElementById('id01').style.display='block'"><b>Multiplayer</b></button>
 </div>
 <script src="/fullscreen.js"></script>
 <script>
   function changeIframe() {
  document.write(" <iframe  id='change' name='change' src='#" + input + "' width='800'  height='500'   allowfullscreen></iframe>");
}
 </script>
 <script>
 var input = document.getElementById("detroit");
 </script>
 <div id="id01" class="sprckn-modal">

<form class="modal-content animate">
    <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>

  <div class="sprckn-modal-content">
    <label for="link"><b>Paste Multiplayer Link Here</b></label>
    <center><input type="text" onsubmit="changeIframe()" id="detroit" placeholder="https://classic.minecraft.net/?join=somelettersand#s" name="link" required></center>
  </div>

  <div class="container" style="background-color:#f1f1f1">
    <center><button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button></center>
</form>
  </div>
</div>
`</code>```

Absolutely no part of the iframe changes, but my website url does, with a ?link=(linkhere). It can be better shown off at https://sprocken.com/game/minecraft/.

答:
You mean this?

```<code>var url = $('#detroit').value;
$('iframe').setAttribute('src', url);
</code>```

This will help you to add the url entered in the textbox to the iframe src. I tested it in your developer console of your website.

screenshot attached

Body:
So, Mojang released a version of Minecraft for the browser and I've been trying to add it to my website. I successfully did that with an iframe but people wanted multiplayer. Since multiplayer works through links, the goal would be to input the link they receive from someone else and change the iframe from the standard one to the new multiplayer one.

What I've tried is to get the user input, assign it to a variable, and use document.write to rewrite the existing iframe with the new src.

Here's what I've got. Note: it's in a modal.

input[type=text], input[type=password] {
  width: 300px;
}
.cancelbtn {
  width: auto;
  padding: 10px 18px;
  background-color: #f44336;
}

/* Center the image and position the close button */
.imgcontainer {
  text-align: center;
  margin: 24px 0 12px 0;
  position: relative;
}

img.avatar {
  width: 40%;
  border-radius: 50%;
}

.container {
  padding: 16px;
}

span.psw {
  float: right;
  padding-top: 16px;
}

/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
  padding-top: 60px;
}

/* Modal Content/Box */
.modal-content {
  background-color: #fefefe;
  margin: 5% auto 15% auto; /* 5% from the top, 15% from the bottom and centered */
  border: 1px solid #888;
  width: 80%; /* Could be more or less, depending on screen size */
}

/* The Close Button (x) */
.close {
  position: absolute;
  right: 25px;
  top: 0;
  color: #000;
  font-size: 35px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: red;
  cursor: pointer;
}

/* Add Zoom Animation */
.animate {
  -webkit-animation: animatezoom 0.6s;
  animation: animatezoom 0.6s
}

@-webkit-keyframes animatezoom {
  from {-webkit-transform: scale(0)}
  to {-webkit-transform: scale(1)}
}

@keyframes animatezoom {
  from {transform: scale(0)}
  to {transform: scale(1)}
}

/* Change styles for span and cancel button on extra small screens */
@media screen and (max-width: 300px) {
  span.psw {
     display: block;
     float: none;
  }
  .cancelbtn {
     width: 100%;
  }
}
.button {
  color: white;
  background-color: #4CAF50;
  border-color: #ccc;
  font-size: 14px;
  font-weight: 400;
  border: 1px solid transparent;
  border-radius: 4px;
  cursor: pointer;
  line-height: 1.42857143;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  padding: 6px 12px;
}

 <button class="button" id="button">Fullscreen </button>
 <button class="button" id="modal" onclick="document.getElementById('id01').style.display='block'">Multiplayer</button>

<form class="modal-content animate">
    ×

    Paste Multiplayer Link Here
    <input type="text" onsubmit="changeIframe()" id="detroit" placeholder="https://classic.minecraft.net/?join=somelettersand#s" name="link" required>

    <button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
</form>

`

Absolutely no part of the iframe changes, but my website url does, with a ?link=(linkhere). It can be better shown off at https://sprocken.com/game/minecraft/.

Body:
You mean this?

var url = $('#detroit').value;
$('iframe').setAttribute('src', url);

This will help you to add the url entered in the textbox to the iframe src. I tested it in your developer console of your website.

screenshot attached


问:
How would I be able to unit test a void method?
I want to test my method which checks for the direction of movement of vehicles. It is a void method and has one parameter - integer.

As far as I know all the if's should be split into different test methods but I am not aware of how to do that.

```<code>/// <summary>
        /// checks the east neighbour of the crossing on a given cell
        /// </summary>
        /// <param name="cellNr">the cell Nr of the crossing whose neighbour ///its checked</param>

    public void CheckEast(int cellNr)
    {
        Crossing cr = Cells[cellNr].Crossing;

        //If there is east neighbour - laneIns of the current crossing with direction east are NOT endLane
        if (cells[cellNr + 1].Taken)
        {
            foreach (LaneIn laneIn in cr.LaneInList)
            {
                if (laneIn.Direction == "west")
                {
                    laneIn.EndLane = false;
                }
            }

            //car should NOT be spawned from east && LaneOut of current crossing with direction east is NOT endLane
            cr.IncomingStreams[3] = "";
            cr.LaneOutList[0].EndLane = false;

            //LaneIn 'east' of the east neighbour is NOT endLane
            foreach (LaneIn laneIn in cells[cellNr + 1].Crossing.LaneInList)
            {
                if (laneIn.Direction == "east")
                {
                    laneIn.EndLane = false;
                }
            }
            //no spawned car in the neighbour from the east laneIns and LaneOut 'west' is not endlane
            cells[cellNr + 1].Crossing.IncomingStreams[1] = "";
            cells[cellNr + 1].Crossing.LaneOutList[1].EndLane = false;
            cr.Neighbours[1] = cells[cellNr + 1].Crossing;
            cells[cellNr + 1].Crossing.Neighbours[3] = cr;
        }
        //if there is NO neighbour on east side, laneIns of the current crossing are endlane(spawning point)
        //laneout is endlane, cars are erased after leaving it
        else
        {
            cr.Neighbours[1] = null;
            cr.IncomingStreams[3] = "west";
            cr.LaneOutList[0].EndLane = true;
            foreach (LaneIn laneIn in cr.LaneInList)
            {
                if (laneIn.Direction == "west")
                {
                    laneIn.EndLane = true;
                }
            }
        }
    }
</code>```

答: In your unit test, you call CheckEast with cellNr set to some values, and then you assert that the expected side effects (that is, changes) were made to the Cells, LaneInList, etc., data structures.

Body:
I want to test my method which checks for the direction of movement of vehicles. It is a void method and has one parameter - integer.

As far as I know all the if's should be split into different test methods but I am not aware of how to do that.

///
        /// checks the east neighbour of the crossing on a given cell
        ///
        /// <param name="cellNr">the cell Nr of the crossing whose neighbour ///its checked</param>

    public void CheckEast(int cellNr)
    {
        Crossing cr = Cells[cellNr].Crossing;

        //If there is east neighbour - laneIns of the current crossing with direction east are NOT endLane
        if (cells[cellNr + 1].Taken)
        {
            foreach (LaneIn laneIn in cr.LaneInList)
            {
                if (laneIn.Direction == "west")
                {
                    laneIn.EndLane = false;
                }
            }

            //car should NOT be spawned from east && LaneOut of current crossing with direction east is NOT endLane
            cr.IncomingStreams[3] = "";
            cr.LaneOutList[0].EndLane = false;

            //LaneIn 'east' of the east neighbour is NOT endLane
            foreach (LaneIn laneIn in cells[cellNr + 1].Crossing.LaneInList)
            {
                if (laneIn.Direction == "east")
                {
                    laneIn.EndLane = false;
                }
            }
            //no spawned car in the neighbour from the east laneIns and LaneOut 'west' is not endlane
            cells[cellNr + 1].Crossing.IncomingStreams[1] = "";
            cells[cellNr + 1].Crossing.LaneOutList[1].EndLane = false;
            cr.Neighbours[1] = cells[cellNr + 1].Crossing;
            cells[cellNr + 1].Crossing.Neighbours[3] = cr;
        }
        //if there is NO neighbour on east side, laneIns of the current crossing are endlane(spawning point)
        //laneout is endlane, cars are erased after leaving it
        else
        {
            cr.Neighbours[1] = null;
            cr.IncomingStreams[3] = "west";
            cr.LaneOutList[0].EndLane = true;
            foreach (LaneIn laneIn in cr.LaneInList)
            {
                if (laneIn.Direction == "west")
                {
                    laneIn.EndLane = true;
                }
            }
        }
    }


问:
Is it possible to lookup for a value from another sheet in the same workbook?
I have a workbook with multiple spreadsheets. One of the sheets is called "Master Filtered" and the other is called "MTL OR TOR"
I want to fill in the column K of the "Master filtered" sheet with a lookup value from the "MTL or TOR" sheet in the second column. I wrote this piece of code but it is not working.

```<code>Sub MTL_OR_TOR()
    Dim AcctNb As String
    Dim result As String

    Worksheets("Master Filtered").Activate
    Dim lastrow As Long
    lastrow = Cells(Rows.Count, 1).End(xlUp).Row

    For G = 4 To lastrow

    AcctNb = Cells(G, 3).Value

    Set myrange = Worksheets("MTL OR TOR").Range("AA4:AB685") 'Range in which the table MTL or TOR should be entered
    result = Application.WorksheetFunction.VLookup(AcctNb, myrange, 2, False)

    Range("K" & G).Value = result
    Next

End Sub
</code>```

Do you have any idea why is this code not working and how to fix it?

I was thinking maybe my error is in the line starting with Set myrange= Worksheets("MTL OR TOR") but couldn't figure it out.

答:
```<code>Sub MTL_OR_TOR()
    ' Name your variables in a meaningful way and indicate their type
    Dim strAcctNb As String
    Dim strResult As String
    Dim lngLastRow As Long
    Dim lngLoop As Long
    Dim rngLookup As Range

    'Set your range and variables before you execute the code for readability
    Set rngLookup = Worksheets("MTL OR TOR").Range("AA4:AB685") 'Range in which the table MTL or TOR should be entered

    'Do not Activate or Select unless you really have to
    'Worksheets("Master Filtered").Activate

    With Worksheets("Master Filtered")

        lngLastRow = .Cells(.Rows.Count, 1).End(xlUp).Row

        For lngLoop = 4 To lngLastRow
            strAcctNb = .Cells(lngLoop, 3).Value
            strResult = Application.WorksheetFunction.VLookup(strAcctNb, rngLookup, 2, False)
            .Range("K" & lngLoop).Value = strResult
        Next

    End With

End Sub
</code>```

Body:
I have a workbook with multiple spreadsheets. One of the sheets is called "Master Filtered" and the other is called "MTL OR TOR"
I want to fill in the column K of the "Master filtered" sheet with a lookup value from the "MTL or TOR" sheet in the second column. I wrote this piece of code but it is not working.

Sub MTL_OR_TOR()
    Dim AcctNb As String
    Dim result As String

    Worksheets("Master Filtered").Activate
    Dim lastrow As Long
    lastrow = Cells(Rows.Count, 1).End(xlUp).Row

    For G = 4 To lastrow

    AcctNb = Cells(G, 3).Value

    Set myrange = Worksheets("MTL OR TOR").Range("AA4:AB685") 'Range in which the table MTL or TOR should be entered
    result = Application.WorksheetFunction.VLookup(AcctNb, myrange, 2, False)

    Range("K" & G).Value = result
    Next

End Sub

Do you have any idea why is this code not working and how to fix it?

I was thinking maybe my error is in the line starting with Set myrange= Worksheets("MTL OR TOR") but couldn't figure it out.


问:
How to elegantly customize the collection key name in laravel

For example, there is such a collection

$phone_Id = $request->get('q');
$colors = Phone::find($phone_Id)->color->toArray();
dd($colors);
```

<ol start="2">
<li>print result</li>
</ol>

<pre class="lang-sh prettyprint-override"><code>array:2 [▼
  0 => array:6 [▼
    "id" => 8
    "name" => "red"
    "value" => "#fb6250"
    "created_at" => "2019-05-29 01:42:51"
    "updated_at" => "2019-05-29 01:42:51"
    "pivot" => array:4 [▼
      "phone_id" => 1
      "color_id" => 8
      "created_at" => "2019-05-29 01:42:51"
      "updated_at" => "2019-05-29 01:42:51"
    ]
  ]
  1 => array:6 [▼
    "id" => 11
    "name" => "blue"
    "value" => "#202020"
    "created_at" => "2019-05-29 01:42:51"
    "updated_at" => "2019-05-29 01:42:51"
    "pivot" => array:4 [▼
      "phone_id" => 1
      "color_id" => 11
      "created_at" => "2019-05-29 01:42:51"
      "updated_at" => "2019-05-29 01:42:51"
    ]
  ]
]
</code>```

The end result I want is an array like this

array:2 [▼
  0 => array:2 [▼
    "id" => 8
    "text" => "red"
  ]
  1 => array:2 [▼
    "id" => 11
    "text" => "blue"
  ]
]
```

<ol start="4">
<li>So my current practice is like this.</li>
</ol>

<pre class="lang-php prettyprint-override"><code>$data = [];
foreach ($colors as $key => $val) {
    $data[$key]['id'] = $val->id;
    $data[$key]['text'] = $val->name;
}
dd($data);
</code>```

print result

array:2 [▼
  0 => array:2 [▼
    "id" => 8
    "text" => "red"
  ]
  1 => array:2 [▼
    "id" => 11
    "text" => "blue"
  ]
]
```

I want to know if there is a better and more beautiful implementation for this kind of demand in laravel?

答:
Using ->trasform(..):

$colors = Phone::find($phone_Id)->color;

$colors->transform(function ($color) {
    return [
        'id' => $color->id,
        'text' => $color->name,
    ];
});
```

<p><strong>Edit:</strong> thanks for the correct answer and upvotes, but I'd like to point out that OP came to a much more elegant solution using query builder's <code>->get(..)</code> and renaming the columns:</p>

<pre class="lang-php prettyprint-override"><code>$colors = Phone::find($phone_Id)->color()->get(['id', 'name as text'])->toArray();
</code>```

Body:
For example, there is such a collection

$phone_Id = $request->get('q');
$colors = Phone::find($phone_Id)->color->toArray();
dd($colors);

print result

array:2 [▼
  0 => array:6 [▼
    "id" => 8
    "name" => "red"
    "value" => "#fb6250"
    "created_at" => "2019-05-29 01:42:51"
    "updated_at" => "2019-05-29 01:42:51"
    "pivot" => array:4 [▼
      "phone_id" => 1
      "color_id" => 8
      "created_at" => "2019-05-29 01:42:51"
      "updated_at" => "2019-05-29 01:42:51"
    ]
  ]
  1 => array:6 [▼
    "id" => 11
    "name" => "blue"
    "value" => "#202020"
    "created_at" => "2019-05-29 01:42:51"
    "updated_at" => "2019-05-29 01:42:51"
    "pivot" => array:4 [▼
      "phone_id" => 1
      "color_id" => 11
      "created_at" => "2019-05-29 01:42:51"
      "updated_at" => "2019-05-29 01:42:51"
    ]
  ]
]

The end result I want is an array like this

array:2 [▼
  0 => array:2 [▼
    "id" => 8
    "text" => "red"
  ]
  1 => array:2 [▼
    "id" => 11
    "text" => "blue"
  ]
]

So my current practice is like this.

$data = [];
foreach ($colors as $key => $val) {
    $data[$key]['id'] = $val->id;
    $data[$key]['text'] = $val->name;
}
dd($data);

print result

array:2 [▼
  0 => array:2 [▼
    "id" => 8
    "text" => "red"
  ]
  1 => array:2 [▼
    "id" => 11
    "text" => "blue"
  ]
]

I want to know if there is a better and more beautiful implementation for this kind of demand in laravel?

Body:
Using ->trasform(..):

$colors = Phone::find($phone_Id)->color;

$colors->transform(function ($color) {
    return [
        'id' => $color->id,
        'text' => $color->name,
    ];
});

Edit: thanks for the correct answer and upvotes, but I'd like to point out that OP came to a much more elegant solution using query builder's ->get(..) and renaming the columns:

$colors = Phone::find($phone_Id)->color()->get(['id', 'name as text'])->toArray();


问:
Opening a file with universal newlines in binary mode in python 3
We're (finally) upgrading an application to Python 3.

One thing we have to upgrade is rewriting a CSV file using normal newlines.

The original (python 2) code looks like this:

import csv

IN_PATH = 'in.csv'
OUT_PATH = 'out.csv'

# Opens the original file in 'text mode' (which has no effect on Python 2)
# and with 'universal newlines',
# meaning \r, \n, and \r\n all get treated as line separators.
with open(IN_PATH, 'rU') as in_csv:
    with open(OUT_PATH, 'w') as out_csv:
        csv_reader = csv.reader(in_csv)
        csv_writer = csv.writer(out_csv)

        for tupl in csv_reader:
            csv_writer.writerow(tupl)

```

<p>These CSV files are user-provided. This means:</p>

<ul>
<li>we have no control over what newline characters they use, so we need to handle all of them.</li>
<li>we don't know the encoding of the file at this stage in the process.</li>
</ul>

<p>Because we don't know the encoding, we cannot decode the bytestrings into text. </p>

<p>To make this work on Python 3, first we changed it to use <code>io.open()</code>, which is mostly compatible with py3's <code>open()</code>. Now we can't use 'text mode' any more, because on Python 3 that requires decoding the bytestrings, and we don't know the encoding.</p>

<p>However, using 'binary mode' means we can no longer use universal-newlines, since that's only available in text mode.</p>

<pre class="lang-py prettyprint-override"><code>
# Opens the original file in 'binary mode'
# (because we don't know the encoding, so we can't decode it)
# FIXME: How to get universal newline support?
with io.open(IN_PATH, 'rb') as in_csv:
    with io.open(OUT_PATH, 'wb') as out_csv:
</code>```

Note that, although the U mode character is no longer supported in python 3, it does use universal newlines by default in text mode. It doesn't appear to have any way of using universal newlines in binary mode.

How can we make this code work in Python 3?

答:
The open function in Python 3 has an argument newline.  Setting it to None enables universal newline mode.

```<code>import csv

IN_PATH = 'in.csv'
OUT_PATH = 'out.csv'

with open(IN_PATH, 'r', newline=None) as in_csv:
    with open(OUT_PATH, 'w') as out_csv:
        csv_reader = csv.reader(in_csv)
        csv_writer = csv.writer(out_csv)

        for tupl in csv_reader:
            csv_writer.writerow(tupl)
</code>```

Examples:

Example file:

```<code>a,b,c\n
1,2,3\r
4,5,6\r\n
7,8,9
</code>```

Example code:

```<code>with open('file.csv', 'r', newline=None) as fp:
    reader = csv.reader(fp)
    for line in reader:
        print(line)

# prints:
['a', 'b', 'c']
['1', '2', '3']
['4', '5', '6']
['7', '8', '9']
</code>```

Body:
We're (finally) upgrading an application to Python 3.

One thing we have to upgrade is rewriting a CSV file using normal newlines.

The original (python 2) code looks like this:

import csv

IN_PATH = 'in.csv'
OUT_PATH = 'out.csv'

# Opens the original file in 'text mode' (which has no effect on Python 2)
# and with 'universal newlines',
# meaning \r, \n, and \r\n all get treated as line separators.
with open(IN_PATH, 'rU') as in_csv:
    with open(OUT_PATH, 'w') as out_csv:
        csv_reader = csv.reader(in_csv)
        csv_writer = csv.writer(out_csv)

        for tupl in csv_reader:
            csv_writer.writerow(tupl)

These CSV files are user-provided. This means:

we have no control over what newline characters they use, so we need to handle all of them.

we don't know the encoding of the file at this stage in the process.

Because we don't know the encoding, we cannot decode the bytestrings into text.

To make this work on Python 3, first we changed it to use io.open(), which is mostly compatible with py3's open(). Now we can't use 'text mode' any more, because on Python 3 that requires decoding the bytestrings, and we don't know the encoding.

However, using 'binary mode' means we can no longer use universal-newlines, since that's only available in text mode.

# Opens the original file in 'binary mode'
# (because we don't know the encoding, so we can't decode it)
# FIXME: How to get universal newline support?
with io.open(IN_PATH, 'rb') as in_csv:
    with io.open(OUT_PATH, 'wb') as out_csv:

Note that, although the U mode character is no longer supported in python 3, it does use universal newlines by default in text mode. It doesn't appear to have any way of using universal newlines in binary mode.

How can we make this code work in Python 3?

Body:
The open function in Python 3 has an argument newline.  Setting it to None enables universal newline mode.

import csv

IN_PATH = 'in.csv'
OUT_PATH = 'out.csv'

with open(IN_PATH, 'r', newline=None) as in_csv:
    with open(OUT_PATH, 'w') as out_csv:
        csv_reader = csv.reader(in_csv)
        csv_writer = csv.writer(out_csv)

        for tupl in csv_reader:
            csv_writer.writerow(tupl)

Examples:

Example file:

a,b,c\n
1,2,3\r
4,5,6\r\n
7,8,9

Example code:

with open('file.csv', 'r', newline=None) as fp:
    reader = csv.reader(fp)
    for line in reader:
        print(line)

# prints:
['a', 'b', 'c']
['1', '2', '3']
['4', '5', '6']
['7', '8', '9']


问:
Button 'onclick' doesn't work in Internet Explorer
I'm testing a web application with spring MVC 3 and I'm facing an error that I can't resolve.

I have a controller that gives me a list of data from the DB that is handled in the JSP with a forEach statement.
Also, inside the forEach i have a form that will be displayed in a jquery-ui dialog after clicking a button.

My JSP looks like this:

```<code><html>
/**
*
*
**/
<c:forEach items="${listaFecha}" var="fec">
            <tr>
                <td><c:out value="${fec.id}" /></td>
                <td><c:out value="${fec.NOM_ASUNTO}" /></td>
                <td><fmt:formatDate value="${fec.FEC_INICIO}" pattern="dd-MMM-YYYY" /></td>
                <td><fmt:formatDate value="${fec.FEC_FIN}" pattern="dd-MMM-YYYY" /></td>
                <td><c:out value="${fec.PERIODO}" /></td>
                <td><button id="faqIE${fec.id}" value="${fec.id}" onclick="changeFec(${fec.id})">Editar</button></td>
            </tr>
            <div id="edit-form${fec.id}" class="edit" style="text-align:center;" title="Editar Fecha">      </br>
                <form name="fechasE" method="POST" target="_parent" action="<c:url value="/manage/insertaForm"/>" id="form2E${fec.id}">
                    <label style="margin-right:133px;">Tipo de Solicitud: </label></br>
                    <input type="text" class="fields" name="asE" value="${fec.NOM_ASUNTO}" disabled/></br>

                    <label style="margin-right:158px;">Fecha Inicial: </label> </br>
                    <input type="text" class="fields" name="date1E" value="<fmt:formatDate value="${fec.FEC_INICIO}" pattern="dd-MMM-YYYY"/>" /></br>

                    <label style="margin-right:165px;">Fecha Final: </label></br>
                    <input type="text" class="fields" name="date2E" value="<fmt:formatDate value="${fec.FEC_FIN}" pattern="dd-MMM-YYYY"/>" /></br>

                    <label style="margin-right:185px;">Periodo: </label></br>
                    <input type="text" class="fields" name="pdE" value="${fec.PERIODO}"/></br>
                </form>
            </div>
        </c:forEach>
/**
*
*
**/
<script type="text/javascript">
function changeFec(n) {
    $( "#edit-form"+n ).dialog({
            autoOpen: true,
            height: 390,
            width: 350,
            modal: true,
            resizable: false,
            buttons: {
                Editar: function() {
                        $( "form2E"+n ).submit();
                        $( this ).dialog( "close" );
                },
                Cancelar: function() {
                    $( this ).dialog( "close" );
                }
            }
        });
}
</script>
</code>```

It work fine in Opera, Google Chrome and Firefox but in IE7,8,9 doesn't.
I don't know why! I've been searching for hours without success! I hope somebody could help me.

Thanks in advance and sorry for my bad English.

EDIT:

This is how it have to work http://jsfiddle.net/NbddB/22/ .
But the value in changeFec(value) have to be dinamic and the divs are created dynamically inside the forEach statement.

答:
```<code>    toggleExpand(e) {
        e.preventDefault()
        e.stopPropagation();
        if (!this.state.expanded) {
            document.addEventListener('click', this.handleOutsideClick, false);
        } else {
            document.removeEventListener('click', this.handleOutsideClick, false);
        }

        this.setState({
            expanded: !this.state.expanded
        });
    }

    handleOutsideClick(e) {
        if (this.node.contains(e.target)) {
            return;
        }

        this.toggleExpand(e);
    }

    toggleOpen(e) {
        e.preventDefault()
        e.stopPropagation();
    }

render() {
  return (
                    {this.state.expanded && (
                            <div
                                className={styles.pointer}
                            >
                                <div
                                    onClick={this.toggleOpen}

                                >
                                    <button
                                        onClick={this.toggleExpand}
                                        className={[
                                            styles.close}
                                        alt="Close Button"

                                    />

                                    <div
                                        className={
                                            styles.pop}
                                     >
                                        <div>
                                            <span className={styles.label}>
                                            abcd
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        )}

)}
</code>```

Body:
I'm testing a web application with spring MVC 3 and I'm facing an error that I can't resolve.

I have a controller that gives me a list of data from the DB that is handled in the JSP with a forEach statement.
Also, inside the forEach i have a form that will be displayed in a jquery-ui dialog after clicking a button.

My JSP looks like this:

/**
*
*
**/
<c:forEach items="${listaFecha}" var="fec">

                <c:out value="${fec.id}" />
                <c:out value="${fec.NOM_ASUNTO}" />
                <fmt:formatDate value="${fec.FEC_INICIO}" pattern="dd-MMM-YYYY" />
                <fmt:formatDate value="${fec.FEC_FIN}" pattern="dd-MMM-YYYY" />
                <c:out value="${fec.PERIODO}" />
                <button id="faqIE${fec.id}" value="${fec.id}" onclick="changeFec(${fec.id})">Editar</button>

                <form name="fechasE" method="POST" target="_parent" action="<c:url value="/manage/insertaForm"/>" id="form2E${fec.id}">
                    Tipo de Solicitud:

                    <input type="text" class="fields" name="asE" value="${fec.NOM_ASUNTO}" disabled/>

                    Fecha Inicial:

                    <input type="text" class="fields" name="date1E" value="<fmt:formatDate value="${fec.FEC_INICIO}" pattern="dd-MMM-YYYY"/>" />

                    Fecha Final:

                    <input type="text" class="fields" name="date2E" value="<fmt:formatDate value="${fec.FEC_FIN}" pattern="dd-MMM-YYYY"/>" />

                    Periodo:

                    <input type="text" class="fields" name="pdE" value="${fec.PERIODO}"/>

                </form>

        </c:forEach>
/**
*
*
**/

It work fine in Opera, Google Chrome and Firefox but in IE7,8,9 doesn't.
I don't know why! I've been searching for hours without success! I hope somebody could help me.

Thanks in advance and sorry for my bad English.

EDIT:

This is how it have to work http://jsfiddle.net/NbddB/22/ .
But the value in changeFec(value) have to be dinamic and the divs are created dynamically inside the forEach statement.


问:
While using sed command i receive the following error : Function cannot be parsed. Any Solutions or reason for this?
I need to replace a particular character in a text file with another character. For example, replacing "E" with "A":

Apple ice → ApplA Ica

While executing sed 's/E/A' < apple.txt > app.txt I receive the error

function cannot be parsed

Please help! I need to automate this using Antscript.

答: sed 's/E/A/g' app.txt. You missed the trailing / (g means all occurrences),


问:
A better way to extract some strings from a string
Is there a better way to extract substring from a string ?

I want to extract characters that are surrounded with " and " in a string. I used substring() and indexOf() methods but I sure there is a better way.

For example, for this input:

I "learn" java "and" python.

The desired output would be:

learn

and

Here is what I tried:

```<code>public static void main(String[] args) {
    Scanner putIn = new Scanner(System.in);
    String input = putIn.nextLine();
    String subInput = input.substring(input.indexOf("\"") + 1);
    System.out.println(subInput);
    String strOne= subInput.substring(0, subInput.indexOf("\""));
    System.out.println(strOne);
    String strTwo = subInput.substring(strOne.length() + 4, subInput.length() - 2);
    System.out.println(strTwo);
}
</code>```

答:
Pattern and Matcher classes seem to fit your needs:

```<code>Pattern pattern = Pattern.compile("\"([a-zA-Z]*)\"");
Matcher matcher = pattern.matcher(input);

while(matcher.find()) {
    System.out.println(matcher.group(1));
}
</code>```

Further explanation:

Pattern pattern = Pattern.compile("\"([a-zA-Z]*)\""); -> Create a Pattern that matches letters between quote characters

Matcher matcher = pattern.matcher(input); -> Create a Matcher to link the Pattern and the user input.

while(matcher.find()) while there are matches... Of course you could add the matched strings to an array, here I just print them.

Body:
Is there a better way to extract substring from a string ?

I want to extract characters that are surrounded with " and " in a string. I used substring() and indexOf() methods but I sure there is a better way.

For example, for this input:

I "learn" java "and" python.

The desired output would be:

learn

and

Here is what I tried:

public static void main(String[] args) {
    Scanner putIn = new Scanner(System.in);
    String input = putIn.nextLine();
    String subInput = input.substring(input.indexOf("\"") + 1);
    System.out.println(subInput);
    String strOne= subInput.substring(0, subInput.indexOf("\""));
    System.out.println(strOne);
    String strTwo = subInput.substring(strOne.length() + 4, subInput.length() - 2);
    System.out.println(strTwo);
}

Body:
Pattern and Matcher classes seem to fit your needs:

Pattern pattern = Pattern.compile("\"([a-zA-Z]*)\"");
Matcher matcher = pattern.matcher(input);

while(matcher.find()) {
    System.out.println(matcher.group(1));
}

Further explanation:

Pattern pattern = Pattern.compile("\"([a-zA-Z]*)\""); -> Create a Pattern that matches letters between quote characters

Matcher matcher = pattern.matcher(input); -> Create a Matcher to link the Pattern and the user input.

while(matcher.find()) while there are matches... Of course you could add the matched strings to an array, here I just print them.


问:
"Attribute 'program' does not exist" for basic node.js project
I created simple node.js application (source code from here https://azure.microsoft.com/en-us/blog/visual-studio-code-and-azure-app-service-a-perfect-fit/)

```<code>var http = require('http');
http.createServer(function (req, res) {
    console.log('Got request for ' + req.url);
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('<h1>Hello Code and Azure Web Apps!</h1>');
}).listen(process.env.PORT);
</code>```

And clicked VSCode generated launch.json:

```<code>{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch",
            "type": "node",
            "request": "launch",
            "program": "${workspaceRoot}/app.js",
            "stopOnEntry": false,
            "args": [],
            "cwd": "${workspaceRoot}",
            "preLaunchTask": null,
            "runtimeExecutable": null,
            "runtimeArgs": [
                "--nolazy"
            ],
            "env": {
                "NODE_ENV": "development"
            },
            "externalConsole": false,
            "sourceMaps": false,
            "outDir": null
        },
        {
            "name": "Attach",
            "type": "node",
            "request": "attach",
            "port": 5858,
            "address": "localhost",
            "restart": false,
            "sourceMaps": false,
            "outDir": null,
            "localRoot": "${workspaceRoot}",
            "remoteRoot": null
        }
    ]
}
</code>```

And still when launched I see:

Attribute 'program' does not exist.

Can anybody help what's wrong?

答:
Firstly, read the official document this answers all question you would have about setting the right attributes for different scenarios using launch.json.

Now, to specifically answer this question, the ${workspaceFolder} is basically containing directory of the .vscode directory, which is your project root directory. So, when setting specific files as your debugging program, remember to map the path from the project root directory, or in other words the relative path of the file that is to be set as the debugging program. This can be easily obtained from the IDE (VS Code) by simply right-clicking the file and selecting the Copy Relative Path option. Then proceed to paste this next to the ${workspaceFolder} in the program attribute in your launch.json file, like below, will fix the problem.

```<code>"program": "${workspaceFolder}/<relative_path>"
</code>```

Replace relative path with your copied relative path as mentioned before
Note that I am on a Mac platform. Please use platform appropriate path separators

Alternatively, not specifically using a launch configuration makes sense if it's a not-for-production or a simple app that does not warrant a launch config file. However, if not, it is super useful when debugging in a Multi-target environment (server, client). In my opinion, using a compound launch configuration setup makes things a lot easier. Read this section of the official docs to learn how to set it up keeping in mind the relative paths of your server and client files.

Body:
I created simple node.js application (source code from here https://azure.microsoft.com/en-us/blog/visual-studio-code-and-azure-app-service-a-perfect-fit/)

var http = require('http');
http.createServer(function (req, res) {
    console.log('Got request for ' + req.url);
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('
Hello Code and Azure Web Apps!
');
}).listen(process.env.PORT);

And clicked VSCode generated launch.json:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch",
            "type": "node",
            "request": "launch",
            "program": "${workspaceRoot}/app.js",
            "stopOnEntry": false,
            "args": [],
            "cwd": "${workspaceRoot}",
            "preLaunchTask": null,
            "runtimeExecutable": null,
            "runtimeArgs": [
                "--nolazy"
            ],
            "env": {
                "NODE_ENV": "development"
            },
            "externalConsole": false,
            "sourceMaps": false,
            "outDir": null
        },
        {
            "name": "Attach",
            "type": "node",
            "request": "attach",
            "port": 5858,
            "address": "localhost",
            "restart": false,
            "sourceMaps": false,
            "outDir": null,
            "localRoot": "${workspaceRoot}",
            "remoteRoot": null
        }
    ]
}

And still when launched I see:

Attribute 'program' does not exist.

Can anybody help what's wrong?

Body:
Firstly, read the official document this answers all question you would have about setting the right attributes for different scenarios using launch.json.

Now, to specifically answer this question, the ${workspaceFolder} is basically containing directory of the .vscode directory, which is your project root directory. So, when setting specific files as your debugging program, remember to map the path from the project root directory, or in other words the relative path of the file that is to be set as the debugging program. This can be easily obtained from the IDE (VS Code) by simply right-clicking the file and selecting the Copy Relative Path option. Then proceed to paste this next to the ${workspaceFolder} in the program attribute in your launch.json file, like below, will fix the problem.

"program": "${workspaceFolder}/<relative_path>"

Replace relative path with your copied relative path as mentioned before
Note that I am on a Mac platform. Please use platform appropriate path separators

Alternatively, not specifically using a launch configuration makes sense if it's a not-for-production or a simple app that does not warrant a launch config file. However, if not, it is super useful when debugging in a Multi-target environment (server, client). In my opinion, using a compound launch configuration setup makes things a lot easier. Read this section of the official docs to learn how to set it up keeping in mind the relative paths of your server and client files.