问:
Array.map() vs d3.selectAll().data.enter()
I am trying to understand what's benefit of using d3.selectAll.data.enter() to loop through a dataset and plot it.

```<code>  var data = [4, 8, 15, 16, 23, 42];

  var x = d3.scale.linear()
      .domain([0, d3.max(data)])
      .range([0, 420]);

  let chartsvg = d3.select(".chart").append("svg");

  chartsvg.selectAll("rect")
    .data(data)
    .enter()
    .append("rect")
    .attr("x", 0)
    .attr("y", function(d, i) {
    return 25*i;
  })
    .attr("width", function(d) {
    return x(d);
  })
    .attr("height", 20)
    .attr("fill", "#f3b562");
</code>```

I see a lot of benefit of d3's functionalities like scale, axes, etc. But it feels like using Array.map() for looping through the dataset, I can achieve the same functionality with much cleaner code and fewer lines, especially when I am creating a much more complex visualization and not a simple barebones bar chart like this.

```<code>  var data = [4, 8, 15, 16, 23, 42];

  var x = d3.scale.linear()
      .domain([0, d3.max(data)])
      .range([0, 420]);

  let chartsvg = d3.select(".chart").append("svg");

  data.map(function(d, i){
    chartsvg.append("rect")
      .attr("x", 0)
      .attr("y", 25*i)
      .attr("width", x(d))
      .attr("height", 20)
      .attr("fill", "#f3b562");
  });
</code>```

答:
D3 stands for Data-Driven Documents

The most powerful feature in D3, which gives the very name of the library, is its ability to bind data to DOM elements. By doing this, you can manipulate those DOM elements based on the bound data in several ways, such as (but not limited to):

Sort

Filter

Translate

Style

Append

Remove

And so on...

If you don't bind data to the DOM elements, for instance using the map() approach in your question (which is the same of a forEach()), you may save a couple of lines at the beginning, but you will end up with an awkward code to deal with later. Let's see it:

The map() approach

Here is a very simple code, using most of your snippet, to create a bar chart using the map() approach:

var h = 250,
  w = 500,
  p = 40;
var svg = d3.select("body")
  .append("svg")
  .attr("width", w)
  .attr("height", h);

var data = [{
  group: "foo",
  value: 14,
  name: "A"
}, {
  group: "foo",
  value: 35,
  name: "B"
}, {
  group: "foo",
  value: 87,
  name: "C"
}, {
  group: "foo",
  value: 12,
  name: "D"
}, {
  group: "bar",
  value: 84,
  name: "E"
}, {
  group: "bar",
  value: 65,
  name: "F"
}, {
  group: "bar",
  value: 34,
  name: "G"
}, {
  group: "baz",
  value: 98,
  name: "H"
}, {
  group: "baz",
  value: 12,
  name: "I"
}, {
  group: "baz",
  value: 43,
  name: "J"
}, {
  group: "baz",
  value: 66,
  name: "K"
}, {
  group: "baz",
  value: 42,
  name: "L"
}];

var color = d3.scaleOrdinal(d3.schemeCategory10);

var xScale = d3.scaleLinear()
  .range([0, w - p])
  .domain([0, d3.max(data, function(d) {
    return d.value
  })]);

var yScale = d3.scaleBand()
  .range([0, h])
  .domain(data.map(function(d) {
    return d.name
  }))
  .padding(0.1);

data.map(function(d, i) {
  svg.append("rect")
    .attr("x", p)
    .attr("y", yScale(d.name))
    .attr("width", xScale(d.value))
    .attr("height", yScale.bandwidth())
    .attr("fill", color(d.group));
});

var axis = d3.axisLeft(yScale);
var gY = svg.append("g").attr("transform", "translate(" + p + ",0)")
  .call(axis);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script></code>```

It seems to be a nice result, the bars are all there. However, there is no data bound to those rectangles. Keep this code, we'll use it in the challenge below.

Enter selections

Now let's try the same code, but using the idiomatic "enter" selection:

var h = 250,
  w = 500,
  p = 40;

var svg = d3.select("body")
  .append("svg")
  .attr("width", w)
  .attr("height", h);

var data = [{
  group: "foo",
  value: 14,
  name: "A"
}, {
  group: "foo",
  value: 35,
  name: "B"
}, {
  group: "foo",
  value: 87,
  name: "C"
}, {
  group: "foo",
  value: 12,
  name: "D"
}, {
  group: "bar",
  value: 84,
  name: "E"
}, {
  group: "bar",
  value: 65,
  name: "F"
}, {
  group: "bar",
  value: 34,
  name: "G"
}, {
  group: "baz",
  value: 98,
  name: "H"
}, {
  group: "baz",
  value: 12,
  name: "I"
}, {
  group: "baz",
  value: 43,
  name: "J"
}, {
  group: "baz",
  value: 66,
  name: "K"
}, {
  group: "baz",
  value: 42,
  name: "L"
}];

var color = d3.scaleOrdinal(d3.schemeCategory10);

var xScale = d3.scaleLinear()
  .range([0, w - p])
  .domain([0, d3.max(data, function(d) {
    return d.value
  })]);

var yScale = d3.scaleBand()
  .range([0, h])
  .domain(data.map(function(d) {
    return d.name
  }))
  .padding(0.1);

svg.selectAll(null)
  .data(data, function(d) {
    return d.name
  })
  .enter()
  .append("rect")
  .attr("x", p)
  .attr("y", function(d) {
    return yScale(d.name)
  })
  .attr("width", function(d) {
    return xScale(d.value)
  })
  .attr("height", yScale.bandwidth())
  .attr("fill", function(d) {
    return color(d.group)
  });

var axis = d3.axisLeft(yScale);
var gY = svg.append("g").attr("transform", "translate(" + p + ",0)")
  .call(axis);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script></code>```

As you can see, it's a little longer than the previous map() method, 2 lines longer.

However, this actually binds data to those rectangles. If you console.log a D3 selection of one of those rectangles, you'll see something like this (in Chrome):

```<code>> Selection
  > _groups: Array(1)
    > 0: Array(1)
      > 0: rect
        > __data__: Object
          group: "bar"
          name: "G"
          value: 34
</code>```

Since this code actually binds data to the DOM elements, you can manipulate them in a way that would be cumbersome (to say the least) using the map() approach. I'll show this in the next snippet, which will be used to propose a challenge.

Challenge

Since your question talks about cleaner code and fewer lines, here is a challenge for you.

I created 3 buttons, one for each group in the data array (and a fourth one for all the groups). When you click the button, it filters the data and updates the chart accordingly:

var h = 250,
  w = 500,
  p = 40;
var svg = d3.select("body")
  .append("svg")
  .attr("width", w)
  .attr("height", h);

var g1 = svg.append("g")
var g2 = svg.append("g")

var data = [{
  group: "foo",
  value: 14,
  name: "A"
}, {
  group: "foo",
  value: 35,
  name: "B"
}, {
  group: "foo",
  value: 87,
  name: "C"
}, {
  group: "foo",
  value: 12,
  name: "D"
}, {
  group: "bar",
  value: 84,
  name: "E"
}, {
  group: "bar",
  value: 65,
  name: "F"
}, {
  group: "bar",
  value: 34,
  name: "G"
}, {
  group: "baz",
  value: 98,
  name: "H"
}, {
  group: "baz",
  value: 12,
  name: "I"
}, {
  group: "baz",
  value: 43,
  name: "J"
}, {
  group: "baz",
  value: 66,
  name: "K"
}, {
  group: "baz",
  value: 42,
  name: "L"
}];

var color = d3.scaleOrdinal(d3.schemeCategory10);

var xScale = d3.scaleLinear()
  .range([0, w - p])
  .domain([0, d3.max(data, function(d) {
    return d.value
  })]);

var yScale = d3.scaleBand()
  .range([0, h])
  .domain(data.map(function(d) {
    return d.name
  }))
  .padding(0.1);

var axis = d3.axisLeft(yScale);
var gY = g2.append("g").attr("transform", "translate(" + p + ",0)")
  .call(axis);

draw(data);

function draw(data) {

  yScale.domain(data.map(function(d) {
    return d.name
  }))

  var rects = g1.selectAll("rect")
    .data(data, function(d) {
      return d.name
    })

  rects.enter()
    .append("rect")
    .attr("x", p)
    .attr("y", function(d) {
      return yScale(d.name)
    })
    .attr("width", 0)
    .attr("height", yScale.bandwidth())
    .attr("fill", function(d) {
      return color(d.group)
    })
    .transition()
    .duration(1000)
    .attr("width", function(d) {
      return xScale(d.value)
    });

  rects.transition()
    .duration(1000)
    .attr("x", p)
    .attr("y", function(d) {
      return yScale(d.name)
    })
    .attr("width", function(d) {
      return xScale(d.value)
    })
    .attr("height", yScale.bandwidth())
    .attr("fill", function(d) {
      return color(d.group)
    });

  rects.exit()
    .transition()
    .duration(1000)
    .attr("width", 0)
    .remove();

  gY.transition().duration(1000).call(axis);
};

d3.selectAll("button").on("click", function() {

  var thisValue = this.id;

  var newData = thisValue === "all" ? data : data.filter(function(d) {
    return d.group === thisValue;
  });

  draw(newData)
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script>
<button id="foo">Foo</button>
<button id="bar">Bar</button>
<button id="baz">Baz</button>
<button id="all">All</button>
<br>
<br></code>```

A cleaner code is somehow opinion-based, but we can easily measure size.

Thus, here is the challenge: try to create a code that does the same, but using the map() approach, that is, without binding any data. Do all the transitions I'm doing here. The code you will try to recreate is all the code inside the on("click") function.

After that, we'll compare the size of your code and the size of an idiomatic "enter", "update" and "exit" selections.

Chalenge #2

This challenge number 2 may be even more interesting to show D3 capabilities when it comes to binding data.

In this new code, I'm sorting the original data array after 1 second, and redrawing the chart. Then, clicking on the "update" button, I'm binding another data array to the bars.

The nice thing here is the key function, that associates each bar to each data point using, in this case, the name property:

```<code>.data(data, function(d) {
    return d.name
})
</code>```

Here is the code, please wait 1 second before clicking "update":

var h = 250,
  w = 500,
  p = 40;

var svg = d3.select("body")
  .append("svg")
  .attr("width", w)
  .attr("height", h);

var data2 = [{
  group: "foo",
  value: 10,
  name: "A"
}, {
  group: "foo",
  value: 20,
  name: "B"
}, {
  group: "foo",
  value: 30,
  name: "C"
}, {
  group: "foo",
  value: 40,
  name: "D"
}, {
  group: "bar",
  value: 50,
  name: "E"
}, {
  group: "bar",
  value: 60,
  name: "F"
}, {
  group: "bar",
  value: 70,
  name: "G"
}, {
  group: "baz",
  value: 80,
  name: "H"
}, {
  group: "baz",
  value: 85,
  name: "I"
}, {
  group: "baz",
  value: 90,
  name: "J"
}, {
  group: "baz",
  value: 95,
  name: "K"
}, {
  group: "baz",
  value: 100,
  name: "L"
}];

var data = [{
  group: "foo",
  value: 14,
  name: "A"
}, {
  group: "foo",
  value: 35,
  name: "B"
}, {
  group: "foo",
  value: 87,
  name: "C"
}, {
  group: "foo",
  value: 12,
  name: "D"
}, {
  group: "bar",
  value: 84,
  name: "E"
}, {
  group: "bar",
  value: 65,
  name: "F"
}, {
  group: "bar",
  value: 34,
  name: "G"
}, {
  group: "baz",
  value: 98,
  name: "H"
}, {
  group: "baz",
  value: 12,
  name: "I"
}, {
  group: "baz",
  value: 43,
  name: "J"
}, {
  group: "baz",
  value: 66,
  name: "K"
}, {
  group: "baz",
  value: 42,
  name: "L"
}];

var color = d3.scaleOrdinal(d3.schemeCategory10);

var xScale = d3.scaleLinear()
  .range([0, w - p])
  .domain([0, d3.max(data, function(d) {
    return d.value
  })]);

var yScale = d3.scaleBand()
  .range([0, h])
  .domain(data.map(function(d) {
    return d.name
  }))
  .padding(0.1);

svg.selectAll(".bars")
  .data(data, function(d) {
    return d.name
  })
  .enter()
  .append("rect")
  .attr("class", "bars")
  .attr("x", p)
  .attr("y", function(d) {
    return yScale(d.name)
  })
  .attr("width", function(d) {
    return xScale(d.value)
  })
  .attr("height", yScale.bandwidth())
  .attr("fill", function(d) {
    return color(d.group)
  })

var axis = d3.axisLeft(yScale);
var gY = svg.append("g").attr("transform", "translate(" + p + ",0)")
  .call(axis);

setTimeout(function() {

  data.sort(function(a, b) {
    return d3.ascending(a.value, b.value)
  });

  yScale.domain(data.map(function(d) {
    return d.name
  }));

  svg.selectAll(".bars").data(data, function(d) {
      return d.name
    })
    .transition()
    .duration(500)
    .attr("y", function(d) {
      return yScale(d.name)
    })
    .attr("width", function(d) {
      return xScale(d.value)
    });

  gY.transition().duration(1000).call(axis);

}, 1000)

d3.selectAll("button").on("click", function() {

  svg.selectAll(".bars").data(data2, function(d) {
      return d.name
    })
    .transition()
    .duration(500)
    .attr("y", function(d) {
      return yScale(d.name)
    })
    .attr("width", function(d) {
      return xScale(d.value)
    });

  gY.transition().duration(1000).call(axis);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script>
<button>Update</button>
<br>
<br></code>```

Your challenge here is the same: change the code inside .on("click"), which is just this...

```<code>svg.selectAll(".bars").data(data2, function(d) {
        return d.name
    })
    .transition()
    .duration(500)
    .attr("y", function(d) {
        return yScale(d.name)
    })
    .attr("width", function(d) {
        return xScale(d.value)
    });

gY.transition().duration(1000).call(axis);
</code>```

... to a code that does the same, but for your map() approach.

Bear in mind that, since I sorted the bars, you cannot change them by the index of your data array anymore!

Conclusion

The map() approach may save you 2 lines when you first draw the elements. However, it will make things terribly cumbersome later on.

Body:
I am trying to understand what's benefit of using d3.selectAll.data.enter() to loop through a dataset and plot it.

  var data = [4, 8, 15, 16, 23, 42];

  var x = d3.scale.linear()
      .domain([0, d3.max(data)])
      .range([0, 420]);

  let chartsvg = d3.select(".chart").append("svg");

  chartsvg.selectAll("rect")
    .data(data)
    .enter()
    .append("rect")
    .attr("x", 0)
    .attr("y", function(d, i) {
    return 25*i;
  })
    .attr("width", function(d) {
    return x(d);
  })
    .attr("height", 20)
    .attr("fill", "#f3b562");

I see a lot of benefit of d3's functionalities like scale, axes, etc. But it feels like using Array.map() for looping through the dataset, I can achieve the same functionality with much cleaner code and fewer lines, especially when I am creating a much more complex visualization and not a simple barebones bar chart like this.

  var data = [4, 8, 15, 16, 23, 42];

  var x = d3.scale.linear()
      .domain([0, d3.max(data)])
      .range([0, 420]);

  let chartsvg = d3.select(".chart").append("svg");

  data.map(function(d, i){
    chartsvg.append("rect")
      .attr("x", 0)
      .attr("y", 25*i)
      .attr("width", x(d))
      .attr("height", 20)
      .attr("fill", "#f3b562");
  });

Body:
D3 stands for Data-Driven Documents

The most powerful feature in D3, which gives the very name of the library, is its ability to bind data to DOM elements. By doing this, you can manipulate those DOM elements based on the bound data in several ways, such as (but not limited to):

Sort

Filter

Translate

Style

Append

Remove

And so on...

If you don't bind data to the DOM elements, for instance using the map() approach in your question (which is the same of a forEach()), you may save a couple of lines at the beginning, but you will end up with an awkward code to deal with later. Let's see it:

The map() approach

Here is a very simple code, using most of your snippet, to create a bar chart using the map() approach:

var h = 250,
  w = 500,
  p = 40;
var svg = d3.select("body")
  .append("svg")
  .attr("width", w)
  .attr("height", h);

var data = [{
  group: "foo",
  value: 14,
  name: "A"
}, {
  group: "foo",
  value: 35,
  name: "B"
}, {
  group: "foo",
  value: 87,
  name: "C"
}, {
  group: "foo",
  value: 12,
  name: "D"
}, {
  group: "bar",
  value: 84,
  name: "E"
}, {
  group: "bar",
  value: 65,
  name: "F"
}, {
  group: "bar",
  value: 34,
  name: "G"
}, {
  group: "baz",
  value: 98,
  name: "H"
}, {
  group: "baz",
  value: 12,
  name: "I"
}, {
  group: "baz",
  value: 43,
  name: "J"
}, {
  group: "baz",
  value: 66,
  name: "K"
}, {
  group: "baz",
  value: 42,
  name: "L"
}];

var color = d3.scaleOrdinal(d3.schemeCategory10);

var xScale = d3.scaleLinear()
  .range([0, w - p])
  .domain([0, d3.max(data, function(d) {
    return d.value
  })]);

var yScale = d3.scaleBand()
  .range([0, h])
  .domain(data.map(function(d) {
    return d.name
  }))
  .padding(0.1);

data.map(function(d, i) {
  svg.append("rect")
    .attr("x", p)
    .attr("y", yScale(d.name))
    .attr("width", xScale(d.value))
    .attr("height", yScale.bandwidth())
    .attr("fill", color(d.group));
});

var axis = d3.axisLeft(yScale);
var gY = svg.append("g").attr("transform", "translate(" + p + ",0)")
  .call(axis);

<script src="https://d3js.org/d3.v4.min.js"></script>

It seems to be a nice result, the bars are all there. However, there is no data bound to those rectangles. Keep this code, we'll use it in the challenge below.

Enter selections

Now let's try the same code, but using the idiomatic "enter" selection:

var h = 250,
  w = 500,
  p = 40;

var svg = d3.select("body")
  .append("svg")
  .attr("width", w)
  .attr("height", h);

var data = [{
  group: "foo",
  value: 14,
  name: "A"
}, {
  group: "foo",
  value: 35,
  name: "B"
}, {
  group: "foo",
  value: 87,
  name: "C"
}, {
  group: "foo",
  value: 12,
  name: "D"
}, {
  group: "bar",
  value: 84,
  name: "E"
}, {
  group: "bar",
  value: 65,
  name: "F"
}, {
  group: "bar",
  value: 34,
  name: "G"
}, {
  group: "baz",
  value: 98,
  name: "H"
}, {
  group: "baz",
  value: 12,
  name: "I"
}, {
  group: "baz",
  value: 43,
  name: "J"
}, {
  group: "baz",
  value: 66,
  name: "K"
}, {
  group: "baz",
  value: 42,
  name: "L"
}];

var color = d3.scaleOrdinal(d3.schemeCategory10);

var xScale = d3.scaleLinear()
  .range([0, w - p])
  .domain([0, d3.max(data, function(d) {
    return d.value
  })]);

var yScale = d3.scaleBand()
  .range([0, h])
  .domain(data.map(function(d) {
    return d.name
  }))
  .padding(0.1);

svg.selectAll(null)
  .data(data, function(d) {
    return d.name
  })
  .enter()
  .append("rect")
  .attr("x", p)
  .attr("y", function(d) {
    return yScale(d.name)
  })
  .attr("width", function(d) {
    return xScale(d.value)
  })
  .attr("height", yScale.bandwidth())
  .attr("fill", function(d) {
    return color(d.group)
  });

var axis = d3.axisLeft(yScale);
var gY = svg.append("g").attr("transform", "translate(" + p + ",0)")
  .call(axis);

<script src="https://d3js.org/d3.v4.min.js"></script>

As you can see, it's a little longer than the previous map() method, 2 lines longer.

However, this actually binds data to those rectangles. If you console.log a D3 selection of one of those rectangles, you'll see something like this (in Chrome):

> Selection
  > _groups: Array(1)
    > 0: Array(1)
      > 0: rect
        > __data__: Object
          group: "bar"
          name: "G"
          value: 34

Since this code actually binds data to the DOM elements, you can manipulate them in a way that would be cumbersome (to say the least) using the map() approach. I'll show this in the next snippet, which will be used to propose a challenge.

Challenge

Since your question talks about cleaner code and fewer lines, here is a challenge for you.

I created 3 buttons, one for each group in the data array (and a fourth one for all the groups). When you click the button, it filters the data and updates the chart accordingly:

var h = 250,
  w = 500,
  p = 40;
var svg = d3.select("body")
  .append("svg")
  .attr("width", w)
  .attr("height", h);

var g1 = svg.append("g")
var g2 = svg.append("g")

var data = [{
  group: "foo",
  value: 14,
  name: "A"
}, {
  group: "foo",
  value: 35,
  name: "B"
}, {
  group: "foo",
  value: 87,
  name: "C"
}, {
  group: "foo",
  value: 12,
  name: "D"
}, {
  group: "bar",
  value: 84,
  name: "E"
}, {
  group: "bar",
  value: 65,
  name: "F"
}, {
  group: "bar",
  value: 34,
  name: "G"
}, {
  group: "baz",
  value: 98,
  name: "H"
}, {
  group: "baz",
  value: 12,
  name: "I"
}, {
  group: "baz",
  value: 43,
  name: "J"
}, {
  group: "baz",
  value: 66,
  name: "K"
}, {
  group: "baz",
  value: 42,
  name: "L"
}];

var color = d3.scaleOrdinal(d3.schemeCategory10);

var xScale = d3.scaleLinear()
  .range([0, w - p])
  .domain([0, d3.max(data, function(d) {
    return d.value
  })]);

var yScale = d3.scaleBand()
  .range([0, h])
  .domain(data.map(function(d) {
    return d.name
  }))
  .padding(0.1);

var axis = d3.axisLeft(yScale);
var gY = g2.append("g").attr("transform", "translate(" + p + ",0)")
  .call(axis);

draw(data);

function draw(data) {

  yScale.domain(data.map(function(d) {
    return d.name
  }))

  var rects = g1.selectAll("rect")
    .data(data, function(d) {
      return d.name
    })

  rects.enter()
    .append("rect")
    .attr("x", p)
    .attr("y", function(d) {
      return yScale(d.name)
    })
    .attr("width", 0)
    .attr("height", yScale.bandwidth())
    .attr("fill", function(d) {
      return color(d.group)
    })
    .transition()
    .duration(1000)
    .attr("width", function(d) {
      return xScale(d.value)
    });

  rects.transition()
    .duration(1000)
    .attr("x", p)
    .attr("y", function(d) {
      return yScale(d.name)
    })
    .attr("width", function(d) {
      return xScale(d.value)
    })
    .attr("height", yScale.bandwidth())
    .attr("fill", function(d) {
      return color(d.group)
    });

  rects.exit()
    .transition()
    .duration(1000)
    .attr("width", 0)
    .remove();

  gY.transition().duration(1000).call(axis);
};

d3.selectAll("button").on("click", function() {

  var thisValue = this.id;

  var newData = thisValue === "all" ? data : data.filter(function(d) {
    return d.group === thisValue;
  });

  draw(newData)
});

<script src="https://d3js.org/d3.v4.min.js"></script>
<button id="foo">Foo</button>
<button id="bar">Bar</button>
<button id="baz">Baz</button>
<button id="all">All</button>
<br>
<br>

A cleaner code is somehow opinion-based, but we can easily measure size.

Thus, here is the challenge: try to create a code that does the same, but using the map() approach, that is, without binding any data. Do all the transitions I'm doing here. The code you will try to recreate is all the code inside the on("click") function.

After that, we'll compare the size of your code and the size of an idiomatic "enter", "update" and "exit" selections.

Chalenge #2

This challenge number 2 may be even more interesting to show D3 capabilities when it comes to binding data.

In this new code, I'm sorting the original data array after 1 second, and redrawing the chart. Then, clicking on the "update" button, I'm binding another data array to the bars.

The nice thing here is the key function, that associates each bar to each data point using, in this case, the name property:

.data(data, function(d) {
    return d.name
})

Here is the code, please wait 1 second before clicking "update":

var h = 250,
  w = 500,
  p = 40;

var svg = d3.select("body")
  .append("svg")
  .attr("width", w)
  .attr("height", h);

var data2 = [{
  group: "foo",
  value: 10,
  name: "A"
}, {
  group: "foo",
  value: 20,
  name: "B"
}, {
  group: "foo",
  value: 30,
  name: "C"
}, {
  group: "foo",
  value: 40,
  name: "D"
}, {
  group: "bar",
  value: 50,
  name: "E"
}, {
  group: "bar",
  value: 60,
  name: "F"
}, {
  group: "bar",
  value: 70,
  name: "G"
}, {
  group: "baz",
  value: 80,
  name: "H"
}, {
  group: "baz",
  value: 85,
  name: "I"
}, {
  group: "baz",
  value: 90,
  name: "J"
}, {
  group: "baz",
  value: 95,
  name: "K"
}, {
  group: "baz",
  value: 100,
  name: "L"
}];

var data = [{
  group: "foo",
  value: 14,
  name: "A"
}, {
  group: "foo",
  value: 35,
  name: "B"
}, {
  group: "foo",
  value: 87,
  name: "C"
}, {
  group: "foo",
  value: 12,
  name: "D"
}, {
  group: "bar",
  value: 84,
  name: "E"
}, {
  group: "bar",
  value: 65,
  name: "F"
}, {
  group: "bar",
  value: 34,
  name: "G"
}, {
  group: "baz",
  value: 98,
  name: "H"
}, {
  group: "baz",
  value: 12,
  name: "I"
}, {
  group: "baz",
  value: 43,
  name: "J"
}, {
  group: "baz",
  value: 66,
  name: "K"
}, {
  group: "baz",
  value: 42,
  name: "L"
}];

var color = d3.scaleOrdinal(d3.schemeCategory10);

var xScale = d3.scaleLinear()
  .range([0, w - p])
  .domain([0, d3.max(data, function(d) {
    return d.value
  })]);

var yScale = d3.scaleBand()
  .range([0, h])
  .domain(data.map(function(d) {
    return d.name
  }))
  .padding(0.1);

svg.selectAll(".bars")
  .data(data, function(d) {
    return d.name
  })
  .enter()
  .append("rect")
  .attr("class", "bars")
  .attr("x", p)
  .attr("y", function(d) {
    return yScale(d.name)
  })
  .attr("width", function(d) {
    return xScale(d.value)
  })
  .attr("height", yScale.bandwidth())
  .attr("fill", function(d) {
    return color(d.group)
  })

var axis = d3.axisLeft(yScale);
var gY = svg.append("g").attr("transform", "translate(" + p + ",0)")
  .call(axis);

setTimeout(function() {

  data.sort(function(a, b) {
    return d3.ascending(a.value, b.value)
  });

  yScale.domain(data.map(function(d) {
    return d.name
  }));

  svg.selectAll(".bars").data(data, function(d) {
      return d.name
    })
    .transition()
    .duration(500)
    .attr("y", function(d) {
      return yScale(d.name)
    })
    .attr("width", function(d) {
      return xScale(d.value)
    });

  gY.transition().duration(1000).call(axis);

}, 1000)

d3.selectAll("button").on("click", function() {

  svg.selectAll(".bars").data(data2, function(d) {
      return d.name
    })
    .transition()
    .duration(500)
    .attr("y", function(d) {
      return yScale(d.name)
    })
    .attr("width", function(d) {
      return xScale(d.value)
    });

  gY.transition().duration(1000).call(axis);
})

<script src="https://d3js.org/d3.v4.min.js"></script>
<button>Update</button>
<br>
<br>

Your challenge here is the same: change the code inside .on("click"), which is just this...

svg.selectAll(".bars").data(data2, function(d) {
        return d.name
    })
    .transition()
    .duration(500)
    .attr("y", function(d) {
        return yScale(d.name)
    })
    .attr("width", function(d) {
        return xScale(d.value)
    });

gY.transition().duration(1000).call(axis);

... to a code that does the same, but for your map() approach.

Bear in mind that, since I sorted the bars, you cannot change them by the index of your data array anymore!

Conclusion

The map() approach may save you 2 lines when you first draw the elements. However, it will make things terribly cumbersome later on.


来源: stackexchange

问:
Copy all but one field with Lodash, without using Object.assign()
If I have an object like so:

```<code>const obj  = { A: 1, B: 2, C: 3, D: 4 };
</code>```

How can I copy all key/values except for C to a new object?

Underscore has the _.pick() functionality, but I am looking to do the opposite.

答: You can achieve this with the omit method : https://lodash.com/docs/4.17.4#omit</p>

ContentLicense: CC BY-SA 3.0

Body:
If I have an object like so:

const obj  = { A: 1, B: 2, C: 3, D: 4 };

How can I copy all key/values except for C to a new object?

Underscore has the _.pick() functionality, but I am looking to do the opposite.


答:
The reason why np.hstack([matrix, vector]) doesn't work is because the shapes don't fit each other:

```<code>>>> vector.shape
(6,)
>>> matrix.shape
(6, 5)
</code>```

But if you make vector a column vector with vector[:, np.newaxis] then np.hstack can handle the shapes:

```<code>>>> matrix = np.arange(30).reshape(6,5)
>>> vector = -np.ones(6)
>>> matrix
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24],
       [25, 26, 27, 28, 29]])
>>> vector
array([-1., -1., -1., -1., -1., -1.])
>>> vector[:, np.newaxis]
array([[-1.],
       [-1.],
       [-1.],
       [-1.],
       [-1.],
       [-1.]])
>>> vector[:, np.newaxis].shape
(6, 1)
>>> np.hstack([matrix, vector])
Rückverfolgung (innerste zuletzt):
  Python-Shell, prompt 23, line 1
  File "C:\Python34\Lib\site-packages\numpy\core\shape_base.py", line 293, in hstack
    return _nx.concatenate(arrs, 1)
builtins.ValueError: all the input arrays must have same number of dimensions
>>> np.hstack([matrix, vector[:, np.newaxis]])
array([[  0.,   1.,   2.,   3.,   4.,  -1.],
       [  5.,   6.,   7.,   8.,   9.,  -1.],
       [ 10.,  11.,  12.,  13.,  14.,  -1.],
       [ 15.,  16.,  17.,  18.,  19.,  -1.],
       [ 20.,  21.,  22.,  23.,  24.,  -1.],
       [ 25.,  26.,  27.,  28.,  29.,  -1.]])
</code>```

Title: Adding a vector as a new column to a matrix

Body:
I have a matrix with 6 rows and 5 columns, and a 1d vector of length 6 that I want to add to my matrix as as new 6th column so that I end up with an 6x6 matrix.

The 1d-vector

[0.77777777777777779, 0.061224489795918366, 0.86864406779661019, 0.66666666666666663, 0.96470588235294119, 83.333333333333343]

The matrix

[[  42.            0.            6.            0.            6.        ]
 [   0.            3.            8.            0.           38.        ]
 [   6.            0.          205.            0.           25.        ]
 [   0.            0.            2.            4.            0.        ]
 [   1.            0.            8.            0.          246.        ]
 [   0.85714286    1.            0.89519651    1.            0.78095238]]

I've tried np.hstack but that does not work for this job.

Body:
The reason why np.hstack([matrix, vector]) doesn't work is because the shapes don't fit each other:

>>> vector.shape
(6,)
>>> matrix.shape
(6, 5)

But if you make vector a column vector with vector[:, np.newaxis] then np.hstack can handle the shapes:

>>> matrix = np.arange(30).reshape(6,5)
>>> vector = -np.ones(6)
>>> matrix
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24],
       [25, 26, 27, 28, 29]])
>>> vector
array([-1., -1., -1., -1., -1., -1.])
>>> vector[:, np.newaxis]
array([[-1.],
       [-1.],
       [-1.],
       [-1.],
       [-1.],
       [-1.]])
>>> vector[:, np.newaxis].shape
(6, 1)
>>> np.hstack([matrix, vector])
Rückverfolgung (innerste zuletzt):
  Python-Shell, prompt 23, line 1
  File "C:\Python34\Lib\site-packages\numpy\core\shape_base.py", line 293, in hstack
    return _nx.concatenate(arrs, 1)
builtins.ValueError: all the input arrays must have same number of dimensions
>>> np.hstack([matrix, vector[:, np.newaxis]])
array([[  0.,   1.,   2.,   3.,   4.,  -1.],
       [  5.,   6.,   7.,   8.,   9.,  -1.],
       [ 10.,  11.,  12.,  13.,  14.,  -1.],
       [ 15.,  16.,  17.,  18.,  19.,  -1.],
       [ 20.,  21.,  22.,  23.,  24.,  -1.],
       [ 25.,  26.,  27.,  28.,  29.,  -1.]])


问:
average over columns for the matrix with Nan values
I have the matrix below:

```<code>rmat =

     1     2     3   NaN   NaN   NaN
     1     2     3     4     5   NaN
     1     2     3     4     5     6
     1   NaN   NaN   NaN   NaN   NaN
     NaN   NaN   NaN   NaN   NaN   NaN
</code>```

is there any way to calculate the average of the coulmns that has value: for i.e in the first column (1+1+1+1)/4=0.25 and just skip Nan and for the second column (2+2+2)/3=2 and so on...

Any advice will be highly appriciated

答: The nanmean() function sounds like what you might be after: https://uk.mathworks.com/help/stats/nanmean.html

Body:
I have the matrix below:

rmat =

     1     2     3   NaN   NaN   NaN
     1     2     3     4     5   NaN
     1     2     3     4     5     6
     1   NaN   NaN   NaN   NaN   NaN
     NaN   NaN   NaN   NaN   NaN   NaN

is there any way to calculate the average of the coulmns that has value: for i.e in the first column (1+1+1+1)/4=0.25 and just skip Nan and for the second column (2+2+2)/3=2 and so on...

Any advice will be highly appriciated


问:
Angular JS: Failed to instantiate module myApp
i was testing a small angular directives code then i got the error by firebug console that Failed to instantiate module myApp

see and tell me what is wrong in the above code

```<code>  <div ng-app="myApp">
    <div log='some-div'></div>
    <p>Have a look at you console!</p>
  </div>

var myApp = angular.module('myApp', []);

myApp.directive('log', function() {

  return {
    controller: function( $scope, $attrs ) {
      console.log( $attrs.log + ' (controller)' );
    },
    compile: function compile( tElement, tAttributes ) {
      console.log( tAttributes.log + ' (compile)'  );
      return {
        pre: function preLink( scope, element, attributes ) {
          console.log( attributes.log + ' (pre-link)'  );
        },
        post: function postLink( scope, element, attributes ) {
          console.log( attributes.log + ' (post-link)'  );
        }
      };
    }
  };

});
</code>```

答:
Not sure why but your fiddle code doesn't work. Used same code in my fiddle and it works

https://jsfiddle.net/sathvike/e7vkqxs8/

If you use this code in your fiddle it works

```<code><div ng-app='myApp'>
    <div log='some-div'></div>
    <p>Have a look at you console!</p>
 </div>
 <script type="text/javascript">
 var myApp = angular.module('myApp', []);
 myApp.directive('log', function() {

 return {
     controller: function($scope, $attrs) {
     console.log($attrs.log + ' (controller)');
  },
  compile: function(tElement, tAttributes) {
    console.log(tAttributes.log + ' (compile)');
    return {
      pre: function preLink(scope, element, attributes) {
        console.log(attributes.log + ' (pre-link)');
      },
      post: function postLink(scope, element, attributes) {
        console.log(attributes.log + ' (post-link)');
      }
    };
  }
  };

 });
</script>
</code>```

Body:
i was testing a small angular directives code then i got the error by firebug console that Failed to instantiate module myApp

see and tell me what is wrong in the above code

Have a look at you console!

var myApp = angular.module('myApp', []);

myApp.directive('log', function() {

  return {
    controller: function( $scope, $attrs ) {
      console.log( $attrs.log + ' (controller)' );
    },
    compile: function compile( tElement, tAttributes ) {
      console.log( tAttributes.log + ' (compile)'  );
      return {
        pre: function preLink( scope, element, attributes ) {
          console.log( attributes.log + ' (pre-link)'  );
        },
        post: function postLink( scope, element, attributes ) {
          console.log( attributes.log + ' (post-link)'  );
        }
      };
    }
  };

});

Body:
Not sure why but your fiddle code doesn't work. Used same code in my fiddle and it works

https://jsfiddle.net/sathvike/e7vkqxs8/

If you use this code in your fiddle it works

<div ng-app='myApp'>
    <div log='some-div'></div>
    <p>Have a look at you console!</p>
 </div>
 <script type="text/javascript">
 var myApp = angular.module('myApp', []);
 myApp.directive('log', function() {

 return {
     controller: function($scope, $attrs) {
     console.log($attrs.log + ' (controller)');
  },
  compile: function(tElement, tAttributes) {
    console.log(tAttributes.log + ' (compile)');
    return {
      pre: function preLink(scope, element, attributes) {
        console.log(attributes.log + ' (pre-link)');
      },
      post: function postLink(scope, element, attributes) {
        console.log(attributes.log + ' (post-link)');
      }
    };
  }
  };

 });
</script>


问:
Entity Framework 5: Concatenate two fields
I want to concatenate two fields and list all items of a database class. Using Entity framework and ASP.Net MVC's list method, why can't I do something like this?

```<code>@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.FName + " " + item.Lname)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Address)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.CustomerID }) |
            @Html.ActionLink("Accounts", "Accounts", new { id=item.CustomerID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.CustomerID })
        </td>
    </tr>
}
</code>```

I get the following error:

```<code>Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS1061: 'Customer' does not contain a definition for 'Lname' and no extension method 'Lname' accepting a first argument of type 'Customer' could be found (are you missing a using directive or an assembly reference?)
</code>```

How to work around this?

答:
Simple fix:

```<code>@Html.DisplayFor(modelItem => item.FName) @Html.DisplayFor(modelItem => item.LName)
</code>```

Alternatively, add a property to your model:

```<code>public string FullName { get { return FName + " " + LName; } }
</code>```

and then do:

```<code>@Html.DisplayFor(modelItem => item.FullName)
</code>```

Additional note:

Upon further inspection of your error, I suspect that you have mistyped Lname - perhaps you meant LName? Regardless, using concatenation in that way will not work and will result in this error, instead:

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

Body:
I want to concatenate two fields and list all items of a database class. Using Entity framework and ASP.Net MVC's list method, why can't I do something like this?

@foreach (var item in Model) {

            @Html.DisplayFor(modelItem => item.FName + " " + item.Lname)

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

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

            @Html.ActionLink("Edit", "Edit", new { id=item.CustomerID }) |
            @Html.ActionLink("Accounts", "Accounts", new { id=item.CustomerID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.CustomerID })

}

I get the following error:

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS1061: 'Customer' does not contain a definition for 'Lname' and no extension method 'Lname' accepting a first argument of type 'Customer' could be found (are you missing a using directive or an assembly reference?)

How to work around this?

Body:
Simple fix:

@Html.DisplayFor(modelItem => item.FName) @Html.DisplayFor(modelItem => item.LName)

Alternatively, add a property to your model:

public string FullName { get { return FName + " " + LName; } }

and then do:

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

Additional note:

Upon further inspection of your error, I suspect that you have mistyped Lname - perhaps you meant LName? Regardless, using concatenation in that way will not work and will result in this error, instead:

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.


问:
Why is sfinae on if constexpr not allowed?
The detection idiom works as follows

```<code>template<typename T, typename = void>
struct has_foo {static constexpr bool value = false;};
template<typename T>
struct has_foo<T, std::void_t<decltype(&T::foo)>> {static constexpr bool value = true;};
template<typename T>
constexpr bool has_foo_v = has_foo<T>::value;
</code>```

And then we can detect the presence of foo in any type T.

```<code>if constexpr(has_foo_v<decltype(var)>)
    var.foo();
</code>```

My problem is, that is quite a lot to type (read: want to smash my keyboard a lot to type), and I wondered if the following is possible

```<code>if constexpr(std::void_t<decltype(&decltype(var)::foo)>(), true)
    var.foo();
</code>```

It is not.

Is there a reason behind this?

More specifically, what trade-offs will have to be made if this were allowed?

答:
Since c++17 there is always a constexpr lambda workaround if you really need to do sfinae inline:

```<code>#include <utility>

template <class Lambda, class... Ts>
constexpr auto test_sfinae(Lambda lambda, Ts&&...)
    -> decltype(lambda(std::declval<Ts>()...), bool{}) { return true; }
constexpr bool test_sfinae(...)  { return false; }

template <class T>
constexpr bool bar(T var) {
    if constexpr(test_sfinae([](auto v) -> decltype(v.foo()){}, var))
       return true;
    return false;
}

struct A {
    void foo() {}
};

struct B { };

int main() {
    static_assert(bar(A{}));
    static_assert(!bar(B{}));
}
</code>```

[live demo]

Body:
The detection idiom works as follows

template<typename T, typename = void>
struct has_foo {static constexpr bool value = false;};
template<typename T>
struct has_foo<T, std::void_t<decltype(&T::foo)>> {static constexpr bool value = true;};
template<typename T>
constexpr bool has_foo_v = has_foo<T>::value;

And then we can detect the presence of foo in any type T.

if constexpr(has_foo_v<decltype(var)>)
    var.foo();

My problem is, that is quite a lot to type (read: want to smash my keyboard a lot to type), and I wondered if the following is possible

if constexpr(std::void_t<decltype(&decltype(var)::foo)>(), true)
    var.foo();

It is not.

Is there a reason behind this?

More specifically, what trade-offs will have to be made if this were allowed?

Body:
Since c++17 there is always a constexpr lambda workaround if you really need to do sfinae inline:

#include <utility>

template <class Lambda, class... Ts>
constexpr auto test_sfinae(Lambda lambda, Ts&&...)
    -> decltype(lambda(std::declval<Ts>()...), bool{}) { return true; }
constexpr bool test_sfinae(...)  { return false; }

template <class T>
constexpr bool bar(T var) {
    if constexpr(test_sfinae([](auto v) -> decltype(v.foo()){}, var))
       return true;
    return false;
}

struct A {
    void foo() {}
};

struct B { };

int main() {
    static_assert(bar(A{}));
    static_assert(!bar(B{}));
}

[live demo]


问:
how to get the dignostic date which is closest to a specified repair date for a particular vehicle from the table in R
I have created table data frame(tbl_df) called "Data1" (25000*4) as follows using dplyr:-
Data1 sample

```<code>Vehicle.no   Repair date  mileage    Diagnosis date
23334         2011-03-03    5160       2011-09-29
23334         2011-03-03    5160       2012-09-29
23334         2011-03-03    5160       2010-09-29
23334         2011-03-03    5160       2010-10-29
</code>```

Here I have unique Vehicle.no, Repair date & mileage as you see in the example and since I have a different diagnostic dates for the same vehicle.no, it is recorded for the multiple times.

Finally I would like to have a table with single diagnostic date which is closest to a specified repair date for a particular vehicle no as follows:-

```<code>Vehicle.no   Repair date  mileage    Diagnosis date
23334        2011-03-03    5160       2010-10-29
</code>```

I have already tried my level best to extract this information using dplyr as follows:-

```<code>Data1<-Data1%>%
       group_by(Vehicle.no,`Repair date.x`) %>%
       select(Data1$`Diagnosis start date`(which(abs(Data1$`Repair date.x`- Data1$`Diagnosis start date`) == min(abs(Data1$`Repair date.x`- Data1$`Diagnosis start date`)))))
</code>```

Since I am a new user to R, I would need some help from you guys.

Thanks

答:
I made a small adjustment to the column names just FYI,

```<code>library(dplyr)
Data1$Repair.date <- as.Date(Data1$Repair.date, format = "%m/%d/%Y")
Data1$Diagnosis.date <- as.Date(Data1$Diagnosis.date, format = "%m/%d/%Y")
</code>```

I think this next part can be condensed into 1 command but I am pressed for time:

```<code>Data1 <- mutate(Data1, date.dif = Diagnosis.date - Repair.date, date.dif = abs(date.dif))

Data2 <- filter(Data1, date.dif == min(date.dif))
</code>```

Body:
I have created table data frame(tbl_df) called "Data1" (25000*4) as follows using dplyr:-
Data1 sample

Vehicle.no   Repair date  mileage    Diagnosis date
23334         2011-03-03    5160       2011-09-29
23334         2011-03-03    5160       2012-09-29
23334         2011-03-03    5160       2010-09-29
23334         2011-03-03    5160       2010-10-29

Here I have unique Vehicle.no, Repair date & mileage as you see in the example and since I have a different diagnostic dates for the same vehicle.no, it is recorded for the multiple times.

Finally I would like to have a table with single diagnostic date which is closest to a specified repair date for a particular vehicle no as follows:-

Vehicle.no   Repair date  mileage    Diagnosis date
23334        2011-03-03    5160       2010-10-29

I have already tried my level best to extract this information using dplyr as follows:-

Data1<-Data1%>%
       group_by(Vehicle.no,`Repair date.x`) %>%
       select(Data1$`Diagnosis start date`(which(abs(Data1$`Repair date.x`- Data1$`Diagnosis start date`) == min(abs(Data1$`Repair date.x`- Data1$`Diagnosis start date`)))))

Since I am a new user to R, I would need some help from you guys.

Thanks

Body:
I made a small adjustment to the column names just FYI,

library(dplyr)
Data1$Repair.date <- as.Date(Data1$Repair.date, format = "%m/%d/%Y")
Data1$Diagnosis.date <- as.Date(Data1$Diagnosis.date, format = "%m/%d/%Y")

I think this next part can be condensed into 1 command but I am pressed for time:

Data1 <- mutate(Data1, date.dif = Diagnosis.date - Repair.date, date.dif = abs(date.dif))

Data2 <- filter(Data1, date.dif == min(date.dif))


问:
C++ using exceptions
I have a simple question

If I have a code with try and catch, like this

```<code>try
{
...
}
catch(exception& ex)
{
   AfxMessageBox(ex.what());
}
</code>```

Will this catch all the exceptions, even exceptions like bad pointer, etc? And also, if this code is there and for example, the code has a pointer, or memory problem, will it still crash? Or do I have to use

```<code>catch(...)
</code>```

But how can I exactly pinpoint what was the reason of an enentual crash then?

答:
If your code has undefined behavior, that could cause almost anything to happen, including throwing an exception.

Visual C++ 6 did (by default) convert some OS-level exceptions like that to C++ exceptions, as you're discussing here. It apparently didn't work out very well though--their newer compilers do not do this by default. If you really want that behavior, they do provide a compiler switch (e.g., /EHa) that will let you do that--but most people probably wouldn't advise using that.

Windows Structured Exception Handling has a SetUnhandledExceptionHandler, which will let you catch SEH exceptions, sort out what exception you've caught, and throw a C++ exception you feel is appropriate to signify what's happened. This, however, is a fairly manual process (i.e., it's up to you to write something like a switch statement to sort out the structured exception you've caught, and decide what C++ exception to throw in response to that).

Likewise, on Linux you could set up handlers for various signals, and throw exceptions in response to them. You may need to get a bit tricky about this though. The problem is that POSIX signals are delivered asynchronously, and you're very limited in what you can do in them. Nearly the only thing the signal handler itself can do is set a flag of type sig_atomic_t, and outside code can (when convenient) check its value, and if it's set, throw an exception. Mixing signals and exceptions is generally a rather non-trivial undertaking though.

As far as catch(...) goes, it'll only catch C++ exceptions, so it'll only catch things like memory problems as noted above, if you use it along with some sort of translation to create a C++ exception from the structured exception/signal. As to what you can do there: it's really pretty limited. You can't get any information about the exception that happened at all. At least when I've used it, it was pretty much a last-ditch thing that attempted to manage as orderly of a shut-down as possible, simply because by the time it was entered, any possibility of doing anything more intelligent had been exhausted in more specific handlers.

Title: C++ using exceptions

Body:
I have a simple question

If I have a code with try and catch, like this

try
{
...
}
catch(exception& ex)
{
   AfxMessageBox(ex.what());
}

Will this catch all the exceptions, even exceptions like bad pointer, etc? And also, if this code is there and for example, the code has a pointer, or memory problem, will it still crash? Or do I have to use

catch(...)

But how can I exactly pinpoint what was the reason of an enentual crash then?


问:
Merging two files by matching of three columns + calculating mean for the output
I have a small problem when merging files based on three separate columns. First, my code and the file structure and more details regarding my question below. Here is my setup so far:

```<code>#making directories
subprocess.call( """ mkdir %s/junctions """%(temp_dir), shell=True)
subprocess.call( """ mkdir %s/out """%(temp_dir), shell=True)

#opening a file with paths to other files
with open(sys.argv[2],"r") as j:
    #creating the output file
    subprocess.call( """ touch %s/junctions/catjunc.txt  """%(temp_dir), shell=True)

    for line in j:
        #reformatting the input file (not important for this question)
        command = """awk 'BEGIN{OFS="\t"}{print $1, $2-20-1, $3+20, "JUNCBJ"NR"%s", $7, ($4 == 1)? "+":"-",$2-20-1, $3+20, "255,0,0", 2, "20,20", "0,300", $7, $8 ,$5 , $6}' %s > %s"""%(line[:-1].split(".")[0].split("/")[-1],line[:-1],temp_dir + "/junctions/junc.bed")
        subprocess.call( command, shell=True)

        # So here i basically concatenate the files. However, I also want to reduce them.
        subprocess.call( """ cat %s >> %s/junctions/catjunc.txt """%( temp_dir + "/junctions/junc.bed", temp_dir), shell=True)
</code>```

The files:

```<code>chrom   start   stop    ID                                                                                count1  count2
1       14809   14989   JUNCBJ1adipose_HS110_50bp_SJ    0       -       14809   14989   255,0,0 2       20,20   0,300   0       59      2       1
1       14809   15815   JUNCBJ2adipose_HS110_50bp_SJ    0       -       14809   15815   255,0,0 2       20,20   0,300   0       2       2       1
1       15018   15815   JUNCBJ4adipose_HS110_50bp_SJ    0       -       15018   15815   255,0,0 2       20,20   0,300   0       76      2       1
1       15927   16626   JUNCBJ5adipose_HS110_50bp_SJ    0       -       15927   16626   255,0,0 2       20,20   0,300   0       4       2       1
1       16745   16873   JUNCBJ6adipose_HS110_50bp_SJ    0       -       16745   16873   255,0,0 2       20,20   0,300   0       2       2       1
</code>```

All my files look like this. In column 1,2 and 3 are the chromosomes and start- and stop-coordinates. In columns 12 and 13 are some counts. In column 4 are the line IDs.
Now for my question. When concatenating both files, I want to carry over all unique lines. However, when there are two lines where all of the three first columns are identical, I want to only include one of the two in which the count values are replaced by the mean for both count columns (12 and 13). I also wanted to append both IDs (Not really important for now).

Example:

file1:

```<code>1       14809   14989   JUNCBJ1adipose_HS110_50bp_SJ    0       -       14809   14989   255,0,0 2       20,20   0,300   10       59      2       1
1       14809   15815   JUNCBJ2adipose_HS110_50bp_SJ    0       -       14809   15815   255,0,0 2       20,20   0,300   0       2       2       1
</code>```

file2:

```<code>1       14809   14989   JUNCBG2adipose_HS110_50bp_SJ    0       -       14809   14989   255,0,0 2       20,20   0,300   20       41      2       1
</code>```

Here, the first line appears in both files with counts 10 and 59 and, 20 and 41. In the output file the line occurs once with the counts 15 and 50. The second line is simply copied.

Output:

```<code>                                                                                replaced means
1       14809   14989   JUNCBJ1adipose_HS110_50bp_SJ,JUNCBG2adipose_HS110_50bp_SJ    0       -       14809   14989   255,0,0 2       20,20   0,300   15       50      2       1
1       14809   15815   JUNCBJ2adipose_HS110_50bp_SJ    0       -       14809   15815   255,0,0 2       20,20   0,300   0       2       2       1
</code>```

If there are any details I missed, I am happy to edit the post. Please don't judge my python-bash mix and

Cheers.

答:
Using awk. The field separator in your files were space(s) so the values 10 and 59 were in fields 13 and 14 ($13 and $14 in awk). If the field separators are tabs instead add BEGIN{FS=OFS="\t"} before the first { (untested but educated guess, whose words are an invitation for demo effect) and replace all 13 with 12 and 14 with 13 (in that order ;).

```<code>$ awk '
{
    a13[$1,$2,$3]+=$13                # sum field 13
    a14[$1,$2,$3]+=$14                # sum field 14
    $13="XX"                          # set a replaceable key to $13
    $14="YY"                          # see above
    a0[$1,$2,$3]=$0                   # now store the record
    an[$1,$2,$3]++                    # count instances of $1,$2,$3
}
END {                                 # after all the records
    for(i in a0) {                    # loop all stored records
        sub(/XX/,a13[i]/an[i],a0[i])  # replace XXs with means
        sub(/YY/,a14[i]/an[i],a0[i])  # and YY
        print a0[i] }                 # output
}' file1 file2
1 14809 15815 JUNCBJ2adipose_HS110_50bp_SJ 0 - 14809 15815 255,0,0 2 20,20 0,300 0 2 2 1
1 14809 14989 JUNCBG2adipose_HS110_50bp_SJ 0 - 14809 14989 255,0,0 2 20,20 0,300 15 50 2 1
</code>```

Naturally, if the keywords XX and YY appear in the data you run into problems but choose them accordingly.

Body:
I have a small problem when merging files based on three separate columns. First, my code and the file structure and more details regarding my question below. Here is my setup so far:

#making directories
subprocess.call( """ mkdir %s/junctions """%(temp_dir), shell=True)
subprocess.call( """ mkdir %s/out """%(temp_dir), shell=True)

#opening a file with paths to other files
with open(sys.argv[2],"r") as j:
    #creating the output file
    subprocess.call( """ touch %s/junctions/catjunc.txt  """%(temp_dir), shell=True)

    for line in j:
        #reformatting the input file (not important for this question)
        command = """awk 'BEGIN{OFS="\t"}{print $1, $2-20-1, $3+20, "JUNCBJ"NR"%s", $7, ($4 == 1)? "+":"-",$2-20-1, $3+20, "255,0,0", 2, "20,20", "0,300", $7, $8 ,$5 , $6}' %s > %s"""%(line[:-1].split(".")[0].split("/")[-1],line[:-1],temp_dir + "/junctions/junc.bed")
        subprocess.call( command, shell=True)

        # So here i basically concatenate the files. However, I also want to reduce them.
        subprocess.call( """ cat %s >> %s/junctions/catjunc.txt """%( temp_dir + "/junctions/junc.bed", temp_dir), shell=True)

The files:

chrom   start   stop    ID                                                                                count1  count2
1       14809   14989   JUNCBJ1adipose_HS110_50bp_SJ    0       -       14809   14989   255,0,0 2       20,20   0,300   0       59      2       1
1       14809   15815   JUNCBJ2adipose_HS110_50bp_SJ    0       -       14809   15815   255,0,0 2       20,20   0,300   0       2       2       1
1       15018   15815   JUNCBJ4adipose_HS110_50bp_SJ    0       -       15018   15815   255,0,0 2       20,20   0,300   0       76      2       1
1       15927   16626   JUNCBJ5adipose_HS110_50bp_SJ    0       -       15927   16626   255,0,0 2       20,20   0,300   0       4       2       1
1       16745   16873   JUNCBJ6adipose_HS110_50bp_SJ    0       -       16745   16873   255,0,0 2       20,20   0,300   0       2       2       1

All my files look like this. In column 1,2 and 3 are the chromosomes and start- and stop-coordinates. In columns 12 and 13 are some counts. In column 4 are the line IDs.
Now for my question. When concatenating both files, I want to carry over all unique lines. However, when there are two lines where all of the three first columns are identical, I want to only include one of the two in which the count values are replaced by the mean for both count columns (12 and 13). I also wanted to append both IDs (Not really important for now).

Example:

file1:

1       14809   14989   JUNCBJ1adipose_HS110_50bp_SJ    0       -       14809   14989   255,0,0 2       20,20   0,300   10       59      2       1
1       14809   15815   JUNCBJ2adipose_HS110_50bp_SJ    0       -       14809   15815   255,0,0 2       20,20   0,300   0       2       2       1

file2:

1       14809   14989   JUNCBG2adipose_HS110_50bp_SJ    0       -       14809   14989   255,0,0 2       20,20   0,300   20       41      2       1

Here, the first line appears in both files with counts 10 and 59 and, 20 and 41. In the output file the line occurs once with the counts 15 and 50. The second line is simply copied.

Output:

                                                                                replaced means
1       14809   14989   JUNCBJ1adipose_HS110_50bp_SJ,JUNCBG2adipose_HS110_50bp_SJ    0       -       14809   14989   255,0,0 2       20,20   0,300   15       50      2       1
1       14809   15815   JUNCBJ2adipose_HS110_50bp_SJ    0       -       14809   15815   255,0,0 2       20,20   0,300   0       2       2       1

If there are any details I missed, I am happy to edit the post. Please don't judge my python-bash mix and

Cheers.

Body:
Using awk. The field separator in your files were space(s) so the values 10 and 59 were in fields 13 and 14 ($13 and $14 in awk). If the field separators are tabs instead add BEGIN{FS=OFS="\t"} before the first { (untested but educated guess, whose words are an invitation for demo effect) and replace all 13 with 12 and 14 with 13 (in that order ;).

$ awk '
{
    a13[$1,$2,$3]+=$13                # sum field 13
    a14[$1,$2,$3]+=$14                # sum field 14
    $13="XX"                          # set a replaceable key to $13
    $14="YY"                          # see above
    a0[$1,$2,$3]=$0                   # now store the record
    an[$1,$2,$3]++                    # count instances of $1,$2,$3
}
END {                                 # after all the records
    for(i in a0) {                    # loop all stored records
        sub(/XX/,a13[i]/an[i],a0[i])  # replace XXs with means
        sub(/YY/,a14[i]/an[i],a0[i])  # and YY
        print a0[i] }                 # output
}' file1 file2
1 14809 15815 JUNCBJ2adipose_HS110_50bp_SJ 0 - 14809 15815 255,0,0 2 20,20 0,300 0 2 2 1
1 14809 14989 JUNCBG2adipose_HS110_50bp_SJ 0 - 14809 14989 255,0,0 2 20,20 0,300 15 50 2 1

Naturally, if the keywords XX and YY appear in the data you run into problems but choose them accordingly.


问:
R - Apply dist function to groups
I am trying to apply the dist() function row wise in R but the result I get is as if it isn't grouping at all, it is simply applying dist() to all of my dataframe.

```<code>df2 %>% dplyr::group_by(X1) %>% dist()
</code>```

Where df2 is my dataframe and I am just applying to the head for now, for simplicity. Essentially, each group contains coordinates (A,B) and I am trying to get the distance between each point.

Here is my dataframe:

```<code>   X1  A              B
1   1  12             0.0
2   1  18             0.0
3   1  18             1.0
4   1  13             0.0
5   1  18             4.0
6   1  18             0.0
7   1  18             5.0
8   1  18             0.0
9   1  18             0.0
10  2  73            -2.0
11  2  73            -0.5
12  2  74            -0.5
13  2  73             0.0
14  2  71            -1.0
15  2  75             0.0
</code>```

My desired output is the lower triangular matrix of each group, here is an example:

Title: R - Apply dist function to groups

Body:
I am trying to apply the dist() function row wise in R but the result I get is as if it isn't grouping at all, it is simply applying dist() to all of my dataframe.

df2 %>% dplyr::group_by(X1) %>% dist()

Where df2 is my dataframe and I am just applying to the head for now, for simplicity. Essentially, each group contains coordinates (A,B) and I am trying to get the distance between each point.

Here is my dataframe:

   X1  A              B
1   1  12             0.0
2   1  18             0.0
3   1  18             1.0
4   1  13             0.0
5   1  18             4.0
6   1  18             0.0
7   1  18             5.0
8   1  18             0.0
9   1  18             0.0
10  2  73            -2.0
11  2  73            -0.5
12  2  74            -0.5
13  2  73             0.0
14  2  71            -1.0
15  2  75             0.0

My desired output is the lower triangular matrix of each group, here is an example:

Body:
We can user purrr::map:

library(purrr)

df %>%
  split(.$X1) %>%
  map(~{
    dist(.x)
  }) -> distList

distList
#> $`1`
#>          1        2        3        4        5        6        7        8
#> 2 6.000000
#> 3 6.082763 1.000000
#> 4 1.000000 5.000000 5.099020
#> 5 7.211103 4.000000 3.000000 6.403124
#> 6 6.000000 0.000000 1.000000 5.000000 4.000000
#> 7 7.810250 5.000000 4.000000 7.071068 1.000000 5.000000
#> 8 6.000000 0.000000 1.000000 5.000000 4.000000 0.000000 5.000000
#> 9 6.000000 0.000000 1.000000 5.000000 4.000000 0.000000 5.000000 0.000000
#>
#> $`2`
#>          10       11       12       13       14
#> 11 1.500000
#> 12 1.802776 1.000000
#> 13 2.000000 0.500000 1.118034
#> 14 2.236068 2.061553 3.041381 2.236068
#> 15 2.828427 2.061553 1.118034 2.000000 4.123106

Data:

df <- read.table(text = 'X1  A              B
1   1  12             0.0
2   1  18             0.0
3   1  18             1.0
4   1  13             0.0
5   1  18             4.0
6   1  18             0.0
7   1  18             5.0
8   1  18             0.0
9   1  18             0.0
10  2  73            -2.0
11  2  73            -0.5
12  2  74            -0.5
13  2  73             0.0
14  2  71            -1.0
15  2  75             0.0', h = T)


问:
After successful selenium install getting ImportError: No module named 'Selenium'
I am receiving an import error after what appears to be a successful selenium install. Here is the message I received when I initially installed selenium:

```<code>My-Mac-Pro:~ Mymachine$ pip3 install selenium
Collecting selenium
  Downloading selenium-3.4.3-py2.py3-none-any.whl (931kB)
    100% |████████████████████████████████| 942kB 490kB/s
Installing collected packages: selenium
Successfully installed selenium-3.4.3
</code>```

When I attempt to import selenium I get the following error message:

```<code>from selenium import webdriver
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/Applications/PyCharm
CE.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py",
line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
ImportError: No module named 'selenium'
</code>```

If I try to reinstall selenium I get the following message indicating the installed selenium module is where it should be:

```<code>My-Mac-Pro:~ Mymachine$ pip3 install -U selenium
Requirement already up-to-date: selenium in
./anaconda/lib/python3.5/site-packages
</code>```

If I navigate to the ./anaconda/lib/python3.5/site-packages folder I see the selenium folder. I've worked my way through every posted question on this topic I could find but have not been able to solve the problem. If anybody has any ideas I would appreciate the help. I am using the Anaconda Python install.

答:
You might have to configure the python environment in Pycharm. To configure Python SDK for the current project, follow these steps:

Open the Settings/Preferences dialog box, and click Project

Interpreter page. In the Projects pane, choose the desired project.

Choose SDK from the list of available Python interpreters and virtual
environments.

Refer Pycharm website for details

Body:
I am receiving an import error after what appears to be a successful selenium install. Here is the message I received when I initially installed selenium:

My-Mac-Pro:~ Mymachine$ pip3 install selenium
Collecting selenium
  Downloading selenium-3.4.3-py2.py3-none-any.whl (931kB)
    100% |████████████████████████████████| 942kB 490kB/s
Installing collected packages: selenium
Successfully installed selenium-3.4.3

When I attempt to import selenium I get the following error message:

from selenium import webdriver
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/Applications/PyCharm
CE.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py",
line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
ImportError: No module named 'selenium'

If I try to reinstall selenium I get the following message indicating the installed selenium module is where it should be:

My-Mac-Pro:~ Mymachine$ pip3 install -U selenium
Requirement already up-to-date: selenium in
./anaconda/lib/python3.5/site-packages

If I navigate to the ./anaconda/lib/python3.5/site-packages folder I see the selenium folder. I've worked my way through every posted question on this topic I could find but have not been able to solve the problem. If anybody has any ideas I would appreciate the help. I am using the Anaconda Python install.


问:
Hazelcast connect to external address
when i try to connect local cluster with

```<code>ClientConfig clientConfig = new ClientConfig();
ClientNetworkConfig cnc = clientConfig.getNetworkConfig();
cnc.addAddress("127.0.0.1:5701");
HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
</code>```

this works fine.
but by connection to external adress, how 10.0.0.1:5701 i receive

```<code>Exception in thread "main" java.lang.IllegalStateException: Unable to connect to any address in the config! The following addresses were tried:[/10.0.0.1:5701]
at com.hazelcast.client.spi.impl.ClusterListenerSupport.connectToCluster(ClusterListenerSupport.java:174)
at com.hazelcast.client.spi.impl.ClientClusterServiceImpl.start(ClientClusterServiceImpl.java:191)
</code>```

how can i set up HazelcastClient to connect IP 10.0.0.1 ? (programmatically or with xml)

i have already seen Hazelcast: connecting to remote cluster but i cannot find how to make it programmatically

答:
Have you tried doing a telnet to the IPaddress and port . If telnet fails then you will need to open firewall port if you are providing public IP .

telnet ip port

Title: Hazelcast connect to external address

Body:
when i try to connect local cluster with

ClientConfig clientConfig = new ClientConfig();
ClientNetworkConfig cnc = clientConfig.getNetworkConfig();
cnc.addAddress("127.0.0.1:5701");
HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);

this works fine.
but by connection to external adress, how 10.0.0.1:5701 i receive

Exception in thread "main" java.lang.IllegalStateException: Unable to connect to any address in the config! The following addresses were tried:[/10.0.0.1:5701]
at com.hazelcast.client.spi.impl.ClusterListenerSupport.connectToCluster(ClusterListenerSupport.java:174)
at com.hazelcast.client.spi.impl.ClientClusterServiceImpl.start(ClientClusterServiceImpl.java:191)

how can i set up HazelcastClient to connect IP 10.0.0.1 ? (programmatically or with xml)

i have already seen Hazelcast: connecting to remote cluster but i cannot find how to make it programmatically


问:
Using R with Google Analytics
I found a great project called r-google-analytics that I'd like to use so I can manipulate GA dat in R at this website http://code.google.com/p/r-google-analytics/.

I run this portion of the code:

```<code>library(RCurl)

library(XML)

# 1. Create a new Google Analytics API object
ga <- RGoogleAnalytics()
# 2. Authorize the object with your Google Analytics Account Credentials
ga$SetCredentials("INSERT_USER_NAME", "INSERT_PASSWORD")
</code>```

And I get this error message:

```<code>Error in postForm("https://www.google.com/accounts/ClientLogin", Email = username,  :
  SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
</code>```

Any ideas as to what could be causing the error?

Thanks!

Kim

答:
I had a similar problem and this helped me out:

Use the alternative internet2.dll by
  starting R with the flag --internet2
  (see How do I install R for Windows?)
  or calling setInternet2(TRUE). These
  cause R to use the Internet Explorer
  internals, which may already be
  configured for use with proxies. Note
  that this does not work with proxies
  that need authentication.

While I was researching the issue, I also discovered that other users reported this issue when they had non-alphanumeric characters (i.e. not A-Za-z0-9) in their password.

ContentLicense: CC BY-SA 2.5

Title: Using R with Google Analytics

Body:
I found a great project called r-google-analytics that I'd like to use so I can manipulate GA dat in R at this website http://code.google.com/p/r-google-analytics/.

I run this portion of the code:

library(RCurl)

library(XML)

# 1. Create a new Google Analytics API object
ga <- RGoogleAnalytics()
# 2. Authorize the object with your Google Analytics Account Credentials
ga$SetCredentials("INSERT_USER_NAME", "INSERT_PASSWORD")

And I get this error message:

Error in postForm("https://www.google.com/accounts/ClientLogin", Email = username,  :
  SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Any ideas as to what could be causing the error?

Thanks!

Kim


问:
Drawing a 3D zero-mean, unit-variance Gaussian in python produces unexpected results
I'm drawing a set of 3D Gaussian samples using numpy with zero-mean and unit-variance:

```<code>cov =  np.zeros((3,3), dtype=np.float32)
np.fill_diagonal(cov, 1.0)
data_values = np.random.multivariate_normal([0.,0.,0.], cov, size=5000)  # 5000 x 3
</code>```

I can plot each dimension and see Gaussians.

I can't plot the full 3D gaussian, so to validate I computed the distance of each sample in data_values from the origin (0,0,0).

```<code>dist_from_center = np.sqrt(np.sum((data_values)**2, axis=1))      # array of 5000
</code>```

When I plot a histogram of the distances I expect to see a half a gaussian, with the mode at zero, but I don't.

Can anyone see the mistake, or explain the result?

答:
The distribution of the distance from the center is not a half-Gaussian.  In two-dimensions, for example, the distribution is the Rayleigh distribution (a special case of the Rice distribution).

Here's a quick explanation of what you should expect the distribution to be, using your simple case where the covariance matrix is the identity.  Then the PDF of the Gaussian in 3D looks like K*exp(-x.dot(x)/2), where K is 1/(2*pi)**(1.5).  Rewrite x.dot(x) as r**2; r is the distance from the origin.  So the PDF behaves like K*exp(-r**2/2).

Now imagine a thin spherical shell around the origin, with radius r and infinitesimal thickness dr.  The "volume" of this thin shell is approximately 4*pi*r**2*dr.  This entire volume is what must be included in the distribution of the distances from the origin.  So we multiply the Gaussian PDF (expressed as a function of r) by the volume of this spherical shell, and divide by dr to get the density as a function of r. This gives (2*r**2)/sqrt(2*pi)*exp(-r**2/2).  (This distribution is known as the Maxwell-Boltzmann distribution.)

Here's a plot of a histogram of the distances, and that function of r:

The histogram was generated using

```<code>hist(dist_from_center, bins=25, normed=True)
</code>```

Body:
I'm drawing a set of 3D Gaussian samples using numpy with zero-mean and unit-variance:

cov =  np.zeros((3,3), dtype=np.float32)
np.fill_diagonal(cov, 1.0)
data_values = np.random.multivariate_normal([0.,0.,0.], cov, size=5000)  # 5000 x 3

I can plot each dimension and see Gaussians.

I can't plot the full 3D gaussian, so to validate I computed the distance of each sample in data_values from the origin (0,0,0).

dist_from_center = np.sqrt(np.sum((data_values)**2, axis=1))      # array of 5000

When I plot a histogram of the distances I expect to see a half a gaussian, with the mode at zero, but I don't.

Can anyone see the mistake, or explain the result?

Body:
The distribution of the distance from the center is not a half-Gaussian.  In two-dimensions, for example, the distribution is the Rayleigh distribution (a special case of the Rice distribution).

Here's a quick explanation of what you should expect the distribution to be, using your simple case where the covariance matrix is the identity.  Then the PDF of the Gaussian in 3D looks like K*exp(-x.dot(x)/2), where K is 1/(2*pi)**(1.5).  Rewrite x.dot(x) as r**2; r is the distance from the origin.  So the PDF behaves like K*exp(-r**2/2).

Now imagine a thin spherical shell around the origin, with radius r and infinitesimal thickness dr.  The "volume" of this thin shell is approximately 4*pi*r**2*dr.  This entire volume is what must be included in the distribution of the distances from the origin.  So we multiply the Gaussian PDF (expressed as a function of r) by the volume of this spherical shell, and divide by dr to get the density as a function of r. This gives (2*r**2)/sqrt(2*pi)*exp(-r**2/2).  (This distribution is known as the Maxwell-Boltzmann distribution.)

Here's a plot of a histogram of the distances, and that function of r:

The histogram was generated using

hist(dist_from_center, bins=25, normed=True)


问:
R Function to write 3 calculated columns to a data.table
This may have already been answered, but couldn't quite find the answer I am looking for. I am trying to write the output of a function that calculates 3 variables to a data.table.

Currently I am copying the function three times (with three different names), each time returning a different variable. This is taking a lot more time as it runs thrice. I understand
there may be a better way to do it, using list or some unique data.table command.

I would greatly appreciate any input you can provide to simplify this. Below is the example of how I am calling it one variable at a time.

Example

```<code>  fn_1 <- function(a, b, c, d){

    for (i in 1:b) { col_1[i] = calculation }
    for (i in 1:c) { col_2[i] = calculation }
    for (i in 1:d) { col_3[i] = calculation }

    return(col_1)
  }

  data[ ,column_1 := fn_1(a,b,c,d) ,by= .(e,f) ]

  fn_2 <- function(a, b, c, d){

    for (i in 1:b) { col_1[i] = calculation }
    for (i in 1:c) { col_2[i] = calculation }
    for (i in 1:d) { col_3[i] = calculation }

    return(col_2)
  }

  data[ ,column_2 := fn_2(a,b,c,d) ,by= .(e,f) ]
</code>```

答:
Answering my own question, based on inputs from @docendodiscimus & @ConCave, i solved it like this. appreciate everyone's input!</p>

```<code>  fn_1 <- function(a, b, c, d){

    for (i in 1:b) { col_1[i] = calculation }
    for (i in 1:c) { col_2[i] = calculation }
    for (i in 1:d) { col_3[i] = calculation }

      df = data.table(col_1, col_2, col_3)
      return(df)
  }

  data[,c("column_1","column_2","column_3"):= fn_1(a,b,c,d) ,by= .(e,f)]
</code>```

Body:
This may have already been answered, but couldn't quite find the answer I am looking for. I am trying to write the output of a function that calculates 3 variables to a data.table.

Currently I am copying the function three times (with three different names), each time returning a different variable. This is taking a lot more time as it runs thrice. I understand
there may be a better way to do it, using list or some unique data.table command.

I would greatly appreciate any input you can provide to simplify this. Below is the example of how I am calling it one variable at a time.

Example

  fn_1 <- function(a, b, c, d){

    for (i in 1:b) { col_1[i] = calculation }
    for (i in 1:c) { col_2[i] = calculation }
    for (i in 1:d) { col_3[i] = calculation }

    return(col_1)
  }

  data[ ,column_1 := fn_1(a,b,c,d) ,by= .(e,f) ]

  fn_2 <- function(a, b, c, d){

    for (i in 1:b) { col_1[i] = calculation }
    for (i in 1:c) { col_2[i] = calculation }
    for (i in 1:d) { col_3[i] = calculation }

    return(col_2)
  }

  data[ ,column_2 := fn_2(a,b,c,d) ,by= .(e,f) ]

Body:
Answering my own question, based on inputs from @docendodiscimus & @ConCave, i solved it like this. appreciate everyone's input!

  fn_1 <- function(a, b, c, d){

    for (i in 1:b) { col_1[i] = calculation }
    for (i in 1:c) { col_2[i] = calculation }
    for (i in 1:d) { col_3[i] = calculation }

      df = data.table(col_1, col_2, col_3)
      return(df)
  }

  data[,c("column_1","column_2","column_3"):= fn_1(a,b,c,d) ,by= .(e,f)]


问:
Javascript, complete calculation into number
I'm trying to convert a calculation String into a Number object in JavaScript, however I can't find a function that do the wanted job.

The parseInt(String) function only parse the first number of calculation but doesn't apply the mathematical functions on it.

I minimal version of what I'm meaning would be something like this: https://jsfiddle.net/qd7u6h60/3/

I'll be glad if someone has an anwser

答:
alert(eval("12+13+5/5"))```
</div>
</div>
</p>

<p>Thats what eval is for. Eval parses valid js, and Math operations are valid JS. Take care on the following</p>

```4^4 => is the binary XOR operator
//you want
4**4
```

Body:
alert(eval("12+13+5/5"))

Thats what eval is for. Eval parses valid js, and Math operations are valid JS. Take care on the following

4^4 => is the binary XOR operator
//you want
4**4


问:
Android: Scan screen for QR code every XX seconds
I have created an android Application that displays the front facing camera inside a SurfaceView.

I would like employees to walk up to the device, show a QR code and enter the building.

So far I have tried converting the SurfaceView contents to a bitmap and reading the contents using the Google Barcode Codelabs to no avail.

Does anyone have any suggestions for doing this?

I need the app to be constantly waiting for a QR code.

Many Thanks

答:
It's probably easiest to do this with a library that can be launched with startActivityForResult. Then when the callback triggers (onActivityResult) you can check if its a valid QR code and then relaunch the QR code scanning activity.

One thing I would note is that a security system this is very insecure so don't use it for a building where security is important.

You will need the zxing barcode scanner app to make this code work.

```<code>package com.example.userme.qr;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
        startActivityForResult(intent, REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
        startActivityForResult(intent, REQUEST);
    }
}
</code>```

Body:
It's probably easiest to do this with a library that can be launched with startActivityForResult. Then when the callback triggers (onActivityResult) you can check if its a valid QR code and then relaunch the QR code scanning activity.

One thing I would note is that a security system this is very insecure so don't use it for a building where security is important.

You will need the zxing barcode scanner app to make this code work.

package com.example.userme.qr;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
        startActivityForResult(intent, REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
        startActivityForResult(intent, REQUEST);
    }
}


问:
Flash/iPhone game development framework
I've been a php/ruby/flash/android/iphone developer for quite some time. I'm starting my mobile/browser game development career. I've been searching for a cross-platform framework that would be the best choice for me as a beginner. I fond the Sparrow framework (iPhone) but I'm not sure about it.

Btw... I'll start with simple games (racing or super mario-style).

My questions:
- Which framework should I use?
- Is it possible to create a game in flash and then export it to native OS (iPhone,Android,Symbian).
- I like screen casts (video tutorials), where can I found them?
- Other tips?

Thx 10x!

答: Using flash is very different than any other framework ive used. Flash takes care of almost everything for you (ie. Loading images, sprites, animations, etc.) while other languages/frameworks require this to be done manually unless you use a game engine. If you are looking to develop on the iphone cocos2d is a good framework to use. Starting from flash and moving to a different framework would be harder than starting with a different framework and moving to flash.</p>

Title: Flash/iPhone game development framework


问:
Android - Validate Fields Prior To Switching Tabs
I have 2 tabs A and B. Tab A contains fields that must be entered by the user. If the user clicks tab B, I am calling my validate routine in a "OnTabSelectedListener". The problem I have is when I want to stop the tab change and keep the user on Tab A to fill out the required fields. Is there a way to accomplish this within the OnTabSelectedListener? </p>

答: This question has answers that shows you how to select a tab programatically but, in my opinion, you should block the user's swipe and put a button to change tabs and validate</p>


答:
std::exception will handle only these kind of exception .http://en.cppreference.com/w/cpp/error/exception.
if you are not sure what all kind of exception your try block can throw and you dont want to terminate your process you can blindly go for catch(...).
If you know what all kind of exception your try block can throw and that all comes under std::exception go with it.</p>

Title: C++ using exceptions


问:
How to stop copyright theft of images?
Is there s a way for anti theft images? I'm not referring to web sites, what I want is if a JPEG is stolen it cannot be manipulated by the thief, only can be used by the owner.</p>

答: This is not possible as jpeg doesn't have a mean to employ digital rights management. You could protect the file itself, but once somebody else has that file, he can do with it as he likes.</p>

Title: How to stop copyright theft of images?


问:
I am having problems with "error ';' expected"
Im having problem with this code. The console shows this error to me and I cannot figure it out. "file.java on line 7: error: ';' expected"

```<code>int adjacentElementsProduct(int[] inputArray) {
    int numberofElements = inputArray.length();
    int [] products = new int [numberofElements];
    for (int firstNumber = 0; numberofElements > firstNumber; firstNumber++) {
         products [firstNumber] = product (inputArray [firstNumber], inputArray [1+firstNumber]);
    };
    int maxValue () {
        int x = products [0];
        for (int i = 1; i < products.length; i++) {
            if (products [i] > x){
                x = products [i];
            }
        }
        return x;
    }
    return maxValue;
}
</code>```

If anyone could help me with this, I would really appreciate.
Thank you.

答: The function maxValue is defined inside adjacentElementsProduct.

Body:
Im having problem with this code. The console shows this error to me and I cannot figure it out. "file.java on line 7: error: ';' expected"

int adjacentElementsProduct(int[] inputArray) {
    int numberofElements = inputArray.length();
    int [] products = new int [numberofElements];
    for (int firstNumber = 0; numberofElements > firstNumber; firstNumber++) {
         products [firstNumber] = product (inputArray [firstNumber], inputArray [1+firstNumber]);
    };
    int maxValue () {
        int x = products [0];
        for (int i = 1; i < products.length; i++) {
            if (products [i] > x){
                x = products [i];
            }
        }
        return x;
    }
    return maxValue;
}

If anyone could help me with this, I would really appreciate.
Thank you.


问:
Running XQuery on the command line
It sounds like I need some type of XML processor

It looks like theres a program called Saxon which I can use to run XQuery

When I try this websites example I get

```<code>Error: Could not find or load main class net.sf.saxon.Query
</code>```

I don't know how to set up the java package from the saxon package I downloaded.

Id like to know if there is an easier option to be able to run XQuery from the command line other than this java package? All I want to do is process an xml file with commands like "Select  where type="something"".

答:
BaseX offers XQuery 3.0 support and is packaged with scripts that encapsulate calling Java, including setting up the classpath:</p>

```<code>$ basex --help
BaseX 8.5.3 [Standalone]
Usage: basex [-bcdiIoqrRstuvVwxXz] [input]
  [input]     XQuery or command file, or query string
  -b<pars>    Bind external query variables
  -c<input>   Execute commands from file or string
  -d          Activate debugging mode
  -i<input>   Assign file or database to context
  -I<input>   Assign input string to context
  -o<output>  Write output to file
  -q<expr>    Execute XQuery expression
  -r<num>     Set number of query executions
  -R          Turn query execution on/off
  -s<pars>    Set serialization parameter(s)
  -t[path]    Run tests in file or directory
  -u          Write updates back to original files
  -v/V        Show (all) process info
  -w          Preserve whitespaces from input files
  -x          Show query plan
  -X          Show query plan before/after compilation
  -z          Skip output of results
</code>```

Title: Running XQuery on the command line

Body:
It sounds like I need some type of XML processor

It looks like theres a program called Saxon which I can use to run XQuery

When I try this websites example I get

Error: Could not find or load main class net.sf.saxon.Query

I don't know how to set up the java package from the saxon package I downloaded.

Id like to know if there is an easier option to be able to run XQuery from the command line other than this java package? All I want to do is process an xml file with commands like "Select  where type="something"".

Body:
BaseX offers XQuery 3.0 support and is packaged with scripts that encapsulate calling Java, including setting up the classpath:

$ basex --help
BaseX 8.5.3 [Standalone]
Usage: basex [-bcdiIoqrRstuvVwxXz] [input]
  [input]     XQuery or command file, or query string
  -b<pars>    Bind external query variables
  -c<input>   Execute commands from file or string
  -d          Activate debugging mode
  -i<input>   Assign file or database to context
  -I<input>   Assign input string to context
  -o<output>  Write output to file
  -q<expr>    Execute XQuery expression
  -r<num>     Set number of query executions
  -R          Turn query execution on/off
  -s<pars>    Set serialization parameter(s)
  -t[path]    Run tests in file or directory
  -u          Write updates back to original files
  -v/V        Show (all) process info
  -w          Preserve whitespaces from input files
  -x          Show query plan
  -X          Show query plan before/after compilation
  -z          Skip output of results


问:
Fail to run project with Xcode 9 , Many new C++ semantic issue
My project works fine in Xcode 8. When I build It in Xcode 9, there are many C++ semantic issues reported.It seems Xcode 9 C++ complier do much stricter type checking than Xcode 8.Is there a build configure fix to this.

答:
There are three little lines in the upper right of the error list. Like an icon of lines of text. Click those to get the raw compiler output for your error messages. At the end of each warning it usually names the command-line flag corresponding to it (like [-Wwarn-about-mistakes]). You can search for that in build settings using the filter field to see the corresponding check box.

All that said: all these warnings have a reason for being there. You should find out what each warning is about and change your code the right way so the compiler doesn't  have to warn anymore.

Even if these warnings seem pointless and your code appears to work, they usually indicate an issue that is either already occurring, or might have unexpected side effects later when you change another part of your code.


问:
Problem with sharepoint 2010 conditional formatting (setting color to text in rows)
i'm tring to set conditional formatting for sharepoint list (2010).
I have a list with a few columns. One of them have 2 values available. 1 or 0.
if 1 then the text in all rows in my list must get color RED.
if 0 then do nothing.
in design mode in sharepoint designer i can see the color red, but the browser doesnt show it at all!
is this a bug of sharepoint? does the code created is not vaild code for browsers?

this is the condition code:

```<code>    <xsl:if test="$thisNode/@findWord = '1'"
ddwrt:cf_explicit="1"
xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime">
     color: #FF0000; font-family: Arial, Helvetica, sans-serif; font-weight: bold;
      text-decoration: underline;
</xsl:if>
</code>```

thanks.
gadym.

答:
You have to add findword column in viewfields which you can find under view tag

```<code>    <FieldRef  Name ="findWord" />
</code>```

Working Syntax is provided below for choice column type taking 1 and 0 as input

```<code><xsl:variable name="titlevalue" select="$thisNode/@Title"/>
      <xsl:choose>
         <xsl:when test="$titlevalue=''">
        <xsl:value-of select="'(no title)'"/>
      </xsl:when>
         <xsl:otherwise>
           <xsl:choose>
              <xsl:when test="$HasTitleField">
            <span>
       <xsl:attribute name="style">
        <xsl:if test="normalize-space($thisNode/@findWord) = '1'" ddwrt:cf_explicit="1">font-family: Arial, Helvetica, sans-serif; color: #FF0000; text-decoration: underline; font-weight: bold; background-color: #BDDFD9;</xsl:if>
       </xsl:attribute>
       <xsl:value-of disable-output-escaping="yes" select="$titlevalue" />
       </span></xsl:when>
              <xsl:otherwise>
            <xsl:value-of select="$titlevalue" />
          </xsl:otherwise>
           </xsl:choose>
      </xsl:otherwise>
      </xsl:choose>
</code>```

Body:
i'm tring to set conditional formatting for sharepoint list (2010).
I have a list with a few columns. One of them have 2 values available. 1 or 0.
if 1 then the text in all rows in my list must get color RED.
if 0 then do nothing.
in design mode in sharepoint designer i can see the color red, but the browser doesnt show it at all!
is this a bug of sharepoint? does the code created is not vaild code for browsers?

this is the condition code:

    <xsl:if test="$thisNode/@findWord = '1'"
ddwrt:cf_explicit="1"
xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime">
     color: #FF0000; font-family: Arial, Helvetica, sans-serif; font-weight: bold;
      text-decoration: underline;
</xsl:if>

thanks.
gadym.

Body:
You have to add findword column in viewfields which you can find under view tag

    <FieldRef  Name ="findWord" />

Working Syntax is provided below for choice column type taking 1 and 0 as input

<xsl:variable name="titlevalue" select="$thisNode/@Title"/>
      <xsl:choose>
         <xsl:when test="$titlevalue=''">
        <xsl:value-of select="'(no title)'"/>
      </xsl:when>
         <xsl:otherwise>
           <xsl:choose>
              <xsl:when test="$HasTitleField">
            <span>
       <xsl:attribute name="style">
        <xsl:if test="normalize-space($thisNode/@findWord) = '1'" ddwrt:cf_explicit="1">font-family: Arial, Helvetica, sans-serif; color: #FF0000; text-decoration: underline; font-weight: bold; background-color: #BDDFD9;</xsl:if>
       </xsl:attribute>
       <xsl:value-of disable-output-escaping="yes" select="$titlevalue" />
       </span></xsl:when>
              <xsl:otherwise>
            <xsl:value-of select="$titlevalue" />
          </xsl:otherwise>
           </xsl:choose>
      </xsl:otherwise>
      </xsl:choose>


问:
Blur half a page
I need to blur the content of half a page, basically I need to show a document preview before the customer pays for it.

In order to accomplish that I have a HTML page which looks pretty much like this:

I need to apply a blur, the blur should start from the 50% of the page height, then I will take an screenshot and show that image to the customer.

So:

I can't apply the filter blur to a div because there are many divs involved. Lets say that the blur will start from somewhere around "Where does it come from"

I tried to add a div position absolute with a filter blur, but the blur is not being applied over the text. I also tried to do that with SVGs but no joy.

Ideas?

答:
Here's a solution that may be a bit rickety, but works - in Firefox, at least:

```<code><?xml version="1.0" standalone="yes"?>
<svg width="600" height="800" version="1.1"
     xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     xmlns:html="http://www.w3.org/1999/xhtml">
  <filter id="halfBlur" filterUnits="objectBoundingBox" x="0" y="0.5" width="1" height="0.5">
    <feGaussianBlur in="SourceGraphic" stdDeviation="2" />
  </filter>
  <g id="source">
    <foreignObject width="600" height="800">
      <html:iframe style="width:600px;height:800px" src=""></html:iframe>
    </foreignObject>
  </g>
  <use xlink:href="#source" filter="url(#halfBlur)"/>
</svg>
</code>```

Mark that the <use> element only works if it references an SVG container element, but not the <foreignObject> directly.

Care must be taken to make all elements big enough to contain the complete html page. As an extra measure, it might be a good idea to provide the html element of the embeded page with a overflow:hidden rule. If scrollbars show up, they will work on both halfs of the page independently.

Title: Blur half a page

Body:
Here's a solution that may be a bit rickety, but works - in Firefox, at least:

<?xml version="1.0" standalone="yes"?>
<svg width="600" height="800" version="1.1"
     xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     xmlns:html="http://www.w3.org/1999/xhtml">
  <filter id="halfBlur" filterUnits="objectBoundingBox" x="0" y="0.5" width="1" height="0.5">
    <feGaussianBlur in="SourceGraphic" stdDeviation="2" />
  </filter>
  <g id="source">
    <foreignObject width="600" height="800">
      <html:iframe style="width:600px;height:800px" src=""></html:iframe>
    </foreignObject>
  </g>
  <use xlink:href="#source" filter="url(#halfBlur)"/>
</svg>

Mark that the <use> element only works if it references an SVG container element, but not the <foreignObject> directly.

Care must be taken to make all elements big enough to contain the complete html page. As an extra measure, it might be a good idea to provide the html element of the embeded page with a overflow:hidden rule. If scrollbars show up, they will work on both halfs of the page independently.


问:
Why is it mandatory to mention the Type information before the return type in case of static as well as non-static methods
I need to understand the need of putting a Type before the return type in case of both, static and non-static classes. Is it only to ensure that the method abides by the type, or is there some other part of the story.</p>

答:
The language is designed this way.　If you don't like it, don't use Java. Try C# instead, where methods can be declared like this:

```<code>void MyMethod<T>(T someParam) { ... }
</code>```

JLS chapter 18 shows that TypeParameters are declared as follows:

```<code>TypeParameters:
    < TypeParameter { , TypeParameter } >

TypeParameter:
    Identifier [extends Bound]

Bound:
    ReferenceType { & ReferenceType }
</code>```

And a GenericMethodOrConstructorDecl is defined like this:

```<code>GenericMethodOrConstructorDecl:
    TypeParameters GenericMethodOrConstructorRest

GenericMethodOrConstructorRest:
    (Type | void) Identifier MethodDeclaratorRest
    Identifier ConstructorDeclaratorRest
</code>```

Here you can see that TypeParameters precedes GenericMethodOrConstructorRest.

As to why it is designed this way, I think the only effect this has is that it encourages you to think about the generic parameters first, then the return type.

ContentLicense: CC BY-SA 4.0

Body:
The language is designed this way.　If you don't like it, don't use Java. Try C# instead, where methods can be declared like this:

void MyMethod<T>(T someParam) { ... }

JLS chapter 18 shows that TypeParameters are declared as follows:

TypeParameters:
    < TypeParameter { , TypeParameter } >

TypeParameter:
    Identifier [extends Bound]

Bound:
    ReferenceType { & ReferenceType }

And a GenericMethodOrConstructorDecl is defined like this:

GenericMethodOrConstructorDecl:
    TypeParameters GenericMethodOrConstructorRest

GenericMethodOrConstructorRest:
    (Type | void) Identifier MethodDeclaratorRest
    Identifier ConstructorDeclaratorRest

Here you can see that TypeParameters precedes GenericMethodOrConstructorRest.

As to why it is designed this way, I think the only effect this has is that it encourages you to think about the generic parameters first, then the return type.