d3.js chemical tube bar chart

Question:
I am interested in creating this liquid bar chart of sorts. With the pointers/dotted markers pulling off to the side like shown.
22 April - latest code to work with dynamic data http://jsfiddle.net/NYEaX/1855/

latest bar chart code
http://jsfiddle.net/NYEaX/1827/
latest cleaned up water wave code
http://jsfiddle.net/Qh9X5/10331/

//I want to strip down this waterwave code
http://jsfiddle.net/Qh9X5/10091/
//progress chart
http://jsfiddle.net/NYEaX/1740/

latest base code for this bar chart.
http://jsfiddle.net/NYEaX/1822/
<code>var $this = $("#checmicalbars");

var data = [{
  "label": "Rendering",
  "value": 90,
  "startcolor": "#c3da54",
  "endcolor": "#c1e500"
},
{
  "label": "Character Design",
  "value": 95,
  "startcolor": "#e94adc",
  "endcolor": "#aae3dd"
},
{
  "label": "Sketching",
  "value": 80,
  "startcolor": "#c3da54",
  "endcolor": "#fa5283"
},
{
  "label": "Story Boarding",
  "value": 90,
  "startcolor": "#e94adc",
  "endcolor": "#f83b03"
},
{
  "label": "Drawing",
  "value": 82,
  "startcolor": "#c3da54",
  "endcolor": "#f88504"
},
{
  "label": "Painting",
  "value": 90,
  "startcolor": "#e94adc",
  "endcolor": "#f7d200"
}];

var h = 150;
var w = 300;

    var options = {
  minlimit: 0,
  maxlimit: 100
}

// setup scales
var x = d3.scale.ordinal()
  .rangeRoundBands([0, w], .1);

var y = d3.scale.linear()
  .range([h, 0]);

var xAxis = d3.svg.axis()
  .scale(this.x)
  .orient("bottom");

var yAxis = d3.svg.axis()
  .scale(this.y)
  .orient("left");
// setup scales

// chart container
var progresschart = d3.select($this[0]).append("svg")
  .attr("width", w)
  .attr("height", h)
  .append("g")
  .attr("transform", "translate(0,5)");

var barrectsholder = progresschart.append("g")
  .attr("class", "chart")
  .attr("transform", "translate(15,0)");
// chart container

y.domain([options["minlimit"], options["maxlimit"]]);

//__ bars
var bar = barrectsholder.selectAll("rect")
  .data(data);

//__ enter
bar.enter()
  .append("rect")
  .attr("class", "bar")
  .attr("y", h);

//__ update
bar
  .attr("y", h)
  .attr("height", 0)
  .style("fill", function(d){
    return d.startcolor;
  })
  .transition()
  .duration(2500)
  .style("fill", function(d){
    return d.endcolor;
  })
  .attr("width", 20)
  .attr("x", function(d, i) {
    return 30 * i;
  })
  .attr("y", function(d) {
    return y(d.value);
  })
  .attr("height", function(d) {
    return h - y(d.value);
  })

//__ exit
bar.exit()
  .transition()
  .duration(250)
  .attr("y", 0)
  .attr("height", 0)
  .remove();
//__ bars
</code>
Comment: Dude, seriously, all these fiddles are not helping! You need to condense all this external information into your question, and make it clear exactly what you are asking.
Comment: I've added the labels - http://jsfiddle.net/NYEaX/1825/
Comment: -- added dotted lines - but struggling to get the vertical lines to match up -- http://jsfiddle.net/NYEaX/1826/
Comment: managed to resolve the 2nd lines -- keen to incorporate the water effects - a way of simplifying the algorithm to get integrated? http://jsfiddle.net/NYEaX/1827/   -- water code - http://jsfiddle.net/Qh9X5/10091/
Comment: -- I've started to strip down this wave code -- http://jsfiddle.net/Qh9X5/10290/
Comment: cleaned up the wave code -- http://jsfiddle.net/Qh9X5/10300/
Comment: -- latest water code -- http://jsfiddle.net/Qh9X5/10334/
Comment: what i don't understand, what part is actually missing?
Comment: -- Hello @NinaScholz http://jsfiddle.net/NYEaX/1842/ -- just trying to clean this up -- so if you take data away or add more data to it - making the chart more dynamic
Comment: -- so its broken when I removed the "Rendering" data part -- http://jsfiddle.net/NYEaX/1843/  -- also actually not sure the labels are matching up with the correct bars - so if its a case of sorting the data or plotting the bars down in a particular order/reverse?
Comment: Any suggestions here @NinaScholz to fix the bugs in the dynamic data aspects -- problems plotting the labels -- http://jsfiddle.net/NYEaX/1855/
Comment: "to fix the bugs in the dynamic data aspects -- problems plotting the labels" - issue is explained with the latest research
Answer: I've merged the two charts together - but the watercode is translated correctly if its a separate svg - be good to get this code cleaned up/reviewed. Also ensuring the pointers/labels adjust/adapt with more/less data sets.

latest jsfiddle
http://jsfiddle.net/NYEaX/1843/
<code>    var $this = $("#checmicalbars");

    var data = [{
      "label": "Rendering",
      "value": 90,
      "startcolor": "#c3da54",
      "endcolor": "#c1e500"
    },
    {
      "label": "Character Design",
      "value": 95,
      "startcolor": "#e94adc",
      "endcolor": "#aae3dd"
    },
    {
      "label": "Sketching",
      "value": 80,
      "startcolor": "#c3da54",
      "endcolor": "#fa5283"
    },
    {
      "label": "Story Boarding",
      "value": 90,
      "startcolor": "#e94adc",
      "endcolor": "#f83b03"
    },
    {
      "label": "Drawing",
      "value": 82,
      "startcolor": "#c3da54",
      "endcolor": "#f88504"
    },
    {
      "label": "Painting",
      "value": 90,
      "startcolor": "#e94adc",
      "endcolor": "#f7d200"
    }];

    var h = 450;
    var w = 400;

    var barHeight = 150;
    var barWidth = 180;

        var options = {
      minlimit: 0,
      maxlimit: 100
    }

    // setup scales
    var x = d3.scale.ordinal()
      .rangeRoundBands([0, barWidth], .1);

    var y = d3.scale.linear()
      .range([barHeight, 0]);

    var xAxis = d3.svg.axis()
      .scale(this.x)
      .orient("bottom");

    var yAxis = d3.svg.axis()
      .scale(this.y)
      .orient("left");
    // setup scales

    // chart container
    var progresschart = d3.select($this[0]).append("svg")
      .attr("width", w)
      .attr("height", h)
      .append("g")
      .attr("transform", "translate(0,5)");

    var barrectsholder = progresschart.append("g")
      .attr("class", "barrectsholder")
      .attr("transform", "translate(15,0)");

        var labelsholder = progresschart.append("g")
      .attr("class", "labelsholder")
      .attr("transform", "translate(10,"+(barHeight+ 20)+")");

      var lineholder = progresschart.append("g")
      .attr("class", "lineholder")
      .attr("transform", "translate(25,"+(barHeight+ 15)+")");
    // chart container

    y.domain([options["minlimit"], options["maxlimit"]]);

/*
  var gauge = barrectsholder
    .append("g")
    .attr("width", config.w)
    .attr("height", config.h)
    .append("g");

  liquidBar(gauge, config);
*/

var bar = barrectsholder.selectAll("svg")
      .data(data);

 bar.enter()
       .append("svg")
       .attr("class", function(d, i) {
        return "bar"+i;
         })
      .attr("width", 20)
      .attr("x", function(d, i) {
        return 30 * i;
      })
      .attr("y", function(d) {
        return y(d.value);
      })
      .attr("height", function(d) {
        return barHeight - y(d.value);
      })

$.each(data, function( index, value ) {
  //alert( index + ": " + value );

  var config = {
    w: 20,
    h: barHeight,
    value: value.value,
    amplitude: 0.02, // The wave height as a percentage of the radius of the wave circle.
    countPerWidth: 1, // The number of full waves per width of the wave circle.
    riseTime: 1000, // The amount of time in milliseconds for the wave to rise from 0 to it's final height.
    animateTime: 1000, // The amount of time in milliseconds for a full wave to enter the wave circle.
    rise: true, // Control if the wave should rise from 0 to it's full height, or start at it's full height.
    colorTransition: 1000,
    colorBefore: value.startcolor, // The color before of the fill wave.
    colorAfter: value.endcolor, // The color after of the fill wave.
    offset: 0 // The amount to initially offset the wave. 0 = no offset. 1 = offset of one full wave.
  };

  var gauge = barrectsholder.selectAll("svg.bar"+index)
   liquidBar(gauge, config);

});

/*
    //__ bars
    var bar = barrectsholder.selectAll("rect")
      .data(data);

    //__ enter
    bar.enter()
      .append("rect")
      .attr("class", "bar")
      .attr("y", barHeight);

    //__ update
    bar
      .attr("y", barHeight)
      .attr("height", 0)
      .style("fill", function(d){
        return d.startcolor;
      })
      .transition()
      .duration(2500)
      .style("fill", function(d){
        return d.endcolor;
      })
      .attr("width", 20)
      .attr("x", function(d, i) {
        return 30 * i;
      })
      .attr("y", function(d) {
        return y(d.value);
      })
      .attr("height", function(d) {
        return barHeight - y(d.value);
      })

    //__ exit
    bar.exit()
      .transition()
      .duration(250)
      .attr("y", 0)
      .attr("height", 0)
      .remove();
    //__ bars

*/

    //__ labels
    var labels = labelsholder.selectAll("text")
      .data(data);

    labels.enter()
      .append("text")
      .attr("class", "barlabels")
      .attr("x", 200)
      .attr("y", function(d, i) {
        return 20 * i;
      })
      .text(function(d) {
        return d.label;
      })

 var lines = lineholder.selectAll("text")
      .data(data);

  lines.enter()
    .append("line")// attach a line
    .style("stroke-dasharray", ("3, 3"))
    .style("stroke", "black")// colour the line
    .attr("x1", function(d, i) {
      return barWidth-(30 * (i+1));
    })//x pos of the 1st end of the line
    .attr("y1", function(d, i) {
      return 20 * i;
    })//y pos of the 1st end of the line
    .attr("x2", function(d, i) {
      return barWidth;
    })//x pos of the 2nd end of the line
    .attr("y2", function(d, i) {
      return 20 * i;
    });//y pos of the 2nd end of the line

    var lineHeights = 100;

  lines.enter()
    .append("line")// attach a line
    .style("stroke-dasharray", ("3, 3"))
    .style("stroke", "black")// colour the line
    .attr("x1", function(d, i) {
      return 30 * i;
    })//x pos of the 1st end of the line
    .attr("y1", function(d, i) {
      return lineHeights - (20 * i);
    })//y pos of the 1st end of the line
    .attr("x2", function(d, i) {
      return 30 * i;
    })//x pos of the 2nd end of the line
    .attr("y2", function(d, i) {
      return -15;
    });//y pos of the 2nd end of the line

  function liquidBar(gauge, config) {

    var fillPercent = Math.max(0, Math.min(100, config.value)) / 100;

    var waveHeightScale = d3.scale.linear()
      .range([0, config.amplitude, 0])
      .domain([0, 50, 100]);

    var waveHeight = (config.h / 2) * waveHeightScale(fillPercent * 100);
    var waveLength = config.w / config.countPerWidth;
    var waveClipCount = 1 + config.countPerWidth;
    var waveClipWidth = waveLength * waveClipCount;

    // Data for building the clip wave area.
    var data = [];
    for (var i = 0; i <= 40 * waveClipCount; i++) {
      data.push({
        x: i / (40 * waveClipCount),
        y: (i / (40))
      });
    }

    // Scales for controlling the size of the clipping path.
    var waveScaleX = d3.scale.linear().range([0, waveClipWidth]).domain([0, 1]);
    var waveScaleY = d3.scale.linear().range([0, waveHeight]).domain([0, 1]);

    // Scales for controlling the position of the clipping path.
    var waveRiseScale = d3.scale.linear()
      // The clipping area size is the height of the fill circle + the wave height, so we position the clip wave
      // such that the it will overlap the fill circle at all when at 0%, and will totally cover the fill
      // circle at 100%.
      .range([(config.h + waveHeight), (waveHeight)])
      .domain([0, 1]);
    var waveAnimateScale = d3.scale.linear()
      .range([0, waveClipWidth - config.w]) // Push the clip area one full wave then snap back.
      .domain([0, 1]);

    // Center the gauge within the parent SVG.
    var gaugeGroup = gauge.append("g")
      .attr("class", "gaugeGroup")
      .attr("transform", "translate(0,0)");

    var randomId = Math.floor(Math.random() * 26) + Date.now();

    // The clipping wave area.
    var clipArea = d3.svg.area()
      .x(function(d) {
        return waveScaleX(d.x);
      })
      .y0(function(d) {
        return waveScaleY(Math.sin(Math.PI * 2 * config.offset * -1 + Math.PI * 2 * (1 - config.countPerWidth) + d.y * 2 * Math.PI));
      })
      .y1(function(d) {
        return (config.h + waveHeight);
      });

    var waveGroup = gaugeGroup.append("defs")
      .append("clipPath")
      .attr("id", "clipWave" + randomId);

    var wave = waveGroup.append("path")
      .datum(data)
      .attr("d", clipArea)
      .attr("T", 0);

    // The inner circle with the clipping wave attached.
    var fillGroup = gaugeGroup.append("g")
      .attr("clip-path", "url(#clipWave" + randomId + ")");

    fillGroup.append("rect")
      .attr("x", 0)
      .attr("y", 0)
      .attr("width", config.w)
      .attr("height", config.h)
      .style("fill", config.colorBefore)
      .transition()
      .duration(config.colorTransition)
      .style("fill", config.colorAfter);

    // Make the wave rise. wave and waveGroup are separate so that horizontal and vertical movement can be controlled independently.
    var waveGroupXPosition = config.w - waveClipWidth;
    if (config.rise) {
      waveGroup.attr('transform', 'translate(' + waveGroupXPosition + ',' + waveRiseScale(0) + ')')
        .transition()
        .duration(config.riseTime)
        .attr('transform', 'translate(' + waveGroupXPosition + ',' + waveRiseScale(fillPercent) + ')')
        .each("start", function() {
          wave.attr('transform', 'translate(1,0)');
        }); // This transform is necessary to get the clip wave positioned correctly when waveRise=true and waveAnimate=false. The wave will not position correctly without this, but it's not clear why this is actually necessary.
    } else {
      waveGroup.attr('transform', 'translate(' + waveGroupXPosition + ',' + waveRiseScale(fillPercent) + ')');
    }

        animateWave();

    function animateWave() {
      wave.attr('transform', 'translate(' + waveAnimateScale(wave.attr('T')) + ',0)');
      wave.transition()
        .duration(config.animateTime * (1 - wave.attr('T')))
        .ease('linear')
        .attr('transform', 'translate(' + waveAnimateScale(1) + ',0)')
        .attr('T', 1)
        .each('end', function() {
          wave.attr('T', 0);
          animateWave(config.animateTime);
        });
    }

  }
</code>
Comment: I've tried to tidy up the chart and provide the value labels above -- keen to have this chart cleaned up - made to work more for handling dynamic/different data sets -- also the best way of creating backgrounds for each bar -- http://jsfiddle.net/NYEaX/1842/
Comment: http://jsfiddle.net/NYEaX/1855/ - fixed the labels dynamically so they are snapping to the bottom
Comment: Here is a related question to this chart -- http://stackoverflow.com/questions/43507667/javascript-dynamic-data-bar-chart-bug-d3-js-paths

d3.js chemical tube bar chart


How do I add a custom field to the image field widget in Drupal 7?

Question: I need to add a custom field (a simple text field) to the image_field widget in Drupal 7.
The structure is a standard node (called Article) which has zero or more images (related photos or graphics) attached via the image_field widget. The field I want to add is the source of the image, and is used later to figure out when it needs to be deleted.
I've tried the code from this post, but couldn't get it to work.
Answer:
Attaching metadata to images and other media, is precisely the reason that prompted the creation of the media module. We use the unfortunately "unstable" version ourselves, with good results. Using Media, your images becomes entities, allowing you to attach any field you want to them through the normal means.
While the solution to manipulate the existing widget is fully valid, it will require quite a bit of understanding of the Field API, and I believe any such solution would get rather messy.


Evaluating $\int_{0}^{2\pi}\frac{1}{\cos^2(\theta)+1}\, d\theta$

Question: What would be the values of this definite Integral?
$$\int_{0}^{2\pi}\frac{1}{\cos^2(\theta)+1}\, d\theta$$
So, I have solved this definite integral using the substitution method, taking $u=\tan(\theta)$.
After some simplification, the solution to the definite integral I get is follows:
$$\frac{1}{\sqrt{2}} \, \tan^{-1}\left(\frac{\tan{\theta}}{\sqrt{2}}\right) \Biggr|_{0}^{2\pi}$$
Whenever I am evaluating the above result at the limits of the integration I am getting an answer of $0$.
My simplification,
$$=\frac{1}{\sqrt{2}} \, \left[ \tan^{-1}\left(\frac{\tan{2\pi}}{\sqrt{2}}\right) - \tan^{-1}\left(\frac{\tan{0}}{\sqrt{2}}\right) \right]$$
$$=\frac{1}{\sqrt{2}} \, \big[ \tan^{-1}(0) - \tan^{-1}(0) \big]$$
$$=\frac{1}{\sqrt{2}} \, \big[ 0-0]$$
$$=0$$
However, using Mathematical/Integral calculator, the value of this Integral is
$$2\pi$$
I am probably doing something very silly, as I can't figure out what I am doing wrong. Any help would be appreciated. Thanks!
Comment: The substitution you made is not bijective.
Comment: @hamam_Abdallah after thinking about it - I don't think the issue was to do with bijectivity, since $u$ substitution doesn't actually require it. What it does require, however, is your substitution be continuous on the domain of integration - and ${u=\tan(x)}$ is not continuous on ${(0,2\pi)}$, and so you have to split up the integral into $4$ separate integrals, just like an improper integral
Answer: You can find the solution below, and afterwards an explanation as of why your $u$ substitution did not work.
An alternative way is to write
$${\int_{0}^{2\pi}\frac{1}{1+\cos^2(x)} dx=4\int_{0}^{\frac{\pi}{2}}\frac{1}{1+\cos^2(x)}dx}$$
$${=4\int_{0}^{\frac{\pi}{2}}\frac{\sin^2(x) + \cos^2(x)}{1+\cos^2(x)}dx}$$
Now, dividing the top and bottom by ${\cos^2(x)}$ gives
$${4\int_{0}^{\frac{\pi}{2}}\frac{\tan^2(x) + 1}{\sec^2(x) + 1} dx}$$
Now using some more trig identities, we get
$${=4\int_{0}^{\frac{\pi}{2}}\frac{\sec^2(x)}{\tan^2(x) + 2}dx}$$
$${=4\int_{0}^{\infty}\frac{1}{2+u^2}du}$$
Now, solving that integral
$${\int_{0}^{\infty}\frac{1}{2+u^2}du=\frac{1}{2}\int_{0}^{\infty}\frac{1}{1+\left(\frac{u}{\sqrt{2}}\right)^2}du}$$
Now do ${k=\frac{u}{\sqrt{2}}}$:
$${=\frac{1}{\sqrt{2}}\int_{0}^{\infty}\frac{1}{1+k^2}dk=\frac{\pi}{2\sqrt{2}}}$$
So putting the whole thing together:
$${=4\times \frac{\pi}{2\sqrt{2}}=\sqrt{2}\pi}$$
Which is the correct answer :)
EDIT: After some reconsideration, I don't believe the issue in your original ${u}$ substitution was really to do with injectivity at all. In fact injectivity is not a strict requirement for $u$ substitution. If we redo all the steps we just did, but don't change the domain of integration, you end up with
$${\int_{0}^{2\pi}\frac{1}{1+\cos^2(x)}dx=\int_{0}^{2\pi}\frac{\sec^2(x)}{\tan^2(x) + 2}dx}$$
You may be tempted to once again do ${u=\tan(x)}$ (which is essentially what you did I believe?) but one requirement for $u$ substitution that is very clearly needed is for $u$ to be continuous on the domain of integration (it needs to be differentiable, and so clearly continuity is a requirement!). ${u=\tan(x)}$ certainly is not continuous on ${(0,2\pi)}$, and so you really end up with an improper integral of sorts. Now, we could split up the integral instead, just as we would with any old improper integral:
$${\int_{0}^{2\pi}\frac{\sec^2(x)}{\tan^2(x) + 2}dx=\int_{0}^{\frac{\pi}{2}}\frac{\sec^2(x)}{\tan^2(x) + 2}dx + \int_{\frac{\pi}{2}}^{\frac{3\pi}{2}}\frac{\sec^2(x)}{\tan^2(x) + 2}dx + \int_{\frac{3\pi}{2}}^{2\pi}\frac{\sec^2(x)}{\tan^2(x) + 2}dx}$$
And now it is legitimate to do ${u=\tan(x)}$, since ${\tan(x)}$ will be differentiable and continuous on these domains (well, technically not at the endpoints - but you take a limit, as per the definition of how we deal with improper integrals). Indeed you will get the answer of ${\sqrt{2}\pi}$ if you evaluate this expression.
So if this was the issue, why did people jump to injectivity / bijectivity? Well there are some instances where this is (indirectly) the problem. An example:
$${\int_{0}^{2\pi}xdx}$$
Clearly the answer to this is ${2\pi^2}$. Now do the substitution ${u=\sin(x)}$ - our endpoints become ${\int_{0}^{0}}$... does this mean the integral is $0$? NO! Recall $u$ substitution only says that
$${\int_{a}^{b}f(\phi(x))\phi'(x)dx = \int_{\phi(a)}^{\phi(b)}f(u)du}$$
If you actually attempt to write ${\int_{0}^{2\pi}xdx}$ to match the form of the lefthand side so we can legit utilise $u$ substitution you will end up using some nasty ${\arcsin}$ rubbish - but the key point to take away is that the ${\arcsin}$ function only gives back principle values. ${\arcsin(\sin(x))}$ does not necessarily equal to ${x}$ for all ${x \in \mathbb{R}}$!. So in actuality you end up having a piecewise function to represent ${x}$, so you are forced to split the integral up. So in this case injectivity is in fact a sort of "requirement" indirectly (unless you split up the integral).
I hope this helped explain a bit better :)
Comment: @Riemann'sPointyNose I went into an internet Rabbit hole trying to pinpoint the injectivity issue. Thanks for explaining with an example as well!
Comment: Thank you for this elaborate answer! This helped a lot overall :D
Comment: Could you please elaborate more why it needs to be injective for the substitution to work? I am getting a vague idea and can't really pin-point it
Comment: Very nice the comment "the u substitution to be injective ..."
Comment: Why not just express $1$ in the original integral as $\sin^2{\theta}+\cos^2{\theta}$?  Saves a few steps from your solution.
Comment: @Rio1210 I have added an explanation at the end of my answer - after more consideration, I do not believe injectivity was the issue :)
Comment: @Riemann'sPointyNose. I should've been more clear.  I meant after you split the integral into 4, let the 1 in the denominator equal $\sin^2{\theta}+\cos^2{\theta}$ then divide by $\cos^2{\theta}$.  It yields the same thing as you have but saves a few steps.
Comment: @Ty. Editted my answer to explain why this is not legitimate :)
Comment: @Ty. I understand, makes sense!
Comment: @Oiler no problem at all! :)
Comment: Suggestion- denominator=$1+\cos^2(x)=\sin^2(x)+\cos^2(x)+\cos^2(x)$ directly :)
Answer: hint
Begin by the substitution
$$t=\theta-\pi$$
it becomes
$$\int_{-\pi}^{\pi}\frac{dt}{\cos^2(t)+1}=$$
$$2\int_0^\pi\frac{dt}{\cos^2(t)+1}$$
because the integrand is an even function.
By the same, if you put $$v=t-\frac{\pi}{2}$$
it gives
$$4\int_0^\frac{\pi}{2}\frac{dv}{2-\cos^2(v)}$$
and now, make the change
$$u=\tan(v)$$
to get
$$4\int_0^{+\infty}\frac{du}{2(1+u^2)-1}=\pi\sqrt{2}$$
Comment: Thanks, this helped me clear up lots of things :)
Answer: tan(x) is periodic:

$\tan^{-1}(x)$ is multi valued:

$\tan(x) =  \tan(x+ k\pi) = y$
$\tan^{-1}(y) = x + k\pi$
Wolfram gives $\sqrt{2} \pi$ for the integral.
$\tan^{-1}\left(\frac{\tan{2\pi}}{\sqrt{2}}\right) = \tan^{-1}(0) = 0 + k\pi = 2\pi$ in this case.
Comment: Thank you! This makes sense :D
Answer: $$\int_{0}^{2\pi}\frac{1}{\cos^2(\theta)+1}\, d\theta=4\int_{0}^{\pi/2}\frac{1}{\cos^2(\theta)+1}\, d\theta$$
$$=4\int_{0}^{\pi/2}\frac{\sec^2\theta}{1+\sec^2\theta}\, d\theta$$
$$=4\int_{0}^{\pi/2}\frac{\sec^2\theta\ d\theta}{1+\tan^2\theta+1}$$
$$=4\int_{0}^{\pi/2}\frac{d(\tan\theta)}{(\tan\theta)^2+(\sqrt2)^2}$$
$$=4\left[\frac{1}{\sqrt2}\tan^{-1}\left(\frac{\tan\theta}{\sqrt2}\right)\right]_0^{\pi/2}$$
$$=4\left[\frac{1}{\sqrt2}\frac{\pi}{2}-0\right]$$
$$=\color{blue}{\pi\sqrt2}$$
Answer: Here is an alternate way with contour integration:
$$\begin{aligned}
 J= \int_{0}^{2\pi}  \frac{d\theta}{\cos^2 \theta+1} &=
\oint_{|z|=1} \frac{\frac{dz}{iz}}{ \left[ \frac{(z+z^{-1})^2}{4}+1 \right]}\\
 &=  \frac{4}{i}\oint \frac{ z \, dz}{  z^4 + 6 z^2 +1 }\\
\end{aligned}$$
Take the integral in the positive (counter-clockwise) direction.
There are four roots to the denominator of the integrand:
$$z_k \in \left\{ \mp i \sqrt{3 \mp 2\sqrt{2}} \right\}, \quad k=1,\cdots,4 $$
The roots inside the circle are
$z_1 =  - i \sqrt{3 - 2\sqrt{2}} $ and $z_2 =  i \sqrt{3 - 2\sqrt{2}} $.
$$J=2\pi i \cdot \frac{4}{i} \left[ \text{Res}_{z=z_1} \frac{z}{z^4+6z^2+1}+\text{Res}_{z=z_2} \frac{z}{z^4+6z^2+1}\right]
= 8\pi \left[\frac{1}{8\sqrt{2}}+ \frac{1}{8\sqrt{2}} \right]=\sqrt{2}\pi.$$
Even easier is to recognize that the substitution $w=z^2$ inside the integral leads to
$$J=\frac{4}{i} \oint_{|w|=1} \frac{dw}{w^2+6w+1}$$
We either have to wind around the circle twice in the $w$-plane or  multiply by $2$ so that the constant out in front is again ${4}/{i}$.
and so
$$J=8\pi \text{ Res}_{z=2\sqrt{2}-3} \, \frac{1}{w^2+6w+1}=8\pi\cdot \frac{1}{4\sqrt{2}}=\sqrt{2}\pi.$$


How much important is it to develop different database specific escaping mechanisms for different projects?

Question: As we know, the magic quotes in PHP is already deprecated, this is done to discourage relying on this feature for preventing SQL Injection and to encourage developers to develop database specific escaping mechanisms.[Source: php.net] Is this really neccessary?
If Yes,
Why? Why can't we just use functions like mysql_real_escape_string(), addslashes() and stripslashes() to achieve the same thing instead of developing a different escaping mechanisms?
An answer with example will be appreciated. Thanks
Comment: Pay attention to the "database specific" part. Not all DB's behave the same way.
Comment: I have modified my question, to reflect my actual query? Please review
Comment: my answer remains unchanged. `mysql_real_escape_string()` is mySQL specific. Other databases may need other methods of escaping data. Modern database layers like PDO do this automatically for you.
Answer: mysql_real_escape_string() already is a database specific escaping mechanism :)
If you are choosing a database layer for a new project, be sure to take a look at PDO whose prepared statements will automatically take care of any necessary escaping.


non-parametric test: proof of Friedman's statistic

Question: I am asked to prove that the Friedman statistic has two equivalent forms, namely:
$$
\Large
\begin{aligned}
S &= \frac{12n}{k(k+1)}\sum_{j=1}^k\left(R_{.j}-\frac{k+1}{2}\right)^2\\
&= \left[\frac{12}{nk(k+1)}\sum_{j=1}^kR_j^2\right]-3n(k+1)
\end{aligned}
$$
This is my attempt at a solution starting from LHS and trying to arrive at RHS. I feel like there are some cancellations of terms I should be aware of. Any help is appreciated. Thanks.
Comment: Please explain what the "$R_j$" and "$R_{\cdot j}$" mean and what distinction is represented by the dot.
Comment: @whuber Rj is the sum of the ranks for each column while R.j = Rj / n (i.e. the sum of the ranks divided by the number of observations in that column). The dot distinguishes the sum (Rj) from the average (R.j)
Answer: The last item should be
$$\frac {12n}{k(k+1)}\sum_{j=1}^k\frac {(k+1)^2}4=\frac {12n}{k(k+1)}k\frac {(k+1)^2}4 = 3n(k+1)$$
instead of $\frac {3n(k+1)}k$ as written on that yellow paper.
The middle item:
$$\frac {12}k\sum_{j=1}^kR_j = \frac {12}k\sum_{j=1}^k\sum_{i=1}^nr_{ij} = \frac {12}k\sum_{i=1}^n\sum_{j=1}^kr_{ij}=\frac {12}k\sum_{i=1}^n\frac {1+k}2k=\frac {12}kn\frac {1+k}2k = 6n(k+1)$$
Combine last two items,
$$-6n(k+1)+3n(k+1)=-3n(k+1)$$


F#m (b6, add9) OR DΔ (#11)/F#? To use b6 chords or not

Question: I have encountered the claim that b6 chords are often a misinterpretation of a Maj7th chord with the third in the bass... It seems fairly reasonable but my head wants to revert to the b6 (or b13 maybe) in the following modulation from B minor to C minor:
Bm (add9)       |      GmΔ7     |        DΔ (11)/G         |
F#m(b6, add9)   |    Em(b6, add9)   | Am(b6, add9)  EΔ7/G#   GMaj7/B |  Cm
Do these b6's in fact make sense? Maybe b13 would make more sense (but I used flat 6 since the fifth is placed in a higher octave) or would you vote for replacing them with:
DΔ#11/F#    |    CΔ#11/E    | FΔ#11/A
If so, what are your arguments?
I have a fair grasp with theory as in WHAT chords, chords are on their own, but sometimes I get lost as to what their "functions" would be and thus become a bit confused with what to call them.
Comment: Side note: judging by the chords in the example, you probably already know that the term "functions" is pretty hard to apply to this chord sequence :)
Answer: I don't think there is a big problem with either version. Where is the root of each chord may depend on the voicing used, and you are the best person to answer where you hear the root of each chord.
Note also, that chord symbols don't always have to indicate the roots of the chords. They primarily serve as an efficient way to communicate what notes to play.
Without additional information, my personal preference would be the second notation, with Δ#11 chords. They seem more straight forward to interpret and I think they appear commonly in scores. "add9" puzzles me a bit more, because it makes me wonder: is it really important that I don't play 7, or is it just a specific voicing the arranger had in mind?
Comment: Thanks for your answer! It makes sense and like you probably guessed I have used the root of the voicings as the root of the chords here. But I agree that it might be more straight forward to use "common" notations if I am to give it to someone else to read.

and as a note on the add9 chords, here it is important to leave out 7 as the focus is strictly on the semitone dissonance created when voicing it with the third stacked just above the ninth. Like 1-5-9-3 (or 1-b6-9-3-5-(1) in the b6add9 case). Adding the 7 simply adds a colour that takes away some of the gloomy vibe.
Thanks again!


Qsort based on a column in a c-string?

Question: A class project involves sorting an array of strings, with each string containing an equal number of columns like this:
Cartwright   Wendy    93
Williamson   Mark     81
Thompson     Mark     100
Anderson     John     76
Turner       Dennis   56
The program accepts a command-line argument for which column to sort on, and should print out the sorted strings unmodified.
I would like to use strtok to break up copies of each string into columns, and make structs for each line like this:
struct line {
    char * line;
    char column_to_sort_on[MAX_COLUMN];
}

My problem is in the comparison function pointer that qsort takes as an arg. If I understand correctly, the comparison function must take two const void pointers to the items to be sorted, and return an int. This means I can't pass pointers to structs into the comparison function because that is not what qsort will be sorting. I can't pass in the column number to sort on to the comparison function, because it can only take two args. How can I get around this to sort these strings based on specific columns?
edit: Sorting is limited to qsort or my own if I really want. Give the choice, I choose qsort. :)
edit # 2:The consensus seems to be either use a global variable for the column number, or just use qsort to sort an array of structs. I hadn't thought of just sorting the structs, and using the pointer in them to print out the original string. I think that is what I will do. Thanks for the help all!
Comment: Does the assignment say you have to pass an array of strings to qsort, or that the as a result a string array must be sorted, no matter what it takes? If the latter, you could sort an array of structs, and then reorder the string array according to the results.
Answer: Assuming you're not limited to using qsort, you can use std::sort, with a functor object that stores the column number. If you have to use qsort, one quick and dirty solution would be to store the column number in a global variable and use that in the comparisson function.
Comment: I thought about storing it in a global variable, but would like to avoid it if possible.
Answer: Different comparator functions, all of which take the whole struct, but each uses only one column for comparation.
Comment: Wouldn't this comparator function necessitate sorting an array of structs? I though what I passed into the comparator function had to be the same as what qsort was sorting, and I would only like to sort the original array of strings.
Answer: You can pass the structs like this:
struct line {
    char * line;
    char column_to_sort_on[MAX_COLUMN];
}
...

line*  Lines[max_lines]; // here you store the structs

int
cmp_lines( const void *elem1, const void *elem2 )
{
    line*  line1 = *(line**)elem1;
    line*  line2 = *(line**)elem2;
    // do the comparisons
}

qsort(Lines, max_lines, sizeof(line*), cmp_lines);

Comment: @Jergason, I corrected a bug in my code (line1 & line2 values).
Answer: C++ or C?  Based on your tags, I assume it's C++.  Let's try STL way.
You should use std::sort instead of qsort.  std::sort can take not only function pointer (compared to its C alternative), but any object that can be called as a function.  You may know that class instances can be called as functions with operator().  Then the solution is straightforward: create a "functor" class that will create different functions upon construction.  The sort call would then look like that:
std::sort(array, array+size, comparator(2 /* sort by column #2 */));

The functor class effectively creates a so-called "closure": a dynamically created functional object that has local variables, but doesn't share them with other functional objects created this way.  It would look like this:
class comparator{
  private: unsigned int field_n;
  public: comparator(unsigned int _field_n) : field_n(_field_n) {};
  public: int operator () (char const *  lhs, char const * rhs)
       { /* compare here fields with index field_n */ };
};

Note that instead of void pointers comparison "function" (i.e. the class instance you create) has char * parameters, so you don't bother yourself with type casting.
In C, unfortunately, you can't do this the other way than creating a global variable.

Qsort based on a column in a c-string?


Is the quotient ring of a PID a PID?

Question:
Let $A$ be a commutative ring and $S$ a multiplicative closed subset of $A$. If $A$ is a PID, show that $S^{-1}A$ is a PID.

I've taken an ideal $I$ of $S^{-1}A$ and I've tried to see that is generated by one element; the ideal $I$ has the form $S^{-1}J$ with $J$ an ideal of $A$. $J$ is generated by one element but I can't see why $I$ has to be generated by one element, maybe I'm wrong.
Comment: PIDs are required to be non-zero. So the question is No. ;) You have to assume that $0 \notin S$.
Answer: If $I$ is an ideal of $S^{-1}A$, then there exists an ideal $J$ of $A$ such that $I = JS^{-1}A$. Now there exists $r \in A$ such that $J = (r)$. We show that
$$
I = (r)
$$
where $r$ is now thought of as an element of $S^{-1}A$.
Firstly, if $x \in (r)$, then $x = \frac{a}{b}r$ where $\frac{a}{b} \in S^{-1}A$ and so $x \in JS^{-1}A = I$.
Secondly, if $y \in I = JS^{-1}A$, then $y = nr\frac{a}{b}$, where $nr \in J$ and $\frac{a}{b} \in S^{-1}A$, so $y = n\frac{a}{b}r \in (r)$.
Comment: Dear Sir , $x\in (r)=J$ J is ideal of A So how $x=a/br$ I do not understand .Please Can you tell me Thanks a lot
Comment: @idon'tknow observe that when we say that $I = (r)$ then it is meant that $I$ is generated by $\frac r 1.$ So if $x \in \left (\frac r 1 \right )$ then there exists $\frac a b \in S^{-1} A$ such that $x = \frac a b \cdot \frac r 1 = \frac {ar} {b},$ as required.
Answer: An arbitrary element $x$ of $S^{-1}J$ is of the form
$$
x=\sum_is_i^{-1}j_i
$$
with $s_i\in S, j_i\in J$ for all $i$. If $j$ is a generator of $J$ as an ideal, then $j_i=a_ij$ for some $a_i\in A$. Can you now write $x$ in the form $x=x'j$ for
some $x'\in S^{-1}A$?
Answer: PID means principal ideal ring and integral domain. I will use notation $R$ instead of $A$.
Let $J$ be an ideal in $S^{-1}R$. Then $\exists I$ ideal in $R$ such that $J=S^{-1}I$. Since $R$ is principal ideal and commutative with identity, we have $I=\langle a\rangle=Ra$ for some $a\in R$. We claim $S^{-1}I=S^{-1} \langle a\rangle = \langle a/s \rangle $ for any $s\in S$. Let $r/t\in S^{-1}I$. Then $r/t=r_1a/t_1$ for some $r_1\in R$ and $t_1\in S$. Note $$r/t=r_1a/t_1= r_1as/t_1s =(r_1s/t_1) (a/s).$$
Thus $r/t\in (S^{-1}R)(a/s)= \langle a/s \rangle $ and $S^{-1}I\subseteq \langle a/s \rangle$. Let $r/t \in \langle a/s \rangle$. Then $r/t=(r_1/t_1)(a/s)$ for some $r_1/t_1\in S^{-1}R$. Clearly $$r/t=(r_1/t_1)(a/s)=r_1a/t_1s\in S^{-1}I$$
since $r_1a\in \langle a\rangle =I$. Thus $\langle a/s \rangle \subseteq S^{-1}I$. Hence $S^{-1}I = \langle a/s \rangle$.
Now we show $S^{-1}R$ is integral domain. $S^{-1}R$ is commutative ring with identity. We claim $S^{-1}A$ has no zero divisor. Assume towards contradiction, $\exists a/s,b/t \in S^{-1}R -\{0/s\}$ such that $(a/s)(b/t)=ab/st=0/s$. So $\exists s_1\in S$ such that $s_1(abs-st0)=abss_1=0$. Since $R$ has no zero divisor and $0\notin S$, we have $a=0$ or $b=0$. WLOG, assume $a=0$. Then $a/s=0/s$. Thus we reach contradiction. Hence $S^{-1}R$ has no zero divisor. Therefore $S^{-1}R$ is integral domain.

Is the quotient ring of a PID a PID?


What do all the climber-specific terms and slang mean?

Question: I've been hearing a lot of words thrown around by climbers like "crimper", "gaston", "flag out", "whipper", "flapper", and others.
What do these and the rest even mean?  Could someone compile a list of these definitions?
Answer: This is a work in progress:
Beta

n. Instructions, suggestions, methods for doing a move (or sequence of moves) in a route. ("You're doing that the hard way. Try my beta...")

Bump

n. A movement where the hand (or foot) that moved last, makes the next move as well.  For example, you grab a hold with your right hand, then move again with the same hand to a further hold.
v. To do the movement described above.

Choss

n. Any kind of debris found on outdoor rock, including chalk buildup, moss, dirt, vines, vegetation, etc.
Variation: chossy (adj.) being covered in choss ("Bring a brush; that route is chossy!")

Crimp

n. Type of hold (or hand position) where the fingers are curled and the fingertips are used most prominently to pull.
v. To use the hand position described above (not necessarily on a "crimp" hold). There is an open-handed crimp position where the thumb is not used, as well as a closed-handed "full-crimp" position where the thumb is used. Both variations have their uses.

Cross

n. A movement where the hand (or foot) horizontally passes the other hand (or foot). The term is often used in contrast with a "bump", to clarify how to approach the next hold. ("Should I cross with my left hand, or bump with my right?")
v. To do the movement described above.

Deadpoint

n. The apex of the body trajectory in a dynamic movement.

Dyno

n. A dynamic movement where the climber launches up to a hold (or holds) with both feet leaving the wall before the hands reach their destination. Essentially a jump.

Edge

n. Type of hold where the usable side consists of a flat, often 90-degree angle.  Similar to a crimp, but usually deeper (at least to the first knuckle) and more flat.

First Ascent

n. The first ever successful send (by anybody) for a given route. Sometimes abbreviated to "F.A."

Flag

n. To extend one's leg and foot outward (at least somewhat horizontally) against and along the wall, rigidly, as a technique to avoid body swing (barn-door). The name comes from horizontal flagpoles.

Flapper

n. A skin injury (generally on the fingers or hand) where a portion of torn skin is left partially attached, like a flap.

Flash

n. A successful send on one's first attempt. (Beta may or may not have been given, and the climber may or may not have seen someone else doing the same climb prior to the ascent.)
v. To successfully send a route on one's first attempt, as described above.

Gaston

n. A hand position where the hand is pointed inward while the elbow points outward.  This is generally the reverse of a side-pull, in which the hand points outward.
v. To use the hand position described above.

Jib

n. Type of hold that is very small, often approximately coin-sized, generally used as footing (though in some situations used as hand-holds as well).

Jug

n. Type of hold that is large and deep enough to wrap one's fingers behind easily. The easiest class of hold to use, perhaps with the exception of some "handlebar"-style artificial holds used in gyms.
v. To use easy, jug-style holds to climb. ("I'm just going to jug up to the top since we're in a hurry.")

On-sight

n. A successful send on one's first attempt (a "flash") without having been given any beta and without having seen another climber work on the route beforehand.
v. To successfully send a route on one's first attempt, as described above.

Pinch

n. Type of hold (or hand position) where two opposite sides are used in a compressing fashion: one side for the thumb, and the other side for the remaining fingers.
v. To use the hand technique described above.

Pump

n. An effect caused by overuse of the forearms where they become stiff and weak
Variation: pumpy (adj.) especially taxing on the forearms
Variation: pumped (adj.) having forearms that are fatigued from overuse

Red-point

n. A climber's first successful send on a particular route, generally after having attempted previously without success. ("I finally got the red-point on that 5.11 today!")
v. To send a route as described above.

Send

n. A successful completion of a route without falling or resting on the rope.
v. To successfully complete a route without falling or resting on the rope.
Variations: sent (v., past tense)

Sloper (rhymes with "hope her")

n. Type of hold where the hand is mostly open and flat, and where the climber must rely more heavily on managing static friction instead of gripping.
Variation: slopey (adj.) having many slopers ("That route sure is slopey!")

Whipper

n. A particularly long-distance, often undesirable fall while sport climbing or trad climbing.  The name comes from the whipping motion of the rope while catching the fall.

I know there are more, but I'll have to add them later.
Comment on or edit this answer if you think anything should be added or changed.


Riemann Integration of greatest integer function on x^2

Question: How to show $$ [x^2] +\mid x-1 \mid $$ is Riemann Integrable in [0,2] ?
After splitting into 3 intervals
$$[0,1],[{1,\sqrt 2 }], [{\sqrt 2,\sqrt 3 }], [{\sqrt 3,2] }$$
I will explain how I proceeded my doubt is with greatest integer function part,
after splitting into 3 intervals
$$[0,1],[{1,\sqrt 2 }], [{\sqrt 2,\sqrt 3 }], [{\sqrt 3,2] }$$
In the interval $$[0,1]$$ Supremum of function is 1 and Infimum is 0.
In the interval $$[{1,\sqrt 2 }]$$ Supremum of function is 2 and Infimum is 1.
In the interval $$[{\sqrt 2,\sqrt 3 }]$$ Supremum of function is 3 and Infimum is 2.
Now U(P,f) = $$ 1(1-0)+2(\sqrt 2-1)+ 3(\sqrt 3-\sqrt 2)+4(2-\sqrt 3)                 $$
and L(P,f) = $$ 0(1-0)+1(\sqrt 2-1)+ 2(\sqrt 3-\sqrt 2)+3(2-\sqrt 3)                 $$
and they are different values.
Comment: Do you know that a function is Riemann integrable if it is bounded and has a finite number of points where it's not continuous?
Comment: Yes, I have seen that theorem. But how to make L(P,f) and U(P,f) equal here, then only it is Riemann integrable, right?  Is there anything wrong in the way I have calculated the Riemann sums.
Answer: Please use the following method:
Since the function $ [x^2]  $ is discontinuous at $1,\sqrt 2, \sqrt 3  $ in the interval [0,2],
we partition the interval as follows:
x0($=0$), x1 , x2 .... xi, y0($=1$), y1 , y2.... yi,z0 (=$\sqrt 2$),z1 , z2.... zi, k0 (=$\sqrt 3$),k1 , k2.... ki,m0$(=2)$
Now U(P,f)= 0*$\Sigma$xi + 1*(y0-xi) +1*$\Sigma$yi + 2*(z0-yi) + 2*$\Sigma$zi +3*(k0-zi)+ 3*$\Sigma$ki + 4*(m0-ki)
=$0+1*(\sqrt2-1)+2*(\sqrt3-\sqrt2)+3*(2-\sqrt3)+$1*(y0-xi) +2*(z0-yi) +3*(k0-zi) + 4*(m0-ki)
Take
        $\epsilon$ = 1*(y0-xi) +2*(z0-yi) +3*(k0-zi) + 4*(m0-ki)
Now L(P,f)= 0*$\Sigma$xi + 0*(y0-xi) +1*$\Sigma$yi + 1*(z0-yi) + 2*$\Sigma$zi +2*(k0-zi)+ 3*$\Sigma$ki + 3*(m0-ki)
=$0+1*(\sqrt2-1)+2*(\sqrt3-\sqrt2)+3*(2-\sqrt3)+$  1*(z0-yi) +  +2*(k0-zi)+  3*(m0-ki)
Now taking U(P,f) - L(P,f) <  $\epsilon$
Hence $ [x^2]  $ is Riemann Integrable in [0,2]
Comment: (y0-xi) etc.. are very small quantities since it is partitioned like that.


Problema no nome da tabela durante a criação pelo hibernate

Question: Estou "anotando" uma entidade Menu usando o hibernate/jpa, e Menu contém uma entidade ShareActivity embeddeble que eu criei.
@Entity(name="menu")
public class Menu implements Component {
    @Embedded
    @AssociationOverride(name="menu_share_activity",joinTable=@JoinTable(name="share_activity"))
    private ShareActivity enable;
    ...
    getters e setters
}

interface Component é vazia
@Embeddable
public class ShareActivity {

    @NotNull
    @CollectionTable(name = "share_activity")
    private Map<Actor, Boolean> status;

    public ShareActivity() {
        this.status = new HashMap<Actor, Boolean>();
        this.status.put(Actor.owner, true);
        this.status.put(Actor.company, false);
        this.status.put(Actor.custumers, false);
        this.status.put(Actor.employee, false);
        this.status.put(Actor.friend, false);
    }
    ...
    getters e setters
}

fasso uso de um enumerador para restringir o número de atores no meu map
public enum Actor {
    owner,
    friend,
    custumers,
    company,
    employee
}

Em fim quando eu adiciono a variável ShareActivity na minha classe Menu ela cria uma tabela Menu_status, só que Menu está "anotado" como @Entity(name="menu") e ainda assim a tabela enciste em criar o nome da classe Menu com m maiúsculo, já tentei @Table(name="menu"), e não funcionou.
Alguém sabe se da pra fazer isso, e se sabe como faz?
Meio que todo o banco de dados está sob o padrão snake_case
Answer: Use a anotação @AssociationOverride. Exemplo:
Classe Menu:
@Entity
public class Menu {

    @Embedded
    @AssociationOverride(name="status",joinTable=@JoinTable(name="menu_share_activity"))
    private ShareActivity enable;

    //outros métodos e atributos
}

Classe ShareActivity:
@Embeddable
public class ShareActivity {

    @ElementCollection
    @MapKeyColumn(name="actor")
    @MapKeyEnumerated(EnumType.STRING)
    @Column(name="value")
    private Map<Actor, Boolean> status;

    public ShareActivity() {
        this.status = new HashMap<Actor, Boolean>();
        this.status.put(Actor.owner, true);
        this.status.put(Actor.company, false);
        this.status.put(Actor.custumers, false);
        this.status.put(Actor.employee, false);
        this.status.put(Actor.friend, false);
    }
}

Comment: dessa forma cria apenas uma tabela, e impossíbilita o reaproveitamento em outras classes (esqueci de mencionar o map em B está anotado como ElementCollection e ele por padrão nomeia como classe_variavel a tabela, e como é Embedebla esse elementCollection deveria fazer a_s) uma vez que A está com Entity(name="a")
Comment: @bruno_arabica editei a resposta com uma solução para esse caso.
Comment: estou recebendo esse erro: org.hibernate.MappingException: Could not determine type for: java.util.Map, at table: A, for columns: [org.hibernate.mapping.Column(s)].
e a anotação @CollectionTable não está criando a tabela
Comment: @bruno_arabica você terá que editar sua resposta e colocar as classes A, B, C e D correspondentes do seu projeto. Sem saber como elas são, não é possível te ajudar.
Comment: Editado! As classes são javabeans, por conta disso removi os outros atributos e os métodos pôs eles não são tão importantes para a pergunta
Comment: @bruno_arabica editei a resposta com a solução.
Comment: fincionou perfeitamente, agradecido por toda ajuda


energy efficiency of the 2014 Formula 1 cars?

Question: How much more energy efficient are the new 2014 Formula 1 cars compared to the 2013 cars?
Answer: 2014 introduced a new rule that fundamentally changes much of the strategy behind a Formula 1 race.  F1 cars are now limited to 100 kg of fuel per race, and limited to a maximum fuel flow of 100 kg/hour.  Prior to this year, there were no fuel limits.
In 2013, F1 vehicles typically used 160 kg of fuel per race at a flow of 170 kg/hour (Source).  The new limits require vehicles to use approximately one-third less fuel in each race than they did last year.  For efficiency in terms of distance per unit of fuel (miles per gallon), this means that this year the vehicles will be about one-third more efficient than last year.
Before this year, cars could burn as much fuel as necessary to get as fast as possible.  Under the new fuel limit rules, cars can only go as fast as they can while staying under the fuel limits.  The penalty for breaking these rules is disqualification, as Daniel Ricciardo found out last week at the Australian Formula 1 Grand Prix, when he finished second, but was later disqualified when it was determined that his car exceeded the 100 kg/hour flow limit (Source).
Comment: The comparison between a F1 and a Ford Focus is irrelevant. Moreover the F1 (as other motor competitions) are a test bench for our cars. If a 1.6L Ford Focus can reach "good values" it's thanks to efforts made in competition
Comment: I've googled for some numbers and here are the efficiencies I found: 2014 Australian GP distance: 191 miles = 307.4 km. Litres of fuel per car: 140 litres. Thus the efficiency for Australia was 307.4/140=2.195 km/l. As a comparison, A 1.6L Ford Focus is reported to do about 19 km/l, or x8.68 more fuel efficient. On a 80kmh speed, the Ford Focus would take 3.8375 hours to complete the race distance, whereas Nico Rosberg did it in 1.55 hours, x2.475 more time efficient. So if my calculations are correct, it takes 8.6 times more fuel to be 2.5 times faster for the two 1.6L motor cars.
Answer: The above answer is a good one but it only addresses fuel efficiency.  There have been other changes noted below that partly allow for this increase in fuel efficiency.
The rules for 2014 have also changed regards the Kinetic Efficiency Recovery Systems used, also known as KERS.
These devices harness energy from the cars when they brake and store this energy in batteries so the driver can use this when accelerating.
In 2013 the cars were allowed to harness energy only when braking, the energy harnessed was typically enough for an equivalent 80 BHP boost for 6-7 seconds per lap and would shave around 2 or 3 tenths of a lap time.  This varies depending on the track and conditions.
For 2014 KERS can be generated under braking (Kinetic) or by using spare heat energy from the engine, they are now referred to as - Motor Generator Unit - Kinetic [MGU-K] and Motor Generator Unit - Heat [MGU-H].  The teams are also allowed bigger battery packs to store more energy.
Power is now greatly increased due to this and the larger batteries, systems can now harness up to 4 Mega Joules of energy per lap, giving a potential boost of 160 BHP for up to 33 seconds per lap.  This can trim up to 8 seconds off the lap time.
When KERS was first introduced in 2011 a lot of teams didn't use it as the benefits weren't obvious - the small lap time gain was offset due to the weight of the system and its reliability.
In 2014 all the teams use this as technological improvements mean the advantages far outweigh the drawbacks.
One final point is the way KERS is now used.  Up to and including 2013 the drivers had a button they could press when they wanted the extra power.  In 2014 the power is automatically delivered when the driver accelerates.  He can modify this behaviour by changing the engine mapping.
Reference:  http://www.formula1.com/inside_f1/understanding_the_sport/8763.html
Comment: +1. The ERS helps the car achieve the required fuel efficiency by converting energy lost due to braking and heat into usable energy for the engine.


How to return text to the client as html page?

Question: In ASP.NET Application. I need to return string (which contains all necessary html tags) to the client browser as downloadable HTML file.
So basically convert string to HTMLDocument and send it to the client.
How it can be done in asp.net c# application?
Comment: Already answered here: http://stackoverflow.com/a/7147898/61697
Answer: Essentially there are four things you would want to do:

Clear anything currently in the Response buffer.  A call to Response.Clear(); will take care of this.
Set the appropriate response headers.  In the case of wanting to return a downloadable file, you'd set the content-disposition header as such: Response.AddHeader("content-disposition", "attachment; filename=somefile.html");  (Where "somefile.html" is the name to suggest that the browser use for saving the file.  It can be hardcoded or a dynamic value, that's up to you.)  This is the standard way to suggest to a browser that it should save the file.  I say "suggest" because it's not required.  Understand that HTTP has no concept of "files."  Only requests and responses.  What you're doing with this header is telling the browser that the data stream you're sending it should be saved as a file.  It's highly likely that the browser will comply with this.
Write the data.  Response.Write(); is the usual way to do this.
End the response (so the browser can be signaled that it's received everything).  Response.End(); does this.

Take a look at the other options available on the HttpResponse class, though.  There are even methods called WriteFile() which may make the code even simpler.  I'm not familiar with them, so I can't really give an example.


Include referenced term's custom fields in node view with content display

Question: I have a taxonomy term reference field in a node (D8).
I have a content (node) view that needs to use a content display rather than fields.
The term is selected, but not the custom fields that have been added to the vocabulary (see the query, below).
The display settings for the vocabulary have all the fields being displayed.
I thought perhaps there was a relationship that I could add that would result in the fields being selected. The only applicable option is for Taxonomy term, which I have added. It results in the taxonomy_term_field_data being joined, but not the custom fields.
Do I actually need to hook the query before execution to add joins for the additional fields?
SELECT node_field_data.created AS node_field_data_created, node_field_data.nid AS nid, taxonomy_term_field_data_node__field_tags.tid AS taxonomy_term_field_data_node__field_tags_tid
FROM
{node_field_data} node_field_data
LEFT JOIN {node__field_tags} node__field_tags ON node_field_data.nid = node__field_tags.entity_id AND (node__field_tags.deleted = '0' AND node__field_tags.langcode = node_field_data.langcode)
LEFT JOIN {taxonomy_term_field_data} taxonomy_term_field_data_node__field_tags ON node__field_tags.field_tags_target_id = taxonomy_term_field_data_node__field_tags.tid
WHERE (node_field_data.status = '1') AND (node_field_data.type IN ('article'))
ORDER BY node_field_data_created DESC
LIMIT 1 OFFSET 0

Comment: I haven't tried it but I expect you need to control it through the Field settings inside Views. What Formatter have you chosen foe the Taxonomy term field? It should be default I think. Also check under Manage Display for the Content Type that you have that Field set to display as Rendered entity or another View that contains all the fields you want to show. I think the Relationship might not be needed if you use View Modes (I mean Display settings modes, not related to Views module).
Comment: It was that it was selected as label in the display mode and not rendered entity. Can you paste it as an answer so I can credit you?
Answer: The Default Content View mode is controlled through the Manage display page of the related Content Type.
Check that page and make sure that the Taxonomy Term reference field is set to Rendered entity and not Label or some other option.
The Rendered entity option will make sure that all the Vocabulary fields set to be displayed for terms will also appear under Content rendering of the Content type.


How to get the name of the apache user

Question:
Possible Duplicate:
Finding out what user Apache is running as?

I use openSuse and I try to find out the name of the apache user. So I enter
vim /etc/passwd

in the terminal. Or
ps -a

Both don't have apache listed. I have mysql and other stuff but apache isn't mentioned.
Any ideas?
ps aux | grep httpd

Output:
Comment: Your apache is running as user `wwwrun`
Comment: Check with `groups wwwrun`.
Comment: thanks and whats the group for that user?
Comment: On OpenSuSe it's done by following command: `grep -i "^user" /etc/apache2/uid.conf
`
Answer: Try
ps aux | grep httpd

or
ps aux | grep apache

The first column of the output is the user that is running the process.
Sample output from a CentOS system
apache    4173  0.0  0.6 239100  6720 ?        S    Aug04   0:00 /usr/sbin/httpd

and an Ubuntu system
www-data  3124  0.0  0.2   6452  2180 ?        S    Aug04   0:00 /usr/sbin/apache2 -k start

On CentOS apache is running as user apache and on Ubuntu it's running as www-data
Comment: the first column is named with root, so is root the apache user?
Comment: I edited my question. habe a look at the output
Comment: no output pal. You messed up the link!
Answer: just see on httpd.conf (usually on /etc/httpd/conf/)
grep User httpd.conf
Answer: You sure have creative ways for finding stuff. :-)
I have not installed Apache in openSUSE, but my blind guess is that the user is not actually named apache but httpd instead. Or then you don't have Apache installed. Please, when asking, try to be more verbose and descriptive.
Answer: $ grep -i "^user" /etc/apache2/httpd.conf

How to get the name of the apache user


What is the most reliable way to import self-updating financial data into R currently?

Question: The broad question of finding free financial data has been tackled extensively (http://quant.stackexchange.com/questions/141/what-data-sources-are-available-online), however, all things R change like the wind. Many answers from that page date to 2012, and similar questions on this stack are outdated.
I'm looking primarily for end of day equity data, but bond yields or currency prices would be good too. Also, I'm not looking for just spreadsheets of historical data, but rather a package or API I can call on in a script. This way it will be part of a dynamic model going into the future.
Answer: Stay away from Yahoo finance. They have unreliable corporate action adjustments.
Register for a free account at Quandl. Check out the Quandl R API.
They have high, low, open, close, and volume (HLOCV) data for around 3000 US stocks for free. Plenty of other stuff for free also.


Is it possible to compute the limit of a function using the Epsilon Delta ($\epsilon,\delta$) Definition of Limit?

Question: I am not sure how this questions sounds but might it be possible to actually compute and not just prove the limit of any arbitrary function whose limit exists using $\epsilon-\delta$ notation?
$$\forall \epsilon >0, \exists \delta>0 :\forall x, |x-c|<\delta\implies|f(x)-L|<\epsilon $$
Comment: I think you might have to work on your logic there, it seems like only constant functions $f(x) = L$ would statify it. I suggest something like $$\forall \epsilon >0, x, \exists \delta>0, L :|x-c|<\delta\implies|f(x)-L|<\epsilon$$
Comment: Hard to tell if something "*might be possible*," but I've never seen anything that would match this.
Comment: I don't get what @Arthur means by $\forall \epsilon >0,x $ or actually most of it...
Comment: Yeah, I'm confused by @Arthur's point, too. Why does $L$ depend on $\epsilon$ here?
Comment: @ThomasAndrews What I mean is that as it stands, for any $\epsilon$, $f$ is closer than $\epsilon$ from $L$, for all $x$. You should rather say that given an $\epsilon$ and an $x$, there exists a $\delta$ and an $L$ (with $\delta$ depending on both $\epsilon$ and $x$, and $L$ depending on just $x$). That is what I'm trying to convey. I'm not used to logic notation conventions, so I might've skipped a qualifier or two.
Comment: $\exists \delta>0,L$ means "there exists a delta greater than zero, and an L." But $L$ is a constant which is not supposed to depend on $\epsilon$
Comment: @ThomasAndrews But it _is_ supposed to depend on $x$. Really, my problem with OP's logical statement is that $x$ seems to be qualified at an awkward place, and $L$ is not qualified at all.
Comment: No, @Arthur, it depends on $c$. We are talking $\lim_{x\to c} f(x)$.
Comment: @ThomasAndrews Oh, yes. It is the $c$ that messes with my head.
Answer: The nature of the $\epsilon-\delta$ definition is that it takes in a function $f(x)$ a limit point $a$, and a limit value $L$, and provides a definition for $\lim_{x\to a} f(x) = L$. Thus the nature of the beast is not one of calculation - it requires even a proof to show that if $\lim_{x\to a} f(x)=L_1$ and $\lim_{x\to a} f(x)=L_2$ then $L_1=L_2$, because the definition does not assert that only one limit can exist.
It is best to realize that the $\epsilon$ definition of limits was arrived at as a formalism of something that all mathematicians understood. They had been using limits and continuity for centuries before they came up with this definition. The definition just finally gave a strong form to validate a limit value.


Node, servidor enviar informação para página (controle de senha banco, laboratório...)

Question: Boa noite!
Não sei se é possível implementar a seguinte situação: tenho uma página html que é um monitor (possui o ultimo numero chamado), na segunda página html, o usuário poderá clicar para solicitar o próximo numero. Eu até consigo trocar informações via socket, porém somente com a página que foi clicada, eu teria que atualizar a outra página que é o monitor. Caso não consiga dessa forma, teria que verificar o endpoint a cada instante para saber se o numero foi alterado. Alguma sugestão, mesmo que não seja via socket?
Solução atual que não funcionou:
server.js
var http = require('http')
var express = require('express')
var socketio = require('socket.io')
var app = express(server)
var server = http.Server(app)
var io = socketio(server)

app.get('/', function(req, res){
  console.log('Passei aqui!!!');

  req.socket.on('login_monitor', function(data, callback) {
    req.socket.join('monitor');
    callback();
   });

  res.sendFile(__dirname + '/monitor.html');
});

app.get('/teste', function(req, res){
  console.log('TESTE!!!');
  io.on('connection', function(socket){
    socket.on('echo', function(data){
      socket.emit('echo', 'Servidor--->');
      console.log(data);

       socket.on('echo', function(data) {
        socket.emit('echo', 'Servidor--->'); //envia para quem invocou o echo
        io.to('monitor').emit('echo', 'Funcionou!!!!!'); //envia para o monitor
      });

    });
  });
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  socket.on('echo', function(data){
    socket.emit('echo', 'Servidor--->');
    console.log(data);
  });
});

server.listen(8080);

index.html
<!DOCTYPE html>

    <meta charset=utf-8 />
    <title>Echo server</title>

Próximo cliente (Clique aqui)

monitor.html
<!DOCTYPE html>

    <meta charset=utf-8 />
    <title>Echo server</title>

Senha 609 caixa 3

Answer: Crie um login para o monitor
monitor.html
  socket.emit('login_monitor', {/*envie parâmetros se necessário*/}, function(){
      console.log('logado como monitor');
  });

server.js
  socket.on('login_monitor', function(data, callback) {
      socket.join('monitor');
      callback();
  });

Agora que os sockets dos monitores podem ser identificados com a chave 'monitor', você pode enviar mensagens para eles no echo
socket.on('echo', function(data) {
  socket.emit('echo', 'Servidor--->'); //envia para quem invocou o echo
  io.to('monitor').emit('echo', 'Servidor--->'); //envia para o monitor
});

Comment: Obrigado pelo retorno, vou fazer as alterações agora no fim da tarde.  Valeu!!!
Comment: Estou iniciando com Node e Javascript, minha dúvida pode ser muito simples, mas pela falta de conhecimento. Incluí o código no monitor.hrml, esse código é responsável por identificar a página, certo? Alterei o server.js  no endpoint raiz '/' para identificar o monitor no back-end. A cada chamada '/teste' incluí o ultimo trecho de código que você enviou.  Estou com erro ao acessar raiz 0.0.0.0:8080.  Vou atualizar os códigos na pergunta.  Obrigado pela força.
Comment: Estudei sobre socket, a sua resposta está show. Não estava conseguindo entender.  Valeu!!!


Disk method to find volume of solid revolved around x axis

Question: Use the disk method to find the volume of the solid generated when the region bounded by $\displaystyle y=\frac1{(1-100x^2)^\frac14}$, $y=0$, $x=0$, and $\displaystyle x=\frac1{20}$ is revolved around the x-axis
Answer: We get immediately that the volume is equal to
$$\int_0^{1/20} \frac{\pi}{\sqrt{1-100x^2}}\,dx.$$
For the integration, I suggest making the change of variable $10x=u$. Then $dx=\frac{1}{10}\,du$. We end up needing the integral
$$\int_{u=0}^{1/2} \frac{\pi}{10\sqrt{1-u^2}}\,du.$$
Note that $\int \frac{du}{\sqrt{1-u^2}}=\arcsin u +C$.
Comment: this makes sense, however the denominator is to the fourth root not to the square root so thats where im having trouble
Comment: Please remember that for $y=f(x)$ the volume is $\int_a^b\pi (f(x))^2\,dx$. So I squared the fourth root and got a square root. Recall that $(w^{1/4})^2=w^{1/2}$.
Comment: okay i see. i got the final answer to be (pi^2)/6 but that is incorrect
Comment: @LeahLewy: Apologies, I misread the function. Have written down the correct function, the answer will turn out to be $\frac{\pi^2}{60}$.


rf95_server freezes raspberry after a while

Question: I try to run a lora server on a raspberry pi 3B+ (from https://github.com/idreamsi/RadioHead/) without changing anything in the source code except the lora hat used (I use the Dragino Lora/gps hat). I run the server with sudo ./rf95_server. From a client whatever (trying with a rocket scream, or Arduino mini pro) I send regularly lora messages with the rf95_client. After about 7 or 8 receives, raspy freezes and I have to plugout plugin the power. Can anybody provide hints, what the cause could be? Thanks!
// rf95_server.cpp
//
// Example program showing how to use RH_RF95 on Raspberry Pi
// Uses the bcm2835 library to access the GPIO pins to drive the RFM95 module
// Requires bcm2835 library to be already installed
// http://www.airspayce.com/mikem/bcm2835/
// Use the Makefile in this directory:
// cd example/raspi/rf95
// make
// sudo ./rf95_server
//
// Contributed by Charles-Henri Hallard based on sample RH_NRF24 by Mike Poublon
// Edited by: Ramin Sangesari
// https://www.hackster.io/idreams/

#include <bcm2835.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>

#include <RH_RF69.h>
#include <RH_RF95.h>

// define hardware used change to fit your need
// Uncomment the board you have, if not listed
// uncommment custom board and set wiring tin custom section

// LoRasPi board
// see https://github.com/hallard/LoRasPI
//#define BOARD_LORASPI

// Adafruit RFM95W LoRa Radio Transceiver Breakout
// see https://www.adafruit.com/product/3072
//#define BOARD_ADAFRUIT_RFM95W

// iC880A and LinkLab Lora Gateway Shield (if RF module plugged into)
// see https://github.com/ch2i/iC880A-Raspberry-PI
//#define BOARD_IC880A_PLATE

// Raspberri PI Lora Gateway for multiple modules
// see https://github.com/hallard/RPI-Lora-Gateway
//#define BOARD_PI_LORA_GATEWAY

// Dragino Raspberry PI hat
// see https://github.com/dragino/Lora
define BOARD_DRAGINO_PIHAT

// Now we include RasPi_Boards.h so this will expose defined
// constants with CS/IRQ/RESET/on board LED pins definition
#include "../RasPiBoards.h"

// Our RFM95 Configuration
#define RF_FREQUENCY  868.00
#define RF_NODE_ID    1

// Create an instance of a driver
RH_RF95 rf95(RF_CS_PIN, RF_IRQ_PIN);
//RH_RF95 rf95(RF_CS_PIN);

//Flag for Ctrl-C
volatile sig_atomic_t force_exit = false;

void sig_handler(int sig)
{
  printf("\n%s Break received, exiting!\n", __BASEFILE__);
  force_exit=true;
}

//Main Function
int main (int argc, const char* argv[] )
{
  unsigned long led_blink = 0;

  signal(SIGINT, sig_handler);
  //printf( "%s\n", __BASEFILE__);

  if (!bcm2835_init()) {
    fprintf( stderr, "%s bcm2835_init() Failed\n\n", __BASEFILE__ );
    return 1;
  }

  //printf( "RF95 CS=GPIO%d", RF_CS_PIN);

#ifdef RF_LED_PIN
  pinMode(RF_LED_PIN, OUTPUT);
  digitalWrite(RF_LED_PIN, HIGH );
#endif

#ifdef RF_IRQ_PIN
  //printf( ", IRQ=GPIO%d", RF_IRQ_PIN );
  // IRQ Pin input/pull down
  pinMode(RF_IRQ_PIN, INPUT);
  bcm2835_gpio_set_pud(RF_IRQ_PIN, BCM2835_GPIO_PUD_DOWN);
  // Now we can enable Rising edge detection
  bcm2835_gpio_ren(RF_IRQ_PIN);
#endif

#ifdef RF_RST_PIN
  //printf( ", RST=GPIO%d", RF_RST_PIN );
  // Pulse a reset on module
  pinMode(RF_RST_PIN, OUTPUT);
  digitalWrite(RF_RST_PIN, LOW );
  bcm2835_delay(150);
  digitalWrite(RF_RST_PIN, HIGH );
  bcm2835_delay(100);
#endif

#ifdef RF_LED_PIN
  //printf( ", LED=GPIO%d", RF_LED_PIN );
  digitalWrite(RF_LED_PIN, LOW );
#endif

  if (!rf95.init()) {
    fprintf( stderr, "\nRF95 module init failed, Please verify wiring/module\n" );
  } else {
    // Defaults after init are 434.0MHz, 13dBm, Bw = 125 kHz, Cr = 4/5, Sf = 128chips/symbol, CRC on

    // The default transmitter power is 13dBm, using PA_BOOST.
    // If you are using RFM95/96/97/98 modules which uses the PA_BOOST transmitter pin, then
    // you can set transmitter powers from 5 to 23 dBm:
    //  driver.setTxPower(23, false);
    // If you are using Modtronix inAir4 or inAir9,or any other module which uses the
    // transmitter RFO pins and not the PA_BOOST pins
    // then you can configure the power transmitter power for -1 to 14 dBm and with useRFO true.
    // Failure to do that will result in extremely low transmit powers.
    // rf95.setTxPower(14, true);

    // RF95 Modules don't have RFO pin connected, so just use PA_BOOST
    // check your country max power useable, in EU it's +14dB
    rf95.setTxPower(14, false);

    // You can optionally require this module to wait until Channel Activity
    // Detection shows no activity on the channel before transmitting by setting
    // the CAD timeout to non-zero:
    //rf95.setCADTimeout(10000);

    // Adjust Frequency
    rf95.setFrequency(RF_FREQUENCY);

    // If we need to send something
    rf95.setThisAddress(RF_NODE_ID);
    rf95.setHeaderFrom(RF_NODE_ID);

    // Be sure to grab all node packet
    // we're sniffing to display, it's a demo
    rf95.setPromiscuous(true);

    // We're ready to listen for incoming message
    rf95.setModeRx();

    //printf( " OK NodeID=%d @ %3.2fMHz\n", RF_NODE_ID, RF_FREQUENCY );
    //printf( "Listening packet...\n" );

    //Begin the main body of code
    while (!force_exit) {

#ifdef RF_IRQ_PIN
      // We have a IRQ pin ,pool it instead reading
      // Modules IRQ registers from SPI in each loop

      // Rising edge fired ?
      if (bcm2835_gpio_eds(RF_IRQ_PIN)) {
        // Now clear the eds flag by setting it to 1
        bcm2835_gpio_set_eds(RF_IRQ_PIN);
        //printf("Packet Received, Rising event detect for pin GPIO%d\n", RF_IRQ_PIN);
#endif

        if (rf95.available()) {
#ifdef RF_LED_PIN
          led_blink = millis();
          digitalWrite(RF_LED_PIN, HIGH);
#endif
          // Should be a message for us now
          uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
          uint8_t len  = sizeof(buf);
          uint8_t from = rf95.headerFrom();
          uint8_t to   = rf95.headerTo();
          uint8_t id   = rf95.headerId();
          uint8_t flags= rf95.headerFlags();;
          int8_t rssi  = rf95.lastRssi();

          if (rf95.recv(buf, &len)) {
            printf("From: [#%d] => Temperature: ", to);
            //printf("Packet[%02d] #%d => #%d %ddB: ", len, from, to, rssi);
            printbuffer(buf, len);
            printf(" °C");
          } else {
            Serial.print("receive failed");
          }
          printf("\n");
        }

#ifdef RF_IRQ_PIN
      }
#endif

#ifdef RF_LED_PIN
      // Led blink timer expiration ?
      if (led_blink && millis()-led_blink>200) {
        led_blink = 0;
        digitalWrite(RF_LED_PIN, LOW);
      }
#endif
      // Let OS doing other tasks
      // For timed critical appliation you can reduce or delete
      // this delay, but this will charge CPU usage, take care and monitor
      bcm2835_delay(5);
    }
  }

#ifdef RF_LED_PIN
  digitalWrite(RF_LED_PIN, LOW );
#endif
  printf( "\n%s Ending\n", __BASEFILE__ );
  bcm2835_close();
  return 0;
}

Comment: Not sure if it's related, but check [this pull request](https://github.com/hallard/RadioHead/pull/4): "_Update README.md to document workaround for hang_" ("_Document a workaround for a system hang that will occur with modern kernels shipping with modern versions of Raspbian._") It's for another fork of the same repo you are using.
Comment: That's it. By adding the ```dtoverlay=gpio-no-irq``` to ```/boot/config.txt``` the freezing is gone. Thank you!
Comment: Good to hear! I will post this as an answer then (comments can be removed in the future)
Answer: This seems to be reported by another user and there is a work-around. At this moment there is pull request ("Update README.md to document workaround for hang") to add this to documentation, although the repository does not seem to be actively maintained (the pull request is from december 2018).
The description is:

Document a workaround for a system hang that will occur with modern kernels shipping with modern versions of Raspbian.

The updated readme says:

To avoid system hangs/instability starting with kernel 4.14, disable all GPIO kernel interrupts by adding this line to your /boot/config.txt:
dtoverlay=gpio-no-irq

This works around an issue with the design of the bcm2835 library and how it handles rising/falling edge detection events, but has some downsides as well.  For more information, see this issue and this discussion.


PostgreSQL foreign function

Question: I have not tested this, but want to know how it would work. I want to create three databases on three nodes. Each will be the same (schema, functions) but with different data.
I want to call a function from each of the database and join them eg:
<code>select server1.very_time_expensive_function(1,2) +
       server2.very_time_expensive_function(2,3) +
       server3.very_time_expensive_function(3,4);
</code>
But foreign functions cannot be created. Just foreign tables
What would you recomend?
Comment: http://wiki.postgresql.org/wiki/PL/Proxy
Comment: I found out when I `CREATE VIEW function_view AS SELECT very_time_expensive_function_without_args() AS col` on servers and then on local server `CREATE FOREIGN TABLE func_viewX (col integer) SERVER serverX options (table_name 'function_view')` then I can `SELECT func_view1.col + func_view2.col + func_view3.col`. But I dont know how to send args to the function in view.
Comment: You could have a look at postgresql_fdw to include your other databases into one ... Having a view on the included ones, you could do something like that. But maybe hadoop or something else would be a better choice maybe.
Answer: You can't send args to a function from a view unless those arguments either come from the rows or are specified at view creation time.  So you are better off looking at pl/proxy or dblink.  You may also be able to design functions and views along principles that work.  To be honest, pl/proxy is probably your best shot.

PostgreSQL foreign function


How do I find the bias of a robust estimator of covariance and mean?

Question: I wanted to use a robust version of covariance and mean. There are many methods like the FastMCD, Olive-Hawkins and DetMCD that achieve this. However, I would like to know how biased is the the final estimate I get.
Comment: Have you had a look at [this](http://stats.stackexchange.com/a/133782/603) answer?
Answer: Have a look at the following paper:
Shape Bias of Robust Covariance Estimators: An Empirical Study
M. Hubert · P. Rousseeuw · K. Vakili.
You can grab a copy here
Comment: Can you please extend your answer? What about summarizing the paper? At the moment this is rather a comment than an answer


Rails Device "Fingerprinting"

Question: Is there any way or best practice around device fingerprinting for a rails app?  In other words.  Given that all cookies are blocked, is there any way, with a relatively good degree of certainty, who the person is before they log in?
My assumption: IPs are unreliable for obvious reasons.
Answer: We've setup device fingerprinting in our rails app using ThreatMetrix.com
They are sort of expensive, but used by a number of large sites on the web and have built some good technology around this.
I have seen some Jquery open source released for this crop up: https://github.com/carlo/jquery-browser-fingerprint
But have not tried it.
Answer: Check out Fingerprintjs2. It is quite useful in trying to uniquely identifying a browser.
Answer: Even if all cookies are blocked, javascript can pick up plenty of device attributes.
Comment: Link is broken.

Rails Device "Fingerprinting"


Showing the maximal ideal of a certain local ring is non-principal

Question: I would like to show directly that the local (Noetherian commutative) ring $R = (k[x,y]/(xy))_{(x,y)}$ is non-regular, where $k$ is a field.
I have managed to show it has dimension 1, so it remains to show that its max ideal $M = xR + yR$ is non-principal.
Here I am stuck. Is there any way to proceed other than writing out all possible elements of $R$ as fractions of elements of the form $c + xf(x) + yg(y)$ for a constant $c \in k$ and polynomials $f,g \in k[t]$?
Comment: There are several approaches one can take depending on exactly how direct you want to be. Perhaps the simplest is to use the grading of $k[x,y]/(xy)$ and argue by degree.
Comment: Use Nakayama to compute the minimum number of generators as the dimension of a certain vector space.
Answer: Wikipedia gives the following characterization: local $(R,m)$ is regular iff $$\dim_{R/m}{\!(m/m^2)}=\dim{\!(R)}$$ where the dimension on the left is the usual dimension of a vector space, but the dimension on the right is Krull dimension.
In your case, $m=(x,y)$, $m^2=(x^2,y^2)$, and $R/m=k$.  Also, you already know that $\dim{\!(R)}=1$.  Thus it suffices to show that $m/m^2$ contains two linearly independent vectors.
What do you know about $ax+by$?


On the nature of exotic spheres

Question: This is a loose question (more philosophical than mathematical, I guess):
One definition reads: An exotic sphere is a manifold homeomorphic to the sphere, and not diffeomophic to it.
When you take this literally, these are just homeomorphic copies of the sphere, in which you cannot "smooth out all the kinks" (i.e. not diffeomorphic) in a way (it is never good too replace the mathematical definitions by "Kindergarten language", but from a distance, this is not far from the truth).
I have also read somewhere that an exotic sphere has a different smooth structure than your regular $(S^n, id)$. So my question is:
Consider an exotic copy $(\Sigma^n, \phi)$ of $(S^n, id)$. Is $(\Sigma^n, \phi)$ a smooth manifold by its own, or is it just a topological copy of it ?
Comment: What does "by its own" mean here? As far as I understand, exotic spheres _are_ smooth.
Answer: The very first time an exotic sphere was built was by Milnor, and he defined them as total spaces of $\Bbb S^3$-bundles over $\Bbb S^4$. From this angle, it does not quite look like he started from $\Bbb S^7$ and did something to the smooth structure.
Historical considerations apart, I can see no reason not to consider an exotic sphere as a smooth manifold in its own right.

On the nature of exotic spheres


Pagination jTable in PHP

Question: How to use paging in jTable use PHP?
I have code below in employeeTable.php

    //Get record count
    $result = mysql_query("SELECT COUNT(*) AS RecordCount FROM employee;");
    $row = mysql_fetch_array($result);
    $recordCount = $row['RecordCount'];

    //Get records from database
    $result = mysql_query("SELECT * FROM employee ORDER BY '" . $_REQUEST["jtSorting"] . "' LIMIT '" . $_REQUEST["jtStartIndex"] . "','" . $_REQUEST["jtPageSize"] . "';");

    //Add all records to an array
    $rows = array();
    while($row = mysql_fetch_array($result))
    {
        $rows[] = $row;
    }

    //Return result to jTable
    $jTableResult = array();
    $jTableResult['Result'] = "OK";
    $jTableResult['TotalRecordCount'] = $recordCount;
    $jTableResult['Records'] = $rows;
    print json_encode($jTableResult);

Then I realize the problem is in here
$result = mysql_query("SELECT * FROM employee ORDER BY '" . $_REQUEST["jtSorting"] . "' LIMIT '" . $_REQUEST["jtStartIndex"] . "','" . $_REQUEST["jtPageSize"] . "';");

if I change $_REQUEST["jtSorting"] = rowname, $_REQUEST["jtStartIndex"] = number, $_REQUEST["jtPageSize"] = number, it works.
But if I don't change it, it shows 'An Error Occured While Communicating to the server'.
here is the code in jquery.jtable.min.js, when there are line about jtSorting, jtStartIndex, jtPageSize
/* Adds jtSorting parameter to a URL as query string.
    *************************************************************************/
    _addSortingInfoToUrl: function (url) {
        if (!this.options.sorting || this._lastSorting.length == 0) {
            return url;
        }

        var sorting = [];
        $.each(this._lastSorting, function (idx, value) {
            sorting.push(value.fieldName + ' ' + value.sortOrder);
        });

        return (url + (url.indexOf('?') < 0 ? '?' : '&') + 'jtSorting=' + sorting.join(","));
    },

    /* Overrides _createJtParamsForLoading method to add sorging parameters to jtParams object.
    *************************************************************************/
    _createJtParamsForLoading: function () {
        var jtParams = base._createJtParamsForLoading.apply(this, arguments);

        if (this.options.sorting && this._lastSorting.length) {
            var sorting = [];
            $.each(this._lastSorting, function (idx, value) {
                sorting.push(value.fieldName + ' ' + value.sortOrder);
            });

            jtParams.jtSorting = sorting.join(",");
        }

        return jtParams;
    }

});
})(jQuery);

Can anybody please help me understand?
Answer: I think you should go through this once.
Listaction jtable for Pagination and sorting table
It would require jQuery.Deferred to return data.
Handle it as
listAction: function (postData, jtParams) {
    return $.Deferred(function ($dfd) {
        $.ajax({
            url: '/Employee_Controller/EmployeeList_method?jtStartIndex=' + jtParams.jtStartIndex + '&jtPageSize=' + jtParams.jtPageSize + '&jtSorting=' + jtParams.jtSorting,
            type: 'POST',
            dataType: 'json',
            data: postData,
            success: function (data) {
                $dfd.resolve(data);
            },
            error: function () {
                $dfd.reject();
            }
        });
    });
}

Manually post values for it. I hope this maybe helpful.
Answer: the options will be received in $_GET object
like:
$jtStartIndex=$_GET['jtStartIndex'];
$jtPageSize=$_GET['jtPageSize'];
$jtSorting=$_GET['jtSorting'];

example:
$query="select * FROM products ORDER BY $jtSorting LIMIT $jtStartIndex, $jtPageSize;";

and in jtable settings:
paging: true, //Enable paging
pageSize: 10, //Set page size (default: 10)
sorting: true, //Enable sorting
defaultSorting: 'name ASC' ,
            actions: {
                listAction: 'data/products.php'//Set default sorting
            },
...

Pagination jTable in PHP


magento getOptionId not working for some labels

Question: I'm using the below code to get the option id for attribute set "size".
It is returning correct id if I use option label greater than 9 (i.e, 10,12,13,14 ..)
But is not working if use option label less than 10 (i.e, 5,6,7,8,9).
$attr = 'size';
$attribute_label = 13;
$_product = Mage::getModel('catalog/product');
$attribute_name = $_product->getResource()->getAttribute($attribute_name);

if ($attr->usesSource()) {
    echo $color_id = $attribute_name->getSource()-  >getOptionId($attribute_label);
}

Example:

Output when I use option label ($attribute_label = 13)  as 13 it
  returns 5.
Output when I use option label ($attribute_label = 6)  as 6 it returns
  6.
Comment: You can try below post http://magentorex.com/magento-get-product-attributes-option-id-from-option-label/
Answer: This happens because getOptionId() does not work well with numeric labels, as stated also in this question: https://magento.stackexchange.com/questions/128445/getoptionid-method-returns-invalid-option-id
What you can do is to avoid using this method and adjust your code something like:
$attribute_name = 'size';
$attribute_label = 13;
$optionId = false;
$attr = Mage::getResourceModel('catalog/product')->getAttribute($attribute_name);
if ($attr->usesSource()) {
    $options = $attr->getSource()->getAllOptions();
    foreach($options as $option) {
        if($option['label'] == $attribute_label) {
            $optionId = $option['value'];
            break;
        }
    }
}


How do I fix the error given from "drush en nodejs -y"?

Question: When I run drush en nodejs -y, I get this error.

In PmCommands.php line 247: Unable to install modules nodejs due to missing modules nodejs.

How do I fix that error?
I am using Drush 10.2.2 and Composer 1.10.9.
Answer: drush en doesn't download the modules anymore. That must be done with Composer.
composer require drupal/nodejs
drush en nodejs -y

If composer require drupal/nodejs was executed, the module could have been saved in the wrong directory, for example in the vendor directory.
In that case, I would check the composer.json file to verify it doesn't instruct Composer to install the modules in the wrong directory. In composer.json there should be a line similar to the following one, under installer-paths.
"modules/contrib/{$name}": ["type:drupal-module"]

If the *composer.json file contains lines similar to the following lines, check that web-root is using the correct web root directory. (Some servers could use public_html instead of web.)
"drupal-scaffold": {
    "locations": {
        "web-root": "web/"
    }
}


Silverlight : alternatives for sending a List as an argument for a WCF RIA DomainService method

Question: I want to create a DomainService method that receives a List (where T: Entity) kind of an argument, but it seems this cannot be done in Silverlight (Error message : "operation ... does not conform to the required signature. Parameter types must be an entity or complex type, a collection of complex types, or one of the predefined serializable types.")
What are the alternatives?
Thank you.
Answer: Just pass a T[] array, it should fix it and it is more "proper" as there's no reason to add elements to the list.
Comment: Still gives me the same _"operation ... does not conform to the required signature"_ error.
Answer: Serialize the List<T> to a string in the client and then deserialize it on the server.
I did this with the DataContractSerializer and it works great.
WCF RIA Services Contrib also has the ability to Import and Export a collection of entities with added benefits.
http://riaservicescontrib.codeplex.com


Drupal 7 field for expandable list

Question: I'm looking for a module that provides a D7 field type that's an expandable list: a list where new values can be added at run-time. Is there a module for that?
Comment: Do you want the new values added to be available to other user's also ?
Answer: Ended up using a taxonomy term reference with a tag widget.

Drupal 7 field for expandable list


Detecting menu button being pressed a second time

Question: I am wanting a certain flag in my code to be set when a menu is on screen. I tried catching the keyCode == KeyEvent.KEYCODE_MENU event in onKeyDown to detect when the menu would appear - but then if the menu button is pressed a second time (making the menu disappear), there is no keyCode == KeyEvent.KEYCODE_MENU event.
Should I look for some other event, or is there a function to test if some kind of menu is on display?
Comment: Check my answer how easy to detect home,recent and power button. Check [this](http://stackoverflow.com/a/29648460/1071545)
Answer: To catch the menu being opened, you can override
public boolean onPrepareOptionsMenu(Menu menu)

To catch the menu being closed, you can override
public void onOptionsMenuClosed(Menu menu)

However keep in mind that the second one will be called both when the user presses "menu" button the second time or taps one of the menu options.  Therefore you'll need to use it in combination with
public boolean onOptionsItemSelected(MenuItem item)

Comment: @ArslanAhmad Care to explain why believe this answer is wrong?  It worked perfectly well two years ago when the question was asked - and it still works well.
Comment: Not working in my case.please refer this http://stackoverflow.com/questions/15652444/not-able-to-dismiss-the-alertdialog-when-pressing-menu-key-second-time
Comment: I am lilterally very disapointed why ppl gave marked answer to the actual wrong answer.
Comment: @AleksG I have tried this 1000s time even my friends and coleagues but this method doesnot detect the Home , Recent Apps button. If you think it works give me the sample code If it runs i will give you 5 + votes from my friends
Comment: @ArslanAhmad Of course it does not.  The question was specifically about the menu button - and so was the answer.


The "state" param from the URL and session do not match when leaving browser open too long

Question: Im getting this error when leaving my browser window open for an extended amount of time say 3 hours , then trying to log in to my site through Facebook using Facebook sdk:
Facebook sdk error : Cross-site request forgery validation failed. The "state" param from the URL and session do not match
Im using laravel 5.3 , if i open a new window then try to log in everything works fine.
I know it has something to do with sessions.
I want it so that if that error appears all a user has to do is refresh the page and then they can login using Facebook.
the problem is if a user logs in using Facebook , they get redirected to mysite/facebookcallback , then on refresh its again my site/facebookcallback and the same error appears .
i'm assuming some how i need to create a new session , in the case a user leaves there browser window open for say 3 hours then tries to log in using Facebook
a new session gets created thus avoiding the error, but i only need to do that if the session is old.
heres a portion of the code I'm using
try {
    $token = $fb->getAccessTokenFromRedirect($redirectURL);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
    dd($e->getMessage());
}

// Access token will be null if the user denied the request
// or if someone just hit this URL outside of the OAuth flow.
if (! $token) {
    // Get the redirect helper
    $helper = $fb->getRedirectLoginHelper();

    if (! $helper->getError()) {
        abort(403, 'Unauthorized action.');
    }

the getRedirectLoginHelper() is as follows
protected function validateCsrf()
{
    $state = $this->getState();
    if (!$state) {
        throw new FacebookSDKException('Cross-site request forgery validation failed. Required GET param "state" missing.');
    }
    $savedState = $this->persistentDataHandler->get('state');
    if (!$savedState) {
        throw new FacebookSDKException('Cross-site request forgery validation failed. Required param "state" missing from persistent data.');
    }

    if (\hash_equals($savedState, $state)) {
        return;
    }

    throw new FacebookSDKException('Cross-site request forgery validation failed. The "state" param from the URL and session do not match.');
}

you can see the error message Cross-site request forgery validation failed. The "state" param from the URL and session do not match
I don't want to touch the getRedirectLoginHelper code because thats from Facebook's sdk
I need to come up with a fix before it get that far
Comment: Redirect them away from your callback URL somewhere else once you got the access token, so that when they then refresh the page they refresh something else, so that your app does not try to perform that step again.
Answer: Kai is right. It has to do with the session expiring. To expand a bit further.
The Problem
Say you generate a login URL and display it on your site somewhere:
$fb = new \Facebook\Facebook([
  'app_id' => '{app-id}',
  'app_secret' => '{app-secret}',
  'default_graph_version' => 'v2.10',
  ]);

$helper = $fb->getRedirectLoginHelper();

$loginUrl = $helper->getLoginUrl('https://example.com/fb-callback.php');

echo 'Log in with Facebook!';

The URL that gets generated contains a state param. Behind the scenes getRedirectLoginHelper() will store the value of state in a session.
Say your session expires in 20 minutes and someone loads the page with a Facebook login URL. They wait 21 minutes and then click on the login button. By that time the session will be blank so the state value will be missing. The user will be asked to authorize the app, then when they are redirected back to your callback URL with the original state param appended to it, the getAccessTokenFromRedirect() method will try to compare the state param in the callback URL with the session. Since the session expired, it will cause that error.
The Solution
When I add a "Log in with Facebook" button to my site, I have it point to an endpoint that I own. Say /facebook/login for example. On that endpoint, I invoke the getLoginUrl() method and automatically redirect the user.
So somewhere on my page I have:
Log in with Facebook

Then on the /facebook/login endpoint I have:
$fb = new \Facebook\Facebook([
  'app_id' => '{app-id}',
  'app_secret' => '{app-secret}',
  'default_graph_version' => 'v2.10',
  ]);

$helper = $fb->getRedirectLoginHelper();

$loginUrl = $helper->getLoginUrl('https://example.com/fb-callback.php');
header('Location: ' . $loginUrl);
exit;

That way you're saving the state the moment they click on the link instead of the moment the page loads. Now if they take 21 minutes to authorize the app, you'll still get the error above, but that's way less likely than someone just leaving your page open for a long time. :)
Comment: the solution works but still has a bug , now the error i get is Cross-site request forgery validation failed. Required param "state" missing , this happens when the window is left open for en extended time
Answer: Facebook's API is using the Synchronizer Token Pattern here for CSRF prevention. The session is expiring after a certain period of time. As this is happening on their servers, there's not much you can do. It's intentional.

The “state” param from the URL and session do not match when leaving browser open too long


what is the foundation of a chord progression

Question: I know that the root note is the foundation of a chord.
What is the foundation of a chord progression?
Comment: Is this a term you've read somewhere?
Answer: There are a few possibilities.
Matviy Kotoniy's answer has already mentioned

The tonic chord
the scale used to write the piece

as things that a chord progression could be said to be 'founded' or 'based' on.
Another angle would be to say that chord is to root note as chord progression is to a series of successive root notes (i.e. of the chords in the progression).
In many genres of music, these 'successive root notes' would be rendered as a bassline - and indeed, the idea that the bassline is the foundation of a chord progression would make sense to musicians in those genres.
Comment: Tonic and scale are necessary, but - regarding the question about foundations of chord progressions - they don't tell you where to go afaik. Correct me if i'm wrong but couldn't cadence traditions be added to the list of foundations?
Comment: @Erik I guess the 'problem' with the question is that 'foundation' doesn't have a particular meaning in music theory so one could make a case for lots of things being the foundation of a progression - cadence traditions definitely, but also instrumental timbres, instrument topography, emotions, and anything else that might inspire the composition...
Comment: bassline=sequence of root notes=the verticle approach of stripping down the chord progression to its foundation
Answer: The closest thing to a "foundation" for a chord progression would be the scale that the progression is based on, or the Tonic "tonal center" chord of the progression.
The scale is what determines which actual notes become part of the chords of your progression and thus the function each chord in the progression.
The Tonic "tonal center" chord would be the harmonic foundation around which the harmony of the chord progression revolves around, and can eventually resolve back to.
Comment: What about progressions that AREN'T all in one key, one scale?  This is very common.
Comment: scale=a group of notes=provides the notes that can be used to build a chord(vertically) or a sequence of notes/chords(horizontaly)
Answer: The root Chord (the I Chord) is the chord that the other chords in the progression act in relation too. It is usually the first chord in the progression and usually the one that the progression resolves back to at
the end of the progression. This is the chord that the progression is built upon.
Comment: the tonic=first scale degree=the horizontal approach of stripping down the chord progression to its foundation
Answer: The foundation of a chord progression (as I like to consider it) lies within the relationships among the chords used. Among those are things like the cycle of fifths (or fourths) used in root motion or having a scale wise descending bassline (like in Pachelbel's Canon). The use (or failure to use) of certain patterns tells a lot about harmonic structure.
There are some common chord progressions (Twelve Bar Blues, Folia, Passamezzo Antico, Passamezzo Moderno, Romanesca, etc.) which provide a common framework. Use of one of these or modifications thereof explains about how the chords work together musically. They emotional or psychological effect of a progression generally depends on other factors. Compare "St James Infirmary" to "Rock Around the Clock."