How to make qtip2 respond to dynamic user input

Question: I have the following working code. It takes the input data and display the histogram based on a threshold.

"use strict";

var histograms,
  thresholds = [];

var input_data = [{
  "threshold": 1.5,
  "histograms": [{
    "sample": "Sample1",
    "values": [{
      "score": 6.7530200000000002,
      "celltype": "Bcells"
    }, {
      "score": 11.432763461538459,
      "celltype": "DendriticCells"
    }, {
      "score": 25.823089615384621,
      "celltype": "Macrophages"
    }, {
      "score": 9.9911211538461551,
      "celltype": "gdTCells"
    }, {
      "score": 7.817228076923076,
      "celltype": "StemCells"
    }, {
      "score": 17.482806923076922,
      "celltype": "StromalCells"
    }, {
      "score": 29.335427692307697,
      "celltype": "Monocytes"
    }, {
      "score": 28.914959615384621,
      "celltype": "Neutrophils"
    }, {
      "score": 13.818888461538467,
      "celltype": "NKCells"
    }, {
      "score": 9.5030688461538464,
      "celltype": "abTcells"
    }]
  }]
}, {
  "threshold": 2,
  "histograms": [{
    "sample": "Sample1",
    "values": [{
      "score": 5.1335499999999996,
      "celltype": "Bcells"
    }, {
      "score": 16.076072499999999,
      "celltype": "DendriticCells"
    }, {
      "score": 46.182032499999998,
      "celltype": "Macrophages"
    }, {
      "score": 6.5895700000000001,
      "celltype": "gdTCells"
    }, {
      "score": 5.3218800000000002,
      "celltype": "StemCells"
    }, {
      "score": 53.643625,
      "celltype": "StromalCells"
    }, {
      "score": 85.1618225,
      "celltype": "Monocytes"
    }, {
      "score": 55.559129999999996,
      "celltype": "Neutrophils"
    }, {
      "score": 7.6717524999999984,
      "celltype": "NKCells"
    }, {
      "score": 6.3277800000000006,
      "celltype": "abTcells"
    }]
  }]
}];

processData(input_data);

function processData(data) {
  histograms = data[0].histograms.map(function(data) {
    return {
      title: data.sample,
      dataset: new Plottable.Dataset(),
      dataByThreshold: {},
      load: function(threshold) {
        this.dataset.data(this.dataByThreshold[threshold]);
      }
    };
  });

  data.forEach(function(data) {
    var threshold = data.threshold;
    thresholds.push(threshold);
    data.histograms.forEach(function(histogram, i) {
      histograms[i].dataByThreshold[threshold] = histogram.values;
    });
  });

  // Here we generalize the slide bar maximum threshold
  $('#threshold').attr('max', thresholds.length - 1);
  updateDatasets(thresholds[0]);
  buildPlots();
  updateThreshold();

}

$('#threshold').change(updateThreshold);

function updateThreshold() {

  // This is where the user input updating slider
  // takes place and where the QTIP is in action.

  var thresholdIndex = parseInt($('#threshold').val(), 10);
  $("#foldchange_threshold").html(thresholds[thresholdIndex]);
  updateDatasets(thresholds[thresholdIndex]);
  $(".tooltipped rect").qtip({
    overwrite: true,
    position: {
      my: "bottom middle",
      at: "top middle"
    },
    style: {
      classes: "qtip-light"
    }
  });
}

function updateDatasets(threshold) {
  histograms.forEach(function(histogram) {
    histogram.load(threshold);
  });
}

function buildPlots() {
  var $histogramContainer = $('#sample-histograms');

  histograms.forEach(function(histogram, index) {
    var elementId = "sample-histogram-" + index;

    $(document.createElementNS('http://www.w3.org/2000/svg', 'svg'))
      .css({
        width: '200px',
        height: '200px',
        display: 'inline-block'
      })
      .attr('id', elementId)
      .appendTo($histogramContainer);

    plotSampleHistogram(histogram.title, histogram.dataset, '#' + elementId);
  });

}

function plotSampleHistogram(title, dataset, targetElement) {
  var xScale = new Plottable.Scales.Category(),
    yScale = new Plottable.Scales.Linear(),
    colorScale = new Plottable.Scales.Color();

    var xAxis = new Plottable.Axes.Numeric(xScale, "bottom"),
        yAxis = new Plottable.Axes.Numeric(yScale, "left"),
        titleLabel = new Plottable.Components.TitleLabel(title);

    yScale.domainMin(0);

    var plot = new Plottable.Plots.Bar()
      .addDataset(dataset)
      .x(function(d) { return d.celltype; }, xScale)
      .y(function(d) { return d.score; }, yScale)
      .attr("fill", function(d) { return d.celltype; }, colorScale)
      .attr("title", function(d) { return '
' + d.celltype + " (" + d.score.toFixed(2) + ')
'; })
      .addClass("tooltipped");

    new Plottable.Components.Table([
        [null, titleLabel],
        [yAxis, plot],
        [null, xAxis]
    ]).renderTo(targetElement);
}

function drawHistogramLegend(targetElement) {
    new Plottable.Components.Legend(colorScale)
        .renderTo(targetElement);
}

  <link href="https://cdnjs.cloudflare.com/ajax/libs/plottable.js/1.15.0/plottable.css" rel="stylesheet" />
  <link href="https://cdnjs.cloudflare.com/ajax/libs/qtip2/2.2.1/basic/jquery.qtip.css" rel="stylesheet" />

  <input id="threshold" type="range" min="0" max="1" step="1" value="0" />

If you run the code you can notice that the histogram will change as you drag the slider. AND a tool tip will appear if you place your mouse in one of the histogram bar.
The problem I'm facing is that the value of the tool tip does not change upon the user input to the sliding bar. For example with threshold=1.5 the Bcell score is 6.75 and threshold=2, the score is 5.13. This is not reflected in the tool tip.
How can resolve this issue?
Answer: It looks like QTip2 modifies the "title" attribute in some way, cacheing the previous information under "oldtitle". I got it to work by switching the title to a different attribute:

plot.attr("qtip2-title", function(d) {
  return '
' + d.celltype + " (" + d.score.toFixed(2) + ')
';
});

Then, we tell QTip2 to look up the "qtip2-title" property for the tooltip text:
$(".tooltipped .content rect").qtip({

  // ... other setup here...

  content: {
    text: function() {
      return $(this).attr("qtip2-title");
    }
  }
});

(Note the use of .content to avoid selecting unwanted rectangles).
Also, I noticed that currently xAxis is an Axes.Numeric, which will not work with Scales.Category. Use Axes.Category instead.

"use strict";

var histograms,
  thresholds = [];

var input_data = [{
  "threshold": 1.5,
  "histograms": [{
    "sample": "Sample1",
    "values": [{
      "score": 6.7530200000000002,
      "celltype": "Bcells"
    }, {
      "score": 11.432763461538459,
      "celltype": "DendriticCells"
    }, {
      "score": 25.823089615384621,
      "celltype": "Macrophages"
    }, {
      "score": 9.9911211538461551,
      "celltype": "gdTCells"
    }, {
      "score": 7.817228076923076,
      "celltype": "StemCells"
    }, {
      "score": 17.482806923076922,
      "celltype": "StromalCells"
    }, {
      "score": 29.335427692307697,
      "celltype": "Monocytes"
    }, {
      "score": 28.914959615384621,
      "celltype": "Neutrophils"
    }, {
      "score": 13.818888461538467,
      "celltype": "NKCells"
    }, {
      "score": 9.5030688461538464,
      "celltype": "abTcells"
    }]
  }]
}, {
  "threshold": 2,
  "histograms": [{
    "sample": "Sample1",
    "values": [{
      "score": 5.1335499999999996,
      "celltype": "Bcells"
    }, {
      "score": 16.076072499999999,
      "celltype": "DendriticCells"
    }, {
      "score": 46.182032499999998,
      "celltype": "Macrophages"
    }, {
      "score": 6.5895700000000001,
      "celltype": "gdTCells"
    }, {
      "score": 5.3218800000000002,
      "celltype": "StemCells"
    }, {
      "score": 53.643625,
      "celltype": "StromalCells"
    }, {
      "score": 85.1618225,
      "celltype": "Monocytes"
    }, {
      "score": 55.559129999999996,
      "celltype": "Neutrophils"
    }, {
      "score": 7.6717524999999984,
      "celltype": "NKCells"
    }, {
      "score": 6.3277800000000006,
      "celltype": "abTcells"
    }]
  }]
}];

processData(input_data);

function processData(data) {
  histograms = data[0].histograms.map(function(data) {
    return {
      title: data.sample,
      dataset: new Plottable.Dataset(),
      dataByThreshold: {},
      load: function(threshold) {
        this.dataset.data(this.dataByThreshold[threshold]);
      }
    };
  });

  data.forEach(function(data) {
    var threshold = data.threshold;
    thresholds.push(threshold);
    data.histograms.forEach(function(histogram, i) {
      histograms[i].dataByThreshold[threshold] = histogram.values;
    });
  });

  // Here we generalize the slide bar maximum threshold
  $('#threshold').attr('max', thresholds.length - 1);
  updateDatasets(thresholds[0]);
  buildPlots();
  updateThreshold();

}

$('#threshold').change(updateThreshold);

function updateThreshold() {

  // This is where the user input updating slider
  // takes place and where the QTIP is in action.

  var thresholdIndex = parseInt($('#threshold').val(), 10);
  $("#foldchange_threshold").html(thresholds[thresholdIndex]);
  updateDatasets(thresholds[thresholdIndex]);
  $(".tooltipped .content rect").qtip({
    overwrite: true,
    position: {
      my: "bottom middle",
      at: "top middle"
    },
    style: {
      classes: "qtip-light"
    },
    content: {
      text: function() {
        return $(this).attr("qtip2-title");
      }
    }
  });
}

function updateDatasets(threshold) {
  histograms.forEach(function(histogram) {
    histogram.load(threshold);
  });
}

function buildPlots() {
  var $histogramContainer = $('#sample-histograms');

  histograms.forEach(function(histogram, index) {
    var elementId = "sample-histogram-" + index;

    $(document.createElementNS('http://www.w3.org/2000/svg', 'svg'))
      .css({
        width: '200px',
        height: '200px',
        display: 'inline-block'
      })
      .attr('id', elementId)
      .appendTo($histogramContainer);

    plotSampleHistogram(histogram.title, histogram.dataset, '#' + elementId);
  });

}

function plotSampleHistogram(title, dataset, targetElement) {
  var xScale = new Plottable.Scales.Category(),
    yScale = new Plottable.Scales.Linear(),
    colorScale = new Plottable.Scales.Color();

    var xAxis = new Plottable.Axes.Category(xScale, "bottom"),
        yAxis = new Plottable.Axes.Numeric(yScale, "left"),
        titleLabel = new Plottable.Components.TitleLabel(title);

    xAxis.tickLabelAngle(-90)
    yScale.domainMin(0);

    var plot = new Plottable.Plots.Bar()
      .addDataset(dataset)
      .x(function(d) { return d.celltype; }, xScale)
      .y(function(d) { return d.score; }, yScale)
      .attr("fill", function(d) { return d.celltype; }, colorScale)
      .attr("qtip2-title", function(d) { return '
' + d.celltype + " (" + d.score.toFixed(2) + ')
'; })
      .addClass("tooltipped");

    new Plottable.Components.Table([
        [null, titleLabel],
        [yAxis, plot],
        [null, xAxis]
    ]).renderTo(targetElement);
}

function drawHistogramLegend(targetElement) {
    new Plottable.Components.Legend(colorScale)
        .renderTo(targetElement);
}

  <link href="https://cdnjs.cloudflare.com/ajax/libs/plottable.js/1.15.0/plottable.css" rel="stylesheet" />
  <link href="https://cdnjs.cloudflare.com/ajax/libs/qtip2/2.2.1/basic/jquery.qtip.css" rel="stylesheet" />

  <input id="threshold" type="range" min="0" max="1" step="1" value="0" />

Hopefully this works for you! Glad to see you're using Plottable.
P.S. We're working on getting a more detailed tooltip tutorial for the website. Stay tuned.
Comment: `xAxis.tickLabelAngle(90)`, or the same with `-90`. Other angles aren't supported yet.
Comment: Thanks. I tried it but didn't work. Would you mind putting the full runnable code in [**StackSnippet**](http://meta.stackoverflow.com/questions/269753/feedback-requested-runnable-code-snippets-in-questions-and-answers) --  you can do that by simply click on **Copy snippet to answer** on my post -- or [**CodePen**](http://codepen.io/pen/).
Comment: thanks. Regarding the `x-axis` how can you rotate the text? Now it looks very squeezy.
Comment: Do you mind take a look at this? http://stackoverflow.com/questions/34588069/how-to-make-labels-in-histogram-respond-to-dynamic-user-input-under-plottable-js


Modal não está dando scroll

Question:     CSS:
.modalDialog {
        position: fixed;
        font-family: Arial, Helvetica, sans-serif;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        background: rgba(0, 0, 0, 0.8);
        z-index: 99999;
        opacity:0;
        -webkit-transition: opacity 400ms ease-in;
        -moz-transition: opacity 400ms ease-in;
        transition: opacity 400ms ease-in;
        pointer-events: none;
    }
    .modalDialog:target {
        opacity:1;
        pointer-events: auto;
    }
    .modalDialog > div {
        width: 400px;
        position: relative;
        margin: 10% auto;
        padding: 5px 20px 13px 20px;
        border-radius: 10px;
        background: #fff;
        background: -moz-linear-gradient(#fff, #999);
        background: -webkit-linear-gradient(#fff, #999);
        background: -o-linear-gradient(#fff, #999);
    }
    .close {
        background: #606061;
        color: #FFFFFF;
        line-height: 25px;
        position: absolute;
        right: -12px;
        text-align: center;
        top: -10px;
        width: 24px;
        text-decoration: none;
        font-weight: bold;
        -webkit-border-radius: 12px;
        -moz-border-radius: 12px;
        border-radius: 12px;
        -moz-box-shadow: 1px 1px 3px #000;
        -webkit-box-shadow: 1px 1px 3px #000;
        box-shadow: 1px 1px 3px #000;
    }
    .close:hover {
        background: #00d9ff;
    }

Tentei colocar esse código embaixo no .modalDialog > div porém ele fica meio desformatado. Teria alguma maneira de fazer o scroll e não mostrar a barra de rolagem?

max-height: calc(100vh - 210px);
overflow-y: auto;

Veja o exemplo no jsFiddle:
http://jsfiddle.net/GG9Sa/4067/
Answer:
.modalDialog {
/*Insira o código debaixo de tudo*/
overflow: scroll;
}

Vê se da ai!
Comment: Nossa algo tão simples, obrigado cara. já te dou upvote tem que esperar uns 10 minutos.
Comment: Mas a minha ideia seria fazer o scroll no próprio modal entendeu?
Comment: Mas solucionou o problema ? @Marcel
Comment: Sim, mas eu gostaria de fazer de outro jeito onde o scroll ocorra no próprio modal. Sem dar scroll na página inteira entendeu?
Comment: @MarceloT.Cortes coloca um height no .modalDialog > div não uso o JsFiddle mas tenta ai para ver se alterou alguma coisa http://jsfiddle.net/GG9Sa/4071/
Comment: Blz valeu cara já ajudou bastante o resto eu me viro aqui.
Answer:
Sim, mas eu gostaria de fazer de outro jeito onde o scroll ocorra no próprio modal. Sem dar scroll na página inteira entendeu?

Encontrei a seguinte solução que resolve esse problema:
HTML: (Ignora o Blade)

Selecione o Item que deseja Encaminhar para a Saida

        <button id="close-modal" class="btn btn-danger">Fechar</button>

                Nome
                Quantidade
                Marca
                Ações

                @foreach($materials as $material)

                      {{ $material->nome }}
                      {{ $material->quantidade }}
                      {{ $material->marca }}
                      Encaminhar

                @endforeach

CSS:
#fade {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.6);
    z-index: 5;
  }

  #modal {
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 1000px;
    max-width: 90%;
    background-color: #fff;
    padding: 1.2rem;
    border-radius: 0.5rem;
    z-index: 10;
    height: 100%;
    overflow: scroll;
  }

  #fade,
  #modal {
    transition: 0.5s;
    opacity: 1;
    pointer-events: all;
  }

  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #ccc;
    margin-bottom: 1rem;
    padding-bottom: 1rem;
  }

  .modal-body p {
    margin-bottom: 1rem;
  }

  #modal.hide,
  #fade.hide {
    opacity: 0;
    pointer-events: none;
  }

  #modal.hide {
    top: 0;
  }

JavaScript:
const openModalButton = document.querySelector("#open-modal");
const closeModalButton = document.querySelector("#close-modal");
const modal = document.querySelector("#modal");
const fade = document.querySelector("#fade");

const toggleModal = () => {
  modal.classList.toggle("hide");
  fade.classList.toggle("hide");
};

[openModalButton, closeModalButton, fade].forEach((el) => {
  el.addEventListener("click", () => toggleModal());
});

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

Modal não está dando scroll


How many right angled triangles can a circle have?

Question: Here's what I recall of the question from CNML Grade 11, 2010/2011 Contest #3, Question 7:

There are 2010 points on a circle,
  evenly spaced. Ford Prefect will*
  randomly choose three points on the
  circle. He will* connect these points
  to form a shape. What is the
  probability that the resulting shape
  will* form a right angled triangle?

I answered $\frac{1}{4} = 25\%$, but that's probably incorrect. (Right?)
When I got home, I thought it out in my head, and I got this:
$\frac{2010 * (2010/1005)}{2010 \choose 3}$
$\frac{2020050}{1351414120} = \frac{3015}{2017036} = 0.149476756984010201\%$
I'm probably wrong ...again. Can anyone tell how to get the right answer (if I'm not wrong :) )?
*in the past of the future of the perfect present present time double into ripple fluctuater byer doininger of the past future continuum...
EDIT: Realized my mistake in copying the question.
Comment: @muntoo: See this http://en.wikipedia.org/wiki/Thales'_theorem
Comment: But muntoo...If you're using the past present pluperfect continuous tense, WTF is Ford Prefect doing in the year 2010? WTF is he doing here anyway?
Comment: @TonyK: but does the fact that we can actually construct a right triangle in a circle contradict that? Or is it one of those thing where the probability is 0, but it's possible?
Comment: @muntoo: I am not sure what you mean. The only way to inscribe a triangle in a circle is by having two vertices diametrically opposite.
Comment: it seems to me that probability is infinitely close to 0, as there are uncountably many points on the circle, though I am probably wrong, too. :)
Comment: Note that the triangle being a right triangle constrains it to being within a semicircle. Use that.
Comment: @J.M. Yeah, I used that for the $(2010 / 1005)$ part
Comment: The probability is zero (not just 'infintely close to zero'). Check the question again - are you sure you copied it right?
Comment: This is the same probability as choosing two diametrically opposite points of the three, since then the third point can be anywhere and it will be a right angled triangle and this probability is zero.
Comment: @TonyK Pretty sure I interpreted it correctly. Can't say what the exact question was - I don't have the test with me.
Comment: @Timothy what about points at angles $0$, $\frac{\pi}{2}$ and $\pi$?
Comment: @TonyK Oops, I realized I forgot to put in the "2010" part. I showed it in my work, but not the question. :)
Comment: @Timothy 1) 0 to pi is a diameter, if you connect the two points. 2) What about chords?
Comment: that makes it solvable :)
Comment: @Timothy I just realized. All those triangles I've conjured in my mind all had diameters...
Comment: @muntoo: You have modified the question now, so the answer changes. Do you see how to do it now?
Comment: @Timothy Yup. :) But are there any right angled triangles that don't have diameters? Is there a way to prove that there aren't?
Comment: @muntoo: No there aren't. This is the converse of Thales theorem. Please scroll down in the wiki link I posted earlier.
Comment: @TonyK As I perfectly did not said, he isn't in the past not doing the future of waited for something to come up on his Sub-Etha Sens-O-Matic.
Answer: Let the points be $P_1$, $P_2$, and $P_3$.  Letting $P_1$ be arbitrary, we win if $P_2$ is the point diametrically opposite to $P_1$, probability $1/2009$.  Otherwise, with probability $2008/2009$, we still win if $P_3$ is diametrically opposite either $P_1$ or $P_2$, which it is with probability $2/2008$.  So the probability of a win is $1/2009 + (2008/2009)(2/2008) = 3/2009$.
You can also get this as follows:  The number of possible wins is the number of diameters times the number of remaining points, or 1005*2008. The number of possible triples is $2010\choose 3$. Dividing the first by the second gives $3/2009$.
Even easier:  The probability that a given pair of points lie on a diameter is $1/2009$.  With three points, you have three pairs, hence $3/2009$.  Here it's OK to add probabilities because it's not possible to have overlap; if one of the pairs lies on a diameter, no other pair can lie on a diameter.
BTW, I do not agree with the comment thread that says we must consider the possibility that the points are not distinct.  Sometimes there can be an ambiguity, but in common language "choose three points from 2010 points" means "without replacement".  For example, I am not incorrect in saying that $n\choose r$ is the number of ways of choosing $r$ objects out of a set of $n$.  Although I admit that if I were grading the test and this issue were pointed out to me, I might accept the "with replacement" answer as well.
The only other alternative answer I might accept is 1, i.e., that the points are certain to lie on a right triangle.  After all, it is Ford Prefect, so I have no way of knowing whether the Infinite Improbability Drive has been activated.
Comment: "I have no way of knowing whether the Infinite Improbability Drive has been activated." - I've already given this answer a +1 before you wrote that, and it's a shame I can't give another...
Comment: To be exact, Ford was trying to come up with the probability that Arthur's cup of not entirely unlike tea will entirely become tea when he would know whether the Improbability Drive would have been activated or not.
Comment: I'm pretty sure that the problem meant "choose different points", but it wasn't "clearly" said.
Answer: Hint: You can choose $3$ points in ${2010}\choose {3}$ ways. To form a right angled triangle, we need to choose a pair of diametrically opposite points (how many ways to do this?) and then any third point will form a right angled triangle with the chosen pair.
Comment: You have to be a bit careful: firstly, the problem didn't specify that the random points have to be distinct, so there are $2010^3$ ways of choosing those. Secondly, that doesn't quite give you the number of ways of _choosing_ the points.
Comment: @Alex: I agree with your first point, I assumed $3$ distinct points were chosen. I am not sure about your second: you can choose a pair of diametrically opposite points in 1050 ways and then choose any other point in 2008 ways. So you can form a right angled triangle with 3 distinct points in $2008\times 1050$ ways. I suppose I interpreted this question to mean how many right angles triangle can be formed using any three distinct of these $2010$ points without regards to the order in which they were chosen.
Comment: You calculate the number of triangles correctly, but not the number of ways of choosing a triangle. As you say, the order in which the points were chosen doesn't matter. There are 6 possible orders in which the points of a triangle can be chosen, so you have to multiply by those, if you want an honest probability.
Comment: @Alex: Perhaps I am having a brain freeze here, but if you account for the order in which the points were chosen, wouldn't you multiply both the numerator and denominator by $6$. So the probability would be the same under either assumption.
Comment: Well, maybe it's me who has a brain freeze. We first count the number of all possible choices. That is $2010^3$, agreed? Now, how many of these choices produce a right-angled triangle? Suppose ABC is a right angled triangle. Then there are several routes to choosing it, by picking the points in different orders. The way we have counted all the choices, the choice (A,B,C) is different from (B,A,C), but they both produce a triangle of the desired shape. Ergo... As I say, it might well be me, who has a brain freeze.
Comment: @Alex: The way you have counted it, the sample space has $2010^3$ events and this counts $ABC$ and $BAC$ differently, so for measuring event space, you need to count $ABC$ and $BAC$ differently as well. The way I have counted it, the size of the sample space does not take into account the order - it's the number of ways of choosing $3$ points from $2010$, so I should not multiply by $6$ while sizing up the event space.
Comment: I agree. The point was that agreeing with my first point (as you wrote in your first comment) and not agreeing with the second was inconsistent :) Never mind, I think we are in agreement now.
Comment: @Alex: I see. What I had meant was that I agree I had made the assumption that the three points were distinct, but under this assumption my calculations didn't need any extra factor which, I thought then, was your point. Anyway, I am glad my confusion was cleared. Thanks.
Answer: Simplify it. There are 2010 points, but if you start with four points instead and pick 3 at random, you see the probability of getting a right triangle is 1 (draw it out, it helps). You can do it with six points too, and if you look at the probability for both figures you can create a formula to give the probability regardless of the number of points. 3/(n-1), where n is the number of points (I think it has to be even for this to work). With four points, 3/(4-1) = 1, six points 3/(6-1) = 3/5. If you have 2010 points then the probability would be 3/(2010-1) = 3/2009.


Como pegar o value de inputs declarando o this de um elemento [jQuery]?

Question: jQuery(function($){

    $('#upusuario').on('submit', function(){

        formulario  = $(this).serialize();

Pergunta: Como eu pegaria o input senha e confirmasenha deste formulário para compará-los, claro sem usar alguma coisa do tipo var senha = $("#upusuario input[name=senha]") visto que eu já recuperei os campos com serialize?
<input type="text" name="senha" class="form-control bott" required>
<input type="text" name="confirmasenha" class="form-control bott" required>

Answer: Não é necessário usar .serialize(). É possível acessar diretamente partir do this, que no caso de formulários é um HTMLFormElement.
Os campos podem ser acessados de 3 maneiras:

atrávés da propriedade name do campo: this.nome_do_campo
através da propriedade .elements por índice: this.elements[0]
através da propriedade .elements por nome: this.elements['nome_do_campo']

Para acessar o valor, basta utilizar uma das opções acima para selecionar o campo e depois a propriedade .value para acessar o valor:

$(function(){
  $('#upusuario').on('submit', function(e) {
    var resultado = $('#resultado');
    var senha1 = this.senha.value;
    var senha2 = this.confirmasenha.value;
    e.preventDefault(); // impede envio do formulário
    resultado.text(senha1 + ' ' + senha2);
  });
});

<form id="upusuario">
  <input type="text" name="senha" value="senha1" required/>
  <input type="text" name="confirmasenha" value="senha2" required/>
  <input type="submit"/>
</form>

Comment: +1 por não ter criado um `elemento [jQuery]` apenas para pegar o valor de um input.
Answer: Você pode fazer por meio da função split(); uma vez que a função serialize(); retorna uma String com delimitador &.
Veja o exemplo abaixo:

$(document).ready(function(){
  $('button').click(function(){
    var arr = $('form').serialize().replace(/password[1,2]=/g,'').split('&');
    if(arr[0] !== arr[1]) {
      $('div').text('Senha incorreta!');
    } else {
      $('div').text('Senha correta!');
    }
  });
});

<form>
  Password1: <input type="text" name="password1">

  Password2: <input type="text" name="password2">

</form>

<button>Serialize!</button>


Python: How do i log requests to multiple files

Question: I'm writing a web-crawler and having an issue, I would like to log each different level of message to its own log file.
I thought this would work but it only creates 'crawler-debug.log'
logging.basicConfig(level=logging.DEBUG, filename='crawler-debug.log')
logging.basicConfig(level=logging.WARN, filename='crawler-warn.log')
logging.basicConfig(level=logging.ERROR, filename='crawler-error.log')
logging.basicConfig(level=logging.INFO, filename='crawler-info.log')

Where am I going wrong here...
Also I would like a time-stamp at the beginning of each line of the log-file so I know when the request was sent.
Answer: You will need to create a file handler for each log level. Formatting can be applied to each handler to add the timestamp. Python Logging Cookbook - Multiple handlers and formatters
Also to filter out other log levels other than the one you want (e.g. only DEBUG logging going to debug log file), you'll need to write your own handler object. See similar question answered here.
Here's an example with just debug and info logging.
import logging

# Define handler to omit logs that are not DEBUG level
class DebugFileHandler(logging.FileHandler):
    def __init__(self, filename, mode='a', encoding=None, delay=False):
        logging.FileHandler.__init__(self, filename, mode, encoding, delay)

    def emit(self, record):
        if not record.levelno == logging.DEBUG:
            return
        logging.FileHandler.emit(self, record)

# Define handler to omit logs that are not INFO level
class InfoFileHandler(logging.FileHandler):
    def __init__(self, filename, mode='a', encoding=None, delay=False):
        logging.FileHandler.__init__(self, filename, mode, encoding, delay)

    def emit(self, record):
        if not record.levelno == logging.INFO:
            return
        logging.FileHandler.emit(self, record)

logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
# create file handlers
dh = DebugFileHandler('debug.log')
dh.setLevel(logging.DEBUG)
ih = InfoFileHandler('info.log')
ih.setLevel(logging.INFO)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(message)s')
dh.setFormatter(formatter)
ih.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ih)
logger.addHandler(dh)

# 'application' code
logger.debug('debug message')
logger.info('info message')

Comment: While this link might answer the question, could you summarize the relevant parts in case it gets changed, removed? Thanks.
Comment: Wow this is getting dense, this is almost as many lines of code as my crawler...  I suppose i should create a separate module for logging requests thus separating the logging logic from the crawler logic.
Comment: When I'm done writing the class I will post it here so that others can use and extent it.


Composition $f^n$ is a contraction $\implies f$ possesses a fix point.

Question:
Definition. $x \in \mathbb{R}^n$ is called a fixpoint of the function $f:\mathbb{R}^n \to \mathbb{R}^n$, if $f(x)=x$.
Notation. $f^n(x) := \underbrace{(f \circ f \circ \cdots \circ f)}_{\text{$n$ times}}(x)$
Definition. A function $f:\mathbb{R}^n \to \mathbb{R}^m$ is called a contraction, if there exists a positive constant $L<1$ such that for all $x,y \in \mathbb{R}^n$ the inequality
$$\|f(x)-f(y)\|_{\mathbb{R}^m} \leq L \cdot \|x-y\|_{\mathbb{R}^n} $$
holds.

Let $A \subseteq \mathbb{R}$ be a closed subset and $f : A \to A$. Assume, there exists an $n \in \mathbb{N}$, such that the $n$-fold composition $f^n:A \to A$ is a contraction. Can it be shown, that there exists a fixpoint $x^* \in A$ for $f$?
Comment: Probable duplicate of https://math.stackexchange.com/questions/2498109/if-fk-is-a-strict-contraction-for-some-integer-k1-show-that-f-has-a-uni
Comment: You can rewrite $f^n(x_0)=f(f^{n-1}(x_0))$
Comment: What are you allowed to use? The Banach fixed point theorem makes this rather simple, but you might not be allowed to use that at this point.
Comment: @DanRust Yes, the Banach FPT may be used. By that theorem, there is a unique fixpoint $x_0 \in A$ with $f^n(x_0)=x_0$. By this, $f^{n+1}(x_0)=f(x_0)$. But how does this imply something for $f$ itself?
Comment: Aaaah, yes, of course! Thanks :D @Cornman
Answer: By the Banach FPT, $f^n$ has a unique fixed point $x$. $f^n(f(x))=f^{n+1}(x)=f(f^n(x))=f(x)$ so $f(x)$ is a fixed point for $f^n$ as well, and so by unicity $f(x)=x$. If $y$ is a fixed point for $f$ then $f^n(y)=y$ and so $x=y$.


What routing protocol to use with MPLS?

Question: My MPLS provider is giving us a choice to use static routes or BGP for our new MPLS setup.
What are advantages/disadvantages of the 2 choices? What is more commonly used?
Answer: MPLS providers will implement MP-BGP in their network to share  all routes from and to your different sites.
They will be separated from other customers' routes by beeing in a "vrf" (vpn), thus eliminating the need of separate IP space (eg all customers can use RFC1918 addresses)
I think that your provider is giving you the choice of the routing protocol between the PE and the CE router.
Typical end-to-end synopsis:
CE --leased line-- PE --backbone link-- P --backbone link-- PE --sdsl line-- CE

CE : customer edge, the routers on your sites.
PE : provider edge. Router facing customers
P : provider router (or "core"). Transit routers, have only knowledge of MPLS and not IP

Static routing between PE and CE is fine for most deployments, but to be avoided if the wan link is ethernet, because in most cases the PE and the CE routers will have no way to know when the link is down (because of L2 devices which don't propagate link state).
If your sites are connected through frame-relay or ATM (dsl, T1, T3...), interfaces will go down if link is down.
To resume:

ethernet leased line : go for BGP
Frame-relay or ATM leased line, or dsl: static routing will do the trick.
Answer: You typically would need a routing protocol whenever

you have many networks/routes to manage
you want to implement redundancy and failover paths at the IP routing level
you need additional features like Anycast

You would use static routes if you can't or don't want to manage the additional complexity of dynamic routing.

What routing protocol to use with MPLS?


Action format in activity feed doesn't make sense

Question: I have an action that states a user has placed an order. Similar to user_name has placed an order on app_name. This shows perfect in activity but in recent activity it shows user_name placed og:title on app_name.
My Action is Place and my object is order.
  <meta property="fb:app_id" content="app id" />
  <meta property="og:type" content="joestakeaways:order" />
  <meta property="og:image" content="http://server.com/path/to/icon.jpg" />
  <meta property="og:title" content="Joe takeaway" />
  <meta property="og:url" content="http://server.com" />
  <meta property="og:description" content="For the best fish and chips in town try Joe's Takeaways!" />

Any way to make the recent activity show the same as actual activity. I could change the og:title to an order but then that looks a bit weird on the other feed.
Comment: Why not use 'order' or a variation of that as the verb?
Answer: You are not really using it as it's intended. You actually want a place or an arbitrary order. But the Open Graph was meant for a specific instance of your object.
Your action is ordering (placing an order).
Your type of object is an order.
A specific instance of order is "1 Portion of Fries with Fish"
i.e. <meta property="og:title" content="Joe takeaway" />
So if you want to keep the object arbitrary you should change the title to reflect an actual object of type order.
<meta property="og:title" content="An order on Joe takeaway" />

Which will result in

User placed an order on Joe's Takeaways
  16 minutes ago
  An order on Joe takeaway
  For the best fish and chips ...

And for the activity

User placed An order on Joe's takeaway on Joe's Takeaways.

It's still repetitive, shows capital A (because it should be an actual name of an object) but it's a better match (in my opinion).
Comment: Your right, I am not really using it as intended. The correct result would be the order and it's contents which would be a bit weird. While I figure out a better way I have changed the title to `Online order` and added ``. Not great but better
Answer: The execution of this action is not in the way intended. While I figure out a better way I have changed the title to Online order and added
  <meta property="og:determiner" content="an" />

Not great but better


Why must io_service::reset() be called?

Question: io_service::reset documentation states that reset() must be called before subsequent calls to run(), run_one(), poll() or poll_one().
Questions:

Why is this necessary?  -
What behaviour might I expect if this step is neglected?
Why is this requirement not important enough to warrant an assert if it's neglected?

Some context: I finished debugging some unit-tests that checked that called poll() repeatedly without reset() and was attempting to check the expected number of handlers was being executed each time. It appears that with enough calls to poll(), all handlers are eventually executed in the order expected, but it takes more calls than you would otherwise expect. Correctly calling reset() fixes the problem, but I'm curious to know if this is the only side effect of not calling reset(), or if there are potentially worse effects such as dropping handlers or effects that might appear in a multi-threaded example.
Answer: When the io_service has been stopped:

all invocations of poll(), poll_one(), run(), and run_one() will return as soon as possible
subsequent calls to poll(), poll_one(), run(), and run_one() will return immediately without invoking any handlers or processing the event loop

Invoking io_service::reset() sets the io_service to no longer be in a stopped state, allowing subsequent calls to poll(), poll_one(), run(), and run_one() to invoke handlers and process the event loop.

Why is this necessary?

It is necessary if one wishes to invoke handlers or process the event loop once the io_service has been stopped explicitly via io_service.stop() or implicitly by running out of work.

What behaviour might I expect if this step is neglected?

If io_service.stopped() is true, then subsequent calls to poll(), poll_one(), run(), and run_one() will not perform any work.

Why is this requirement not important enough to warrant an assert if it's neglected?

The io_service::reset() documentation's use of the word "must" tends to set an overly critical tone without mentioning the consequences of not calling reset().  The behavior  described by io_service::stop() is not critical enough to warrant an error:

Subsequent calls to run(), run_one(), poll() or poll_one() will return immediately until reset() is called.

For reset(), the only hard requirement is to not call it when there are unfinished calls to poll(), poll_one(), run(), and run_one().

Why must io_service::reset() be called?


Delay before dragging in gridster

Question: I'm using gridster.net in project, and i've run into problem.
I'm trying to get widgets start dragging only after a second of holding mouse after click. I'm using the next code:
$(".gridster .gs-w").on('mousedown', function(e) {
    gridsterObj.disable();
    dragTimeout = setTimeout(function() {
        gridsterObj.enable();
    }, 500);
}).bind('mouseup mouseleave', function() {
    clearTimeout(dragTimeout);
});

but it didn't work. It seems that i have to call function of starting dragging, something like gridsterObj.on_start_drag.call(gridsterObj, e, ui);, but where can i get the UI object? It's used everywhere in gridster code, but i can't find where it created.
It seems that it jquery UI object. How can i create it?
Answer: You should be able to reference the UI object as $.ui or window.jQuery.ui.
So your code should look like this:
$(".gridster .gs-w").on('mousedown', function(e) {
    gridsterObj.disable();
    dragTimeout = setTimeout(function() {
        gridsterObj.enable();
        gridsterObj.on_start_drag.call(gridsterObj, $.ui);
    }, 500);
}).bind('mouseup mouseleave', function() {
    clearTimeout(dragTimeout);
});

Comment: No, i need jquery ui event object, not jquery ui global object.
Answer: I've ended with the next code:
$(".gridster .gs-w").on('mousedown', function(e, data) {
    var self = this;

    if (!data || !data.start) {
        gridsterObj.disable();

        dragTimeout = setTimeout(function() {
            gridsterObj.enable();
            $(self).trigger(e, [{ start: true }]);
        }, 500);
    } else {
        $(self).addClass('dragging');
    }
}).bind('mouseup mouseleave', function() {
    clearTimeout(dragTimeout);
});

With that, gridster has delay 0.5 second before starting dragging.

Delay before dragging in gridster


Pager missing in View

Question: I have a view with navigation set to paged, 12 items. I can see 12 items (there are way more available), but no pager. Googling this problem I found the following solutions that didn't work:
View uses Global: PHP fields (my view doesn't do that)
View is displayed in a block (my view is displayed in a page)
Changing pager id (tried everything from 0 to 5, also, this is the only pager on this page)
It's also not a styling issue, the pager is not in the markup. I didn't override any templates related to the view.
In other views, the pager works and I can also see it in the views preview. In this view, I can't even see it in the preview - this should prove that it's not a theming issue as well, am I right?
I tried displaying a "more" link, but that didn't work as well. Changing the navigation to "mini pager" also doesn't help.
The view is using a relationship to an entity reference, but that shouldn't be an issue IMO. Other than that it's a pretty ordinary view displaying some fields. Anyone have any ideas?
(Drupal 7, Views 3)
Comment: possible duplicate of [Pager doesn't work in views block if views php field is used](http://drupal.stackexchange.com/questions/140559/pager-doesnt-work-in-views-block-if-views-php-field-is-used)
Comment: I'm voting to close this question as off-topic because it is about an old bug that been fixed, so it is no longer on topic here.
Comment: Do you have any pager plugins enabled? And is the view set to be cached?
Comment: Drupalist: No, not a duplicate, as I said in the question, I'm not using such a field and don't even have this module installed
Comment: Clive: No, don't have any pager plugins or caching for this view enabled.
Comment: Same or simillar Issue i have in D8 :/
Answer: I'm guessing you have caching enabled for this view.  You can disable caching for this view or, better, you can apply this patch: https://www.drupal.org/node/1819538
Comment: No, caching is disabled for this view.
Answer: This is a bug in Views Php module,there is a patch for that: Pager disappears when Global: PHP used in Views 3.8

After upgrading from Views version 7.x-3.7 to 7.x-3.8, the pager was
  missing from all views that used Global: PHP fields.

I had the same problem and #6 worked for me ,If patch#6 does not work for you, just follow the links in #27
Comment: Question states "View uses Global: PHP fields (my view doesn't do that)". I'm not using the Views PHP Module.
Comment: @1nterference It is not important you use or not use Php fields, try it please
Answer: I found the issue, the View was set to display as a Display Suite Layout and the pager field was hidden in the settings of the Layout.

Pager missing in View


Solutions to Polynomials of different degrees

Question: We have $p(x)$ a degree $m$ polynomial and $q(x)$ a degree $k$ polynomial. We also know that $p(x) = q(x)$ has at least $n+1$ solutions. And, $n\geq m\land n\geq k$.
Now, I tried graphing a little to see if I see a pattern
I tried making $$y= x^{2} $$
and
$$y = -x^{2}+5 $$
There were two points of intersection so $n$ was $1$ in some sense here while the degrees were $2$.
Then the only way I thought that the condition can hold for $n+1$ solutions and $n \geq m $ and $ n \geq k$ is if $p(x)$ and $q(x)$ are the same polynomial.
That was the answer to this problem. But can someone give an idea for this please.
Comment: Seems unclear what the question was, about polynomials.
Answer: $P(x) - Q(x)$ is a polynomial of degree at most $\max(m,k)$, and therefore has at most $\max(m,k)$ roots unless it is the $0$ polynomial, i.e. unless $P = Q$.
Comment: Oh wow yeah that makes sense. Thank you sir. And since we are saying $$ n \geq max(m,k) $$ we must have $$P(x) = Q(x)$$ Thanks
Answer: just a hint
If the equation $R (x)=P (x)-Q (x)=0$ has at least $n+1$ solutions, it means that degree of $R (x)\ge n+1$.
but degree of $R (x)\le \max(m,k) $
thus
$m\ge n+1$
or  $k\ge n+1$


Setting xlim() removes the xticks

Question: I am trying to plot 3 lines in matplotlib but whenever I add the xlim([]) the line disappears.
Without xlim:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

df.iloc[3:6,5:].T.plot()

with xlim:
df.iloc[3:6,5:].T.plot()
plt.xlim([410,1004])

I have made sure that the column I plot are astype float, so what could be the reason for this?
Comment: @JohanC then why when it has no xlim argument is does plot it? and also I have cganed it to flaot and checked with dypes, it is float
Comment: Well, `plot` clearly sees its input as string.
Answer: I found the problem: the labels of the X axis were string.
I have changed them using the following finction from here: Python - How to convert only numbers in a mixed list into float?
cols=df.columns.tolist()

def maybe_float(s):
    try:
        return float(s)
    except (ValueError, TypeError):
        return s
cols1=[maybe_float(v) for v in cols]
df.columns=cols1

After that it worked

Setting xlim() removes the xticks


Backbone.js cannot merge attributes when using template?

Question: I've just started learning backbone.js and ran into my first problem. I'd like to inject attributes in User view using attributes property instead of writing them in my template itself:

window.UserView = Backbone.View.extend({
    attributes : { "data-route" : '/users/' + this.name },
    template: _.template($('#user-template').html()),
    initialize : function() {
        _.bindAll(this, "render");
    },
    render : function() {
        $(this.el).html(this.template(this.model.toJSON()));
        return this;
    }
});

var u = new User({ first : 'First', last : 'Last' });
var v = new UserView({ model : u, el : '#lista' });

v.render();

Output is missing data-route attribute:

     First Last

Can you confirm that attributes doesn't work with template?
Answer: template uses the hash passed as argument, in your case you can merge this.model.toJSON() and this.attributes
Try
render: function() {
    var data = _.extend(this.model.toJSON(), this.attributes);
    this.$el.html(this.template(data));
    return this;
}

Answer: Specifically from the docs:

attributes model.attributes
The attributes property is the internal hash containing the model's state. Please use set to update the attributes instead of modifying them directly. If you'd like to retrieve and munge a copy of the model's attributes, use toJSON instead


Selecionar valor desejado com REGEX para dois padrões diferentes

Question: Eu tenho a seguinte entrada de dados:
INSTANCE-hostname:Sys
INSTANCE-hostname-INSTANCE_00:Ins

Sempre irá seguir este caso, onde somente o que me interessa é o valor hostname, ou seja, meu OUTPUT deve ser:
hostname
hostname

Testei com o regex [^-]*-([^:]+), mas está falhando:
REGEX101
PYTHEX
Como obter a saída desejada?
Answer: Sua regex falha porque você só verifica os casos em que há : depois de hostname. Mas você precisa verificar também se tem um -:
import re

textos = [ 'INSTANCE-hostname:Sys', 'INSTANCE-hostname-INSTANCE_00:Ins' ]

r = re.compile(r'^[^-]+-([^-:]+)[-:]')
for texto in textos:
    m = r.match(texto)
    if m:
        print(m.group(1))

O marcador ^ indica que vou começar a busca pelo início da string.
A regex busca por vários caracteres que não são hífen ([^-]+), seguido de um hífen, seguido de vários caracteres que não sejam hífen nem dois pontos ([^-:]+), seguido de um hífen ou dois pontos ([-:]).
A parte que eu quero pegar (logo após o primeiro hífen) está entre parênteses para formar um grupo de captura. Em seguida, eu posso pegar esse grupo usando group(1) (eu uso 1 porque é o primeiro par de parênteses da regex, e portanto é o primeiro grupo).
A saída é:
hostname
hostname

Se a parte correspondente a "hostname" sempre será "uma ou mais letras", dá para usar também:
r = re.compile(r'^[^-]+-([a-zA-Z]+)[-:]')

Isso pode dar resultados diferentes, dependendo das strings que você usar, já que  [^-:]+ considera quaisquer caracteres que não sejam - ou : (ou seja, quebras de linha, números, sinais de pontuação, espaços, etc). Mas se usar [a-zA-Z], você restringe somente ao que precisa (o ideal em regex é tentar, na medida do possível, dizer exatamente o que você quer e o que não quer).
Comment: @LuisV. Só lembrando que se a resposta resolveu o seu problema, vc pode aceitá-la, [**veja aqui**](https://pt.meta.stackoverflow.com/q/1078/112052) como e porque fazê-lo. Não é obrigatório, mas é uma boa prática do site, para indicar a futuros visitantes que aquilo resolveu o problema.
Comment: @LuisV. Ah é, esqueci que tinha esse tempo mínimo pra aceitar... :-)
Comment: @LuisV. Não, vc vai ter que adicionar o `_` na lista: https://regex101.com/r/QHgxpD/1/
Comment: ficou muito boa sua resposta, consegui entender exatamente onde meu regex estava falhando, muito obrigado pela ajuda e por ter formulado o script em python junto com o regex !!
Comment: Vou aceitar sim, so estou aguardando terminar o tempo, ainda esta bloqueado para aceitar respostas!
Comment: Feito, muito obrigado !!
Comment: so uma duvida, quando eu tiver o seguinte caso 'INSTANCE-hostname_INSTANCE_00:Ins', o regex acima se aplica?
Comment: Perfeito, entendi, muito obrigado mesmo, esclareceu todas minhas duvidas !!


What is a hierarchical model that can estimated via the Metropolis-Hastings Algorithm but not the Gibbs Sampler?

Question: My understanding of the differences between MH and Gibbs Samplers is that a Gibbs Sampler is usually used when the full conditionals are present to us. In other words, it is a known distribution, so that sampling from it is just as easy as calling a function in R.
I would usually use MH if the conditionals are not well known. However, I am failing to think of an example which cannot be done by Gibbs and must be handled by MH. Is there a prototypical hierarchical model? Thanks.
Answer: Take for instance a hierarchical logit model
$$\mathbb{P}(Y_{ij}=1|\boldsymbol{\theta},\mathbf{X})=\dfrac{\exp\{\theta_i^\prime x_{ij}\}}{1+\exp\{\theta_i^\prime x_{ij}\}}$$
with a non-standard prior on the $\theta_i$'s, itself parameterised to achieve a hierarchical structure.


Prove or Disprove Big-Oh using ratio and limits

Question: $$n^{1.001}+nlog (n) = O(nlog(n))$$
So from there we can break it down into a ratio where we are using limits and approaching infinity:
$$\frac{n^{1.001}+nlog (n)}{nlog(n)}$$
A bit rusty on the arithmetic, should I find a derivative next?
Comment: fun fact: $n^\epsilon$ eventually grows faster than $\log n$ for any $\epsilon>0$
Answer: You are right to look at the ratio. Discarding the $+1$, we get:
$$
{n^{1.001} \over n \log(n)} = {n^{0.001} \over \log(n)}.
$$
Taking the $\log$ of the latter ratio, we get:
$$
0.001 \log(n) - \log (\log(n)),
$$
which grows without bound as $n \rightarrow \infty$.  (To see this, let $m = \log(n)$ and examine the expression as $m \rightarrow \infty$.)


Reference request for a theorem in Lee's Smooth Manifolds

Question: In Lee's book Introduction to Smooth Manifolds, he remarks on page 25 that

It is a fact (which we will neither prove nor use) that $F: U\rightarrow \mathbb R^k$ is smooth in this sense if and only if $F$ is continuous, $F|_{U\cap \text{Int }\mathbb H^n}$ is smooth, and the partial derivatives of $F|_{U\cap \text{Int }\mathbb H^n}$ of all orders have continuous extensions to all of $U$.

This follows a discussion of the definition of a smooth function on an arbitrary subset of $\mathbb R^n$. A function on such a set is defined to be smooth if and only if it admits a smooth extension to an open neighborhood of each point. The quote concerns functions defined on the closed upper half space (the subset of $\mathbb R^n$ with $x_n \ge 0$).
My question: Where can I find a proof of the quoted theorem?
Answer: Good question.  One direction is immediate; the other direction depends on a lemma of Émile Borel, which shows that there is a smooth function defined in the lower half-space whose derivatives all match those of $F$ on $U \smallsetminus \mathbb H^n$. See, e.g., Theorem 1.2.6 in The Analysis of Linear Partial Differential Operators I: Distribution  Theory and Fourier Analysis, 2nd ed., by Lars Hörmander. (I included this reference in the second edition of my Smooth Manifolds book.)


Question on a submanifold of $\mathbb{C}^2$ and tangent vectors

Question: Let $X\subset \mathbb{C}^2$ (with complex coordinates $z,w$) be defined by the equation $|z|^2=|w|^2$.
If we see $\mathbb{C}^2$ as $\mathbb{R}^4$ with real coordinates $z=x+iy$, $w=u+iv$ then $X$ is a real submanifold of dimension 3 defined by $x^2+y^2-u^2-v^2=0$.
Question 1: is $X$ also a complex submanifold?
Question 2: is $(i,0)$ a tangent vector to $X$ in $(1,1)\in X$?
I think the answer is no to both questions. In particular for the second one it should be true that $T_{(1,1)}X\simeq Ker(df_{(1,1)})$ with $f= x^2+y^2-u^2-v^2=0$ and $df_{(1,1)}=(2,2,-2,-2)$. But $(i,0)=(0,1,0,0)$ in real coordinates and $df_{(1,1)}(0,1,0,0)\neq 0$.
Am I right?
Comment: Yes, you're right. Note, furthermore, that any complex manifold must have even real dimension.
Comment: I think, contrary to you and  @Ted, that the vector $(i,0)$ **is** tangent to $X$ at the point $(1,1)\in X$ : this is because I think that your equality $df_{(1,1)}=(2,2,-2,-2)$ is false and that it should be $df_{(1,1)}=(2,0,-2,0)$. What do **you** think is $df_{(z,w)}$ and what do you get with your formula when $z=1, w=1$ ? See my answer for my point of view.
Comment: Of course, @Georges is right. I fell in the trap of skimming the second part and not being careful. My apologies.
Comment: Thanks  for your gentlemanly  comment,  @Ted.
Answer: Question 1
Since $X\subset \mathbb R^4$ is a real hypersuface it has real dimension $3$ and so cannot be a complex manifold nor even a complex space since complex spaces have even real dimension.
(Beware that, if  $O\in \mathbb C^2$ denotes  the origin,  $X\setminus \{O\}$ is indeed a real manifold , but $X$ itself is not a real manifold because  it has a singularity at $O$)
Question 2
We have for $P=(a,b)=(p+iq,r+is)\neq O\in X\subset \mathbb C^2$ the relation $T_PX=\ker d_Pf$, where $$d_Pf:\mathbb C^2\to \mathbb R:(z=x+iy,w=u+iv)\mapsto 2(px+qy-ru-sv)$$ or in vector notation $$ d_Pf=(2p,2q,-2r,-2s)$$ If now $a=1,b=1$, we get $$d_Pf(z,w)=2(x-u) \quad [\operatorname {or in vector notation } d_Pf=(2,0-2,0)]$$ so that $T_Pf$ is the real hyperplane $$T_Pf=\{(z,w)\in \mathbb C^2\vert x=u\}$$ So, yes,  $(i,0)=(0+i,0+0i)\in T_Pf$ since for that vector $(i,0)$ one has $x=u=0$
Supplementary remark
 One may notice that the only complex line $L$ included in the $3$-dimensional real vector space $T_{(1,1)}X\subset \mathbb C^2$ is $$L=\{(0,w)\in \mathbb C^2\vert w\in \mathbb C\}$$


Uncaught ReferenceError: grecaptcha is not defined

Question: I am using recaptcha v2
I am getting the following error occasionally (sometimes i don't get error and sometimes i do get it)
Uncaught ReferenceError: grecaptcha is not defined

It seems because of the internal http request. that takes some time to get another js recaptcha__en.js. Meanwhile actual rendering code of grecaptcha executes.
So what is the standard solution to avoid this issue.?
PS : of course i am looking for some solution other than setTimeout
Answer: Recaptcha has a onload callback that will run once recaptcha is loaded. Place your code inside that callback function.
https://developers.google.com/recaptcha/docs/display

Comment: but i want to render the captcha challenge not on pageload. i want to render it after user enters into some bootstrap modal
Comment: @nodeofcode It is not page `onload`. This is provided by recaptcha. I have updated my answer with the example
Comment: i do get your point.. but how can i render captcha into block which doesn't exists
Comment: I didn't get what you meant by **but how can i render captcha into block which doesn't exists** ?
Comment: grecaptcha.render(, paramObj) .. here somedivid need to exists in DOM in order that captcha renders into this div. Now If i provide onload query param, then the callback executes right after the scripts get loaded, and at that time i don't have that somedivid.
Comment: I can get your point but i am not sure when `` will be available in DOM ? What you can do is, once you rendered ``, then you can inject captcha script with `onload` callback.
Comment: If you want to load grecaptcha on page load, then set a boolean inside the callback of `onload` and check against the boolean before rendering recaptcha.
Comment: Of course the wrapper www.google.com/recaptcha/api.js, get loaded. then my code get executed. But In this case, i have to inject recaptcha__en.js, not api.js. So the question in how do i inject second level code that is recaptcha__en.js?
Comment: @nodeofcode Why do you need to do that ? Any how `api.js` will do some pre-processing and will inject `recaptcha__en.js` (language specific code).
Comment: I had already injected api.js before this question was asked. Then i found that api.js does load recaptcha__en.js but only after its injection get resolved.
Comment: You can inject `recaptcha__en.js` yourself but i don't recommend it. Moreover, i think the content of `recaptcha__en.js` is dynamic. So, it is better to use `api.js` as suggested by them.
Answer: I have solved this by ordering the script in below manner
HTML

jQuery

Answer: It works on landing page and also in bootstrap 4 popup form:

Thanks for asking this question. :)
Answer: My Problem got resolved by doing following changes in the script code (:
i.e from internal path

to external google path i.e

Answer: For me it was working for years then suddenly stopped.
switching the API load from

to having async and defer fixed it

Answer: Sometimes the application loads several times the script 'https://www.google.com/recaptcha/api.js after refresh, make sure your application doesn't have multiple
Answer: If you don't want to use a callback, another async solution is explained in the recaptcha docs:

When loading reCAPTCHA asynchronously, keep in mind that reCAPTCHA
cannot be used until it has finished loading. For example, the
following code would likely break:

In some situations, adjusting script ordering can be enough to prevent
race conditions. Alternatively, you can prevent race conditions by
including the following code snippet on pages that load reCAPTCHA. If
you are using grecaptcha.ready() to wrap API calls, add the following
code snippet to ensure that reCAPTCHA can be called at any time.

Comment: Not sure why but I couldn't get this working for v3. https://www.google.com/recaptcha/api.js?onload=loadReCaptcha&render={key} seemed to work
Answer: I know this is an old question but maybe this will help someone.  The reason I was getting this 'Uncaught ReferenceError: grecaptcha is not defined' error was because I couldn't reach the dependency js file (recaptcha_en.js) which is hosted on www.gstatic.com.  Once I solved that issue, it worked for me.
Comment: It wasn't meant as a link, it was meant as a hostname.  This server was blocked by my network policy which is what caused the issue for me.
Comment: link isn't valid
Answer: I have solved the problem by updating site key and secret key. Actually I was using v3 API but used v2 configuration.
After using v3 key, my captcha is working fine.


Loop para repetir as chaves anteriores (3, 32, 321, ...)

Question: Estou tentando fazer um breadcrumb dinâmico e preciso fazer um loop para montar o link. A cada loop, ele precisa repetir os itens anteriores, como no exemplo abaixo o array e o output.
array( array( 'Bairro' , 'bairro' ) , array( 'Rua' , 'rua' ) )

Bairro
Rua

O pouco que consegui foi usando unset para gerar um novo array. Após esse for para montar a repetição, eu ainda preciso de mais 2 loops e reverter a ordem. Uma baita gambiarra.
foreach( $list as $i => $item ){
    $newlist[] = $list;
    unset( $list[$i] );
}

Comment: Só uma pergunta: o label do breadcrumb precisa mesmo ocupar outra posição na tua array? Não seria melhor ser um array associativo? Ex.: `array('item' => 'Label', 'bairro' => 'Bairro', 'rua' => 'Rua')`
Comment: @Thomas, Seria melhor sim, mas como disse, é dinâmico e com vários sub itens. Se pudesse refazer o array não teria problema.
Answer: Acredito que acumulando o link em uma variável você consiga o resultado que espera, por exemplo:
$breadcrumbs = array( array( 'Bairro' , 'bairro' ) , array( 'Rua' , 'rua' ) );

foreach ( $breadcrumbs as $item ) {
    $link_acumulado .= $item[1] . '/';

    echo '' . $item[0] . '';
}

Saída:
Bairro
Rua

Answer: Vou deixar outra possibilidade, mais complexa e menos performática que a do Márcio, mas ainda assim válida.
Se você transpor a matriz original vai ter sempre um array de dois índices, um com os labels e outro com os breadcrumbs.
Combine os índices numa nova matriz (aqui descrita como $breadcrumbs) e itere:
$previous = NULL;

$last = key( array_slice( $breadcrumbs, -1, 1, TRUE ) );
$separator = ' » ';

foreach( $breadcrumbs as $label => $breadcrumb ) {

    $previous .= sprintf( '/%s', $breadcrumb );

    if( $label == $last ) $separator = NULL;

    printf( '%s%s', $previous, $label, $separator );
}

Comment: Valeu Bruno, o problema é a ordem do array. Achei mais prático trabalhar em pares..


Lagged dependent variable in linear regression

Question: Recently I read an paper where in a time series data has been modelled according to the equation
$$
  Y_t=\beta_1 Y_{t−1}+\beta_2X+\varepsilon.
$$
OLS was used here (with the lm() command in R) for obtaining the coefficient of $Y_{t-1}$. Is it statistically correct?
I understand when we deal with time series data, this actually means an ARX process and can be represented as
$$
Y_t=\theta Y_{t-1}+\beta X + \varepsilon,
$$
where $\theta$ comes from the Yule-Walker equations.
Will $\theta$ and $\beta_1$ yield the same result? Won't the OLS estimator suffer from autocorrelation problem as $E[x_t \varepsilon_t] \ne 0$ ? My statistics knowledge is beginner level. Please guide me on understanding this.
Comment: In the absence of Moving Average (MA) terms, AR models (with or without exogenous variables) can be fit with OLS without big problems. Compared to MLE it will have small sample bias, but doesn't affect consistency. And we are not scared of bias boogeyman anymore.
Comment: @CagdasOzgenc, if I am not mistaken, MLE will also have bias, won't it?
Comment: I stand corrected. I always thought that bias disappeared when exact likelihood is used. It seems conditional likelihood and OLS have the same properties while exact likelihood has a smaller bias, yet still biased. All schemes are consistent, that's for sure.
Comment: See [Can I use OLS to estimate an ARX(1) model?](https://stats.stackexchange.com/questions/299175/can-i-use-ols-to-estimate-an-arx1-model?rq=1)
Answer: Hi: Your model is also called a koyck distributed lag and it can be difficult to estimate with small samples. With larger samples, my experience is that there is not a problem with bias. ( I used simulation to check this ).
The link discusses the statistical properties of the estimates briefly on pages 12 and 13. Essentially the problems with it are similar to those of the estimates of an AR(1).
https://www.reed.edu/economics/parker/312/tschapters/S13_Ch_3.pdf
I would check out hamilton or the little koyck book (1954) for a more in depth discussion but hopefully the above helps some.
Answer: From what I have read, the Yule-Walker equations use least squares to estimate the AR-1 lag coefficient (what you call $\beta_1$ in display 1 and $\theta$ in display 2). The joint estimation of the lag coefficient and the $X$ coefficient is correctly done using a least squares model adjusting for the lag and the concurrent $X$ in the model you have written. If the model is misspecified due to either cross lags, omitted variables, or higher lag orders, and display 1 does not describe the data generation process, the coefficients can be massively biased.


How can I calculate the sample size of self-control study design for a two-arm meta-analysis

Question: I recently encounter with a question is that I want to perform a traditional two-arm meta-analysis, however, some of the included studies are self-controlled study design.
The natural way to deal this is to set the sample size of the intervention arm and control arm as the patient number.
However, it seems to me that the self-control design and the traditional randomized controlled trial are different.
How could I deal with this problem, thanks a lot!
Answer: It depends on what you mean by "self-controlled design".
If you mean a randomized cross-over study, then such a study can nicely be combined with parallel group randomized trials by using the estimate of the treatment effect and the standard error (SE) for it as estimated in the publication by the authors using the individual patient data (assuming they used an appropriate analysis for a cross-over study). The generic inverse variance approach that uses estimates of treatment effects and SEs as an input is described e.g. in Section 10.3 of the Cochrane Handbook. However, this will not so easily fit into a paradigm that expects mean and SE by group, because the outcomes by group are correlated. That's because each patient received multiple treatments and hence the outcomes of the groups are correlated, because results for the same patient are not independent (which carries through to the group means). This makes them a bit harder to integrate into network meta-analyses, but it sounds like the estimate & SE approach could work in your simpler case.
If you mean a before-and-after design (i.e. looking at patients before an intervention and then, again, after an intervention and seeing how much things changed), these studies are much harder to use, because  the commonly done before-and-after comparisons are essentially invalid/useless/pointless/misleading (pick your favorite term) for assessing whether the intervention had a causal effect. That's because of things like regression to the mean that usually mean that you see a substantial improvement even with completely ineffective interventions. Most people would probably use well-performed observational studies before relying on evidence like that. Versions of such uncontrolled studies that try to account to the amount of improvement you might see without intervention are more appropriate. For example, trials that use solely external controls (i.e. compare to what you expect in similar patients from some other data source) are an already quite an improvement on that simple before and after comparison, but that's of course still not a randomized comparison as you have a randomized parallel group trial or a randomized cross-over trial. Even better approaches exist that try to have some concurrent randomized controls, or try to take measures to make external controls better matched to the trial population.
Comment: Another type of self control design is that using a cream on the different side of the patient.
Comment: Good point. In terms of analysis & how to use that, it will depend on what gets reported, but the inverse-variance meta-analysis strategy of taking the estimate of treatment difference (within patient) with SE from some appropriate analysis (either using the within patient difference, or using e.g. a random effects model for the two values per patients) in the published paper would again work.


Space Invaders - strange movement with alien movement algorithm

Question: I've been working for a while on a clone of space invaders. The biggest problem I've faced by far is getting the aliens to move. After a lot of effort, I've developed n algorithm to move them. The algorithm behaves as expected, except that when the aliens have finished moving to the left/right and then move down, the left or rightmost aliens begin to converge on the two next to them, overlapping their sprites. Monitoring their X coordinates, I discovered that they move 10 pixels to the left/right every time they move down. I can't figure out why they do this, and am hoping you can help me. Here is my movement algorithm (the aliens are arranged in 2 rows of 10 and this method is called every ten frames. movestate dictates which direction the aliens are moving in.):
public void alienMove()
    {
        boolean movedown = false;
        if(movestate)
        {
            for(int i = 0;i<aliens.length;i++)
            {
                if(aliens[i].getX()==950)
                {
                    movestate = false;
                    movedown = true;
                }
                else
                {
                    aliens[i].setX(aliens[i].getX()+10);
                }
            }
            if(movedown)
            {
                for(int j = 0;j<aliens.length;j++)
                {
                    aliens[j].setY(aliens[j].getY()+20);
                }
                movedown = false;
            }
        }
        else
        {
            for(int i = 0;i<aliens.length;i++)
            {
                if(aliens[i].getX()==50)
                {
                    movestate = true;
                    movedown = true;
                }
                else
                {
                    aliens[i].setX(aliens[i].getX()-10);
                }
            }
            if(movedown)
            {
                for(int j = 0;j<aliens.length;j++)
                {
                    aliens[j].setY(aliens[j].getY()+20);
                }
                movedown = false;
            }
        }
    }

Comment: Seems like a great case for a debugger, have you tried debugging?
Comment: Shouldn't you swap `movestate` *after* you have moved down? Also, the aliens are not moving as a block, because you test the x position for each individual alien; maybe you should determine `movedown` outside the block, bease on the position of the top left alien, say.
Comment: @RyPope As a matter of fact I have. I came here simply because I couldn't work out what was happening. I apologize for my obvious ignorance, but I was under the impression that SO was a place where one could get help, rather than be insulted. My mistake
Comment: @imulsion Oh come on now, surely you don't get insulted just by someone asking if you've debugged...
Answer: Suppose the aliens are about to hit the right edge. The first 9 (reading left-to-right) don't have X = 950, so move 10 pixels right. Then the rightmost does have X=950, so doesn't move right; instead, it triggers the direction change and downshift.
Similarly, at the left edge, the first alien doesn't move, but triggers the (later) downshift and direction reversal, then the other nine aliens move left by 10 pixels.
You need to treat all the aliens the same way. Either move the edge alien as well, or don't move any aliens when the edge is reached.
Comment: I can't thank you enough. Thanks so much for actually making me understand the problem I had.
Answer: Before trying to debug this code, I would propose you to improve and simplify it. First, if you look at your code, there are many parts completely similar that could be easily factorized.
Plus, you may be more comfortable if you had an enum Direction with some methods like move(Point p), the code would be clearer. Plus, I get that aliens[i].getX() == 50 is actually always false except for the leftmost alien, so this test should be out of the loop.
It may also be the reason why your code doesn't work, because your first loop moves the aliens from aliens[0] to aliens[aliens.length - 1]. Only the last alien can verify aliens[i].getX() == 950 so when this condition is reached, all the aliens from aliens[0] to aliens[aliens.length - 2] will be moved to the right and to the bottom, whereas aliens[aliens.length - 1] will only be moved to the bottom.
Answer: Normally in Space Invaders, the aliens move as a block.  So when they are moving left, you wouldn't want to test that all of them have reached coordinate 50. Just the leftmost one.  So perhaps:
if(aliens[i].getX()==50)

should be:
if(aliens[0].getX()==50)

etc.  And correspondingly:
if(aliens[aliens.length - 1].getX()==950)

when they are going right?
Answer: Here is a bug, last one didn't move, but all before it has moved in left/right direction;
if(aliens[i].getX()==950)
{
   movestate = false;
   movedown = true;
}
else
{
   aliens[i].setX(aliens[i].getX()+10);
}

this check if(aliens[i].getX()==950) should be after increment.
In last iteration you have moved all aliens to left/right but last one detects edge and its position it isn't moved, so all movement effect from last iteration should be reverted.


How can it be explained that the natural fifth of an euphonium is not in the "natural fifth pitch?

Question: I practice with 3 different Euphoniums, a brass-instrument like a small tuba. One of them - a Yamaha training instrument with 4 valves in a row - has a bad intonation at the natural fifth (upper G) actually the f ...
which can hardly be compensated by lip tension or embouchure. I have no idea what could be the reason of this phenomenon as this tone  is part of the overtone series.
Comment: The euphonium has its own particular set of problems. I suggest you search online for *euphonum pitch problems*. You will discover many useful articles, e.g. http://www.dwerden.com/CompensatingSystem.pdf ... https://merbrassresourcefile.weebly.com/uploads/4/0/5/8/40583795/instr_may_1981_eu029.pdf
Answer: A perfect air column contained in a perfect, straight tube, plays the notes of the harmonic series.
A real-world instrument, with all its twists, bends and constrictions, doesn't.
Part of the art of designing a good instrument is minimising these imperfections.  Or the designer may have taken the attitude 'Ok the open note is out of tune, but it's fine with an alternate fingering'. Try 1+3 or 4.
(I think that's right.  We're talking in 'Bb transposed' notation?   Anyway, try SOME alternative fingering.)
You think THAT's bad?  Look at the overtone series of a church bell.  It bears very little resemblence to the theoretical harmonic series.  It isn't a simple tuning fork, designed for purity of pitch, it's a very complex resonant system. The 'hum note' may be a major 7th below the 'strike note'!  This isn't the place to discuss it fully, just know that real instruments don't have a nice tidy overtone structure!
https://en.wikipedia.org/wiki/Strike_tone
Comment: Read my answer again.  A euphonium is not a laboratory demonstration of acoustical principles, it's an imperfect, real-world object.
Comment: Yes, I'm talking about Bb instrument. My question is concerning the fifth and I can't understand that it sound so much wrong as it doesn't need any walve and no compenation. And with all other instruments I never had this problem. I could even post a piece of the Tokyo Staff Band where you can hear the same negative effect.
Comment: I can understand a reputable band using instruments with an out-of-tune open G.   I can't understand them failing to solve this with an alternative fingering!   Let's hear the piece?

How can it be explained that the natural fifth of an euphonium is not in the “natural fifth pitch?


Create custom front page without adding content

Question: I am trying to create a custom welcome front page, it should contain two parts (left block and right block).
Each block has a background image (editor can upload), a logo (1 logo for each block), a description text...
Creating a new content type, is not a good idea in my opinion, because I don't like editors to add as much as they want nodes of that content type, so it should be only one content the editor can edit it each time he want to edit the background or logo...
I am thinking of creating a new setting form for this specific front page content containing those fields in a custom module. In this case, can I use picture module to make the background load a responsive image and not the default one uploaded by the editor ?
Thanks in advance.
Answer: In your case, yes you can create settings form, where admin will load background images, logo and enter description. But why you want use picture module? You can define new variables in hook preprocess_page for front page. Where in variable you put url to background image, url to logo, descriptions. After in front page template file, set url background to our block, logo and place descriptions.
Finally add styles to block class or id in css file for align background at the block. For this you can use something like this:
<code>.your-class {
    background: transparent url("path/to/background.jpg") no-repeat scroll 50% 50% / cover;
    width: 100%;
}
</code>
background url you add in template. I write path to url in code for quick example, you can place this code in some div, add correct url and see result.
Answer: I understand that:

Your key reason for not considering a content type is that you wish
only one of this content type to be added to the site.
It is the intention that all of the content for the homepage is to be editable.

I would suggest that using a content type may still be a suitable approach: by virtue of not granting any role the "create new [content type x] permission", you ensure that the only type of user who could add new homepages would be the "administrator role" which you have set - a role which you won't have given to content editors.
For the blocks with background images, you might wish to consider use of the field_collection module to create sets of grouped fields; you can template field collections, allowing you to create an element with a background image and other field outputs contained within that element, for example. Ref http://www.drupalcontrib.org/api/drupal/contributions!field_collection!field-collection-item.tpl.php/7 for templating a field collection item. (If you prefer to use the paragraphs module, an equivalent approach would apply.)
The key thing here is that when you create your templates, you can output the file names of the editor-uploaded background images (e.g. a small inline CSS block), and ensure that you make use of the background-size property (you want "cover"). Set the position of the background images depending on how you'd like the visual effect of the responsive behaviour to work.

For example, 50% 50% will keep the centre of the image in the centre of the available area, while 0 0 would pin the top left corner to the top left of the area.

(The Picture module is aimed at embedding responsive content images, rather than for background images, so would not help you to achieve what I understand you're trying to do.)


D3 changes from Version 3.0 to make a circle path of points

Question: I am trying to make a gradient path along a circle. Very similar to this example.
http://bl.ocks.org/mbostock/4163057
This is D3 version 3. I'm trying to update this to Version 4.
I fixed a few items like
d3.ns.prefix.svg is now d3.namespaces.svg
d3.svg.line().interpolate("basis") is now d3.line().interpolateBasis;
What is killing me is that function d3.line().interpolateBasis is returning "line is not a function" d3.line and d3.arc is returning NaN.
here is a working version of what i am trying to do in D3 Version 3
http:// jsfiddle.net/firetiki/k3q0d848/
Here is the code for D3 Version 4 with the changes for v4 that does not work. I am getting line is not a function in the console.
http://jsfiddle.net/firetiki/9nwwgywz/
Any help would be appreciated. Maybe I am missing another change in the version update?
Comment: @GerardoFurtado. yes. my code would be helpful. thanks. forgot to post the link.
Comment: Without seeing your code it's impossible to help you.
Answer: There is no interpolateBasis in D3 v4: https://github.com/d3/d3-shape/blob/master/README.md#curves
So, change your line function to this:
var line = d3.line().curve(d3.curveBasis);

Here is your fiddle using D3 v4: http://jsfiddle.net/gerardofurtado/fro6Lu2x/
Answer: Mike Bostock has now updated to D3 version 4
http://bl.ocks.org/mbostock/4163057


Full height content block width sticky footer

Question: Problem is trivial (I am sure there must be plenty of solutions, but can't find proper one myself (honestly))
I need simple header->content->footer page, like this

Where header footer is sticky to botom (not fixed position, if there is no content it's on bottom, if there is, It must move depending on content block height.
What I've tried
header and footer are absolute with top and bottom properties, content have padding from top and bottom same as header and footer height but it doesn't work as I want to.
Jsfiddle example:
https://jsfiddle.net/xwjhn7ej/
Comment: http://stackoverflow.com/q/37887589/483779
Comment: @Alexis your footer doesn't stick to the bottom when there's no content.
Comment: @Paulie_D since the duplicate you close uses `flexbox` as a solution will be better if you ask OP first if that support is an option. I think with the comment of Pangloss was enough to point OP that solution and wait if he can use it ... also that answer has always the footer visible that wasn't a requirement from OP
Comment: The dupe has 3 different options not just flexbox...that's why it's a dupe.
Comment: Right but **always the footer visible** isn't a requirement ...
Comment: I'd say it IS a requirement... *"if there is no content, it's on bottom"*
Answer: You are so close ... just need to change the value from height , what you need is to set the min-height :
.container {
     min-height: 100%;

Updated Fiddle

Bonus:
To keep the content all visible you can use padding on the container = to the height of your footer and header:
    .container {
        min-height: 100%;
        background:red;
        width:1280px;
        margin:0 auto;
        position: relative;

        /*Use box-sizing to include the values of the padding on the 100% min-height*/
        box-sizing:border-box;
        /*Padding for bottom and top = to the height of your elements footer-header*/
        padding: 135px 0;
    }

2nd Demo Fiddle
Comment: But text must not be over header and footer :/
Comment: @Nerfair no problem mate let me edit to suit that requirement, I don't see it on the question
Answer: Based on your fiddle you can could try the following:
.container {
    /* height: 100%; - remove this*/
    min-height: 100vh;

   ...
}

Then add appropriate padding to the top and bottom of the content depending on the height of your header and footer.
Answer: .container {
  min-height: 100%;
}
.content {
  padding-top: 135px; // height of the header
  padding-bottom: 135px; // height of the footer
}

JSFiddle


How to install Software package on windows vps?

Question: I have installed 3 vps on my windows machine. now i want different software on every vps. so do i install all software on main machine on which i installed vps or should i login in all vps one by one and install software separately? is there any other way by which i install all software on main server machine and allocate them to VPS?
thank you...
Comment: 1) Ensure the installers are accessible to your VPS 2) Remote desktop into your VPS 3) Run the aforementioned installers 4) Profit!
Comment: I fear that this is incoherent, as it stands.  Typically one runs installers on whatever machine they are installing software on; there is no procedure, nor is any warranted.  If you encounter some problem besides extreme disorientation, feel free to ask about it.
Answer: From the viewpoint of installing software, a virtual machine is just like the real thing, you need to install software from inside the virtual machine.


high event processing in twisted

Question: I need to write an app that can receive, process, and then send events at ~15k Events Per Second (EPS).  I've been learning twisted and have been using it to benchmark some tests:
Twisted RX only = ~90K EPS
Twisted RX and TX = ~45K EPS (basically half of RX only)
Twisted RX, processing, and TX = ~6K EPS (close, but not 15K EPS)

The processing portion is mostly a single regex matches condition - a task that is CPU-bound.  I tried using threads.deferToThread and callbacks but, as expected, didn't improve the CPU-bound processing.
My server has 256 cores and I'd love to be able to put them to use while using twisted.  Can I wrap multiprocessing in with twisted?  Each process needs to share a dict, so I'd have to use multiprocessing.Manager().
Can multiprocessing be done within twisted?  Is there a faster way run CPU-heavy tasks (regex expressions) in parallel within twisted?
Comment: See this question: http://stackoverflow.com/questions/5715217/mix-python-twisted-with-multiprocessing. The accepted answer is from the founder of twisted, so he's a fairly the authoritative source.
Comment: related: "[Powerhose](http://powerhose.readthedocs.org/en/latest/) turns your CPU-bound tasks into I/O-bound tasks so your Python applications are easier to scale." (I like the quote: it applies to twisted too)
Comment: [`regex` module (drop in `re` replacement)](https://pypi.python.org/pypi/regex/) can release GIL. You could try it with `deferToThread` and see whether it improves things.
Comment: @J.F.Sebastian - good idea with the `regex` replacement - my results shows that it is actually slower than standard `re`.  3484 EPS using `regex` and concurrent=True, 6414 EPS using `re`.  Thanks for the suggestion though, I'll play with it a little more to see if I squeeze any more efficiency out of my regular expression.
Answer: Like the commenter, I would point at Glyph's answer for the multiprocessing question.
With that you could spawn off a fleet of blocking regex matching processes and communicate with them via the childFDs IProcessProtocol.childDataReceived and IProcessTransport.writeToChild methods.
This would let your twisted reactor continue to run at full speed and should get you a lot closer to your non-processing numbers (minus the cpu time for managing the extra file descriptors (though that should be tiny as compared letting the regex block the reactor))

high event processing in twisted


How can I make a response cachable by browsers?

Question: I am working on a Drupal Controller implementation that would return a generated image as response. I used Symfony's Response and I was trying to add ETag header to it:
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class MyController extends ControllerBase {

  public static function viewGraph(string $id, Request $request) {
    $response = new Response();
    $response->setEtag($etag); // some etag genrated from $id
    if ($response->isNotModified($request)) {
      return $response;
    }
    // ...
    return $response;
  }

}

I expected to see the "ETag" header in my response. But there is nothing. I've even tried CacheableResponse and it didn't work as well.
What's wrong with my approach? What is the right approach to it?
Comment: Is `$etag` being converted to `md5`? From symfony's docs `$response->setEtag(md5($response->getContent()));`.
Comment: I'm using the [hash](https://api.drupal.org/api/drupal/vendor%21guzzlehttp%21psr7%21src%21functions.php/function/hash/8.3.x) for `$etag`. I think the specification only needed it to be string, not specifically md5.
Comment: And the problem is not generating the etag, but to actually get etag header in the browser ersponse.
Comment: Keep in mind that some server config will strip etags, eg `Header unset ETag` and `FileETag None` in an Apache .conf.
Answer: FinishResponseSubscriber overwrites the ETag header, unless your response meets certain conditions. That is it has to be cacheable and provides a custom Cache-Control header. When testing the code make sure you have browser caching enabled (in the performance settings).
Example:
  public function view() {
    $response = new CacheableResponse();
    $response->headers->set('Cache-Control', 'public, max-age=60');
    $response->setEtag('123');
    return $response;
  }

Besides browser caching you might also want to set Drupal caching data to invalidate the cached response when the content becomes outdated, see for example Invalidate cache on a REST endpoint.
Comment: I have already switched on the browser caching option. But I still don't see the eTag. How do my controller response meet the "certain condition"?
Comment: Still unable to cache on browser after all these. Is there an easy way to debug the cache header generation process?
Comment: You can debug the response handling by setting a breakpoint in FinishResponseSubscriber::onRespond
Answer: Thanks to 4k4's answer. I took a deeper dive into the issue. Here is something that might benefits others who want to do the same thing.
ETag Header Setting
The class FinishResponseSubscriber will check if response is cacheable. If it is, you're good to go. Then it will also check if the response is customized by checking if you have setup "Cache-Control" header to "public":

If it is "customized", it will assume you have properly setup your header yourself.
If not it will call setResponseCacheable and rewrites the ETag header with whatever timestamp it think is suitable (either your "Last-Modified" header value or the request time).

Customized Header
As 4k4 pointed out, you can achieve the ETag setup by this:

use Drupal\Core\Cache\CacheableResponse;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;

class MyController extends ControllerBase {

  public static function viewGraph(string $id, Request $request) {
    // ... generate $etag
    $response = new CacheableResponse();
    $response
      ->setPublic()
      ->setMaxAge(60)
      ->setEtag($etag);
    if ($response->isNotModified($request)) {
      return $response;
    }
    return $response;
  }

}

Hands off to Drupal

use Drupal\Core\Cache\CacheableResponse;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;

class MyController extends ControllerBase {

  public static function viewGraph(string $id, Request $request) {
    // ... get $last_modified
    $response = new CacheableResponse();
    $response->setLastModified($last_modified);
    if ($response->isNotModified($request)) {
      return $response;
    }
    return $response;
  }

}

Similarly, if it found that the response is not cacheable, it would call FinishResponseSubscriber::setResponseNotCacheable and unset ETag header.
So unless you were to override FinishResponseSubscriber somehow, you can only stick with the ETag generated by Drupal.
And the ETag header will be generated by your Last-Modified header automatically.
Wait, there's more...
Oh right. Even you got the header right, it does not mean your response is cacheable! It's because that cache header is not the only requirement for you to see ETag and have browser cache.
As of Drupal 8.7, to have a cached response, the FinishResponseSubscriber checks both the request and response to see if both are cacheable.
The below points are the extra criterias for browser cache to work.
Setup Browser Cache Max Age
As 4k4 mentioned, you need to setup the browser / proxy cache maximum age to a non-zero value in order to have any browser cache. The setting is in "Home > Administration > Configuration > Development > Performance".
Make sure your Request is cacheable
The request, unless otherwise configured / programmed, will be checked by DefaultRequestPolicy, which contains 2 rules:

Drupal\Core\PageCache\RequestPolicy\CommandLineOrUnsafeMethod
Denies cache if Drupal is run in CLI or by unsafe method (i.e. request method is neither GET nor HEAD); and
Drupal\Core\PageCache\RequestPolicy\NoSessionOpen
Denies cache if the Drupal user has a login session.

Make sure your Response is also cacheable
The response cache policy in my installation includes these rules:

Drupal\Core\PageCache\ResponsePolicy\KillSwitch
A policy evaluating to static::DENY when the kill switch was triggered.
Drupal\Core\PageCache\ResponsePolicy\DenyNoCacheRoutes
Cache policy for routes with the 'no_cache' option set.
This policy rule denies caching of responses generated for routes that have the 'no_cache' option set to TRUE.
Drupal\Core\PageCache\ResponsePolicy\NoServerError
A policy denying caching of a server error (HTTP 5xx) responses.
Drupal\image\PageCache\DenyPrivateImageStyleDownload
Cache policy for image preview page.
This policy rule denies caching of responses generated by the entity.image.preview route.
Drupal\node\PageCache\DenyNodePreview
Cache policy for node preview page.
This policy rule denies caching of responses generated by the entity.node.preview route.

Besides, your Response object would also need to implement the CacheableResponseInterface. The simplest way to implement it would be to use the CacheableResponse class
Summary
To summarize. For a custom controller to have browser cache, you need to meet these criteria:

The controller method of the endpoint needs to return an object that implements the CacheableResponseInterface (e.g. a CacheableResponse instance)
Have correct cache header setup.
Have non-zero cache's maximum age.
Have the browser / client calling the controller's endpoint with GET or HEAD method.
Make sure no kill switch nor error is trigger during the rendering process.
The route does not match the preview page of node or image.

When the criterias are met, the ETag setup would be effective.

Update: Correct my "You cannot set ETag" claim. Thanks 4k4 for correcting me.
Comment: **You can set your own ETag header** when you set at the same time a custom Cache-Control header, see the code example in my answer and https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21EventSubscriber%21FinishResponseSubscriber.php/function/FinishResponseSubscriber%3A%3AisCacheControlCustomized/8.7.x


Monitor status of a command I spawn using Popen

Question: I use Popen() to spawn a program? That program will display 'text' at the program?
How can I monitor status of my program I spawn? How can I determine if there is nothing print out for 1 min, i assume the program is hang and I need to kill the process 'p'?
# command is my command to run
p = subprocess.Popen(command,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT)

Comment: provide custom pipes to `stdout=` and `stdout=` and read from it for program output.
Comment: http://docs.python.org/2/library/subprocess.html#subprocess.Popen
Comment: oops, I meant this one http://docs.python.org/2/library/subprocess.html#popen-objects
Comment: you can monitor status of process by psutil
Answer: This is largely based on Non-blocking read on a subprocess.PIPE in python
We use a separate thread and Queue to check for output after a certain amount of time, given in the q.get(timeout=5) portion. Change it to 60 if you only want to kill the process after 60 seconds. Change the first argument to subprocess.Popen to an appropriate command you want to run.
import Queue
import subprocess
import threading

def checkStdout(p, q):
    s = p.stdout.read(1)
    if len(s) > 0:
        q.put(s)

def run():
    p = subprocess.Popen(['cat'], stdout=subprocess.PIPE, close_fds=True)
    print 'pid %d started' % p.pid
    q = Queue.Queue()
    t = threading.Thread(target=checkStdout, args=(p, q))
    t.daemon = True
    t.start()
    try:
        canGet = q.get(timeout=5)
        print 'has output'
    except Queue.Empty:
        print 'no output'
        # kill process
        p.kill()

if __name__ == '__main__':
    run()

Comment: Thanks. I tired this in my script. I see 'has output'. But then the function run just return without waiting for p (the process running my command (replace your 'cat' in your example) to finish.
Comment: Try adding a `p.communicate()` after the `print 'has output'`, I think that will wait for the process to terminate. http://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate