How to rescale x axis using the crossfilter?

Question: First, sorry for my English.
I'm learning dc.js.
I have 3 charts(1 composite chart, 1 line chart and 1 bar chart).
When I control the brush of the bar chart, I want to rescale the X axis of the other 2 charts.
Use event trigger?
Image here
var temperatureChart;
var windSpeedChart;
var dateChart;

var init = function() {
temperatureChart = dc.compositeChart("#temperature-chart");
windSpeedChart = dc.lineChart("#windspeed-chart");
dateChart = dc.barChart("#date-chart");

d3.json(jsonUrl, function(error, result) {
    var dateFormat = d3.time.format("%Y-%m-%d %H:%M");
    var numberFormat = d3.format(".2f");
    var data = result.result.data[0];

    data.forEach(function(e) {
        e.observeDate = dateFormat.parse(e.observeDate);
    });

    var ndx = crossfilter(data),
    all = ndx.groupAll();
    dimension1 = ndx.dimension(function(d) {return d.observeDate;}),
    dimension2 = ndx.dimension(function(d) {return d.observeDate;}),
    dimension3 = ndx.dimension(function(d) {return d.observeDate;}),
    temperatureGroup = dimension1.group().reduceSum(function(d) {return d.temperature;}),
    windSpeedGroup = dimension2.group().reduceSum(function(d) {return d.windSpeed;}),
    dateGroup = dimension3.group();

    var scaleMin = d3.min(data, function(d){
        return d.observeDate;
    });
    var scaleMax = d3.max(data, function(d){
        return d.observeDate;
    });

    var width = 1000, height = 300;
    var margin = {top: 30, right: 50, bottom: 25, left: 40};

    temperatureChart
    .width(width)
    .height(height)
    .transitionDuration(1000)
    .margins(margin)
    .dimension(dimension1)
    .xUnits(d3.time.hours)
    .elasticY(true)
    .elasticX(true)
    .mouseZoomable(true)
    .renderHorizontalGridLines(true)
    .x(d3.time.scale().domain([scaleMin, scaleMax]))
    .brushOn(false)
    .renderlet(function(c) {
        var canvas = (c.g()).append("g").attr("transform", "translate("+margin.left+","+margin.top+")").attr("pointer-events", "all");
        var crossHair = canvas.append("g").attr("class", "crosshair");

        crossHair.append("line").attr("id", "h_crosshair")
            .attr("x1", 0)
            .attr("y1", 0)
            .attr("x2", 0)
            .attr("y2", 0)
            .style("stroke", "gray")
            .style("stroke-width", "1px")
            .style("stroke-dasharray", "5,5")
            .style("display", "none");

        crossHair.append("line").attr("id", "v_crosshair")
            .attr("x1", 0)
            .attr("y1", 0)
            .attr("x2", 0)
            .attr("y2", 0)
            .style("stroke", "gray")
            .style("stroke-width", "1px")
            .style("stroke-dasharray", "5,5")
            .style("display", "none");

        crossHair.append("text").attr("id", "crosshair_text")
            .style("font-size", "10px")
            .style("stroke", "gray")
            .style("stroke-width", "0.5px");

        canvas.on("mousemove", function() {
            addCrossHair(d3.mouse(this)[0], d3.mouse(this)[1]);
        }).on("mouseover", function() {
            d3.selectAll("#v_crosshair").style("display", "block");
            c.selectAll("#h_crosshair").style("display", "block");
        }).on("mouseout", function() {
            d3.selectAll("#v_crosshair").style("display", "none");
            c.selectAll("#h_crosshair").style("display", "none");
        }).append("rect")
          .style("visibility", "hidden")
          .attr("x", 0)
          .attr("y", 0)
          .attr("width", width - margin.left - margin.right)
          .attr("height", height - margin.top - margin.bottom);

        function addCrossHair(x, y) {
            c.selectAll("#h_crosshair")
                .attr("x1", 0)
                .attr("y1", y)
                .attr("x2", c.xAxisLength())
                .attr("y2", y)
                .style("display", "block");

            d3.selectAll("#v_crosshair")
                .attr("x1", x)
                .attr("y1", 0)
                .attr("x2", x)
                .attr("y2", c.yAxisHeight())
                .style("display", "block");

        }
    })
    .compose([
        dc.lineChart(temperatureChart)
                .dotRadius(5)
                .group(temperatureGroup)
    ]);

    windSpeedChart
    .width(width)
    .height(height)
    .transitionDuration(1000)
    .margins(margin)
    .dimension(dimension2)
    .xUnits(d3.time.hours)
    .elasticY(true)
    .elasticX(true)
    .mouseZoomable(true)
    .renderHorizontalGridLines(true)
    .x(d3.time.scale().domain([scaleMin, scaleMax]))
    .brushOn(false)
    .group(windSpeedGroup)
    .renderlet(function(c) {
        var canvas = (c.g()).append("g").attr("transform", "translate("+margin.left+","+margin.top+")").attr("pointer-events", "all");
        var crossHair = canvas.append("g").attr("class", "crosshair");

        crossHair.append("line").attr("id", "h_crosshair")
            .attr("x1", 0)
            .attr("y1", 0)
            .attr("x2", 0)
            .attr("y2", 0)
            .style("stroke", "gray")
            .style("stroke-width", "1px")
            .style("stroke-dasharray", "5,5")
            .style("display", "none");

        crossHair.append("line").attr("id", "v_crosshair")
            .attr("x1", 0)
            .attr("y1", 0)
            .attr("x2", 0)
            .attr("y2", 0)
            .style("stroke", "gray")
            .style("stroke-width", "1px")
            .style("stroke-dasharray", "5,5")
            .style("display", "none");

        crossHair.append("text").attr("id", "crosshair_text")
            .style("font-size", "10px")
            .style("stroke", "gray")
            .style("stroke-width", "0.5px");

        var bisectDate = d3.bisector(function(d) {
            return d.observeDate;
        }).right;

        canvas.on("mousemove", function() {
            addCrossHair(d3.mouse(this)[0], d3.mouse(this)[1]);
        }).on("mouseover", function() {
            d3.selectAll("#v_crosshair").style("display", "block");
            c.selectAll("#h_crosshair").style("display", "block");
        }).on("mouseout", function() {
            d3.selectAll("#v_crosshair").style("display", "none");
            c.selectAll("#h_crosshair").style("display", "none");
        }).append("rect")
          .style("visibility", "hidden")
          .attr("x", 0)
          .attr("y", 0)
          .attr("width", width - margin.left - margin.right)
          .attr("height", height - margin.top - margin.bottom);

        c.xAxis().scale();

        function addCrossHair(x, y) {
            c.select("#h_crosshair")
                .attr("x1", 0)
                .attr("y1", y)
                .attr("x2", c.xAxisLength())
                .attr("y2", y)
                .style("display", "block");

            d3.selectAll("#v_crosshair")
                .attr("x1", x)
                .attr("y1", 0)
                .attr("x2", x)
                .attr("y2", c.yAxisHeight())
                .style("display", "block");

        }
    });

    dateChart
     .width(width)
     .height(50)
     .margins({top: 0, right: 50, bottom: 20, left: 40})
     .xUnits(d3.time.hours)
     .x(d3.time.scale().domain([scaleMin, scaleMax]))
     .centerBar(true)
     .brushOn(true)
     .dimension(dimension3)
     .group(dateGroup).yAxis().ticks(0);

    dateChart.on("filtered", function(c) {
        if(c.filter())
            dc.events.trigger(function() {
                        // Any code here?
            });
    });
    dc.renderAll();
});

Answer: Do you mean the "range / focus chart" functionality that can be seen in the last "monthly abs volume & move" chart on the main dc.js page?
If so, here is the documentation:
https://github.com/dc-js/dc.js/blob/develop/web/docs/api-latest.md#dc.coordinateGridMixin+rangeChart
It is a very simple feature and not fully documented, so please ask if you have any questions.
EDIT: noticed that you are talking about multiple "focus charts" for one "range chart". That's not built-in, but it's covered in this Q/A:
https://stackoverflow.com/a/27725811/676195
Answer: For reference, my understanding of the question was that you want to automatically rescale the Y axis depending on the changing range of values and I found that the following worked for me:
chart.elasticY(true);


Personalização CSS com jQuery

Question:
Eu estou num desenvolvimento de um site e precisava de um help numa questão:
Eu estou fazendo 6 cards com alguns títulos e quando eu clico sobre um card, ele faz uma requisição Ajax busca algumas informações do serviço logo abaixo do card especifico. Esse é só uma breve explicação.
O negócio é que quero usar dentro dessa requisição Ajax, no Success , uma modificação de CSS e não estou conseguindo pensar em uma boa forma de informar o elemento que deverá ser modificado
Primeiro, segue o código HTML + CSS que usei para desenvolver os cards:

                            Logística

                            Comercial

E aqui vai o script Javascript que eu estou usando para buscar informações adicionais lá no banco de dados e voltar ela de forma assincrona no response-content:

Então, a linha $().css({backgroundColor: '#663399'}); é o que eu preciso saber.
A pergunta é: Quando eu clicar em um card e for retornado o resultado, eu quero que a tag  obtenha um background #663399 mas apenas quando estiver ativo, mas como posso especificar isso para exatamente aquele card, sabendo que quando eu clico sobre o elemento, é a tag  que é identificada e ativada. Como passo isso ali?
O link da página é esse caso queiram olhar o projeto todo, no contexto inteiro: http://hecato.com/sistema/info/consultores.php
Precisando de outras informações é só informar abaixo e acho que passei todas as info importantes. Obrigado aos que ajudarem.
Answer: Como o  objetivo é selecionar apenas a tag i, no seu success você pode fazer assim:

$('a[data-consult-id]').click(function(){
    //use isso para zerar o background dos outros, deixano    selecionado apenas o que você clicou
    $('a[data-consult-id] .element div').children('i').css("background-color", "");

    //mudando a cor
    $('.element div',this).children('i').css("background-color", "#663399");

    //Para ter certeza que é o icone que esta sendo selecionado
    console.log($('.element div',this).children('i').html());
})
.element {
                    box-shadow: 0 8px 50px -6px rgba(84,84,120,.26);
                    padding: 40px 20px 20px;
                    position: relative;
                    background: #fff;
                    cursor: pointer;
                }
                .element h4 {
                    color: #3c9890;
                    font-size: 20px
                }
                .element:hover div i{
                    background: rebeccapurple !important;
                    -webkit-transition: all .5s ease-in-out;
                    -moz-transition: all .5s ease-in-out;
                    -ms-transition: all .5s ease-in-out;
                    -o-transition: all .5s ease-in-out;
                    transition: all .5s ease-in-out;
                }
                .element:hover h4{
                    color: #9e6bd2 !important;
                    transition: all .5s ease-in-out;
                }

                .ti-icone {
                    background: #35b1a6;

                    width: 80px;
                    height: 80px;
                    display: inline-block;
                    line-height: 80px;
                    text-align: center;
                    color: #fff;
                    font-size: 28px;
                    border-radius: 50%;
                }

                            ◘

                            Logística

                            ◘

                            Comercial

Comment: Creio que seja por conta do `this`. Declare uma variável no início, abaixo da sua `consult_id` assim: `var obj = $(this)` e ao invés de usar o `this`, usa assim: `$('.element div',obj).children('i').css("background-color", "#663399");`
Comment: Opa @Jorge.M, cara eu fiz como mostrou ali, mas mesmo assim não está funcionando. É por conta do Ajax sendo feito. :/ Eu tirei a chamada e ele funcionou perfeitamente, será que teria uma forma de resolver isso. Eu não sei na vdd pq nao funciona estando dentro de um success, já que as especificações estão todas corretas :c
Comment: Mano, eu consegui fazer adaptando algumas coisas só, isto é, eu coloquei fora do success, antes da requisição e troquei o .css por um .toggleClass que resolve bastante o problema. Não solucionou totalmente o problema, mas já ajudou muito. Você sabe porque não funcionou dentro do Success? é algum problema com o children na hora de encontrar o elemento?
Comment: Mesmo assim mano, vlw, vou marcaar a sua como correta. Aguardo retorno :)
Comment: Legal, nossa... Valeu mesmo mano. Eu preciso de mais uma ajudinha. Se quiser responder essa rsrs vai me ajudar bastante: Tipo, se acessar o site que coloquei na pergunta, vai ter os cards e quando clico sobre um deles, ele realiza a requisição e aplica a mudança de cor quando ativo, para isso usei o slideToggle() no retorno da requisição (success) e junto com isso uma funcao para modificar a tag  adicionando uma classe. Mas quando eu seleciono outro card tendo um já aberto, ele fecha o resultado ( (response).html(data) ) mas mantem as classes inseridas com o toggleClass em ambos os cards.
Comment: @LougansdeMatos, recomendo abrir outra pergunta, coloque exemplos e explique qual o resultado você deseja chegar. Tentarei ajudar :D
Comment: Blz :) Obrigado!
Comment: aqui está o link da nova pergunta. Eu repeti algumas coisas que achei relevante e expressei bem mais a natureza da minha pergunta, segue: https://pt.stackoverflow.com/questions/347048/slidetoggle-configura%C3%A7%C3%A3o-em-aberto-e-fechado-jquery

Personalização CSS com jQuery


Generic that implements an interface or is a double?

Question: Say I have this generic class:
abstract class Foo<T> where T : IBar

This is fine up to here, however I would like to also be able to pass double as well. Now I have been told that this is a bad idea and that the only way to solve this problem is to write a duplicate class handling the double case. I have also been told that toying with primitive types like this is not a good idea.
What I thought about doing was wrapping double in a class that implements IBar. This would allow me to use the wrapped double. I can for see some problems with usage of the class and I have again been told that wrapping primitive types for these kinds of purposes is a bad idea.

What would be a good way to go around this?
Is it time for me to reconsider using doubles?
Should I just go with creating a separate duplicate class to handle doubles? (in my opinion this sounds as if I am not reusing).
What is the rule of thumb (if there is one) when having to deal with primitives in a generic way?

The structs that are catagorised are double which we know of and a BigRational struct. This is a representation of a quotient between two System.Numerics.BigInteger members. Arithmetic is fully defined on this struct and what Foo is doing with T should be defined for double and BigRational.
Now the apposing reason is that these are unrelated and therefore it is bad practice to create an interface to unite them (not to mention wrapping the primitive in the first place).
My idea for the IBar interface was to have arithmetic as a requirement. Now in the future if I attempt to use Foo for other classes/structs that implement IBar it should be fine. But I want double to work as well. So now what I am looking for is a good reason to even wrap double in the first place and how this would coincide with good practice.
Answer: I would consider wrapping double in a struct rather than a class.
There's no way of saying "T must either be double or implement IBar" but wrapping a primitive value in a struct is entirely reasonable (assuming it actually makes sense for the meaning of IBar; we don't know anything about it at the moment).
Comment: @Alizter: When someone says not to do something that feels natural, demand an explanation. You shouldn't do things just because you've been told not to - that just propagates myths. (It's entirely possible that the person telling you not to has misunderstood something, for example.)
Comment: I have been told (again) that it would be *bad practice* to create and interface `IBar` solely for the purpose of categorizing problematically unrelated classes/structs especially `double`. Now the reason I would like to do this in the first place is because intuitively they are similar. I shall add to the question giving more details.
Comment: The explanation I received: "There is a fundamental difference between `double` and `BigRational` [See OP]. A double adds two doubles and returns a double a BigRational adds two BigRationals and returns a BigRational. An interface relating the two cannot be done as they return different things. This is the flaw."
Comment: @Alizter: Well that sounds like you want to make the interface generic as well. Then it could be `IAddable` with a member of `T Add(T lhs, T rhs)`. Then your `double` wrapper would implement `IAddable` and your `BigRational` struct would implement `IAddable`. They can still return different things with no issues.
Comment: It is all working. Thank you very much! However the struct wrapper for `double` felt a bit unstable (I don't know) so I stuck with a class.


Receive custom XMPP stanzas with Smack

Question: I am trying to receive XMPP custom stanzas inside a message packet. For instance,
<message ...>
    <custom_stanza>
        <foo>wololo</foo>
        <bar>haiooh</bar>
    </custom_stanza>
    ...
</message>

The point is that I know I will receive a "custom_stanza" stanza but I do not know about the names of the tags "foo" and "bar", and I need to retrieve the data inside them.
I have used an EmbeddedExtensionProvider subclass which gives me the names of "foo" and "bar" but  I am not able to retrieve "wololo" nor "haiooh". How can I achieve this?
Cheers,
Answer: If you use PacketExtension to send custom stanzas, as this thread explained: https://stackoverflow.com/a/6390037/474002
Then, you could use smack api Packet.getExtensions as the document: http://www.igniterealtime.org/builds/smack/docs/latest/javadoc/org/jivesoftware/smack/packet/Packet.html#getExtensions()
Hope this will help ~

Receive custom XMPP stanzas with Smack


Compact union of images of equicontinuous family

Question: Suppose $\{f_n, n = 1, 2, \dots\}$ is an equicontinuous family of real-valued functions on a compact metric space $(X, d)$. What are some appropriate conditions ensuring that $\cup_{n = 1}^\infty f_n(X)$ is compact? In particular, is it enough that $\sup_n \sup_x \vert f_n(x)\vert \leq M$ for some constant $M< \infty$?
Answer: Hint: Let $X=[0,1]$ and let $f_n(x) = 1/n + (1-1/n)x.$ What is $\cup\, f_n(X)?$
Answer: No (as zhw.'s hint should allude), to have that the set $\underset{n \in \mathbb{N}}{\cup}\, f_n(X) \subseteq \mathbb{R}$ is compact it is insufficient to merely assume that $\mathscr{F}=\{\, f_n:X \to \mathbb{R} : n \in \mathbb{N}\}$ is a uniformly bounded equicontinuous family of functions on a compact metric space $(X,d)$.
If $(X,d)$ is a compact metric space and $\mathscr{F}=\{\, f_n : n \in \mathbb{N}\}$ is an equicontinuous family of real-valued functions on $X$, then $\underset{n \in \mathbb{N}}{\bigcup} f_n(X)$ is a compact subset of $\mathbb{R}$ if and only if $\mathscr{F}$ is closed and bounded in $C(X)$ (the set of continuous real-valued functions on $X$) with the supremum metric $\rho(\, f, g)= \underset{x \in X}{\sup} |\, f(x)-g(x)|$.
Sticking with $X=[0,1]$, another example to consider is the sequence of real-valued functions on $X$ $\{g_n\}_{n=1}^\infty$ such that $g_n(x)=x+\frac{1}{n}$ ($n=1,2,\ldots$).


Check all apenas seleciona o primeiro valor do foreach

Question: Boas pessoal, tenho o seguinte codigo, e era suposto ele selecionar todos os valores dentro do foreach, mas em vez de o fazer apenas seleciona o primeiro valor..
Ja tentei fazer um teste de o submit que deleta as cenas so aparecer quando se clica nas checkboxes, mas acontece a mesma coisa, so aparecia se seleccionasse a primeira. Mas se seleccionasse a primeira e mais umas quantas ele apagava na mesma, mas apenas aparecia se a primeira estivesse seleccionada..
<form action="" method="post">
<? foreach($itens as $myrow){ ?>
<a href="pagina.php?ID=<? echo $myrow['ID']; ?>"><? echo $myrow['Title']; ?>

<? echo $myrow['GDate']; ?>
?>
<? echo $myrow['Hour']; ?>

<input name="selector[]" id="testecb" type="checkbox" value="<?php echo $myrow['ID']; ?>" />

<?}?>
<input type="button" id="selectall-game-button" label="check all" value="Selecionar tudo"
><input type="submit" id="delete-game-button" value="Eliminar" />

<?
****************** AQUI ESTA A ACÇÃO QUE DELETA.. **************
}
} ?>

JS:
$('#selectall-game-button').click(function(){
        var chk = $(this).click('checked')?true:false;
        $('#testecb').attr('checked',chk);
});

Alguém tem alguma odeia o porque de isto acontecer? :ss
Comment: `$(this).click('checked')?true:false;` devia ser `.attr()` em vez de `.click()`...
Comment: Na verdade podias simplificar para `$('#testecb').attr('checked', this.checked);` somente.
Comment: @Sergio Poderia, mas isso não não alteraria em nada o estado do checkbox :)
Comment: Sim, porque quero que selecione tudo quando clico no botao ..
Comment: Comece dando um ID diferente para cada checkbox, você não pode repetir IDs no HTML. Se quiser, também pode colocar uma mesma classe em todos para selecionar com mais facilidade no jQuery (mas isso não elimina a necessidade dos IDs únicos).
Answer: Tens dois problemas: IDs multiplas e um erro no JS.
#1 - Não podes usar IDs multiplas neste caso. Classes de CSS é a solução. Isto porque o seletor $('#testecb') vai somente retornar o primeiro elemento que encontrar. sugiro usares $('.dashed-line input')
#2 - No JS tens $(this).click('checked') mas esse elemento é um input e não tem checked. Imagino então que esse input type="button" deva checkar todos os checkboxs...
Assim uma sugestão seria:
$('#selectall-game-button').click(function(){
    $('[name="selector[]"]').prop('checked', true);
});

Repara que esta solução não corrige as IDs multiplas que estás a gerar no PHP. Para corrigir isso podias usar no PHP:

<input name="selector[]" class="testecb" type="checkbox" value="<?php echo $myrow['ID']; ?>" />

e então o seletor já podia ser $('.testecb').prop('checked', true);
Comment: Desculpe, esqueci-me completamente ! Mais uma vez obrigado por toda a paciencia e por me ter ajudado a resolver isto !
Comment: Agora nao seleciona nada..
Comment: O que eu quero é selecionar TODAS as checkbox's..
Comment: @thecreator `$('name="selector[]"').prop('checked', this.checked);` faz isso mesmo. Se não estiver a funcionar cria um jsFiddle com o HTML renderizado para ver o teu HTML todo.
Comment: http://jsfiddle.net/262z0jdp/1/
Comment: @thecreator eu pensava que querias selecionar/des-selecionar tudo dependente de uma outra checkbox estar checkada ou não. Se é só um botão que seleciona todas então é mais simple... http://jsfiddle.net/262z0jdp/2/
Comment: E se este botão tiver que des-selecionar também? é possivel fazer? E o botão delete so aparecer quando Alguma checkbox estiver selecionada.. Se me conseguisse ajudar nisso eu agradecia!
Comment: @thecreator pois, essa era mais ou menos a ideia inicial. Algo assim por exemplo: http://jsfiddle.net/262z0jdp/3/
Comment: Mas ai o botao de deletar esta sempre visivel, como faço para ficar visivel apenas quando 1 ou mais checkbox estiverem selecionadas?
Comment: @thecreator nesse exemplo a ideia é usar o checkbox para selecionar __e__ para de-selecionar, clicando de novo nele.
Comment: Nao é possivel fazer isto sem ser em checkbox? o selecionar e des-selecionar? Ex: type="button"
Comment: @thecreator sim, é. Queres 3 botões ou só dois? o "Elemminar" é o que de-seleciona?
Comment: Passo a explicar.. Gostaria que o Botao "Selecionar" Fosse mesmo um botão (type="button") e que selecionasse e des-selecionasse. E o botao ELIMINAR só aparecia quando 1 ou mais checkbox's estivessem selecionados..
Comment: @thecreator ok, estou a ver. Então queres algo assim: http://jsfiddle.net/xges18jq/ O "Elemninar" devia estar escondido no CSS no inicio... sabes como fazer isso?
Comment: Siim, `display:none;` Obrigado!
Comment: @thecreator se quiseres podes marcar a resposta como aceite.


How to take a string, search for a certain character, and return a string with everything before the character?

Question: I'm a bit new to programming, and for an in class project, I have to take a user-inputted email, find everything before the @ symbol, and return it as a username. The part I'm having trouble on is finding the characters before the @, with it being variable length. As far as I can tell, most methods rely on a preset string length.
My current code
Comment: Please do not post a picture of code. It's hard to read and prevents our sight impaired users from participating.  Also it cannot be searched or copied into a text editor.  Consider editing your question and pasting the code directly into it as text.
Comment: I would suggest using two methods of the String class, `indexOf` and `substring`.  Use `indexOf` to find the position of the `@` character, and then `substring` to grab just the first portion of the string based on that position. Since you're processing user input you'll want to allow for the case where the user didn't enter a valid email address and so `indexOf('@')` returns `-1`.  Your code will throw an exception if you blindy try to use that value.
Answer: Read the javadoc of String. Of particular interest are substring and indexOf. It's.. a trivial assignment, there's nothing left to say except spoonfeed you the answer, which probably doesn't help you accomplish the goal (which is, surely, to learn java).
Comment: Ha!  Were we on the same page, or what?!?!


My array isn't generated correctly in php

Question: I have a problem with my array. Somehow it doesn't understand where my array is. I tried with the following code:
<code>while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $pers_inventar = array();

    $pers_id = $row['pers_id'];
    $pers_person = array('birthday' => $row['pers_birthday'],'lastname' => $row['pers_lastname'],'firstname' => $row['pers_firstname'],'job' => $row['pers_job']);
    $pers_inventar[$pers_id][] = $pers_person;
}
</code>
Maybe my function is wrong. Thanks for any help
Comment: Remove `$pers_inventar = array();` from the loop.
Answer: The problem is you clear your array every iteration. Put your array declaration before the loop.
<code>$pers_inventar = array();

while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $pers_id = $row['pers_id'];
    $pers_person = array('birthday' => $row['pers_birthday'],'lastname' => $row['pers_lastname'],'firstname' => $row['pers_firstname'],'job' => $row['pers_job']);
    $pers_inventar[$pers_id][] = $pers_person;
}
</code>
Answer: You could try it like this:
<code>$pers_inventar = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
              $pers_id = $row['pers_id'];
              $pers_person = array('birthday' => $row['pers_birthday'],'lastname' => $row['pers_lastname'],'firstname' => $row['pers_firstname'],'job' => $row['pers_job']);
              $pers_inventar[$pers_id][] = $pers_person;
        }
</code>
The best is, when you add an empty array first and then go into your while loop.
Another suggestion:
Why do you create an array to put in your "pers_id" array?
Why don't you just create your "pers_id" array and add the information right in there.
Comment: That worked perfectly. And thanks for the suggestion. I will try it with another array creation script. But the main problem is solved with this. THANKS!


ng-model - bind to dynamic field in object

Question: I have this code:

          {{c.value}}
          <textarea ng-model="q.newResponse.value['{{c._id}}']"></textarea>

  // ...

What I am trying to do is bind a property on newReponse.value, where that property is dynamic and is the c._id value, so something like:
newResponse.value.44PkfeoakfoAf5o3r3773oZS3a = 'foo bar baz';

This doesn't work as is, and I get this error:
Error: [$parse:syntax] Syntax Error: Token '{' invalid key at column 22 of the expression [q.newResponse.value[{{c._id}}]] starting at [{c._id}}]].
http://errors.angularjs.org/1.6.1/$parse/syntax?p0=%7B&p1=invalid%20key&p2=22&p3=q.newResponse.value%5B%7B%7Bc._id%7D%7D%5D&p4=%7Bc._id%7D%7D%5D
    at angular.js:68
    at AST.throwError (angular.js:14893)
    at AST.object (angular.js:14882)

Is this possible and what is the right way to do this?
Answer: Nevermind, that wasn't so hard -

          {{c.value}}
          <textarea ng-model="q.newResponse.value[c._id]"></textarea>


Query Mysql não retorna erro nem resultado

Question: Tenho 5 tabelas nas quais cada uma delas tem dados que preciso ser exibido agrupado por data. São propostas, agrupadas por data, quantidade de propostas, valor das propostas, mídia, valor investido, quantidade de cliques, código (source_code) e se é negada ou aceita.
o resultado seria mais ou menos esse:
data_proposta | source_code | custo(total por data) | midia | cliques | impressoes | custo | negadas | aceitas

Eu tenho uma tabela chamada proposta, outra mídia (que traz cliques, valor, impressões), precog (valida ou não) e source_code.
Cada proposta é salva em uma nova linha da tabela propostas e essa consulta faz um COUNT() na quantidade de propostas, separar por propostas negadas e aceitas  com um COUNT() tbm.
Traz da tabela mídia a quantidade de cliques, valor do custo agrupado por data com base no source_code.
Estou tentando fazer um select no MySQL e o phpMyAdmin simplesmente não retorna erro nenhum e também não exibe o resultado.
Vejam minha query:
SELECT data_proposta,
       propostas.source_code,
       Sum(midias.custo)             AS custo,
       Count(data_proposta)          AS propostas,
       Sum(IF(precog_fk <> 9, 1, 0)) AS validas
FROM   propostas
       LEFT JOIN midias
              ON `data_proposta` = `midias`.`data`
GROUP  BY data_proposta
LIMIT  0, 1

Comment: Ajudaria também colocar as estruturas das tabelas (ao menos os tipos dos campos que são usados na query).
Comment: tipos dos campos:
data_proposta(datetime), source_code(varchar), custo(decimal(10,2)), precog_fk(int); É isso.
Comment: Troque o `LEFT JOIN` por `OUTER JOIN`
Comment: @Dorathoto já utilizei o outer join e nao aconteceu nada.
Answer: Tente isso abaixo:
SELECT a.data_proposta,
       a.source_code,
       Sum(b.custo)             AS custo,
       Count(a.data_proposta)          AS propostas,
       Sum(IF(precog_fk <> 9, 1, 0)) AS validas
FROM   propostas a, midias b
       a.data_proposta(+) = b.data
GROUP  BY a.data_proposta

Comment: Isto te serviu? @DeBarros
Answer: O problema pode estar no formato do campo da data, como você não passou a estrutura de tabelas, fica difícil identificar o problema, veja se isso resolveria o seu caso:
SELECT DATE_FORMAT(data_proposta, '%d/%m/%Y') as data_proposta,
       propostas.source_code,
       Sum(midias.custo) AS custo,
       Count(DATE_FORMAT(data_proposta, '%Y-%m-%d')) AS propostas,
       Sum(IF(precog_fk <> 9, 1, 0)) AS validas
FROM   propostas
       LEFT JOIN midias
              ON data_proposta = midias.data
               where custo > 0
GROUP  BY data_proposta, propostas.source_code


$10 − 2 + 0.4 - 0.08 + \cdots$· converge or diverge?

Question: Determine whether the following are convergent or divergent. If it is
convergent find its sum. Make sure to fully justify all of your work.
2/10 = 1/5, which happens to be the common ratio. According to geometric series test since r is less than 1 we know it converges.
My problem is, I don't know how to check if r = 1/5, or -1/5.
If its r = -1/5, the sum is 25/3, if its r = 1/5 the sum is 25/2
Comment: here  $r = -1/5.$.
Comment: Alternatively, the value is less than $10$, so it can't be $25/2$.
Comment: the signs alternate so its -1/5
Comment: Think of it as $10+(-2)+0.4+(-0.08)+\cdots$. A geometric series is a sum. Then the ration of the consecutive terms is $-1/5$.
Answer: You need to watch the signs.  The ratio of the first two terms is $\frac {-2}{10}=-\frac 15$.  The ratio of every other pair that we can see is the same.  The signs are important.
Answer: See if you find that difficult or confusing then we can have this way
Approach 1 -
$|r| < 1$ is required for the geometric series to converge implying your series converges and you can find the sum by using $s = \frac{a}{1- r}$ , $a$ is the first term in your series.

In your answer $25/3$ is the correct one , for simple intuition as provided in the comments, the sum cannot exceed 10 so it cannot be $25/2$ so only choice remaining is $25/3$.

Approach 2 -
Another way is this which helps in proving the series is converging. Intuition - If something bigger converges then the smaller thing converges too! (Comparision test for series convergence)-
Better find the absolute value sum and if it converges then surely the given series converges.
see that $10 - 2 + 0.4 - 0.08 + ... <  10 + 2 + 0.4 + 0.08 + ...$
and the right side sum is convergent as it is a geometric series with $r = 0.2$ which is $r < 1$ and hence since absolute series converges , the original series also converges!
hope this helps!


Cumulocity - managedObject Event - detect device first connection

Question: Looking to understand whether there is a a bulletproof event from the namagedObject side of c8y where we know the device has just connected.
I have a microservice that listens for events in real time and I want to trigger a process once we know a device has connected to send its payload.
We have used:
"c8y_Connection": {"status":"CONNECTED"}

We have had the microservice log to Slack all events from managedObjects where we saw for three days the "status":"CONNECTED" value in the payload of our demo devices at reporting times.
But after three days, we see no more this "CONNECTED" state (all payloads showing "DISCONNECTED").
What I am trying to achieve from the inventoryObject event is to understand when a device had connected and sent payload to know when data had arrived. I then go get the data and process it externally. This is post registration and as part of the daily data send cycle for my type of device.
What would be the best way to understand when a device has sent payload in a microservice? I want to notify an external application with either "data is arriving for id 35213" or even better, "data has arrived for device 35213, and here's the $payload".
Answer: Just as a general information ahead:
The c8y_Connection fragment showing connected shows an active MQTT connection or an active long polling connection and it is only evaluated once every minute.
So if the client is just sending data and immediately disconnecting afterwards this might not picked up.
If you want to see the device having send something to Cumulocity maybe the c8y_Availability fragment is a better as it holds the timestamp when the device last send something.
{ "lastMessage": "2022-10-11T14:49:50.201+09:00", "status": "UNAVAILABLE"}

Also here the evaluation (or better the update to database) only happens every minute.
Both c8y_Availability and c8y_Connection however are only generated if the availability monitoring has been activated for the device (by defining a required interval for the device).
So if you have activated the availability monitoring and you see a "lastMessage" you can reliably say that the device has already send something to Cumulocity.
Comment: Hey @TyrManuZ!! Thank you so much!! Your insight is really useful. What I am trying to achieve is to know when a device has connected / finished sending payload. I do this in a microservice in c8y instance. How to confirm that the lastMessage date has changed in the current payload? I cannot find an "events history" to check previous to current event.
Comment: @TheRealPapa that is very tricky. As you already mentioned there is no log of these updates as it would be simply too much traffic on the large scale. There is a push notification on the notification APIs when this availability fragment is updated but the notification itself does not mention what was updated. So such a push notification could also mean that something else in the device object changed


Polynomials can approximate the identity (proof)

Question: From Terence Tao's Analysis II:

I'm having problems with 14.8.2.(c), since it seems like the choice of $N$ depends on $c$ (and vice versa). The only proof I have relies on the convergence of the sequence $\sqrt{n} (1-\delta^2)^n$ to zero, but I don't know if that's even true.
Answer: For $|x|>1$ let $p_n(x)=0.$ For $|x|\le 1$ let $p_n=c_n(1-x^2)^n$ where $c_n\cdot\int_{-1}^1(1-x^2)^ndx=1.$ By 14.8.2.(b) we have $c_n\le \sqrt n\,.$ The idea is to show that $p_n\to 0$ uniformly on $[-1,-\delta]\cup [\delta,1]$ for any fixed $\delta \in (0,1).$ So, given any $\epsilon^*$ in $(0,1)$  we find some "small"  $x_n$ in $(0,1)$ such that $x_n\le |x|\le 1\implies p_n(x)\le\epsilon^*,$ and hope that $x_n\to 0$ as $n\to \infty.$
Since $c_n\le \sqrt n ,$ it would suffice that  $\sqrt n\,(1-x_n^2)^n=\epsilon^*,$ equivalently $$x_n^2= 1-(\epsilon^*/\sqrt n)^{1/n}.$$
We have $x_n\to 0 \iff x_n^2\to 0 \iff (\epsilon^*/\sqrt n)^{1/n}\to 1.$
(i). Let $\epsilon^*=(1+k)^{-1}$. Then $k>0.$ Let $(1+k)^{1/n}=1+k_n.$ Then $k_n> 0.$ By the Binomial Theorem $1+k=(1+k_n)^n\ge 1+nk_n,$ so $k/n\ge k_n>0,$ so $k_n\to 0.$
So $(\epsilon^*)^{1/n}\to 1.$
(ii). Let $n^{1/2n}=1+y_n.$  For $n\ge 2$ we have $y_n>0$ and by the Binomial Theorem $$n=(1+y_n)^{2n}\ge 1+\binom {2n}{1}y_n+\binom {2n}{2}y_n^2> 1+\binom {2n}{2}y_n^2>1+2(n-1)^2y_n,$$ so $n-1>2(n-1)^2y_n^2,$ so $1/\sqrt {2(n-1)}>y_n>0$, so $y_n\to 0.$
So $(\sqrt n )^{1/n}=n^{1/2n}\to 1.$
(iii). Therefore $x_n\to 0.$
In summary, given $\epsilon>0$ and given $0<\delta<1,$ let $\epsilon^*=\min(1/2,\epsilon).$ Now for all  $n$ large enough that $x_n$ (as defined above) is less than $\delta,$ we have $$1\ge |x|\ge \delta \implies 1\ge |x|>x_n\implies 0\le p_n(x)<p_n(x_n)\le \epsilon^*\le \epsilon.$$
Comment: To get $x_n\to 0$ we want $(c_n)^{1/n}\to 1,$ and $c_n$ is small enough that it works.


$E^p$ is a ring, but not a $\sigma$-ring

Question: An interval in $\mathbb{R}^p$ is defined as a set of the form $\{ \vec{x} \in \mathbb{R}^p : \forall i=1,2,...,p \quad a_i \le x_i \le b_i \}$, where the inequalities can be strict or not, and the numbers $a_i,b_i$ are allowed to be infinite. An elementary set is a set which is a union of a finite amount of intervals. The class of all elementary sets is denoted by $E^p$. It is left as a comment in Rudin to verify that $E^p$ is a ring, yet not a $\sigma$-ring, that is a countable union of such sets need not be necessarily elementary. Showing that it's a ring I kind of get (although I don't know if there's a truly simple way of showing that the compliment of an elementary set is elementary), but I'm having trouble thinking up a counterexample to the countable union property...
Answer: It's enough to give a counter-example when $p=1$. Consider $A_n:=(n-1/2,n+1/2)$: the union is not elementary.
Comment: Thanks for the counterexample. How to show that the resulting union $\mathbb{R} \setminus (\mathbb{N}+\frac{1}{2})$ isn't elementary? Try to write a proof by contradiction or is there maybe an immediate way to see this?
Comment: If $A=\bigcup_n A_n$ was elementary, then $A=\bigcup_{i=1}^NI_i$. At least one of these intervals is not bounded (otherwise so would be $A$), and this intervals contains points which are not in $A$.
Answer: I think the most intuitive counterexample for this is given by considering connected components. Note that all intervals (your definition) are connected, and that unioning a set with a connected set can at worst increase the number of connected components by 1.
It follows that finite unions of intervals must have finitely many connected components.
However, it is easy to construct an example of a set in $\mathbb{R}^n$ which is a union of intervals but has infinitely many connected components, e.g. take integer translates of a small interval around the origin.


The "right" way to use my pinky.

Question: Ever since I've been playing, I've always fretted a B chord like this:

Using my pinky to cover the D, G, & B string. However, while it works, it's never felt quite right. I've tried to use three fingers to do the same thing, but I've never seemed to be able to move them in to position fast enough for the chord to sound good.
Is this the "right" way to fret the chord, or should I be trying to use a three-fingered approach?
Answer: Wherever possible you should be trying to use a finger per fret, in the case of the B chord in your picture your fingering is wrong.
Your index finger should be barring from the A string on the second fret (B note), with your ring finger covering the D,G,B strings on the 4th fret.
The you should strum the chord from the A string, if you are having trouble with the strength of your ring finger then as previously mentioned, the three finger fingering is an option.
Its really mostly about hand strength; if you play these types of chord more often using both fingering then you will build up your hand strength to cope better with this and other types of chord.
Failing all of the above; you could always find and use a different and less stressful voicing for the chord, check this link out
Comment: Thanks for the info and the link. I've always figured I was doing it wrong, it's just always been much faster for me and kinda worked so I went with it. I've got no problem with other barre chords, just these Bs, so I'll just have to work on that some more.
Comment: No probs, that particular shape is a bit of a pain.
Comment: I have trouble fitting all three of my fingers if I try to use the individual fretting technique.  However, I don't use my pinky but my ring finger.
Answer: In my opinion, if something doesn't feel right, try not do it. I would try either the 3 finger method, or using your fourth/ring finger in the same way as your pinky. Your ring finger is usually stronger than your pinky, so it will be a little easier.
Using three fingers is great, because it means you can play variations on those chords, such as minors, 7th's or sus4's. With this, I'm afraid, it is just a case of practice, practice, practice! For me, it was like learning playing F-shaped barre chords. I could not get to that shape and position fast enough, but eventually I got there. It's just a case of learning to get in that position and making a clean sound.
If you are finding it tricky to learn that, try not barring your first finger fully across the fretboard, just fretting the 1st string. That certainly helped me learn them.
Hope this helps! :)
Answer: I use my ring finger, freeing my pinkie for fretting the B string to get a sus4 or the D string to get the 6, but this is valid.
Answer: First of all! If you use the "three-fingered" approach you will be able to play more complex chords more easily. By using the pinky to press down all the three strings you will be very limited to playing only that chord and if you would like to learn more "interesting" chord progressions (i.e most jazz chords...), your technique wont work.
Then again as you say, your technique is faster, at least to a start, and a bit easier if you have fast and simple chord changes.
I actually use them both depending on what I'm playing. However I don't use the pinky to press down the three strings but my ring finger. I would recommend learning to fret the normal way. It will be a lot easier for you to learn new things from there... After all, bad technique will affect your "learning curve".
Answer: In looking at your photo, I would suggest using a finger per string could help your fretting anyway. It makes it much easier to barre close to, and parallel to the frets, giving better tone.
Answer: I would find this too hard for my pinky.
There have been several answers suggesting "one finger per fret". In this case, it seems overkill to me, but my fingers might be relatively large.
My personal balance between control and easiness for this kind of barré is middle finger for 5th and tonic and ring finger for the 3rd, but if the piece is in a "don't give a f***" mood, I might just use my ring finger and whatever happens happens.
[UPDATE] Actually depending on where on the neck and whether I want to play the high E string, I might as well use the same form but with the ring finger and the pinky (thus covering the 3rd). So there you are.
Answer: Agree with the "one finger per string" approach as a general rule.  Ultimately, whatever works works!
One thing to look at is the size of your hands vs the size of the guitar neck and string spacing.  For instance, if you have smaller hands, playing a B chord with one-per-string is probably not a big issue.  If you have larger hands or fat fingers, it's a real chore.  Check out some other guitars that have wider fretboards - where the strings are spaced farther apart.  This will make it easier to fret because your fingers can "spread out" a bit more and not interfere with one another.

The "right" way to use my pinky.


How do I grab the objects from php Twitter API

Question: So I can get the tweets using Twitter Oauth I can echo the tweets using foreach. But I want to grab the data from the php and bring them to another page.
Index.php contains the json array of tweets.
Then in page2.php I have the code below to display specific objects using $.ajax get from index.php
   $.ajax({
     dataType: "html",
     url: 'index.php',
     success:function(data){
    //$('#tweets').html(data['text']);
    $.each(data, function () {
    list += '
'+ this.text +'
';
});
    $('#tweets').html(list);
}

});
But when I  try to specify the a particular object to grab like the text I get no results. Do use
 data['text']

or
data->text

Answer: From observing your current code, you're using the JQuery GET method to send the data to the PHP file.
I am 99% sure that the following should work:
$_GET['list'];

Comment: I think I posted it wrong. the index page contains the twitter api in php and json. But I want page to grab the json objects and use jquery to display the data..
Comment: In that case, I am not too sure then. I'd have to give it a go to see the results.


What scale is this (C# D# F F# G# A# B)?

Question: I have these notes:
C# D# F F# G# A# B
What scale is it?
Comment: You should correct your spelling.  The third note should be E#.  Scales are customarily written with each letter class only appearing once.  You have F and F#, but no E.
Comment: Most of the related ones show more research, and explain why they did not find a standard that fits. Maybe some of the related should be closed also, or maybe this one should show a bit of effort about why the op didn't find the answer.
Comment: I agree with @Tim. We have answered many of this type of question. The "identifying scale" close restriction has to do with identifying the scale in a particular song.
Comment: How come this has been closed, when there are several other very similar questions related still standing? Or do they need similarly closing, too? Just peruse the Related list.
Comment: @Tim if that does not fall in basic analysis question, what does?
Comment: There are many other very similar questions to the right (in Related) that are still remaining. Either they all go, or this is re-instated. Can't see why this in particuar is any different.
Comment: @Tom - there's the possibility that searching for a scale containing F and F# as well didn''t yield much, if anything.
Answer: C# mixolydian.
The technically correct spelling is
C# D# E# F# G# A# B
It shares its key signature with F# major.

C# mixolydian:  C#   D#   E#  F# G# A# B
F# major:      (C#) (D#) (E#) F# G# A# B C# D# E#
Comment: It may be easier to see if you mentally lower everything by a half-step.  That gives CDEFGABb, which is clearly C mixoyldian (or F major, but Aaron is right that the start note makes it modal).
Answer: As nuggethead states, that F needs to be E♯. That gives a key signature of 6 sharps - F♯ major. When writing music, it makes sense to dedicate one letter name to each line or space. Your way would necessitate loads of accidentals!
That would give the parent key, and key signature, as explained, of F♯ major. However, starting on C♯ and playing through to the next C♯ means it's not so much a scale, but a mode - of said F♯. And that mode is, as Aaron states, C♯ Mixolydian.


Using Fitting's decomposition theorem on modules directly in calculation

Question: Let $V=\mathbb{R}^3$ be a vector space with standard basis. Given a linear map $A\in End(V)$. Fitting's theorem says that there exists a unique reduction $V=N\oplus R $ for which $A|_N\in End(N)$ is nilpotent and $A|_R\in End(R)$ is invertible. I'm following this far, but if we where to apply this to an example, let $A$ be represented by the matrix $\left(
\begin{array}{ccc}
    1   &   1   &   0 \\
    0   &   1   &   1 \\
    0   &   0   &   0
\end{array}\right)$. How would one determine $N,R,A|_R,A|_N$? I guess that $N,R$ is of lower dimension than $dim(V)=3$, and hence $A|_R,A|_N$ would not be a square matrix, or am I all wrong? Is it then even possible to explicitly determine $A|_R,A|_N$?
Text on Fittings theorem: https://planetmath.org/fittingslemma
Answer: I suppose that $V=\mathbb R^3$ instead of $\mathbb R$, otherwise the vector space is one-dimensional and $A$ is represented not by a $3\times3$ matrix but by a $1\times1$ matrix.
In general, suppose $m$ is the smallest positive integer such that $\ker(A^m)=\ker(A^{m+1})$. Then $N=\ker(A^m)$ and $R=\operatorname{range}(A^m)$. If you don't want to calculate $m$, it is also guaranteed that $N=\ker(A^n)$ and $R=\operatorname{range}(A^n)$ because $m\le n$. In your case, $m$ is obviously equal to $1$. Therefore $N=\ker(A)=\operatorname{span}\{(1,-1,1)^T\}$ and $R=\operatorname{range}(A)=\{(x,y,0)^T:x,y\in\mathbb R\}$. It follows that $A|_N=0$ and $A|_R$ is represented by the matrix $\pmatrix{1&1\\ 0&1}$ with respect to the ordered basis $\{(1,0,0)^T,(0,1,0)^T\}$.
Comment: @slowpoke Oh, I meant the index of nilpotency of the nilpotent part of $A$. Edited now.
Comment: @slowpoke $N$ and $R$ are found by simple inspection. Let $\{e_1,e_2,e_3\}$ be the standard basis of $\mathbb R^3$. We have $Ae_1=e_1,\,Ae_3=e_2$ and $A(e_1-e_2+e_3)=0$. Hence $\operatorname{range}(A)$ is the linear span of $e_1$ and $e_2$, and $\ker(A)=e_1-e_2+e_3$.
Comment: @slowpoke It's trivial to check that $A(\mathbb R\times \mathbb R\times \{0\})=\mathbb R\times \mathbb R \times \{0\}$, and so (as a surjective endomorphism of two-dimensional spaces, $A$ is an isomorphism on $\mathbb R\times\mathbb R\times \{0\}$. As for the other submodule, it is exactly the kernel, so of course it acts nilpotently on it (it is uniformly zero after one application!). What more is needed?  Nothing I think...
Comment: You are correct in assuming that I meant $V=\mathbb{R}$. As far as I understand the index of nilpotency is the smallest $k$ s.t. the matrix $B^k=0$. But given the $A$ defined above we do in particular have that $A^1 \neq 0$. As far as I can see $A$ is not nilpotent in it self. Especially we have $A^3=\left(
\begin{array}{ccc}
     1 & 3 & 2  \\
     0 & 1 & 1 \\
     0 & 0 & 0
\end{array} \right) \neq 0 $. It could be nice if you could clarify :)
Comment: Thank you. And once again I mean $V=\mathbb{R}^3$... How did you find the span of $N,R$?
Comment: Is it is because: for $v_1=\left(\begin{array}{cc}
     1  \\
     0 \\
     0
\end{array}\right)$ and $v_2=\left(\begin{array}{cc}
     0  \\
     1 \\
     0
\end{array}\right)$ you can write $v_3=\left(\begin{array}{cc}
     1  \\
     1 \\
     0
\end{array}\right)$ as $v_1+v_2$? And hence the image must be a linear combination of $v_1$ and $v_2$. Especially we get that $dim(Im(A))=2$, hence we need to have $dim(ker(A))=1$. After that you see that $w=\left(\begin{array}{cc}
     1  \\
     -1 \\
     1
\end{array}\right)$ ($dim(w)=1$) satisfy $Aw=0$.
Comment: Ah, makes sense. Now we only have to convince ourselves that $A|_N=\left(\begin{array}{ccc}
    1 & 1 & 0 \\
     0 & 1 &   1 \\
     0 & 0 & 0
\end{array}\right)|_{span\{ e_1, e_2\} } = \left(\begin{array}{cc}
    1 & 1 \\
    0 & 1
\end{array}\right)
$. And that $A|_R=\left(\begin{array}{ccc}
    1 & 1 & 0 \\
     0 & 1 &   1 \\
     0 & 0 & 0
\end{array}\right)|_{span\{ \left( \begin{array}{c}
    1 \\
    -1 \\
    1
\end{array}\right) \} } = 0
$. But I feel like we need another augment here. Why is this true?


Alernating content of one web site from another

Question: I have java/Flask (any other technology I don't know exists yet :)) question.
Suppose I have two sites: index1.html and index2.html
index1.html:
<!DOCTYPE html>

This example "trigger" action on another site "onclick".

Click me.

index2.html
<!DOCTYPE html>

To change

It can be done partially with Flask but every time i trigger from index1.html index2.html I have to refresh manually index2.html.
Maybe there is another technology which help me to do that
Comment: Sites or pages on same origin? You cannot pass data from one origin to another using client side technology like localStorage - you could pass in the URL
Comment: yep how to do that ?
Answer: You can use localStorage storage event or SharedWorker to communicate between browsing contexts.
index1.html
<!DOCTYPE html>

    page2

This example "trigger" action on another site "onclick".

Click me.

index2.html
<!DOCTYPE html>

To change

plnkr http://plnkr.co/edit/4Xz58S5MDidORm4CAPco?p=preview
Comment: @mplungjan If you are referencing the call to `.clear()` at page2.html, see updated post.
Comment: on the same origin yes
Comment: @mplungjan `storage` event is dispatched when `oldValue` is changed.
Comment: You are not passing anything if you clear localStorage before reading it
Comment: @mplungjan Not sure what you mean. Clearing `localStorage` should ensure that whenever the link at page1.html is clicked the `storage` event should be dispatched at page2.html if the page is reloaded. We could go further and clear `localStorage` at each `storage` event at page2.html
Comment: @mplungjan For example, if you comment `localStorage.clear()` at page1.html `storage` event will only be dispatched at most once at page2.html if the value set at `localStorage` does not change at page1.html
Comment: Thanks that helped a lot. Is there any way to do it on remote server? Json exchange etc. ? I  found that i can only make get request and wait for response, not just waiting for some request and then act.
Comment: @ŁukaszAndrzejewski How is a server related to the original question?
Comment: Im just looking for some way to force site (index2.html) to wait for request from index1.html than take action, could be server.
Comment: ok, I done it using websockets, maybe there is better way but works :)


Solution to Square Triangle Area

Question: i have question  again about the same link  because i have national exam in one week i am trying  to know  way of solution of such recriational geometry problem see please below link of stated problem and it's solution.i have one question : is it correct?
Problem: find the area of the shaded region:

http://web.gnowledge.org/wiki/index.php/Square%2C_Triangle_and_Area#
Solution: See how the region has been restructured. The right triangle that has been removed and the new one that has been added are both conguent by the property ASA (prove it!). Thus the two triangles have the same areas.
It is now easy to find the area of the shaded region: 9 square units.

http://web.gnowledge.org/wiki/index.php/Solution_to_Square_Triangle_Area
is here everything correct? if not please can anybody tell me how to solve it?
Update:
 thanks guys everything is clear just i am curious what would be result if angle will not be right but anything else?  could we find required area or it would be impossible?
Comment: The solution is correct.
Comment: @ joriki it is because triangle is right angle yes?it's sides are 10 and 8  and one of  angle is right am i correct?
Comment: The ping doesn't work if you put a space between the '@' and the name. The $10$ and $8$ don't enter into it; the small triangles that cancel each other are congruent because the angle of the big triangle is right.
Comment: my only question is: what about if angle will be different from 90?
Comment: If the angle isn't right, the problem doesn't have such an elegant solution, and you need the actual lengths or angles in the small triangles to calculate the area.
Answer: The yellow area is the same as the area of the small square drawn with dashed lines. Why? Because if you continue the dotted lines, you divide the square in four parts. The yellow section outside the lower left square is the same as the white section inside that square. If it is not clear I'll try and make a drawing.
Comment: dont worry about it everything is clear i will accept your answer  thanks @Beni Bogosel
Answer: Rotate the triangle slowly about the center of the square, say counterclockwise. As you rotate, by symmetry you are losing yellow area on one side as fast as you are acquiring new yellow area on the other side.
After a while, you will have rotated the triangle so that its "legs" are horizontal and vertical.  Then the yellow area has become a $3 \times 3$ square.
Comment: Mathematicians usually prefer counterclockwise rotation.  I would like a mathematical watch whose hands rotate couunterclockwise.  Of course noon and midnight would be at the right end of the watch, not on top.  And there would not be a $12$ there, instead there would be a $0$.

Solution to Square Triangle Area


Swift: When Does the Completion Block of Dismiss View Get Executed?

Question: When does the completion block of dismiss view get executed?
Is it after or before the user sees the view dismissed?
I have this code to make a toast with a message inside completion block but never see the toast after this view dismissed.
       self.dismiss(animated: true, completion: {
       self.view.makeToast(message: "Employee has been assigned successfully.", duration: 2.0, position: HRToastPositionCenter as AnyObject, title: "Succeeded!")
})

What I want is the user can see the toast when the view gets completely dismissed?
How do I do this ?
Comment: You can delegate the event from presented controller to the parent and handle it there (dismiss and makeToast)
Answer: You can delegate the event from presented controller to the parent and handle it there.
In EmployeePickerViewController (or whatever your modal controller is called):
@protocol EmployeePickerDelegate {
    func employeeAssigned()
}

class EmployeePickerViewController {
    weak delegate: EmployeePickerDelegate!
}

When employee assignment is finished just call delegate's method:
delegate?.employeeAssigned()

In MainViewController when you present modally:
employeePicker.delegate = self
present(employeePicker, animated: true, completion: nil)

In MainViewController below:
extension MainViewController: EmployeePickerDelegate {
   func employeeAssigned {
       dismiss(animated: true, completion: {
            self.view.makeToast(message: "Employee has been assigned successfully.", duration: 2.0, position: HRToastPositionCenter as AnyObject, title: "Succeeded!")
       })
   }
}

Answer: For UIViewController.dismiss(animated:completion:)

The completion handler is called after the viewDidDisappear(_:) method
  is called on the presented view controller.

Source
For UIViewController.present(_:animated:completion:)

The completion handler is called after the viewDidAppear(_:) method is
  called on the presented view controller.

Source.

If you don't know when that is, this is the order of the UIViewController load, appear and dissapear methods

viewDidLoad

normally we initialize data objects and controls. It will create all
  the necessary memory for all controls/data objects for this view. i.e.
  In the above case, anotherView and btnView, they will keep the same
  memory addresses for the whole life cycle.

viewWillAppear

Called before the view is added to the windows' view hierarchy. So it
  is ideal for updating the viewcontroller's data.

viewDidAppear

Called after the view is added to the windows' view hierarchy.

viewWillDisappear

Called before the view is removed from the windows' view hierarchy.

viewDidDisappear

Called after the view is removed from the windows' view hierarchy.

Source
Answer: You are calling a dismiss on self, so every reference of that will be dealloc. your self.view doesn't exist anymore I guess.
Comment: self.view does still exist because it's strongly captured
Comment: try adding breakpoint on your self.view.makeToast() line and check entities at this time
Answer: The completion block is executed after the View Controller has been dismissed. This means your view is no longer on screen. I think you want to render the toast inside that view, which is not possible because it is off screen.
Answer: The toast will be shown inside your dismissed view. Since the view has disappeared you won't see its toast. You might want to show the toast in the following screen that appears after the dismissed view.
Comment: Thank you but how to show the toast from current view to next view
Comment: How did you _present_ the view that you are now dismissing?
Answer: Maybe could be easier to show the toast on the window instead of a particular view?
   UIApplication.shared.keyWindow?.makeToast(message: "Employee has been assigned successfully.", duration: 2.0, position: HRToastPositionCenter as AnyObject, title: "Succeeded!")


How does the scala compiler locate the positions for variance annotation

Question: I am trying to understand how the compiler checks whether the position for a type parameter is covariant or contravariant.
As far as I know, if the type parameter is annotated with the +, which is the covariant annotation, then any method cannot have a input parameter typed with that class/trait's type parameter.
For example, bar cannot have a parameter of type T.
class Foo[+T] {
  def bar(param: T): Unit =
    println("Hello foo bar")
}

Because the position for the parameter of bar() is considered to be negative, which means any type parameter in that position is in a contravariant position.
I am curious how the Scala compiler can find if every location in the class/trait is positive, negative, or neutral. It seems that there exist some rules like flipping its position in some condition but couldn't understand it clearly.
Also, if possible, I would like to know how these rules are defined. For example, it seems that parameters for methods defined in a class that has covariant annotation, like bar() method in Foo class, should have contravariant class type. Why?
Comment: Could you please clarify your question: 1. "It seems that there exist some rules like flipping its position in some condition" - what makes you think that? 2. "parameters for methods defined in a class that has covariant annotation... should have contravariant class type. Why?" - are you asking about why variance rules were introduced, or something else? By the way, in fact, method parameters are allowed to have either contravariant or non-variant types, not necessarily contravariant.
Answer:
I am curious how the Scala compiler can find if every location in the
  class/trait is positive, negative, or neutral. It seems that there
  exist some rules like flipping its position in some condition but
  couldn't understand it clearly.

The Scala compiler has a phase called parser (like most compilers), which goes over the text and parses out tokens. One of these tokens is called variance. If we dive into the detail, there's a method called Parsers.typeParamClauseOpt which is responsible for parsing out the type parameter clause. The part relevant to your question is this:
def typeParam(ms: Modifiers): TypeDef = {
  var mods = ms | Flags.PARAM
  val start = in.offset
  if (owner.isTypeName && isIdent) {
    if (in.name == raw.PLUS) {
      in.nextToken()
      mods |= Flags.COVARIANT
    } else if (in.name == raw.MINUS) {
      in.nextToken()
      mods |= Flags.CONTRAVARIANT
    }
  }

The parser looks for the + and - signs in the type parameter signature, and creates a class called TypeDef which describes the type and states that it is covariant, contravariant or invariant.

Also, if possible, I would like to know how these rules are defined.

Variance rules are universal, and they stem from a branch of mathematics called Category Theory. More specifically, they're derived from Covariant and Contravariant Functors and the composition between the two. If you want to learn more on these rules, that would be the path I'd take.
Additionally, there is a class called Variance in the Scala compiler which looks like a helper class in regards to variance rules, if you want to take a deeper look.
Comment: I really appreciate your explanation and editings! It helps me a lot to understand internals, and I learned lot from your answer.
Answer: To verify the correctness of variance annotation, the compiler classifies all positions in a class or trait body as positive (+), negative (-) or neutral.
A "position" is any location in the class or trait (but from now on I'll just write "class") body where a type parameter may be used.
The compiler checks each use of each of the class's type parameters:

+T type parameters (covariant/flexible) may only be used in positive
positions.
-T type parameters (contravariant) may only be used in
negative positions.
T type parameters (invariant/rigid) may be used in
any position, and is therefore, the only kind of type parameter that
can be used in neutral positions.

To classify the positions, the compiler starts from the given class declaration of a type parameter and moves inward through deeper nesting levels. Positions at the top level of the declaring class are classified as positive. By default, positions at deeper nesting levels are classified the same as that at enclosing levels, but there are three exceptions where the classification changes:

Method value parameter positions are classified to the flipped
classification relative to positions outside the method, where:

the flip of a positive classification is negative
the flip of a negative classification is positive
the flip of a neutral classification remains neutral.

Besides method value parameter positions, the current classification
is also flipped at the type parameters of methods.

A classification is sometimes flipped at the type argument position of a type, such as the Arg in C[Arg], depending on the variance of the corresponding type parameter. If C's type parameter is:

+T then the classification stays the same.
-T then the current classification is flipped
T then the current classification is changed to neutral

To understand better, here's a contrived example, where all positions are annotated with their classifications, given by the compiler:
abstract class Cat[-T, +U] {
    def meow[W-](volume: T-, listener: Cat[U+, T-]-): Cat[Cat[U+, T-]-, U+]+
}

The type parameter W is in a negative (contravariant) position because of rule number 2 stated above. (So it is flipped relative to positions outside the method - which are stated to be positive by default, so the compiler flips it and that is why it becomes negative.).
The value parameter volume is in a negative position (contravariant) because of rule number 1. (So it is flipped in the same manner as W)
The value parameter listener, is in a negative position for the same reason as volume. Looking at the positions of its type arguments U and T inside the type Cat, they are flipped because Cat is in a negative position, and according to rule number 3 it must be flipped.
The result type of the method is positive because it's considered
outside the method. Looking inside the result type of meow: the
position of the first Cat[U, T] is negative because Cat's first
type parameter, T is annotated with a -; while the second type
argument, U is positive since Cat's second type parameter, U is
annotated with a +. The two positions remain unchanged (are not
flipped) because the flipping rule does not apply here (rule number
3), since Cat is  in a positive position.  But the types U and T inside the first argument of Cat are flipped because the flipping
rule does apply here - that Cat is in a negative position.

As you can see it's quite hard to keep track of variance positions. That's why is a welcome relief that the Scala compiler does this job for you.
Once the classification is computed, the compiler checks that each type parameter is only used in positions that are classified appropriately. In this case, T is only used in negative positions, while U is only used in positive positions. So class Cat is type correct.
The rules and example are taken directly from the Programming in Scala book by M. Odersky, B. Venners and L. Spoon.
This also answers your second question: based on these rules we can infer that method value arguments will always be in contravariant positions, while method result types will always be in covariant positions. This is why you can't have a covariant type in a method value parameter position in your example.


Prevent screen output heredoc

Question: I'm writing a bash shell script whose purpose is to create a php skeleton for new projects.
To create certain php documents within the newly created directory structure, I'm using HEREDOCs with tons of codelines..
sudo tee $projectname/www/index.php <<- EOF | > null
<?php

ob_start();

require_once 'inc/header.inc';

ob_end_flush();
?>
EOF

## Create header.inc
sudo tee $projectname/www/inc/header.inc <<- EOF 1>&2

<!DOCTYPE html>

<meta charset="utf-8">
....
EOF

The problem is:
All HEREDOC lines are echoed to the screen. That is really not what I want, it looks very messy.
So, I tried to issue this, by redirecting output to nulland /dev/null. Unfortunately without success.
Research:

Preventing output from commands in Batch
Echo in heredoc / nowdoc syntax
Outputting variable within Heredoc
http://wiki.bash-hackers.org/syntax/redirection
Answer: Your redirect syntax is incorrect.  Lose the |
sudo tee $projectname/www/index.php <<-EOF >/dev/null

The other redirection attempt you have 1>&2 would merely redirect standard output to standard error, which (normally) lands on your screen in the end anyway.  It's useful, but not for you are trying to accomplish.
It would be better hygiene to create the project as yourself and use a separate (version control and) deployment infrastructure to publish a production version only when you have something of suitable quality and completeness, though.  Then you don't need sudo, and then you don't need tee.
cat <<-EOF >$projectname/www/index.php

The sudo tee file >/dev/null trick is a bit of an antipattern to enable you to write files like with cat when you are using sudo.
Comment: @kzpm: If the webserver can execute a sudo, then you might as well just give it write permissions to a directory; obviously, it has them if it needs them. Better solutions exist but that would be a different question, and arguably better asked on a sysadmin QA site. Anyway, I still prefer `sudo dd` to `sudo tee` (because you don't have to deal with discarding the output), but tastes vary.
Comment: @Etan Reisner Thanks for your suggestions! The <<-EOF >/dev/null part solved the output problem!
Comment: FWIW, I prefer `sudo dd of=/path/to/file <<-EOF` to the `sudo tee` hack, but obviously avoiding the sudo in the first place is better.
Comment: @rici Thanks for your observation rici, I will try 'dd'. Never thought one could use dd also for this specific purpose.

Prevent screen output heredoc


React material-ui : Selection box over ListItemButton do not fit the cornerRadius

Question: I have a selectable menu items icons in React using Material UI with cornerRadius :
<Paper sx={{borderRadius: '25px'}}>
    <List component={Stack} direction="row">
        <ListItemButton>
            <CropSquareRounded />
        </ListItemButton>
        <ListItemButton>
            <CropSquareRounded />
        </ListItemButton>
        <ListItemButton>
            <CropSquareRounded />
        </ListItemButton>
    </List>
</Paper>

When the mouse is over a item in this menu, the selection box do not fit the corner radius. The selection box is still rectangular.
see square corner on selection
How to fix this ?
Answer: You have to style the hover state of your ListItemButton to achieve what you want:
<ListItemButton
              sx={{
                "&:hover": {
                  borderRadius: "16px"
                }
              }}
            >

Demo


É possível gerar um executável no Android Studio?

Question: Olá, quero rodar minha aplicação Android no PC (Windows) sem emulador, para seja possível instalar com .exe, isso é possível?
Comment: Vai precisar do emulador... não tem jeito, o windows não irá interpretar instruções que são para outro SO.
Comment: https://developer.android.com/studio/run/?hl=pt-br
Comment: Eu  preciso de um .exe para produção. obrigado.
Answer: Infelizmente, até onde sei, não é possível.
Quando você compila o seu código, ele gera um bytecode que roda em uma JVM, mas essa JVM é dedicada ao sistema android. De toda forma você precisa de um emulador para simular recursos como GPS, Rede, sistema de arquivos e câmera.
Comment: Obrigado @Renato Tavares é bastante esclarecedora a sua resposta, vou aguardar um pouco mais antes de validar isso.
Answer: Com certeza não, windows e android são duas plataformas distintas com duas arquiteturas diferentes, assim como um código para o android não vai ser executado no windows, um programa executável não vai executar no android, então a única forma de executar uma aplicação android no windows é através de um emulador, se você precisa de um emulador para produção recomendo o BlueStacks.


What would a rigorous proof that the vector space of functions from $\mathbb{Z}$ to $\mathbb{R}$ is not finite-dimensional look like?

Question: So consider the vector space of functions from $\mathbb{Z}$ to $\mathbb{R}$. Intuitively, this vector space is not finite-dimensional. Indeed, $\mathbb{Z}$ and $\mathbb{N}$ are the same by "zig-zagging", and with regards to the vector space of functions from $\mathbb{N} \to \mathbb{Z}$, indeed I can exhibit via construction infinitely many linearly independent vectors via just taking vectors$$(0, 0, 0, \ldots, 0, 1, \ldots).$$My concern is, I feel as if this is not rigorous. What would a rigorous proof that the vector space of functions $\mathbb{Z}$ to $\mathbb{R}$ is not finite-dimensional look like? Thank you in advance!
Comment: Actually it's not even of countable dimension
Answer: You may prove it by contradiction.
Just assume the given space was finite dimensional with dimension $n$.
Then any $n+1$ vectors would be linearly dependent.
But, you can find $n+1$ linearly independent vectors $e_1, \ldots , e_{n+1}$
with $e_k(i) = \delta_{ik}$ for $k=1, \ldots , n+1$  and $i \in \mathbb{N}$.
This contradiction shows that the assumption was wrong.


Purity of functions generating ByteString (or any object with ForeignPtr component)

Question: Since a ByteString is a constructor with ForeignPtr:
data ByteString = PS {-# UNPACK #-} !(ForeignPtr Word8) -- payload
                     {-# UNPACK #-} !Int                -- offset
                     {-# UNPACK #-} !Int                -- length

If I have a function that returns ByteString, then given an input, say a constant Word8, the function will return a ByteString with non-deterministic ForeignPtr value - as to what that value will be is determined by the memory manager.
So, does that mean that a function that returns ByteString is not pure? That doesn't seem to be the case obviously, if you have used ByteString and Vector libraries. Surely, it would have been discussed widely if it were the case (and hopefully show up on top of google search). How is that purity enforced?
The reason for asking this question is I am curious what are the subtle points involved in using ByteString and Vector objects, from the GHC compiler perspective, given ForeignPtr member in their constructor.
Answer: There is no way to observe the value of the pointer inside the ForeignPtr from outside the Data.ByteString module; its implementation is internally impure, but externally pure, because it makes sure that the invariants required to be pure are maintained as long as you cannot see inside the ByteString constructor — which you can't, because it's not exported.
This is a common technique in Haskell: implementing something with unsafe techniques under the hood, but exposing a pure interface; you get both the performance and power unsafe techniques bring, without compromising Haskell's safety. (Of course, the implementation modules can have bugs, but do you think ByteString would be less likely to leak its abstraction if it was written in C? :))
As far as the subtle points go, if you're talking from a user's perspective, don't worry: you can use any function the ByteString and Vector libraries export without worrying, as long as they don't start with unsafe. They are both very mature and well-tested libraries, so you shouldn't run into any purity problems at all, and if you do, that's a bug in the library, and you should report it.
As far as writing your own code that provides external safety with an unsafe internal implementation, the rule is very simple: maintain referential transparency.
Taking ByteString as an example, the functions to construct ByteStrings use unsafePerformIO to allocate blocks of data, which they then mutate and put in the constructor. If we exported the constructor, then user code would be able to get at the ForeignPtr. Is this problematic? To determine whether it is, we need to find a pure function (i.e. not in IO) that lets us distinguish two ForeignPtrs allocated in this way. A quick glance at the documentation shows that there is such a function: instance Eq (ForeignPtr a) would let us distinguish these. So we must not allow user code to access the ForeignPtr. The easiest way to do this is to not export the constructor.
In summary: When you use an unsafe mechanism to implement something, verify that the impurity it introduces cannot leak outside of the module, e.g. by inspecting the values you produce with it.
As far as compiler issues go, you shouldn't really have to worry about them; while the functions are unsafe, they shouldn't allow you to do anything more dangerous, beyond violating purity, than you can do in the IO monad to start with. Generally, if you want to do something that could produce really unexpected results, you'll have to go out of your way to do so: for instance, you can use unsafeDupablePerformIO if you can deal with the possibility of two threads evaluating the same thunk of the form unsafeDupablePerformIO m simultaneously. unsafePerformIO is slightly slower than unsafeDupablePerformIO because it prevents this from happening. (Thunks in your program can be evaluated by two threads simultaneously during normal execution with GHC; this is normally not a problem, as evaluating the same pure value twice should have no adverse side-effects (by definition), but when writing unsafe code, it's something you have to take into account.)
The GHC documentation for unsafePerformIO (and unsafeDupablePerformIO, as I linked above) details some pitfalls you might run into; similarly the documentation for unsafeCoerce# (which should be used through its portable name, Unsafe.Coerce.unsafeCoerce).
Comment: Well, I do plan to use unsafe operations. Hence, this question :) I will like to learn of the issues I should be aware of, as the library writers were. Those insights will be very useful, when writing our own code that needs to be fast, but still externally pure, for parallel and concurrent extensions.
Comment: Ah, OK; that wasn't clear to me from the question. I'll try and incorporate some of that information into my answer, although it's tricky since the basic rule is just "ensure referential transparency from outside the module".
Comment: I've expanded it some more, hope this helps :)
Comment: thank you so much for taking time to expand on it. It is very useful. I too read the GHC documentation about unsafePerformIO and unsafeDupablePerformIO, which got me thinking, which got me to this question :)


block->subject set when using one theme, but not when using identical copy of the theme?

Question: I have a theme (based on zen). I made a copy of the theme, replacing all the references to the theme's name in the files. I switched to the new theme and copied all theme settings in drupal (drupal 6).
As far as I can tell everything looks just the same, except that on some blocks (notably the footer menu) the name ("Footer Menu") appears. From the theme files i see this is because $block->subject suddenly is set.
What's up with this - if the themes are identical and the configuration is the same, why does one have a block->subject set and not the other?
Answer: Looks to be a known issue. I see blocks display emptry string for $block->subject. in this thread someone mentions that they had to modify system.module for this to work. you can check it out in this thread here. Looks like a patch is out there for it.
Comment: You were right, this is probably the same issue. Thanks!


Why does Port 9721 intermittently refuse connections on Apache Tomcat 8.5 running on Windows Server 2012 R2?

Question: Web Server: Apache Tomcat 8.5
Operating System: Windows Server 2012 R2
Port: 9721
We are running a Web server on our internal network and have about 8500 kiosks connecting through our VPN to a Java servlet that is running on this port: :9721
This Web server was set up by a former employee and we are not sure how it was originally configured.
We noticed recently that about 25% of the connection attempts are being refused (Connection Refused error). We found this information by monitoring Port 9721 using PRTG and this monitoring tool is reporting that this port is refusing connections on multiple occasions within each hour throughout the day. I have not been able to find a pattern to the refused connections...it appears to be intermittent.
Our network administrator says it is not a firewall issue, but I have not ruled out this possibility. We have tried to review the "maxconnections" setting in the Tomcat server.xml configuration file, but cannot find the "maxconnections" attribute included in that configuration file. We do not have the Tomcat Manager Application installed on this server that I can find.
How do I troubleshoot and resolve this port connection issue?
Answer: To identify what is the issue here I would go for mix of monitoring and testing the situation using following steps:

create PRTG sensor which will tell you how many TCP connections you have currently connected to port 9721. To achieve that we will create powershell file in PRTG installation (EXE/show-connections.ps1) containging following:
Invoke-Command -ComputerName ToBeReplacedWithWebServerHostname -ScriptBlock {
$CountConnections = $(Get-NetTCPConnection -LocalPort 9721).Count
echo "0:$CountConnections Info sensor only - we have currently $CountConnections clients connected to port 9721"
}

Schedule this sensor to run each 30 seconds to give you information twice a minute

Run Jmeter remotely on that server against port 9721 and make sure that you don't get any connection refuse using 100, 1000 and 10000 simultanious connections. I bet if you run 10k test you will reach maximum and you will see that PRTG sensor shows you how many max connections you can use at once

I believe that PRTG sensor will never fail to connect to server - meaning that there is no issue on that Windows firewall, but i believe you will hit the application server (Tomcat) limit and following article could help you to try to tune few parameters:
Apache Tomcat Connection Refused error while load testing with 1000 users using JMeter
Let me know if you have more questions regarding PRTG/PowerShell or JMeter. And let me know if you found the issue
Comment: Thanks for your detailed advice. I will work with our network administrator to implement the PRTG monitor and to run Jmeter as you suggested.


How to setup a test suit for unit testing Firebase Functions that connect with emulators, specifically the Firestore emulator?

Question: I want to set up a test suit to write a unit test for my Firebase application which connects to the Firestore emulator that is running locally on port 8080
Here is my firebase configuration in index.js
    const functions = require("firebase-functions");
    const dotenv = require('dotenv');
    dotenv.config();

    const emailFormatter = require("./emailFormatter");

    const admin = require("firebase-admin");

    admin.initializeApp();
    const db = admin.firestore();

And the following is my functions.test.js
    const admin = require('firebase-admin');
    const serviceAccount = require('../../../fir-react-mailer-firebase-adminsdk-wfei1-0fff68d44e.json');

    const testConfig = {
       credential: admin.credential.cert(serviceAccount),
       databaseURL: 'http://localhost:8080'
    }

    const testApp = admin.initializeApp(testConfig, 'test');

    const projectConfig = {
       projectId: 'fir-react-mailer',
       databaseURL: 'http://localhost:8080',
    }

    const testF = require('firebase-functions-test')(projectConfig, serviceAccount);

    const myFinctions = require('../index')

    let db = admin.firestore(testApp)

Here is my package.json
    {
      "name": "functions",
      "description": "Cloud Functions for Firebase",
      "scripts": {
        "serve": "firebase emulators:start --only functions",
        "shell": "firebase functions:shell",
        "start": "npm run shell",
        "deploy": "firebase deploy --only functions",
        "logs": "firebase functions:log",
        "test": "jest"
      },
      "engines": {
        "node": "12"
      },
      "dependencies": {
        "chalk": "^4.1.0",
        "dotenv": "^8.2.0",
        "firebase-admin": "^8.9.0",
        "firebase-functions": "^3.3.0",
        "nodemailer": "^6.4.6"
      },
      "devDependencies": {
        "@types/jest": "^26.0.20",
        "firebase-functions-test": "^0.1.7",
        "jest": "^26.6.3"
      },
      "private": true
    }

When running the command npm run test, I am getting the following error on the console.

Please suggest to me, If I am doing something wrong. I am a newbie to Firebase, so this whole setup is confusing.
Comment: I'm not entirely sure if this will help but it looks like it's trying to read the credentials file? Have you tried creating one or making sure it exists locally? There's some more people working a similar issue here: https://stackoverflow.com/questions/54711038/firebase-cloud-functions-failed-to-read-credentials-from-file
Answer: I was having this issue as well and it was because I had to provide the location of the serviceAccount json file in relation to the functions folder. I also didn't import it and instead provided the string. So if my project is like so:
functions
 |
 +-- src
 |
 +-- test
 |  |
 |  \-- functions.test.js
 |
 +-- package.json
 +-- service-account.json

I would change your functions-test variable to:
const testF = require('firebase-functions-test')(projectConfig, "./service-account.json");

You might also try calling initializeApp only once. It looks like you're calling initializeApp() twice. The first one is in your test code at line 9 and then again in your actual code. The one from the test code looks right, but then your actual code is calling it again without the testConfig.
Maybe try wrapping admin.initializeApp() in an if statement so it doesn't get initialized unless it has to (which will occur in production).
if (admin.apps.length === 0) {
  admin.initializeApp();
}

Answer: As per the documentation:

After creating your service account, you need to download the service account key to your machine(s) where your application runs. You can either use the GOOGLE_APPLICATION_CREDENTIALS environment variable or write code to pass the service account key to the client library.

You need to set the Windows environment variables like this:
With PowerShell:
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\my-key.json"

For example:
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\my-key.json"

With command prompt:
set GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\my-key.json"

Try to avoid hard coding the location of your credentials file if you can to reduce the amount of code you write and it means your code is reusable.


Delete duplicate rows but keep one without having a uniqe column

Question: I have a table with duplicate entries which I want to remove, keeping none but one of the duplicate entries. As you can see, they are exactly the same in every colum, there's no way to differentiate them:

I've used this query to figure out how many duplicates I have:
select url_rewrite_id, category_id, product_id, count(*) cnt
from catalog_url_rewrite_product_category
group by url_rewrite_id, category_id, product_id
having cnt > 1
order by cnt desc

I could use a variant of this to remove all duplicates:
delete
from catalog_url_rewrite_product_category
where url_rewrite_id in (
    select url_rewrite_id
    from catalog_url_rewrite_product_category
    group by url_rewrite_id, category_id, product_id
    having count(*) > 1
)

The problem I have with this is it would remove all entries that are duplicates and wouldn't keep the last one.
Earlier questions (here and here) assume a unique id column of sorts which is not the case with the data structure I have.
Answer: Have you tried one of the solutions I read in the thread you shared (here)?
ALTER IGNORE TABLE jobs
ADD UNIQUE INDEX idx_name (site_id, title, company);

I think this would work.
Comment: I was just about to post this! That does indeed work.

Full query that worked for me was:

`alter ignore table catalog_url_rewrite_product_category add unique index tmp_remove_key(url_rewrite_id, category_id, product_id)`


MobX running a function after async action

Question: I have an issue with MobX as I'd like to call onSortHandler as well as loadingCallback after an async action in my store but the call order is misaligned due to the async action. The added complexity of the issue is that onSortHandler triggers a function which uses a computed value calculated by the given action.
Here is my action in the store:
loadFurniturePage = async (pageNumber: number, pageAmount: number) => {
        const nextPage = await agent.FrontEnd.getNextFurniturePage(pageNumber, pageAmount); <-- I suppose while waiting here, the finally block get called. (See it below)
        nextPage.forEach((furniture: IFurniture) => {
            furniture.type = furniture.typeInString;
            this.furnitureMap.set(furniture.id, furniture)
        });
    }

Here is the place where I call the action above:
loadFurniturePage(pageNumber, pageAmount).finally(() => { <-- this code block should be called after the action finishes it's running.
    onSortHandler(selectedSortByValue);
    loadingCallback(false);
});

And this is the computed value I use when calling onSortHandler:
get getAllFurniture() {
    return Array.from(this.furnitureMap.values())
}

Does anybody have an idea, how to solve this?
Comment: hi. Is `this.furnitureMap.set(furniture.id, furniture)` an `async` function?
Comment: @EhsanNazeri it is not, as far as I know.
Comment: Does this answer your question? [MobX: Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed](https://stackoverflow.com/questions/64770762/mobx-since-strict-mode-is-enabled-changing-observed-observable-values-withou)
Answer: After async function call if you continue to change mobx observables, wrap that code in runInAction
loadFurniturePage = async (pageNumber: number, pageAmount: number) => {
        const nextPage = await agent.FrontEnd.getNextFurniturePage(pageNumber, pageAmount);
        runInAction(()=>{
        nextPage.forEach((furniture: IFurniture) => {
            furniture.type = furniture.typeInString;
            this.furnitureMap.set(furniture.id, furniture)
        });
})

    }

loadFurniturePage(pageNumber, pageAmount).finally(() => {
    runInAction(()=>{
    onSortHandler(selectedSortByValue);
    loadingCallback(false);
})

});


Rendering and saving SSRS report in PDF

Question: I need to save SSRS report in PDF programmatically (vb.net).  I know when the report is rendered, we can save it in PDF from the triangle next to Disk icon, but I do not need to press this, rather save it using vb.net code.
Please advise.
Thanks
Comment: possible duplicate of [Suggest correction in code to render report](http://stackoverflow.com/questions/22730317/suggest-correction-in-code-to-render-report)
Answer: This should help:
<code>If reportViewer.ServerReport.IsReadyForRendering Then
    Dim fileData As Byte() = reportViewer.ServerReport.Render("PDF")
    System.IO.File.WriteAllBytes("C:\Path\filename.pdf", fileData)
Else
    'report parameters are not properly set, warn user to check
End If
</code>

Rendering and saving SSRS report in PDF


Is there a name for the "I - bVI - bIII - bVII" progression?

Question: I heard a song with "I - bVI - bIII - bVII" and it's one of my favorite progressions. So I want to know about that progression.
Comment: Is your `I` chord minor or major? So Roman numeral systems use `i` lower case for minor, others don't.
Answer: There isn't a name for this specific progression, but it might make sense to call it a circle of fifths turnaround. Let's assume you're in C; this would make the progression:
<code>| C Maj | A♭Maj | E♭Maj | B♭Maj |</code>
Here are some things that make the progression interesting:

the change from major tonality (in measure 1) minor tonality (in measures 2-4)
measures 2 - 4 follow the circle of fifths
upon repeating the progression, going from B♭Maj to CMaj is a nice parallel movement

The term 'circle of fifths turnaround' might make sense given that turnarounds are typically short, repeatable progressions that lead back to the I chord. And the use of the circle of fifths is a key feature of the progression.
Separately, the reason ♭VII to I sounds good is that ♭VII has the 2nd and 4th scale degrees of the I chord, which draw the ear toward the 1 and 3 of the I chord.
Comment: The thing that jumped out to me was that the tonic E♭ actually has less chromaticism with the same chords. Not surprising, since the progression is diatonic to C minor, except for the C major triad at the start. I think viewers might even start to hear the progression as C minor or E♭major with a little surprise twist on the C chords... Of course, context is everything.
Comment: @user45266, agreed! Treating E♭ as the tonic is an interesting take I hadn't considered. This makes the progression `| VI | IV | I | V |`. V → VI would require some finesse to solo over. If we go this route, then my ear wants to hear the CMaj chord more as C7alt. This is totally possible given the current info from the OP. As you say, context matters. For example, if the CMaj chord isn't voiced with a 7th, then it may very well function as a VI7alt. But if the CMaj is voiced with a major 7th, then the first chord is less diatonic & sticks out more. Of course, that doesn't mean it's 'wrong'!
Answer: It's likely you mean the I is minor, thus i-, bVI, bIII, bVII.
This is a very popular progression (turnaround) in disguise.
It is the same as vi, IV, I, V when you make the bIII the I.
For example, the progression for the verses of Bob Marley's "Is This Love?" is F#-, D, A, E.
The key signature has three sharps which could make the song either in F# minor (as indicated by the first chord in the progression) or A Major.
If we agree that the song is in F#- then the progression is i-, bVI, bIII, bVII.
However, if we look at it from the relative major, which is A Major, then the progression is vi, IV, I, V.
Progression = F#-, D, A, E
In F# minor = i-, bVI, bIII, bVII
In A Major = vi, IV, I, V
Same song, same progression, just a different perspective.
We usually look at progressions from the perspective of the relative Major key, hence vi, IV, I, V is popular and the more common way to view.  However, it's equally valid to understand it from its minor perspective, hence  i-, bVI, bIII, bVII.
Answer: It's VI IV I V
Majorizing the vi chord is an example of modal interchange, which is a fancy way of saying you're borrowing a chord from a different mode of the same key centre.
Answer: To expound upon both UrbanSmash and neil thomas, they have identified that this is a rotation of the common I–V–vi–IV, what Mark Richards called an axis progression in a famous article from 2017.
When the above progression threats the vi as tonic, the progression then becomes ♭III–♭VII–i–♭VI, which is your exact i–♭VI–♭III–♭VI progression.
(Note that, in my first progression, vi is minor, while the requisite tonic in the second progression is major. This latter tonic can be major or minor.)
In Chris Doll's 2017 book Hearing Harmony: Toward a Tonal Theory for the Rock Era, he names these two progressions based on their prevailing mode. When heard in major (i.e., the first progression, I–V–vi–IV), this is the "journey" progression named after Journey's 1980 "Any Way You Want It." When heard in minor (i.e., the second progression, i–♭VI–♭III–♭VI), this is the "zombie" progression, named after the song by The Cranberries.
Doll himself, however, recognizes the ambiguity between these two, saying (as quoted by Richards):

since the journey and zombie schemas are so similar in certain ways, any given progression in a song might be heard as projecting both schemas simultaneously. The fundamental issue here is that some degree of tonic quality is usually projected by both the journey's I and ↑VI and the zombie's I and ↓III (the Em and GM chords in Em–CM–GM–DM). If one of the sonorities is clearly more a tonic, then the progression can be understood as a realization of one schema versus the other, but attempting to hear an invocation of the journey as opposed to the zombie, or vice versa, can be a difficult, or futile, task. (2017, 120)

And for the sake of completeness, one addition Richards quote:

Other proposed terms for the progression include "gravitas loop" (Robison 2013) and Boston Globe columnist Marc Hirsh's notoriously controversial "Sensitive Female Chord Progression" (2008). (paragraph 3)